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