builtin / fetch.con commit Sync with maint (3cdd5d1)
   1/*
   2 * "git fetch"
   3 */
   4#include "cache.h"
   5#include "refs.h"
   6#include "commit.h"
   7#include "builtin.h"
   8#include "string-list.h"
   9#include "remote.h"
  10#include "transport.h"
  11#include "run-command.h"
  12#include "parse-options.h"
  13#include "sigchain.h"
  14#include "submodule-config.h"
  15#include "submodule.h"
  16#include "connected.h"
  17#include "argv-array.h"
  18#include "utf8.h"
  19
  20static const char * const builtin_fetch_usage[] = {
  21        N_("git fetch [<options>] [<repository> [<refspec>...]]"),
  22        N_("git fetch [<options>] <group>"),
  23        N_("git fetch --multiple [<options>] [(<repository> | <group>)...]"),
  24        N_("git fetch --all [<options>]"),
  25        NULL
  26};
  27
  28enum {
  29        TAGS_UNSET = 0,
  30        TAGS_DEFAULT = 1,
  31        TAGS_SET = 2
  32};
  33
  34static int fetch_prune_config = -1; /* unspecified */
  35static int prune = -1; /* unspecified */
  36#define PRUNE_BY_DEFAULT 0 /* do we prune by default? */
  37
  38static int all, append, dry_run, force, keep, multiple, update_head_ok, verbosity, deepen_relative;
  39static int progress = -1, recurse_submodules = RECURSE_SUBMODULES_DEFAULT;
  40static int tags = TAGS_DEFAULT, unshallow, update_shallow, deepen;
  41static int max_children = -1;
  42static enum transport_family family;
  43static const char *depth;
  44static const char *deepen_since;
  45static const char *upload_pack;
  46static struct string_list deepen_not = STRING_LIST_INIT_NODUP;
  47static struct strbuf default_rla = STRBUF_INIT;
  48static struct transport *gtransport;
  49static struct transport *gsecondary;
  50static const char *submodule_prefix = "";
  51static const char *recurse_submodules_default;
  52static int shown_url = 0;
  53static int refmap_alloc, refmap_nr;
  54static const char **refmap_array;
  55
  56static int option_parse_recurse_submodules(const struct option *opt,
  57                                   const char *arg, int unset)
  58{
  59        if (unset) {
  60                recurse_submodules = RECURSE_SUBMODULES_OFF;
  61        } else {
  62                if (arg)
  63                        recurse_submodules = parse_fetch_recurse_submodules_arg(opt->long_name, arg);
  64                else
  65                        recurse_submodules = RECURSE_SUBMODULES_ON;
  66        }
  67        return 0;
  68}
  69
  70static int git_fetch_config(const char *k, const char *v, void *cb)
  71{
  72        if (!strcmp(k, "fetch.prune")) {
  73                fetch_prune_config = git_config_bool(k, v);
  74                return 0;
  75        }
  76        return git_default_config(k, v, cb);
  77}
  78
  79static int parse_refmap_arg(const struct option *opt, const char *arg, int unset)
  80{
  81        ALLOC_GROW(refmap_array, refmap_nr + 1, refmap_alloc);
  82
  83        /*
  84         * "git fetch --refmap='' origin foo"
  85         * can be used to tell the command not to store anywhere
  86         */
  87        if (*arg)
  88                refmap_array[refmap_nr++] = arg;
  89        return 0;
  90}
  91
  92static struct option builtin_fetch_options[] = {
  93        OPT__VERBOSITY(&verbosity),
  94        OPT_BOOL(0, "all", &all,
  95                 N_("fetch from all remotes")),
  96        OPT_BOOL('a', "append", &append,
  97                 N_("append to .git/FETCH_HEAD instead of overwriting")),
  98        OPT_STRING(0, "upload-pack", &upload_pack, N_("path"),
  99                   N_("path to upload pack on remote end")),
 100        OPT__FORCE(&force, N_("force overwrite of local branch")),
 101        OPT_BOOL('m', "multiple", &multiple,
 102                 N_("fetch from multiple remotes")),
 103        OPT_SET_INT('t', "tags", &tags,
 104                    N_("fetch all tags and associated objects"), TAGS_SET),
 105        OPT_SET_INT('n', NULL, &tags,
 106                    N_("do not fetch all tags (--no-tags)"), TAGS_UNSET),
 107        OPT_INTEGER('j', "jobs", &max_children,
 108                    N_("number of submodules fetched in parallel")),
 109        OPT_BOOL('p', "prune", &prune,
 110                 N_("prune remote-tracking branches no longer on remote")),
 111        { OPTION_CALLBACK, 0, "recurse-submodules", NULL, N_("on-demand"),
 112                    N_("control recursive fetching of submodules"),
 113                    PARSE_OPT_OPTARG, option_parse_recurse_submodules },
 114        OPT_BOOL(0, "dry-run", &dry_run,
 115                 N_("dry run")),
 116        OPT_BOOL('k', "keep", &keep, N_("keep downloaded pack")),
 117        OPT_BOOL('u', "update-head-ok", &update_head_ok,
 118                    N_("allow updating of HEAD ref")),
 119        OPT_BOOL(0, "progress", &progress, N_("force progress reporting")),
 120        OPT_STRING(0, "depth", &depth, N_("depth"),
 121                   N_("deepen history of shallow clone")),
 122        OPT_STRING(0, "shallow-since", &deepen_since, N_("time"),
 123                   N_("deepen history of shallow repository based on time")),
 124        OPT_STRING_LIST(0, "shallow-exclude", &deepen_not, N_("revision"),
 125                        N_("deepen history of shallow clone by excluding rev")),
 126        OPT_INTEGER(0, "deepen", &deepen_relative,
 127                    N_("deepen history of shallow clone")),
 128        { OPTION_SET_INT, 0, "unshallow", &unshallow, NULL,
 129                   N_("convert to a complete repository"),
 130                   PARSE_OPT_NONEG | PARSE_OPT_NOARG, NULL, 1 },
 131        { OPTION_STRING, 0, "submodule-prefix", &submodule_prefix, N_("dir"),
 132                   N_("prepend this to submodule path output"), PARSE_OPT_HIDDEN },
 133        { OPTION_STRING, 0, "recurse-submodules-default",
 134                   &recurse_submodules_default, NULL,
 135                   N_("default mode for recursion"), PARSE_OPT_HIDDEN },
 136        OPT_BOOL(0, "update-shallow", &update_shallow,
 137                 N_("accept refs that update .git/shallow")),
 138        { OPTION_CALLBACK, 0, "refmap", NULL, N_("refmap"),
 139          N_("specify fetch refmap"), PARSE_OPT_NONEG, parse_refmap_arg },
 140        OPT_SET_INT('4', "ipv4", &family, N_("use IPv4 addresses only"),
 141                        TRANSPORT_FAMILY_IPV4),
 142        OPT_SET_INT('6', "ipv6", &family, N_("use IPv6 addresses only"),
 143                        TRANSPORT_FAMILY_IPV6),
 144        OPT_END()
 145};
 146
 147static void unlock_pack(void)
 148{
 149        if (gtransport)
 150                transport_unlock_pack(gtransport);
 151        if (gsecondary)
 152                transport_unlock_pack(gsecondary);
 153}
 154
 155static void unlock_pack_on_signal(int signo)
 156{
 157        unlock_pack();
 158        sigchain_pop(signo);
 159        raise(signo);
 160}
 161
 162static void add_merge_config(struct ref **head,
 163                           const struct ref *remote_refs,
 164                           struct branch *branch,
 165                           struct ref ***tail)
 166{
 167        int i;
 168
 169        for (i = 0; i < branch->merge_nr; i++) {
 170                struct ref *rm, **old_tail = *tail;
 171                struct refspec refspec;
 172
 173                for (rm = *head; rm; rm = rm->next) {
 174                        if (branch_merge_matches(branch, i, rm->name)) {
 175                                rm->fetch_head_status = FETCH_HEAD_MERGE;
 176                                break;
 177                        }
 178                }
 179                if (rm)
 180                        continue;
 181
 182                /*
 183                 * Not fetched to a remote-tracking branch?  We need to fetch
 184                 * it anyway to allow this branch's "branch.$name.merge"
 185                 * to be honored by 'git pull', but we do not have to
 186                 * fail if branch.$name.merge is misconfigured to point
 187                 * at a nonexisting branch.  If we were indeed called by
 188                 * 'git pull', it will notice the misconfiguration because
 189                 * there is no entry in the resulting FETCH_HEAD marked
 190                 * for merging.
 191                 */
 192                memset(&refspec, 0, sizeof(refspec));
 193                refspec.src = branch->merge[i]->src;
 194                get_fetch_map(remote_refs, &refspec, tail, 1);
 195                for (rm = *old_tail; rm; rm = rm->next)
 196                        rm->fetch_head_status = FETCH_HEAD_MERGE;
 197        }
 198}
 199
 200static int add_existing(const char *refname, const struct object_id *oid,
 201                        int flag, void *cbdata)
 202{
 203        struct string_list *list = (struct string_list *)cbdata;
 204        struct string_list_item *item = string_list_insert(list, refname);
 205        struct object_id *old_oid = xmalloc(sizeof(*old_oid));
 206
 207        oidcpy(old_oid, oid);
 208        item->util = old_oid;
 209        return 0;
 210}
 211
 212static int will_fetch(struct ref **head, const unsigned char *sha1)
 213{
 214        struct ref *rm = *head;
 215        while (rm) {
 216                if (!hashcmp(rm->old_oid.hash, sha1))
 217                        return 1;
 218                rm = rm->next;
 219        }
 220        return 0;
 221}
 222
 223static void find_non_local_tags(struct transport *transport,
 224                        struct ref **head,
 225                        struct ref ***tail)
 226{
 227        struct string_list existing_refs = STRING_LIST_INIT_DUP;
 228        struct string_list remote_refs = STRING_LIST_INIT_NODUP;
 229        const struct ref *ref;
 230        struct string_list_item *item = NULL;
 231
 232        for_each_ref(add_existing, &existing_refs);
 233        for (ref = transport_get_remote_refs(transport); ref; ref = ref->next) {
 234                if (!starts_with(ref->name, "refs/tags/"))
 235                        continue;
 236
 237                /*
 238                 * The peeled ref always follows the matching base
 239                 * ref, so if we see a peeled ref that we don't want
 240                 * to fetch then we can mark the ref entry in the list
 241                 * as one to ignore by setting util to NULL.
 242                 */
 243                if (ends_with(ref->name, "^{}")) {
 244                        if (item && !has_object_file(&ref->old_oid) &&
 245                            !will_fetch(head, ref->old_oid.hash) &&
 246                            !has_sha1_file(item->util) &&
 247                            !will_fetch(head, item->util))
 248                                item->util = NULL;
 249                        item = NULL;
 250                        continue;
 251                }
 252
 253                /*
 254                 * If item is non-NULL here, then we previously saw a
 255                 * ref not followed by a peeled reference, so we need
 256                 * to check if it is a lightweight tag that we want to
 257                 * fetch.
 258                 */
 259                if (item && !has_sha1_file(item->util) &&
 260                    !will_fetch(head, item->util))
 261                        item->util = NULL;
 262
 263                item = NULL;
 264
 265                /* skip duplicates and refs that we already have */
 266                if (string_list_has_string(&remote_refs, ref->name) ||
 267                    string_list_has_string(&existing_refs, ref->name))
 268                        continue;
 269
 270                item = string_list_insert(&remote_refs, ref->name);
 271                item->util = (void *)&ref->old_oid;
 272        }
 273        string_list_clear(&existing_refs, 1);
 274
 275        /*
 276         * We may have a final lightweight tag that needs to be
 277         * checked to see if it needs fetching.
 278         */
 279        if (item && !has_sha1_file(item->util) &&
 280            !will_fetch(head, item->util))
 281                item->util = NULL;
 282
 283        /*
 284         * For all the tags in the remote_refs string list,
 285         * add them to the list of refs to be fetched
 286         */
 287        for_each_string_list_item(item, &remote_refs) {
 288                /* Unless we have already decided to ignore this item... */
 289                if (item->util)
 290                {
 291                        struct ref *rm = alloc_ref(item->string);
 292                        rm->peer_ref = alloc_ref(item->string);
 293                        oidcpy(&rm->old_oid, item->util);
 294                        **tail = rm;
 295                        *tail = &rm->next;
 296                }
 297        }
 298
 299        string_list_clear(&remote_refs, 0);
 300}
 301
 302static struct ref *get_ref_map(struct transport *transport,
 303                               struct refspec *refspecs, int refspec_count,
 304                               int tags, int *autotags)
 305{
 306        int i;
 307        struct ref *rm;
 308        struct ref *ref_map = NULL;
 309        struct ref **tail = &ref_map;
 310
 311        /* opportunistically-updated references: */
 312        struct ref *orefs = NULL, **oref_tail = &orefs;
 313
 314        const struct ref *remote_refs = transport_get_remote_refs(transport);
 315
 316        if (refspec_count) {
 317                struct refspec *fetch_refspec;
 318                int fetch_refspec_nr;
 319
 320                for (i = 0; i < refspec_count; i++) {
 321                        get_fetch_map(remote_refs, &refspecs[i], &tail, 0);
 322                        if (refspecs[i].dst && refspecs[i].dst[0])
 323                                *autotags = 1;
 324                }
 325                /* Merge everything on the command line (but not --tags) */
 326                for (rm = ref_map; rm; rm = rm->next)
 327                        rm->fetch_head_status = FETCH_HEAD_MERGE;
 328
 329                /*
 330                 * For any refs that we happen to be fetching via
 331                 * command-line arguments, the destination ref might
 332                 * have been missing or have been different than the
 333                 * remote-tracking ref that would be derived from the
 334                 * configured refspec.  In these cases, we want to
 335                 * take the opportunity to update their configured
 336                 * remote-tracking reference.  However, we do not want
 337                 * to mention these entries in FETCH_HEAD at all, as
 338                 * they would simply be duplicates of existing
 339                 * entries, so we set them FETCH_HEAD_IGNORE below.
 340                 *
 341                 * We compute these entries now, based only on the
 342                 * refspecs specified on the command line.  But we add
 343                 * them to the list following the refspecs resulting
 344                 * from the tags option so that one of the latter,
 345                 * which has FETCH_HEAD_NOT_FOR_MERGE, is not removed
 346                 * by ref_remove_duplicates() in favor of one of these
 347                 * opportunistic entries with FETCH_HEAD_IGNORE.
 348                 */
 349                if (refmap_array) {
 350                        fetch_refspec = parse_fetch_refspec(refmap_nr, refmap_array);
 351                        fetch_refspec_nr = refmap_nr;
 352                } else {
 353                        fetch_refspec = transport->remote->fetch;
 354                        fetch_refspec_nr = transport->remote->fetch_refspec_nr;
 355                }
 356
 357                for (i = 0; i < fetch_refspec_nr; i++)
 358                        get_fetch_map(ref_map, &fetch_refspec[i], &oref_tail, 1);
 359
 360                if (tags == TAGS_SET)
 361                        get_fetch_map(remote_refs, tag_refspec, &tail, 0);
 362        } else if (refmap_array) {
 363                die("--refmap option is only meaningful with command-line refspec(s).");
 364        } else {
 365                /* Use the defaults */
 366                struct remote *remote = transport->remote;
 367                struct branch *branch = branch_get(NULL);
 368                int has_merge = branch_has_merge_config(branch);
 369                if (remote &&
 370                    (remote->fetch_refspec_nr ||
 371                     /* Note: has_merge implies non-NULL branch->remote_name */
 372                     (has_merge && !strcmp(branch->remote_name, remote->name)))) {
 373                        for (i = 0; i < remote->fetch_refspec_nr; i++) {
 374                                get_fetch_map(remote_refs, &remote->fetch[i], &tail, 0);
 375                                if (remote->fetch[i].dst &&
 376                                    remote->fetch[i].dst[0])
 377                                        *autotags = 1;
 378                                if (!i && !has_merge && ref_map &&
 379                                    !remote->fetch[0].pattern)
 380                                        ref_map->fetch_head_status = FETCH_HEAD_MERGE;
 381                        }
 382                        /*
 383                         * if the remote we're fetching from is the same
 384                         * as given in branch.<name>.remote, we add the
 385                         * ref given in branch.<name>.merge, too.
 386                         *
 387                         * Note: has_merge implies non-NULL branch->remote_name
 388                         */
 389                        if (has_merge &&
 390                            !strcmp(branch->remote_name, remote->name))
 391                                add_merge_config(&ref_map, remote_refs, branch, &tail);
 392                } else {
 393                        ref_map = get_remote_ref(remote_refs, "HEAD");
 394                        if (!ref_map)
 395                                die(_("Couldn't find remote ref HEAD"));
 396                        ref_map->fetch_head_status = FETCH_HEAD_MERGE;
 397                        tail = &ref_map->next;
 398                }
 399        }
 400
 401        if (tags == TAGS_SET)
 402                /* also fetch all tags */
 403                get_fetch_map(remote_refs, tag_refspec, &tail, 0);
 404        else if (tags == TAGS_DEFAULT && *autotags)
 405                find_non_local_tags(transport, &ref_map, &tail);
 406
 407        /* Now append any refs to be updated opportunistically: */
 408        *tail = orefs;
 409        for (rm = orefs; rm; rm = rm->next) {
 410                rm->fetch_head_status = FETCH_HEAD_IGNORE;
 411                tail = &rm->next;
 412        }
 413
 414        return ref_remove_duplicates(ref_map);
 415}
 416
 417#define STORE_REF_ERROR_OTHER 1
 418#define STORE_REF_ERROR_DF_CONFLICT 2
 419
 420static int s_update_ref(const char *action,
 421                        struct ref *ref,
 422                        int check_old)
 423{
 424        char msg[1024];
 425        char *rla = getenv("GIT_REFLOG_ACTION");
 426        struct ref_transaction *transaction;
 427        struct strbuf err = STRBUF_INIT;
 428        int ret, df_conflict = 0;
 429
 430        if (dry_run)
 431                return 0;
 432        if (!rla)
 433                rla = default_rla.buf;
 434        snprintf(msg, sizeof(msg), "%s: %s", rla, action);
 435
 436        transaction = ref_transaction_begin(&err);
 437        if (!transaction ||
 438            ref_transaction_update(transaction, ref->name,
 439                                   ref->new_oid.hash,
 440                                   check_old ? ref->old_oid.hash : NULL,
 441                                   0, msg, &err))
 442                goto fail;
 443
 444        ret = ref_transaction_commit(transaction, &err);
 445        if (ret) {
 446                df_conflict = (ret == TRANSACTION_NAME_CONFLICT);
 447                goto fail;
 448        }
 449
 450        ref_transaction_free(transaction);
 451        strbuf_release(&err);
 452        return 0;
 453fail:
 454        ref_transaction_free(transaction);
 455        error("%s", err.buf);
 456        strbuf_release(&err);
 457        return df_conflict ? STORE_REF_ERROR_DF_CONFLICT
 458                           : STORE_REF_ERROR_OTHER;
 459}
 460
 461static int refcol_width = 10;
 462static int compact_format;
 463
 464static void adjust_refcol_width(const struct ref *ref)
 465{
 466        int max, rlen, llen, len;
 467
 468        /* uptodate lines are only shown on high verbosity level */
 469        if (!verbosity && !oidcmp(&ref->peer_ref->old_oid, &ref->old_oid))
 470                return;
 471
 472        max    = term_columns();
 473        rlen   = utf8_strwidth(prettify_refname(ref->name));
 474
 475        llen   = utf8_strwidth(prettify_refname(ref->peer_ref->name));
 476
 477        /*
 478         * rough estimation to see if the output line is too long and
 479         * should not be counted (we can't do precise calculation
 480         * anyway because we don't know if the error explanation part
 481         * will be printed in update_local_ref)
 482         */
 483        if (compact_format) {
 484                llen = 0;
 485                max = max * 2 / 3;
 486        }
 487        len = 21 /* flag and summary */ + rlen + 4 /* -> */ + llen;
 488        if (len >= max)
 489                return;
 490
 491        /*
 492         * Not precise calculation for compact mode because '*' can
 493         * appear on the left hand side of '->' and shrink the column
 494         * back.
 495         */
 496        if (refcol_width < rlen)
 497                refcol_width = rlen;
 498}
 499
 500static void prepare_format_display(struct ref *ref_map)
 501{
 502        struct ref *rm;
 503        const char *format = "full";
 504
 505        git_config_get_string_const("fetch.output", &format);
 506        if (!strcasecmp(format, "full"))
 507                compact_format = 0;
 508        else if (!strcasecmp(format, "compact"))
 509                compact_format = 1;
 510        else
 511                die(_("configuration fetch.output contains invalid value %s"),
 512                    format);
 513
 514        for (rm = ref_map; rm; rm = rm->next) {
 515                if (rm->status == REF_STATUS_REJECT_SHALLOW ||
 516                    !rm->peer_ref ||
 517                    !strcmp(rm->name, "HEAD"))
 518                        continue;
 519
 520                adjust_refcol_width(rm);
 521        }
 522}
 523
 524static void print_remote_to_local(struct strbuf *display,
 525                                  const char *remote, const char *local)
 526{
 527        strbuf_addf(display, "%-*s -> %s", refcol_width, remote, local);
 528}
 529
 530static int find_and_replace(struct strbuf *haystack,
 531                            const char *needle,
 532                            const char *placeholder)
 533{
 534        const char *p = strstr(haystack->buf, needle);
 535        int plen, nlen;
 536
 537        if (!p)
 538                return 0;
 539
 540        if (p > haystack->buf && p[-1] != '/')
 541                return 0;
 542
 543        plen = strlen(p);
 544        nlen = strlen(needle);
 545        if (plen > nlen && p[nlen] != '/')
 546                return 0;
 547
 548        strbuf_splice(haystack, p - haystack->buf, nlen,
 549                      placeholder, strlen(placeholder));
 550        return 1;
 551}
 552
 553static void print_compact(struct strbuf *display,
 554                          const char *remote, const char *local)
 555{
 556        struct strbuf r = STRBUF_INIT;
 557        struct strbuf l = STRBUF_INIT;
 558
 559        if (!strcmp(remote, local)) {
 560                strbuf_addf(display, "%-*s -> *", refcol_width, remote);
 561                return;
 562        }
 563
 564        strbuf_addstr(&r, remote);
 565        strbuf_addstr(&l, local);
 566
 567        if (!find_and_replace(&r, local, "*"))
 568                find_and_replace(&l, remote, "*");
 569        print_remote_to_local(display, r.buf, l.buf);
 570
 571        strbuf_release(&r);
 572        strbuf_release(&l);
 573}
 574
 575static void format_display(struct strbuf *display, char code,
 576                           const char *summary, const char *error,
 577                           const char *remote, const char *local)
 578{
 579        strbuf_addf(display, "%c %-*s ", code, TRANSPORT_SUMMARY(summary));
 580        if (!compact_format)
 581                print_remote_to_local(display, remote, local);
 582        else
 583                print_compact(display, remote, local);
 584        if (error)
 585                strbuf_addf(display, "  (%s)", error);
 586}
 587
 588static int update_local_ref(struct ref *ref,
 589                            const char *remote,
 590                            const struct ref *remote_ref,
 591                            struct strbuf *display)
 592{
 593        struct commit *current = NULL, *updated;
 594        enum object_type type;
 595        struct branch *current_branch = branch_get(NULL);
 596        const char *pretty_ref = prettify_refname(ref->name);
 597
 598        type = sha1_object_info(ref->new_oid.hash, NULL);
 599        if (type < 0)
 600                die(_("object %s not found"), oid_to_hex(&ref->new_oid));
 601
 602        if (!oidcmp(&ref->old_oid, &ref->new_oid)) {
 603                if (verbosity > 0)
 604                        format_display(display, '=', _("[up to date]"), NULL,
 605                                       remote, pretty_ref);
 606                return 0;
 607        }
 608
 609        if (current_branch &&
 610            !strcmp(ref->name, current_branch->name) &&
 611            !(update_head_ok || is_bare_repository()) &&
 612            !is_null_oid(&ref->old_oid)) {
 613                /*
 614                 * If this is the head, and it's not okay to update
 615                 * the head, and the old value of the head isn't empty...
 616                 */
 617                format_display(display, '!', _("[rejected]"),
 618                               _("can't fetch in current branch"),
 619                               remote, pretty_ref);
 620                return 1;
 621        }
 622
 623        if (!is_null_oid(&ref->old_oid) &&
 624            starts_with(ref->name, "refs/tags/")) {
 625                int r;
 626                r = s_update_ref("updating tag", ref, 0);
 627                format_display(display, r ? '!' : 't', _("[tag update]"),
 628                               r ? _("unable to update local ref") : NULL,
 629                               remote, pretty_ref);
 630                return r;
 631        }
 632
 633        current = lookup_commit_reference_gently(ref->old_oid.hash, 1);
 634        updated = lookup_commit_reference_gently(ref->new_oid.hash, 1);
 635        if (!current || !updated) {
 636                const char *msg;
 637                const char *what;
 638                int r;
 639                /*
 640                 * Nicely describe the new ref we're fetching.
 641                 * Base this on the remote's ref name, as it's
 642                 * more likely to follow a standard layout.
 643                 */
 644                const char *name = remote_ref ? remote_ref->name : "";
 645                if (starts_with(name, "refs/tags/")) {
 646                        msg = "storing tag";
 647                        what = _("[new tag]");
 648                } else if (starts_with(name, "refs/heads/")) {
 649                        msg = "storing head";
 650                        what = _("[new branch]");
 651                } else {
 652                        msg = "storing ref";
 653                        what = _("[new ref]");
 654                }
 655
 656                if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
 657                    (recurse_submodules != RECURSE_SUBMODULES_ON))
 658                        check_for_new_submodule_commits(ref->new_oid.hash);
 659                r = s_update_ref(msg, ref, 0);
 660                format_display(display, r ? '!' : '*', what,
 661                               r ? _("unable to update local ref") : NULL,
 662                               remote, pretty_ref);
 663                return r;
 664        }
 665
 666        if (in_merge_bases(current, updated)) {
 667                struct strbuf quickref = STRBUF_INIT;
 668                int r;
 669                strbuf_add_unique_abbrev(&quickref, current->object.oid.hash, DEFAULT_ABBREV);
 670                strbuf_addstr(&quickref, "..");
 671                strbuf_add_unique_abbrev(&quickref, ref->new_oid.hash, DEFAULT_ABBREV);
 672                if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
 673                    (recurse_submodules != RECURSE_SUBMODULES_ON))
 674                        check_for_new_submodule_commits(ref->new_oid.hash);
 675                r = s_update_ref("fast-forward", ref, 1);
 676                format_display(display, r ? '!' : ' ', quickref.buf,
 677                               r ? _("unable to update local ref") : NULL,
 678                               remote, pretty_ref);
 679                strbuf_release(&quickref);
 680                return r;
 681        } else if (force || ref->force) {
 682                struct strbuf quickref = STRBUF_INIT;
 683                int r;
 684                strbuf_add_unique_abbrev(&quickref, current->object.oid.hash, DEFAULT_ABBREV);
 685                strbuf_addstr(&quickref, "...");
 686                strbuf_add_unique_abbrev(&quickref, ref->new_oid.hash, DEFAULT_ABBREV);
 687                if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
 688                    (recurse_submodules != RECURSE_SUBMODULES_ON))
 689                        check_for_new_submodule_commits(ref->new_oid.hash);
 690                r = s_update_ref("forced-update", ref, 1);
 691                format_display(display, r ? '!' : '+', quickref.buf,
 692                               r ? _("unable to update local ref") : _("forced update"),
 693                               remote, pretty_ref);
 694                strbuf_release(&quickref);
 695                return r;
 696        } else {
 697                format_display(display, '!', _("[rejected]"), _("non-fast-forward"),
 698                               remote, pretty_ref);
 699                return 1;
 700        }
 701}
 702
 703static int iterate_ref_map(void *cb_data, unsigned char sha1[20])
 704{
 705        struct ref **rm = cb_data;
 706        struct ref *ref = *rm;
 707
 708        while (ref && ref->status == REF_STATUS_REJECT_SHALLOW)
 709                ref = ref->next;
 710        if (!ref)
 711                return -1; /* end of the list */
 712        *rm = ref->next;
 713        hashcpy(sha1, ref->old_oid.hash);
 714        return 0;
 715}
 716
 717static int store_updated_refs(const char *raw_url, const char *remote_name,
 718                struct ref *ref_map)
 719{
 720        FILE *fp;
 721        struct commit *commit;
 722        int url_len, i, rc = 0;
 723        struct strbuf note = STRBUF_INIT;
 724        const char *what, *kind;
 725        struct ref *rm;
 726        char *url;
 727        const char *filename = dry_run ? "/dev/null" : git_path_fetch_head();
 728        int want_status;
 729
 730        fp = fopen(filename, "a");
 731        if (!fp)
 732                return error_errno(_("cannot open %s"), filename);
 733
 734        if (raw_url)
 735                url = transport_anonymize_url(raw_url);
 736        else
 737                url = xstrdup("foreign");
 738
 739        rm = ref_map;
 740        if (check_connected(iterate_ref_map, &rm, NULL)) {
 741                rc = error(_("%s did not send all necessary objects\n"), url);
 742                goto abort;
 743        }
 744
 745        prepare_format_display(ref_map);
 746
 747        /*
 748         * We do a pass for each fetch_head_status type in their enum order, so
 749         * merged entries are written before not-for-merge. That lets readers
 750         * use FETCH_HEAD as a refname to refer to the ref to be merged.
 751         */
 752        for (want_status = FETCH_HEAD_MERGE;
 753             want_status <= FETCH_HEAD_IGNORE;
 754             want_status++) {
 755                for (rm = ref_map; rm; rm = rm->next) {
 756                        struct ref *ref = NULL;
 757                        const char *merge_status_marker = "";
 758
 759                        if (rm->status == REF_STATUS_REJECT_SHALLOW) {
 760                                if (want_status == FETCH_HEAD_MERGE)
 761                                        warning(_("reject %s because shallow roots are not allowed to be updated"),
 762                                                rm->peer_ref ? rm->peer_ref->name : rm->name);
 763                                continue;
 764                        }
 765
 766                        commit = lookup_commit_reference_gently(rm->old_oid.hash, 1);
 767                        if (!commit)
 768                                rm->fetch_head_status = FETCH_HEAD_NOT_FOR_MERGE;
 769
 770                        if (rm->fetch_head_status != want_status)
 771                                continue;
 772
 773                        if (rm->peer_ref) {
 774                                ref = alloc_ref(rm->peer_ref->name);
 775                                oidcpy(&ref->old_oid, &rm->peer_ref->old_oid);
 776                                oidcpy(&ref->new_oid, &rm->old_oid);
 777                                ref->force = rm->peer_ref->force;
 778                        }
 779
 780
 781                        if (!strcmp(rm->name, "HEAD")) {
 782                                kind = "";
 783                                what = "";
 784                        }
 785                        else if (starts_with(rm->name, "refs/heads/")) {
 786                                kind = "branch";
 787                                what = rm->name + 11;
 788                        }
 789                        else if (starts_with(rm->name, "refs/tags/")) {
 790                                kind = "tag";
 791                                what = rm->name + 10;
 792                        }
 793                        else if (starts_with(rm->name, "refs/remotes/")) {
 794                                kind = "remote-tracking branch";
 795                                what = rm->name + 13;
 796                        }
 797                        else {
 798                                kind = "";
 799                                what = rm->name;
 800                        }
 801
 802                        url_len = strlen(url);
 803                        for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
 804                                ;
 805                        url_len = i + 1;
 806                        if (4 < i && !strncmp(".git", url + i - 3, 4))
 807                                url_len = i - 3;
 808
 809                        strbuf_reset(&note);
 810                        if (*what) {
 811                                if (*kind)
 812                                        strbuf_addf(&note, "%s ", kind);
 813                                strbuf_addf(&note, "'%s' of ", what);
 814                        }
 815                        switch (rm->fetch_head_status) {
 816                        case FETCH_HEAD_NOT_FOR_MERGE:
 817                                merge_status_marker = "not-for-merge";
 818                                /* fall-through */
 819                        case FETCH_HEAD_MERGE:
 820                                fprintf(fp, "%s\t%s\t%s",
 821                                        oid_to_hex(&rm->old_oid),
 822                                        merge_status_marker,
 823                                        note.buf);
 824                                for (i = 0; i < url_len; ++i)
 825                                        if ('\n' == url[i])
 826                                                fputs("\\n", fp);
 827                                        else
 828                                                fputc(url[i], fp);
 829                                fputc('\n', fp);
 830                                break;
 831                        default:
 832                                /* do not write anything to FETCH_HEAD */
 833                                break;
 834                        }
 835
 836                        strbuf_reset(&note);
 837                        if (ref) {
 838                                rc |= update_local_ref(ref, what, rm, &note);
 839                                free(ref);
 840                        } else
 841                                format_display(&note, '*',
 842                                               *kind ? kind : "branch", NULL,
 843                                               *what ? what : "HEAD",
 844                                               "FETCH_HEAD");
 845                        if (note.len) {
 846                                if (verbosity >= 0 && !shown_url) {
 847                                        fprintf(stderr, _("From %.*s\n"),
 848                                                        url_len, url);
 849                                        shown_url = 1;
 850                                }
 851                                if (verbosity >= 0)
 852                                        fprintf(stderr, " %s\n", note.buf);
 853                        }
 854                }
 855        }
 856
 857        if (rc & STORE_REF_ERROR_DF_CONFLICT)
 858                error(_("some local refs could not be updated; try running\n"
 859                      " 'git remote prune %s' to remove any old, conflicting "
 860                      "branches"), remote_name);
 861
 862 abort:
 863        strbuf_release(&note);
 864        free(url);
 865        fclose(fp);
 866        return rc;
 867}
 868
 869/*
 870 * We would want to bypass the object transfer altogether if
 871 * everything we are going to fetch already exists and is connected
 872 * locally.
 873 */
 874static int quickfetch(struct ref *ref_map)
 875{
 876        struct ref *rm = ref_map;
 877        struct check_connected_options opt = CHECK_CONNECTED_INIT;
 878
 879        /*
 880         * If we are deepening a shallow clone we already have these
 881         * objects reachable.  Running rev-list here will return with
 882         * a good (0) exit status and we'll bypass the fetch that we
 883         * really need to perform.  Claiming failure now will ensure
 884         * we perform the network exchange to deepen our history.
 885         */
 886        if (deepen)
 887                return -1;
 888        opt.quiet = 1;
 889        return check_connected(iterate_ref_map, &rm, &opt);
 890}
 891
 892static int fetch_refs(struct transport *transport, struct ref *ref_map)
 893{
 894        int ret = quickfetch(ref_map);
 895        if (ret)
 896                ret = transport_fetch_refs(transport, ref_map);
 897        if (!ret)
 898                ret |= store_updated_refs(transport->url,
 899                                transport->remote->name,
 900                                ref_map);
 901        transport_unlock_pack(transport);
 902        return ret;
 903}
 904
 905static int prune_refs(struct refspec *refs, int ref_count, struct ref *ref_map,
 906                const char *raw_url)
 907{
 908        int url_len, i, result = 0;
 909        struct ref *ref, *stale_refs = get_stale_heads(refs, ref_count, ref_map);
 910        char *url;
 911        const char *dangling_msg = dry_run
 912                ? _("   (%s will become dangling)")
 913                : _("   (%s has become dangling)");
 914
 915        if (raw_url)
 916                url = transport_anonymize_url(raw_url);
 917        else
 918                url = xstrdup("foreign");
 919
 920        url_len = strlen(url);
 921        for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
 922                ;
 923
 924        url_len = i + 1;
 925        if (4 < i && !strncmp(".git", url + i - 3, 4))
 926                url_len = i - 3;
 927
 928        if (!dry_run) {
 929                struct string_list refnames = STRING_LIST_INIT_NODUP;
 930
 931                for (ref = stale_refs; ref; ref = ref->next)
 932                        string_list_append(&refnames, ref->name);
 933
 934                result = delete_refs(&refnames, 0);
 935                string_list_clear(&refnames, 0);
 936        }
 937
 938        if (verbosity >= 0) {
 939                for (ref = stale_refs; ref; ref = ref->next) {
 940                        struct strbuf sb = STRBUF_INIT;
 941                        if (!shown_url) {
 942                                fprintf(stderr, _("From %.*s\n"), url_len, url);
 943                                shown_url = 1;
 944                        }
 945                        format_display(&sb, '-', _("[deleted]"), NULL,
 946                                       _("(none)"), prettify_refname(ref->name));
 947                        fprintf(stderr, " %s\n",sb.buf);
 948                        strbuf_release(&sb);
 949                        warn_dangling_symref(stderr, dangling_msg, ref->name);
 950                }
 951        }
 952
 953        free(url);
 954        free_refs(stale_refs);
 955        return result;
 956}
 957
 958static void check_not_current_branch(struct ref *ref_map)
 959{
 960        struct branch *current_branch = branch_get(NULL);
 961
 962        if (is_bare_repository() || !current_branch)
 963                return;
 964
 965        for (; ref_map; ref_map = ref_map->next)
 966                if (ref_map->peer_ref && !strcmp(current_branch->refname,
 967                                        ref_map->peer_ref->name))
 968                        die(_("Refusing to fetch into current branch %s "
 969                            "of non-bare repository"), current_branch->refname);
 970}
 971
 972static int truncate_fetch_head(void)
 973{
 974        const char *filename = git_path_fetch_head();
 975        FILE *fp = fopen_for_writing(filename);
 976
 977        if (!fp)
 978                return error_errno(_("cannot open %s"), filename);
 979        fclose(fp);
 980        return 0;
 981}
 982
 983static void set_option(struct transport *transport, const char *name, const char *value)
 984{
 985        int r = transport_set_option(transport, name, value);
 986        if (r < 0)
 987                die(_("Option \"%s\" value \"%s\" is not valid for %s"),
 988                    name, value, transport->url);
 989        if (r > 0)
 990                warning(_("Option \"%s\" is ignored for %s\n"),
 991                        name, transport->url);
 992}
 993
 994static struct transport *prepare_transport(struct remote *remote, int deepen)
 995{
 996        struct transport *transport;
 997        transport = transport_get(remote, NULL);
 998        transport_set_verbosity(transport, verbosity, progress);
 999        transport->family = family;
1000        if (upload_pack)
1001                set_option(transport, TRANS_OPT_UPLOADPACK, upload_pack);
1002        if (keep)
1003                set_option(transport, TRANS_OPT_KEEP, "yes");
1004        if (depth)
1005                set_option(transport, TRANS_OPT_DEPTH, depth);
1006        if (deepen && deepen_since)
1007                set_option(transport, TRANS_OPT_DEEPEN_SINCE, deepen_since);
1008        if (deepen && deepen_not.nr)
1009                set_option(transport, TRANS_OPT_DEEPEN_NOT,
1010                           (const char *)&deepen_not);
1011        if (deepen_relative)
1012                set_option(transport, TRANS_OPT_DEEPEN_RELATIVE, "yes");
1013        if (update_shallow)
1014                set_option(transport, TRANS_OPT_UPDATE_SHALLOW, "yes");
1015        return transport;
1016}
1017
1018static void backfill_tags(struct transport *transport, struct ref *ref_map)
1019{
1020        int cannot_reuse;
1021
1022        /*
1023         * Once we have set TRANS_OPT_DEEPEN_SINCE, we can't unset it
1024         * when remote helper is used (setting it to an empty string
1025         * is not unsetting). We could extend the remote helper
1026         * protocol for that, but for now, just force a new connection
1027         * without deepen-since. Similar story for deepen-not.
1028         */
1029        cannot_reuse = transport->cannot_reuse ||
1030                deepen_since || deepen_not.nr;
1031        if (cannot_reuse) {
1032                gsecondary = prepare_transport(transport->remote, 0);
1033                transport = gsecondary;
1034        }
1035
1036        transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
1037        transport_set_option(transport, TRANS_OPT_DEPTH, "0");
1038        transport_set_option(transport, TRANS_OPT_DEEPEN_RELATIVE, NULL);
1039        fetch_refs(transport, ref_map);
1040
1041        if (gsecondary) {
1042                transport_disconnect(gsecondary);
1043                gsecondary = NULL;
1044        }
1045}
1046
1047static int do_fetch(struct transport *transport,
1048                    struct refspec *refs, int ref_count)
1049{
1050        struct string_list existing_refs = STRING_LIST_INIT_DUP;
1051        struct ref *ref_map;
1052        struct ref *rm;
1053        int autotags = (transport->remote->fetch_tags == 1);
1054        int retcode = 0;
1055
1056        for_each_ref(add_existing, &existing_refs);
1057
1058        if (tags == TAGS_DEFAULT) {
1059                if (transport->remote->fetch_tags == 2)
1060                        tags = TAGS_SET;
1061                if (transport->remote->fetch_tags == -1)
1062                        tags = TAGS_UNSET;
1063        }
1064
1065        if (!transport->get_refs_list || !transport->fetch)
1066                die(_("Don't know how to fetch from %s"), transport->url);
1067
1068        /* if not appending, truncate FETCH_HEAD */
1069        if (!append && !dry_run) {
1070                retcode = truncate_fetch_head();
1071                if (retcode)
1072                        goto cleanup;
1073        }
1074
1075        ref_map = get_ref_map(transport, refs, ref_count, tags, &autotags);
1076        if (!update_head_ok)
1077                check_not_current_branch(ref_map);
1078
1079        for (rm = ref_map; rm; rm = rm->next) {
1080                if (rm->peer_ref) {
1081                        struct string_list_item *peer_item =
1082                                string_list_lookup(&existing_refs,
1083                                                   rm->peer_ref->name);
1084                        if (peer_item) {
1085                                struct object_id *old_oid = peer_item->util;
1086                                oidcpy(&rm->peer_ref->old_oid, old_oid);
1087                        }
1088                }
1089        }
1090
1091        if (tags == TAGS_DEFAULT && autotags)
1092                transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
1093        if (prune) {
1094                /*
1095                 * We only prune based on refspecs specified
1096                 * explicitly (via command line or configuration); we
1097                 * don't care whether --tags was specified.
1098                 */
1099                if (ref_count) {
1100                        prune_refs(refs, ref_count, ref_map, transport->url);
1101                } else {
1102                        prune_refs(transport->remote->fetch,
1103                                   transport->remote->fetch_refspec_nr,
1104                                   ref_map,
1105                                   transport->url);
1106                }
1107        }
1108        if (fetch_refs(transport, ref_map)) {
1109                free_refs(ref_map);
1110                retcode = 1;
1111                goto cleanup;
1112        }
1113        free_refs(ref_map);
1114
1115        /* if neither --no-tags nor --tags was specified, do automated tag
1116         * following ... */
1117        if (tags == TAGS_DEFAULT && autotags) {
1118                struct ref **tail = &ref_map;
1119                ref_map = NULL;
1120                find_non_local_tags(transport, &ref_map, &tail);
1121                if (ref_map)
1122                        backfill_tags(transport, ref_map);
1123                free_refs(ref_map);
1124        }
1125
1126 cleanup:
1127        string_list_clear(&existing_refs, 1);
1128        return retcode;
1129}
1130
1131static int get_one_remote_for_fetch(struct remote *remote, void *priv)
1132{
1133        struct string_list *list = priv;
1134        if (!remote->skip_default_update)
1135                string_list_append(list, remote->name);
1136        return 0;
1137}
1138
1139struct remote_group_data {
1140        const char *name;
1141        struct string_list *list;
1142};
1143
1144static int get_remote_group(const char *key, const char *value, void *priv)
1145{
1146        struct remote_group_data *g = priv;
1147
1148        if (skip_prefix(key, "remotes.", &key) && !strcmp(key, g->name)) {
1149                /* split list by white space */
1150                while (*value) {
1151                        size_t wordlen = strcspn(value, " \t\n");
1152
1153                        if (wordlen >= 1)
1154                                string_list_append_nodup(g->list,
1155                                                   xstrndup(value, wordlen));
1156                        value += wordlen + (value[wordlen] != '\0');
1157                }
1158        }
1159
1160        return 0;
1161}
1162
1163static int add_remote_or_group(const char *name, struct string_list *list)
1164{
1165        int prev_nr = list->nr;
1166        struct remote_group_data g;
1167        g.name = name; g.list = list;
1168
1169        git_config(get_remote_group, &g);
1170        if (list->nr == prev_nr) {
1171                struct remote *remote = remote_get(name);
1172                if (!remote_is_configured(remote))
1173                        return 0;
1174                string_list_append(list, remote->name);
1175        }
1176        return 1;
1177}
1178
1179static void add_options_to_argv(struct argv_array *argv)
1180{
1181        if (dry_run)
1182                argv_array_push(argv, "--dry-run");
1183        if (prune != -1)
1184                argv_array_push(argv, prune ? "--prune" : "--no-prune");
1185        if (update_head_ok)
1186                argv_array_push(argv, "--update-head-ok");
1187        if (force)
1188                argv_array_push(argv, "--force");
1189        if (keep)
1190                argv_array_push(argv, "--keep");
1191        if (recurse_submodules == RECURSE_SUBMODULES_ON)
1192                argv_array_push(argv, "--recurse-submodules");
1193        else if (recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND)
1194                argv_array_push(argv, "--recurse-submodules=on-demand");
1195        if (tags == TAGS_SET)
1196                argv_array_push(argv, "--tags");
1197        else if (tags == TAGS_UNSET)
1198                argv_array_push(argv, "--no-tags");
1199        if (verbosity >= 2)
1200                argv_array_push(argv, "-v");
1201        if (verbosity >= 1)
1202                argv_array_push(argv, "-v");
1203        else if (verbosity < 0)
1204                argv_array_push(argv, "-q");
1205
1206}
1207
1208static int fetch_multiple(struct string_list *list)
1209{
1210        int i, result = 0;
1211        struct argv_array argv = ARGV_ARRAY_INIT;
1212
1213        if (!append && !dry_run) {
1214                int errcode = truncate_fetch_head();
1215                if (errcode)
1216                        return errcode;
1217        }
1218
1219        argv_array_pushl(&argv, "fetch", "--append", NULL);
1220        add_options_to_argv(&argv);
1221
1222        for (i = 0; i < list->nr; i++) {
1223                const char *name = list->items[i].string;
1224                argv_array_push(&argv, name);
1225                if (verbosity >= 0)
1226                        printf(_("Fetching %s\n"), name);
1227                if (run_command_v_opt(argv.argv, RUN_GIT_CMD)) {
1228                        error(_("Could not fetch %s"), name);
1229                        result = 1;
1230                }
1231                argv_array_pop(&argv);
1232        }
1233
1234        argv_array_clear(&argv);
1235        return result;
1236}
1237
1238static int fetch_one(struct remote *remote, int argc, const char **argv)
1239{
1240        static const char **refs = NULL;
1241        struct refspec *refspec;
1242        int ref_nr = 0;
1243        int exit_code;
1244
1245        if (!remote)
1246                die(_("No remote repository specified.  Please, specify either a URL or a\n"
1247                    "remote name from which new revisions should be fetched."));
1248
1249        gtransport = prepare_transport(remote, 1);
1250
1251        if (prune < 0) {
1252                /* no command line request */
1253                if (0 <= gtransport->remote->prune)
1254                        prune = gtransport->remote->prune;
1255                else if (0 <= fetch_prune_config)
1256                        prune = fetch_prune_config;
1257                else
1258                        prune = PRUNE_BY_DEFAULT;
1259        }
1260
1261        if (argc > 0) {
1262                int j = 0;
1263                int i;
1264                refs = xcalloc(st_add(argc, 1), sizeof(const char *));
1265                for (i = 0; i < argc; i++) {
1266                        if (!strcmp(argv[i], "tag")) {
1267                                i++;
1268                                if (i >= argc)
1269                                        die(_("You need to specify a tag name."));
1270                                refs[j++] = xstrfmt("refs/tags/%s:refs/tags/%s",
1271                                                    argv[i], argv[i]);
1272                        } else
1273                                refs[j++] = argv[i];
1274                }
1275                refs[j] = NULL;
1276                ref_nr = j;
1277        }
1278
1279        sigchain_push_common(unlock_pack_on_signal);
1280        atexit(unlock_pack);
1281        refspec = parse_fetch_refspec(ref_nr, refs);
1282        exit_code = do_fetch(gtransport, refspec, ref_nr);
1283        free_refspec(ref_nr, refspec);
1284        transport_disconnect(gtransport);
1285        gtransport = NULL;
1286        return exit_code;
1287}
1288
1289int cmd_fetch(int argc, const char **argv, const char *prefix)
1290{
1291        int i;
1292        struct string_list list = STRING_LIST_INIT_DUP;
1293        struct remote *remote;
1294        int result = 0;
1295        struct argv_array argv_gc_auto = ARGV_ARRAY_INIT;
1296
1297        packet_trace_identity("fetch");
1298
1299        /* Record the command line for the reflog */
1300        strbuf_addstr(&default_rla, "fetch");
1301        for (i = 1; i < argc; i++)
1302                strbuf_addf(&default_rla, " %s", argv[i]);
1303
1304        git_config(git_fetch_config, NULL);
1305
1306        argc = parse_options(argc, argv, prefix,
1307                             builtin_fetch_options, builtin_fetch_usage, 0);
1308
1309        if (deepen_relative) {
1310                if (deepen_relative < 0)
1311                        die(_("Negative depth in --deepen is not supported"));
1312                if (depth)
1313                        die(_("--deepen and --depth are mutually exclusive"));
1314                depth = xstrfmt("%d", deepen_relative);
1315        }
1316        if (unshallow) {
1317                if (depth)
1318                        die(_("--depth and --unshallow cannot be used together"));
1319                else if (!is_repository_shallow())
1320                        die(_("--unshallow on a complete repository does not make sense"));
1321                else
1322                        depth = xstrfmt("%d", INFINITE_DEPTH);
1323        }
1324
1325        /* no need to be strict, transport_set_option() will validate it again */
1326        if (depth && atoi(depth) < 1)
1327                die(_("depth %s is not a positive number"), depth);
1328        if (depth || deepen_since || deepen_not.nr)
1329                deepen = 1;
1330
1331        if (recurse_submodules != RECURSE_SUBMODULES_OFF) {
1332                if (recurse_submodules_default) {
1333                        int arg = parse_fetch_recurse_submodules_arg("--recurse-submodules-default", recurse_submodules_default);
1334                        set_config_fetch_recurse_submodules(arg);
1335                }
1336                gitmodules_config();
1337                git_config(submodule_config, NULL);
1338        }
1339
1340        if (all) {
1341                if (argc == 1)
1342                        die(_("fetch --all does not take a repository argument"));
1343                else if (argc > 1)
1344                        die(_("fetch --all does not make sense with refspecs"));
1345                (void) for_each_remote(get_one_remote_for_fetch, &list);
1346                result = fetch_multiple(&list);
1347        } else if (argc == 0) {
1348                /* No arguments -- use default remote */
1349                remote = remote_get(NULL);
1350                result = fetch_one(remote, argc, argv);
1351        } else if (multiple) {
1352                /* All arguments are assumed to be remotes or groups */
1353                for (i = 0; i < argc; i++)
1354                        if (!add_remote_or_group(argv[i], &list))
1355                                die(_("No such remote or remote group: %s"), argv[i]);
1356                result = fetch_multiple(&list);
1357        } else {
1358                /* Single remote or group */
1359                (void) add_remote_or_group(argv[0], &list);
1360                if (list.nr > 1) {
1361                        /* More than one remote */
1362                        if (argc > 1)
1363                                die(_("Fetching a group and specifying refspecs does not make sense"));
1364                        result = fetch_multiple(&list);
1365                } else {
1366                        /* Zero or one remotes */
1367                        remote = remote_get(argv[0]);
1368                        result = fetch_one(remote, argc-1, argv+1);
1369                }
1370        }
1371
1372        if (!result && (recurse_submodules != RECURSE_SUBMODULES_OFF)) {
1373                struct argv_array options = ARGV_ARRAY_INIT;
1374
1375                add_options_to_argv(&options);
1376                result = fetch_populated_submodules(&options,
1377                                                    submodule_prefix,
1378                                                    recurse_submodules,
1379                                                    verbosity < 0,
1380                                                    max_children);
1381                argv_array_clear(&options);
1382        }
1383
1384        string_list_clear(&list, 0);
1385
1386        close_all_packs();
1387
1388        argv_array_pushl(&argv_gc_auto, "gc", "--auto", NULL);
1389        if (verbosity < 0)
1390                argv_array_push(&argv_gc_auto, "--quiet");
1391        run_command_v_opt(argv_gc_auto.argv, RUN_GIT_CMD);
1392        argv_array_clear(&argv_gc_auto);
1393
1394        return result;
1395}