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