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