builtin / fetch.con commit builtin/fetch.c: ignore merge config when not fetching from branch's remote (3ee1757)
   1/*
   2 * "git fetch"
   3 */
   4#include "cache.h"
   5#include "refs.h"
   6#include "commit.h"
   7#include "builtin.h"
   8#include "string-list.h"
   9#include "remote.h"
  10#include "transport.h"
  11#include "run-command.h"
  12#include "parse-options.h"
  13#include "sigchain.h"
  14#include "transport.h"
  15
  16static const char * const builtin_fetch_usage[] = {
  17        "git fetch [<options>] [<repository> [<refspec>...]]",
  18        "git fetch [<options>] <group>",
  19        "git fetch --multiple [<options>] [<repository> | <group>]...",
  20        "git fetch --all [<options>]",
  21        NULL
  22};
  23
  24enum {
  25        TAGS_UNSET = 0,
  26        TAGS_DEFAULT = 1,
  27        TAGS_SET = 2
  28};
  29
  30static int all, append, dry_run, force, keep, multiple, prune, update_head_ok, verbosity;
  31static int progress;
  32static int tags = TAGS_DEFAULT;
  33static const char *depth;
  34static const char *upload_pack;
  35static struct strbuf default_rla = STRBUF_INIT;
  36static struct transport *transport;
  37
  38static struct option builtin_fetch_options[] = {
  39        OPT__VERBOSITY(&verbosity),
  40        OPT_BOOLEAN(0, "all", &all,
  41                    "fetch from all remotes"),
  42        OPT_BOOLEAN('a', "append", &append,
  43                    "append to .git/FETCH_HEAD instead of overwriting"),
  44        OPT_STRING(0, "upload-pack", &upload_pack, "PATH",
  45                   "path to upload pack on remote end"),
  46        OPT_BOOLEAN('f', "force", &force,
  47                    "force overwrite of local branch"),
  48        OPT_BOOLEAN('m', "multiple", &multiple,
  49                    "fetch from multiple remotes"),
  50        OPT_SET_INT('t', "tags", &tags,
  51                    "fetch all tags and associated objects", TAGS_SET),
  52        OPT_SET_INT('n', NULL, &tags,
  53                    "do not fetch all tags (--no-tags)", TAGS_UNSET),
  54        OPT_BOOLEAN('p', "prune", &prune,
  55                    "prune tracking branches no longer on remote"),
  56        OPT_BOOLEAN(0, "dry-run", &dry_run,
  57                    "dry run"),
  58        OPT_BOOLEAN('k', "keep", &keep, "keep downloaded pack"),
  59        OPT_BOOLEAN('u', "update-head-ok", &update_head_ok,
  60                    "allow updating of HEAD ref"),
  61        OPT_BOOLEAN(0, "progress", &progress, "force progress reporting"),
  62        OPT_STRING(0, "depth", &depth, "DEPTH",
  63                   "deepen history of shallow clone"),
  64        OPT_END()
  65};
  66
  67static void unlock_pack(void)
  68{
  69        if (transport)
  70                transport_unlock_pack(transport);
  71}
  72
  73static void unlock_pack_on_signal(int signo)
  74{
  75        unlock_pack();
  76        sigchain_pop(signo);
  77        raise(signo);
  78}
  79
  80static void add_merge_config(struct ref **head,
  81                           const struct ref *remote_refs,
  82                           struct branch *branch,
  83                           struct ref ***tail)
  84{
  85        int i;
  86
  87        for (i = 0; i < branch->merge_nr; i++) {
  88                struct ref *rm, **old_tail = *tail;
  89                struct refspec refspec;
  90
  91                for (rm = *head; rm; rm = rm->next) {
  92                        if (branch_merge_matches(branch, i, rm->name)) {
  93                                rm->merge = 1;
  94                                break;
  95                        }
  96                }
  97                if (rm)
  98                        continue;
  99
 100                /*
 101                 * Not fetched to a tracking branch?  We need to fetch
 102                 * it anyway to allow this branch's "branch.$name.merge"
 103                 * to be honored by 'git pull', but we do not have to
 104                 * fail if branch.$name.merge is misconfigured to point
 105                 * at a nonexisting branch.  If we were indeed called by
 106                 * 'git pull', it will notice the misconfiguration because
 107                 * there is no entry in the resulting FETCH_HEAD marked
 108                 * for merging.
 109                 */
 110                memset(&refspec, 0, sizeof(refspec));
 111                refspec.src = branch->merge[i]->src;
 112                get_fetch_map(remote_refs, &refspec, tail, 1);
 113                for (rm = *old_tail; rm; rm = rm->next)
 114                        rm->merge = 1;
 115        }
 116}
 117
 118static void find_non_local_tags(struct transport *transport,
 119                        struct ref **head,
 120                        struct ref ***tail);
 121
 122static struct ref *get_ref_map(struct transport *transport,
 123                               struct refspec *refs, int ref_count, int tags,
 124                               int *autotags)
 125{
 126        int i;
 127        struct ref *rm;
 128        struct ref *ref_map = NULL;
 129        struct ref **tail = &ref_map;
 130
 131        const struct ref *remote_refs = transport_get_remote_refs(transport);
 132
 133        if (ref_count || tags == TAGS_SET) {
 134                for (i = 0; i < ref_count; i++) {
 135                        get_fetch_map(remote_refs, &refs[i], &tail, 0);
 136                        if (refs[i].dst && refs[i].dst[0])
 137                                *autotags = 1;
 138                }
 139                /* Merge everything on the command line, but not --tags */
 140                for (rm = ref_map; rm; rm = rm->next)
 141                        rm->merge = 1;
 142                if (tags == TAGS_SET)
 143                        get_fetch_map(remote_refs, tag_refspec, &tail, 0);
 144        } else {
 145                /* Use the defaults */
 146                struct remote *remote = transport->remote;
 147                struct branch *branch = branch_get(NULL);
 148                int has_merge = branch_has_merge_config(branch);
 149                if (remote &&
 150                    (remote->fetch_refspec_nr ||
 151                     (has_merge && !strcmp(branch->remote_name, remote->name)))) {
 152                        for (i = 0; i < remote->fetch_refspec_nr; i++) {
 153                                get_fetch_map(remote_refs, &remote->fetch[i], &tail, 0);
 154                                if (remote->fetch[i].dst &&
 155                                    remote->fetch[i].dst[0])
 156                                        *autotags = 1;
 157                                if (!i && !has_merge && ref_map &&
 158                                    !remote->fetch[0].pattern)
 159                                        ref_map->merge = 1;
 160                        }
 161                        /*
 162                         * if the remote we're fetching from is the same
 163                         * as given in branch.<name>.remote, we add the
 164                         * ref given in branch.<name>.merge, too.
 165                         */
 166                        if (has_merge &&
 167                            !strcmp(branch->remote_name, remote->name))
 168                                add_merge_config(&ref_map, remote_refs, branch, &tail);
 169                } else {
 170                        ref_map = get_remote_ref(remote_refs, "HEAD");
 171                        if (!ref_map)
 172                                die("Couldn't find remote ref HEAD");
 173                        ref_map->merge = 1;
 174                        tail = &ref_map->next;
 175                }
 176        }
 177        if (tags == TAGS_DEFAULT && *autotags)
 178                find_non_local_tags(transport, &ref_map, &tail);
 179        ref_remove_duplicates(ref_map);
 180
 181        return ref_map;
 182}
 183
 184#define STORE_REF_ERROR_OTHER 1
 185#define STORE_REF_ERROR_DF_CONFLICT 2
 186
 187static int s_update_ref(const char *action,
 188                        struct ref *ref,
 189                        int check_old)
 190{
 191        char msg[1024];
 192        char *rla = getenv("GIT_REFLOG_ACTION");
 193        static struct ref_lock *lock;
 194
 195        if (dry_run)
 196                return 0;
 197        if (!rla)
 198                rla = default_rla.buf;
 199        snprintf(msg, sizeof(msg), "%s: %s", rla, action);
 200        lock = lock_any_ref_for_update(ref->name,
 201                                       check_old ? ref->old_sha1 : NULL, 0);
 202        if (!lock)
 203                return errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
 204                                          STORE_REF_ERROR_OTHER;
 205        if (write_ref_sha1(lock, ref->new_sha1, msg) < 0)
 206                return errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
 207                                          STORE_REF_ERROR_OTHER;
 208        return 0;
 209}
 210
 211#define REFCOL_WIDTH  10
 212
 213static int update_local_ref(struct ref *ref,
 214                            const char *remote,
 215                            char *display)
 216{
 217        struct commit *current = NULL, *updated;
 218        enum object_type type;
 219        struct branch *current_branch = branch_get(NULL);
 220        const char *pretty_ref = prettify_refname(ref->name);
 221
 222        *display = 0;
 223        type = sha1_object_info(ref->new_sha1, NULL);
 224        if (type < 0)
 225                die("object %s not found", sha1_to_hex(ref->new_sha1));
 226
 227        if (!hashcmp(ref->old_sha1, ref->new_sha1)) {
 228                if (verbosity > 0)
 229                        sprintf(display, "= %-*s %-*s -> %s", TRANSPORT_SUMMARY_WIDTH,
 230                                "[up to date]", REFCOL_WIDTH, remote,
 231                                pretty_ref);
 232                return 0;
 233        }
 234
 235        if (current_branch &&
 236            !strcmp(ref->name, current_branch->name) &&
 237            !(update_head_ok || is_bare_repository()) &&
 238            !is_null_sha1(ref->old_sha1)) {
 239                /*
 240                 * If this is the head, and it's not okay to update
 241                 * the head, and the old value of the head isn't empty...
 242                 */
 243                sprintf(display, "! %-*s %-*s -> %s  (can't fetch in current branch)",
 244                        TRANSPORT_SUMMARY_WIDTH, "[rejected]", REFCOL_WIDTH, remote,
 245                        pretty_ref);
 246                return 1;
 247        }
 248
 249        if (!is_null_sha1(ref->old_sha1) &&
 250            !prefixcmp(ref->name, "refs/tags/")) {
 251                int r;
 252                r = s_update_ref("updating tag", ref, 0);
 253                sprintf(display, "%c %-*s %-*s -> %s%s", r ? '!' : '-',
 254                        TRANSPORT_SUMMARY_WIDTH, "[tag update]", REFCOL_WIDTH, remote,
 255                        pretty_ref, r ? "  (unable to update local ref)" : "");
 256                return r;
 257        }
 258
 259        current = lookup_commit_reference_gently(ref->old_sha1, 1);
 260        updated = lookup_commit_reference_gently(ref->new_sha1, 1);
 261        if (!current || !updated) {
 262                const char *msg;
 263                const char *what;
 264                int r;
 265                if (!strncmp(ref->name, "refs/tags/", 10)) {
 266                        msg = "storing tag";
 267                        what = "[new tag]";
 268                }
 269                else {
 270                        msg = "storing head";
 271                        what = "[new branch]";
 272                }
 273
 274                r = s_update_ref(msg, ref, 0);
 275                sprintf(display, "%c %-*s %-*s -> %s%s", r ? '!' : '*',
 276                        TRANSPORT_SUMMARY_WIDTH, what, REFCOL_WIDTH, remote, pretty_ref,
 277                        r ? "  (unable to update local ref)" : "");
 278                return r;
 279        }
 280
 281        if (in_merge_bases(current, &updated, 1)) {
 282                char quickref[83];
 283                int r;
 284                strcpy(quickref, find_unique_abbrev(current->object.sha1, DEFAULT_ABBREV));
 285                strcat(quickref, "..");
 286                strcat(quickref, find_unique_abbrev(ref->new_sha1, DEFAULT_ABBREV));
 287                r = s_update_ref("fast-forward", ref, 1);
 288                sprintf(display, "%c %-*s %-*s -> %s%s", r ? '!' : ' ',
 289                        TRANSPORT_SUMMARY_WIDTH, quickref, REFCOL_WIDTH, remote,
 290                        pretty_ref, r ? "  (unable to update local ref)" : "");
 291                return r;
 292        } else if (force || ref->force) {
 293                char quickref[84];
 294                int r;
 295                strcpy(quickref, find_unique_abbrev(current->object.sha1, DEFAULT_ABBREV));
 296                strcat(quickref, "...");
 297                strcat(quickref, find_unique_abbrev(ref->new_sha1, DEFAULT_ABBREV));
 298                r = s_update_ref("forced-update", ref, 1);
 299                sprintf(display, "%c %-*s %-*s -> %s  (%s)", r ? '!' : '+',
 300                        TRANSPORT_SUMMARY_WIDTH, quickref, REFCOL_WIDTH, remote,
 301                        pretty_ref,
 302                        r ? "unable to update local ref" : "forced update");
 303                return r;
 304        } else {
 305                sprintf(display, "! %-*s %-*s -> %s  (non-fast-forward)",
 306                        TRANSPORT_SUMMARY_WIDTH, "[rejected]", REFCOL_WIDTH, remote,
 307                        pretty_ref);
 308                return 1;
 309        }
 310}
 311
 312static int store_updated_refs(const char *raw_url, const char *remote_name,
 313                struct ref *ref_map)
 314{
 315        FILE *fp;
 316        struct commit *commit;
 317        int url_len, i, note_len, shown_url = 0, rc = 0;
 318        char note[1024];
 319        const char *what, *kind;
 320        struct ref *rm;
 321        char *url, *filename = dry_run ? "/dev/null" : git_path("FETCH_HEAD");
 322
 323        fp = fopen(filename, "a");
 324        if (!fp)
 325                return error("cannot open %s: %s\n", filename, strerror(errno));
 326
 327        if (raw_url)
 328                url = transport_anonymize_url(raw_url);
 329        else
 330                url = xstrdup("foreign");
 331        for (rm = ref_map; rm; rm = rm->next) {
 332                struct ref *ref = NULL;
 333
 334                if (rm->peer_ref) {
 335                        ref = xcalloc(1, sizeof(*ref) + strlen(rm->peer_ref->name) + 1);
 336                        strcpy(ref->name, rm->peer_ref->name);
 337                        hashcpy(ref->old_sha1, rm->peer_ref->old_sha1);
 338                        hashcpy(ref->new_sha1, rm->old_sha1);
 339                        ref->force = rm->peer_ref->force;
 340                }
 341
 342                commit = lookup_commit_reference_gently(rm->old_sha1, 1);
 343                if (!commit)
 344                        rm->merge = 0;
 345
 346                if (!strcmp(rm->name, "HEAD")) {
 347                        kind = "";
 348                        what = "";
 349                }
 350                else if (!prefixcmp(rm->name, "refs/heads/")) {
 351                        kind = "branch";
 352                        what = rm->name + 11;
 353                }
 354                else if (!prefixcmp(rm->name, "refs/tags/")) {
 355                        kind = "tag";
 356                        what = rm->name + 10;
 357                }
 358                else if (!prefixcmp(rm->name, "refs/remotes/")) {
 359                        kind = "remote branch";
 360                        what = rm->name + 13;
 361                }
 362                else {
 363                        kind = "";
 364                        what = rm->name;
 365                }
 366
 367                url_len = strlen(url);
 368                for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
 369                        ;
 370                url_len = i + 1;
 371                if (4 < i && !strncmp(".git", url + i - 3, 4))
 372                        url_len = i - 3;
 373
 374                note_len = 0;
 375                if (*what) {
 376                        if (*kind)
 377                                note_len += sprintf(note + note_len, "%s ",
 378                                                    kind);
 379                        note_len += sprintf(note + note_len, "'%s' of ", what);
 380                }
 381                note[note_len] = '\0';
 382                fprintf(fp, "%s\t%s\t%s",
 383                        sha1_to_hex(commit ? commit->object.sha1 :
 384                                    rm->old_sha1),
 385                        rm->merge ? "" : "not-for-merge",
 386                        note);
 387                for (i = 0; i < url_len; ++i)
 388                        if ('\n' == url[i])
 389                                fputs("\\n", fp);
 390                        else
 391                                fputc(url[i], fp);
 392                fputc('\n', fp);
 393
 394                if (ref) {
 395                        rc |= update_local_ref(ref, what, note);
 396                        free(ref);
 397                } else
 398                        sprintf(note, "* %-*s %-*s -> FETCH_HEAD",
 399                                TRANSPORT_SUMMARY_WIDTH, *kind ? kind : "branch",
 400                                 REFCOL_WIDTH, *what ? what : "HEAD");
 401                if (*note) {
 402                        if (verbosity >= 0 && !shown_url) {
 403                                fprintf(stderr, "From %.*s\n",
 404                                                url_len, url);
 405                                shown_url = 1;
 406                        }
 407                        if (verbosity >= 0)
 408                                fprintf(stderr, " %s\n", note);
 409                }
 410        }
 411        free(url);
 412        fclose(fp);
 413        if (rc & STORE_REF_ERROR_DF_CONFLICT)
 414                error("some local refs could not be updated; try running\n"
 415                      " 'git remote prune %s' to remove any old, conflicting "
 416                      "branches", remote_name);
 417        return rc;
 418}
 419
 420/*
 421 * We would want to bypass the object transfer altogether if
 422 * everything we are going to fetch already exists and is connected
 423 * locally.
 424 *
 425 * The refs we are going to fetch are in ref_map.  If running
 426 *
 427 *  $ git rev-list --objects --stdin --not --all
 428 *
 429 * (feeding all the refs in ref_map on its standard input)
 430 * does not error out, that means everything reachable from the
 431 * refs we are going to fetch exists and is connected to some of
 432 * our existing refs.
 433 */
 434static int quickfetch(struct ref *ref_map)
 435{
 436        struct child_process revlist;
 437        struct ref *ref;
 438        int err;
 439        const char *argv[] = {"rev-list",
 440                "--quiet", "--objects", "--stdin", "--not", "--all", NULL};
 441
 442        /*
 443         * If we are deepening a shallow clone we already have these
 444         * objects reachable.  Running rev-list here will return with
 445         * a good (0) exit status and we'll bypass the fetch that we
 446         * really need to perform.  Claiming failure now will ensure
 447         * we perform the network exchange to deepen our history.
 448         */
 449        if (depth)
 450                return -1;
 451
 452        if (!ref_map)
 453                return 0;
 454
 455        memset(&revlist, 0, sizeof(revlist));
 456        revlist.argv = argv;
 457        revlist.git_cmd = 1;
 458        revlist.no_stdout = 1;
 459        revlist.no_stderr = 1;
 460        revlist.in = -1;
 461
 462        err = start_command(&revlist);
 463        if (err) {
 464                error("could not run rev-list");
 465                return err;
 466        }
 467
 468        /*
 469         * If rev-list --stdin encounters an unknown commit, it terminates,
 470         * which will cause SIGPIPE in the write loop below.
 471         */
 472        sigchain_push(SIGPIPE, SIG_IGN);
 473
 474        for (ref = ref_map; ref; ref = ref->next) {
 475                if (write_in_full(revlist.in, sha1_to_hex(ref->old_sha1), 40) < 0 ||
 476                    write_str_in_full(revlist.in, "\n") < 0) {
 477                        if (errno != EPIPE && errno != EINVAL)
 478                                error("failed write to rev-list: %s", strerror(errno));
 479                        err = -1;
 480                        break;
 481                }
 482        }
 483
 484        if (close(revlist.in)) {
 485                error("failed to close rev-list's stdin: %s", strerror(errno));
 486                err = -1;
 487        }
 488
 489        sigchain_pop(SIGPIPE);
 490
 491        return finish_command(&revlist) || err;
 492}
 493
 494static int fetch_refs(struct transport *transport, struct ref *ref_map)
 495{
 496        int ret = quickfetch(ref_map);
 497        if (ret)
 498                ret = transport_fetch_refs(transport, ref_map);
 499        if (!ret)
 500                ret |= store_updated_refs(transport->url,
 501                                transport->remote->name,
 502                                ref_map);
 503        transport_unlock_pack(transport);
 504        return ret;
 505}
 506
 507static int prune_refs(struct transport *transport, struct ref *ref_map)
 508{
 509        int result = 0;
 510        struct ref *ref, *stale_refs = get_stale_heads(transport->remote, ref_map);
 511        const char *dangling_msg = dry_run
 512                ? "   (%s will become dangling)\n"
 513                : "   (%s has become dangling)\n";
 514
 515        for (ref = stale_refs; ref; ref = ref->next) {
 516                if (!dry_run)
 517                        result |= delete_ref(ref->name, NULL, 0);
 518                if (verbosity >= 0) {
 519                        fprintf(stderr, " x %-*s %-*s -> %s\n",
 520                                TRANSPORT_SUMMARY_WIDTH, "[deleted]",
 521                                REFCOL_WIDTH, "(none)", prettify_refname(ref->name));
 522                        warn_dangling_symref(stderr, dangling_msg, ref->name);
 523                }
 524        }
 525        free_refs(stale_refs);
 526        return result;
 527}
 528
 529static int add_existing(const char *refname, const unsigned char *sha1,
 530                        int flag, void *cbdata)
 531{
 532        struct string_list *list = (struct string_list *)cbdata;
 533        struct string_list_item *item = string_list_insert(refname, list);
 534        item->util = (void *)sha1;
 535        return 0;
 536}
 537
 538static int will_fetch(struct ref **head, const unsigned char *sha1)
 539{
 540        struct ref *rm = *head;
 541        while (rm) {
 542                if (!hashcmp(rm->old_sha1, sha1))
 543                        return 1;
 544                rm = rm->next;
 545        }
 546        return 0;
 547}
 548
 549struct tag_data {
 550        struct ref **head;
 551        struct ref ***tail;
 552};
 553
 554static int add_to_tail(struct string_list_item *item, void *cb_data)
 555{
 556        struct tag_data *data = (struct tag_data *)cb_data;
 557        struct ref *rm = NULL;
 558
 559        /* We have already decided to ignore this item */
 560        if (!item->util)
 561                return 0;
 562
 563        rm = alloc_ref(item->string);
 564        rm->peer_ref = alloc_ref(item->string);
 565        hashcpy(rm->old_sha1, item->util);
 566
 567        **data->tail = rm;
 568        *data->tail = &rm->next;
 569
 570        return 0;
 571}
 572
 573static void find_non_local_tags(struct transport *transport,
 574                        struct ref **head,
 575                        struct ref ***tail)
 576{
 577        struct string_list existing_refs = { NULL, 0, 0, 0 };
 578        struct string_list remote_refs = { NULL, 0, 0, 0 };
 579        struct tag_data data = {head, tail};
 580        const struct ref *ref;
 581        struct string_list_item *item = NULL;
 582
 583        for_each_ref(add_existing, &existing_refs);
 584        for (ref = transport_get_remote_refs(transport); ref; ref = ref->next) {
 585                if (prefixcmp(ref->name, "refs/tags"))
 586                        continue;
 587
 588                /*
 589                 * The peeled ref always follows the matching base
 590                 * ref, so if we see a peeled ref that we don't want
 591                 * to fetch then we can mark the ref entry in the list
 592                 * as one to ignore by setting util to NULL.
 593                 */
 594                if (!suffixcmp(ref->name, "^{}")) {
 595                        if (item && !has_sha1_file(ref->old_sha1) &&
 596                            !will_fetch(head, ref->old_sha1) &&
 597                            !has_sha1_file(item->util) &&
 598                            !will_fetch(head, item->util))
 599                                item->util = NULL;
 600                        item = NULL;
 601                        continue;
 602                }
 603
 604                /*
 605                 * If item is non-NULL here, then we previously saw a
 606                 * ref not followed by a peeled reference, so we need
 607                 * to check if it is a lightweight tag that we want to
 608                 * fetch.
 609                 */
 610                if (item && !has_sha1_file(item->util) &&
 611                    !will_fetch(head, item->util))
 612                        item->util = NULL;
 613
 614                item = NULL;
 615
 616                /* skip duplicates and refs that we already have */
 617                if (string_list_has_string(&remote_refs, ref->name) ||
 618                    string_list_has_string(&existing_refs, ref->name))
 619                        continue;
 620
 621                item = string_list_insert(ref->name, &remote_refs);
 622                item->util = (void *)ref->old_sha1;
 623        }
 624        string_list_clear(&existing_refs, 0);
 625
 626        /*
 627         * We may have a final lightweight tag that needs to be
 628         * checked to see if it needs fetching.
 629         */
 630        if (item && !has_sha1_file(item->util) &&
 631            !will_fetch(head, item->util))
 632                item->util = NULL;
 633
 634        /*
 635         * For all the tags in the remote_refs string list, call
 636         * add_to_tail to add them to the list of refs to be fetched
 637         */
 638        for_each_string_list(add_to_tail, &remote_refs, &data);
 639
 640        string_list_clear(&remote_refs, 0);
 641}
 642
 643static void check_not_current_branch(struct ref *ref_map)
 644{
 645        struct branch *current_branch = branch_get(NULL);
 646
 647        if (is_bare_repository() || !current_branch)
 648                return;
 649
 650        for (; ref_map; ref_map = ref_map->next)
 651                if (ref_map->peer_ref && !strcmp(current_branch->refname,
 652                                        ref_map->peer_ref->name))
 653                        die("Refusing to fetch into current branch %s "
 654                            "of non-bare repository", current_branch->refname);
 655}
 656
 657static int truncate_fetch_head(void)
 658{
 659        char *filename = git_path("FETCH_HEAD");
 660        FILE *fp = fopen(filename, "w");
 661
 662        if (!fp)
 663                return error("cannot open %s: %s\n", filename, strerror(errno));
 664        fclose(fp);
 665        return 0;
 666}
 667
 668static int do_fetch(struct transport *transport,
 669                    struct refspec *refs, int ref_count)
 670{
 671        struct string_list existing_refs = { NULL, 0, 0, 0 };
 672        struct string_list_item *peer_item = NULL;
 673        struct ref *ref_map;
 674        struct ref *rm;
 675        int autotags = (transport->remote->fetch_tags == 1);
 676
 677        for_each_ref(add_existing, &existing_refs);
 678
 679        if (transport->remote->fetch_tags == 2 && tags != TAGS_UNSET)
 680                tags = TAGS_SET;
 681        if (transport->remote->fetch_tags == -1)
 682                tags = TAGS_UNSET;
 683
 684        if (!transport->get_refs_list || !transport->fetch)
 685                die("Don't know how to fetch from %s", transport->url);
 686
 687        /* if not appending, truncate FETCH_HEAD */
 688        if (!append && !dry_run) {
 689                int errcode = truncate_fetch_head();
 690                if (errcode)
 691                        return errcode;
 692        }
 693
 694        ref_map = get_ref_map(transport, refs, ref_count, tags, &autotags);
 695        if (!update_head_ok)
 696                check_not_current_branch(ref_map);
 697
 698        for (rm = ref_map; rm; rm = rm->next) {
 699                if (rm->peer_ref) {
 700                        peer_item = string_list_lookup(rm->peer_ref->name,
 701                                                       &existing_refs);
 702                        if (peer_item)
 703                                hashcpy(rm->peer_ref->old_sha1,
 704                                        peer_item->util);
 705                }
 706        }
 707
 708        if (tags == TAGS_DEFAULT && autotags)
 709                transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
 710        if (fetch_refs(transport, ref_map)) {
 711                free_refs(ref_map);
 712                return 1;
 713        }
 714        if (prune)
 715                prune_refs(transport, ref_map);
 716        free_refs(ref_map);
 717
 718        /* if neither --no-tags nor --tags was specified, do automated tag
 719         * following ... */
 720        if (tags == TAGS_DEFAULT && autotags) {
 721                struct ref **tail = &ref_map;
 722                ref_map = NULL;
 723                find_non_local_tags(transport, &ref_map, &tail);
 724                if (ref_map) {
 725                        transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
 726                        transport_set_option(transport, TRANS_OPT_DEPTH, "0");
 727                        fetch_refs(transport, ref_map);
 728                }
 729                free_refs(ref_map);
 730        }
 731
 732        return 0;
 733}
 734
 735static void set_option(const char *name, const char *value)
 736{
 737        int r = transport_set_option(transport, name, value);
 738        if (r < 0)
 739                die("Option \"%s\" value \"%s\" is not valid for %s",
 740                        name, value, transport->url);
 741        if (r > 0)
 742                warning("Option \"%s\" is ignored for %s\n",
 743                        name, transport->url);
 744}
 745
 746static int get_one_remote_for_fetch(struct remote *remote, void *priv)
 747{
 748        struct string_list *list = priv;
 749        if (!remote->skip_default_update)
 750                string_list_append(remote->name, list);
 751        return 0;
 752}
 753
 754struct remote_group_data {
 755        const char *name;
 756        struct string_list *list;
 757};
 758
 759static int get_remote_group(const char *key, const char *value, void *priv)
 760{
 761        struct remote_group_data *g = priv;
 762
 763        if (!prefixcmp(key, "remotes.") &&
 764                        !strcmp(key + 8, g->name)) {
 765                /* split list by white space */
 766                int space = strcspn(value, " \t\n");
 767                while (*value) {
 768                        if (space > 1) {
 769                                string_list_append(xstrndup(value, space),
 770                                                   g->list);
 771                        }
 772                        value += space + (value[space] != '\0');
 773                        space = strcspn(value, " \t\n");
 774                }
 775        }
 776
 777        return 0;
 778}
 779
 780static int add_remote_or_group(const char *name, struct string_list *list)
 781{
 782        int prev_nr = list->nr;
 783        struct remote_group_data g = { name, list };
 784
 785        git_config(get_remote_group, &g);
 786        if (list->nr == prev_nr) {
 787                struct remote *remote;
 788                if (!remote_is_configured(name))
 789                        return 0;
 790                remote = remote_get(name);
 791                string_list_append(remote->name, list);
 792        }
 793        return 1;
 794}
 795
 796static int fetch_multiple(struct string_list *list)
 797{
 798        int i, result = 0;
 799        const char *argv[11] = { "fetch", "--append" };
 800        int argc = 2;
 801
 802        if (dry_run)
 803                argv[argc++] = "--dry-run";
 804        if (prune)
 805                argv[argc++] = "--prune";
 806        if (update_head_ok)
 807                argv[argc++] = "--update-head-ok";
 808        if (force)
 809                argv[argc++] = "--force";
 810        if (keep)
 811                argv[argc++] = "--keep";
 812        if (verbosity >= 2)
 813                argv[argc++] = "-v";
 814        if (verbosity >= 1)
 815                argv[argc++] = "-v";
 816        else if (verbosity < 0)
 817                argv[argc++] = "-q";
 818
 819        if (!append && !dry_run) {
 820                int errcode = truncate_fetch_head();
 821                if (errcode)
 822                        return errcode;
 823        }
 824
 825        for (i = 0; i < list->nr; i++) {
 826                const char *name = list->items[i].string;
 827                argv[argc] = name;
 828                argv[argc + 1] = NULL;
 829                if (verbosity >= 0)
 830                        printf("Fetching %s\n", name);
 831                if (run_command_v_opt(argv, RUN_GIT_CMD)) {
 832                        error("Could not fetch %s", name);
 833                        result = 1;
 834                }
 835        }
 836
 837        return result;
 838}
 839
 840static int fetch_one(struct remote *remote, int argc, const char **argv)
 841{
 842        int i;
 843        static const char **refs = NULL;
 844        int ref_nr = 0;
 845        int exit_code;
 846
 847        if (!remote)
 848                die("Where do you want to fetch from today?");
 849
 850        transport = transport_get(remote, NULL);
 851        transport_set_verbosity(transport, verbosity, progress);
 852        if (upload_pack)
 853                set_option(TRANS_OPT_UPLOADPACK, upload_pack);
 854        if (keep)
 855                set_option(TRANS_OPT_KEEP, "yes");
 856        if (depth)
 857                set_option(TRANS_OPT_DEPTH, depth);
 858
 859        if (argc > 0) {
 860                int j = 0;
 861                refs = xcalloc(argc + 1, sizeof(const char *));
 862                for (i = 0; i < argc; i++) {
 863                        if (!strcmp(argv[i], "tag")) {
 864                                char *ref;
 865                                i++;
 866                                if (i >= argc)
 867                                        die("You need to specify a tag name.");
 868                                ref = xmalloc(strlen(argv[i]) * 2 + 22);
 869                                strcpy(ref, "refs/tags/");
 870                                strcat(ref, argv[i]);
 871                                strcat(ref, ":refs/tags/");
 872                                strcat(ref, argv[i]);
 873                                refs[j++] = ref;
 874                        } else
 875                                refs[j++] = argv[i];
 876                }
 877                refs[j] = NULL;
 878                ref_nr = j;
 879        }
 880
 881        sigchain_push_common(unlock_pack_on_signal);
 882        atexit(unlock_pack);
 883        exit_code = do_fetch(transport,
 884                        parse_fetch_refspec(ref_nr, refs), ref_nr);
 885        transport_disconnect(transport);
 886        transport = NULL;
 887        return exit_code;
 888}
 889
 890int cmd_fetch(int argc, const char **argv, const char *prefix)
 891{
 892        int i;
 893        struct string_list list = { NULL, 0, 0, 0 };
 894        struct remote *remote;
 895        int result = 0;
 896
 897        /* Record the command line for the reflog */
 898        strbuf_addstr(&default_rla, "fetch");
 899        for (i = 1; i < argc; i++)
 900                strbuf_addf(&default_rla, " %s", argv[i]);
 901
 902        argc = parse_options(argc, argv, prefix,
 903                             builtin_fetch_options, builtin_fetch_usage, 0);
 904
 905        if (all) {
 906                if (argc == 1)
 907                        die("fetch --all does not take a repository argument");
 908                else if (argc > 1)
 909                        die("fetch --all does not make sense with refspecs");
 910                (void) for_each_remote(get_one_remote_for_fetch, &list);
 911                result = fetch_multiple(&list);
 912        } else if (argc == 0) {
 913                /* No arguments -- use default remote */
 914                remote = remote_get(NULL);
 915                result = fetch_one(remote, argc, argv);
 916        } else if (multiple) {
 917                /* All arguments are assumed to be remotes or groups */
 918                for (i = 0; i < argc; i++)
 919                        if (!add_remote_or_group(argv[i], &list))
 920                                die("No such remote or remote group: %s", argv[i]);
 921                result = fetch_multiple(&list);
 922        } else {
 923                /* Single remote or group */
 924                (void) add_remote_or_group(argv[0], &list);
 925                if (list.nr > 1) {
 926                        /* More than one remote */
 927                        if (argc > 1)
 928                                die("Fetching a group and specifying refspecs does not make sense");
 929                        result = fetch_multiple(&list);
 930                } else {
 931                        /* Zero or one remotes */
 932                        remote = remote_get(argv[0]);
 933                        result = fetch_one(remote, argc-1, argv+1);
 934                }
 935        }
 936
 937        /* All names were strdup()ed or strndup()ed */
 938        list.strdup_strings = 1;
 939        string_list_clear(&list, 0);
 940
 941        return result;
 942}