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