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