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