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