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