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