exclude: add flags parameter to add_patterns()
[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 "refspec.h"
9 #include "object-store.h"
10 #include "oidset.h"
11 #include "commit.h"
12 #include "builtin.h"
13 #include "string-list.h"
14 #include "remote.h"
15 #include "transport.h"
16 #include "run-command.h"
17 #include "parse-options.h"
18 #include "sigchain.h"
19 #include "submodule-config.h"
20 #include "submodule.h"
21 #include "connected.h"
22 #include "strvec.h"
23 #include "utf8.h"
24 #include "packfile.h"
25 #include "list-objects-filter-options.h"
26 #include "commit-reach.h"
27 #include "branch.h"
28 #include "promisor-remote.h"
29 #include "commit-graph.h"
30 #include "shallow.h"
31
32 #define FORCED_UPDATES_DELAY_WARNING_IN_MS (10 * 1000)
33
34 static const char * const builtin_fetch_usage[] = {
35         N_("git fetch [<options>] [<repository> [<refspec>...]]"),
36         N_("git fetch [<options>] <group>"),
37         N_("git fetch --multiple [<options>] [(<repository> | <group>)...]"),
38         N_("git fetch --all [<options>]"),
39         NULL
40 };
41
42 enum {
43         TAGS_UNSET = 0,
44         TAGS_DEFAULT = 1,
45         TAGS_SET = 2
46 };
47
48 static int fetch_prune_config = -1; /* unspecified */
49 static int fetch_show_forced_updates = 1;
50 static uint64_t forced_updates_ms = 0;
51 static int prune = -1; /* unspecified */
52 #define PRUNE_BY_DEFAULT 0 /* do we prune by default? */
53
54 static int fetch_prune_tags_config = -1; /* unspecified */
55 static int prune_tags = -1; /* unspecified */
56 #define PRUNE_TAGS_BY_DEFAULT 0 /* do we prune tags by default? */
57
58 static int all, append, dry_run, force, keep, multiple, update_head_ok;
59 static int write_fetch_head = 1;
60 static int verbosity, deepen_relative, set_upstream;
61 static int progress = -1;
62 static int enable_auto_gc = 1;
63 static int tags = TAGS_DEFAULT, unshallow, update_shallow, deepen;
64 static int max_jobs = -1, submodule_fetch_jobs_config = -1;
65 static int fetch_parallel_config = 1;
66 static int atomic_fetch;
67 static enum transport_family family;
68 static const char *depth;
69 static const char *deepen_since;
70 static const char *upload_pack;
71 static struct string_list deepen_not = STRING_LIST_INIT_NODUP;
72 static struct strbuf default_rla = STRBUF_INIT;
73 static struct transport *gtransport;
74 static struct transport *gsecondary;
75 static const char *submodule_prefix = "";
76 static int recurse_submodules = RECURSE_SUBMODULES_DEFAULT;
77 static int recurse_submodules_default = RECURSE_SUBMODULES_ON_DEMAND;
78 static int shown_url = 0;
79 static struct refspec refmap = REFSPEC_INIT_FETCH;
80 static struct list_objects_filter_options filter_options;
81 static struct string_list server_options = STRING_LIST_INIT_DUP;
82 static struct string_list negotiation_tip = STRING_LIST_INIT_NODUP;
83 static int fetch_write_commit_graph = -1;
84 static int stdin_refspecs = 0;
85
86 static int git_fetch_config(const char *k, const char *v, void *cb)
87 {
88         if (!strcmp(k, "fetch.prune")) {
89                 fetch_prune_config = git_config_bool(k, v);
90                 return 0;
91         }
92
93         if (!strcmp(k, "fetch.prunetags")) {
94                 fetch_prune_tags_config = git_config_bool(k, v);
95                 return 0;
96         }
97
98         if (!strcmp(k, "fetch.showforcedupdates")) {
99                 fetch_show_forced_updates = git_config_bool(k, v);
100                 return 0;
101         }
102
103         if (!strcmp(k, "submodule.recurse")) {
104                 int r = git_config_bool(k, v) ?
105                         RECURSE_SUBMODULES_ON : RECURSE_SUBMODULES_OFF;
106                 recurse_submodules = r;
107         }
108
109         if (!strcmp(k, "submodule.fetchjobs")) {
110                 submodule_fetch_jobs_config = parse_submodule_fetchjobs(k, v);
111                 return 0;
112         } else if (!strcmp(k, "fetch.recursesubmodules")) {
113                 recurse_submodules = parse_fetch_recurse_submodules_arg(k, v);
114                 return 0;
115         }
116
117         if (!strcmp(k, "fetch.parallel")) {
118                 fetch_parallel_config = git_config_int(k, v);
119                 if (fetch_parallel_config < 0)
120                         die(_("fetch.parallel cannot be negative"));
121                 return 0;
122         }
123
124         return git_default_config(k, v, cb);
125 }
126
127 static int parse_refmap_arg(const struct option *opt, const char *arg, int unset)
128 {
129         BUG_ON_OPT_NEG(unset);
130
131         /*
132          * "git fetch --refmap='' origin foo"
133          * can be used to tell the command not to store anywhere
134          */
135         refspec_append(&refmap, arg);
136
137         return 0;
138 }
139
140 static struct option builtin_fetch_options[] = {
141         OPT__VERBOSITY(&verbosity),
142         OPT_BOOL(0, "all", &all,
143                  N_("fetch from all remotes")),
144         OPT_BOOL(0, "set-upstream", &set_upstream,
145                  N_("set upstream for git pull/fetch")),
146         OPT_BOOL('a', "append", &append,
147                  N_("append to .git/FETCH_HEAD instead of overwriting")),
148         OPT_BOOL(0, "atomic", &atomic_fetch,
149                  N_("use atomic transaction to update references")),
150         OPT_STRING(0, "upload-pack", &upload_pack, N_("path"),
151                    N_("path to upload pack on remote end")),
152         OPT__FORCE(&force, N_("force overwrite of local reference"), 0),
153         OPT_BOOL('m', "multiple", &multiple,
154                  N_("fetch from multiple remotes")),
155         OPT_SET_INT('t', "tags", &tags,
156                     N_("fetch all tags and associated objects"), TAGS_SET),
157         OPT_SET_INT('n', NULL, &tags,
158                     N_("do not fetch all tags (--no-tags)"), TAGS_UNSET),
159         OPT_INTEGER('j', "jobs", &max_jobs,
160                     N_("number of submodules fetched in parallel")),
161         OPT_BOOL('p', "prune", &prune,
162                  N_("prune remote-tracking branches no longer on remote")),
163         OPT_BOOL('P', "prune-tags", &prune_tags,
164                  N_("prune local tags no longer on remote and clobber changed tags")),
165         OPT_CALLBACK_F(0, "recurse-submodules", &recurse_submodules, N_("on-demand"),
166                     N_("control recursive fetching of submodules"),
167                     PARSE_OPT_OPTARG, option_fetch_parse_recurse_submodules),
168         OPT_BOOL(0, "dry-run", &dry_run,
169                  N_("dry run")),
170         OPT_BOOL(0, "write-fetch-head", &write_fetch_head,
171                  N_("write fetched references to the FETCH_HEAD file")),
172         OPT_BOOL('k', "keep", &keep, N_("keep downloaded pack")),
173         OPT_BOOL('u', "update-head-ok", &update_head_ok,
174                     N_("allow updating of HEAD ref")),
175         OPT_BOOL(0, "progress", &progress, N_("force progress reporting")),
176         OPT_STRING(0, "depth", &depth, N_("depth"),
177                    N_("deepen history of shallow clone")),
178         OPT_STRING(0, "shallow-since", &deepen_since, N_("time"),
179                    N_("deepen history of shallow repository based on time")),
180         OPT_STRING_LIST(0, "shallow-exclude", &deepen_not, N_("revision"),
181                         N_("deepen history of shallow clone, excluding rev")),
182         OPT_INTEGER(0, "deepen", &deepen_relative,
183                     N_("deepen history of shallow clone")),
184         OPT_SET_INT_F(0, "unshallow", &unshallow,
185                       N_("convert to a complete repository"),
186                       1, PARSE_OPT_NONEG),
187         { OPTION_STRING, 0, "submodule-prefix", &submodule_prefix, N_("dir"),
188                    N_("prepend this to submodule path output"), PARSE_OPT_HIDDEN },
189         OPT_CALLBACK_F(0, "recurse-submodules-default",
190                    &recurse_submodules_default, N_("on-demand"),
191                    N_("default for recursive fetching of submodules "
192                       "(lower priority than config files)"),
193                    PARSE_OPT_HIDDEN, option_fetch_parse_recurse_submodules),
194         OPT_BOOL(0, "update-shallow", &update_shallow,
195                  N_("accept refs that update .git/shallow")),
196         OPT_CALLBACK_F(0, "refmap", NULL, N_("refmap"),
197                        N_("specify fetch refmap"), PARSE_OPT_NONEG, parse_refmap_arg),
198         OPT_STRING_LIST('o', "server-option", &server_options, N_("server-specific"), N_("option to transmit")),
199         OPT_SET_INT('4', "ipv4", &family, N_("use IPv4 addresses only"),
200                         TRANSPORT_FAMILY_IPV4),
201         OPT_SET_INT('6', "ipv6", &family, N_("use IPv6 addresses only"),
202                         TRANSPORT_FAMILY_IPV6),
203         OPT_STRING_LIST(0, "negotiation-tip", &negotiation_tip, N_("revision"),
204                         N_("report that we have only objects reachable from this object")),
205         OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
206         OPT_BOOL(0, "auto-maintenance", &enable_auto_gc,
207                  N_("run 'maintenance --auto' after fetching")),
208         OPT_BOOL(0, "auto-gc", &enable_auto_gc,
209                  N_("run 'maintenance --auto' after fetching")),
210         OPT_BOOL(0, "show-forced-updates", &fetch_show_forced_updates,
211                  N_("check for forced-updates on all updated branches")),
212         OPT_BOOL(0, "write-commit-graph", &fetch_write_commit_graph,
213                  N_("write the commit-graph after fetching")),
214         OPT_BOOL(0, "stdin", &stdin_refspecs,
215                  N_("accept refspecs from stdin")),
216         OPT_END()
217 };
218
219 static void unlock_pack(void)
220 {
221         if (gtransport)
222                 transport_unlock_pack(gtransport);
223         if (gsecondary)
224                 transport_unlock_pack(gsecondary);
225 }
226
227 static void unlock_pack_on_signal(int signo)
228 {
229         unlock_pack();
230         sigchain_pop(signo);
231         raise(signo);
232 }
233
234 static void add_merge_config(struct ref **head,
235                            const struct ref *remote_refs,
236                            struct branch *branch,
237                            struct ref ***tail)
238 {
239         int i;
240
241         for (i = 0; i < branch->merge_nr; i++) {
242                 struct ref *rm, **old_tail = *tail;
243                 struct refspec_item refspec;
244
245                 for (rm = *head; rm; rm = rm->next) {
246                         if (branch_merge_matches(branch, i, rm->name)) {
247                                 rm->fetch_head_status = FETCH_HEAD_MERGE;
248                                 break;
249                         }
250                 }
251                 if (rm)
252                         continue;
253
254                 /*
255                  * Not fetched to a remote-tracking branch?  We need to fetch
256                  * it anyway to allow this branch's "branch.$name.merge"
257                  * to be honored by 'git pull', but we do not have to
258                  * fail if branch.$name.merge is misconfigured to point
259                  * at a nonexisting branch.  If we were indeed called by
260                  * 'git pull', it will notice the misconfiguration because
261                  * there is no entry in the resulting FETCH_HEAD marked
262                  * for merging.
263                  */
264                 memset(&refspec, 0, sizeof(refspec));
265                 refspec.src = branch->merge[i]->src;
266                 get_fetch_map(remote_refs, &refspec, tail, 1);
267                 for (rm = *old_tail; rm; rm = rm->next)
268                         rm->fetch_head_status = FETCH_HEAD_MERGE;
269         }
270 }
271
272 static void create_fetch_oidset(struct ref **head, struct oidset *out)
273 {
274         struct ref *rm = *head;
275         while (rm) {
276                 oidset_insert(out, &rm->old_oid);
277                 rm = rm->next;
278         }
279 }
280
281 struct refname_hash_entry {
282         struct hashmap_entry ent;
283         struct object_id oid;
284         int ignore;
285         char refname[FLEX_ARRAY];
286 };
287
288 static int refname_hash_entry_cmp(const void *hashmap_cmp_fn_data,
289                                   const struct hashmap_entry *eptr,
290                                   const struct hashmap_entry *entry_or_key,
291                                   const void *keydata)
292 {
293         const struct refname_hash_entry *e1, *e2;
294
295         e1 = container_of(eptr, const struct refname_hash_entry, ent);
296         e2 = container_of(entry_or_key, const struct refname_hash_entry, ent);
297         return strcmp(e1->refname, keydata ? keydata : e2->refname);
298 }
299
300 static struct refname_hash_entry *refname_hash_add(struct hashmap *map,
301                                                    const char *refname,
302                                                    const struct object_id *oid)
303 {
304         struct refname_hash_entry *ent;
305         size_t len = strlen(refname);
306
307         FLEX_ALLOC_MEM(ent, refname, refname, len);
308         hashmap_entry_init(&ent->ent, strhash(refname));
309         oidcpy(&ent->oid, oid);
310         hashmap_add(map, &ent->ent);
311         return ent;
312 }
313
314 static int add_one_refname(const char *refname,
315                            const struct object_id *oid,
316                            int flag, void *cbdata)
317 {
318         struct hashmap *refname_map = cbdata;
319
320         (void) refname_hash_add(refname_map, refname, oid);
321         return 0;
322 }
323
324 static void refname_hash_init(struct hashmap *map)
325 {
326         hashmap_init(map, refname_hash_entry_cmp, NULL, 0);
327 }
328
329 static int refname_hash_exists(struct hashmap *map, const char *refname)
330 {
331         return !!hashmap_get_from_hash(map, strhash(refname), refname);
332 }
333
334 static void clear_item(struct refname_hash_entry *item)
335 {
336         item->ignore = 1;
337 }
338
339 static void find_non_local_tags(const struct ref *refs,
340                                 struct ref **head,
341                                 struct ref ***tail)
342 {
343         struct hashmap existing_refs;
344         struct hashmap remote_refs;
345         struct oidset fetch_oids = OIDSET_INIT;
346         struct string_list remote_refs_list = STRING_LIST_INIT_NODUP;
347         struct string_list_item *remote_ref_item;
348         const struct ref *ref;
349         struct refname_hash_entry *item = NULL;
350         const int quick_flags = OBJECT_INFO_QUICK | OBJECT_INFO_SKIP_FETCH_OBJECT;
351
352         refname_hash_init(&existing_refs);
353         refname_hash_init(&remote_refs);
354         create_fetch_oidset(head, &fetch_oids);
355
356         for_each_ref(add_one_refname, &existing_refs);
357         for (ref = refs; ref; ref = ref->next) {
358                 if (!starts_with(ref->name, "refs/tags/"))
359                         continue;
360
361                 /*
362                  * The peeled ref always follows the matching base
363                  * ref, so if we see a peeled ref that we don't want
364                  * to fetch then we can mark the ref entry in the list
365                  * as one to ignore by setting util to NULL.
366                  */
367                 if (ends_with(ref->name, "^{}")) {
368                         if (item &&
369                             !has_object_file_with_flags(&ref->old_oid, quick_flags) &&
370                             !oidset_contains(&fetch_oids, &ref->old_oid) &&
371                             !has_object_file_with_flags(&item->oid, quick_flags) &&
372                             !oidset_contains(&fetch_oids, &item->oid))
373                                 clear_item(item);
374                         item = NULL;
375                         continue;
376                 }
377
378                 /*
379                  * If item is non-NULL here, then we previously saw a
380                  * ref not followed by a peeled reference, so we need
381                  * to check if it is a lightweight tag that we want to
382                  * fetch.
383                  */
384                 if (item &&
385                     !has_object_file_with_flags(&item->oid, quick_flags) &&
386                     !oidset_contains(&fetch_oids, &item->oid))
387                         clear_item(item);
388
389                 item = NULL;
390
391                 /* skip duplicates and refs that we already have */
392                 if (refname_hash_exists(&remote_refs, ref->name) ||
393                     refname_hash_exists(&existing_refs, ref->name))
394                         continue;
395
396                 item = refname_hash_add(&remote_refs, ref->name, &ref->old_oid);
397                 string_list_insert(&remote_refs_list, ref->name);
398         }
399         hashmap_clear_and_free(&existing_refs, struct refname_hash_entry, ent);
400
401         /*
402          * We may have a final lightweight tag that needs to be
403          * checked to see if it needs fetching.
404          */
405         if (item &&
406             !has_object_file_with_flags(&item->oid, quick_flags) &&
407             !oidset_contains(&fetch_oids, &item->oid))
408                 clear_item(item);
409
410         /*
411          * For all the tags in the remote_refs_list,
412          * add them to the list of refs to be fetched
413          */
414         for_each_string_list_item(remote_ref_item, &remote_refs_list) {
415                 const char *refname = remote_ref_item->string;
416                 struct ref *rm;
417                 unsigned int hash = strhash(refname);
418
419                 item = hashmap_get_entry_from_hash(&remote_refs, hash, refname,
420                                         struct refname_hash_entry, ent);
421                 if (!item)
422                         BUG("unseen remote ref?");
423
424                 /* Unless we have already decided to ignore this item... */
425                 if (item->ignore)
426                         continue;
427
428                 rm = alloc_ref(item->refname);
429                 rm->peer_ref = alloc_ref(item->refname);
430                 oidcpy(&rm->old_oid, &item->oid);
431                 **tail = rm;
432                 *tail = &rm->next;
433         }
434         hashmap_clear_and_free(&remote_refs, struct refname_hash_entry, ent);
435         string_list_clear(&remote_refs_list, 0);
436         oidset_clear(&fetch_oids);
437 }
438
439 static struct ref *get_ref_map(struct remote *remote,
440                                const struct ref *remote_refs,
441                                struct refspec *rs,
442                                int tags, int *autotags)
443 {
444         int i;
445         struct ref *rm;
446         struct ref *ref_map = NULL;
447         struct ref **tail = &ref_map;
448
449         /* opportunistically-updated references: */
450         struct ref *orefs = NULL, **oref_tail = &orefs;
451
452         struct hashmap existing_refs;
453         int existing_refs_populated = 0;
454
455         if (rs->nr) {
456                 struct refspec *fetch_refspec;
457
458                 for (i = 0; i < rs->nr; i++) {
459                         get_fetch_map(remote_refs, &rs->items[i], &tail, 0);
460                         if (rs->items[i].dst && rs->items[i].dst[0])
461                                 *autotags = 1;
462                 }
463                 /* Merge everything on the command line (but not --tags) */
464                 for (rm = ref_map; rm; rm = rm->next)
465                         rm->fetch_head_status = FETCH_HEAD_MERGE;
466
467                 /*
468                  * For any refs that we happen to be fetching via
469                  * command-line arguments, the destination ref might
470                  * have been missing or have been different than the
471                  * remote-tracking ref that would be derived from the
472                  * configured refspec.  In these cases, we want to
473                  * take the opportunity to update their configured
474                  * remote-tracking reference.  However, we do not want
475                  * to mention these entries in FETCH_HEAD at all, as
476                  * they would simply be duplicates of existing
477                  * entries, so we set them FETCH_HEAD_IGNORE below.
478                  *
479                  * We compute these entries now, based only on the
480                  * refspecs specified on the command line.  But we add
481                  * them to the list following the refspecs resulting
482                  * from the tags option so that one of the latter,
483                  * which has FETCH_HEAD_NOT_FOR_MERGE, is not removed
484                  * by ref_remove_duplicates() in favor of one of these
485                  * opportunistic entries with FETCH_HEAD_IGNORE.
486                  */
487                 if (refmap.nr)
488                         fetch_refspec = &refmap;
489                 else
490                         fetch_refspec = &remote->fetch;
491
492                 for (i = 0; i < fetch_refspec->nr; i++)
493                         get_fetch_map(ref_map, &fetch_refspec->items[i], &oref_tail, 1);
494         } else if (refmap.nr) {
495                 die("--refmap option is only meaningful with command-line refspec(s).");
496         } else {
497                 /* Use the defaults */
498                 struct branch *branch = branch_get(NULL);
499                 int has_merge = branch_has_merge_config(branch);
500                 if (remote &&
501                     (remote->fetch.nr ||
502                      /* Note: has_merge implies non-NULL branch->remote_name */
503                      (has_merge && !strcmp(branch->remote_name, remote->name)))) {
504                         for (i = 0; i < remote->fetch.nr; i++) {
505                                 get_fetch_map(remote_refs, &remote->fetch.items[i], &tail, 0);
506                                 if (remote->fetch.items[i].dst &&
507                                     remote->fetch.items[i].dst[0])
508                                         *autotags = 1;
509                                 if (!i && !has_merge && ref_map &&
510                                     !remote->fetch.items[0].pattern)
511                                         ref_map->fetch_head_status = FETCH_HEAD_MERGE;
512                         }
513                         /*
514                          * if the remote we're fetching from is the same
515                          * as given in branch.<name>.remote, we add the
516                          * ref given in branch.<name>.merge, too.
517                          *
518                          * Note: has_merge implies non-NULL branch->remote_name
519                          */
520                         if (has_merge &&
521                             !strcmp(branch->remote_name, remote->name))
522                                 add_merge_config(&ref_map, remote_refs, branch, &tail);
523                 } else {
524                         ref_map = get_remote_ref(remote_refs, "HEAD");
525                         if (!ref_map)
526                                 die(_("Couldn't find remote ref HEAD"));
527                         ref_map->fetch_head_status = FETCH_HEAD_MERGE;
528                         tail = &ref_map->next;
529                 }
530         }
531
532         if (tags == TAGS_SET)
533                 /* also fetch all tags */
534                 get_fetch_map(remote_refs, tag_refspec, &tail, 0);
535         else if (tags == TAGS_DEFAULT && *autotags)
536                 find_non_local_tags(remote_refs, &ref_map, &tail);
537
538         /* Now append any refs to be updated opportunistically: */
539         *tail = orefs;
540         for (rm = orefs; rm; rm = rm->next) {
541                 rm->fetch_head_status = FETCH_HEAD_IGNORE;
542                 tail = &rm->next;
543         }
544
545         /*
546          * apply negative refspecs first, before we remove duplicates. This is
547          * necessary as negative refspecs might remove an otherwise conflicting
548          * duplicate.
549          */
550         if (rs->nr)
551                 ref_map = apply_negative_refspecs(ref_map, rs);
552         else
553                 ref_map = apply_negative_refspecs(ref_map, &remote->fetch);
554
555         ref_map = ref_remove_duplicates(ref_map);
556
557         for (rm = ref_map; rm; rm = rm->next) {
558                 if (rm->peer_ref) {
559                         const char *refname = rm->peer_ref->name;
560                         struct refname_hash_entry *peer_item;
561                         unsigned int hash = strhash(refname);
562
563                         if (!existing_refs_populated) {
564                                 refname_hash_init(&existing_refs);
565                                 for_each_ref(add_one_refname, &existing_refs);
566                                 existing_refs_populated = 1;
567                         }
568
569                         peer_item = hashmap_get_entry_from_hash(&existing_refs,
570                                                 hash, refname,
571                                                 struct refname_hash_entry, ent);
572                         if (peer_item) {
573                                 struct object_id *old_oid = &peer_item->oid;
574                                 oidcpy(&rm->peer_ref->old_oid, old_oid);
575                         }
576                 }
577         }
578         if (existing_refs_populated)
579                 hashmap_clear_and_free(&existing_refs, struct refname_hash_entry, ent);
580
581         return ref_map;
582 }
583
584 #define STORE_REF_ERROR_OTHER 1
585 #define STORE_REF_ERROR_DF_CONFLICT 2
586
587 static int s_update_ref(const char *action,
588                         struct ref *ref,
589                         struct ref_transaction *transaction,
590                         int check_old)
591 {
592         char *msg;
593         char *rla = getenv("GIT_REFLOG_ACTION");
594         struct ref_transaction *our_transaction = NULL;
595         struct strbuf err = STRBUF_INIT;
596         int ret;
597
598         if (dry_run)
599                 return 0;
600         if (!rla)
601                 rla = default_rla.buf;
602         msg = xstrfmt("%s: %s", rla, action);
603
604         /*
605          * If no transaction was passed to us, we manage the transaction
606          * ourselves. Otherwise, we trust the caller to handle the transaction
607          * lifecycle.
608          */
609         if (!transaction) {
610                 transaction = our_transaction = ref_transaction_begin(&err);
611                 if (!transaction) {
612                         ret = STORE_REF_ERROR_OTHER;
613                         goto out;
614                 }
615         }
616
617         ret = ref_transaction_update(transaction, ref->name, &ref->new_oid,
618                                      check_old ? &ref->old_oid : NULL,
619                                      0, msg, &err);
620         if (ret) {
621                 ret = STORE_REF_ERROR_OTHER;
622                 goto out;
623         }
624
625         if (our_transaction) {
626                 switch (ref_transaction_commit(our_transaction, &err)) {
627                 case 0:
628                         break;
629                 case TRANSACTION_NAME_CONFLICT:
630                         ret = STORE_REF_ERROR_DF_CONFLICT;
631                         goto out;
632                 default:
633                         ret = STORE_REF_ERROR_OTHER;
634                         goto out;
635                 }
636         }
637
638 out:
639         ref_transaction_free(our_transaction);
640         if (ret)
641                 error("%s", err.buf);
642         strbuf_release(&err);
643         free(msg);
644         return ret;
645 }
646
647 static int refcol_width = 10;
648 static int compact_format;
649
650 static void adjust_refcol_width(const struct ref *ref)
651 {
652         int max, rlen, llen, len;
653
654         /* uptodate lines are only shown on high verbosity level */
655         if (!verbosity && oideq(&ref->peer_ref->old_oid, &ref->old_oid))
656                 return;
657
658         max    = term_columns();
659         rlen   = utf8_strwidth(prettify_refname(ref->name));
660
661         llen   = utf8_strwidth(prettify_refname(ref->peer_ref->name));
662
663         /*
664          * rough estimation to see if the output line is too long and
665          * should not be counted (we can't do precise calculation
666          * anyway because we don't know if the error explanation part
667          * will be printed in update_local_ref)
668          */
669         if (compact_format) {
670                 llen = 0;
671                 max = max * 2 / 3;
672         }
673         len = 21 /* flag and summary */ + rlen + 4 /* -> */ + llen;
674         if (len >= max)
675                 return;
676
677         /*
678          * Not precise calculation for compact mode because '*' can
679          * appear on the left hand side of '->' and shrink the column
680          * back.
681          */
682         if (refcol_width < rlen)
683                 refcol_width = rlen;
684 }
685
686 static void prepare_format_display(struct ref *ref_map)
687 {
688         struct ref *rm;
689         const char *format = "full";
690
691         git_config_get_string_tmp("fetch.output", &format);
692         if (!strcasecmp(format, "full"))
693                 compact_format = 0;
694         else if (!strcasecmp(format, "compact"))
695                 compact_format = 1;
696         else
697                 die(_("configuration fetch.output contains invalid value %s"),
698                     format);
699
700         for (rm = ref_map; rm; rm = rm->next) {
701                 if (rm->status == REF_STATUS_REJECT_SHALLOW ||
702                     !rm->peer_ref ||
703                     !strcmp(rm->name, "HEAD"))
704                         continue;
705
706                 adjust_refcol_width(rm);
707         }
708 }
709
710 static void print_remote_to_local(struct strbuf *display,
711                                   const char *remote, const char *local)
712 {
713         strbuf_addf(display, "%-*s -> %s", refcol_width, remote, local);
714 }
715
716 static int find_and_replace(struct strbuf *haystack,
717                             const char *needle,
718                             const char *placeholder)
719 {
720         const char *p = NULL;
721         int plen, nlen;
722
723         nlen = strlen(needle);
724         if (ends_with(haystack->buf, needle))
725                 p = haystack->buf + haystack->len - nlen;
726         else
727                 p = strstr(haystack->buf, needle);
728         if (!p)
729                 return 0;
730
731         if (p > haystack->buf && p[-1] != '/')
732                 return 0;
733
734         plen = strlen(p);
735         if (plen > nlen && p[nlen] != '/')
736                 return 0;
737
738         strbuf_splice(haystack, p - haystack->buf, nlen,
739                       placeholder, strlen(placeholder));
740         return 1;
741 }
742
743 static void print_compact(struct strbuf *display,
744                           const char *remote, const char *local)
745 {
746         struct strbuf r = STRBUF_INIT;
747         struct strbuf l = STRBUF_INIT;
748
749         if (!strcmp(remote, local)) {
750                 strbuf_addf(display, "%-*s -> *", refcol_width, remote);
751                 return;
752         }
753
754         strbuf_addstr(&r, remote);
755         strbuf_addstr(&l, local);
756
757         if (!find_and_replace(&r, local, "*"))
758                 find_and_replace(&l, remote, "*");
759         print_remote_to_local(display, r.buf, l.buf);
760
761         strbuf_release(&r);
762         strbuf_release(&l);
763 }
764
765 static void format_display(struct strbuf *display, char code,
766                            const char *summary, const char *error,
767                            const char *remote, const char *local,
768                            int summary_width)
769 {
770         int width = (summary_width + strlen(summary) - gettext_width(summary));
771
772         strbuf_addf(display, "%c %-*s ", code, width, summary);
773         if (!compact_format)
774                 print_remote_to_local(display, remote, local);
775         else
776                 print_compact(display, remote, local);
777         if (error)
778                 strbuf_addf(display, "  (%s)", error);
779 }
780
781 static int update_local_ref(struct ref *ref,
782                             struct ref_transaction *transaction,
783                             const char *remote,
784                             const struct ref *remote_ref,
785                             struct strbuf *display,
786                             int summary_width)
787 {
788         struct commit *current = NULL, *updated;
789         enum object_type type;
790         struct branch *current_branch = branch_get(NULL);
791         const char *pretty_ref = prettify_refname(ref->name);
792         int fast_forward = 0;
793
794         type = oid_object_info(the_repository, &ref->new_oid, NULL);
795         if (type < 0)
796                 die(_("object %s not found"), oid_to_hex(&ref->new_oid));
797
798         if (oideq(&ref->old_oid, &ref->new_oid)) {
799                 if (verbosity > 0)
800                         format_display(display, '=', _("[up to date]"), NULL,
801                                        remote, pretty_ref, summary_width);
802                 return 0;
803         }
804
805         if (current_branch &&
806             !strcmp(ref->name, current_branch->name) &&
807             !(update_head_ok || is_bare_repository()) &&
808             !is_null_oid(&ref->old_oid)) {
809                 /*
810                  * If this is the head, and it's not okay to update
811                  * the head, and the old value of the head isn't empty...
812                  */
813                 format_display(display, '!', _("[rejected]"),
814                                _("can't fetch in current branch"),
815                                remote, pretty_ref, summary_width);
816                 return 1;
817         }
818
819         if (!is_null_oid(&ref->old_oid) &&
820             starts_with(ref->name, "refs/tags/")) {
821                 if (force || ref->force) {
822                         int r;
823                         r = s_update_ref("updating tag", ref, transaction, 0);
824                         format_display(display, r ? '!' : 't', _("[tag update]"),
825                                        r ? _("unable to update local ref") : NULL,
826                                        remote, pretty_ref, summary_width);
827                         return r;
828                 } else {
829                         format_display(display, '!', _("[rejected]"), _("would clobber existing tag"),
830                                        remote, pretty_ref, summary_width);
831                         return 1;
832                 }
833         }
834
835         current = lookup_commit_reference_gently(the_repository,
836                                                  &ref->old_oid, 1);
837         updated = lookup_commit_reference_gently(the_repository,
838                                                  &ref->new_oid, 1);
839         if (!current || !updated) {
840                 const char *msg;
841                 const char *what;
842                 int r;
843                 /*
844                  * Nicely describe the new ref we're fetching.
845                  * Base this on the remote's ref name, as it's
846                  * more likely to follow a standard layout.
847                  */
848                 const char *name = remote_ref ? remote_ref->name : "";
849                 if (starts_with(name, "refs/tags/")) {
850                         msg = "storing tag";
851                         what = _("[new tag]");
852                 } else if (starts_with(name, "refs/heads/")) {
853                         msg = "storing head";
854                         what = _("[new branch]");
855                 } else {
856                         msg = "storing ref";
857                         what = _("[new ref]");
858                 }
859
860                 r = s_update_ref(msg, ref, transaction, 0);
861                 format_display(display, r ? '!' : '*', what,
862                                r ? _("unable to update local ref") : NULL,
863                                remote, pretty_ref, summary_width);
864                 return r;
865         }
866
867         if (fetch_show_forced_updates) {
868                 uint64_t t_before = getnanotime();
869                 fast_forward = in_merge_bases(current, updated);
870                 forced_updates_ms += (getnanotime() - t_before) / 1000000;
871         } else {
872                 fast_forward = 1;
873         }
874
875         if (fast_forward) {
876                 struct strbuf quickref = STRBUF_INIT;
877                 int r;
878
879                 strbuf_add_unique_abbrev(&quickref, &current->object.oid, DEFAULT_ABBREV);
880                 strbuf_addstr(&quickref, "..");
881                 strbuf_add_unique_abbrev(&quickref, &ref->new_oid, DEFAULT_ABBREV);
882                 r = s_update_ref("fast-forward", ref, transaction, 1);
883                 format_display(display, r ? '!' : ' ', quickref.buf,
884                                r ? _("unable to update local ref") : NULL,
885                                remote, pretty_ref, summary_width);
886                 strbuf_release(&quickref);
887                 return r;
888         } else if (force || ref->force) {
889                 struct strbuf quickref = STRBUF_INIT;
890                 int r;
891                 strbuf_add_unique_abbrev(&quickref, &current->object.oid, DEFAULT_ABBREV);
892                 strbuf_addstr(&quickref, "...");
893                 strbuf_add_unique_abbrev(&quickref, &ref->new_oid, DEFAULT_ABBREV);
894                 r = s_update_ref("forced-update", ref, transaction, 1);
895                 format_display(display, r ? '!' : '+', quickref.buf,
896                                r ? _("unable to update local ref") : _("forced update"),
897                                remote, pretty_ref, summary_width);
898                 strbuf_release(&quickref);
899                 return r;
900         } else {
901                 format_display(display, '!', _("[rejected]"), _("non-fast-forward"),
902                                remote, pretty_ref, summary_width);
903                 return 1;
904         }
905 }
906
907 static int iterate_ref_map(void *cb_data, struct object_id *oid)
908 {
909         struct ref **rm = cb_data;
910         struct ref *ref = *rm;
911
912         while (ref && ref->status == REF_STATUS_REJECT_SHALLOW)
913                 ref = ref->next;
914         if (!ref)
915                 return -1; /* end of the list */
916         *rm = ref->next;
917         oidcpy(oid, &ref->old_oid);
918         return 0;
919 }
920
921 struct fetch_head {
922         FILE *fp;
923         struct strbuf buf;
924 };
925
926 static int open_fetch_head(struct fetch_head *fetch_head)
927 {
928         const char *filename = git_path_fetch_head(the_repository);
929
930         if (write_fetch_head) {
931                 fetch_head->fp = fopen(filename, "a");
932                 if (!fetch_head->fp)
933                         return error_errno(_("cannot open %s"), filename);
934                 strbuf_init(&fetch_head->buf, 0);
935         } else {
936                 fetch_head->fp = NULL;
937         }
938
939         return 0;
940 }
941
942 static void append_fetch_head(struct fetch_head *fetch_head,
943                               const struct object_id *old_oid,
944                               enum fetch_head_status fetch_head_status,
945                               const char *note,
946                               const char *url, size_t url_len)
947 {
948         char old_oid_hex[GIT_MAX_HEXSZ + 1];
949         const char *merge_status_marker;
950         size_t i;
951
952         if (!fetch_head->fp)
953                 return;
954
955         switch (fetch_head_status) {
956         case FETCH_HEAD_NOT_FOR_MERGE:
957                 merge_status_marker = "not-for-merge";
958                 break;
959         case FETCH_HEAD_MERGE:
960                 merge_status_marker = "";
961                 break;
962         default:
963                 /* do not write anything to FETCH_HEAD */
964                 return;
965         }
966
967         strbuf_addf(&fetch_head->buf, "%s\t%s\t%s",
968                     oid_to_hex_r(old_oid_hex, old_oid), merge_status_marker, note);
969         for (i = 0; i < url_len; ++i)
970                 if ('\n' == url[i])
971                         strbuf_addstr(&fetch_head->buf, "\\n");
972                 else
973                         strbuf_addch(&fetch_head->buf, url[i]);
974         strbuf_addch(&fetch_head->buf, '\n');
975
976         /*
977          * When using an atomic fetch, we do not want to update FETCH_HEAD if
978          * any of the reference updates fails. We thus have to write all
979          * updates to a buffer first and only commit it as soon as all
980          * references have been successfully updated.
981          */
982         if (!atomic_fetch) {
983                 strbuf_write(&fetch_head->buf, fetch_head->fp);
984                 strbuf_reset(&fetch_head->buf);
985         }
986 }
987
988 static void commit_fetch_head(struct fetch_head *fetch_head)
989 {
990         if (!fetch_head->fp || !atomic_fetch)
991                 return;
992         strbuf_write(&fetch_head->buf, fetch_head->fp);
993 }
994
995 static void close_fetch_head(struct fetch_head *fetch_head)
996 {
997         if (!fetch_head->fp)
998                 return;
999
1000         fclose(fetch_head->fp);
1001         strbuf_release(&fetch_head->buf);
1002 }
1003
1004 static const char warn_show_forced_updates[] =
1005 N_("Fetch normally indicates which branches had a forced update,\n"
1006    "but that check has been disabled. To re-enable, use '--show-forced-updates'\n"
1007    "flag or run 'git config fetch.showForcedUpdates true'.");
1008 static const char warn_time_show_forced_updates[] =
1009 N_("It took %.2f seconds to check forced updates. You can use\n"
1010    "'--no-show-forced-updates' or run 'git config fetch.showForcedUpdates false'\n"
1011    " to avoid this check.\n");
1012
1013 static int store_updated_refs(const char *raw_url, const char *remote_name,
1014                               int connectivity_checked, struct ref *ref_map)
1015 {
1016         struct fetch_head fetch_head;
1017         struct commit *commit;
1018         int url_len, i, rc = 0;
1019         struct strbuf note = STRBUF_INIT, err = STRBUF_INIT;
1020         struct ref_transaction *transaction = NULL;
1021         const char *what, *kind;
1022         struct ref *rm;
1023         char *url;
1024         int want_status;
1025         int summary_width = transport_summary_width(ref_map);
1026
1027         rc = open_fetch_head(&fetch_head);
1028         if (rc)
1029                 return -1;
1030
1031         if (raw_url)
1032                 url = transport_anonymize_url(raw_url);
1033         else
1034                 url = xstrdup("foreign");
1035
1036         if (!connectivity_checked) {
1037                 struct check_connected_options opt = CHECK_CONNECTED_INIT;
1038
1039                 rm = ref_map;
1040                 if (check_connected(iterate_ref_map, &rm, &opt)) {
1041                         rc = error(_("%s did not send all necessary objects\n"), url);
1042                         goto abort;
1043                 }
1044         }
1045
1046         if (atomic_fetch) {
1047                 transaction = ref_transaction_begin(&err);
1048                 if (!transaction) {
1049                         error("%s", err.buf);
1050                         goto abort;
1051                 }
1052         }
1053
1054         prepare_format_display(ref_map);
1055
1056         /*
1057          * We do a pass for each fetch_head_status type in their enum order, so
1058          * merged entries are written before not-for-merge. That lets readers
1059          * use FETCH_HEAD as a refname to refer to the ref to be merged.
1060          */
1061         for (want_status = FETCH_HEAD_MERGE;
1062              want_status <= FETCH_HEAD_IGNORE;
1063              want_status++) {
1064                 for (rm = ref_map; rm; rm = rm->next) {
1065                         struct ref *ref = NULL;
1066
1067                         if (rm->status == REF_STATUS_REJECT_SHALLOW) {
1068                                 if (want_status == FETCH_HEAD_MERGE)
1069                                         warning(_("reject %s because shallow roots are not allowed to be updated"),
1070                                                 rm->peer_ref ? rm->peer_ref->name : rm->name);
1071                                 continue;
1072                         }
1073
1074                         commit = lookup_commit_reference_gently(the_repository,
1075                                                                 &rm->old_oid,
1076                                                                 1);
1077                         if (!commit)
1078                                 rm->fetch_head_status = FETCH_HEAD_NOT_FOR_MERGE;
1079
1080                         if (rm->fetch_head_status != want_status)
1081                                 continue;
1082
1083                         if (rm->peer_ref) {
1084                                 ref = alloc_ref(rm->peer_ref->name);
1085                                 oidcpy(&ref->old_oid, &rm->peer_ref->old_oid);
1086                                 oidcpy(&ref->new_oid, &rm->old_oid);
1087                                 ref->force = rm->peer_ref->force;
1088                         }
1089
1090                         if (recurse_submodules != RECURSE_SUBMODULES_OFF &&
1091                             (!rm->peer_ref || !oideq(&ref->old_oid, &ref->new_oid))) {
1092                                 check_for_new_submodule_commits(&rm->old_oid);
1093                         }
1094
1095                         if (!strcmp(rm->name, "HEAD")) {
1096                                 kind = "";
1097                                 what = "";
1098                         }
1099                         else if (skip_prefix(rm->name, "refs/heads/", &what))
1100                                 kind = "branch";
1101                         else if (skip_prefix(rm->name, "refs/tags/", &what))
1102                                 kind = "tag";
1103                         else if (skip_prefix(rm->name, "refs/remotes/", &what))
1104                                 kind = "remote-tracking branch";
1105                         else {
1106                                 kind = "";
1107                                 what = rm->name;
1108                         }
1109
1110                         url_len = strlen(url);
1111                         for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
1112                                 ;
1113                         url_len = i + 1;
1114                         if (4 < i && !strncmp(".git", url + i - 3, 4))
1115                                 url_len = i - 3;
1116
1117                         strbuf_reset(&note);
1118                         if (*what) {
1119                                 if (*kind)
1120                                         strbuf_addf(&note, "%s ", kind);
1121                                 strbuf_addf(&note, "'%s' of ", what);
1122                         }
1123
1124                         append_fetch_head(&fetch_head, &rm->old_oid,
1125                                           rm->fetch_head_status,
1126                                           note.buf, url, url_len);
1127
1128                         strbuf_reset(&note);
1129                         if (ref) {
1130                                 rc |= update_local_ref(ref, transaction, what,
1131                                                        rm, &note, summary_width);
1132                                 free(ref);
1133                         } else if (write_fetch_head || dry_run) {
1134                                 /*
1135                                  * Display fetches written to FETCH_HEAD (or
1136                                  * would be written to FETCH_HEAD, if --dry-run
1137                                  * is set).
1138                                  */
1139                                 format_display(&note, '*',
1140                                                *kind ? kind : "branch", NULL,
1141                                                *what ? what : "HEAD",
1142                                                "FETCH_HEAD", summary_width);
1143                         }
1144                         if (note.len) {
1145                                 if (verbosity >= 0 && !shown_url) {
1146                                         fprintf(stderr, _("From %.*s\n"),
1147                                                         url_len, url);
1148                                         shown_url = 1;
1149                                 }
1150                                 if (verbosity >= 0)
1151                                         fprintf(stderr, " %s\n", note.buf);
1152                         }
1153                 }
1154         }
1155
1156         if (!rc && transaction) {
1157                 rc = ref_transaction_commit(transaction, &err);
1158                 if (rc) {
1159                         error("%s", err.buf);
1160                         goto abort;
1161                 }
1162         }
1163
1164         if (!rc)
1165                 commit_fetch_head(&fetch_head);
1166
1167         if (rc & STORE_REF_ERROR_DF_CONFLICT)
1168                 error(_("some local refs could not be updated; try running\n"
1169                       " 'git remote prune %s' to remove any old, conflicting "
1170                       "branches"), remote_name);
1171
1172         if (advice_fetch_show_forced_updates) {
1173                 if (!fetch_show_forced_updates) {
1174                         warning(_(warn_show_forced_updates));
1175                 } else if (forced_updates_ms > FORCED_UPDATES_DELAY_WARNING_IN_MS) {
1176                         warning(_(warn_time_show_forced_updates),
1177                                 forced_updates_ms / 1000.0);
1178                 }
1179         }
1180
1181  abort:
1182         strbuf_release(&note);
1183         strbuf_release(&err);
1184         ref_transaction_free(transaction);
1185         free(url);
1186         close_fetch_head(&fetch_head);
1187         return rc;
1188 }
1189
1190 /*
1191  * We would want to bypass the object transfer altogether if
1192  * everything we are going to fetch already exists and is connected
1193  * locally.
1194  */
1195 static int check_exist_and_connected(struct ref *ref_map)
1196 {
1197         struct ref *rm = ref_map;
1198         struct check_connected_options opt = CHECK_CONNECTED_INIT;
1199         struct ref *r;
1200
1201         /*
1202          * If we are deepening a shallow clone we already have these
1203          * objects reachable.  Running rev-list here will return with
1204          * a good (0) exit status and we'll bypass the fetch that we
1205          * really need to perform.  Claiming failure now will ensure
1206          * we perform the network exchange to deepen our history.
1207          */
1208         if (deepen)
1209                 return -1;
1210
1211         /*
1212          * check_connected() allows objects to merely be promised, but
1213          * we need all direct targets to exist.
1214          */
1215         for (r = rm; r; r = r->next) {
1216                 if (!has_object_file_with_flags(&r->old_oid,
1217                                                 OBJECT_INFO_SKIP_FETCH_OBJECT))
1218                         return -1;
1219         }
1220
1221         opt.quiet = 1;
1222         return check_connected(iterate_ref_map, &rm, &opt);
1223 }
1224
1225 static int fetch_refs(struct transport *transport, struct ref *ref_map)
1226 {
1227         int ret = check_exist_and_connected(ref_map);
1228         if (ret) {
1229                 trace2_region_enter("fetch", "fetch_refs", the_repository);
1230                 ret = transport_fetch_refs(transport, ref_map);
1231                 trace2_region_leave("fetch", "fetch_refs", the_repository);
1232         }
1233         if (!ret)
1234                 /*
1235                  * Keep the new pack's ".keep" file around to allow the caller
1236                  * time to update refs to reference the new objects.
1237                  */
1238                 return 0;
1239         transport_unlock_pack(transport);
1240         return ret;
1241 }
1242
1243 /* Update local refs based on the ref values fetched from a remote */
1244 static int consume_refs(struct transport *transport, struct ref *ref_map)
1245 {
1246         int connectivity_checked = transport->smart_options
1247                 ? transport->smart_options->connectivity_checked : 0;
1248         int ret;
1249         trace2_region_enter("fetch", "consume_refs", the_repository);
1250         ret = store_updated_refs(transport->url,
1251                                  transport->remote->name,
1252                                  connectivity_checked,
1253                                  ref_map);
1254         transport_unlock_pack(transport);
1255         trace2_region_leave("fetch", "consume_refs", the_repository);
1256         return ret;
1257 }
1258
1259 static int prune_refs(struct refspec *rs, struct ref *ref_map,
1260                       const char *raw_url)
1261 {
1262         int url_len, i, result = 0;
1263         struct ref *ref, *stale_refs = get_stale_heads(rs, ref_map);
1264         char *url;
1265         int summary_width = transport_summary_width(stale_refs);
1266         const char *dangling_msg = dry_run
1267                 ? _("   (%s will become dangling)")
1268                 : _("   (%s has become dangling)");
1269
1270         if (raw_url)
1271                 url = transport_anonymize_url(raw_url);
1272         else
1273                 url = xstrdup("foreign");
1274
1275         url_len = strlen(url);
1276         for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
1277                 ;
1278
1279         url_len = i + 1;
1280         if (4 < i && !strncmp(".git", url + i - 3, 4))
1281                 url_len = i - 3;
1282
1283         if (!dry_run) {
1284                 struct string_list refnames = STRING_LIST_INIT_NODUP;
1285
1286                 for (ref = stale_refs; ref; ref = ref->next)
1287                         string_list_append(&refnames, ref->name);
1288
1289                 result = delete_refs("fetch: prune", &refnames, 0);
1290                 string_list_clear(&refnames, 0);
1291         }
1292
1293         if (verbosity >= 0) {
1294                 for (ref = stale_refs; ref; ref = ref->next) {
1295                         struct strbuf sb = STRBUF_INIT;
1296                         if (!shown_url) {
1297                                 fprintf(stderr, _("From %.*s\n"), url_len, url);
1298                                 shown_url = 1;
1299                         }
1300                         format_display(&sb, '-', _("[deleted]"), NULL,
1301                                        _("(none)"), prettify_refname(ref->name),
1302                                        summary_width);
1303                         fprintf(stderr, " %s\n",sb.buf);
1304                         strbuf_release(&sb);
1305                         warn_dangling_symref(stderr, dangling_msg, ref->name);
1306                 }
1307         }
1308
1309         free(url);
1310         free_refs(stale_refs);
1311         return result;
1312 }
1313
1314 static void check_not_current_branch(struct ref *ref_map)
1315 {
1316         struct branch *current_branch = branch_get(NULL);
1317
1318         if (is_bare_repository() || !current_branch)
1319                 return;
1320
1321         for (; ref_map; ref_map = ref_map->next)
1322                 if (ref_map->peer_ref && !strcmp(current_branch->refname,
1323                                         ref_map->peer_ref->name))
1324                         die(_("Refusing to fetch into current branch %s "
1325                             "of non-bare repository"), current_branch->refname);
1326 }
1327
1328 static int truncate_fetch_head(void)
1329 {
1330         const char *filename = git_path_fetch_head(the_repository);
1331         FILE *fp = fopen_for_writing(filename);
1332
1333         if (!fp)
1334                 return error_errno(_("cannot open %s"), filename);
1335         fclose(fp);
1336         return 0;
1337 }
1338
1339 static void set_option(struct transport *transport, const char *name, const char *value)
1340 {
1341         int r = transport_set_option(transport, name, value);
1342         if (r < 0)
1343                 die(_("Option \"%s\" value \"%s\" is not valid for %s"),
1344                     name, value, transport->url);
1345         if (r > 0)
1346                 warning(_("Option \"%s\" is ignored for %s\n"),
1347                         name, transport->url);
1348 }
1349
1350
1351 static int add_oid(const char *refname, const struct object_id *oid, int flags,
1352                    void *cb_data)
1353 {
1354         struct oid_array *oids = cb_data;
1355
1356         oid_array_append(oids, oid);
1357         return 0;
1358 }
1359
1360 static void add_negotiation_tips(struct git_transport_options *smart_options)
1361 {
1362         struct oid_array *oids = xcalloc(1, sizeof(*oids));
1363         int i;
1364
1365         for (i = 0; i < negotiation_tip.nr; i++) {
1366                 const char *s = negotiation_tip.items[i].string;
1367                 int old_nr;
1368                 if (!has_glob_specials(s)) {
1369                         struct object_id oid;
1370                         if (get_oid(s, &oid))
1371                                 die("%s is not a valid object", s);
1372                         oid_array_append(oids, &oid);
1373                         continue;
1374                 }
1375                 old_nr = oids->nr;
1376                 for_each_glob_ref(add_oid, s, oids);
1377                 if (old_nr == oids->nr)
1378                         warning("Ignoring --negotiation-tip=%s because it does not match any refs",
1379                                 s);
1380         }
1381         smart_options->negotiation_tips = oids;
1382 }
1383
1384 static struct transport *prepare_transport(struct remote *remote, int deepen)
1385 {
1386         struct transport *transport;
1387
1388         transport = transport_get(remote, NULL);
1389         transport_set_verbosity(transport, verbosity, progress);
1390         transport->family = family;
1391         if (upload_pack)
1392                 set_option(transport, TRANS_OPT_UPLOADPACK, upload_pack);
1393         if (keep)
1394                 set_option(transport, TRANS_OPT_KEEP, "yes");
1395         if (depth)
1396                 set_option(transport, TRANS_OPT_DEPTH, depth);
1397         if (deepen && deepen_since)
1398                 set_option(transport, TRANS_OPT_DEEPEN_SINCE, deepen_since);
1399         if (deepen && deepen_not.nr)
1400                 set_option(transport, TRANS_OPT_DEEPEN_NOT,
1401                            (const char *)&deepen_not);
1402         if (deepen_relative)
1403                 set_option(transport, TRANS_OPT_DEEPEN_RELATIVE, "yes");
1404         if (update_shallow)
1405                 set_option(transport, TRANS_OPT_UPDATE_SHALLOW, "yes");
1406         if (filter_options.choice) {
1407                 const char *spec =
1408                         expand_list_objects_filter_spec(&filter_options);
1409                 set_option(transport, TRANS_OPT_LIST_OBJECTS_FILTER, spec);
1410                 set_option(transport, TRANS_OPT_FROM_PROMISOR, "1");
1411         }
1412         if (negotiation_tip.nr) {
1413                 if (transport->smart_options)
1414                         add_negotiation_tips(transport->smart_options);
1415                 else
1416                         warning("Ignoring --negotiation-tip because the protocol does not support it.");
1417         }
1418         return transport;
1419 }
1420
1421 static void backfill_tags(struct transport *transport, struct ref *ref_map)
1422 {
1423         int cannot_reuse;
1424
1425         /*
1426          * Once we have set TRANS_OPT_DEEPEN_SINCE, we can't unset it
1427          * when remote helper is used (setting it to an empty string
1428          * is not unsetting). We could extend the remote helper
1429          * protocol for that, but for now, just force a new connection
1430          * without deepen-since. Similar story for deepen-not.
1431          */
1432         cannot_reuse = transport->cannot_reuse ||
1433                 deepen_since || deepen_not.nr;
1434         if (cannot_reuse) {
1435                 gsecondary = prepare_transport(transport->remote, 0);
1436                 transport = gsecondary;
1437         }
1438
1439         transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
1440         transport_set_option(transport, TRANS_OPT_DEPTH, "0");
1441         transport_set_option(transport, TRANS_OPT_DEEPEN_RELATIVE, NULL);
1442         if (!fetch_refs(transport, ref_map))
1443                 consume_refs(transport, ref_map);
1444
1445         if (gsecondary) {
1446                 transport_disconnect(gsecondary);
1447                 gsecondary = NULL;
1448         }
1449 }
1450
1451 static int do_fetch(struct transport *transport,
1452                     struct refspec *rs)
1453 {
1454         struct ref *ref_map;
1455         int autotags = (transport->remote->fetch_tags == 1);
1456         int retcode = 0;
1457         const struct ref *remote_refs;
1458         struct strvec ref_prefixes = STRVEC_INIT;
1459         int must_list_refs = 1;
1460
1461         if (tags == TAGS_DEFAULT) {
1462                 if (transport->remote->fetch_tags == 2)
1463                         tags = TAGS_SET;
1464                 if (transport->remote->fetch_tags == -1)
1465                         tags = TAGS_UNSET;
1466         }
1467
1468         /* if not appending, truncate FETCH_HEAD */
1469         if (!append && write_fetch_head) {
1470                 retcode = truncate_fetch_head();
1471                 if (retcode)
1472                         goto cleanup;
1473         }
1474
1475         if (rs->nr) {
1476                 int i;
1477
1478                 refspec_ref_prefixes(rs, &ref_prefixes);
1479
1480                 /*
1481                  * We can avoid listing refs if all of them are exact
1482                  * OIDs
1483                  */
1484                 must_list_refs = 0;
1485                 for (i = 0; i < rs->nr; i++) {
1486                         if (!rs->items[i].exact_sha1) {
1487                                 must_list_refs = 1;
1488                                 break;
1489                         }
1490                 }
1491         } else if (transport->remote && transport->remote->fetch.nr)
1492                 refspec_ref_prefixes(&transport->remote->fetch, &ref_prefixes);
1493
1494         if (tags == TAGS_SET || tags == TAGS_DEFAULT) {
1495                 must_list_refs = 1;
1496                 if (ref_prefixes.nr)
1497                         strvec_push(&ref_prefixes, "refs/tags/");
1498         }
1499
1500         if (must_list_refs) {
1501                 trace2_region_enter("fetch", "remote_refs", the_repository);
1502                 remote_refs = transport_get_remote_refs(transport, &ref_prefixes);
1503                 trace2_region_leave("fetch", "remote_refs", the_repository);
1504         } else
1505                 remote_refs = NULL;
1506
1507         strvec_clear(&ref_prefixes);
1508
1509         ref_map = get_ref_map(transport->remote, remote_refs, rs,
1510                               tags, &autotags);
1511         if (!update_head_ok)
1512                 check_not_current_branch(ref_map);
1513
1514         if (tags == TAGS_DEFAULT && autotags)
1515                 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
1516         if (prune) {
1517                 /*
1518                  * We only prune based on refspecs specified
1519                  * explicitly (via command line or configuration); we
1520                  * don't care whether --tags was specified.
1521                  */
1522                 if (rs->nr) {
1523                         prune_refs(rs, ref_map, transport->url);
1524                 } else {
1525                         prune_refs(&transport->remote->fetch,
1526                                    ref_map,
1527                                    transport->url);
1528                 }
1529         }
1530         if (fetch_refs(transport, ref_map) || consume_refs(transport, ref_map)) {
1531                 free_refs(ref_map);
1532                 retcode = 1;
1533                 goto cleanup;
1534         }
1535
1536         if (set_upstream) {
1537                 struct branch *branch = branch_get("HEAD");
1538                 struct ref *rm;
1539                 struct ref *source_ref = NULL;
1540
1541                 /*
1542                  * We're setting the upstream configuration for the
1543                  * current branch. The relevant upstream is the
1544                  * fetched branch that is meant to be merged with the
1545                  * current one, i.e. the one fetched to FETCH_HEAD.
1546                  *
1547                  * When there are several such branches, consider the
1548                  * request ambiguous and err on the safe side by doing
1549                  * nothing and just emit a warning.
1550                  */
1551                 for (rm = ref_map; rm; rm = rm->next) {
1552                         if (!rm->peer_ref) {
1553                                 if (source_ref) {
1554                                         warning(_("multiple branches detected, incompatible with --set-upstream"));
1555                                         goto skip;
1556                                 } else {
1557                                         source_ref = rm;
1558                                 }
1559                         }
1560                 }
1561                 if (source_ref) {
1562                         if (!strcmp(source_ref->name, "HEAD") ||
1563                             starts_with(source_ref->name, "refs/heads/"))
1564                                 install_branch_config(0,
1565                                                       branch->name,
1566                                                       transport->remote->name,
1567                                                       source_ref->name);
1568                         else if (starts_with(source_ref->name, "refs/remotes/"))
1569                                 warning(_("not setting upstream for a remote remote-tracking branch"));
1570                         else if (starts_with(source_ref->name, "refs/tags/"))
1571                                 warning(_("not setting upstream for a remote tag"));
1572                         else
1573                                 warning(_("unknown branch type"));
1574                 } else {
1575                         warning(_("no source branch found.\n"
1576                                 "you need to specify exactly one branch with the --set-upstream option."));
1577                 }
1578         }
1579  skip:
1580         free_refs(ref_map);
1581
1582         /* if neither --no-tags nor --tags was specified, do automated tag
1583          * following ... */
1584         if (tags == TAGS_DEFAULT && autotags) {
1585                 struct ref **tail = &ref_map;
1586                 ref_map = NULL;
1587                 find_non_local_tags(remote_refs, &ref_map, &tail);
1588                 if (ref_map)
1589                         backfill_tags(transport, ref_map);
1590                 free_refs(ref_map);
1591         }
1592
1593  cleanup:
1594         return retcode;
1595 }
1596
1597 static int get_one_remote_for_fetch(struct remote *remote, void *priv)
1598 {
1599         struct string_list *list = priv;
1600         if (!remote->skip_default_update)
1601                 string_list_append(list, remote->name);
1602         return 0;
1603 }
1604
1605 struct remote_group_data {
1606         const char *name;
1607         struct string_list *list;
1608 };
1609
1610 static int get_remote_group(const char *key, const char *value, void *priv)
1611 {
1612         struct remote_group_data *g = priv;
1613
1614         if (skip_prefix(key, "remotes.", &key) && !strcmp(key, g->name)) {
1615                 /* split list by white space */
1616                 while (*value) {
1617                         size_t wordlen = strcspn(value, " \t\n");
1618
1619                         if (wordlen >= 1)
1620                                 string_list_append_nodup(g->list,
1621                                                    xstrndup(value, wordlen));
1622                         value += wordlen + (value[wordlen] != '\0');
1623                 }
1624         }
1625
1626         return 0;
1627 }
1628
1629 static int add_remote_or_group(const char *name, struct string_list *list)
1630 {
1631         int prev_nr = list->nr;
1632         struct remote_group_data g;
1633         g.name = name; g.list = list;
1634
1635         git_config(get_remote_group, &g);
1636         if (list->nr == prev_nr) {
1637                 struct remote *remote = remote_get(name);
1638                 if (!remote_is_configured(remote, 0))
1639                         return 0;
1640                 string_list_append(list, remote->name);
1641         }
1642         return 1;
1643 }
1644
1645 static void add_options_to_argv(struct strvec *argv)
1646 {
1647         if (dry_run)
1648                 strvec_push(argv, "--dry-run");
1649         if (prune != -1)
1650                 strvec_push(argv, prune ? "--prune" : "--no-prune");
1651         if (prune_tags != -1)
1652                 strvec_push(argv, prune_tags ? "--prune-tags" : "--no-prune-tags");
1653         if (update_head_ok)
1654                 strvec_push(argv, "--update-head-ok");
1655         if (force)
1656                 strvec_push(argv, "--force");
1657         if (keep)
1658                 strvec_push(argv, "--keep");
1659         if (recurse_submodules == RECURSE_SUBMODULES_ON)
1660                 strvec_push(argv, "--recurse-submodules");
1661         else if (recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND)
1662                 strvec_push(argv, "--recurse-submodules=on-demand");
1663         if (tags == TAGS_SET)
1664                 strvec_push(argv, "--tags");
1665         else if (tags == TAGS_UNSET)
1666                 strvec_push(argv, "--no-tags");
1667         if (verbosity >= 2)
1668                 strvec_push(argv, "-v");
1669         if (verbosity >= 1)
1670                 strvec_push(argv, "-v");
1671         else if (verbosity < 0)
1672                 strvec_push(argv, "-q");
1673         if (family == TRANSPORT_FAMILY_IPV4)
1674                 strvec_push(argv, "--ipv4");
1675         else if (family == TRANSPORT_FAMILY_IPV6)
1676                 strvec_push(argv, "--ipv6");
1677 }
1678
1679 /* Fetch multiple remotes in parallel */
1680
1681 struct parallel_fetch_state {
1682         const char **argv;
1683         struct string_list *remotes;
1684         int next, result;
1685 };
1686
1687 static int fetch_next_remote(struct child_process *cp, struct strbuf *out,
1688                              void *cb, void **task_cb)
1689 {
1690         struct parallel_fetch_state *state = cb;
1691         char *remote;
1692
1693         if (state->next < 0 || state->next >= state->remotes->nr)
1694                 return 0;
1695
1696         remote = state->remotes->items[state->next++].string;
1697         *task_cb = remote;
1698
1699         strvec_pushv(&cp->args, state->argv);
1700         strvec_push(&cp->args, remote);
1701         cp->git_cmd = 1;
1702
1703         if (verbosity >= 0)
1704                 printf(_("Fetching %s\n"), remote);
1705
1706         return 1;
1707 }
1708
1709 static int fetch_failed_to_start(struct strbuf *out, void *cb, void *task_cb)
1710 {
1711         struct parallel_fetch_state *state = cb;
1712         const char *remote = task_cb;
1713
1714         state->result = error(_("Could not fetch %s"), remote);
1715
1716         return 0;
1717 }
1718
1719 static int fetch_finished(int result, struct strbuf *out,
1720                           void *cb, void *task_cb)
1721 {
1722         struct parallel_fetch_state *state = cb;
1723         const char *remote = task_cb;
1724
1725         if (result) {
1726                 strbuf_addf(out, _("could not fetch '%s' (exit code: %d)\n"),
1727                             remote, result);
1728                 state->result = -1;
1729         }
1730
1731         return 0;
1732 }
1733
1734 static int fetch_multiple(struct string_list *list, int max_children)
1735 {
1736         int i, result = 0;
1737         struct strvec argv = STRVEC_INIT;
1738
1739         if (!append && write_fetch_head) {
1740                 int errcode = truncate_fetch_head();
1741                 if (errcode)
1742                         return errcode;
1743         }
1744
1745         strvec_pushl(&argv, "fetch", "--append", "--no-auto-gc",
1746                      "--no-write-commit-graph", NULL);
1747         add_options_to_argv(&argv);
1748
1749         if (max_children != 1 && list->nr != 1) {
1750                 struct parallel_fetch_state state = { argv.v, list, 0, 0 };
1751
1752                 strvec_push(&argv, "--end-of-options");
1753                 result = run_processes_parallel_tr2(max_children,
1754                                                     &fetch_next_remote,
1755                                                     &fetch_failed_to_start,
1756                                                     &fetch_finished,
1757                                                     &state,
1758                                                     "fetch", "parallel/fetch");
1759
1760                 if (!result)
1761                         result = state.result;
1762         } else
1763                 for (i = 0; i < list->nr; i++) {
1764                         const char *name = list->items[i].string;
1765                         strvec_push(&argv, name);
1766                         if (verbosity >= 0)
1767                                 printf(_("Fetching %s\n"), name);
1768                         if (run_command_v_opt(argv.v, RUN_GIT_CMD)) {
1769                                 error(_("Could not fetch %s"), name);
1770                                 result = 1;
1771                         }
1772                         strvec_pop(&argv);
1773                 }
1774
1775         strvec_clear(&argv);
1776         return !!result;
1777 }
1778
1779 /*
1780  * Fetching from the promisor remote should use the given filter-spec
1781  * or inherit the default filter-spec from the config.
1782  */
1783 static inline void fetch_one_setup_partial(struct remote *remote)
1784 {
1785         /*
1786          * Explicit --no-filter argument overrides everything, regardless
1787          * of any prior partial clones and fetches.
1788          */
1789         if (filter_options.no_filter)
1790                 return;
1791
1792         /*
1793          * If no prior partial clone/fetch and the current fetch DID NOT
1794          * request a partial-fetch, do a normal fetch.
1795          */
1796         if (!has_promisor_remote() && !filter_options.choice)
1797                 return;
1798
1799         /*
1800          * If this is a partial-fetch request, we enable partial on
1801          * this repo if not already enabled and remember the given
1802          * filter-spec as the default for subsequent fetches to this
1803          * remote if there is currently no default filter-spec.
1804          */
1805         if (filter_options.choice) {
1806                 partial_clone_register(remote->name, &filter_options);
1807                 return;
1808         }
1809
1810         /*
1811          * Do a partial-fetch from the promisor remote using either the
1812          * explicitly given filter-spec or inherit the filter-spec from
1813          * the config.
1814          */
1815         if (!filter_options.choice)
1816                 partial_clone_get_default_filter_spec(&filter_options, remote->name);
1817         return;
1818 }
1819
1820 static int fetch_one(struct remote *remote, int argc, const char **argv,
1821                      int prune_tags_ok, int use_stdin_refspecs)
1822 {
1823         struct refspec rs = REFSPEC_INIT_FETCH;
1824         int i;
1825         int exit_code;
1826         int maybe_prune_tags;
1827         int remote_via_config = remote_is_configured(remote, 0);
1828
1829         if (!remote)
1830                 die(_("No remote repository specified.  Please, specify either a URL or a\n"
1831                     "remote name from which new revisions should be fetched."));
1832
1833         gtransport = prepare_transport(remote, 1);
1834
1835         if (prune < 0) {
1836                 /* no command line request */
1837                 if (0 <= remote->prune)
1838                         prune = remote->prune;
1839                 else if (0 <= fetch_prune_config)
1840                         prune = fetch_prune_config;
1841                 else
1842                         prune = PRUNE_BY_DEFAULT;
1843         }
1844
1845         if (prune_tags < 0) {
1846                 /* no command line request */
1847                 if (0 <= remote->prune_tags)
1848                         prune_tags = remote->prune_tags;
1849                 else if (0 <= fetch_prune_tags_config)
1850                         prune_tags = fetch_prune_tags_config;
1851                 else
1852                         prune_tags = PRUNE_TAGS_BY_DEFAULT;
1853         }
1854
1855         maybe_prune_tags = prune_tags_ok && prune_tags;
1856         if (maybe_prune_tags && remote_via_config)
1857                 refspec_append(&remote->fetch, TAG_REFSPEC);
1858
1859         if (maybe_prune_tags && (argc || !remote_via_config))
1860                 refspec_append(&rs, TAG_REFSPEC);
1861
1862         for (i = 0; i < argc; i++) {
1863                 if (!strcmp(argv[i], "tag")) {
1864                         i++;
1865                         if (i >= argc)
1866                                 die(_("You need to specify a tag name."));
1867
1868                         refspec_appendf(&rs, "refs/tags/%s:refs/tags/%s",
1869                                         argv[i], argv[i]);
1870                 } else {
1871                         refspec_append(&rs, argv[i]);
1872                 }
1873         }
1874
1875         if (use_stdin_refspecs) {
1876                 struct strbuf line = STRBUF_INIT;
1877                 while (strbuf_getline_lf(&line, stdin) != EOF)
1878                         refspec_append(&rs, line.buf);
1879                 strbuf_release(&line);
1880         }
1881
1882         if (server_options.nr)
1883                 gtransport->server_options = &server_options;
1884
1885         sigchain_push_common(unlock_pack_on_signal);
1886         atexit(unlock_pack);
1887         sigchain_push(SIGPIPE, SIG_IGN);
1888         exit_code = do_fetch(gtransport, &rs);
1889         sigchain_pop(SIGPIPE);
1890         refspec_clear(&rs);
1891         transport_disconnect(gtransport);
1892         gtransport = NULL;
1893         return exit_code;
1894 }
1895
1896 int cmd_fetch(int argc, const char **argv, const char *prefix)
1897 {
1898         int i;
1899         struct string_list list = STRING_LIST_INIT_DUP;
1900         struct remote *remote = NULL;
1901         int result = 0;
1902         int prune_tags_ok = 1;
1903
1904         packet_trace_identity("fetch");
1905
1906         /* Record the command line for the reflog */
1907         strbuf_addstr(&default_rla, "fetch");
1908         for (i = 1; i < argc; i++) {
1909                 /* This handles non-URLs gracefully */
1910                 char *anon = transport_anonymize_url(argv[i]);
1911
1912                 strbuf_addf(&default_rla, " %s", anon);
1913                 free(anon);
1914         }
1915
1916         git_config(git_fetch_config, NULL);
1917
1918         argc = parse_options(argc, argv, prefix,
1919                              builtin_fetch_options, builtin_fetch_usage, 0);
1920         if (recurse_submodules != RECURSE_SUBMODULES_OFF) {
1921                 int *sfjc = submodule_fetch_jobs_config == -1
1922                             ? &submodule_fetch_jobs_config : NULL;
1923                 int *rs = recurse_submodules == RECURSE_SUBMODULES_DEFAULT
1924                           ? &recurse_submodules : NULL;
1925
1926                 fetch_config_from_gitmodules(sfjc, rs);
1927         }
1928
1929         if (deepen_relative) {
1930                 if (deepen_relative < 0)
1931                         die(_("Negative depth in --deepen is not supported"));
1932                 if (depth)
1933                         die(_("--deepen and --depth are mutually exclusive"));
1934                 depth = xstrfmt("%d", deepen_relative);
1935         }
1936         if (unshallow) {
1937                 if (depth)
1938                         die(_("--depth and --unshallow cannot be used together"));
1939                 else if (!is_repository_shallow(the_repository))
1940                         die(_("--unshallow on a complete repository does not make sense"));
1941                 else
1942                         depth = xstrfmt("%d", INFINITE_DEPTH);
1943         }
1944
1945         /* no need to be strict, transport_set_option() will validate it again */
1946         if (depth && atoi(depth) < 1)
1947                 die(_("depth %s is not a positive number"), depth);
1948         if (depth || deepen_since || deepen_not.nr)
1949                 deepen = 1;
1950
1951         /* FETCH_HEAD never gets updated in --dry-run mode */
1952         if (dry_run)
1953                 write_fetch_head = 0;
1954
1955         if (all) {
1956                 if (argc == 1)
1957                         die(_("fetch --all does not take a repository argument"));
1958                 else if (argc > 1)
1959                         die(_("fetch --all does not make sense with refspecs"));
1960                 (void) for_each_remote(get_one_remote_for_fetch, &list);
1961         } else if (argc == 0) {
1962                 /* No arguments -- use default remote */
1963                 remote = remote_get(NULL);
1964         } else if (multiple) {
1965                 /* All arguments are assumed to be remotes or groups */
1966                 for (i = 0; i < argc; i++)
1967                         if (!add_remote_or_group(argv[i], &list))
1968                                 die(_("No such remote or remote group: %s"), argv[i]);
1969         } else {
1970                 /* Single remote or group */
1971                 (void) add_remote_or_group(argv[0], &list);
1972                 if (list.nr > 1) {
1973                         /* More than one remote */
1974                         if (argc > 1)
1975                                 die(_("Fetching a group and specifying refspecs does not make sense"));
1976                 } else {
1977                         /* Zero or one remotes */
1978                         remote = remote_get(argv[0]);
1979                         prune_tags_ok = (argc == 1);
1980                         argc--;
1981                         argv++;
1982                 }
1983         }
1984
1985         if (remote) {
1986                 if (filter_options.choice || has_promisor_remote())
1987                         fetch_one_setup_partial(remote);
1988                 result = fetch_one(remote, argc, argv, prune_tags_ok, stdin_refspecs);
1989         } else {
1990                 int max_children = max_jobs;
1991
1992                 if (filter_options.choice)
1993                         die(_("--filter can only be used with the remote "
1994                               "configured in extensions.partialclone"));
1995
1996                 if (atomic_fetch)
1997                         die(_("--atomic can only be used when fetching "
1998                               "from one remote"));
1999
2000                 if (stdin_refspecs)
2001                         die(_("--stdin can only be used when fetching "
2002                               "from one remote"));
2003
2004                 if (max_children < 0)
2005                         max_children = fetch_parallel_config;
2006
2007                 /* TODO should this also die if we have a previous partial-clone? */
2008                 result = fetch_multiple(&list, max_children);
2009         }
2010
2011         if (!result && (recurse_submodules != RECURSE_SUBMODULES_OFF)) {
2012                 struct strvec options = STRVEC_INIT;
2013                 int max_children = max_jobs;
2014
2015                 if (max_children < 0)
2016                         max_children = submodule_fetch_jobs_config;
2017                 if (max_children < 0)
2018                         max_children = fetch_parallel_config;
2019
2020                 add_options_to_argv(&options);
2021                 result = fetch_populated_submodules(the_repository,
2022                                                     &options,
2023                                                     submodule_prefix,
2024                                                     recurse_submodules,
2025                                                     recurse_submodules_default,
2026                                                     verbosity < 0,
2027                                                     max_children);
2028                 strvec_clear(&options);
2029         }
2030
2031         string_list_clear(&list, 0);
2032
2033         prepare_repo_settings(the_repository);
2034         if (fetch_write_commit_graph > 0 ||
2035             (fetch_write_commit_graph < 0 &&
2036              the_repository->settings.fetch_write_commit_graph)) {
2037                 int commit_graph_flags = COMMIT_GRAPH_WRITE_SPLIT;
2038
2039                 if (progress)
2040                         commit_graph_flags |= COMMIT_GRAPH_WRITE_PROGRESS;
2041
2042                 write_commit_graph_reachable(the_repository->objects->odb,
2043                                              commit_graph_flags,
2044                                              NULL);
2045         }
2046
2047         close_object_store(the_repository->objects);
2048
2049         if (enable_auto_gc)
2050                 run_auto_maintenance(verbosity < 0);
2051
2052         return result;
2053 }