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