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