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