remote.con commit remote: let guess_remote_head() optionally return all matches (4229f1f)
   1#include "cache.h"
   2#include "remote.h"
   3#include "refs.h"
   4#include "commit.h"
   5#include "diff.h"
   6#include "revision.h"
   7#include "dir.h"
   8#include "tag.h"
   9
  10static struct refspec s_tag_refspec = {
  11        0,
  12        1,
  13        0,
  14        "refs/tags/",
  15        "refs/tags/"
  16};
  17
  18const struct refspec *tag_refspec = &s_tag_refspec;
  19
  20struct counted_string {
  21        size_t len;
  22        const char *s;
  23};
  24struct rewrite {
  25        const char *base;
  26        size_t baselen;
  27        struct counted_string *instead_of;
  28        int instead_of_nr;
  29        int instead_of_alloc;
  30};
  31
  32static struct remote **remotes;
  33static int remotes_alloc;
  34static int remotes_nr;
  35
  36static struct branch **branches;
  37static int branches_alloc;
  38static int branches_nr;
  39
  40static struct branch *current_branch;
  41static const char *default_remote_name;
  42
  43static struct rewrite **rewrite;
  44static int rewrite_alloc;
  45static int rewrite_nr;
  46
  47#define BUF_SIZE (2048)
  48static char buffer[BUF_SIZE];
  49
  50static const char *alias_url(const char *url)
  51{
  52        int i, j;
  53        char *ret;
  54        struct counted_string *longest;
  55        int longest_i;
  56
  57        longest = NULL;
  58        longest_i = -1;
  59        for (i = 0; i < rewrite_nr; i++) {
  60                if (!rewrite[i])
  61                        continue;
  62                for (j = 0; j < rewrite[i]->instead_of_nr; j++) {
  63                        if (!prefixcmp(url, rewrite[i]->instead_of[j].s) &&
  64                            (!longest ||
  65                             longest->len < rewrite[i]->instead_of[j].len)) {
  66                                longest = &(rewrite[i]->instead_of[j]);
  67                                longest_i = i;
  68                        }
  69                }
  70        }
  71        if (!longest)
  72                return url;
  73
  74        ret = xmalloc(rewrite[longest_i]->baselen +
  75                     (strlen(url) - longest->len) + 1);
  76        strcpy(ret, rewrite[longest_i]->base);
  77        strcpy(ret + rewrite[longest_i]->baselen, url + longest->len);
  78        return ret;
  79}
  80
  81static void add_push_refspec(struct remote *remote, const char *ref)
  82{
  83        ALLOC_GROW(remote->push_refspec,
  84                   remote->push_refspec_nr + 1,
  85                   remote->push_refspec_alloc);
  86        remote->push_refspec[remote->push_refspec_nr++] = ref;
  87}
  88
  89static void add_fetch_refspec(struct remote *remote, const char *ref)
  90{
  91        ALLOC_GROW(remote->fetch_refspec,
  92                   remote->fetch_refspec_nr + 1,
  93                   remote->fetch_refspec_alloc);
  94        remote->fetch_refspec[remote->fetch_refspec_nr++] = ref;
  95}
  96
  97static void add_url(struct remote *remote, const char *url)
  98{
  99        ALLOC_GROW(remote->url, remote->url_nr + 1, remote->url_alloc);
 100        remote->url[remote->url_nr++] = url;
 101}
 102
 103static void add_url_alias(struct remote *remote, const char *url)
 104{
 105        add_url(remote, alias_url(url));
 106}
 107
 108static struct remote *make_remote(const char *name, int len)
 109{
 110        struct remote *ret;
 111        int i;
 112
 113        for (i = 0; i < remotes_nr; i++) {
 114                if (len ? (!strncmp(name, remotes[i]->name, len) &&
 115                           !remotes[i]->name[len]) :
 116                    !strcmp(name, remotes[i]->name))
 117                        return remotes[i];
 118        }
 119
 120        ret = xcalloc(1, sizeof(struct remote));
 121        ALLOC_GROW(remotes, remotes_nr + 1, remotes_alloc);
 122        remotes[remotes_nr++] = ret;
 123        if (len)
 124                ret->name = xstrndup(name, len);
 125        else
 126                ret->name = xstrdup(name);
 127        return ret;
 128}
 129
 130static void add_merge(struct branch *branch, const char *name)
 131{
 132        ALLOC_GROW(branch->merge_name, branch->merge_nr + 1,
 133                   branch->merge_alloc);
 134        branch->merge_name[branch->merge_nr++] = name;
 135}
 136
 137static struct branch *make_branch(const char *name, int len)
 138{
 139        struct branch *ret;
 140        int i;
 141        char *refname;
 142
 143        for (i = 0; i < branches_nr; i++) {
 144                if (len ? (!strncmp(name, branches[i]->name, len) &&
 145                           !branches[i]->name[len]) :
 146                    !strcmp(name, branches[i]->name))
 147                        return branches[i];
 148        }
 149
 150        ALLOC_GROW(branches, branches_nr + 1, branches_alloc);
 151        ret = xcalloc(1, sizeof(struct branch));
 152        branches[branches_nr++] = ret;
 153        if (len)
 154                ret->name = xstrndup(name, len);
 155        else
 156                ret->name = xstrdup(name);
 157        refname = xmalloc(strlen(name) + strlen("refs/heads/") + 1);
 158        strcpy(refname, "refs/heads/");
 159        strcpy(refname + strlen("refs/heads/"), ret->name);
 160        ret->refname = refname;
 161
 162        return ret;
 163}
 164
 165static struct rewrite *make_rewrite(const char *base, int len)
 166{
 167        struct rewrite *ret;
 168        int i;
 169
 170        for (i = 0; i < rewrite_nr; i++) {
 171                if (len
 172                    ? (len == rewrite[i]->baselen &&
 173                       !strncmp(base, rewrite[i]->base, len))
 174                    : !strcmp(base, rewrite[i]->base))
 175                        return rewrite[i];
 176        }
 177
 178        ALLOC_GROW(rewrite, rewrite_nr + 1, rewrite_alloc);
 179        ret = xcalloc(1, sizeof(struct rewrite));
 180        rewrite[rewrite_nr++] = ret;
 181        if (len) {
 182                ret->base = xstrndup(base, len);
 183                ret->baselen = len;
 184        }
 185        else {
 186                ret->base = xstrdup(base);
 187                ret->baselen = strlen(base);
 188        }
 189        return ret;
 190}
 191
 192static void add_instead_of(struct rewrite *rewrite, const char *instead_of)
 193{
 194        ALLOC_GROW(rewrite->instead_of, rewrite->instead_of_nr + 1, rewrite->instead_of_alloc);
 195        rewrite->instead_of[rewrite->instead_of_nr].s = instead_of;
 196        rewrite->instead_of[rewrite->instead_of_nr].len = strlen(instead_of);
 197        rewrite->instead_of_nr++;
 198}
 199
 200static void read_remotes_file(struct remote *remote)
 201{
 202        FILE *f = fopen(git_path("remotes/%s", remote->name), "r");
 203
 204        if (!f)
 205                return;
 206        remote->origin = REMOTE_REMOTES;
 207        while (fgets(buffer, BUF_SIZE, f)) {
 208                int value_list;
 209                char *s, *p;
 210
 211                if (!prefixcmp(buffer, "URL:")) {
 212                        value_list = 0;
 213                        s = buffer + 4;
 214                } else if (!prefixcmp(buffer, "Push:")) {
 215                        value_list = 1;
 216                        s = buffer + 5;
 217                } else if (!prefixcmp(buffer, "Pull:")) {
 218                        value_list = 2;
 219                        s = buffer + 5;
 220                } else
 221                        continue;
 222
 223                while (isspace(*s))
 224                        s++;
 225                if (!*s)
 226                        continue;
 227
 228                p = s + strlen(s);
 229                while (isspace(p[-1]))
 230                        *--p = 0;
 231
 232                switch (value_list) {
 233                case 0:
 234                        add_url_alias(remote, xstrdup(s));
 235                        break;
 236                case 1:
 237                        add_push_refspec(remote, xstrdup(s));
 238                        break;
 239                case 2:
 240                        add_fetch_refspec(remote, xstrdup(s));
 241                        break;
 242                }
 243        }
 244        fclose(f);
 245}
 246
 247static void read_branches_file(struct remote *remote)
 248{
 249        const char *slash = strchr(remote->name, '/');
 250        char *frag;
 251        struct strbuf branch = STRBUF_INIT;
 252        int n = slash ? slash - remote->name : 1000;
 253        FILE *f = fopen(git_path("branches/%.*s", n, remote->name), "r");
 254        char *s, *p;
 255        int len;
 256
 257        if (!f)
 258                return;
 259        s = fgets(buffer, BUF_SIZE, f);
 260        fclose(f);
 261        if (!s)
 262                return;
 263        while (isspace(*s))
 264                s++;
 265        if (!*s)
 266                return;
 267        remote->origin = REMOTE_BRANCHES;
 268        p = s + strlen(s);
 269        while (isspace(p[-1]))
 270                *--p = 0;
 271        len = p - s;
 272        if (slash)
 273                len += strlen(slash);
 274        p = xmalloc(len + 1);
 275        strcpy(p, s);
 276        if (slash)
 277                strcat(p, slash);
 278
 279        /*
 280         * With "slash", e.g. "git fetch jgarzik/netdev-2.6" when
 281         * reading from $GIT_DIR/branches/jgarzik fetches "HEAD" from
 282         * the partial URL obtained from the branches file plus
 283         * "/netdev-2.6" and does not store it in any tracking ref.
 284         * #branch specifier in the file is ignored.
 285         *
 286         * Otherwise, the branches file would have URL and optionally
 287         * #branch specified.  The "master" (or specified) branch is
 288         * fetched and stored in the local branch of the same name.
 289         */
 290        frag = strchr(p, '#');
 291        if (frag) {
 292                *(frag++) = '\0';
 293                strbuf_addf(&branch, "refs/heads/%s", frag);
 294        } else
 295                strbuf_addstr(&branch, "refs/heads/master");
 296        if (!slash) {
 297                strbuf_addf(&branch, ":refs/heads/%s", remote->name);
 298        } else {
 299                strbuf_reset(&branch);
 300                strbuf_addstr(&branch, "HEAD:");
 301        }
 302        add_url_alias(remote, p);
 303        add_fetch_refspec(remote, strbuf_detach(&branch, 0));
 304        /*
 305         * Cogito compatible push: push current HEAD to remote #branch
 306         * (master if missing)
 307         */
 308        strbuf_init(&branch, 0);
 309        strbuf_addstr(&branch, "HEAD");
 310        if (frag)
 311                strbuf_addf(&branch, ":refs/heads/%s", frag);
 312        else
 313                strbuf_addstr(&branch, ":refs/heads/master");
 314        add_push_refspec(remote, strbuf_detach(&branch, 0));
 315        remote->fetch_tags = 1; /* always auto-follow */
 316}
 317
 318static int handle_config(const char *key, const char *value, void *cb)
 319{
 320        const char *name;
 321        const char *subkey;
 322        struct remote *remote;
 323        struct branch *branch;
 324        if (!prefixcmp(key, "branch.")) {
 325                name = key + 7;
 326                subkey = strrchr(name, '.');
 327                if (!subkey)
 328                        return 0;
 329                branch = make_branch(name, subkey - name);
 330                if (!strcmp(subkey, ".remote")) {
 331                        if (!value)
 332                                return config_error_nonbool(key);
 333                        branch->remote_name = xstrdup(value);
 334                        if (branch == current_branch)
 335                                default_remote_name = branch->remote_name;
 336                } else if (!strcmp(subkey, ".merge")) {
 337                        if (!value)
 338                                return config_error_nonbool(key);
 339                        add_merge(branch, xstrdup(value));
 340                }
 341                return 0;
 342        }
 343        if (!prefixcmp(key, "url.")) {
 344                struct rewrite *rewrite;
 345                name = key + 4;
 346                subkey = strrchr(name, '.');
 347                if (!subkey)
 348                        return 0;
 349                rewrite = make_rewrite(name, subkey - name);
 350                if (!strcmp(subkey, ".insteadof")) {
 351                        if (!value)
 352                                return config_error_nonbool(key);
 353                        add_instead_of(rewrite, xstrdup(value));
 354                }
 355        }
 356        if (prefixcmp(key,  "remote."))
 357                return 0;
 358        name = key + 7;
 359        if (*name == '/') {
 360                warning("Config remote shorthand cannot begin with '/': %s",
 361                        name);
 362                return 0;
 363        }
 364        subkey = strrchr(name, '.');
 365        if (!subkey)
 366                return error("Config with no key for remote %s", name);
 367        remote = make_remote(name, subkey - name);
 368        remote->origin = REMOTE_CONFIG;
 369        if (!strcmp(subkey, ".mirror"))
 370                remote->mirror = git_config_bool(key, value);
 371        else if (!strcmp(subkey, ".skipdefaultupdate"))
 372                remote->skip_default_update = git_config_bool(key, value);
 373
 374        else if (!strcmp(subkey, ".url")) {
 375                const char *v;
 376                if (git_config_string(&v, key, value))
 377                        return -1;
 378                add_url(remote, v);
 379        } else if (!strcmp(subkey, ".push")) {
 380                const char *v;
 381                if (git_config_string(&v, key, value))
 382                        return -1;
 383                add_push_refspec(remote, v);
 384        } else if (!strcmp(subkey, ".fetch")) {
 385                const char *v;
 386                if (git_config_string(&v, key, value))
 387                        return -1;
 388                add_fetch_refspec(remote, v);
 389        } else if (!strcmp(subkey, ".receivepack")) {
 390                const char *v;
 391                if (git_config_string(&v, key, value))
 392                        return -1;
 393                if (!remote->receivepack)
 394                        remote->receivepack = v;
 395                else
 396                        error("more than one receivepack given, using the first");
 397        } else if (!strcmp(subkey, ".uploadpack")) {
 398                const char *v;
 399                if (git_config_string(&v, key, value))
 400                        return -1;
 401                if (!remote->uploadpack)
 402                        remote->uploadpack = v;
 403                else
 404                        error("more than one uploadpack given, using the first");
 405        } else if (!strcmp(subkey, ".tagopt")) {
 406                if (!strcmp(value, "--no-tags"))
 407                        remote->fetch_tags = -1;
 408        } else if (!strcmp(subkey, ".proxy")) {
 409                return git_config_string((const char **)&remote->http_proxy,
 410                                         key, value);
 411        }
 412        return 0;
 413}
 414
 415static void alias_all_urls(void)
 416{
 417        int i, j;
 418        for (i = 0; i < remotes_nr; i++) {
 419                if (!remotes[i])
 420                        continue;
 421                for (j = 0; j < remotes[i]->url_nr; j++) {
 422                        remotes[i]->url[j] = alias_url(remotes[i]->url[j]);
 423                }
 424        }
 425}
 426
 427static void read_config(void)
 428{
 429        unsigned char sha1[20];
 430        const char *head_ref;
 431        int flag;
 432        if (default_remote_name) // did this already
 433                return;
 434        default_remote_name = xstrdup("origin");
 435        current_branch = NULL;
 436        head_ref = resolve_ref("HEAD", sha1, 0, &flag);
 437        if (head_ref && (flag & REF_ISSYMREF) &&
 438            !prefixcmp(head_ref, "refs/heads/")) {
 439                current_branch =
 440                        make_branch(head_ref + strlen("refs/heads/"), 0);
 441        }
 442        git_config(handle_config, NULL);
 443        alias_all_urls();
 444}
 445
 446/*
 447 * We need to make sure the tracking branches are well formed, but a
 448 * wildcard refspec in "struct refspec" must have a trailing slash. We
 449 * temporarily drop the trailing '/' while calling check_ref_format(),
 450 * and put it back.  The caller knows that a CHECK_REF_FORMAT_ONELEVEL
 451 * error return is Ok for a wildcard refspec.
 452 */
 453static int verify_refname(char *name, int is_glob)
 454{
 455        int result, len = -1;
 456
 457        if (is_glob) {
 458                len = strlen(name);
 459                assert(name[len - 1] == '/');
 460                name[len - 1] = '\0';
 461        }
 462        result = check_ref_format(name);
 463        if (is_glob)
 464                name[len - 1] = '/';
 465        return result;
 466}
 467
 468/*
 469 * This function frees a refspec array.
 470 * Warning: code paths should be checked to ensure that the src
 471 *          and dst pointers are always freeable pointers as well
 472 *          as the refspec pointer itself.
 473 */
 474static void free_refspecs(struct refspec *refspec, int nr_refspec)
 475{
 476        int i;
 477
 478        if (!refspec)
 479                return;
 480
 481        for (i = 0; i < nr_refspec; i++) {
 482                free(refspec[i].src);
 483                free(refspec[i].dst);
 484        }
 485        free(refspec);
 486}
 487
 488static struct refspec *parse_refspec_internal(int nr_refspec, const char **refspec, int fetch, int verify)
 489{
 490        int i;
 491        int st;
 492        struct refspec *rs = xcalloc(sizeof(*rs), nr_refspec);
 493
 494        for (i = 0; i < nr_refspec; i++) {
 495                size_t llen;
 496                int is_glob;
 497                const char *lhs, *rhs;
 498
 499                llen = is_glob = 0;
 500
 501                lhs = refspec[i];
 502                if (*lhs == '+') {
 503                        rs[i].force = 1;
 504                        lhs++;
 505                }
 506
 507                rhs = strrchr(lhs, ':');
 508
 509                /*
 510                 * Before going on, special case ":" (or "+:") as a refspec
 511                 * for matching refs.
 512                 */
 513                if (!fetch && rhs == lhs && rhs[1] == '\0') {
 514                        rs[i].matching = 1;
 515                        continue;
 516                }
 517
 518                if (rhs) {
 519                        size_t rlen = strlen(++rhs);
 520                        is_glob = (2 <= rlen && !strcmp(rhs + rlen - 2, "/*"));
 521                        rs[i].dst = xstrndup(rhs, rlen - is_glob);
 522                }
 523
 524                llen = (rhs ? (rhs - lhs - 1) : strlen(lhs));
 525                if (2 <= llen && !memcmp(lhs + llen - 2, "/*", 2)) {
 526                        if ((rhs && !is_glob) || (!rhs && fetch))
 527                                goto invalid;
 528                        is_glob = 1;
 529                        llen--;
 530                } else if (rhs && is_glob) {
 531                        goto invalid;
 532                }
 533
 534                rs[i].pattern = is_glob;
 535                rs[i].src = xstrndup(lhs, llen);
 536
 537                if (fetch) {
 538                        /*
 539                         * LHS
 540                         * - empty is allowed; it means HEAD.
 541                         * - otherwise it must be a valid looking ref.
 542                         */
 543                        if (!*rs[i].src)
 544                                ; /* empty is ok */
 545                        else {
 546                                st = verify_refname(rs[i].src, is_glob);
 547                                if (st && st != CHECK_REF_FORMAT_ONELEVEL)
 548                                        goto invalid;
 549                        }
 550                        /*
 551                         * RHS
 552                         * - missing is ok, and is same as empty.
 553                         * - empty is ok; it means not to store.
 554                         * - otherwise it must be a valid looking ref.
 555                         */
 556                        if (!rs[i].dst) {
 557                                ; /* ok */
 558                        } else if (!*rs[i].dst) {
 559                                ; /* ok */
 560                        } else {
 561                                st = verify_refname(rs[i].dst, is_glob);
 562                                if (st && st != CHECK_REF_FORMAT_ONELEVEL)
 563                                        goto invalid;
 564                        }
 565                } else {
 566                        /*
 567                         * LHS
 568                         * - empty is allowed; it means delete.
 569                         * - when wildcarded, it must be a valid looking ref.
 570                         * - otherwise, it must be an extended SHA-1, but
 571                         *   there is no existing way to validate this.
 572                         */
 573                        if (!*rs[i].src)
 574                                ; /* empty is ok */
 575                        else if (is_glob) {
 576                                st = verify_refname(rs[i].src, is_glob);
 577                                if (st && st != CHECK_REF_FORMAT_ONELEVEL)
 578                                        goto invalid;
 579                        }
 580                        else
 581                                ; /* anything goes, for now */
 582                        /*
 583                         * RHS
 584                         * - missing is allowed, but LHS then must be a
 585                         *   valid looking ref.
 586                         * - empty is not allowed.
 587                         * - otherwise it must be a valid looking ref.
 588                         */
 589                        if (!rs[i].dst) {
 590                                st = verify_refname(rs[i].src, is_glob);
 591                                if (st && st != CHECK_REF_FORMAT_ONELEVEL)
 592                                        goto invalid;
 593                        } else if (!*rs[i].dst) {
 594                                goto invalid;
 595                        } else {
 596                                st = verify_refname(rs[i].dst, is_glob);
 597                                if (st && st != CHECK_REF_FORMAT_ONELEVEL)
 598                                        goto invalid;
 599                        }
 600                }
 601        }
 602        return rs;
 603
 604 invalid:
 605        if (verify) {
 606                /*
 607                 * nr_refspec must be greater than zero and i must be valid
 608                 * since it is only possible to reach this point from within
 609                 * the for loop above.
 610                 */
 611                free_refspecs(rs, i+1);
 612                return NULL;
 613        }
 614        die("Invalid refspec '%s'", refspec[i]);
 615}
 616
 617int valid_fetch_refspec(const char *fetch_refspec_str)
 618{
 619        const char *fetch_refspec[] = { fetch_refspec_str };
 620        struct refspec *refspec;
 621
 622        refspec = parse_refspec_internal(1, fetch_refspec, 1, 1);
 623        free_refspecs(refspec, 1);
 624        return !!refspec;
 625}
 626
 627struct refspec *parse_fetch_refspec(int nr_refspec, const char **refspec)
 628{
 629        return parse_refspec_internal(nr_refspec, refspec, 1, 0);
 630}
 631
 632static struct refspec *parse_push_refspec(int nr_refspec, const char **refspec)
 633{
 634        return parse_refspec_internal(nr_refspec, refspec, 0, 0);
 635}
 636
 637static int valid_remote_nick(const char *name)
 638{
 639        if (!name[0] || is_dot_or_dotdot(name))
 640                return 0;
 641        return !strchr(name, '/'); /* no slash */
 642}
 643
 644struct remote *remote_get(const char *name)
 645{
 646        struct remote *ret;
 647
 648        read_config();
 649        if (!name)
 650                name = default_remote_name;
 651        ret = make_remote(name, 0);
 652        if (valid_remote_nick(name)) {
 653                if (!ret->url)
 654                        read_remotes_file(ret);
 655                if (!ret->url)
 656                        read_branches_file(ret);
 657        }
 658        if (!ret->url)
 659                add_url_alias(ret, name);
 660        if (!ret->url)
 661                return NULL;
 662        ret->fetch = parse_fetch_refspec(ret->fetch_refspec_nr, ret->fetch_refspec);
 663        ret->push = parse_push_refspec(ret->push_refspec_nr, ret->push_refspec);
 664        return ret;
 665}
 666
 667int for_each_remote(each_remote_fn fn, void *priv)
 668{
 669        int i, result = 0;
 670        read_config();
 671        for (i = 0; i < remotes_nr && !result; i++) {
 672                struct remote *r = remotes[i];
 673                if (!r)
 674                        continue;
 675                if (!r->fetch)
 676                        r->fetch = parse_fetch_refspec(r->fetch_refspec_nr,
 677                                                       r->fetch_refspec);
 678                if (!r->push)
 679                        r->push = parse_push_refspec(r->push_refspec_nr,
 680                                                     r->push_refspec);
 681                result = fn(r, priv);
 682        }
 683        return result;
 684}
 685
 686void ref_remove_duplicates(struct ref *ref_map)
 687{
 688        struct ref **posn;
 689        struct ref *next;
 690        for (; ref_map; ref_map = ref_map->next) {
 691                if (!ref_map->peer_ref)
 692                        continue;
 693                posn = &ref_map->next;
 694                while (*posn) {
 695                        if ((*posn)->peer_ref &&
 696                            !strcmp((*posn)->peer_ref->name,
 697                                    ref_map->peer_ref->name)) {
 698                                if (strcmp((*posn)->name, ref_map->name))
 699                                        die("%s tracks both %s and %s",
 700                                            ref_map->peer_ref->name,
 701                                            (*posn)->name, ref_map->name);
 702                                next = (*posn)->next;
 703                                free((*posn)->peer_ref);
 704                                free(*posn);
 705                                *posn = next;
 706                        } else {
 707                                posn = &(*posn)->next;
 708                        }
 709                }
 710        }
 711}
 712
 713int remote_has_url(struct remote *remote, const char *url)
 714{
 715        int i;
 716        for (i = 0; i < remote->url_nr; i++) {
 717                if (!strcmp(remote->url[i], url))
 718                        return 1;
 719        }
 720        return 0;
 721}
 722
 723int remote_find_tracking(struct remote *remote, struct refspec *refspec)
 724{
 725        int find_src = refspec->src == NULL;
 726        char *needle, **result;
 727        int i;
 728
 729        if (find_src) {
 730                if (!refspec->dst)
 731                        return error("find_tracking: need either src or dst");
 732                needle = refspec->dst;
 733                result = &refspec->src;
 734        } else {
 735                needle = refspec->src;
 736                result = &refspec->dst;
 737        }
 738
 739        for (i = 0; i < remote->fetch_refspec_nr; i++) {
 740                struct refspec *fetch = &remote->fetch[i];
 741                const char *key = find_src ? fetch->dst : fetch->src;
 742                const char *value = find_src ? fetch->src : fetch->dst;
 743                if (!fetch->dst)
 744                        continue;
 745                if (fetch->pattern) {
 746                        if (!prefixcmp(needle, key)) {
 747                                *result = xmalloc(strlen(value) +
 748                                                  strlen(needle) -
 749                                                  strlen(key) + 1);
 750                                strcpy(*result, value);
 751                                strcpy(*result + strlen(value),
 752                                       needle + strlen(key));
 753                                refspec->force = fetch->force;
 754                                return 0;
 755                        }
 756                } else if (!strcmp(needle, key)) {
 757                        *result = xstrdup(value);
 758                        refspec->force = fetch->force;
 759                        return 0;
 760                }
 761        }
 762        return -1;
 763}
 764
 765static struct ref *alloc_ref_with_prefix(const char *prefix, size_t prefixlen,
 766                const char *name)
 767{
 768        size_t len = strlen(name);
 769        struct ref *ref = xcalloc(1, sizeof(struct ref) + prefixlen + len + 1);
 770        memcpy(ref->name, prefix, prefixlen);
 771        memcpy(ref->name + prefixlen, name, len);
 772        return ref;
 773}
 774
 775struct ref *alloc_ref(const char *name)
 776{
 777        return alloc_ref_with_prefix("", 0, name);
 778}
 779
 780static struct ref *copy_ref(const struct ref *ref)
 781{
 782        struct ref *cpy;
 783        size_t len;
 784        if (!ref)
 785                return NULL;
 786        len = strlen(ref->name);
 787        cpy = xmalloc(sizeof(struct ref) + len + 1);
 788        memcpy(cpy, ref, sizeof(struct ref) + len + 1);
 789        cpy->next = NULL;
 790        cpy->symref = ref->symref ? xstrdup(ref->symref) : NULL;
 791        cpy->remote_status = ref->remote_status ? xstrdup(ref->remote_status) : NULL;
 792        cpy->peer_ref = copy_ref(ref->peer_ref);
 793        return cpy;
 794}
 795
 796struct ref *copy_ref_list(const struct ref *ref)
 797{
 798        struct ref *ret = NULL;
 799        struct ref **tail = &ret;
 800        while (ref) {
 801                *tail = copy_ref(ref);
 802                ref = ref->next;
 803                tail = &((*tail)->next);
 804        }
 805        return ret;
 806}
 807
 808static void free_ref(struct ref *ref)
 809{
 810        if (!ref)
 811                return;
 812        free_ref(ref->peer_ref);
 813        free(ref->remote_status);
 814        free(ref->symref);
 815        free(ref);
 816}
 817
 818void free_refs(struct ref *ref)
 819{
 820        struct ref *next;
 821        while (ref) {
 822                next = ref->next;
 823                free_ref(ref);
 824                ref = next;
 825        }
 826}
 827
 828static int count_refspec_match(const char *pattern,
 829                               struct ref *refs,
 830                               struct ref **matched_ref)
 831{
 832        int patlen = strlen(pattern);
 833        struct ref *matched_weak = NULL;
 834        struct ref *matched = NULL;
 835        int weak_match = 0;
 836        int match = 0;
 837
 838        for (weak_match = match = 0; refs; refs = refs->next) {
 839                char *name = refs->name;
 840                int namelen = strlen(name);
 841
 842                if (!refname_match(pattern, name, ref_rev_parse_rules))
 843                        continue;
 844
 845                /* A match is "weak" if it is with refs outside
 846                 * heads or tags, and did not specify the pattern
 847                 * in full (e.g. "refs/remotes/origin/master") or at
 848                 * least from the toplevel (e.g. "remotes/origin/master");
 849                 * otherwise "git push $URL master" would result in
 850                 * ambiguity between remotes/origin/master and heads/master
 851                 * at the remote site.
 852                 */
 853                if (namelen != patlen &&
 854                    patlen != namelen - 5 &&
 855                    prefixcmp(name, "refs/heads/") &&
 856                    prefixcmp(name, "refs/tags/")) {
 857                        /* We want to catch the case where only weak
 858                         * matches are found and there are multiple
 859                         * matches, and where more than one strong
 860                         * matches are found, as ambiguous.  One
 861                         * strong match with zero or more weak matches
 862                         * are acceptable as a unique match.
 863                         */
 864                        matched_weak = refs;
 865                        weak_match++;
 866                }
 867                else {
 868                        matched = refs;
 869                        match++;
 870                }
 871        }
 872        if (!matched) {
 873                *matched_ref = matched_weak;
 874                return weak_match;
 875        }
 876        else {
 877                *matched_ref = matched;
 878                return match;
 879        }
 880}
 881
 882static void tail_link_ref(struct ref *ref, struct ref ***tail)
 883{
 884        **tail = ref;
 885        while (ref->next)
 886                ref = ref->next;
 887        *tail = &ref->next;
 888}
 889
 890static struct ref *try_explicit_object_name(const char *name)
 891{
 892        unsigned char sha1[20];
 893        struct ref *ref;
 894
 895        if (!*name) {
 896                ref = alloc_ref("(delete)");
 897                hashclr(ref->new_sha1);
 898                return ref;
 899        }
 900        if (get_sha1(name, sha1))
 901                return NULL;
 902        ref = alloc_ref(name);
 903        hashcpy(ref->new_sha1, sha1);
 904        return ref;
 905}
 906
 907static struct ref *make_linked_ref(const char *name, struct ref ***tail)
 908{
 909        struct ref *ret = alloc_ref(name);
 910        tail_link_ref(ret, tail);
 911        return ret;
 912}
 913
 914static char *guess_ref(const char *name, struct ref *peer)
 915{
 916        struct strbuf buf = STRBUF_INIT;
 917        unsigned char sha1[20];
 918
 919        const char *r = resolve_ref(peer->name, sha1, 1, NULL);
 920        if (!r)
 921                return NULL;
 922
 923        if (!prefixcmp(r, "refs/heads/"))
 924                strbuf_addstr(&buf, "refs/heads/");
 925        else if (!prefixcmp(r, "refs/tags/"))
 926                strbuf_addstr(&buf, "refs/tags/");
 927        else
 928                return NULL;
 929
 930        strbuf_addstr(&buf, name);
 931        return strbuf_detach(&buf, NULL);
 932}
 933
 934static int match_explicit(struct ref *src, struct ref *dst,
 935                          struct ref ***dst_tail,
 936                          struct refspec *rs)
 937{
 938        struct ref *matched_src, *matched_dst;
 939
 940        const char *dst_value = rs->dst;
 941        char *dst_guess;
 942
 943        if (rs->pattern || rs->matching)
 944                return 0;
 945
 946        matched_src = matched_dst = NULL;
 947        switch (count_refspec_match(rs->src, src, &matched_src)) {
 948        case 1:
 949                break;
 950        case 0:
 951                /* The source could be in the get_sha1() format
 952                 * not a reference name.  :refs/other is a
 953                 * way to delete 'other' ref at the remote end.
 954                 */
 955                matched_src = try_explicit_object_name(rs->src);
 956                if (!matched_src)
 957                        return error("src refspec %s does not match any.", rs->src);
 958                break;
 959        default:
 960                return error("src refspec %s matches more than one.", rs->src);
 961        }
 962
 963        if (!dst_value) {
 964                unsigned char sha1[20];
 965                int flag;
 966
 967                dst_value = resolve_ref(matched_src->name, sha1, 1, &flag);
 968                if (!dst_value ||
 969                    ((flag & REF_ISSYMREF) &&
 970                     prefixcmp(dst_value, "refs/heads/")))
 971                        die("%s cannot be resolved to branch.",
 972                            matched_src->name);
 973        }
 974
 975        switch (count_refspec_match(dst_value, dst, &matched_dst)) {
 976        case 1:
 977                break;
 978        case 0:
 979                if (!memcmp(dst_value, "refs/", 5))
 980                        matched_dst = make_linked_ref(dst_value, dst_tail);
 981                else if((dst_guess = guess_ref(dst_value, matched_src)))
 982                        matched_dst = make_linked_ref(dst_guess, dst_tail);
 983                else
 984                        error("unable to push to unqualified destination: %s\n"
 985                              "The destination refspec neither matches an "
 986                              "existing ref on the remote nor\n"
 987                              "begins with refs/, and we are unable to "
 988                              "guess a prefix based on the source ref.",
 989                              dst_value);
 990                break;
 991        default:
 992                matched_dst = NULL;
 993                error("dst refspec %s matches more than one.",
 994                      dst_value);
 995                break;
 996        }
 997        if (!matched_dst)
 998                return -1;
 999        if (matched_dst->peer_ref)
1000                return error("dst ref %s receives from more than one src.",
1001                      matched_dst->name);
1002        else {
1003                matched_dst->peer_ref = matched_src;
1004                matched_dst->force = rs->force;
1005        }
1006        return 0;
1007}
1008
1009static int match_explicit_refs(struct ref *src, struct ref *dst,
1010                               struct ref ***dst_tail, struct refspec *rs,
1011                               int rs_nr)
1012{
1013        int i, errs;
1014        for (i = errs = 0; i < rs_nr; i++)
1015                errs += match_explicit(src, dst, dst_tail, &rs[i]);
1016        return errs;
1017}
1018
1019static const struct refspec *check_pattern_match(const struct refspec *rs,
1020                                                 int rs_nr,
1021                                                 const struct ref *src)
1022{
1023        int i;
1024        int matching_refs = -1;
1025        for (i = 0; i < rs_nr; i++) {
1026                if (rs[i].matching &&
1027                    (matching_refs == -1 || rs[i].force)) {
1028                        matching_refs = i;
1029                        continue;
1030                }
1031
1032                if (rs[i].pattern && !prefixcmp(src->name, rs[i].src))
1033                        return rs + i;
1034        }
1035        if (matching_refs != -1)
1036                return rs + matching_refs;
1037        else
1038                return NULL;
1039}
1040
1041/*
1042 * Note. This is used only by "push"; refspec matching rules for
1043 * push and fetch are subtly different, so do not try to reuse it
1044 * without thinking.
1045 */
1046int match_refs(struct ref *src, struct ref *dst, struct ref ***dst_tail,
1047               int nr_refspec, const char **refspec, int flags)
1048{
1049        struct refspec *rs;
1050        int send_all = flags & MATCH_REFS_ALL;
1051        int send_mirror = flags & MATCH_REFS_MIRROR;
1052        static const char *default_refspec[] = { ":", 0 };
1053
1054        if (!nr_refspec) {
1055                nr_refspec = 1;
1056                refspec = default_refspec;
1057        }
1058        rs = parse_push_refspec(nr_refspec, (const char **) refspec);
1059        if (match_explicit_refs(src, dst, dst_tail, rs, nr_refspec))
1060                return -1;
1061
1062        /* pick the remainder */
1063        for ( ; src; src = src->next) {
1064                struct ref *dst_peer;
1065                const struct refspec *pat = NULL;
1066                char *dst_name;
1067                if (src->peer_ref)
1068                        continue;
1069
1070                pat = check_pattern_match(rs, nr_refspec, src);
1071                if (!pat)
1072                        continue;
1073
1074                if (pat->matching) {
1075                        /*
1076                         * "matching refs"; traditionally we pushed everything
1077                         * including refs outside refs/heads/ hierarchy, but
1078                         * that does not make much sense these days.
1079                         */
1080                        if (!send_mirror && prefixcmp(src->name, "refs/heads/"))
1081                                continue;
1082                        dst_name = xstrdup(src->name);
1083
1084                } else {
1085                        const char *dst_side = pat->dst ? pat->dst : pat->src;
1086                        dst_name = xmalloc(strlen(dst_side) +
1087                                           strlen(src->name) -
1088                                           strlen(pat->src) + 2);
1089                        strcpy(dst_name, dst_side);
1090                        strcat(dst_name, src->name + strlen(pat->src));
1091                }
1092                dst_peer = find_ref_by_name(dst, dst_name);
1093                if (dst_peer) {
1094                        if (dst_peer->peer_ref)
1095                                /* We're already sending something to this ref. */
1096                                goto free_name;
1097
1098                } else {
1099                        if (pat->matching && !(send_all || send_mirror))
1100                                /*
1101                                 * Remote doesn't have it, and we have no
1102                                 * explicit pattern, and we don't have
1103                                 * --all nor --mirror.
1104                                 */
1105                                goto free_name;
1106
1107                        /* Create a new one and link it */
1108                        dst_peer = make_linked_ref(dst_name, dst_tail);
1109                        hashcpy(dst_peer->new_sha1, src->new_sha1);
1110                }
1111                dst_peer->peer_ref = src;
1112                dst_peer->force = pat->force;
1113        free_name:
1114                free(dst_name);
1115        }
1116        return 0;
1117}
1118
1119struct branch *branch_get(const char *name)
1120{
1121        struct branch *ret;
1122
1123        read_config();
1124        if (!name || !*name || !strcmp(name, "HEAD"))
1125                ret = current_branch;
1126        else
1127                ret = make_branch(name, 0);
1128        if (ret && ret->remote_name) {
1129                ret->remote = remote_get(ret->remote_name);
1130                if (ret->merge_nr) {
1131                        int i;
1132                        ret->merge = xcalloc(sizeof(*ret->merge),
1133                                             ret->merge_nr);
1134                        for (i = 0; i < ret->merge_nr; i++) {
1135                                ret->merge[i] = xcalloc(1, sizeof(**ret->merge));
1136                                ret->merge[i]->src = xstrdup(ret->merge_name[i]);
1137                                remote_find_tracking(ret->remote,
1138                                                     ret->merge[i]);
1139                        }
1140                }
1141        }
1142        return ret;
1143}
1144
1145int branch_has_merge_config(struct branch *branch)
1146{
1147        return branch && !!branch->merge;
1148}
1149
1150int branch_merge_matches(struct branch *branch,
1151                                 int i,
1152                                 const char *refname)
1153{
1154        if (!branch || i < 0 || i >= branch->merge_nr)
1155                return 0;
1156        return refname_match(branch->merge[i]->src, refname, ref_fetch_rules);
1157}
1158
1159static struct ref *get_expanded_map(const struct ref *remote_refs,
1160                                    const struct refspec *refspec)
1161{
1162        const struct ref *ref;
1163        struct ref *ret = NULL;
1164        struct ref **tail = &ret;
1165
1166        int remote_prefix_len = strlen(refspec->src);
1167        int local_prefix_len = strlen(refspec->dst);
1168
1169        for (ref = remote_refs; ref; ref = ref->next) {
1170                if (strchr(ref->name, '^'))
1171                        continue; /* a dereference item */
1172                if (!prefixcmp(ref->name, refspec->src)) {
1173                        const char *match;
1174                        struct ref *cpy = copy_ref(ref);
1175                        match = ref->name + remote_prefix_len;
1176
1177                        cpy->peer_ref = alloc_ref_with_prefix(refspec->dst,
1178                                        local_prefix_len, match);
1179                        if (refspec->force)
1180                                cpy->peer_ref->force = 1;
1181                        *tail = cpy;
1182                        tail = &cpy->next;
1183                }
1184        }
1185
1186        return ret;
1187}
1188
1189static const struct ref *find_ref_by_name_abbrev(const struct ref *refs, const char *name)
1190{
1191        const struct ref *ref;
1192        for (ref = refs; ref; ref = ref->next) {
1193                if (refname_match(name, ref->name, ref_fetch_rules))
1194                        return ref;
1195        }
1196        return NULL;
1197}
1198
1199struct ref *get_remote_ref(const struct ref *remote_refs, const char *name)
1200{
1201        const struct ref *ref = find_ref_by_name_abbrev(remote_refs, name);
1202
1203        if (!ref)
1204                return NULL;
1205
1206        return copy_ref(ref);
1207}
1208
1209static struct ref *get_local_ref(const char *name)
1210{
1211        if (!name)
1212                return NULL;
1213
1214        if (!prefixcmp(name, "refs/"))
1215                return alloc_ref(name);
1216
1217        if (!prefixcmp(name, "heads/") ||
1218            !prefixcmp(name, "tags/") ||
1219            !prefixcmp(name, "remotes/"))
1220                return alloc_ref_with_prefix("refs/", 5, name);
1221
1222        return alloc_ref_with_prefix("refs/heads/", 11, name);
1223}
1224
1225int get_fetch_map(const struct ref *remote_refs,
1226                  const struct refspec *refspec,
1227                  struct ref ***tail,
1228                  int missing_ok)
1229{
1230        struct ref *ref_map, **rmp;
1231
1232        if (refspec->pattern) {
1233                ref_map = get_expanded_map(remote_refs, refspec);
1234        } else {
1235                const char *name = refspec->src[0] ? refspec->src : "HEAD";
1236
1237                ref_map = get_remote_ref(remote_refs, name);
1238                if (!missing_ok && !ref_map)
1239                        die("Couldn't find remote ref %s", name);
1240                if (ref_map) {
1241                        ref_map->peer_ref = get_local_ref(refspec->dst);
1242                        if (ref_map->peer_ref && refspec->force)
1243                                ref_map->peer_ref->force = 1;
1244                }
1245        }
1246
1247        for (rmp = &ref_map; *rmp; ) {
1248                if ((*rmp)->peer_ref) {
1249                        int st = check_ref_format((*rmp)->peer_ref->name + 5);
1250                        if (st && st != CHECK_REF_FORMAT_ONELEVEL) {
1251                                struct ref *ignore = *rmp;
1252                                error("* Ignoring funny ref '%s' locally",
1253                                      (*rmp)->peer_ref->name);
1254                                *rmp = (*rmp)->next;
1255                                free(ignore->peer_ref);
1256                                free(ignore);
1257                                continue;
1258                        }
1259                }
1260                rmp = &((*rmp)->next);
1261        }
1262
1263        if (ref_map)
1264                tail_link_ref(ref_map, tail);
1265
1266        return 0;
1267}
1268
1269int resolve_remote_symref(struct ref *ref, struct ref *list)
1270{
1271        if (!ref->symref)
1272                return 0;
1273        for (; list; list = list->next)
1274                if (!strcmp(ref->symref, list->name)) {
1275                        hashcpy(ref->old_sha1, list->old_sha1);
1276                        return 0;
1277                }
1278        return 1;
1279}
1280
1281static void unmark_and_free(struct commit_list *list, unsigned int mark)
1282{
1283        while (list) {
1284                struct commit_list *temp = list;
1285                temp->item->object.flags &= ~mark;
1286                list = temp->next;
1287                free(temp);
1288        }
1289}
1290
1291int ref_newer(const unsigned char *new_sha1, const unsigned char *old_sha1)
1292{
1293        struct object *o;
1294        struct commit *old, *new;
1295        struct commit_list *list, *used;
1296        int found = 0;
1297
1298        /* Both new and old must be commit-ish and new is descendant of
1299         * old.  Otherwise we require --force.
1300         */
1301        o = deref_tag(parse_object(old_sha1), NULL, 0);
1302        if (!o || o->type != OBJ_COMMIT)
1303                return 0;
1304        old = (struct commit *) o;
1305
1306        o = deref_tag(parse_object(new_sha1), NULL, 0);
1307        if (!o || o->type != OBJ_COMMIT)
1308                return 0;
1309        new = (struct commit *) o;
1310
1311        if (parse_commit(new) < 0)
1312                return 0;
1313
1314        used = list = NULL;
1315        commit_list_insert(new, &list);
1316        while (list) {
1317                new = pop_most_recent_commit(&list, TMP_MARK);
1318                commit_list_insert(new, &used);
1319                if (new == old) {
1320                        found = 1;
1321                        break;
1322                }
1323        }
1324        unmark_and_free(list, TMP_MARK);
1325        unmark_and_free(used, TMP_MARK);
1326        return found;
1327}
1328
1329/*
1330 * Return true if there is anything to report, otherwise false.
1331 */
1332int stat_tracking_info(struct branch *branch, int *num_ours, int *num_theirs)
1333{
1334        unsigned char sha1[20];
1335        struct commit *ours, *theirs;
1336        char symmetric[84];
1337        struct rev_info revs;
1338        const char *rev_argv[10], *base;
1339        int rev_argc;
1340
1341        /*
1342         * Nothing to report unless we are marked to build on top of
1343         * somebody else.
1344         */
1345        if (!branch ||
1346            !branch->merge || !branch->merge[0] || !branch->merge[0]->dst)
1347                return 0;
1348
1349        /*
1350         * If what we used to build on no longer exists, there is
1351         * nothing to report.
1352         */
1353        base = branch->merge[0]->dst;
1354        if (!resolve_ref(base, sha1, 1, NULL))
1355                return 0;
1356        theirs = lookup_commit(sha1);
1357        if (!theirs)
1358                return 0;
1359
1360        if (!resolve_ref(branch->refname, sha1, 1, NULL))
1361                return 0;
1362        ours = lookup_commit(sha1);
1363        if (!ours)
1364                return 0;
1365
1366        /* are we the same? */
1367        if (theirs == ours)
1368                return 0;
1369
1370        /* Run "rev-list --left-right ours...theirs" internally... */
1371        rev_argc = 0;
1372        rev_argv[rev_argc++] = NULL;
1373        rev_argv[rev_argc++] = "--left-right";
1374        rev_argv[rev_argc++] = symmetric;
1375        rev_argv[rev_argc++] = "--";
1376        rev_argv[rev_argc] = NULL;
1377
1378        strcpy(symmetric, sha1_to_hex(ours->object.sha1));
1379        strcpy(symmetric + 40, "...");
1380        strcpy(symmetric + 43, sha1_to_hex(theirs->object.sha1));
1381
1382        init_revisions(&revs, NULL);
1383        setup_revisions(rev_argc, rev_argv, &revs, NULL);
1384        prepare_revision_walk(&revs);
1385
1386        /* ... and count the commits on each side. */
1387        *num_ours = 0;
1388        *num_theirs = 0;
1389        while (1) {
1390                struct commit *c = get_revision(&revs);
1391                if (!c)
1392                        break;
1393                if (c->object.flags & SYMMETRIC_LEFT)
1394                        (*num_ours)++;
1395                else
1396                        (*num_theirs)++;
1397        }
1398
1399        /* clear object flags smudged by the above traversal */
1400        clear_commit_marks(ours, ALL_REV_FLAGS);
1401        clear_commit_marks(theirs, ALL_REV_FLAGS);
1402        return 1;
1403}
1404
1405/*
1406 * Return true when there is anything to report, otherwise false.
1407 */
1408int format_tracking_info(struct branch *branch, struct strbuf *sb)
1409{
1410        int num_ours, num_theirs;
1411        const char *base;
1412
1413        if (!stat_tracking_info(branch, &num_ours, &num_theirs))
1414                return 0;
1415
1416        base = branch->merge[0]->dst;
1417        if (!prefixcmp(base, "refs/remotes/")) {
1418                base += strlen("refs/remotes/");
1419        }
1420        if (!num_theirs)
1421                strbuf_addf(sb, "Your branch is ahead of '%s' "
1422                            "by %d commit%s.\n",
1423                            base, num_ours, (num_ours == 1) ? "" : "s");
1424        else if (!num_ours)
1425                strbuf_addf(sb, "Your branch is behind '%s' "
1426                            "by %d commit%s, "
1427                            "and can be fast-forwarded.\n",
1428                            base, num_theirs, (num_theirs == 1) ? "" : "s");
1429        else
1430                strbuf_addf(sb, "Your branch and '%s' have diverged,\n"
1431                            "and have %d and %d different commit(s) each, "
1432                            "respectively.\n",
1433                            base, num_ours, num_theirs);
1434        return 1;
1435}
1436
1437static int one_local_ref(const char *refname, const unsigned char *sha1, int flag, void *cb_data)
1438{
1439        struct ref ***local_tail = cb_data;
1440        struct ref *ref;
1441        int len;
1442
1443        /* we already know it starts with refs/ to get here */
1444        if (check_ref_format(refname + 5))
1445                return 0;
1446
1447        len = strlen(refname) + 1;
1448        ref = xcalloc(1, sizeof(*ref) + len);
1449        hashcpy(ref->new_sha1, sha1);
1450        memcpy(ref->name, refname, len);
1451        **local_tail = ref;
1452        *local_tail = &ref->next;
1453        return 0;
1454}
1455
1456struct ref *get_local_heads(void)
1457{
1458        struct ref *local_refs, **local_tail = &local_refs;
1459        for_each_ref(one_local_ref, &local_tail);
1460        return local_refs;
1461}
1462
1463struct ref *guess_remote_head(const struct ref *head,
1464                              const struct ref *refs,
1465                              int all)
1466{
1467        const struct ref *r;
1468        struct ref *list = NULL;
1469        struct ref **tail = &list;
1470
1471        if (!head)
1472                return NULL;
1473
1474        /* If refs/heads/master could be right, it is. */
1475        if (!all) {
1476                r = find_ref_by_name(refs, "refs/heads/master");
1477                if (r && !hashcmp(r->old_sha1, head->old_sha1))
1478                        return copy_ref(r);
1479        }
1480
1481        /* Look for another ref that points there */
1482        for (r = refs; r; r = r->next) {
1483                if (r != head && !hashcmp(r->old_sha1, head->old_sha1)) {
1484                        *tail = copy_ref(r);
1485                        tail = &((*tail)->next);
1486                        if (!all)
1487                                break;
1488                }
1489        }
1490
1491        return list;
1492}