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