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