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