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