remote.con commit Windows: do not treat a path with backslashes as a remote's nick name (d9244ec)
   1#include "cache.h"
   2#include "remote.h"
   3#include "refs.h"
   4#include "commit.h"
   5#include "diff.h"
   6#include "revision.h"
   7#include "dir.h"
   8#include "tag.h"
   9#include "string-list.h"
  10#include "mergesort.h"
  11#include "argv-array.h"
  12
  13enum map_direction { FROM_SRC, FROM_DST };
  14
  15static struct refspec s_tag_refspec = {
  16        0,
  17        1,
  18        0,
  19        0,
  20        "refs/tags/*",
  21        "refs/tags/*"
  22};
  23
  24const struct refspec *tag_refspec = &s_tag_refspec;
  25
  26struct counted_string {
  27        size_t len;
  28        const char *s;
  29};
  30struct rewrite {
  31        const char *base;
  32        size_t baselen;
  33        struct counted_string *instead_of;
  34        int instead_of_nr;
  35        int instead_of_alloc;
  36};
  37struct rewrites {
  38        struct rewrite **rewrite;
  39        int rewrite_alloc;
  40        int rewrite_nr;
  41};
  42
  43static struct remote **remotes;
  44static int remotes_alloc;
  45static int remotes_nr;
  46static struct hashmap remotes_hash;
  47
  48static struct branch **branches;
  49static int branches_alloc;
  50static int branches_nr;
  51
  52static struct branch *current_branch;
  53static const char *pushremote_name;
  54
  55static struct rewrites rewrites;
  56static struct rewrites rewrites_push;
  57
  58static int valid_remote(const struct remote *remote)
  59{
  60        return (!!remote->url) || (!!remote->foreign_vcs);
  61}
  62
  63static const char *alias_url(const char *url, struct rewrites *r)
  64{
  65        int i, j;
  66        struct counted_string *longest;
  67        int longest_i;
  68
  69        longest = NULL;
  70        longest_i = -1;
  71        for (i = 0; i < r->rewrite_nr; i++) {
  72                if (!r->rewrite[i])
  73                        continue;
  74                for (j = 0; j < r->rewrite[i]->instead_of_nr; j++) {
  75                        if (starts_with(url, r->rewrite[i]->instead_of[j].s) &&
  76                            (!longest ||
  77                             longest->len < r->rewrite[i]->instead_of[j].len)) {
  78                                longest = &(r->rewrite[i]->instead_of[j]);
  79                                longest_i = i;
  80                        }
  81                }
  82        }
  83        if (!longest)
  84                return url;
  85
  86        return xstrfmt("%s%s", r->rewrite[longest_i]->base, url + longest->len);
  87}
  88
  89static void add_push_refspec(struct remote *remote, const char *ref)
  90{
  91        ALLOC_GROW(remote->push_refspec,
  92                   remote->push_refspec_nr + 1,
  93                   remote->push_refspec_alloc);
  94        remote->push_refspec[remote->push_refspec_nr++] = ref;
  95}
  96
  97static void add_fetch_refspec(struct remote *remote, const char *ref)
  98{
  99        ALLOC_GROW(remote->fetch_refspec,
 100                   remote->fetch_refspec_nr + 1,
 101                   remote->fetch_refspec_alloc);
 102        remote->fetch_refspec[remote->fetch_refspec_nr++] = ref;
 103}
 104
 105static void add_url(struct remote *remote, const char *url)
 106{
 107        ALLOC_GROW(remote->url, remote->url_nr + 1, remote->url_alloc);
 108        remote->url[remote->url_nr++] = url;
 109}
 110
 111static void add_pushurl(struct remote *remote, const char *pushurl)
 112{
 113        ALLOC_GROW(remote->pushurl, remote->pushurl_nr + 1, remote->pushurl_alloc);
 114        remote->pushurl[remote->pushurl_nr++] = pushurl;
 115}
 116
 117static void add_pushurl_alias(struct remote *remote, const char *url)
 118{
 119        const char *pushurl = alias_url(url, &rewrites_push);
 120        if (pushurl != url)
 121                add_pushurl(remote, pushurl);
 122}
 123
 124static void add_url_alias(struct remote *remote, const char *url)
 125{
 126        add_url(remote, alias_url(url, &rewrites));
 127        add_pushurl_alias(remote, url);
 128}
 129
 130struct remotes_hash_key {
 131        const char *str;
 132        int len;
 133};
 134
 135static int remotes_hash_cmp(const struct remote *a, const struct remote *b, const struct remotes_hash_key *key)
 136{
 137        if (key)
 138                return strncmp(a->name, key->str, key->len) || a->name[key->len];
 139        else
 140                return strcmp(a->name, b->name);
 141}
 142
 143static inline void init_remotes_hash(void)
 144{
 145        if (!remotes_hash.cmpfn)
 146                hashmap_init(&remotes_hash, (hashmap_cmp_fn)remotes_hash_cmp, 0);
 147}
 148
 149static struct remote *make_remote(const char *name, int len)
 150{
 151        struct remote *ret, *replaced;
 152        struct remotes_hash_key lookup;
 153        struct hashmap_entry lookup_entry;
 154
 155        if (!len)
 156                len = strlen(name);
 157
 158        init_remotes_hash();
 159        lookup.str = name;
 160        lookup.len = len;
 161        hashmap_entry_init(&lookup_entry, memhash(name, len));
 162
 163        if ((ret = hashmap_get(&remotes_hash, &lookup_entry, &lookup)) != NULL)
 164                return ret;
 165
 166        ret = xcalloc(1, sizeof(struct remote));
 167        ret->prune = -1;  /* unspecified */
 168        ALLOC_GROW(remotes, remotes_nr + 1, remotes_alloc);
 169        remotes[remotes_nr++] = ret;
 170        ret->name = xstrndup(name, len);
 171
 172        hashmap_entry_init(ret, lookup_entry.hash);
 173        replaced = hashmap_put(&remotes_hash, ret);
 174        assert(replaced == NULL);  /* no previous entry overwritten */
 175        return ret;
 176}
 177
 178static void add_merge(struct branch *branch, const char *name)
 179{
 180        ALLOC_GROW(branch->merge_name, branch->merge_nr + 1,
 181                   branch->merge_alloc);
 182        branch->merge_name[branch->merge_nr++] = name;
 183}
 184
 185static struct branch *make_branch(const char *name, int len)
 186{
 187        struct branch *ret;
 188        int i;
 189
 190        for (i = 0; i < branches_nr; i++) {
 191                if (len ? (!strncmp(name, branches[i]->name, len) &&
 192                           !branches[i]->name[len]) :
 193                    !strcmp(name, branches[i]->name))
 194                        return branches[i];
 195        }
 196
 197        ALLOC_GROW(branches, branches_nr + 1, branches_alloc);
 198        ret = xcalloc(1, sizeof(struct branch));
 199        branches[branches_nr++] = ret;
 200        if (len)
 201                ret->name = xstrndup(name, len);
 202        else
 203                ret->name = xstrdup(name);
 204        ret->refname = xstrfmt("refs/heads/%s", ret->name);
 205
 206        return ret;
 207}
 208
 209static struct rewrite *make_rewrite(struct rewrites *r, const char *base, int len)
 210{
 211        struct rewrite *ret;
 212        int i;
 213
 214        for (i = 0; i < r->rewrite_nr; i++) {
 215                if (len
 216                    ? (len == r->rewrite[i]->baselen &&
 217                       !strncmp(base, r->rewrite[i]->base, len))
 218                    : !strcmp(base, r->rewrite[i]->base))
 219                        return r->rewrite[i];
 220        }
 221
 222        ALLOC_GROW(r->rewrite, r->rewrite_nr + 1, r->rewrite_alloc);
 223        ret = xcalloc(1, sizeof(struct rewrite));
 224        r->rewrite[r->rewrite_nr++] = ret;
 225        if (len) {
 226                ret->base = xstrndup(base, len);
 227                ret->baselen = len;
 228        }
 229        else {
 230                ret->base = xstrdup(base);
 231                ret->baselen = strlen(base);
 232        }
 233        return ret;
 234}
 235
 236static void add_instead_of(struct rewrite *rewrite, const char *instead_of)
 237{
 238        ALLOC_GROW(rewrite->instead_of, rewrite->instead_of_nr + 1, rewrite->instead_of_alloc);
 239        rewrite->instead_of[rewrite->instead_of_nr].s = instead_of;
 240        rewrite->instead_of[rewrite->instead_of_nr].len = strlen(instead_of);
 241        rewrite->instead_of_nr++;
 242}
 243
 244static const char *skip_spaces(const char *s)
 245{
 246        while (isspace(*s))
 247                s++;
 248        return s;
 249}
 250
 251static void read_remotes_file(struct remote *remote)
 252{
 253        struct strbuf buf = STRBUF_INIT;
 254        FILE *f = fopen(git_path("remotes/%s", remote->name), "r");
 255
 256        if (!f)
 257                return;
 258        remote->origin = REMOTE_REMOTES;
 259        while (strbuf_getline(&buf, f) != EOF) {
 260                const char *v;
 261
 262                strbuf_rtrim(&buf);
 263
 264                if (skip_prefix(buf.buf, "URL:", &v))
 265                        add_url_alias(remote, xstrdup(skip_spaces(v)));
 266                else if (skip_prefix(buf.buf, "Push:", &v))
 267                        add_push_refspec(remote, xstrdup(skip_spaces(v)));
 268                else if (skip_prefix(buf.buf, "Pull:", &v))
 269                        add_fetch_refspec(remote, xstrdup(skip_spaces(v)));
 270        }
 271        strbuf_release(&buf);
 272        fclose(f);
 273}
 274
 275static void read_branches_file(struct remote *remote)
 276{
 277        char *frag;
 278        struct strbuf buf = STRBUF_INIT;
 279        FILE *f = fopen(git_path("branches/%s", remote->name), "r");
 280
 281        if (!f)
 282                return;
 283
 284        strbuf_getline_lf(&buf, f);
 285        fclose(f);
 286        strbuf_trim(&buf);
 287        if (!buf.len) {
 288                strbuf_release(&buf);
 289                return;
 290        }
 291
 292        remote->origin = REMOTE_BRANCHES;
 293
 294        /*
 295         * The branches file would have URL and optionally
 296         * #branch specified.  The "master" (or specified) branch is
 297         * fetched and stored in the local branch matching the
 298         * remote name.
 299         */
 300        frag = strchr(buf.buf, '#');
 301        if (frag)
 302                *(frag++) = '\0';
 303        else
 304                frag = "master";
 305
 306        add_url_alias(remote, strbuf_detach(&buf, NULL));
 307        add_fetch_refspec(remote, xstrfmt("refs/heads/%s:refs/heads/%s",
 308                                          frag, remote->name));
 309
 310        /*
 311         * Cogito compatible push: push current HEAD to remote #branch
 312         * (master if missing)
 313         */
 314        add_push_refspec(remote, xstrfmt("HEAD:refs/heads/%s", frag));
 315        remote->fetch_tags = 1; /* always auto-follow */
 316}
 317
 318static int handle_config(const char *key, const char *value, void *cb)
 319{
 320        const char *name;
 321        int namelen;
 322        const char *subkey;
 323        struct remote *remote;
 324        struct branch *branch;
 325        if (parse_config_key(key, "branch", &name, &namelen, &subkey) >= 0) {
 326                if (!name)
 327                        return 0;
 328                branch = make_branch(name, namelen);
 329                if (!strcmp(subkey, "remote")) {
 330                        return git_config_string(&branch->remote_name, key, value);
 331                } else if (!strcmp(subkey, "pushremote")) {
 332                        return git_config_string(&branch->pushremote_name, key, value);
 333                } else if (!strcmp(subkey, "merge")) {
 334                        if (!value)
 335                                return config_error_nonbool(key);
 336                        add_merge(branch, xstrdup(value));
 337                }
 338                return 0;
 339        }
 340        if (parse_config_key(key, "url", &name, &namelen, &subkey) >= 0) {
 341                struct rewrite *rewrite;
 342                if (!name)
 343                        return 0;
 344                if (!strcmp(subkey, "insteadof")) {
 345                        rewrite = make_rewrite(&rewrites, name, namelen);
 346                        if (!value)
 347                                return config_error_nonbool(key);
 348                        add_instead_of(rewrite, xstrdup(value));
 349                } else if (!strcmp(subkey, "pushinsteadof")) {
 350                        rewrite = make_rewrite(&rewrites_push, name, namelen);
 351                        if (!value)
 352                                return config_error_nonbool(key);
 353                        add_instead_of(rewrite, xstrdup(value));
 354                }
 355        }
 356
 357        if (parse_config_key(key, "remote", &name, &namelen, &subkey) < 0)
 358                return 0;
 359
 360        /* Handle remote.* variables */
 361        if (!name && !strcmp(subkey, "pushdefault"))
 362                return git_config_string(&pushremote_name, key, value);
 363
 364        if (!name)
 365                return 0;
 366        /* Handle remote.<name>.* variables */
 367        if (*name == '/') {
 368                warning("Config remote shorthand cannot begin with '/': %s",
 369                        name);
 370                return 0;
 371        }
 372        remote = make_remote(name, namelen);
 373        remote->origin = REMOTE_CONFIG;
 374        if (!strcmp(subkey, "mirror"))
 375                remote->mirror = git_config_bool(key, value);
 376        else if (!strcmp(subkey, "skipdefaultupdate"))
 377                remote->skip_default_update = git_config_bool(key, value);
 378        else if (!strcmp(subkey, "skipfetchall"))
 379                remote->skip_default_update = git_config_bool(key, value);
 380        else if (!strcmp(subkey, "prune"))
 381                remote->prune = git_config_bool(key, value);
 382        else if (!strcmp(subkey, "url")) {
 383                const char *v;
 384                if (git_config_string(&v, key, value))
 385                        return -1;
 386                add_url(remote, v);
 387        } else if (!strcmp(subkey, "pushurl")) {
 388                const char *v;
 389                if (git_config_string(&v, key, value))
 390                        return -1;
 391                add_pushurl(remote, v);
 392        } else if (!strcmp(subkey, "push")) {
 393                const char *v;
 394                if (git_config_string(&v, key, value))
 395                        return -1;
 396                add_push_refspec(remote, v);
 397        } else if (!strcmp(subkey, "fetch")) {
 398                const char *v;
 399                if (git_config_string(&v, key, value))
 400                        return -1;
 401                add_fetch_refspec(remote, v);
 402        } else if (!strcmp(subkey, "receivepack")) {
 403                const char *v;
 404                if (git_config_string(&v, key, value))
 405                        return -1;
 406                if (!remote->receivepack)
 407                        remote->receivepack = v;
 408                else
 409                        error("more than one receivepack given, using the first");
 410        } else if (!strcmp(subkey, "uploadpack")) {
 411                const char *v;
 412                if (git_config_string(&v, key, value))
 413                        return -1;
 414                if (!remote->uploadpack)
 415                        remote->uploadpack = v;
 416                else
 417                        error("more than one uploadpack given, using the first");
 418        } else if (!strcmp(subkey, "tagopt")) {
 419                if (!strcmp(value, "--no-tags"))
 420                        remote->fetch_tags = -1;
 421                else if (!strcmp(value, "--tags"))
 422                        remote->fetch_tags = 2;
 423        } else if (!strcmp(subkey, "proxy")) {
 424                return git_config_string((const char **)&remote->http_proxy,
 425                                         key, value);
 426        } else if (!strcmp(subkey, "proxyauthmethod")) {
 427                return git_config_string((const char **)&remote->http_proxy_authmethod,
 428                                         key, value);
 429        } else if (!strcmp(subkey, "vcs")) {
 430                return git_config_string(&remote->foreign_vcs, key, value);
 431        }
 432        return 0;
 433}
 434
 435static void alias_all_urls(void)
 436{
 437        int i, j;
 438        for (i = 0; i < remotes_nr; i++) {
 439                int add_pushurl_aliases;
 440                if (!remotes[i])
 441                        continue;
 442                for (j = 0; j < remotes[i]->pushurl_nr; j++) {
 443                        remotes[i]->pushurl[j] = alias_url(remotes[i]->pushurl[j], &rewrites);
 444                }
 445                add_pushurl_aliases = remotes[i]->pushurl_nr == 0;
 446                for (j = 0; j < remotes[i]->url_nr; j++) {
 447                        if (add_pushurl_aliases)
 448                                add_pushurl_alias(remotes[i], remotes[i]->url[j]);
 449                        remotes[i]->url[j] = alias_url(remotes[i]->url[j], &rewrites);
 450                }
 451        }
 452}
 453
 454static void read_config(void)
 455{
 456        static int loaded;
 457        struct object_id oid;
 458        int flag;
 459
 460        if (loaded)
 461                return;
 462        loaded = 1;
 463
 464        current_branch = NULL;
 465        if (startup_info->have_repository) {
 466                const char *head_ref = resolve_ref_unsafe("HEAD", 0, oid.hash, &flag);
 467                if (head_ref && (flag & REF_ISSYMREF) &&
 468                    skip_prefix(head_ref, "refs/heads/", &head_ref)) {
 469                        current_branch = make_branch(head_ref, 0);
 470                }
 471        }
 472        git_config(handle_config, NULL);
 473        alias_all_urls();
 474}
 475
 476/*
 477 * This function frees a refspec array.
 478 * Warning: code paths should be checked to ensure that the src
 479 *          and dst pointers are always freeable pointers as well
 480 *          as the refspec pointer itself.
 481 */
 482static void free_refspecs(struct refspec *refspec, int nr_refspec)
 483{
 484        int i;
 485
 486        if (!refspec)
 487                return;
 488
 489        for (i = 0; i < nr_refspec; i++) {
 490                free(refspec[i].src);
 491                free(refspec[i].dst);
 492        }
 493        free(refspec);
 494}
 495
 496static struct refspec *parse_refspec_internal(int nr_refspec, const char **refspec, int fetch, int verify)
 497{
 498        int i;
 499        struct refspec *rs = xcalloc(nr_refspec, sizeof(*rs));
 500
 501        for (i = 0; i < nr_refspec; i++) {
 502                size_t llen;
 503                int is_glob;
 504                const char *lhs, *rhs;
 505                int flags;
 506
 507                is_glob = 0;
 508
 509                lhs = refspec[i];
 510                if (*lhs == '+') {
 511                        rs[i].force = 1;
 512                        lhs++;
 513                }
 514
 515                rhs = strrchr(lhs, ':');
 516
 517                /*
 518                 * Before going on, special case ":" (or "+:") as a refspec
 519                 * for pushing matching refs.
 520                 */
 521                if (!fetch && rhs == lhs && rhs[1] == '\0') {
 522                        rs[i].matching = 1;
 523                        continue;
 524                }
 525
 526                if (rhs) {
 527                        size_t rlen = strlen(++rhs);
 528                        is_glob = (1 <= rlen && strchr(rhs, '*'));
 529                        rs[i].dst = xstrndup(rhs, rlen);
 530                }
 531
 532                llen = (rhs ? (rhs - lhs - 1) : strlen(lhs));
 533                if (1 <= llen && memchr(lhs, '*', llen)) {
 534                        if ((rhs && !is_glob) || (!rhs && fetch))
 535                                goto invalid;
 536                        is_glob = 1;
 537                } else if (rhs && is_glob) {
 538                        goto invalid;
 539                }
 540
 541                rs[i].pattern = is_glob;
 542                rs[i].src = xstrndup(lhs, llen);
 543                flags = REFNAME_ALLOW_ONELEVEL | (is_glob ? REFNAME_REFSPEC_PATTERN : 0);
 544
 545                if (fetch) {
 546                        struct object_id unused;
 547
 548                        /* LHS */
 549                        if (!*rs[i].src)
 550                                ; /* empty is ok; it means "HEAD" */
 551                        else if (llen == GIT_SHA1_HEXSZ && !get_oid_hex(rs[i].src, &unused))
 552                                rs[i].exact_sha1 = 1; /* ok */
 553                        else if (!check_refname_format(rs[i].src, flags))
 554                                ; /* valid looking ref is ok */
 555                        else
 556                                goto invalid;
 557                        /* RHS */
 558                        if (!rs[i].dst)
 559                                ; /* missing is ok; it is the same as empty */
 560                        else if (!*rs[i].dst)
 561                                ; /* empty is ok; it means "do not store" */
 562                        else if (!check_refname_format(rs[i].dst, flags))
 563                                ; /* valid looking ref is ok */
 564                        else
 565                                goto invalid;
 566                } else {
 567                        /*
 568                         * LHS
 569                         * - empty is allowed; it means delete.
 570                         * - when wildcarded, it must be a valid looking ref.
 571                         * - otherwise, it must be an extended SHA-1, but
 572                         *   there is no existing way to validate this.
 573                         */
 574                        if (!*rs[i].src)
 575                                ; /* empty is ok */
 576                        else if (is_glob) {
 577                                if (check_refname_format(rs[i].src, flags))
 578                                        goto invalid;
 579                        }
 580                        else
 581                                ; /* anything goes, for now */
 582                        /*
 583                         * RHS
 584                         * - missing is allowed, but LHS then must be a
 585                         *   valid looking ref.
 586                         * - empty is not allowed.
 587                         * - otherwise it must be a valid looking ref.
 588                         */
 589                        if (!rs[i].dst) {
 590                                if (check_refname_format(rs[i].src, flags))
 591                                        goto invalid;
 592                        } else if (!*rs[i].dst) {
 593                                goto invalid;
 594                        } else {
 595                                if (check_refname_format(rs[i].dst, flags))
 596                                        goto invalid;
 597                        }
 598                }
 599        }
 600        return rs;
 601
 602 invalid:
 603        if (verify) {
 604                /*
 605                 * nr_refspec must be greater than zero and i must be valid
 606                 * since it is only possible to reach this point from within
 607                 * the for loop above.
 608                 */
 609                free_refspecs(rs, i+1);
 610                return NULL;
 611        }
 612        die("Invalid refspec '%s'", refspec[i]);
 613}
 614
 615int valid_fetch_refspec(const char *fetch_refspec_str)
 616{
 617        struct refspec *refspec;
 618
 619        refspec = parse_refspec_internal(1, &fetch_refspec_str, 1, 1);
 620        free_refspecs(refspec, 1);
 621        return !!refspec;
 622}
 623
 624struct refspec *parse_fetch_refspec(int nr_refspec, const char **refspec)
 625{
 626        return parse_refspec_internal(nr_refspec, refspec, 1, 0);
 627}
 628
 629static struct refspec *parse_push_refspec(int nr_refspec, const char **refspec)
 630{
 631        return parse_refspec_internal(nr_refspec, refspec, 0, 0);
 632}
 633
 634void free_refspec(int nr_refspec, struct refspec *refspec)
 635{
 636        int i;
 637        for (i = 0; i < nr_refspec; i++) {
 638                free(refspec[i].src);
 639                free(refspec[i].dst);
 640        }
 641        free(refspec);
 642}
 643
 644static int valid_remote_nick(const char *name)
 645{
 646        if (!name[0] || is_dot_or_dotdot(name))
 647                return 0;
 648
 649        /* remote nicknames cannot contain slashes */
 650        while (*name)
 651                if (is_dir_sep(*name++))
 652                        return 0;
 653        return 1;
 654}
 655
 656const char *remote_for_branch(struct branch *branch, int *explicit)
 657{
 658        if (branch && branch->remote_name) {
 659                if (explicit)
 660                        *explicit = 1;
 661                return branch->remote_name;
 662        }
 663        if (explicit)
 664                *explicit = 0;
 665        return "origin";
 666}
 667
 668const char *pushremote_for_branch(struct branch *branch, int *explicit)
 669{
 670        if (branch && branch->pushremote_name) {
 671                if (explicit)
 672                        *explicit = 1;
 673                return branch->pushremote_name;
 674        }
 675        if (pushremote_name) {
 676                if (explicit)
 677                        *explicit = 1;
 678                return pushremote_name;
 679        }
 680        return remote_for_branch(branch, explicit);
 681}
 682
 683static struct remote *remote_get_1(const char *name,
 684                                   const char *(*get_default)(struct branch *, int *))
 685{
 686        struct remote *ret;
 687        int name_given = 0;
 688
 689        read_config();
 690
 691        if (name)
 692                name_given = 1;
 693        else
 694                name = get_default(current_branch, &name_given);
 695
 696        ret = make_remote(name, 0);
 697        if (valid_remote_nick(name)) {
 698                if (!valid_remote(ret))
 699                        read_remotes_file(ret);
 700                if (!valid_remote(ret))
 701                        read_branches_file(ret);
 702        }
 703        if (name_given && !valid_remote(ret))
 704                add_url_alias(ret, name);
 705        if (!valid_remote(ret))
 706                return NULL;
 707        ret->fetch = parse_fetch_refspec(ret->fetch_refspec_nr, ret->fetch_refspec);
 708        ret->push = parse_push_refspec(ret->push_refspec_nr, ret->push_refspec);
 709        return ret;
 710}
 711
 712struct remote *remote_get(const char *name)
 713{
 714        return remote_get_1(name, remote_for_branch);
 715}
 716
 717struct remote *pushremote_get(const char *name)
 718{
 719        return remote_get_1(name, pushremote_for_branch);
 720}
 721
 722int remote_is_configured(struct remote *remote)
 723{
 724        return remote && remote->origin;
 725}
 726
 727int for_each_remote(each_remote_fn fn, void *priv)
 728{
 729        int i, result = 0;
 730        read_config();
 731        for (i = 0; i < remotes_nr && !result; i++) {
 732                struct remote *r = remotes[i];
 733                if (!r)
 734                        continue;
 735                if (!r->fetch)
 736                        r->fetch = parse_fetch_refspec(r->fetch_refspec_nr,
 737                                                       r->fetch_refspec);
 738                if (!r->push)
 739                        r->push = parse_push_refspec(r->push_refspec_nr,
 740                                                     r->push_refspec);
 741                result = fn(r, priv);
 742        }
 743        return result;
 744}
 745
 746static void handle_duplicate(struct ref *ref1, struct ref *ref2)
 747{
 748        if (strcmp(ref1->name, ref2->name)) {
 749                if (ref1->fetch_head_status != FETCH_HEAD_IGNORE &&
 750                    ref2->fetch_head_status != FETCH_HEAD_IGNORE) {
 751                        die(_("Cannot fetch both %s and %s to %s"),
 752                            ref1->name, ref2->name, ref2->peer_ref->name);
 753                } else if (ref1->fetch_head_status != FETCH_HEAD_IGNORE &&
 754                           ref2->fetch_head_status == FETCH_HEAD_IGNORE) {
 755                        warning(_("%s usually tracks %s, not %s"),
 756                                ref2->peer_ref->name, ref2->name, ref1->name);
 757                } else if (ref1->fetch_head_status == FETCH_HEAD_IGNORE &&
 758                           ref2->fetch_head_status == FETCH_HEAD_IGNORE) {
 759                        die(_("%s tracks both %s and %s"),
 760                            ref2->peer_ref->name, ref1->name, ref2->name);
 761                } else {
 762                        /*
 763                         * This last possibility doesn't occur because
 764                         * FETCH_HEAD_IGNORE entries always appear at
 765                         * the end of the list.
 766                         */
 767                        die(_("Internal error"));
 768                }
 769        }
 770        free(ref2->peer_ref);
 771        free(ref2);
 772}
 773
 774struct ref *ref_remove_duplicates(struct ref *ref_map)
 775{
 776        struct string_list refs = STRING_LIST_INIT_NODUP;
 777        struct ref *retval = NULL;
 778        struct ref **p = &retval;
 779
 780        while (ref_map) {
 781                struct ref *ref = ref_map;
 782
 783                ref_map = ref_map->next;
 784                ref->next = NULL;
 785
 786                if (!ref->peer_ref) {
 787                        *p = ref;
 788                        p = &ref->next;
 789                } else {
 790                        struct string_list_item *item =
 791                                string_list_insert(&refs, ref->peer_ref->name);
 792
 793                        if (item->util) {
 794                                /* Entry already existed */
 795                                handle_duplicate((struct ref *)item->util, ref);
 796                        } else {
 797                                *p = ref;
 798                                p = &ref->next;
 799                                item->util = ref;
 800                        }
 801                }
 802        }
 803
 804        string_list_clear(&refs, 0);
 805        return retval;
 806}
 807
 808int remote_has_url(struct remote *remote, const char *url)
 809{
 810        int i;
 811        for (i = 0; i < remote->url_nr; i++) {
 812                if (!strcmp(remote->url[i], url))
 813                        return 1;
 814        }
 815        return 0;
 816}
 817
 818static int match_name_with_pattern(const char *key, const char *name,
 819                                   const char *value, char **result)
 820{
 821        const char *kstar = strchr(key, '*');
 822        size_t klen;
 823        size_t ksuffixlen;
 824        size_t namelen;
 825        int ret;
 826        if (!kstar)
 827                die("Key '%s' of pattern had no '*'", key);
 828        klen = kstar - key;
 829        ksuffixlen = strlen(kstar + 1);
 830        namelen = strlen(name);
 831        ret = !strncmp(name, key, klen) && namelen >= klen + ksuffixlen &&
 832                !memcmp(name + namelen - ksuffixlen, kstar + 1, ksuffixlen);
 833        if (ret && value) {
 834                struct strbuf sb = STRBUF_INIT;
 835                const char *vstar = strchr(value, '*');
 836                if (!vstar)
 837                        die("Value '%s' of pattern has no '*'", value);
 838                strbuf_add(&sb, value, vstar - value);
 839                strbuf_add(&sb, name + klen, namelen - klen - ksuffixlen);
 840                strbuf_addstr(&sb, vstar + 1);
 841                *result = strbuf_detach(&sb, NULL);
 842        }
 843        return ret;
 844}
 845
 846static void query_refspecs_multiple(struct refspec *refs, int ref_count, struct refspec *query, struct string_list *results)
 847{
 848        int i;
 849        int find_src = !query->src;
 850
 851        if (find_src && !query->dst)
 852                error("query_refspecs_multiple: need either src or dst");
 853
 854        for (i = 0; i < ref_count; i++) {
 855                struct refspec *refspec = &refs[i];
 856                const char *key = find_src ? refspec->dst : refspec->src;
 857                const char *value = find_src ? refspec->src : refspec->dst;
 858                const char *needle = find_src ? query->dst : query->src;
 859                char **result = find_src ? &query->src : &query->dst;
 860
 861                if (!refspec->dst)
 862                        continue;
 863                if (refspec->pattern) {
 864                        if (match_name_with_pattern(key, needle, value, result))
 865                                string_list_append_nodup(results, *result);
 866                } else if (!strcmp(needle, key)) {
 867                        string_list_append(results, value);
 868                }
 869        }
 870}
 871
 872int query_refspecs(struct refspec *refs, int ref_count, struct refspec *query)
 873{
 874        int i;
 875        int find_src = !query->src;
 876        const char *needle = find_src ? query->dst : query->src;
 877        char **result = find_src ? &query->src : &query->dst;
 878
 879        if (find_src && !query->dst)
 880                return error("query_refspecs: need either src or dst");
 881
 882        for (i = 0; i < ref_count; i++) {
 883                struct refspec *refspec = &refs[i];
 884                const char *key = find_src ? refspec->dst : refspec->src;
 885                const char *value = find_src ? refspec->src : refspec->dst;
 886
 887                if (!refspec->dst)
 888                        continue;
 889                if (refspec->pattern) {
 890                        if (match_name_with_pattern(key, needle, value, result)) {
 891                                query->force = refspec->force;
 892                                return 0;
 893                        }
 894                } else if (!strcmp(needle, key)) {
 895                        *result = xstrdup(value);
 896                        query->force = refspec->force;
 897                        return 0;
 898                }
 899        }
 900        return -1;
 901}
 902
 903char *apply_refspecs(struct refspec *refspecs, int nr_refspec,
 904                     const char *name)
 905{
 906        struct refspec query;
 907
 908        memset(&query, 0, sizeof(struct refspec));
 909        query.src = (char *)name;
 910
 911        if (query_refspecs(refspecs, nr_refspec, &query))
 912                return NULL;
 913
 914        return query.dst;
 915}
 916
 917int remote_find_tracking(struct remote *remote, struct refspec *refspec)
 918{
 919        return query_refspecs(remote->fetch, remote->fetch_refspec_nr, refspec);
 920}
 921
 922static struct ref *alloc_ref_with_prefix(const char *prefix, size_t prefixlen,
 923                const char *name)
 924{
 925        size_t len = strlen(name);
 926        struct ref *ref = xcalloc(1, st_add4(sizeof(*ref), prefixlen, len, 1));
 927        memcpy(ref->name, prefix, prefixlen);
 928        memcpy(ref->name + prefixlen, name, len);
 929        return ref;
 930}
 931
 932struct ref *alloc_ref(const char *name)
 933{
 934        return alloc_ref_with_prefix("", 0, name);
 935}
 936
 937struct ref *copy_ref(const struct ref *ref)
 938{
 939        struct ref *cpy;
 940        size_t len;
 941        if (!ref)
 942                return NULL;
 943        len = st_add3(sizeof(struct ref), strlen(ref->name), 1);
 944        cpy = xmalloc(len);
 945        memcpy(cpy, ref, len);
 946        cpy->next = NULL;
 947        cpy->symref = xstrdup_or_null(ref->symref);
 948        cpy->remote_status = xstrdup_or_null(ref->remote_status);
 949        cpy->peer_ref = copy_ref(ref->peer_ref);
 950        return cpy;
 951}
 952
 953struct ref *copy_ref_list(const struct ref *ref)
 954{
 955        struct ref *ret = NULL;
 956        struct ref **tail = &ret;
 957        while (ref) {
 958                *tail = copy_ref(ref);
 959                ref = ref->next;
 960                tail = &((*tail)->next);
 961        }
 962        return ret;
 963}
 964
 965static void free_ref(struct ref *ref)
 966{
 967        if (!ref)
 968                return;
 969        free_ref(ref->peer_ref);
 970        free(ref->remote_status);
 971        free(ref->symref);
 972        free(ref);
 973}
 974
 975void free_refs(struct ref *ref)
 976{
 977        struct ref *next;
 978        while (ref) {
 979                next = ref->next;
 980                free_ref(ref);
 981                ref = next;
 982        }
 983}
 984
 985int ref_compare_name(const void *va, const void *vb)
 986{
 987        const struct ref *a = va, *b = vb;
 988        return strcmp(a->name, b->name);
 989}
 990
 991static void *ref_list_get_next(const void *a)
 992{
 993        return ((const struct ref *)a)->next;
 994}
 995
 996static void ref_list_set_next(void *a, void *next)
 997{
 998        ((struct ref *)a)->next = next;
 999}
