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