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