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