1000
1001void sort_ref_list(struct ref **l, int (*cmp)(const void *, const void *))
1002{
1003        *l = llist_mergesort(*l, ref_list_get_next, ref_list_set_next, cmp);
1004}
1005
1006int count_refspec_match(const char *pattern,
1007                        struct ref *refs,
1008                        struct ref **matched_ref)
1009{
1010        int patlen = strlen(pattern);
1011        struct ref *matched_weak = NULL;
1012        struct ref *matched = NULL;
1013        int weak_match = 0;
1014        int match = 0;
1015
1016        for (weak_match = match = 0; refs; refs = refs->next) {
1017                char *name = refs->name;
1018                int namelen = strlen(name);
1019
1020                if (!refname_match(pattern, name))
1021                        continue;
1022
1023                /* A match is "weak" if it is with refs outside
1024                 * heads or tags, and did not specify the pattern
1025                 * in full (e.g. "refs/remotes/origin/master") or at
1026                 * least from the toplevel (e.g. "remotes/origin/master");
1027                 * otherwise "git push $URL master" would result in
1028                 * ambiguity between remotes/origin/master and heads/master
1029                 * at the remote site.
1030                 */
1031                if (namelen != patlen &&
1032                    patlen != namelen - 5 &&
1033                    !starts_with(name, "refs/heads/") &&
1034                    !starts_with(name, "refs/tags/")) {
1035                        /* We want to catch the case where only weak
1036                         * matches are found and there are multiple
1037                         * matches, and where more than one strong
1038                         * matches are found, as ambiguous.  One
1039                         * strong match with zero or more weak matches
1040                         * are acceptable as a unique match.
1041                         */
1042                        matched_weak = refs;
1043                        weak_match++;
1044                }
1045                else {
1046                        matched = refs;
1047                        match++;
1048                }
1049        }
1050        if (!matched) {
1051                if (matched_ref)
1052                        *matched_ref = matched_weak;
1053                return weak_match;
1054        }
1055        else {
1056                if (matched_ref)
1057                        *matched_ref = matched;
1058                return match;
1059        }
1060}
1061
1062static void tail_link_ref(struct ref *ref, struct ref ***tail)
1063{
1064        **tail = ref;
1065        while (ref->next)
1066                ref = ref->next;
1067        *tail = &ref->next;
1068}
1069
1070static struct ref *alloc_delete_ref(void)
1071{
1072        struct ref *ref = alloc_ref("(delete)");
1073        oidclr(&ref->new_oid);
1074        return ref;
1075}
1076
1077static int try_explicit_object_name(const char *name,
1078                                    struct ref **match)
1079{
1080        struct object_id oid;
1081
1082        if (!*name) {
1083                if (match)
1084                        *match = alloc_delete_ref();
1085                return 0;
1086        }
1087
1088        if (get_sha1(name, oid.hash))
1089                return -1;
1090
1091        if (match) {
1092                *match = alloc_ref(name);
1093                oidcpy(&(*match)->new_oid, &oid);
1094        }
1095        return 0;
1096}
1097
1098static struct ref *make_linked_ref(const char *name, struct ref ***tail)
1099{
1100        struct ref *ret = alloc_ref(name);
1101        tail_link_ref(ret, tail);
1102        return ret;
1103}
1104
1105static char *guess_ref(const char *name, struct ref *peer)
1106{
1107        struct strbuf buf = STRBUF_INIT;
1108        struct object_id oid;
1109
1110        const char *r = resolve_ref_unsafe(peer->name, RESOLVE_REF_READING,
1111                                           oid.hash, NULL);
1112        if (!r)
1113                return NULL;
1114
1115        if (starts_with(r, "refs/heads/"))
1116                strbuf_addstr(&buf, "refs/heads/");
1117        else if (starts_with(r, "refs/tags/"))
1118                strbuf_addstr(&buf, "refs/tags/");
1119        else
1120                return NULL;
1121
1122        strbuf_addstr(&buf, name);
1123        return strbuf_detach(&buf, NULL);
1124}
1125
1126static int match_explicit_lhs(struct ref *src,
1127                              struct refspec *rs,
1128                              struct ref **match,
1129                              int *allocated_match)
1130{
1131        switch (count_refspec_match(rs->src, src, match)) {
1132        case 1:
1133                if (allocated_match)
1134                        *allocated_match = 0;
1135                return 0;
1136        case 0:
1137                /* The source could be in the get_sha1() format
1138                 * not a reference name.  :refs/other is a
1139                 * way to delete 'other' ref at the remote end.
1140                 */
1141                if (try_explicit_object_name(rs->src, match) < 0)
1142                        return error("src refspec %s does not match any.", rs->src);
1143                if (allocated_match)
1144                        *allocated_match = 1;
1145                return 0;
1146        default:
1147                return error("src refspec %s matches more than one.", rs->src);
1148        }
1149}
1150
1151static int match_explicit(struct ref *src, struct ref *dst,
1152                          struct ref ***dst_tail,
1153                          struct refspec *rs)
1154{
1155        struct ref *matched_src, *matched_dst;
1156        int allocated_src;
1157
1158        const char *dst_value = rs->dst;
1159        char *dst_guess;
1160
1161        if (rs->pattern || rs->matching)
1162                return 0;
1163
1164        matched_src = matched_dst = NULL;
1165        if (match_explicit_lhs(src, rs, &matched_src, &allocated_src) < 0)
1166                return -1;
1167
1168        if (!dst_value) {
1169                struct object_id oid;
1170                int flag;
1171
1172                dst_value = resolve_ref_unsafe(matched_src->name,
1173                                               RESOLVE_REF_READING,
1174                                               oid.hash, &flag);
1175                if (!dst_value ||
1176                    ((flag & REF_ISSYMREF) &&
1177                     !starts_with(dst_value, "refs/heads/")))
1178                        die("%s cannot be resolved to branch.",
1179                            matched_src->name);
1180        }
1181
1182        switch (count_refspec_match(dst_value, dst, &matched_dst)) {
1183        case 1:
1184                break;
1185        case 0:
1186                if (starts_with(dst_value, "refs/"))
1187                        matched_dst = make_linked_ref(dst_value, dst_tail);
1188                else if (is_null_oid(&matched_src->new_oid))
1189                        error("unable to delete '%s': remote ref does not exist",
1190                              dst_value);
1191                else if ((dst_guess = guess_ref(dst_value, matched_src)))
1192                        matched_dst = make_linked_ref(dst_guess, dst_tail);
1193                else
1194                        error("unable to push to unqualified destination: %s\n"
1195                              "The destination refspec neither matches an "
1196                              "existing ref on the remote nor\n"
1197                              "begins with refs/, and we are unable to "
1198                              "guess a prefix based on the source ref.",
1199                              dst_value);
1200                break;
1201        default:
1202                matched_dst = NULL;
1203                error("dst refspec %s matches more than one.",
1204                      dst_value);
1205                break;
1206        }
1207        if (!matched_dst)
1208                return -1;
1209        if (matched_dst->peer_ref)
1210                return error("dst ref %s receives from more than one src.",
1211                      matched_dst->name);
1212        else {
1213                matched_dst->peer_ref = allocated_src ?
1214                                        matched_src :
1215                                        copy_ref(matched_src);
1216                matched_dst->force = rs->force;
1217        }
1218        return 0;
1219}
1220
1221static int match_explicit_refs(struct ref *src, struct ref *dst,
1222                               struct ref ***dst_tail, struct refspec *rs,
1223                               int rs_nr)
1224{
1225        int i, errs;
1226        for (i = errs = 0; i < rs_nr; i++)
1227                errs += match_explicit(src, dst, dst_tail, &rs[i]);
1228        return errs;
1229}
1230
1231static char *get_ref_match(const struct refspec *rs, int rs_nr, const struct ref *ref,
1232                int send_mirror, int direction, const struct refspec **ret_pat)
1233{
1234        const struct refspec *pat;
1235        char *name;
1236        int i;
1237        int matching_refs = -1;
1238        for (i = 0; i < rs_nr; i++) {
1239                if (rs[i].matching &&
1240                    (matching_refs == -1 || rs[i].force)) {
1241                        matching_refs = i;
1242                        continue;
1243                }
1244
1245                if (rs[i].pattern) {
1246                        const char *dst_side = rs[i].dst ? rs[i].dst : rs[i].src;
1247                        int match;
1248                        if (direction == FROM_SRC)
1249                                match = match_name_with_pattern(rs[i].src, ref->name, dst_side, &name);
1250                        else
1251                                match = match_name_with_pattern(dst_side, ref->name, rs[i].src, &name);
1252                        if (match) {
1253                                matching_refs = i;
1254                                break;
1255                        }
1256                }
1257        }
1258        if (matching_refs == -1)
1259                return NULL;
1260
1261        pat = rs + matching_refs;
1262        if (pat->matching) {
1263                /*
1264                 * "matching refs"; traditionally we pushed everything
1265                 * including refs outside refs/heads/ hierarchy, but
1266                 * that does not make much sense these days.
1267                 */
1268                if (!send_mirror && !starts_with(ref->name, "refs/heads/"))
1269                        return NULL;
1270                name = xstrdup(ref->name);
1271        }
1272        if (ret_pat)
1273                *ret_pat = pat;
1274        return name;
1275}
1276
1277static struct ref **tail_ref(struct ref **head)
1278{
1279        struct ref **tail = head;
1280        while (*tail)
1281                tail = &((*tail)->next);
1282        return tail;
1283}
1284
1285struct tips {
1286        struct commit **tip;
1287        int nr, alloc;
1288};
1289
1290static void add_to_tips(struct tips *tips, const struct object_id *oid)
1291{
1292        struct commit *commit;
1293
1294        if (is_null_oid(oid))
1295                return;
1296        commit = lookup_commit_reference_gently(oid->hash, 1);
1297        if (!commit || (commit->object.flags & TMP_MARK))
1298                return;
1299        commit->object.flags |= TMP_MARK;
1300        ALLOC_GROW(tips->tip, tips->nr + 1, tips->alloc);
1301        tips->tip[tips->nr++] = commit;
1302}
1303
1304static void add_missing_tags(struct ref *src, struct ref **dst, struct ref ***dst_tail)
1305{
1306        struct string_list dst_tag = STRING_LIST_INIT_NODUP;
1307        struct string_list src_tag = STRING_LIST_INIT_NODUP;
1308        struct string_list_item *item;
1309        struct ref *ref;
1310        struct tips sent_tips;
1311
1312        /*
1313         * Collect everything we know they would have at the end of
1314         * this push, and collect all tags they have.
1315         */
1316        memset(&sent_tips, 0, sizeof(sent_tips));
1317        for (ref = *dst; ref; ref = ref->next) {
1318                if (ref->peer_ref &&
1319                    !is_null_oid(&ref->peer_ref->new_oid))
1320                        add_to_tips(&sent_tips, &ref->peer_ref->new_oid);
1321                else
1322                        add_to_tips(&sent_tips, &ref->old_oid);
1323                if (starts_with(ref->name, "refs/tags/"))
1324                        string_list_append(&dst_tag, ref->name);
1325        }
1326        clear_commit_marks_many(sent_tips.nr, sent_tips.tip, TMP_MARK);
1327
1328        string_list_sort(&dst_tag);
1329
1330        /* Collect tags they do not have. */
1331        for (ref = src; ref; ref = ref->next) {
1332                if (!starts_with(ref->name, "refs/tags/"))
1333                        continue; /* not a tag */
1334                if (string_list_has_string(&dst_tag, ref->name))
1335                        continue; /* they already have it */
1336                if (sha1_object_info(ref->new_oid.hash, NULL) != OBJ_TAG)
1337                        continue; /* be conservative */
1338                item = string_list_append(&src_tag, ref->name);
1339                item->util = ref;
1340        }
1341        string_list_clear(&dst_tag, 0);
1342
1343        /*
1344         * At this point, src_tag lists tags that are missing from
1345         * dst, and sent_tips lists the tips we are pushing or those
1346         * that we know they already have. An element in the src_tag
1347         * that is an ancestor of any of the sent_tips needs to be
1348         * sent to the other side.
1349         */
1350        if (sent_tips.nr) {
1351                for_each_string_list_item(item, &src_tag) {
1352                        struct ref *ref = item->util;
1353                        struct ref *dst_ref;
1354                        struct commit *commit;
1355
1356                        if (is_null_oid(&ref->new_oid))
1357                                continue;
1358                        commit = lookup_commit_reference_gently(ref->new_oid.hash, 1);
1359                        if (!commit)
1360                                /* not pushing a commit, which is not an error */
1361                                continue;
1362
1363                        /*
1364                         * Is this tag, which they do not have, reachable from
1365                         * any of the commits we are sending?
1366                         */
1367                        if (!in_merge_bases_many(commit, sent_tips.nr, sent_tips.tip))
1368                                continue;
1369
1370                        /* Add it in */
1371                        dst_ref = make_linked_ref(ref->name, dst_tail);
1372                        oidcpy(&dst_ref->new_oid, &ref->new_oid);
1373                        dst_ref->peer_ref = copy_ref(ref);
1374                }
1375        }
1376        string_list_clear(&src_tag, 0);
1377        free(sent_tips.tip);
1378}
1379
1380struct ref *find_ref_by_name(const struct ref *list, const char *name)
1381{
1382        for ( ; list; list = list->next)
1383                if (!strcmp(list->name, name))
1384                        return (struct ref *)list;
1385        return NULL;
1386}
1387
1388static void prepare_ref_index(struct string_list *ref_index, struct ref *ref)
1389{
1390        for ( ; ref; ref = ref->next)
1391                string_list_append_nodup(ref_index, ref->name)->util = ref;
1392
1393        string_list_sort(ref_index);
1394}
1395
1396/*
1397 * Given only the set of local refs, sanity-check the set of push
1398 * refspecs. We can't catch all errors that match_push_refs would,
1399 * but we can catch some errors early before even talking to the
1400 * remote side.
1401 */
1402int check_push_refs(struct ref *src, int nr_refspec, const char **refspec_names)
1403{
1404        struct refspec *refspec = parse_push_refspec(nr_refspec, refspec_names);
1405        int ret = 0;
1406        int i;
1407
1408        for (i = 0; i < nr_refspec; i++) {
1409                struct refspec *rs = refspec + i;
1410
1411                if (rs->pattern || rs->matching)
1412                        continue;
1413
1414                ret |= match_explicit_lhs(src, rs, NULL, NULL);
1415        }
1416
1417        free_refspec(nr_refspec, refspec);
1418        return ret;
1419}
1420
1421/*
1422 * Given the set of refs the local repository has, the set of refs the
1423 * remote repository has, and the refspec used for push, determine
1424 * what remote refs we will update and with what value by setting
1425 * peer_ref (which object is being pushed) and force (if the push is
1426 * forced) in elements of "dst". The function may add new elements to
1427 * dst (e.g. pushing to a new branch, done in match_explicit_refs).
1428 */
1429int match_push_refs(struct ref *src, struct ref **dst,
1430                    int nr_refspec, const char **refspec, int flags)
1431{
1432        struct refspec *rs;
1433        int send_all = flags & MATCH_REFS_ALL;
1434        int send_mirror = flags & MATCH_REFS_MIRROR;
1435        int send_prune = flags & MATCH_REFS_PRUNE;
1436        int errs;
1437        static const char *default_refspec[] = { ":", NULL };
1438        struct ref *ref, **dst_tail = tail_ref(dst);
1439        struct string_list dst_ref_index = STRING_LIST_INIT_NODUP;
1440
1441        if (!nr_refspec) {
1442                nr_refspec = 1;
1443                refspec = default_refspec;
1444        }
1445        rs = parse_push_refspec(nr_refspec, (const char **) refspec);
1446        errs = match_explicit_refs(src, *dst, &dst_tail, rs, nr_refspec);
1447
1448        /* pick the remainder */
1449        for (ref = src; ref; ref = ref->next) {
1450                struct string_list_item *dst_item;
1451                struct ref *dst_peer;
1452                const struct refspec *pat = NULL;
1453                char *dst_name;
1454
1455                dst_name = get_ref_match(rs, nr_refspec, ref, send_mirror, FROM_SRC, &pat);
1456                if (!dst_name)
1457                        continue;
1458
1459                if (!dst_ref_index.nr)
1460                        prepare_ref_index(&dst_ref_index, *dst);
1461
1462                dst_item = string_list_lookup(&dst_ref_index, dst_name);
1463                dst_peer = dst_item ? dst_item->util : NULL;
1464                if (dst_peer) {
1465                        if (dst_peer->peer_ref)
1466                                /* We're already sending something to this ref. */
1467                                goto free_name;
1468                } else {
1469                        if (pat->matching && !(send_all || send_mirror))
1470                                /*
1471                                 * Remote doesn't have it, and we have no
1472                                 * explicit pattern, and we don't have
1473                                 * --all or --mirror.
1474                                 */
1475                                goto free_name;
1476
1477                        /* Create a new one and link it */
1478                        dst_peer = make_linked_ref(dst_name, &dst_tail);
1479                        oidcpy(&dst_peer->new_oid, &ref->new_oid);
1480                        string_list_insert(&dst_ref_index,
1481                                dst_peer->name)->util = dst_peer;
1482                }
1483                dst_peer->peer_ref = copy_ref(ref);
1484                dst_peer->force = pat->force;
1485        free_name:
1486                free(dst_name);
1487        }
1488
1489        string_list_clear(&dst_ref_index, 0);
1490
1491        if (flags & MATCH_REFS_FOLLOW_TAGS)
1492                add_missing_tags(src, dst, &dst_tail);
1493
1494        if (send_prune) {
1495                struct string_list src_ref_index = STRING_LIST_INIT_NODUP;
1496                /* check for missing refs on the remote */
1497                for (ref = *dst; ref; ref = ref->next) {
1498                        char *src_name;
1499
1500                        if (ref->peer_ref)
1501                                /* We're already sending something to this ref. */
1502                                continue;
1503
1504                        src_name = get_ref_match(rs, nr_refspec, ref, send_mirror, FROM_DST, NULL);
1505                        if (src_name) {
1506                                if (!src_ref_index.nr)
1507                                        prepare_ref_index(&src_ref_index, src);
1508                                if (!string_list_has_string(&src_ref_index,
1509                                            src_name))
1510                                        ref->peer_ref = alloc_delete_ref();
1511                                free(src_name);
1512                        }
1513                }
1514                string_list_clear(&src_ref_index, 0);
1515        }
1516        if (errs)
1517                return -1;
1518        return 0;
1519}
1520
1521void set_ref_status_for_push(struct ref *remote_refs, int send_mirror,
1522                             int force_update)
1523{
1524        struct ref *ref;
1525
1526        for (ref = remote_refs; ref; ref = ref->next) {
1527                int force_ref_update = ref->force || force_update;
1528                int reject_reason = 0;
1529
1530                if (ref->peer_ref)
1531                        oidcpy(&ref->new_oid, &ref->peer_ref->new_oid);
1532                else if (!send_mirror)
1533                        continue;
1534
1535                ref->deletion = is_null_oid(&ref->new_oid);
1536                if (!ref->deletion &&
1537                        !oidcmp(&ref->old_oid, &ref->new_oid)) {
1538                        ref->status = REF_STATUS_UPTODATE;
1539                        continue;
1540                }
1541
1542                /*
1543                 * If the remote ref has moved and is now different
1544                 * from what we expect, reject any push.
1545                 *
1546                 * It also is an error if the user told us to check
1547                 * with the remote-tracking branch to find the value
1548                 * to expect, but we did not have such a tracking
1549                 * branch.
1550                 */
1551                if (ref->expect_old_sha1) {
1552                        if (oidcmp(&ref->old_oid, &ref->old_oid_expect))
1553                                reject_reason = REF_STATUS_REJECT_STALE;
1554                        else
1555                                /* If the ref isn't stale then force the update. */
1556                                force_ref_update = 1;
1557                }
1558
1559                /*
1560                 * If the update isn't already rejected then check
1561                 * the usual "must fast-forward" rules.
1562                 *
1563                 * Decide whether an individual refspec A:B can be
1564                 * pushed.  The push will succeed if any of the
1565                 * following are true:
1566                 *
1567                 * (1) the remote reference B does not exist
1568                 *
1569                 * (2) the remote reference B is being removed (i.e.,
1570                 *     pushing :B where no source is specified)
1571                 *
1572                 * (3) the destination is not under refs/tags/, and
1573                 *     if the old and new value is a commit, the new
1574                 *     is a descendant of the old.
1575                 *
1576                 * (4) it is forced using the +A:B notation, or by
1577                 *     passing the --force argument
1578                 */
1579
1580                if (!reject_reason && !ref->deletion && !is_null_oid(&ref->old_oid)) {
1581                        if (starts_with(ref->name, "refs/tags/"))
1582                                reject_reason = REF_STATUS_REJECT_ALREADY_EXISTS;
1583                        else if (!has_object_file(&ref->old_oid))
1584                                reject_reason = REF_STATUS_REJECT_FETCH_FIRST;
1585                        else if (!lookup_commit_reference_gently(ref->old_oid.hash, 1) ||
1586                                 !lookup_commit_reference_gently(ref->new_oid.hash, 1))
1587                                reject_reason = REF_STATUS_REJECT_NEEDS_FORCE;
1588                        else if (!ref_newer(&ref->new_oid, &ref->old_oid))
1589                                reject_reason = REF_STATUS_REJECT_NONFASTFORWARD;
1590                }
1591
1592                /*
1593                 * "--force" will defeat any rejection implemented
1594                 * by the rules above.
1595                 */
1596                if (!force_ref_update)
1597                        ref->status = reject_reason;
1598                else if (reject_reason)
1599                        ref->forced_update = 1;
1600        }
1601}
1602
1603static void set_merge(struct branch *ret)
1604{
1605        struct remote *remote;
1606        char *ref;
1607        struct object_id oid;
1608        int i;
1609
1610        if (!ret)
1611                return; /* no branch */
1612        if (ret->merge)
1613                return; /* already run */
1614        if (!ret->remote_name || !ret->merge_nr) {
1615                /*
1616                 * no merge config; let's make sure we don't confuse callers
1617                 * with a non-zero merge_nr but a NULL merge
1618                 */
1619                ret->merge_nr = 0;
1620                return;
1621        }
1622
1623        remote = remote_get(ret->remote_name);
1624
1625        ret->merge = xcalloc(ret->merge_nr, sizeof(*ret->merge));
1626        for (i = 0; i < ret->merge_nr; i++) {
1627                ret->merge[i] = xcalloc(1, sizeof(**ret->merge));
1628                ret->merge[i]->src = xstrdup(ret->merge_name[i]);
1629                if (!remote_find_tracking(remote, ret->merge[i]) ||
1630                    strcmp(ret->remote_name, "."))
1631                        continue;
1632                if (dwim_ref(ret->merge_name[i], strlen(ret->merge_name[i]),
1633                             oid.hash, &ref) == 1)
1634                        ret->merge[i]->dst = ref;
1635                else
1636                        ret->merge[i]->dst = xstrdup(ret->merge_name[i]);
1637        }
1638}
1639
1640struct branch *branch_get(const char *name)
1641{
1642        struct branch *ret;
1643
1644        read_config();
1645        if (!name || !*name || !strcmp(name, "HEAD"))
1646                ret = current_branch;
1647        else
1648                ret = make_branch(name, 0);
1649        set_merge(ret);
1650        return ret;
1651}
1652
1653int branch_has_merge_config(struct branch *branch)
1654{
1655        return branch && !!branch->merge;
1656}
1657
1658int branch_merge_matches(struct branch *branch,
1659                                 int i,
1660                                 const char *refname)
1661{
1662        if (!branch || i < 0 || i >= branch->merge_nr)
1663                return 0;
1664        return refname_match(branch->merge[i]->src, refname);
1665}
1666
1667__attribute__((format (printf,2,3)))
1668static const char *error_buf(struct strbuf *err, const char *fmt, ...)
1669{
1670        if (err) {
1671                va_list ap;
1672                va_start(ap, fmt);
1673                strbuf_vaddf(err, fmt, ap);
1674                va_end(ap);
1675        }
1676        return NULL;
1677}
1678
1679const char *branch_get_upstream(struct branch *branch, struct strbuf *err)
1680{
1681        if (!branch)
1682                return error_buf(err, _("HEAD does not point to a branch"));
1683
1684        if (!branch->merge || !branch->merge[0]) {
1685                /*
1686                 * no merge config; is it because the user didn't define any,
1687                 * or because it is not a real branch, and get_branch
1688                 * auto-vivified it?
1689                 */
1690                if (!ref_exists(branch->refname))
1691                        return error_buf(err, _("no such branch: '%s'"),
1692                                         branch->name);
1693                return error_buf(err,
1694                                 _("no upstream configured for branch '%s'"),
1695                                 branch->name);
1696        }
1697
1698        if (!branch->merge[0]->dst)
1699                return error_buf(err,
1700                                 _("upstream branch '%s' not stored as a remote-tracking branch"),
1701                                 branch->merge[0]->src);
1702
1703        return branch->merge[0]->dst;
1704}
1705
1706static const char *tracking_for_push_dest(struct remote *remote,
1707                                          const char *refname,
1708                                          struct strbuf *err)
1709{
1710        char *ret;
1711
1712        ret = apply_refspecs(remote->fetch, remote->fetch_refspec_nr, refname);
1713        if (!ret)
1714                return error_buf(err,
1715                                 _("push destination '%s' on remote '%s' has no local tracking branch"),
1716                                 refname, remote->name);
1717        return ret;
1718}
1719
1720static const char *branch_get_push_1(struct branch *branch, struct strbuf *err)
1721{
1722        struct remote *remote;
1723
1724        if (!branch)
1725                return error_buf(err, _("HEAD does not point to a branch"));
1726
1727        remote = remote_get(pushremote_for_branch(branch, NULL));
1728        if (!remote)
1729                return error_buf(err,
1730                                 _("branch '%s' has no remote for pushing"),
1731                                 branch->name);
1732
1733        if (remote->push_refspec_nr) {
1734                char *dst;
1735                const char *ret;
1736
1737                dst = apply_refspecs(remote->push, remote->push_refspec_nr,
1738                                     branch->refname);
1739                if (!dst)
1740                        return error_buf(err,
1741                                         _("push refspecs for '%s' do not include '%s'"),
1742                                         remote->name, branch->name);
1743
1744                ret = tracking_for_push_dest(remote, dst, err);
1745                free(dst);
1746                return ret;
1747        }
1748
1749        if (remote->mirror)
1750                return tracking_for_push_dest(remote, branch->refname, err);
1751
1752        switch (push_default) {
1753        case PUSH_DEFAULT_NOTHING:
1754                return error_buf(err, _("push has no destination (push.default is 'nothing')"));
1755
1756        case PUSH_DEFAULT_MATCHING:
1757        case PUSH_DEFAULT_CURRENT:
1758                return tracking_for_push_dest(remote, branch->refname, err);
1759
1760        case PUSH_DEFAULT_UPSTREAM:
1761                return branch_get_upstream(branch, err);
1762
1763        case PUSH_DEFAULT_UNSPECIFIED:
1764        case PUSH_DEFAULT_SIMPLE:
1765                {
1766                        const char *up, *cur;
1767
1768                        up = branch_get_upstream(branch, err);
1769                        if (!up)
1770                                return NULL;
1771                        cur = tracking_for_push_dest(remote, branch->refname, err);
1772                        if (!cur)
1773                                return NULL;
1774                        if (strcmp(cur, up))
1775                                return error_buf(err,
1776                                                 _("cannot resolve 'simple' push to a single destination"));
1777                        return cur;
1778                }
1779        }
1780
1781        die("BUG: unhandled push situation");
1782}
1783
1784const char *branch_get_push(struct branch *branch, struct strbuf *err)
1785{
1786        if (!branch->push_tracking_ref)
1787                branch->push_tracking_ref = branch_get_push_1(branch, err);
1788        return branch->push_tracking_ref;
1789}
1790
1791static int ignore_symref_update(const char *refname)
1792{
1793        struct object_id oid;
1794        int flag;
1795
1796        if (!resolve_ref_unsafe(refname, 0, oid.hash, &flag))
1797                return 0; /* non-existing refs are OK */
1798        return (flag & REF_ISSYMREF);
1799}
1800
1801/*
1802 * Create and return a list of (struct ref) consisting of copies of
1803 * each remote_ref that matches refspec.  refspec must be a pattern.
1804 * Fill in the copies' peer_ref to describe the local tracking refs to
1805 * which they map.  Omit any references that would map to an existing
1806 * local symbolic ref.
1807 */
1808static struct ref *get_expanded_map(const struct ref *remote_refs,
1809                                    const struct refspec *refspec)
1810{
1811        const struct ref *ref;
1812        struct ref *ret = NULL;
1813        struct ref **tail = &ret;
1814
1815        for (ref = remote_refs; ref; ref = ref->next) {
1816                char *expn_name = NULL;
1817
1818                if (strchr(ref->name, '^'))
1819                        continue; /* a dereference item */
1820                if (match_name_with_pattern(refspec->src, ref->name,
1821                                            refspec->dst, &expn_name) &&
1822                    !ignore_symref_update(expn_name)) {
1823                        struct ref *cpy = copy_ref(ref);
1824
1825                        cpy->peer_ref = alloc_ref(expn_name);
1826                        if (refspec->force)
1827                                cpy->peer_ref->force = 1;
1828                        *tail = cpy;
1829                        tail = &cpy->next;
1830                }
1831                free(expn_name);
1832        }
1833
1834        return ret;
1835}
1836
1837static const struct ref *find_ref_by_name_abbrev(const struct ref *refs, const char *name)
1838{
1839        const struct ref *ref;
1840        for (ref = refs; ref; ref = ref->next) {
1841                if (refname_match(name, ref->name))
1842                        return ref;
1843        }
1844        return NULL;
1845}
1846
1847struct ref *get_remote_ref(const struct ref *remote_refs, const char *name)
1848{
1849        const struct ref *ref = find_ref_by_name_abbrev(remote_refs, name);
1850
1851        if (!ref)
1852                return NULL;
1853
1854        return copy_ref(ref);
1855}
1856
1857static struct ref *get_local_ref(const char *name)
1858{
1859        if (!name || name[0] == '\0')
1860                return NULL;
1861
1862        if (starts_with(name, "refs/"))
1863                return alloc_ref(name);
1864
1865        if (starts_with(name, "heads/") ||
1866            starts_with(name, "tags/") ||
1867            starts_with(name, "remotes/"))
1868                return alloc_ref_with_prefix("refs/", 5, name);
1869
1870        return alloc_ref_with_prefix("refs/heads/", 11, name);
1871}
1872
1873int get_fetch_map(const struct ref *remote_refs,
1874                  const struct refspec *refspec,
1875                  struct ref ***tail,
1876                  int missing_ok)
1877{
1878        struct ref *ref_map, **rmp;
1879
1880        if (refspec->pattern) {
1881                ref_map = get_expanded_map(remote_refs, refspec);
1882        } else {
1883                const char *name = refspec->src[0] ? refspec->src : "HEAD";
1884
1885                if (refspec->exact_sha1) {
1886                        ref_map = alloc_ref(name);
1887                        get_oid_hex(name, &ref_map->old_oid);
1888                } else {
1889                        ref_map = get_remote_ref(remote_refs, name);
1890                }
1891                if (!missing_ok && !ref_map)
1892                        die("Couldn't find remote ref %s", name);
1893                if (ref_map) {
1894                        ref_map->peer_ref = get_local_ref(refspec->dst);
1895                        if (ref_map->peer_ref && refspec->force)
1896                                ref_map->peer_ref->force = 1;
1897                }
1898        }
1899
1900        for (rmp = &ref_map; *rmp; ) {
1901                if ((*rmp)->peer_ref) {
1902                        if (!starts_with((*rmp)->peer_ref->name, "refs/") ||
1903                            check_refname_format((*rmp)->peer_ref->name, 0)) {
1904                                struct ref *ignore = *rmp;
1905                                error("* Ignoring funny ref '%s' locally",
1906                                      (*rmp)->peer_ref->name);
1907                                *rmp = (*rmp)->next;
1908                                free(ignore->peer_ref);
1909                                free(ignore);
1910                                continue;
1911                        }
1912                }
1913                rmp = &((*rmp)->next);
1914        }
1915
1916        if (ref_map)
1917                tail_link_ref(ref_map, tail);
1918
1919        return 0;
1920}
1921
1922int resolve_remote_symref(struct ref *ref, struct ref *list)
1923{
1924        if (!ref->symref)
1925                return 0;
1926        for (; list; list = list->next)
1927                if (!strcmp(ref->symref, list->name)) {
1928                        oidcpy(&ref->old_oid, &list->old_oid);
1929                        return 0;
1930                }
1931        return 1;
1932}
1933
1934static void unmark_and_free(struct commit_list *list, unsigned int mark)
1935{
1936        while (list) {
1937                struct commit *commit = pop_commit(&list);
1938                commit->object.flags &= ~mark;
1939        }
1940}
1941
1942int ref_newer(const struct object_id *new_oid, const struct object_id *old_oid)
1943{
1944        struct object *o;
1945        struct commit *old, *new;
1946        struct commit_list *list, *used;
1947        int found = 0;
1948
1949        /*
1950         * Both new and old must be commit-ish and new is descendant of
1951         * old.  Otherwise we require --force.
1952         */
1953        o = deref_tag(parse_object(old_oid->hash), NULL, 0);
1954        if (!o || o->type != OBJ_COMMIT)
1955                return 0;
1956        old = (struct commit *) o;
1957
1958        o = deref_tag(parse_object(new_oid->hash), NULL, 0);
1959        if (!o || o->type != OBJ_COMMIT)
1960                return 0;
1961        new = (struct commit *) o;
1962
1963        if (parse_commit(new) < 0)
1964                return 0;
1965
1966        used = list = NULL;
1967        commit_list_insert(new, &list);
1968        while (list) {
1969                new = pop_most_recent_commit(&list, TMP_MARK);
1970                commit_list_insert(new, &used);
1971                if (new == old) {
1972                        found = 1;
1973                        break;
1974                }
1975        }
1976        unmark_and_free(list, TMP_MARK);
1977        unmark_and_free(used, TMP_MARK);
1978        return found;
1979}
1980
1981/*
1982 * Compare a branch with its upstream, and save their differences (number
1983 * of commits) in *num_ours and *num_theirs. The name of the upstream branch
1984 * (or NULL if no upstream is defined) is returned via *upstream_name, if it
1985 * is not itself NULL.
1986 *
1987 * Returns -1 if num_ours and num_theirs could not be filled in (e.g., no
1988 * upstream defined, or ref does not exist), 0 otherwise.
1989 */
1990int stat_tracking_info(struct branch *branch, int *num_ours, int *num_theirs,
1991                       const char **upstream_name)
1992{
1993        struct object_id oid;
1994        struct commit *ours, *theirs;
1995        struct rev_info revs;
1996        const char *base;
1997        struct argv_array argv = ARGV_ARRAY_INIT;
1998
1999        /* Cannot stat unless we are marked to build on top of somebody else. */
2000        base = branch_get_upstream(branch, NULL);
2001        if (upstream_name)
2002                *upstream_name = base;
2003        if (!base)
2004                return -1;
2005
2006        /* Cannot stat if what we used to build on no longer exists */
2007        if (read_ref(base, oid.hash))
2008                return -1;
2009        theirs = lookup_commit_reference(oid.hash);
2010        if (!theirs)
2011                return -1;
2012
2013        if (read_ref(branch->refname, oid.hash))
2014                return -1;
2015        ours = lookup_commit_reference(oid.hash);
2016        if (!ours)
2017                return -1;
2018
2019        /* are we the same? */
2020        if (theirs == ours) {
2021                *num_theirs = *num_ours = 0;
2022                return 0;
2023        }
2024
2025        /* Run "rev-list --left-right ours...theirs" internally... */
2026        argv_array_push(&argv, ""); /* ignored */
2027        argv_array_push(&argv, "--left-right");
2028        argv_array_pushf(&argv, "%s...%s",
2029                         oid_to_hex(&ours->object.oid),
2030                         oid_to_hex(&theirs->object.oid));
2031        argv_array_push(&argv, "--");
2032
2033        init_revisions(&revs, NULL);
2034        setup_revisions(argv.argc, argv.argv, &revs, NULL);
2035        if (prepare_revision_walk(&revs))
2036                die("revision walk setup failed");
2037
2038        /* ... and count the commits on each side. */
2039        *num_ours = 0;
2040        *num_theirs = 0;
2041        while (1) {
2042                struct commit *c = get_revision(&revs);
2043                if (!c)
2044                        break;
2045                if (c->object.flags & SYMMETRIC_LEFT)
2046                        (*num_ours)++;
2047                else
2048                        (*num_theirs)++;
2049        }
2050
2051        /* clear object flags smudged by the above traversal */
2052        clear_commit_marks(ours, ALL_REV_FLAGS);
2053        clear_commit_marks(theirs, ALL_REV_FLAGS);
2054
2055        argv_array_clear(&argv);
2056        return 0;
2057}
2058
2059/*
2060 * Return true when there is anything to report, otherwise false.
2061 */
2062int format_tracking_info(struct branch *branch, struct strbuf *sb)
2063{
2064        int ours, theirs;
2065        const char *full_base;
2066        char *base;
2067        int upstream_is_gone = 0;
2068
2069        if (stat_tracking_info(branch, &ours, &theirs, &full_base) < 0) {
2070                if (!full_base)
2071                        return 0;
2072                upstream_is_gone = 1;
2073        }
2074
2075        base = shorten_unambiguous_ref(full_base, 0);
2076        if (upstream_is_gone) {
2077                strbuf_addf(sb,
2078                        _("Your branch is based on '%s', but the upstream is gone.\n"),
2079                        base);
2080                if (advice_status_hints)
2081                        strbuf_addstr(sb,
2082                                _("  (use \"git branch --unset-upstream\" to fixup)\n"));
2083        } else if (!ours && !theirs) {
2084                strbuf_addf(sb,
2085                        _("Your branch is up-to-date with '%s'.\n"),
2086                        base);
2087        } else if (!theirs) {
2088                strbuf_addf(sb,
2089                        Q_("Your branch is ahead of '%s' by %d commit.\n",
2090                           "Your branch is ahead of '%s' by %d commits.\n",
2091                           ours),
2092                        base, ours);
2093                if (advice_status_hints)
2094                        strbuf_addstr(sb,
2095                                _("  (use \"git push\" to publish your local commits)\n"));
2096        } else if (!ours) {
2097                strbuf_addf(sb,
2098                        Q_("Your branch is behind '%s' by %d commit, "
2099                               "and can be fast-forwarded.\n",
2100                           "Your branch is behind '%s' by %d commits, "
2101                               "and can be fast-forwarded.\n",
2102                           theirs),
2103                        base, theirs);
2104                if (advice_status_hints)
2105                        strbuf_addstr(sb,
2106                                _("  (use \"git pull\" to update your local branch)\n"));
2107        } else {
2108                strbuf_addf(sb,
2109                        Q_("Your branch and '%s' have diverged,\n"
2110                               "and have %d and %d different commit each, "
2111                               "respectively.\n",
2112                           "Your branch and '%s' have diverged,\n"
2113                               "and have %d and %d different commits each, "
2114                               "respectively.\n",
2115                           ours + theirs),
2116                        base, ours, theirs);
2117                if (advice_status_hints)
2118                        strbuf_addstr(sb,
2119                                _("  (use \"git pull\" to merge the remote branch into yours)\n"));
2120        }
2121        free(base);
2122        return 1;
2123}
2124
2125static int one_local_ref(const char *refname, const struct object_id *oid,
2126                         int flag, void *cb_data)
2127{
2128        struct ref ***local_tail = cb_data;
2129        struct ref *ref;
2130
2131        /* we already know it starts with refs/ to get here */
2132        if (check_refname_format(refname + 5, 0))
2133                return 0;
2134
2135        ref = alloc_ref(refname);
2136        oidcpy(&ref->new_oid, oid);
2137        **local_tail = ref;
2138        *local_tail = &ref->next;
2139        return 0;
2140}
2141
2142struct ref *get_local_heads(void)
2143{
2144        struct ref *local_refs = NULL, **local_tail = &local_refs;
2145
2146        for_each_ref(one_local_ref, &local_tail);
2147        return local_refs;
2148}
2149
2150struct ref *guess_remote_head(const struct ref *head,
2151                              const struct ref *refs,
2152                              int all)
2153{
2154        const struct ref *r;
2155        struct ref *list = NULL;
2156        struct ref **tail = &list;
2157
2158        if (!head)
2159                return NULL;
2160
2161        /*
2162         * Some transports support directly peeking at
2163         * where HEAD points; if that is the case, then
2164         * we don't have to guess.
2165         */
2166        if (head->symref)
2167                return copy_ref(find_ref_by_name(refs, head->symref));
2168
2169        /* If refs/heads/master could be right, it is. */
2170        if (!all) {
2171                r = find_ref_by_name(refs, "refs/heads/master");
2172                if (r && !oidcmp(&r->old_oid, &head->old_oid))
2173                        return copy_ref(r);
2174        }
2175
2176        /* Look for another ref that points there */
2177        for (r = refs; r; r = r->next) {
2178                if (r != head &&
2179                    starts_with(r->name, "refs/heads/") &&
2180                    !oidcmp(&r->old_oid, &head->old_oid)) {
2181                        *tail = copy_ref(r);
2182                        tail = &((*tail)->next);
2183                        if (!all)
2184                                break;
2185                }
2186        }
2187
2188        return list;
2189}
2190
2191struct stale_heads_info {
2192        struct string_list *ref_names;
2193        struct ref **stale_refs_tail;
2194        struct refspec *refs;
2195        int ref_count;
2196};
2197
2198static int get_stale_heads_cb(const char *refname, const struct object_id *oid,
2199                              int flags, void *cb_data)
2200{
2201        struct stale_heads_info *info = cb_data;
2202        struct string_list matches = STRING_LIST_INIT_DUP;
2203        struct refspec query;
2204        int i, stale = 1;
2205        memset(&query, 0, sizeof(struct refspec));
2206        query.dst = (char *)refname;
2207
2208        query_refspecs_multiple(info->refs, info->ref_count, &query, &matches);
2209        if (matches.nr == 0)
2210                goto clean_exit; /* No matches */
2211
2212        /*
2213         * If we did find a suitable refspec and it's not a symref and
2214         * it's not in the list of refs that currently exist in that
2215         * remote, we consider it to be stale. In order to deal with
2216         * overlapping refspecs, we need to go over all of the
2217         * matching refs.
2218         */
2219        if (flags & REF_ISSYMREF)
2220                goto clean_exit;
2221
2222        for (i = 0; stale && i < matches.nr; i++)
2223                if (string_list_has_string(info->ref_names, matches.items[i].string))
2224                        stale = 0;
2225
2226        if (stale) {
2227                struct ref *ref = make_linked_ref(refname, &info->stale_refs_tail);
2228                oidcpy(&ref->new_oid, oid);
2229        }
2230
2231clean_exit:
2232        string_list_clear(&matches, 0);
2233        return 0;
2234}
2235
2236struct ref *get_stale_heads(struct refspec *refs, int ref_count, struct ref *fetch_map)
2237{
2238        struct ref *ref, *stale_refs = NULL;
2239        struct string_list ref_names = STRING_LIST_INIT_NODUP;
2240        struct stale_heads_info info;
2241
2242        info.ref_names = &ref_names;
2243        info.stale_refs_tail = &stale_refs;
2244        info.refs = refs;
2245        info.ref_count = ref_count;
2246        for (ref = fetch_map; ref; ref = ref->next)
2247                string_list_append(&ref_names, ref->name);
2248        string_list_sort(&ref_names);
2249        for_each_ref(get_stale_heads_cb, &info);
2250        string_list_clear(&ref_names, 0);
2251        return stale_refs;
2252}
2253
2254/*
2255 * Compare-and-swap
2256 */
2257static void clear_cas_option(struct push_cas_option *cas)
2258{
2259        int i;
2260
2261        for (i = 0; i < cas->nr; i++)
2262                free(cas->entry[i].refname);
2263        free(cas->entry);
2264        memset(cas, 0, sizeof(*cas));
2265}
2266
2267static struct push_cas *add_cas_entry(struct push_cas_option *cas,
2268                                      const char *refname,
2269                                      size_t refnamelen)
2270{
2271        struct push_cas *entry;
2272        ALLOC_GROW(cas->entry, cas->nr + 1, cas->alloc);
2273        entry = &cas->entry[cas->nr++];
2274        memset(entry, 0, sizeof(*entry));
2275        entry->refname = xmemdupz(refname, refnamelen);
2276        return entry;
2277}
2278
2279int parse_push_cas_option(struct push_cas_option *cas, const char *arg, int unset)
2280{
2281        const char *colon;
2282        struct push_cas *entry;
2283
2284        if (unset) {
2285                /* "--no-<option>" */
2286                clear_cas_option(cas);
2287                return 0;
2288        }
2289
2290        if (!arg) {
2291                /* just "--<option>" */
2292                cas->use_tracking_for_rest = 1;
2293                return 0;
2294        }
2295
2296        /* "--<option>=refname" or "--<option>=refname:value" */
2297        colon = strchrnul(arg, ':');
2298        entry = add_cas_entry(cas, arg, colon - arg);
2299        if (!*colon)
2300                entry->use_tracking = 1;
2301        else if (!colon[1])
2302                hashclr(entry->expect);
2303        else if (get_sha1(colon + 1, entry->expect))
2304                return error("cannot parse expected object name '%s'", colon + 1);
2305        return 0;
2306}
2307
2308int parseopt_push_cas_option(const struct option *opt, const char *arg, int unset)
2309{
2310        return parse_push_cas_option(opt->value, arg, unset);
2311}
2312
2313int is_empty_cas(const struct push_cas_option *cas)
2314{
2315        return !cas->use_tracking_for_rest && !cas->nr;
2316}
2317
2318/*
2319 * Look at remote.fetch refspec and see if we have a remote
2320 * tracking branch for the refname there.  Fill its current
2321 * value in sha1[].
2322 * If we cannot do so, return negative to signal an error.
2323 */
2324static int remote_tracking(struct remote *remote, const char *refname,
2325                           struct object_id *oid)
2326{
2327        char *dst;
2328
2329        dst = apply_refspecs(remote->fetch, remote->fetch_refspec_nr, refname);
2330        if (!dst)
2331                return -1; /* no tracking ref for refname at remote */
2332        if (read_ref(dst, oid->hash))
2333                return -1; /* we know what the tracking ref is but we cannot read it */
2334        return 0;
2335}
2336
2337static void apply_cas(struct push_cas_option *cas,
2338                      struct remote *remote,
2339                      struct ref *ref)
2340{
2341        int i;
2342
2343        /* Find an explicit --<option>=<name>[:<value>] entry */
2344        for (i = 0; i < cas->nr; i++) {
2345                struct push_cas *entry = &cas->entry[i];
2346                if (!refname_match(entry->refname, ref->name))
2347                        continue;
2348                ref->expect_old_sha1 = 1;
2349                if (!entry->use_tracking)
2350                        hashcpy(ref->old_oid_expect.hash, cas->entry[i].expect);
2351                else if (remote_tracking(remote, ref->name, &ref->old_oid_expect))
2352                        oidclr(&ref->old_oid_expect);
2353                return;
2354        }
2355
2356        /* Are we using "--<option>" to cover all? */
2357        if (!cas->use_tracking_for_rest)
2358                return;
2359
2360        ref->expect_old_sha1 = 1;
2361        if (remote_tracking(remote, ref->name, &ref->old_oid_expect))
2362                oidclr(&ref->old_oid_expect);
2363}
2364
2365void apply_push_cas(struct push_cas_option *cas,
2366                    struct remote *remote,
2367                    struct ref *remote_refs)
2368{
2369        struct ref *ref;
2370        for (ref = remote_refs; ref; ref = ref->next)
2371                apply_cas(cas, remote, ref);
2372}