+static char *config_repo;
+static char *config_remote;
+static const char *start_ref;
+static int start_len;
+static int base_len;
+
+static int get_remote_branch_name(const char *value)
+{
+ const char *colon;
+ const char *end;
+
+ if (*value == '+')
+ value++;
+
+ colon = strchr(value, ':');
+ if (!colon)
+ return 0;
+
+ end = value + strlen(value);
+
+ /* Try an exact match first. */
+ if (!strcmp(colon + 1, start_ref)) {
+ /* Truncate the value before the colon. */
+ nfasprintf(&config_repo, "%.*s", colon - value, value);
+ return 1;
+ }
+
+ /* Try with a wildcard match now. */
+ if (end - value > 2 && end[-2] == '/' && end[-1] == '*' &&
+ colon - value > 2 && colon[-2] == '/' && colon[-1] == '*' &&
+ (end - 2) - (colon + 1) == base_len &&
+ !strncmp(colon + 1, start_ref, base_len)) {
+ /* Replace the star with the remote branch name. */
+ nfasprintf(&config_repo, "%.*s%s",
+ (colon - 2) - value, value,
+ start_ref + base_len);
+ return 1;
+ }
+
+ return 0;
+}
+
+static int get_remote_config(const char *key, const char *value)
+{
+ const char *var;
+ if (prefixcmp(key, "remote."))
+ return 0;
+
+ var = strrchr(key, '.');
+ if (var == key + 6)
+ return 0;
+
+ if (!strcmp(var, ".fetch") && get_remote_branch_name(value))
+ nfasprintf(&config_remote, "%.*s", var - (key + 7), key + 7);
+
+ return 0;
+}
+
+static void set_branch_defaults(const char *name, const char *real_ref)
+{
+ char key[1024];
+ const char *slash = strrchr(real_ref, '/');
+
+ if (!slash)
+ return;
+
+ start_ref = real_ref;
+ start_len = strlen(real_ref);
+ base_len = slash - real_ref;
+ git_config(get_remote_config);
+
+ if (config_repo && config_remote) {
+ if (sizeof(key) <=
+ snprintf(key, sizeof(key), "branch.%s.remote", name))
+ die("what a long branch name you have!");
+ git_config_set(key, config_remote);
+
+ /*
+ * We do not have to check if we have enough space for
+ * the 'merge' key, since it's shorter than the
+ * previous 'remote' key, which we already checked.
+ */
+ snprintf(key, sizeof(key), "branch.%s.merge", name);
+ git_config_set(key, config_repo);
+
+ printf("Branch %s set up to track remote branch %s.\n",
+ name, real_ref);
+ }
+
+ if (config_repo)
+ free(config_repo);
+ if (config_remote)
+ free(config_remote);
+}
+