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