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