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