]> git.ipfire.org Git - thirdparty/git.git/blame - builtin/fetch.c
treewide: be explicit about dependence on trace.h & trace2.h
[thirdparty/git.git] / builtin / fetch.c
CommitLineData
b888d61c
DB
1/*
2 * "git fetch"
3 */
4#include "cache.h"
b2141fc1 5#include "config.h"
f394e093 6#include "gettext.h"
32a8f510 7#include "environment.h"
41771fa4 8#include "hex.h"
e724197f 9#include "repository.h"
b888d61c 10#include "refs.h"
ec0cb496 11#include "refspec.h"
cbd53a21 12#include "object-store.h"
b7e2d8bc 13#include "oidset.h"
b888d61c
DB
14#include "commit.h"
15#include "builtin.h"
c455c87c 16#include "string-list.h"
b888d61c
DB
17#include "remote.h"
18#include "transport.h"
4191c356 19#include "run-command.h"
83201998 20#include "parse-options.h"
4a16d072 21#include "sigchain.h"
027771fc 22#include "submodule-config.h"
7dce19d3 23#include "submodule.h"
f96400cb 24#include "connected.h"
dbbcd44f 25#include "strvec.h"
6bc91f23 26#include "utf8.h"
3836d88a 27#include "packfile.h"
acb0c572 28#include "list-objects-filter-options.h"
64043556 29#include "commit-reach.h"
24bc1a12 30#include "branch.h"
b14ed5ad 31#include "promisor-remote.h"
50f26bd0 32#include "commit-graph.h"
120ad2b0 33#include "shallow.h"
74ea5c95
EN
34#include "trace.h"
35#include "trace2.h"
8bc1f39f 36#include "worktree.h"
7f0cc04f 37#include "bundle-uri.h"
b888d61c 38
377444b4
DS
39#define FORCED_UPDATES_DELAY_WARNING_IN_MS (10 * 1000)
40
83201998 41static const char * const builtin_fetch_usage[] = {
719acedb
NTND
42 N_("git fetch [<options>] [<repository> [<refspec>...]]"),
43 N_("git fetch [<options>] <group>"),
44 N_("git fetch --multiple [<options>] [(<repository> | <group>)...]"),
45 N_("git fetch --all [<options>]"),
83201998
KH
46 NULL
47};
b888d61c 48
83201998
KH
49enum {
50 TAGS_UNSET = 0,
51 TAGS_DEFAULT = 1,
52 TAGS_SET = 2
53};
54
737c5a9c 55static int fetch_prune_config = -1; /* unspecified */
cdbd70c4 56static int fetch_show_forced_updates = 1;
377444b4 57static uint64_t forced_updates_ms = 0;
2e03115d 58static int prefetch = 0;
737c5a9c
MS
59static int prune = -1; /* unspecified */
60#define PRUNE_BY_DEFAULT 0 /* do we prune by default? */
61
97716d21
ÆAB
62static int fetch_prune_tags_config = -1; /* unspecified */
63static int prune_tags = -1; /* unspecified */
64#define PRUNE_TAGS_BY_DEFAULT 0 /* do we prune tags by default? */
65
24bc1a12 66static int all, append, dry_run, force, keep, multiple, update_head_ok;
887952b8 67static int write_fetch_head = 1;
3c7bab06 68static int verbosity, deepen_relative, set_upstream, refetch;
8c69832d 69static int progress = -1;
c3d6b703 70static int enable_auto_gc = 1;
508ea882 71static int tags = TAGS_DEFAULT, unshallow, update_shallow, deepen;
d54dea77
JS
72static int max_jobs = -1, submodule_fetch_jobs_config = -1;
73static int fetch_parallel_config = 1;
c7b190da 74static int atomic_fetch;
c915f11e 75static enum transport_family family;
4191c356 76static const char *depth;
508ea882 77static const char *deepen_since;
83201998 78static const char *upload_pack;
a45a2600 79static struct string_list deepen_not = STRING_LIST_INIT_NODUP;
2d324efa 80static struct strbuf default_rla = STRBUF_INIT;
af234459 81static struct transport *gtransport;
b26ed430 82static struct transport *gsecondary;
7dce19d3 83static const char *submodule_prefix = "";
8c69832d 84static int recurse_submodules = RECURSE_SUBMODULES_DEFAULT;
386c076a 85static int recurse_submodules_cli = RECURSE_SUBMODULES_DEFAULT;
e8906a90 86static int recurse_submodules_default = RECURSE_SUBMODULES_ON_DEMAND;
4b3b33a7 87static int shown_url = 0;
e4cffacc 88static struct refspec refmap = REFSPEC_INIT_FETCH;
2a01bded 89static struct list_objects_filter_options filter_options = LIST_OBJECTS_FILTER_INIT;
5e3548ef 90static struct string_list server_options = STRING_LIST_INIT_DUP;
3390e42a 91static struct string_list negotiation_tip = STRING_LIST_INIT_NODUP;
c14e6e79 92static int fetch_write_commit_graph = -1;
2b713c27 93static int stdin_refspecs = 0;
9c1e657a 94static int negotiate_only;
e4022ed2 95
737c5a9c
MS
96static int git_fetch_config(const char *k, const char *v, void *cb)
97{
98 if (!strcmp(k, "fetch.prune")) {
99 fetch_prune_config = git_config_bool(k, v);
100 return 0;
101 }
58f4203e 102
97716d21
ÆAB
103 if (!strcmp(k, "fetch.prunetags")) {
104 fetch_prune_tags_config = git_config_bool(k, v);
105 return 0;
106 }
107
cdbd70c4
DS
108 if (!strcmp(k, "fetch.showforcedupdates")) {
109 fetch_show_forced_updates = git_config_bool(k, v);
110 return 0;
111 }
112
58f4203e
SB
113 if (!strcmp(k, "submodule.recurse")) {
114 int r = git_config_bool(k, v) ?
115 RECURSE_SUBMODULES_ON : RECURSE_SUBMODULES_OFF;
116 recurse_submodules = r;
117 }
118
f20e7c1e 119 if (!strcmp(k, "submodule.fetchjobs")) {
d54dea77 120 submodule_fetch_jobs_config = parse_submodule_fetchjobs(k, v);
f20e7c1e 121 return 0;
8fa29159
BW
122 } else if (!strcmp(k, "fetch.recursesubmodules")) {
123 recurse_submodules = parse_fetch_recurse_submodules_arg(k, v);
124 return 0;
f20e7c1e
BW
125 }
126
d54dea77
JS
127 if (!strcmp(k, "fetch.parallel")) {
128 fetch_parallel_config = git_config_int(k, v);
129 if (fetch_parallel_config < 0)
130 die(_("fetch.parallel cannot be negative"));
51243f9f
ÆAB
131 if (!fetch_parallel_config)
132 fetch_parallel_config = online_cpus();
d54dea77
JS
133 return 0;
134 }
135
72549dfd 136 return git_default_config(k, v, cb);
737c5a9c
MS
137}
138
c5558f80
JH
139static int parse_refmap_arg(const struct option *opt, const char *arg, int unset)
140{
517fe807
JK
141 BUG_ON_OPT_NEG(unset);
142
c5558f80
JH
143 /*
144 * "git fetch --refmap='' origin foo"
145 * can be used to tell the command not to store anywhere
146 */
e4cffacc
BW
147 refspec_append(&refmap, arg);
148
c5558f80
JH
149 return 0;
150}
151
83201998 152static struct option builtin_fetch_options[] = {
7f87aff2 153 OPT__VERBOSITY(&verbosity),
d5d09d47
SB
154 OPT_BOOL(0, "all", &all,
155 N_("fetch from all remotes")),
24bc1a12
CB
156 OPT_BOOL(0, "set-upstream", &set_upstream,
157 N_("set upstream for git pull/fetch")),
d5d09d47
SB
158 OPT_BOOL('a', "append", &append,
159 N_("append to .git/FETCH_HEAD instead of overwriting")),
c7b190da
PS
160 OPT_BOOL(0, "atomic", &atomic_fetch,
161 N_("use atomic transaction to update references")),
719acedb
NTND
162 OPT_STRING(0, "upload-pack", &upload_pack, N_("path"),
163 N_("path to upload pack on remote end")),
8cd4b7c1 164 OPT__FORCE(&force, N_("force overwrite of local reference"), 0),
d5d09d47
SB
165 OPT_BOOL('m', "multiple", &multiple,
166 N_("fetch from multiple remotes")),
83201998 167 OPT_SET_INT('t', "tags", &tags,
719acedb 168 N_("fetch all tags and associated objects"), TAGS_SET),
e7951290 169 OPT_SET_INT('n', NULL, &tags,
719acedb 170 N_("do not fetch all tags (--no-tags)"), TAGS_UNSET),
d54dea77 171 OPT_INTEGER('j', "jobs", &max_jobs,
62104ba1 172 N_("number of submodules fetched in parallel")),
2e03115d
DS
173 OPT_BOOL(0, "prefetch", &prefetch,
174 N_("modify the refspec to place all refs within refs/prefetch/")),
d5d09d47
SB
175 OPT_BOOL('p', "prune", &prune,
176 N_("prune remote-tracking branches no longer on remote")),
97716d21
ÆAB
177 OPT_BOOL('P', "prune-tags", &prune_tags,
178 N_("prune local tags no longer on remote and clobber changed tags")),
386c076a 179 OPT_CALLBACK_F(0, "recurse-submodules", &recurse_submodules_cli, N_("on-demand"),
719acedb 180 N_("control recursive fetching of submodules"),
203c8533 181 PARSE_OPT_OPTARG, option_fetch_parse_recurse_submodules),
d5d09d47
SB
182 OPT_BOOL(0, "dry-run", &dry_run,
183 N_("dry run")),
887952b8
JH
184 OPT_BOOL(0, "write-fetch-head", &write_fetch_head,
185 N_("write fetched references to the FETCH_HEAD file")),
d5d09d47
SB
186 OPT_BOOL('k', "keep", &keep, N_("keep downloaded pack")),
187 OPT_BOOL('u', "update-head-ok", &update_head_ok,
719acedb
NTND
188 N_("allow updating of HEAD ref")),
189 OPT_BOOL(0, "progress", &progress, N_("force progress reporting")),
190 OPT_STRING(0, "depth", &depth, N_("depth"),
191 N_("deepen history of shallow clone")),
508ea882
NTND
192 OPT_STRING(0, "shallow-since", &deepen_since, N_("time"),
193 N_("deepen history of shallow repository based on time")),
a45a2600 194 OPT_STRING_LIST(0, "shallow-exclude", &deepen_not, N_("revision"),
6d873865 195 N_("deepen history of shallow clone, excluding rev")),
cccf74e2
NTND
196 OPT_INTEGER(0, "deepen", &deepen_relative,
197 N_("deepen history of shallow clone")),
3e4a67b4
NTND
198 OPT_SET_INT_F(0, "unshallow", &unshallow,
199 N_("convert to a complete repository"),
200 1, PARSE_OPT_NONEG),
3c7bab06
RC
201 OPT_SET_INT_F(0, "refetch", &refetch,
202 N_("re-fetch without negotiating common commits"),
203 1, PARSE_OPT_NONEG),
719acedb
NTND
204 { OPTION_STRING, 0, "submodule-prefix", &submodule_prefix, N_("dir"),
205 N_("prepend this to submodule path output"), PARSE_OPT_HIDDEN },
203c8533 206 OPT_CALLBACK_F(0, "recurse-submodules-default",
8c69832d
SB
207 &recurse_submodules_default, N_("on-demand"),
208 N_("default for recursive fetching of submodules "
209 "(lower priority than config files)"),
203c8533 210 PARSE_OPT_HIDDEN, option_fetch_parse_recurse_submodules),
48d25cae
NTND
211 OPT_BOOL(0, "update-shallow", &update_shallow,
212 N_("accept refs that update .git/shallow")),
203c8533
DL
213 OPT_CALLBACK_F(0, "refmap", NULL, N_("refmap"),
214 N_("specify fetch refmap"), PARSE_OPT_NONEG, parse_refmap_arg),
5e3548ef 215 OPT_STRING_LIST('o', "server-option", &server_options, N_("server-specific"), N_("option to transmit")),
c915f11e
EW
216 OPT_SET_INT('4', "ipv4", &family, N_("use IPv4 addresses only"),
217 TRANSPORT_FAMILY_IPV4),
218 OPT_SET_INT('6', "ipv6", &family, N_("use IPv6 addresses only"),
219 TRANSPORT_FAMILY_IPV6),
3390e42a
JT
220 OPT_STRING_LIST(0, "negotiation-tip", &negotiation_tip, N_("revision"),
221 N_("report that we have only objects reachable from this object")),
9c1e657a
JT
222 OPT_BOOL(0, "negotiate-only", &negotiate_only,
223 N_("do not fetch a packfile; instead, print ancestors of negotiation tips")),
acb0c572 224 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
a95ce124
DS
225 OPT_BOOL(0, "auto-maintenance", &enable_auto_gc,
226 N_("run 'maintenance --auto' after fetching")),
c3d6b703 227 OPT_BOOL(0, "auto-gc", &enable_auto_gc,
a95ce124 228 N_("run 'maintenance --auto' after fetching")),
cdbd70c4
DS
229 OPT_BOOL(0, "show-forced-updates", &fetch_show_forced_updates,
230 N_("check for forced-updates on all updated branches")),
c14e6e79
JS
231 OPT_BOOL(0, "write-commit-graph", &fetch_write_commit_graph,
232 N_("write the commit-graph after fetching")),
2b713c27
JT
233 OPT_BOOL(0, "stdin", &stdin_refspecs,
234 N_("accept refspecs from stdin")),
83201998
KH
235 OPT_END()
236};
237
58d4d7f1 238static void unlock_pack(unsigned int flags)
e4022ed2 239{
af234459 240 if (gtransport)
58d4d7f1 241 transport_unlock_pack(gtransport, flags);
b26ed430 242 if (gsecondary)
58d4d7f1
PS
243 transport_unlock_pack(gsecondary, flags);
244}
245
246static void unlock_pack_atexit(void)
247{
248 unlock_pack(0);
e4022ed2
SP
249}
250
251static void unlock_pack_on_signal(int signo)
252{
58d4d7f1 253 unlock_pack(TRANSPORT_UNLOCK_PACK_IN_SIGNAL_HANDLER);
4a16d072 254 sigchain_pop(signo);
e4022ed2
SP
255 raise(signo);
256}
b888d61c 257
85682c19 258static void add_merge_config(struct ref **head,
4577370e 259 const struct ref *remote_refs,
85682c19
SP
260 struct branch *branch,
261 struct ref ***tail)
b888d61c 262{
85682c19 263 int i;
b888d61c 264
85682c19
SP
265 for (i = 0; i < branch->merge_nr; i++) {
266 struct ref *rm, **old_tail = *tail;
0ad4a5ff 267 struct refspec_item refspec;
85682c19
SP
268
269 for (rm = *head; rm; rm = rm->next) {
270 if (branch_merge_matches(branch, i, rm->name)) {
900f2814 271 rm->fetch_head_status = FETCH_HEAD_MERGE;
85682c19
SP
272 break;
273 }
b888d61c 274 }
85682c19
SP
275 if (rm)
276 continue;
277
9ad7c5ae 278 /*
8b3f3f84 279 * Not fetched to a remote-tracking branch? We need to fetch
85682c19 280 * it anyway to allow this branch's "branch.$name.merge"
05207a28 281 * to be honored by 'git pull', but we do not have to
9ad7c5ae
JH
282 * fail if branch.$name.merge is misconfigured to point
283 * at a nonexisting branch. If we were indeed called by
05207a28 284 * 'git pull', it will notice the misconfiguration because
9ad7c5ae
JH
285 * there is no entry in the resulting FETCH_HEAD marked
286 * for merging.
85682c19 287 */
8da61a2a 288 memset(&refspec, 0, sizeof(refspec));
85682c19 289 refspec.src = branch->merge[i]->src;
9ad7c5ae 290 get_fetch_map(remote_refs, &refspec, tail, 1);
85682c19 291 for (rm = *old_tail; rm; rm = rm->next)
900f2814 292 rm->fetch_head_status = FETCH_HEAD_MERGE;
b888d61c
DB
293 }
294}
295
b7e2d8bc 296static void create_fetch_oidset(struct ref **head, struct oidset *out)
a0fbb5a3
MH
297{
298 struct ref *rm = *head;
299 while (rm) {
b7e2d8bc 300 oidset_insert(out, &rm->old_oid);
a0fbb5a3
MH
301 rm = rm->next;
302 }
a0fbb5a3
MH
303}
304
e198b3a7 305struct refname_hash_entry {
e2b5038d 306 struct hashmap_entry ent;
e198b3a7 307 struct object_id oid;
f80d9223 308 int ignore;
e198b3a7
JH
309 char refname[FLEX_ARRAY];
310};
311
5cf88fd8 312static int refname_hash_entry_cmp(const void *hashmap_cmp_fn_data UNUSED,
939af16e
EW
313 const struct hashmap_entry *eptr,
314 const struct hashmap_entry *entry_or_key,
e198b3a7
JH
315 const void *keydata)
316{
939af16e 317 const struct refname_hash_entry *e1, *e2;
e198b3a7 318
939af16e
EW
319 e1 = container_of(eptr, const struct refname_hash_entry, ent);
320 e2 = container_of(entry_or_key, const struct refname_hash_entry, ent);
e198b3a7
JH
321 return strcmp(e1->refname, keydata ? keydata : e2->refname);
322}
323
324static struct refname_hash_entry *refname_hash_add(struct hashmap *map,
325 const char *refname,
326 const struct object_id *oid)
327{
328 struct refname_hash_entry *ent;
329 size_t len = strlen(refname);
330
331 FLEX_ALLOC_MEM(ent, refname, refname, len);
d22245a2 332 hashmap_entry_init(&ent->ent, strhash(refname));
e198b3a7 333 oidcpy(&ent->oid, oid);
b94e5c1d 334 hashmap_add(map, &ent->ent);
e198b3a7
JH
335 return ent;
336}
337
338static int add_one_refname(const char *refname,
339 const struct object_id *oid,
5cf88fd8 340 int flag UNUSED, void *cbdata)
e198b3a7
JH
341{
342 struct hashmap *refname_map = cbdata;
343
344 (void) refname_hash_add(refname_map, refname, oid);
345 return 0;
346}
347
348static void refname_hash_init(struct hashmap *map)
349{
350 hashmap_init(map, refname_hash_entry_cmp, NULL, 0);
351}
352
353static int refname_hash_exists(struct hashmap *map, const char *refname)
354{
355 return !!hashmap_get_from_hash(map, strhash(refname), refname);
356}
357
a8363b57
FC
358static void clear_item(struct refname_hash_entry *item)
359{
f80d9223 360 item->ignore = 1;
a8363b57
FC
361}
362
b3a80466
PS
363
364static void add_already_queued_tags(const char *refname,
365 const struct object_id *old_oid,
366 const struct object_id *new_oid,
367 void *cb_data)
368{
369 struct hashmap *queued_tags = cb_data;
370 if (starts_with(refname, "refs/tags/") && new_oid)
371 (void) refname_hash_add(queued_tags, refname, new_oid);
372}
373
6d1700d5 374static void find_non_local_tags(const struct ref *refs,
b3a80466 375 struct ref_transaction *transaction,
6d1700d5
BW
376 struct ref **head,
377 struct ref ***tail)
a0fbb5a3 378{
e198b3a7
JH
379 struct hashmap existing_refs;
380 struct hashmap remote_refs;
b7e2d8bc 381 struct oidset fetch_oids = OIDSET_INIT;
e198b3a7
JH
382 struct string_list remote_refs_list = STRING_LIST_INIT_NODUP;
383 struct string_list_item *remote_ref_item;
a0fbb5a3 384 const struct ref *ref;
e198b3a7 385 struct refname_hash_entry *item = NULL;
3e96c668 386 const int quick_flags = OBJECT_INFO_QUICK | OBJECT_INFO_SKIP_FETCH_OBJECT;
e198b3a7
JH
387
388 refname_hash_init(&existing_refs);
389 refname_hash_init(&remote_refs);
b7e2d8bc 390 create_fetch_oidset(head, &fetch_oids);
a0fbb5a3 391
e198b3a7 392 for_each_ref(add_one_refname, &existing_refs);
b3a80466
PS
393
394 /*
395 * If we already have a transaction, then we need to filter out all
396 * tags which have already been queued up.
397 */
398 if (transaction)
399 ref_transaction_for_each_queued_update(transaction,
400 add_already_queued_tags,
401 &existing_refs);
402
6d1700d5 403 for (ref = refs; ref; ref = ref->next) {
ad704485 404 if (!starts_with(ref->name, "refs/tags/"))
a0fbb5a3
MH
405 continue;
406
407 /*
408 * The peeled ref always follows the matching base
409 * ref, so if we see a peeled ref that we don't want
410 * to fetch then we can mark the ref entry in the list
411 * as one to ignore by setting util to NULL.
412 */
ad704485 413 if (ends_with(ref->name, "^{}")) {
5827a035 414 if (item &&
bc726bd0 415 !repo_has_object_file_with_flags(the_repository, &ref->old_oid, quick_flags) &&
b7e2d8bc 416 !oidset_contains(&fetch_oids, &ref->old_oid) &&
bc726bd0 417 !repo_has_object_file_with_flags(the_repository, &item->oid, quick_flags) &&
b7e2d8bc 418 !oidset_contains(&fetch_oids, &item->oid))
a8363b57 419 clear_item(item);
a0fbb5a3
MH
420 item = NULL;
421 continue;
422 }
423
424 /*
425 * If item is non-NULL here, then we previously saw a
426 * ref not followed by a peeled reference, so we need
427 * to check if it is a lightweight tag that we want to
428 * fetch.
429 */
5827a035 430 if (item &&
bc726bd0 431 !repo_has_object_file_with_flags(the_repository, &item->oid, quick_flags) &&
b7e2d8bc 432 !oidset_contains(&fetch_oids, &item->oid))
a8363b57 433 clear_item(item);
a0fbb5a3
MH
434
435 item = NULL;
436
437 /* skip duplicates and refs that we already have */
e198b3a7
JH
438 if (refname_hash_exists(&remote_refs, ref->name) ||
439 refname_hash_exists(&existing_refs, ref->name))
a0fbb5a3
MH
440 continue;
441
e198b3a7
JH
442 item = refname_hash_add(&remote_refs, ref->name, &ref->old_oid);
443 string_list_insert(&remote_refs_list, ref->name);
a0fbb5a3 444 }
6da1a258 445 hashmap_clear_and_free(&existing_refs, struct refname_hash_entry, ent);
a0fbb5a3
MH
446
447 /*
448 * We may have a final lightweight tag that needs to be
449 * checked to see if it needs fetching.
450 */
5827a035 451 if (item &&
bc726bd0 452 !repo_has_object_file_with_flags(the_repository, &item->oid, quick_flags) &&
b7e2d8bc 453 !oidset_contains(&fetch_oids, &item->oid))
a8363b57 454 clear_item(item);
a0fbb5a3
MH
455
456 /*
e198b3a7 457 * For all the tags in the remote_refs_list,
a0fbb5a3
MH
458 * add them to the list of refs to be fetched
459 */
e198b3a7
JH
460 for_each_string_list_item(remote_ref_item, &remote_refs_list) {
461 const char *refname = remote_ref_item->string;
9528b80b 462 struct ref *rm;
f23a4651 463 unsigned int hash = strhash(refname);
e198b3a7 464
f23a4651
EW
465 item = hashmap_get_entry_from_hash(&remote_refs, hash, refname,
466 struct refname_hash_entry, ent);
e198b3a7
JH
467 if (!item)
468 BUG("unseen remote ref?");
469
a0fbb5a3 470 /* Unless we have already decided to ignore this item... */
f80d9223 471 if (item->ignore)
9528b80b
FC
472 continue;
473
474 rm = alloc_ref(item->refname);
475 rm->peer_ref = alloc_ref(item->refname);
476 oidcpy(&rm->old_oid, &item->oid);
477 **tail = rm;
478 *tail = &rm->next;
a0fbb5a3 479 }
6da1a258 480 hashmap_clear_and_free(&remote_refs, struct refname_hash_entry, ent);
e198b3a7 481 string_list_clear(&remote_refs_list, 0);
b7e2d8bc 482 oidset_clear(&fetch_oids);
a0fbb5a3 483}
767f176a 484
2e03115d
DS
485static void filter_prefetch_refspec(struct refspec *rs)
486{
487 int i;
488
489 if (!prefetch)
490 return;
491
492 for (i = 0; i < rs->nr; i++) {
493 struct strbuf new_dst = STRBUF_INIT;
494 char *old_dst;
495 const char *sub = NULL;
496
497 if (rs->items[i].negative)
498 continue;
499 if (!rs->items[i].dst ||
500 (rs->items[i].src &&
992f25d7
DS
501 !strncmp(rs->items[i].src,
502 ref_namespace[NAMESPACE_TAGS].ref,
503 strlen(ref_namespace[NAMESPACE_TAGS].ref)))) {
2e03115d
DS
504 int j;
505
506 free(rs->items[i].src);
507 free(rs->items[i].dst);
508
509 for (j = i + 1; j < rs->nr; j++) {
510 rs->items[j - 1] = rs->items[j];
511 rs->raw[j - 1] = rs->raw[j];
512 }
513 rs->nr--;
514 i--;
515 continue;
516 }
517
518 old_dst = rs->items[i].dst;
992f25d7 519 strbuf_addstr(&new_dst, ref_namespace[NAMESPACE_PREFETCH].ref);
2e03115d
DS
520
521 /*
522 * If old_dst starts with "refs/", then place
523 * sub after that prefix. Otherwise, start at
524 * the beginning of the string.
525 */
526 if (!skip_prefix(old_dst, "refs/", &sub))
527 sub = old_dst;
528 strbuf_addstr(&new_dst, sub);
529
530 rs->items[i].dst = strbuf_detach(&new_dst, NULL);
531 rs->items[i].force = 1;
532
533 free(old_dst);
534 }
535}
536
6d1700d5
BW
537static struct ref *get_ref_map(struct remote *remote,
538 const struct ref *remote_refs,
65d96c8b 539 struct refspec *rs,
f137a45e 540 int tags, int *autotags)
b888d61c
DB
541{
542 int i;
543 struct ref *rm;
544 struct ref *ref_map = NULL;
545 struct ref **tail = &ref_map;
546
c5a84e92
MH
547 /* opportunistically-updated references: */
548 struct ref *orefs = NULL, **oref_tail = &orefs;
b888d61c 549
e198b3a7 550 struct hashmap existing_refs;
abcb7eeb 551 int existing_refs_populated = 0;
f2690487 552
2e03115d
DS
553 filter_prefetch_refspec(rs);
554 if (remote)
555 filter_prefetch_refspec(&remote->fetch);
556
65d96c8b 557 if (rs->nr) {
c5558f80 558 struct refspec *fetch_refspec;
c5558f80 559
65d96c8b
BW
560 for (i = 0; i < rs->nr; i++) {
561 get_fetch_map(remote_refs, &rs->items[i], &tail, 0);
562 if (rs->items[i].dst && rs->items[i].dst[0])
b888d61c
DB
563 *autotags = 1;
564 }
0281c930 565 /* Merge everything on the command line (but not --tags) */
b888d61c 566 for (rm = ref_map; rm; rm = rm->next)
900f2814 567 rm->fetch_head_status = FETCH_HEAD_MERGE;
f2690487
JK
568
569 /*
0281c930
MH
570 * For any refs that we happen to be fetching via
571 * command-line arguments, the destination ref might
572 * have been missing or have been different than the
573 * remote-tracking ref that would be derived from the
574 * configured refspec. In these cases, we want to
575 * take the opportunity to update their configured
576 * remote-tracking reference. However, we do not want
577 * to mention these entries in FETCH_HEAD at all, as
578 * they would simply be duplicates of existing
579 * entries, so we set them FETCH_HEAD_IGNORE below.
580 *
581 * We compute these entries now, based only on the
582 * refspecs specified on the command line. But we add
583 * them to the list following the refspecs resulting
584 * from the tags option so that one of the latter,
585 * which has FETCH_HEAD_NOT_FOR_MERGE, is not removed
586 * by ref_remove_duplicates() in favor of one of these
587 * opportunistic entries with FETCH_HEAD_IGNORE.
f2690487 588 */
65d96c8b
BW
589 if (refmap.nr)
590 fetch_refspec = &refmap;
591 else
6d1700d5 592 fetch_refspec = &remote->fetch;
c5558f80 593
65d96c8b
BW
594 for (i = 0; i < fetch_refspec->nr; i++)
595 get_fetch_map(ref_map, &fetch_refspec->items[i], &oref_tail, 1);
e4cffacc 596 } else if (refmap.nr) {
66996bea 597 die("--refmap option is only meaningful with command-line refspec(s)");
b888d61c
DB
598 } else {
599 /* Use the defaults */
85682c19
SP
600 struct branch *branch = branch_get(NULL);
601 int has_merge = branch_has_merge_config(branch);
3ee1757b 602 if (remote &&
e5349abf 603 (remote->fetch.nr ||
f31dbdc7 604 /* Note: has_merge implies non-NULL branch->remote_name */
3ee1757b 605 (has_merge && !strcmp(branch->remote_name, remote->name)))) {
e5349abf
BW
606 for (i = 0; i < remote->fetch.nr; i++) {
607 get_fetch_map(remote_refs, &remote->fetch.items[i], &tail, 0);
608 if (remote->fetch.items[i].dst &&
609 remote->fetch.items[i].dst[0])
b888d61c 610 *autotags = 1;
85682c19 611 if (!i && !has_merge && ref_map &&
e5349abf 612 !remote->fetch.items[0].pattern)
900f2814 613 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
b888d61c 614 }
da0204df
JS
615 /*
616 * if the remote we're fetching from is the same
617 * as given in branch.<name>.remote, we add the
618 * ref given in branch.<name>.merge, too.
f31dbdc7
BC
619 *
620 * Note: has_merge implies non-NULL branch->remote_name
da0204df 621 */
9ad7c5ae
JH
622 if (has_merge &&
623 !strcmp(branch->remote_name, remote->name))
85682c19 624 add_merge_config(&ref_map, remote_refs, branch, &tail);
2e03115d 625 } else if (!prefetch) {
b888d61c 626 ref_map = get_remote_ref(remote_refs, "HEAD");
9ad7c5ae 627 if (!ref_map)
66996bea 628 die(_("couldn't find remote ref HEAD"));
900f2814 629 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
5aaf7f2a 630 tail = &ref_map->next;
b888d61c
DB
631 }
632 }
0281c930 633
c5a84e92
MH
634 if (tags == TAGS_SET)
635 /* also fetch all tags */
636 get_fetch_map(remote_refs, tag_refspec, &tail, 0);
637 else if (tags == TAGS_DEFAULT && *autotags)
b3a80466 638 find_non_local_tags(remote_refs, NULL, &ref_map, &tail);
0281c930 639
c5a84e92
MH
640 /* Now append any refs to be updated opportunistically: */
641 *tail = orefs;
642 for (rm = orefs; rm; rm = rm->next) {
643 rm->fetch_head_status = FETCH_HEAD_IGNORE;
644 tail = &rm->next;
645 }
646
c0192df6
JK
647 /*
648 * apply negative refspecs first, before we remove duplicates. This is
649 * necessary as negative refspecs might remove an otherwise conflicting
650 * duplicate.
651 */
652 if (rs->nr)
653 ref_map = apply_negative_refspecs(ref_map, rs);
654 else
655 ref_map = apply_negative_refspecs(ref_map, &remote->fetch);
656
14b8ced3
BW
657 ref_map = ref_remove_duplicates(ref_map);
658
14b8ced3
BW
659 for (rm = ref_map; rm; rm = rm->next) {
660 if (rm->peer_ref) {
e198b3a7
JH
661 const char *refname = rm->peer_ref->name;
662 struct refname_hash_entry *peer_item;
f23a4651 663 unsigned int hash = strhash(refname);
e198b3a7 664
abcb7eeb
JT
665 if (!existing_refs_populated) {
666 refname_hash_init(&existing_refs);
667 for_each_ref(add_one_refname, &existing_refs);
668 existing_refs_populated = 1;
669 }
670
f23a4651
EW
671 peer_item = hashmap_get_entry_from_hash(&existing_refs,
672 hash, refname,
673 struct refname_hash_entry, ent);
14b8ced3 674 if (peer_item) {
e198b3a7 675 struct object_id *old_oid = &peer_item->oid;
14b8ced3
BW
676 oidcpy(&rm->peer_ref->old_oid, old_oid);
677 }
678 }
679 }
abcb7eeb 680 if (existing_refs_populated)
6da1a258 681 hashmap_clear_and_free(&existing_refs, struct refname_hash_entry, ent);
14b8ced3
BW
682
683 return ref_map;
b888d61c
DB
684}
685
fa250759
JK
686#define STORE_REF_ERROR_OTHER 1
687#define STORE_REF_ERROR_DF_CONFLICT 2
688
b888d61c
DB
689static int s_update_ref(const char *action,
690 struct ref *ref,
d4c8db8f 691 struct ref_transaction *transaction,
b888d61c
DB
692 int check_old)
693{
1412f762 694 char *msg;
b888d61c 695 char *rla = getenv("GIT_REFLOG_ACTION");
d4c8db8f 696 struct ref_transaction *our_transaction = NULL;
cd94f765 697 struct strbuf err = STRBUF_INIT;
c45889f1 698 int ret;
b888d61c 699
28a15401
JS
700 if (dry_run)
701 return 0;
b888d61c 702 if (!rla)
2d324efa 703 rla = default_rla.buf;
1412f762 704 msg = xstrfmt("%s: %s", rla, action);
cd94f765 705
d4c8db8f
PS
706 /*
707 * If no transaction was passed to us, we manage the transaction
708 * ourselves. Otherwise, we trust the caller to handle the transaction
709 * lifecycle.
710 */
c45889f1 711 if (!transaction) {
d4c8db8f
PS
712 transaction = our_transaction = ref_transaction_begin(&err);
713 if (!transaction) {
714 ret = STORE_REF_ERROR_OTHER;
715 goto out;
716 }
c45889f1
PS
717 }
718
719 ret = ref_transaction_update(transaction, ref->name, &ref->new_oid,
720 check_old ? &ref->old_oid : NULL,
721 0, msg, &err);
cd94f765 722 if (ret) {
c45889f1
PS
723 ret = STORE_REF_ERROR_OTHER;
724 goto out;
cd94f765
RS
725 }
726
d4c8db8f
PS
727 if (our_transaction) {
728 switch (ref_transaction_commit(our_transaction, &err)) {
729 case 0:
730 break;
731 case TRANSACTION_NAME_CONFLICT:
732 ret = STORE_REF_ERROR_DF_CONFLICT;
733 goto out;
734 default:
735 ret = STORE_REF_ERROR_OTHER;
736 goto out;
737 }
c45889f1
PS
738 }
739
740out:
d4c8db8f 741 ref_transaction_free(our_transaction);
c45889f1
PS
742 if (ret)
743 error("%s", err.buf);
cd94f765 744 strbuf_release(&err);
1412f762 745 free(msg);
c45889f1 746 return ret;
b888d61c
DB
747}
748
6bc91f23 749static int refcol_width = 10;
bc437d10 750static int compact_format;
6bc91f23
NTND
751
752static void adjust_refcol_width(const struct ref *ref)
753{
754 int max, rlen, llen, len;
755
756 /* uptodate lines are only shown on high verbosity level */
f6bb64df 757 if (verbosity <= 0 && oideq(&ref->peer_ref->old_oid, &ref->old_oid))
6bc91f23
NTND
758 return;
759
760 max = term_columns();
761 rlen = utf8_strwidth(prettify_refname(ref->name));
bc437d10 762
6bc91f23
NTND
763 llen = utf8_strwidth(prettify_refname(ref->peer_ref->name));
764
765 /*
766 * rough estimation to see if the output line is too long and
767 * should not be counted (we can't do precise calculation
768 * anyway because we don't know if the error explanation part
769 * will be printed in update_local_ref)
770 */
bc437d10
NTND
771 if (compact_format) {
772 llen = 0;
773 max = max * 2 / 3;
774 }
6bc91f23
NTND
775 len = 21 /* flag and summary */ + rlen + 4 /* -> */ + llen;
776 if (len >= max)
777 return;
778
bc437d10
NTND
779 /*
780 * Not precise calculation for compact mode because '*' can
781 * appear on the left hand side of '->' and shrink the column
782 * back.
783 */
6bc91f23
NTND
784 if (refcol_width < rlen)
785 refcol_width = rlen;
786}
787
788static void prepare_format_display(struct ref *ref_map)
789{
790 struct ref *rm;
bc437d10
NTND
791 const char *format = "full";
792
f6bb64df
PS
793 if (verbosity < 0)
794 return;
795
f1de981e 796 git_config_get_string_tmp("fetch.output", &format);
bc437d10
NTND
797 if (!strcasecmp(format, "full"))
798 compact_format = 0;
799 else if (!strcasecmp(format, "compact"))
800 compact_format = 1;
801 else
1a8aea85
JNA
802 die(_("invalid value for '%s': '%s'"),
803 "fetch.output", format);
6bc91f23
NTND
804
805 for (rm = ref_map; rm; rm = rm->next) {
806 if (rm->status == REF_STATUS_REJECT_SHALLOW ||
807 !rm->peer_ref ||
808 !strcmp(rm->name, "HEAD"))
809 continue;
810
811 adjust_refcol_width(rm);
812 }
813}
165f3902 814
bc437d10
NTND
815static void print_remote_to_local(struct strbuf *display,
816 const char *remote, const char *local)
817{
818 strbuf_addf(display, "%-*s -> %s", refcol_width, remote, local);
819}
820
821static int find_and_replace(struct strbuf *haystack,
822 const char *needle,
823 const char *placeholder)
824{
dc40b24d 825 const char *p = NULL;
bc437d10
NTND
826 int plen, nlen;
827
dc40b24d
NTND
828 nlen = strlen(needle);
829 if (ends_with(haystack->buf, needle))
830 p = haystack->buf + haystack->len - nlen;
831 else
832 p = strstr(haystack->buf, needle);
bc437d10
NTND
833 if (!p)
834 return 0;
835
836 if (p > haystack->buf && p[-1] != '/')
837 return 0;
838
839 plen = strlen(p);
bc437d10
NTND
840 if (plen > nlen && p[nlen] != '/')
841 return 0;
842
843 strbuf_splice(haystack, p - haystack->buf, nlen,
844 placeholder, strlen(placeholder));
845 return 1;
846}
847
848static void print_compact(struct strbuf *display,
849 const char *remote, const char *local)
850{
851 struct strbuf r = STRBUF_INIT;
852 struct strbuf l = STRBUF_INIT;
853
854 if (!strcmp(remote, local)) {
855 strbuf_addf(display, "%-*s -> *", refcol_width, remote);
856 return;
857 }
858
859 strbuf_addstr(&r, remote);
860 strbuf_addstr(&l, local);
861
862 if (!find_and_replace(&r, local, "*"))
863 find_and_replace(&l, remote, "*");
864 print_remote_to_local(display, r.buf, l.buf);
865
866 strbuf_release(&r);
867 strbuf_release(&l);
868}
869
d0b39a03
NTND
870static void format_display(struct strbuf *display, char code,
871 const char *summary, const char *error,
901f3d40
JH
872 const char *remote, const char *local,
873 int summary_width)
d0b39a03 874{
f6bb64df
PS
875 int width;
876
877 if (verbosity < 0)
878 return;
879
880 width = (summary_width + strlen(summary) - gettext_width(summary));
901f3d40
JH
881
882 strbuf_addf(display, "%c %-*s ", code, width, summary);
bc437d10
NTND
883 if (!compact_format)
884 print_remote_to_local(display, remote, local);
885 else
886 print_compact(display, remote, local);
d0b39a03
NTND
887 if (error)
888 strbuf_addf(display, " (%s)", error);
889}
165f3902 890
b888d61c 891static int update_local_ref(struct ref *ref,
d4c8db8f 892 struct ref_transaction *transaction,
8bc1f39f 893 const char *remote, const struct ref *remote_ref,
b2463fc3 894 struct strbuf *display, int summary_width)
b888d61c 895{
b888d61c 896 struct commit *current = NULL, *updated;
4577e483 897 const char *pretty_ref = prettify_refname(ref->name);
377444b4 898 int fast_forward = 0;
b888d61c 899
47c61004 900 if (!repo_has_object_file(the_repository, &ref->new_oid))
f4e54d02 901 die(_("object %s not found"), oid_to_hex(&ref->new_oid));
b888d61c 902
4a7e27e9 903 if (oideq(&ref->old_oid, &ref->new_oid)) {
7f87aff2 904 if (verbosity > 0)
d0b39a03 905 format_display(display, '=', _("[up to date]"), NULL,
901f3d40 906 remote, pretty_ref, summary_width);
b888d61c
DB
907 return 0;
908 }
909
8bc1f39f 910 if (!update_head_ok &&
12d47e3b
DS
911 !is_null_oid(&ref->old_oid) &&
912 branch_checked_out(ref->name)) {
b888d61c
DB
913 /*
914 * If this is the head, and it's not okay to update
915 * the head, and the old value of the head isn't empty...
916 */
d0b39a03 917 format_display(display, '!', _("[rejected]"),
12d47e3b 918 _("can't fetch into checked-out branch"),
901f3d40 919 remote, pretty_ref, summary_width);
b888d61c
DB
920 return 1;
921 }
922
f4e54d02 923 if (!is_null_oid(&ref->old_oid) &&
59556548 924 starts_with(ref->name, "refs/tags/")) {
0bc8d71b
ÆAB
925 if (force || ref->force) {
926 int r;
d4c8db8f 927 r = s_update_ref("updating tag", ref, transaction, 0);
0bc8d71b
ÆAB
928 format_display(display, r ? '!' : 't', _("[tag update]"),
929 r ? _("unable to update local ref") : NULL,
930 remote, pretty_ref, summary_width);
931 return r;
932 } else {
933 format_display(display, '!', _("[rejected]"), _("would clobber existing tag"),
934 remote, pretty_ref, summary_width);
935 return 1;
936 }
b888d61c
DB
937 }
938
21e1ee8f
SB
939 current = lookup_commit_reference_gently(the_repository,
940 &ref->old_oid, 1);
941 updated = lookup_commit_reference_gently(the_repository,
942 &ref->new_oid, 1);
b888d61c 943 if (!current || !updated) {
165f3902
NP
944 const char *msg;
945 const char *what;
6315472e 946 int r;
0997adaa
MB
947 /*
948 * Nicely describe the new ref we're fetching.
949 * Base this on the remote's ref name, as it's
950 * more likely to follow a standard layout.
951 */
952 const char *name = remote_ref ? remote_ref->name : "";
59556548 953 if (starts_with(name, "refs/tags/")) {
b888d61c 954 msg = "storing tag";
f7b3742a 955 what = _("[new tag]");
59556548 956 } else if (starts_with(name, "refs/heads/")) {
b888d61c 957 msg = "storing head";
f7b3742a 958 what = _("[new branch]");
0997adaa
MB
959 } else {
960 msg = "storing ref";
961 what = _("[new ref]");
165f3902
NP
962 }
963
d4c8db8f 964 r = s_update_ref(msg, ref, transaction, 0);
d0b39a03
NTND
965 format_display(display, r ? '!' : '*', what,
966 r ? _("unable to update local ref") : NULL,
901f3d40 967 remote, pretty_ref, summary_width);
6315472e 968 return r;
b888d61c
DB
969 }
970
377444b4
DS
971 if (fetch_show_forced_updates) {
972 uint64_t t_before = getnanotime();
cb338c23
ÆAB
973 fast_forward = repo_in_merge_bases(the_repository, current,
974 updated);
377444b4
DS
975 forced_updates_ms += (getnanotime() - t_before) / 1000000;
976 } else {
977 fast_forward = 1;
978 }
979
980 if (fast_forward) {
bd22d4ff 981 struct strbuf quickref = STRBUF_INIT;
6315472e 982 int r;
cdbd70c4 983
30e677e0 984 strbuf_add_unique_abbrev(&quickref, &current->object.oid, DEFAULT_ABBREV);
bd22d4ff 985 strbuf_addstr(&quickref, "..");
30e677e0 986 strbuf_add_unique_abbrev(&quickref, &ref->new_oid, DEFAULT_ABBREV);
d4c8db8f 987 r = s_update_ref("fast-forward", ref, transaction, 1);
d0b39a03
NTND
988 format_display(display, r ? '!' : ' ', quickref.buf,
989 r ? _("unable to update local ref") : NULL,
901f3d40 990 remote, pretty_ref, summary_width);
bd22d4ff 991 strbuf_release(&quickref);
6315472e 992 return r;
165f3902 993 } else if (force || ref->force) {
bd22d4ff 994 struct strbuf quickref = STRBUF_INIT;
6315472e 995 int r;
30e677e0 996 strbuf_add_unique_abbrev(&quickref, &current->object.oid, DEFAULT_ABBREV);
bd22d4ff 997 strbuf_addstr(&quickref, "...");
30e677e0 998 strbuf_add_unique_abbrev(&quickref, &ref->new_oid, DEFAULT_ABBREV);
d4c8db8f 999 r = s_update_ref("forced-update", ref, transaction, 1);
d0b39a03
NTND
1000 format_display(display, r ? '!' : '+', quickref.buf,
1001 r ? _("unable to update local ref") : _("forced update"),
901f3d40 1002 remote, pretty_ref, summary_width);
bd22d4ff 1003 strbuf_release(&quickref);
6315472e 1004 return r;
165f3902 1005 } else {
d0b39a03 1006 format_display(display, '!', _("[rejected]"), _("non-fast-forward"),
901f3d40 1007 remote, pretty_ref, summary_width);
b888d61c
DB
1008 return 1;
1009 }
b888d61c
DB
1010}
1011
9fec7b21 1012static const struct object_id *iterate_ref_map(void *cb_data)
6b67e0dc 1013{
f0e278b1
JH
1014 struct ref **rm = cb_data;
1015 struct ref *ref = *rm;
6b67e0dc 1016
4820a33b
NTND
1017 while (ref && ref->status == REF_STATUS_REJECT_SHALLOW)
1018 ref = ref->next;
f0e278b1 1019 if (!ref)
9fec7b21 1020 return NULL;
f0e278b1 1021 *rm = ref->next;
9fec7b21 1022 return &ref->old_oid;
6b67e0dc
JH
1023}
1024
58a646a3
PS
1025struct fetch_head {
1026 FILE *fp;
929d0445 1027 struct strbuf buf;
58a646a3
PS
1028};
1029
1030static int open_fetch_head(struct fetch_head *fetch_head)
1031{
1032 const char *filename = git_path_fetch_head(the_repository);
1033
1034 if (write_fetch_head) {
1035 fetch_head->fp = fopen(filename, "a");
1036 if (!fetch_head->fp)
c4904377 1037 return error_errno(_("cannot open '%s'"), filename);
929d0445 1038 strbuf_init(&fetch_head->buf, 0);
58a646a3
PS
1039 } else {
1040 fetch_head->fp = NULL;
1041 }
1042
1043 return 0;
1044}
1045
1046static void append_fetch_head(struct fetch_head *fetch_head,
1047 const struct object_id *old_oid,
1048 enum fetch_head_status fetch_head_status,
1049 const char *note,
1050 const char *url, size_t url_len)
1051{
1052 char old_oid_hex[GIT_MAX_HEXSZ + 1];
1053 const char *merge_status_marker;
1054 size_t i;
1055
1056 if (!fetch_head->fp)
1057 return;
1058
1059 switch (fetch_head_status) {
1060 case FETCH_HEAD_NOT_FOR_MERGE:
1061 merge_status_marker = "not-for-merge";
1062 break;
1063 case FETCH_HEAD_MERGE:
1064 merge_status_marker = "";
1065 break;
1066 default:
1067 /* do not write anything to FETCH_HEAD */
1068 return;
1069 }
1070
929d0445
PS
1071 strbuf_addf(&fetch_head->buf, "%s\t%s\t%s",
1072 oid_to_hex_r(old_oid_hex, old_oid), merge_status_marker, note);
58a646a3
PS
1073 for (i = 0; i < url_len; ++i)
1074 if ('\n' == url[i])
929d0445 1075 strbuf_addstr(&fetch_head->buf, "\\n");
58a646a3 1076 else
929d0445
PS
1077 strbuf_addch(&fetch_head->buf, url[i]);
1078 strbuf_addch(&fetch_head->buf, '\n');
1079
c7b190da
PS
1080 /*
1081 * When using an atomic fetch, we do not want to update FETCH_HEAD if
1082 * any of the reference updates fails. We thus have to write all
1083 * updates to a buffer first and only commit it as soon as all
1084 * references have been successfully updated.
1085 */
1086 if (!atomic_fetch) {
1087 strbuf_write(&fetch_head->buf, fetch_head->fp);
1088 strbuf_reset(&fetch_head->buf);
1089 }
58a646a3
PS
1090}
1091
1092static void commit_fetch_head(struct fetch_head *fetch_head)
1093{
c7b190da
PS
1094 if (!fetch_head->fp || !atomic_fetch)
1095 return;
1096 strbuf_write(&fetch_head->buf, fetch_head->fp);
58a646a3
PS
1097}
1098
1099static void close_fetch_head(struct fetch_head *fetch_head)
1100{
1101 if (!fetch_head->fp)
1102 return;
1103
1104 fclose(fetch_head->fp);
929d0445 1105 strbuf_release(&fetch_head->buf);
58a646a3
PS
1106}
1107
182f59da 1108static const char warn_show_forced_updates[] =
66996bea
AK
1109N_("fetch normally indicates which branches had a forced update,\n"
1110 "but that check has been disabled; to re-enable, use '--show-forced-updates'\n"
1111 "flag or run 'git config fetch.showForcedUpdates true'");
182f59da 1112static const char warn_time_show_forced_updates[] =
66996bea 1113N_("it took %.2f seconds to check forced updates; you can use\n"
182f59da 1114 "'--no-show-forced-updates' or run 'git config fetch.showForcedUpdates false'\n"
66996bea 1115 "to avoid this check\n");
182f59da 1116
47abd85b 1117static int store_updated_refs(const char *raw_url, const char *remote_name,
b3a80466
PS
1118 int connectivity_checked,
1119 struct ref_transaction *transaction, struct ref *ref_map,
b2463fc3 1120 struct fetch_head *fetch_head)
b888d61c 1121{
4b3b33a7 1122 int url_len, i, rc = 0;
4f40f6cb 1123 struct strbuf note = STRBUF_INIT;
b888d61c
DB
1124 const char *what, *kind;
1125 struct ref *rm;
dcf69262 1126 char *url;
900f2814 1127 int want_status;
b18aaaa5 1128 int summary_width = 0;
b888d61c 1129
b18aaaa5
PS
1130 if (verbosity >= 0)
1131 summary_width = transport_summary_width(ref_map);
1132
fb0cc87e
DB
1133 if (raw_url)
1134 url = transport_anonymize_url(raw_url);
1135 else
1136 url = xstrdup("foreign");
6b67e0dc 1137
cf1e7c07 1138 if (!connectivity_checked) {
2df1aa23
JT
1139 struct check_connected_options opt = CHECK_CONNECTED_INIT;
1140
c6ce27ab 1141 opt.exclude_hidden_refs_section = "fetch";
cf1e7c07 1142 rm = ref_map;
2df1aa23 1143 if (check_connected(iterate_ref_map, &rm, &opt)) {
cf1e7c07
JT
1144 rc = error(_("%s did not send all necessary objects\n"), url);
1145 goto abort;
1146 }
9516a598 1147 }
6b67e0dc 1148
6bc91f23
NTND
1149 prepare_format_display(ref_map);
1150
96890f4c 1151 /*
900f2814
JK
1152 * We do a pass for each fetch_head_status type in their enum order, so
1153 * merged entries are written before not-for-merge. That lets readers
1154 * use FETCH_HEAD as a refname to refer to the ref to be merged.
96890f4c 1155 */
900f2814
JK
1156 for (want_status = FETCH_HEAD_MERGE;
1157 want_status <= FETCH_HEAD_IGNORE;
1158 want_status++) {
96890f4c
JH
1159 for (rm = ref_map; rm; rm = rm->next) {
1160 struct ref *ref = NULL;
1161
4820a33b
NTND
1162 if (rm->status == REF_STATUS_REJECT_SHALLOW) {
1163 if (want_status == FETCH_HEAD_MERGE)
09667e95 1164 warning(_("rejected %s because shallow roots are not allowed to be updated"),
4820a33b
NTND
1165 rm->peer_ref ? rm->peer_ref->name : rm->name);
1166 continue;
1167 }
1168
fe7df03a 1169 /*
8e55634b
PS
1170 * When writing FETCH_HEAD we need to determine whether
1171 * we already have the commit or not. If not, then the
1172 * reference is not for merge and needs to be written
1173 * to the reflog after other commits which we already
1174 * have. We're not interested in this property though
1175 * in case FETCH_HEAD is not to be updated, so we can
1176 * skip the classification in that case.
fe7df03a 1177 */
8e55634b
PS
1178 if (fetch_head->fp) {
1179 struct commit *commit = NULL;
1180
1181 /*
1182 * References in "refs/tags/" are often going to point
1183 * to annotated tags, which are not part of the
1184 * commit-graph. We thus only try to look up refs in
1185 * the graph which are not in that namespace to not
1186 * regress performance in repositories with many
1187 * annotated tags.
1188 */
1189 if (!starts_with(rm->name, "refs/tags/"))
1190 commit = lookup_commit_in_graph(the_repository, &rm->old_oid);
1191 if (!commit) {
1192 commit = lookup_commit_reference_gently(the_repository,
1193 &rm->old_oid,
1194 1);
1195 if (!commit)
1196 rm->fetch_head_status = FETCH_HEAD_NOT_FOR_MERGE;
1197 }
fe7df03a 1198 }
96890f4c 1199
900f2814 1200 if (rm->fetch_head_status != want_status)
96890f4c
JH
1201 continue;
1202
1203 if (rm->peer_ref) {
6f687c21 1204 ref = alloc_ref(rm->peer_ref->name);
f4e54d02 1205 oidcpy(&ref->old_oid, &rm->peer_ref->old_oid);
1206 oidcpy(&ref->new_oid, &rm->old_oid);
96890f4c
JH
1207 ref->force = rm->peer_ref->force;
1208 }
b888d61c 1209
7ea0c2f4
OS
1210 if (recurse_submodules != RECURSE_SUBMODULES_OFF &&
1211 (!rm->peer_ref || !oideq(&ref->old_oid, &ref->new_oid))) {
be76c212 1212 check_for_new_submodule_commits(&rm->old_oid);
7ea0c2f4 1213 }
b888d61c 1214
96890f4c
JH
1215 if (!strcmp(rm->name, "HEAD")) {
1216 kind = "";
1217 what = "";
1218 }
a6293f5d 1219 else if (skip_prefix(rm->name, "refs/heads/", &what))
96890f4c 1220 kind = "branch";
a6293f5d 1221 else if (skip_prefix(rm->name, "refs/tags/", &what))
96890f4c 1222 kind = "tag";
a6293f5d 1223 else if (skip_prefix(rm->name, "refs/remotes/", &what))
96890f4c 1224 kind = "remote-tracking branch";
96890f4c
JH
1225 else {
1226 kind = "";
1227 what = rm->name;
1228 }
b888d61c 1229
96890f4c
JH
1230 url_len = strlen(url);
1231 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
1232 ;
1233 url_len = i + 1;
1234 if (4 < i && !strncmp(".git", url + i - 3, 4))
1235 url_len = i - 3;
1236
1237 strbuf_reset(&note);
1238 if (*what) {
1239 if (*kind)
1240 strbuf_addf(&note, "%s ", kind);
1241 strbuf_addf(&note, "'%s' of ", what);
1242 }
58a646a3 1243
2983cec0 1244 append_fetch_head(fetch_head, &rm->old_oid,
58a646a3
PS
1245 rm->fetch_head_status,
1246 note.buf, url, url_len);
96890f4c
JH
1247
1248 strbuf_reset(&note);
1249 if (ref) {
c7b190da 1250 rc |= update_local_ref(ref, transaction, what,
b2463fc3 1251 rm, &note, summary_width);
96890f4c 1252 free(ref);
db3c293e
JT
1253 } else if (write_fetch_head || dry_run) {
1254 /*
1255 * Display fetches written to FETCH_HEAD (or
1256 * would be written to FETCH_HEAD, if --dry-run
1257 * is set).
1258 */
d0b39a03
NTND
1259 format_display(&note, '*',
1260 *kind ? kind : "branch", NULL,
1261 *what ? what : "HEAD",
901f3d40 1262 "FETCH_HEAD", summary_width);
db3c293e 1263 }
96890f4c 1264 if (note.len) {
f6bb64df 1265 if (!shown_url) {
96890f4c
JH
1266 fprintf(stderr, _("From %.*s\n"),
1267 url_len, url);
1268 shown_url = 1;
1269 }
f6bb64df 1270 fprintf(stderr, " %s\n", note.buf);
165f3902
NP
1271 }
1272 }
b888d61c 1273 }
9516a598 1274
fa250759 1275 if (rc & STORE_REF_ERROR_DF_CONFLICT)
bd4a51fc 1276 error(_("some local refs could not be updated; try running\n"
f3cb169b 1277 " 'git remote prune %s' to remove any old, conflicting "
bd4a51fc 1278 "branches"), remote_name);
9516a598 1279
ed9bff08 1280 if (advice_enabled(ADVICE_FETCH_SHOW_FORCED_UPDATES)) {
377444b4 1281 if (!fetch_show_forced_updates) {
182f59da 1282 warning(_(warn_show_forced_updates));
377444b4 1283 } else if (forced_updates_ms > FORCED_UPDATES_DELAY_WARNING_IN_MS) {
182f59da 1284 warning(_(warn_time_show_forced_updates),
377444b4 1285 forced_updates_ms / 1000.0);
377444b4
DS
1286 }
1287 }
1288
9516a598 1289 abort:
5914f2d0 1290 strbuf_release(&note);
9516a598 1291 free(url);
efb98b44 1292 return rc;
b888d61c
DB
1293}
1294
4191c356
SP
1295/*
1296 * We would want to bypass the object transfer altogether if
d9eb0205 1297 * everything we are going to fetch already exists and is connected
4191c356 1298 * locally.
4191c356 1299 */
35f9e3e5 1300static int check_exist_and_connected(struct ref *ref_map)
4191c356 1301{
f0e278b1 1302 struct ref *rm = ref_map;
7043c707 1303 struct check_connected_options opt = CHECK_CONNECTED_INIT;
35f9e3e5 1304 struct ref *r;
f0e278b1 1305
4191c356
SP
1306 /*
1307 * If we are deepening a shallow clone we already have these
1308 * objects reachable. Running rev-list here will return with
1309 * a good (0) exit status and we'll bypass the fetch that we
1310 * really need to perform. Claiming failure now will ensure
1311 * we perform the network exchange to deepen our history.
1312 */
508ea882 1313 if (deepen)
4191c356 1314 return -1;
35f9e3e5 1315
3c7bab06
RC
1316 /*
1317 * Similarly, if we need to refetch, we always want to perform a full
1318 * fetch ignoring existing objects.
1319 */
1320 if (refetch)
1321 return -1;
1322
1323
35f9e3e5
JT
1324 /*
1325 * check_connected() allows objects to merely be promised, but
1326 * we need all direct targets to exist.
1327 */
1328 for (r = rm; r; r = r->next) {
bc726bd0
ÆAB
1329 if (!repo_has_object_file_with_flags(the_repository, &r->old_oid,
1330 OBJECT_INFO_SKIP_FETCH_OBJECT))
35f9e3e5
JT
1331 return -1;
1332 }
1333
7043c707 1334 opt.quiet = 1;
c6ce27ab 1335 opt.exclude_hidden_refs_section = "fetch";
7043c707 1336 return check_connected(iterate_ref_map, &rm, &opt);
4191c356
SP
1337}
1338
8bc1f39f 1339static int fetch_and_consume_refs(struct transport *transport,
b3a80466 1340 struct ref_transaction *transaction,
8bc1f39f 1341 struct ref *ref_map,
b2463fc3 1342 struct fetch_head *fetch_head)
b888d61c 1343{
caff8b73 1344 int connectivity_checked = 1;
284b2ce8
PS
1345 int ret;
1346
1347 /*
1348 * We don't need to perform a fetch in case we can already satisfy all
1349 * refs.
1350 */
1351 ret = check_exist_and_connected(ref_map);
5fc31180
JS
1352 if (ret) {
1353 trace2_region_enter("fetch", "fetch_refs", the_repository);
e2842b39 1354 ret = transport_fetch_refs(transport, ref_map);
5fc31180 1355 trace2_region_leave("fetch", "fetch_refs", the_repository);
284b2ce8
PS
1356 if (ret)
1357 goto out;
caff8b73
PS
1358 connectivity_checked = transport->smart_options ?
1359 transport->smart_options->connectivity_checked : 0;
5fc31180 1360 }
05c44226 1361
5fc31180 1362 trace2_region_enter("fetch", "consume_refs", the_repository);
8bc1f39f 1363 ret = store_updated_refs(transport->url, transport->remote->name,
b3a80466 1364 connectivity_checked, transaction, ref_map,
b2463fc3 1365 fetch_head);
5fc31180 1366 trace2_region_leave("fetch", "consume_refs", the_repository);
1c7d1ab6
PS
1367
1368out:
58d4d7f1 1369 transport_unlock_pack(transport, 0);
b888d61c
DB
1370 return ret;
1371}
1372
583bc419
PS
1373static int prune_refs(struct refspec *rs,
1374 struct ref_transaction *transaction,
1375 struct ref *ref_map,
def11e71 1376 const char *raw_url)
f360d844 1377{
4b3b33a7 1378 int url_len, i, result = 0;
a2ac50cb 1379 struct ref *ref, *stale_refs = get_stale_heads(rs, ref_map);
583bc419 1380 struct strbuf err = STRBUF_INIT;
4b3b33a7 1381 char *url;
f360d844 1382 const char *dangling_msg = dry_run
18986d53
NTND
1383 ? _(" (%s will become dangling)")
1384 : _(" (%s has become dangling)");
f360d844 1385
4b3b33a7
TM
1386 if (raw_url)
1387 url = transport_anonymize_url(raw_url);
1388 else
1389 url = xstrdup("foreign");
1390
1391 url_len = strlen(url);
1392 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
1393 ;
1394
1395 url_len = i + 1;
1396 if (4 < i && !strncmp(".git", url + i - 3, 4))
1397 url_len = i - 3;
1398
a087b432 1399 if (!dry_run) {
583bc419
PS
1400 if (transaction) {
1401 for (ref = stale_refs; ref; ref = ref->next) {
1402 result = ref_transaction_delete(transaction, ref->name, NULL, 0,
1403 "fetch: prune", &err);
1404 if (result)
1405 goto cleanup;
1406 }
1407 } else {
1408 struct string_list refnames = STRING_LIST_INIT_NODUP;
a087b432 1409
583bc419
PS
1410 for (ref = stale_refs; ref; ref = ref->next)
1411 string_list_append(&refnames, ref->name);
a087b432 1412
583bc419
PS
1413 result = delete_refs("fetch: prune", &refnames, 0);
1414 string_list_clear(&refnames, 0);
1415 }
a087b432
MH
1416 }
1417
1418 if (verbosity >= 0) {
b18aaaa5
PS
1419 int summary_width = transport_summary_width(stale_refs);
1420
a087b432 1421 for (ref = stale_refs; ref; ref = ref->next) {
d0b39a03 1422 struct strbuf sb = STRBUF_INIT;
a087b432
MH
1423 if (!shown_url) {
1424 fprintf(stderr, _("From %.*s\n"), url_len, url);
1425 shown_url = 1;
1426 }
2cb040ba 1427 format_display(&sb, '-', _("[deleted]"), NULL,
901f3d40
JH
1428 _("(none)"), prettify_refname(ref->name),
1429 summary_width);
d0b39a03
NTND
1430 fprintf(stderr, " %s\n",sb.buf);
1431 strbuf_release(&sb);
f360d844
JS
1432 warn_dangling_symref(stderr, dangling_msg, ref->name);
1433 }
1434 }
a087b432 1435
583bc419
PS
1436cleanup:
1437 strbuf_release(&err);
4b3b33a7 1438 free(url);
f360d844
JS
1439 free_refs(stale_refs);
1440 return result;
1441}
1442
12d47e3b 1443static void check_not_current_branch(struct ref *ref_map)
8ee5d731 1444{
12d47e3b 1445 const char *path;
8ee5d731 1446 for (; ref_map; ref_map = ref_map->next)
8bc1f39f 1447 if (ref_map->peer_ref &&
f7400da8 1448 starts_with(ref_map->peer_ref->name, "refs/heads/") &&
12d47e3b 1449 (path = branch_checked_out(ref_map->peer_ref->name)))
8bc1f39f
AK
1450 die(_("refusing to fetch into branch '%s' "
1451 "checked out at '%s'"),
12d47e3b 1452 ref_map->peer_ref->name, path);
8ee5d731
JS
1453}
1454
e6cc5104
JH
1455static int truncate_fetch_head(void)
1456{
102de880 1457 const char *filename = git_path_fetch_head(the_repository);
ea56518d 1458 FILE *fp = fopen_for_writing(filename);
e6cc5104
JH
1459
1460 if (!fp)
c4904377 1461 return error_errno(_("cannot open '%s'"), filename);
e6cc5104
JH
1462 fclose(fp);
1463 return 0;
1464}
1465
db5723c6
JH
1466static void set_option(struct transport *transport, const char *name, const char *value)
1467{
1468 int r = transport_set_option(transport, name, value);
1469 if (r < 0)
66996bea 1470 die(_("option \"%s\" value \"%s\" is not valid for %s"),
db5723c6
JH
1471 name, value, transport->url);
1472 if (r > 0)
66996bea 1473 warning(_("option \"%s\" is ignored for %s\n"),
db5723c6
JH
1474 name, transport->url);
1475}
1476
3390e42a 1477
5cf88fd8 1478static int add_oid(const char *refname UNUSED,
63e14ee2 1479 const struct object_id *oid,
5cf88fd8 1480 int flags UNUSED, void *cb_data)
3390e42a
JT
1481{
1482 struct oid_array *oids = cb_data;
1483
1484 oid_array_append(oids, oid);
1485 return 0;
1486}
1487
1488static void add_negotiation_tips(struct git_transport_options *smart_options)
1489{
1490 struct oid_array *oids = xcalloc(1, sizeof(*oids));
1491 int i;
1492
1493 for (i = 0; i < negotiation_tip.nr; i++) {
1494 const char *s = negotiation_tip.items[i].string;
1495 int old_nr;
1496 if (!has_glob_specials(s)) {
1497 struct object_id oid;
d850b7a5 1498 if (repo_get_oid(the_repository, s, &oid))
82823118
JT
1499 die(_("%s is not a valid object"), s);
1500 if (!has_object(the_repository, &oid, 0))
1501 die(_("the object %s does not exist"), s);
3390e42a
JT
1502 oid_array_append(oids, &oid);
1503 continue;
1504 }
1505 old_nr = oids->nr;
1506 for_each_glob_ref(add_oid, s, oids);
1507 if (old_nr == oids->nr)
66996bea 1508 warning("ignoring --negotiation-tip=%s because it does not match any refs",
3390e42a
JT
1509 s);
1510 }
1511 smart_options->negotiation_tips = oids;
1512}
1513
508ea882 1514static struct transport *prepare_transport(struct remote *remote, int deepen)
db5723c6
JH
1515{
1516 struct transport *transport;
87c2d9d3 1517
db5723c6
JH
1518 transport = transport_get(remote, NULL);
1519 transport_set_verbosity(transport, verbosity, progress);
c915f11e 1520 transport->family = family;
db5723c6
JH
1521 if (upload_pack)
1522 set_option(transport, TRANS_OPT_UPLOADPACK, upload_pack);
1523 if (keep)
1524 set_option(transport, TRANS_OPT_KEEP, "yes");
1525 if (depth)
1526 set_option(transport, TRANS_OPT_DEPTH, depth);
508ea882
NTND
1527 if (deepen && deepen_since)
1528 set_option(transport, TRANS_OPT_DEEPEN_SINCE, deepen_since);
a45a2600
NTND
1529 if (deepen && deepen_not.nr)
1530 set_option(transport, TRANS_OPT_DEEPEN_NOT,
1531 (const char *)&deepen_not);
cccf74e2
NTND
1532 if (deepen_relative)
1533 set_option(transport, TRANS_OPT_DEEPEN_RELATIVE, "yes");
48d25cae
NTND
1534 if (update_shallow)
1535 set_option(transport, TRANS_OPT_UPDATE_SHALLOW, "yes");
3c7bab06
RC
1536 if (refetch)
1537 set_option(transport, TRANS_OPT_REFETCH, "yes");
acb0c572 1538 if (filter_options.choice) {
cf9ceb5a
MD
1539 const char *spec =
1540 expand_list_objects_filter_spec(&filter_options);
1541 set_option(transport, TRANS_OPT_LIST_OBJECTS_FILTER, spec);
acb0c572
JH
1542 set_option(transport, TRANS_OPT_FROM_PROMISOR, "1");
1543 }
3390e42a
JT
1544 if (negotiation_tip.nr) {
1545 if (transport->smart_options)
1546 add_negotiation_tips(transport->smart_options);
1547 else
66996bea 1548 warning("ignoring --negotiation-tip because the protocol does not support it");
3390e42a 1549 }
db5723c6
JH
1550 return transport;
1551}
1552
62091b4c 1553static int backfill_tags(struct transport *transport,
b3a80466 1554 struct ref_transaction *transaction,
62091b4c 1555 struct ref *ref_map,
b2463fc3 1556 struct fetch_head *fetch_head)
069d5032 1557{
62091b4c 1558 int retcode, cannot_reuse;
508ea882
NTND
1559
1560 /*
1561 * Once we have set TRANS_OPT_DEEPEN_SINCE, we can't unset it
1562 * when remote helper is used (setting it to an empty string
1563 * is not unsetting). We could extend the remote helper
1564 * protocol for that, but for now, just force a new connection
a45a2600 1565 * without deepen-since. Similar story for deepen-not.
508ea882 1566 */
a45a2600
NTND
1567 cannot_reuse = transport->cannot_reuse ||
1568 deepen_since || deepen_not.nr;
508ea882
NTND
1569 if (cannot_reuse) {
1570 gsecondary = prepare_transport(transport->remote, 0);
b26ed430
JH
1571 transport = gsecondary;
1572 }
1573
069d5032
JH
1574 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
1575 transport_set_option(transport, TRANS_OPT_DEPTH, "0");
cccf74e2 1576 transport_set_option(transport, TRANS_OPT_DEEPEN_RELATIVE, NULL);
b2463fc3 1577 retcode = fetch_and_consume_refs(transport, transaction, ref_map, fetch_head);
b26ed430
JH
1578
1579 if (gsecondary) {
1580 transport_disconnect(gsecondary);
1581 gsecondary = NULL;
1582 }
62091b4c
PS
1583
1584 return retcode;
069d5032
JH
1585}
1586
b888d61c 1587static int do_fetch(struct transport *transport,
65a1301f 1588 struct refspec *rs)
b888d61c 1589{
b3a80466 1590 struct ref_transaction *transaction = NULL;
efbade06 1591 struct ref *ref_map = NULL;
b888d61c 1592 int autotags = (transport->remote->fetch_tags == 1);
5b87d8d3 1593 int retcode = 0;
6d1700d5 1594 const struct ref *remote_refs;
39835409
JT
1595 struct transport_ls_refs_options transport_ls_refs_options =
1596 TRANSPORT_LS_REFS_OPTIONS_INIT;
e70a3030 1597 int must_list_refs = 1;
2983cec0 1598 struct fetch_head fetch_head = { 0 };
b3a80466 1599 struct strbuf err = STRBUF_INIT;
b1a01e1c 1600
ed368546
DJ
1601 if (tags == TAGS_DEFAULT) {
1602 if (transport->remote->fetch_tags == 2)
1603 tags = TAGS_SET;
1604 if (transport->remote->fetch_tags == -1)
1605 tags = TAGS_UNSET;
1606 }
b888d61c 1607
b888d61c 1608 /* if not appending, truncate FETCH_HEAD */
887952b8 1609 if (!append && write_fetch_head) {
5b87d8d3
MH
1610 retcode = truncate_fetch_head();
1611 if (retcode)
1612 goto cleanup;
d6617c7c 1613 }
b888d61c 1614
e70a3030
JT
1615 if (rs->nr) {
1616 int i;
1617
39835409 1618 refspec_ref_prefixes(rs, &transport_ls_refs_options.ref_prefixes);
e70a3030
JT
1619
1620 /*
1621 * We can avoid listing refs if all of them are exact
1622 * OIDs
1623 */
1624 must_list_refs = 0;
1625 for (i = 0; i < rs->nr; i++) {
1626 if (!rs->items[i].exact_sha1) {
1627 must_list_refs = 1;
1628 break;
1629 }
1630 }
49ca2fba
JK
1631 } else {
1632 struct branch *branch = branch_get(NULL);
1633
1634 if (transport->remote->fetch.nr)
1635 refspec_ref_prefixes(&transport->remote->fetch,
1636 &transport_ls_refs_options.ref_prefixes);
1637 if (branch_has_merge_config(branch) &&
1638 !strcmp(branch->remote_name, transport->remote->name)) {
1639 int i;
1640 for (i = 0; i < branch->merge_nr; i++) {
1641 strvec_push(&transport_ls_refs_options.ref_prefixes,
1642 branch->merge[i]->src);
1643 }
1644 }
1645 }
b888d61c 1646
e70a3030
JT
1647 if (tags == TAGS_SET || tags == TAGS_DEFAULT) {
1648 must_list_refs = 1;
39835409
JT
1649 if (transport_ls_refs_options.ref_prefixes.nr)
1650 strvec_push(&transport_ls_refs_options.ref_prefixes,
1651 "refs/tags/");
b888d61c
DB
1652 }
1653
5fc31180
JS
1654 if (must_list_refs) {
1655 trace2_region_enter("fetch", "remote_refs", the_repository);
39835409
JT
1656 remote_refs = transport_get_remote_refs(transport,
1657 &transport_ls_refs_options);
5fc31180
JS
1658 trace2_region_leave("fetch", "remote_refs", the_repository);
1659 } else
e70a3030
JT
1660 remote_refs = NULL;
1661
f36d4f83 1662 transport_ls_refs_options_release(&transport_ls_refs_options);
6d1700d5
BW
1663
1664 ref_map = get_ref_map(transport->remote, remote_refs, rs,
1665 tags, &autotags);
8ee5d731 1666 if (!update_head_ok)
12d47e3b 1667 check_not_current_branch(ref_map);
b888d61c 1668
2983cec0
PS
1669 retcode = open_fetch_head(&fetch_head);
1670 if (retcode)
1671 goto cleanup;
1672
b3a80466
PS
1673 if (atomic_fetch) {
1674 transaction = ref_transaction_begin(&err);
1675 if (!transaction) {
1676 retcode = error("%s", err.buf);
1677 goto cleanup;
1678 }
1679 }
1680
41fa7d2e
SP
1681 if (tags == TAGS_DEFAULT && autotags)
1682 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
ed43de6e 1683 if (prune) {
0838bf47
MH
1684 /*
1685 * We only prune based on refspecs specified
1686 * explicitly (via command line or configuration); we
1687 * don't care whether --tags was specified.
1688 */
65a1301f 1689 if (rs->nr) {
583bc419 1690 retcode = prune_refs(rs, transaction, ref_map, transport->url);
e8c1e6c7 1691 } else {
c9e04d90 1692 retcode = prune_refs(&transport->remote->fetch,
583bc419 1693 transaction, ref_map,
c9e04d90 1694 transport->url);
e8c1e6c7 1695 }
c9e04d90
TG
1696 if (retcode != 0)
1697 retcode = 1;
ed43de6e 1698 }
2983cec0 1699
b2463fc3 1700 if (fetch_and_consume_refs(transport, transaction, ref_map, &fetch_head)) {
10a6cc88
TM
1701 retcode = 1;
1702 goto cleanup;
1703 }
24bc1a12 1704
efbade06
PS
1705 /*
1706 * If neither --no-tags nor --tags was specified, do automated tag
1707 * following.
1708 */
1709 if (tags == TAGS_DEFAULT && autotags) {
1710 struct ref *tags_ref_map = NULL, **tail = &tags_ref_map;
1711
b3a80466 1712 find_non_local_tags(remote_refs, transaction, &tags_ref_map, &tail);
62091b4c
PS
1713 if (tags_ref_map) {
1714 /*
1715 * If backfilling of tags fails then we want to tell
1716 * the user so, but we have to continue regardless to
1717 * populate upstream information of the references we
b3a80466
PS
1718 * have already fetched above. The exception though is
1719 * when `--atomic` is passed: in that case we'll abort
1720 * the transaction and don't commit anything.
62091b4c 1721 */
b3a80466 1722 if (backfill_tags(transport, transaction, tags_ref_map,
b2463fc3 1723 &fetch_head))
62091b4c
PS
1724 retcode = 1;
1725 }
efbade06
PS
1726
1727 free_refs(tags_ref_map);
1728 }
1729
b3a80466
PS
1730 if (transaction) {
1731 if (retcode)
1732 goto cleanup;
1733
1734 retcode = ref_transaction_commit(transaction, &err);
1735 if (retcode) {
1736 error("%s", err.buf);
1737 ref_transaction_free(transaction);
1738 transaction = NULL;
1739 goto cleanup;
1740 }
1741 }
1742
2983cec0
PS
1743 commit_fetch_head(&fetch_head);
1744
24bc1a12
CB
1745 if (set_upstream) {
1746 struct branch *branch = branch_get("HEAD");
1747 struct ref *rm;
1748 struct ref *source_ref = NULL;
1749
1750 /*
1751 * We're setting the upstream configuration for the
15beaaa3 1752 * current branch. The relevant upstream is the
24bc1a12
CB
1753 * fetched branch that is meant to be merged with the
1754 * current one, i.e. the one fetched to FETCH_HEAD.
1755 *
1756 * When there are several such branches, consider the
1757 * request ambiguous and err on the safe side by doing
1758 * nothing and just emit a warning.
1759 */
1760 for (rm = ref_map; rm; rm = rm->next) {
1761 if (!rm->peer_ref) {
1762 if (source_ref) {
391c7e40 1763 warning(_("multiple branches detected, incompatible with --set-upstream"));
efbade06 1764 goto cleanup;
24bc1a12
CB
1765 } else {
1766 source_ref = rm;
1767 }
1768 }
1769 }
1770 if (source_ref) {
17baeaf8
ÆAB
1771 if (!branch) {
1772 const char *shortname = source_ref->name;
1773 skip_prefix(shortname, "refs/heads/", &shortname);
1774
1775 warning(_("could not set upstream of HEAD to '%s' from '%s' when "
1776 "it does not point to any branch."),
1777 shortname, transport->remote->name);
efbade06 1778 goto cleanup;
17baeaf8
ÆAB
1779 }
1780
24bc1a12
CB
1781 if (!strcmp(source_ref->name, "HEAD") ||
1782 starts_with(source_ref->name, "refs/heads/"))
1783 install_branch_config(0,
1784 branch->name,
1785 transport->remote->name,
1786 source_ref->name);
1787 else if (starts_with(source_ref->name, "refs/remotes/"))
1788 warning(_("not setting upstream for a remote remote-tracking branch"));
1789 else if (starts_with(source_ref->name, "refs/tags/"))
1790 warning(_("not setting upstream for a remote tag"));
1791 else
1792 warning(_("unknown branch type"));
1793 } else {
66996bea
AK
1794 warning(_("no source branch found;\n"
1795 "you need to specify exactly one branch with the --set-upstream option"));
24bc1a12
CB
1796 }
1797 }
b888d61c 1798
8bc1f39f 1799cleanup:
b3a80466
PS
1800 if (retcode && transaction) {
1801 ref_transaction_abort(transaction, &err);
1802 error("%s", err.buf);
b888d61c
DB
1803 }
1804
2983cec0 1805 close_fetch_head(&fetch_head);
b3a80466 1806 strbuf_release(&err);
efbade06 1807 free_refs(ref_map);
5b87d8d3 1808 return retcode;
b888d61c
DB
1809}
1810
9c4a036b
BG
1811static int get_one_remote_for_fetch(struct remote *remote, void *priv)
1812{
1813 struct string_list *list = priv;
7cc91a2f 1814 if (!remote->skip_default_update)
1d2f80fa 1815 string_list_append(list, remote->name);
9c4a036b
BG
1816 return 0;
1817}
1818
1819struct remote_group_data {
1820 const char *name;
1821 struct string_list *list;
1822};
1823
1824static int get_remote_group(const char *key, const char *value, void *priv)
1825{
1826 struct remote_group_data *g = priv;
1827
bc598c32 1828 if (skip_prefix(key, "remotes.", &key) && !strcmp(key, g->name)) {
9c4a036b 1829 /* split list by white space */
9c4a036b 1830 while (*value) {
5f65499f
MH
1831 size_t wordlen = strcspn(value, " \t\n");
1832
e286542d 1833 if (wordlen >= 1)
b7410f61 1834 string_list_append_nodup(g->list,
e286542d
MH
1835 xstrndup(value, wordlen));
1836 value += wordlen + (value[wordlen] != '\0');
9c4a036b
BG
1837 }
1838 }
1839
1840 return 0;
1841}
1842
1843static int add_remote_or_group(const char *name, struct string_list *list)
1844{
1845 int prev_nr = list->nr;
66dbfd55
GV
1846 struct remote_group_data g;
1847 g.name = name; g.list = list;
9c4a036b
BG
1848
1849 git_config(get_remote_group, &g);
1850 if (list->nr == prev_nr) {
674468b3 1851 struct remote *remote = remote_get(name);
e459b073 1852 if (!remote_is_configured(remote, 0))
9c4a036b 1853 return 0;
1d2f80fa 1854 string_list_append(list, remote->name);
9c4a036b
BG
1855 }
1856 return 1;
1857}
1858
22f9b7f3 1859static void add_options_to_argv(struct strvec *argv)
9c4a036b 1860{
28a15401 1861 if (dry_run)
22f9b7f3 1862 strvec_push(argv, "--dry-run");
90765fa3 1863 if (prune != -1)
22f9b7f3 1864 strvec_push(argv, prune ? "--prune" : "--no-prune");
97716d21 1865 if (prune_tags != -1)
22f9b7f3 1866 strvec_push(argv, prune_tags ? "--prune-tags" : "--no-prune-tags");
bba5322a 1867 if (update_head_ok)
22f9b7f3 1868 strvec_push(argv, "--update-head-ok");
bba5322a 1869 if (force)
22f9b7f3 1870 strvec_push(argv, "--force");
bba5322a 1871 if (keep)
22f9b7f3 1872 strvec_push(argv, "--keep");
be254a0e 1873 if (recurse_submodules == RECURSE_SUBMODULES_ON)
22f9b7f3 1874 strvec_push(argv, "--recurse-submodules");
8f0700dd 1875 else if (recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND)
22f9b7f3 1876 strvec_push(argv, "--recurse-submodules=on-demand");
85566460 1877 if (tags == TAGS_SET)
22f9b7f3 1878 strvec_push(argv, "--tags");
85566460 1879 else if (tags == TAGS_UNSET)
22f9b7f3 1880 strvec_push(argv, "--no-tags");
9c4a036b 1881 if (verbosity >= 2)
22f9b7f3 1882 strvec_push(argv, "-v");
9c4a036b 1883 if (verbosity >= 1)
22f9b7f3 1884 strvec_push(argv, "-v");
9c4a036b 1885 else if (verbosity < 0)
22f9b7f3 1886 strvec_push(argv, "-q");
4e735c13 1887 if (family == TRANSPORT_FAMILY_IPV4)
6854689e 1888 strvec_push(argv, "--ipv4");
4e735c13 1889 else if (family == TRANSPORT_FAMILY_IPV6)
6854689e 1890 strvec_push(argv, "--ipv6");
15184ae9
EW
1891 if (!write_fetch_head)
1892 strvec_push(argv, "--no-write-fetch-head");
7dce19d3
JL
1893}
1894
d54dea77
JS
1895/* Fetch multiple remotes in parallel */
1896
1897struct parallel_fetch_state {
1898 const char **argv;
1899 struct string_list *remotes;
1900 int next, result;
1901};
1902
a5c76b36
JK
1903static int fetch_next_remote(struct child_process *cp,
1904 struct strbuf *out UNUSED,
d54dea77
JS
1905 void *cb, void **task_cb)
1906{
1907 struct parallel_fetch_state *state = cb;
1908 char *remote;
1909
1910 if (state->next < 0 || state->next >= state->remotes->nr)
1911 return 0;
1912
1913 remote = state->remotes->items[state->next++].string;
1914 *task_cb = remote;
1915
22f9b7f3
JK
1916 strvec_pushv(&cp->args, state->argv);
1917 strvec_push(&cp->args, remote);
d54dea77
JS
1918 cp->git_cmd = 1;
1919
1920 if (verbosity >= 0)
1921 printf(_("Fetching %s\n"), remote);
1922
1923 return 1;
1924}
1925
a5c76b36
JK
1926static int fetch_failed_to_start(struct strbuf *out UNUSED,
1927 void *cb, void *task_cb)
d54dea77
JS
1928{
1929 struct parallel_fetch_state *state = cb;
1930 const char *remote = task_cb;
1931
66996bea 1932 state->result = error(_("could not fetch %s"), remote);
d54dea77
JS
1933
1934 return 0;
1935}
1936
1937static int fetch_finished(int result, struct strbuf *out,
1938 void *cb, void *task_cb)
1939{
1940 struct parallel_fetch_state *state = cb;
1941 const char *remote = task_cb;
1942
1943 if (result) {
1944 strbuf_addf(out, _("could not fetch '%s' (exit code: %d)\n"),
1945 remote, result);
1946 state->result = -1;
1947 }
1948
1949 return 0;
1950}
1951
1952static int fetch_multiple(struct string_list *list, int max_children)
7dce19d3
JL
1953{
1954 int i, result = 0;
22f9b7f3 1955 struct strvec argv = STRVEC_INIT;
9c4a036b 1956
887952b8 1957 if (!append && write_fetch_head) {
e6cc5104
JH
1958 int errcode = truncate_fetch_head();
1959 if (errcode)
1960 return errcode;
1961 }
1962
22f9b7f3 1963 strvec_pushl(&argv, "fetch", "--append", "--no-auto-gc",
f6d8942b 1964 "--no-write-commit-graph", NULL);
85556d4e
JK
1965 add_options_to_argv(&argv);
1966
d54dea77 1967 if (max_children != 1 && list->nr != 1) {
d70a9eb6 1968 struct parallel_fetch_state state = { argv.v, list, 0, 0 };
36d69bf7
ÆAB
1969 const struct run_process_parallel_opts opts = {
1970 .tr2_category = "fetch",
1971 .tr2_label = "parallel/fetch",
1972
1973 .processes = max_children,
1974
1975 .get_next_task = &fetch_next_remote,
1976 .start_failure = &fetch_failed_to_start,
1977 .task_finished = &fetch_finished,
1978 .data = &state,
1979 };
d54dea77 1980
22f9b7f3 1981 strvec_push(&argv, "--end-of-options");
7dd5762d 1982
36d69bf7 1983 run_processes_parallel(&opts);
7dd5762d 1984 result = state.result;
d54dea77
JS
1985 } else
1986 for (i = 0; i < list->nr; i++) {
1987 const char *name = list->items[i].string;
ddbb47fd
RS
1988 struct child_process cmd = CHILD_PROCESS_INIT;
1989
1990 strvec_pushv(&cmd.args, argv.v);
1991 strvec_push(&cmd.args, name);
d54dea77
JS
1992 if (verbosity >= 0)
1993 printf(_("Fetching %s\n"), name);
ddbb47fd
RS
1994 cmd.git_cmd = 1;
1995 if (run_command(&cmd)) {
66996bea 1996 error(_("could not fetch %s"), name);
d54dea77
JS
1997 result = 1;
1998 }
9c4a036b 1999 }
9c4a036b 2000
22f9b7f3 2001 strvec_clear(&argv);
d54dea77 2002 return !!result;
9c4a036b
BG
2003}
2004
aa57b871
JH
2005/*
2006 * Fetching from the promisor remote should use the given filter-spec
2007 * or inherit the default filter-spec from the config.
2008 */
2009static inline void fetch_one_setup_partial(struct remote *remote)
2010{
2011 /*
2012 * Explicit --no-filter argument overrides everything, regardless
2013 * of any prior partial clones and fetches.
2014 */
2015 if (filter_options.no_filter)
2016 return;
2017
2018 /*
2019 * If no prior partial clone/fetch and the current fetch DID NOT
2020 * request a partial-fetch, do a normal fetch.
2021 */
a5183d76 2022 if (!repo_has_promisor_remote(the_repository) && !filter_options.choice)
aa57b871
JH
2023 return;
2024
2025 /*
5e461393
CC
2026 * If this is a partial-fetch request, we enable partial on
2027 * this repo if not already enabled and remember the given
2028 * filter-spec as the default for subsequent fetches to this
23547c40 2029 * remote if there is currently no default filter-spec.
aa57b871 2030 */
5e461393 2031 if (filter_options.choice) {
aa57b871
JH
2032 partial_clone_register(remote->name, &filter_options);
2033 return;
2034 }
2035
aa57b871
JH
2036 /*
2037 * Do a partial-fetch from the promisor remote using either the
2038 * explicitly given filter-spec or inherit the filter-spec from
2039 * the config.
2040 */
2041 if (!filter_options.choice)
fa3d1b63 2042 partial_clone_get_default_filter_spec(&filter_options, remote->name);
aa57b871
JH
2043 return;
2044}
2045
2b713c27
JT
2046static int fetch_one(struct remote *remote, int argc, const char **argv,
2047 int prune_tags_ok, int use_stdin_refspecs)
b888d61c 2048{
d7c8e307
BW
2049 struct refspec rs = REFSPEC_INIT_FETCH;
2050 int i;
7b7f39ea 2051 int exit_code;
6317972c
ÆAB
2052 int maybe_prune_tags;
2053 int remote_via_config = remote_is_configured(remote, 0);
b888d61c 2054
fa685bdf 2055 if (!remote)
66996bea
AK
2056 die(_("no remote repository specified; please specify either a URL or a\n"
2057 "remote name from which new revisions should be fetched"));
fa685bdf 2058
508ea882 2059 gtransport = prepare_transport(remote, 1);
737c5a9c
MS
2060
2061 if (prune < 0) {
2062 /* no command line request */
07118832
ÆAB
2063 if (0 <= remote->prune)
2064 prune = remote->prune;
737c5a9c
MS
2065 else if (0 <= fetch_prune_config)
2066 prune = fetch_prune_config;
2067 else
2068 prune = PRUNE_BY_DEFAULT;
2069 }
2070
97716d21
ÆAB
2071 if (prune_tags < 0) {
2072 /* no command line request */
2073 if (0 <= remote->prune_tags)
2074 prune_tags = remote->prune_tags;
2075 else if (0 <= fetch_prune_tags_config)
2076 prune_tags = fetch_prune_tags_config;
2077 else
2078 prune_tags = PRUNE_TAGS_BY_DEFAULT;
2079 }
2080
6317972c
ÆAB
2081 maybe_prune_tags = prune_tags_ok && prune_tags;
2082 if (maybe_prune_tags && remote_via_config)
95303500 2083 refspec_append(&remote->fetch, TAG_REFSPEC);
97716d21 2084
d7c8e307
BW
2085 if (maybe_prune_tags && (argc || !remote_via_config))
2086 refspec_append(&rs, TAG_REFSPEC);
6317972c 2087
d7c8e307
BW
2088 for (i = 0; i < argc; i++) {
2089 if (!strcmp(argv[i], "tag")) {
d7c8e307
BW
2090 i++;
2091 if (i >= argc)
66996bea 2092 die(_("you need to specify a tag name"));
d7c8e307 2093
1af8b8c0
RS
2094 refspec_appendf(&rs, "refs/tags/%s:refs/tags/%s",
2095 argv[i], argv[i]);
d7c8e307
BW
2096 } else {
2097 refspec_append(&rs, argv[i]);
b888d61c 2098 }
b888d61c
DB
2099 }
2100
2b713c27
JT
2101 if (use_stdin_refspecs) {
2102 struct strbuf line = STRBUF_INIT;
2103 while (strbuf_getline_lf(&line, stdin) != EOF)
2104 refspec_append(&rs, line.buf);
2105 strbuf_release(&line);
2106 }
2107
5e3548ef
BW
2108 if (server_options.nr)
2109 gtransport->server_options = &server_options;
2110
57b235a4 2111 sigchain_push_common(unlock_pack_on_signal);
58d4d7f1 2112 atexit(unlock_pack_atexit);
14358894 2113 sigchain_push(SIGPIPE, SIG_IGN);
65a1301f 2114 exit_code = do_fetch(gtransport, &rs);
14358894 2115 sigchain_pop(SIGPIPE);
d7c8e307 2116 refspec_clear(&rs);
af234459
JH
2117 transport_disconnect(gtransport);
2118 gtransport = NULL;
7b7f39ea 2119 return exit_code;
b888d61c 2120}
9c4a036b
BG
2121
2122int cmd_fetch(int argc, const char **argv, const char *prefix)
2123{
2124 int i;
7f0cc04f 2125 const char *bundle_uri;
b7410f61 2126 struct string_list list = STRING_LIST_INIT_DUP;
a1743343 2127 struct remote *remote = NULL;
9c4a036b 2128 int result = 0;
c1a7902f 2129 int prune_tags_ok = 1;
9c4a036b 2130
bbc30f99
JK
2131 packet_trace_identity("fetch");
2132
9c4a036b
BG
2133 /* Record the command line for the reflog */
2134 strbuf_addstr(&default_rla, "fetch");
46da295a
JS
2135 for (i = 1; i < argc; i++) {
2136 /* This handles non-URLs gracefully */
2137 char *anon = transport_anonymize_url(argv[i]);
2138
2139 strbuf_addf(&default_rla, " %s", anon);
2140 free(anon);
2141 }
9c4a036b 2142
737c5a9c 2143 git_config(git_fetch_config, NULL);
059fda19
JS
2144 if (the_repository->gitdir) {
2145 prepare_repo_settings(the_repository);
2146 the_repository->settings.command_requires_full_index = 0;
2147 }
737c5a9c 2148
9c4a036b
BG
2149 argc = parse_options(argc, argv, prefix,
2150 builtin_fetch_options, builtin_fetch_usage, 0);
386c076a
GC
2151
2152 if (recurse_submodules_cli != RECURSE_SUBMODULES_DEFAULT)
2153 recurse_submodules = recurse_submodules_cli;
2154
2155 if (negotiate_only) {
2156 switch (recurse_submodules_cli) {
2157 case RECURSE_SUBMODULES_OFF:
2158 case RECURSE_SUBMODULES_DEFAULT:
2159 /*
2160 * --negotiate-only should never recurse into
2161 * submodules. Skip it by setting recurse_submodules to
2162 * RECURSE_SUBMODULES_OFF.
2163 */
2164 recurse_submodules = RECURSE_SUBMODULES_OFF;
2165 break;
2166
2167 default:
de4eaae6
JH
2168 die(_("options '%s' and '%s' cannot be used together"),
2169 "--negotiate-only", "--recurse-submodules");
386c076a
GC
2170 }
2171 }
2172
e5b94213
JT
2173 if (recurse_submodules != RECURSE_SUBMODULES_OFF) {
2174 int *sfjc = submodule_fetch_jobs_config == -1
2175 ? &submodule_fetch_jobs_config : NULL;
2176 int *rs = recurse_submodules == RECURSE_SUBMODULES_DEFAULT
2177 ? &recurse_submodules : NULL;
2178
2179 fetch_config_from_gitmodules(sfjc, rs);
2180 }
9c4a036b 2181
eff40457 2182 if (negotiate_only && !negotiation_tip.nr)
2826ffad 2183 die(_("--negotiate-only needs one or more --negotiation-tip=*"));
eff40457 2184
cccf74e2
NTND
2185 if (deepen_relative) {
2186 if (deepen_relative < 0)
66996bea 2187 die(_("negative depth in --deepen is not supported"));
cccf74e2 2188 if (depth)
43ea635c 2189 die(_("options '%s' and '%s' cannot be used together"), "--deepen", "--depth");
cccf74e2
NTND
2190 depth = xstrfmt("%d", deepen_relative);
2191 }
4dcb167f
NTND
2192 if (unshallow) {
2193 if (depth)
43ea635c 2194 die(_("options '%s' and '%s' cannot be used together"), "--depth", "--unshallow");
c8813487 2195 else if (!is_repository_shallow(the_repository))
4dcb167f 2196 die(_("--unshallow on a complete repository does not make sense"));
2805bb59
JK
2197 else
2198 depth = xstrfmt("%d", INFINITE_DEPTH);
4dcb167f
NTND
2199 }
2200
5594bcad
NTND
2201 /* no need to be strict, transport_set_option() will validate it again */
2202 if (depth && atoi(depth) < 1)
2203 die(_("depth %s is not a positive number"), depth);
a45a2600 2204 if (depth || deepen_since || deepen_not.nr)
508ea882 2205 deepen = 1;
5594bcad 2206
887952b8
JH
2207 /* FETCH_HEAD never gets updated in --dry-run mode */
2208 if (dry_run)
2209 write_fetch_head = 0;
2210
c39952b9
MA
2211 if (!max_jobs)
2212 max_jobs = online_cpus();
2213
7f0cc04f
DS
2214 if (!git_config_get_string_tmp("fetch.bundleuri", &bundle_uri) &&
2215 fetch_bundle_uri(the_repository, bundle_uri, NULL))
2216 warning(_("failed to fetch bundles from '%s'"), bundle_uri);
2217
9c4a036b
BG
2218 if (all) {
2219 if (argc == 1)
bd4a51fc 2220 die(_("fetch --all does not take a repository argument"));
9c4a036b 2221 else if (argc > 1)
bd4a51fc 2222 die(_("fetch --all does not make sense with refspecs"));
9c4a036b 2223 (void) for_each_remote(get_one_remote_for_fetch, &list);
0353c688
JH
2224
2225 /* do not do fetch_multiple() of one */
2226 if (list.nr == 1)
2227 remote = remote_get(list.items[0].string);
9c4a036b
BG
2228 } else if (argc == 0) {
2229 /* No arguments -- use default remote */
2230 remote = remote_get(NULL);
16679e37
BG
2231 } else if (multiple) {
2232 /* All arguments are assumed to be remotes or groups */
2233 for (i = 0; i < argc; i++)
2234 if (!add_remote_or_group(argv[i], &list))
66996bea
AK
2235 die(_("no such remote or remote group: %s"),
2236 argv[i]);
9c4a036b
BG
2237 } else {
2238 /* Single remote or group */
2239 (void) add_remote_or_group(argv[0], &list);
2240 if (list.nr > 1) {
2241 /* More than one remote */
2242 if (argc > 1)
66996bea 2243 die(_("fetching a group and specifying refspecs does not make sense"));
9c4a036b
BG
2244 } else {
2245 /* Zero or one remotes */
2246 remote = remote_get(argv[0]);
c1a7902f 2247 prune_tags_ok = (argc == 1);
a1743343
JT
2248 argc--;
2249 argv++;
9c4a036b
BG
2250 }
2251 }
06a668cb 2252 string_list_remove_duplicates(&list, 0);
9c4a036b 2253
9c1e657a
JT
2254 if (negotiate_only) {
2255 struct oidset acked_commits = OIDSET_INIT;
2256 struct oidset_iter iter;
2257 const struct object_id *oid;
2258
2259 if (!remote)
2260 die(_("must supply remote when using --negotiate-only"));
2261 gtransport = prepare_transport(remote, 1);
2262 if (gtransport->smart_options) {
2263 gtransport->smart_options->acked_commits = &acked_commits;
2264 } else {
66996bea 2265 warning(_("protocol does not support --negotiate-only, exiting"));
bec587d4
GC
2266 result = 1;
2267 goto cleanup;
9c1e657a
JT
2268 }
2269 if (server_options.nr)
2270 gtransport->server_options = &server_options;
2271 result = transport_fetch_refs(gtransport, NULL);
2272
2273 oidset_iter_init(&acked_commits, &iter);
2274 while ((oid = oidset_iter_next(&iter)))
2275 printf("%s\n", oid_to_hex(oid));
2276 oidset_clear(&acked_commits);
2277 } else if (remote) {
a5183d76 2278 if (filter_options.choice || repo_has_promisor_remote(the_repository))
aa57b871 2279 fetch_one_setup_partial(remote);
2b713c27 2280 result = fetch_one(remote, argc, argv, prune_tags_ok, stdin_refspecs);
acb0c572 2281 } else {
d54dea77
JS
2282 int max_children = max_jobs;
2283
acb0c572 2284 if (filter_options.choice)
e0137875
CC
2285 die(_("--filter can only be used with the remote "
2286 "configured in extensions.partialclone"));
d54dea77 2287
c7b190da
PS
2288 if (atomic_fetch)
2289 die(_("--atomic can only be used when fetching "
2290 "from one remote"));
2291
2b713c27
JT
2292 if (stdin_refspecs)
2293 die(_("--stdin can only be used when fetching "
2294 "from one remote"));
2295
d54dea77
JS
2296 if (max_children < 0)
2297 max_children = fetch_parallel_config;
2298
aa57b871 2299 /* TODO should this also die if we have a previous partial-clone? */
d54dea77 2300 result = fetch_multiple(&list, max_children);
acb0c572 2301 }
a1743343 2302
0353c688
JH
2303
2304 /*
2305 * This is only needed after fetch_one(), which does not fetch
2306 * submodules by itself.
2307 *
2308 * When we fetch from multiple remotes, fetch_multiple() has
2309 * already updated submodules to grab commits necessary for
2310 * the fetched history from each remote, so there is no need
2311 * to fetch submodules from here.
2312 */
2313 if (!result && remote && (recurse_submodules != RECURSE_SUBMODULES_OFF)) {
22f9b7f3 2314 struct strvec options = STRVEC_INIT;
d54dea77
JS
2315 int max_children = max_jobs;
2316
2317 if (max_children < 0)
2318 max_children = submodule_fetch_jobs_config;
2319 if (max_children < 0)
2320 max_children = fetch_parallel_config;
85556d4e
JK
2321
2322 add_options_to_argv(&options);
b90d9f76
GC
2323 result = fetch_submodules(the_repository,
2324 &options,
2325 submodule_prefix,
2326 recurse_submodules,
2327 recurse_submodules_default,
2328 verbosity < 0,
2329 max_children);
22f9b7f3 2330 strvec_clear(&options);
7dce19d3
JL
2331 }
2332
135a12bc
GC
2333 /*
2334 * Skip irrelevant tasks because we know objects were not
2335 * fetched.
2336 *
2337 * NEEDSWORK: as a future optimization, we can return early
2338 * whenever objects were not fetched e.g. if we already have all
2339 * of them.
2340 */
2341 if (negotiate_only)
2342 goto cleanup;
9c4a036b 2343
50f26bd0 2344 prepare_repo_settings(the_repository);
c14e6e79
JS
2345 if (fetch_write_commit_graph > 0 ||
2346 (fetch_write_commit_graph < 0 &&
2347 the_repository->settings.fetch_write_commit_graph)) {
5a535094 2348 int commit_graph_flags = COMMIT_GRAPH_WRITE_SPLIT;
50f26bd0
DS
2349
2350 if (progress)
5a535094 2351 commit_graph_flags |= COMMIT_GRAPH_WRITE_PROGRESS;
50f26bd0 2352
0bd52e27 2353 write_commit_graph_reachable(the_repository->objects->odb,
50f26bd0 2354 commit_graph_flags,
63020f17 2355 NULL);
50f26bd0
DS
2356 }
2357
7390f05a
RC
2358 if (enable_auto_gc) {
2359 if (refetch) {
2360 /*
2361 * Hint auto-maintenance strongly to encourage repacking,
2362 * but respect config settings disabling it.
2363 */
2364 int opt_val;
2365 if (git_config_get_int("gc.autopacklimit", &opt_val))
2366 opt_val = -1;
2367 if (opt_val != 0)
2368 git_config_push_parameter("gc.autoPackLimit=1");
2369
2370 if (git_config_get_int("maintenance.incremental-repack.auto", &opt_val))
2371 opt_val = -1;
2372 if (opt_val != 0)
2373 git_config_push_parameter("maintenance.incremental-repack.auto=-1");
2374 }
a95ce124 2375 run_auto_maintenance(verbosity < 0);
7390f05a 2376 }
131b8fcb 2377
bec587d4
GC
2378 cleanup:
2379 string_list_clear(&list, 0);
9c4a036b
BG
2380 return result;
2381}