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