]> git.ipfire.org Git - thirdparty/git.git/blame - builtin/fetch.c
fetch: convert prune_refs to take a struct refspec
[thirdparty/git.git] / builtin / fetch.c
CommitLineData
b888d61c
DB
1/*
2 * "git fetch"
3 */
4#include "cache.h"
b2141fc1 5#include "config.h"
e724197f 6#include "repository.h"
b888d61c 7#include "refs.h"
ec0cb496 8#include "refspec.h"
b888d61c
DB
9#include "commit.h"
10#include "builtin.h"
c455c87c 11#include "string-list.h"
b888d61c
DB
12#include "remote.h"
13#include "transport.h"
4191c356 14#include "run-command.h"
83201998 15#include "parse-options.h"
4a16d072 16#include "sigchain.h"
027771fc 17#include "submodule-config.h"
7dce19d3 18#include "submodule.h"
f96400cb 19#include "connected.h"
85556d4e 20#include "argv-array.h"
6bc91f23 21#include "utf8.h"
3836d88a 22#include "packfile.h"
acb0c572 23#include "list-objects-filter-options.h"
b888d61c 24
83201998 25static const char * const builtin_fetch_usage[] = {
719acedb
NTND
26 N_("git fetch [<options>] [<repository> [<refspec>...]]"),
27 N_("git fetch [<options>] <group>"),
28 N_("git fetch --multiple [<options>] [(<repository> | <group>)...]"),
29 N_("git fetch --all [<options>]"),
83201998
KH
30 NULL
31};
b888d61c 32
83201998
KH
33enum {
34 TAGS_UNSET = 0,
35 TAGS_DEFAULT = 1,
36 TAGS_SET = 2
37};
38
737c5a9c
MS
39static int fetch_prune_config = -1; /* unspecified */
40static int prune = -1; /* unspecified */
41#define PRUNE_BY_DEFAULT 0 /* do we prune by default? */
42
97716d21
ÆAB
43static int fetch_prune_tags_config = -1; /* unspecified */
44static int prune_tags = -1; /* unspecified */
45#define PRUNE_TAGS_BY_DEFAULT 0 /* do we prune tags by default? */
46
cccf74e2 47static int all, append, dry_run, force, keep, multiple, update_head_ok, verbosity, deepen_relative;
8c69832d 48static int progress = -1;
508ea882 49static int tags = TAGS_DEFAULT, unshallow, update_shallow, deepen;
f20e7c1e 50static int max_children = 1;
c915f11e 51static enum transport_family family;
4191c356 52static const char *depth;
508ea882 53static const char *deepen_since;
83201998 54static const char *upload_pack;
a45a2600 55static struct string_list deepen_not = STRING_LIST_INIT_NODUP;
2d324efa 56static struct strbuf default_rla = STRBUF_INIT;
af234459 57static struct transport *gtransport;
b26ed430 58static struct transport *gsecondary;
7dce19d3 59static const char *submodule_prefix = "";
8c69832d 60static int recurse_submodules = RECURSE_SUBMODULES_DEFAULT;
e8906a90 61static int recurse_submodules_default = RECURSE_SUBMODULES_ON_DEMAND;
4b3b33a7 62static int shown_url = 0;
e4cffacc 63static struct refspec refmap = REFSPEC_INIT_FETCH;
acb0c572 64static struct list_objects_filter_options filter_options;
e4022ed2 65
737c5a9c
MS
66static int git_fetch_config(const char *k, const char *v, void *cb)
67{
68 if (!strcmp(k, "fetch.prune")) {
69 fetch_prune_config = git_config_bool(k, v);
70 return 0;
71 }
58f4203e 72
97716d21
ÆAB
73 if (!strcmp(k, "fetch.prunetags")) {
74 fetch_prune_tags_config = git_config_bool(k, v);
75 return 0;
76 }
77
58f4203e
SB
78 if (!strcmp(k, "submodule.recurse")) {
79 int r = git_config_bool(k, v) ?
80 RECURSE_SUBMODULES_ON : RECURSE_SUBMODULES_OFF;
81 recurse_submodules = r;
82 }
83
f20e7c1e
BW
84 if (!strcmp(k, "submodule.fetchjobs")) {
85 max_children = parse_submodule_fetchjobs(k, v);
86 return 0;
8fa29159
BW
87 } else if (!strcmp(k, "fetch.recursesubmodules")) {
88 recurse_submodules = parse_fetch_recurse_submodules_arg(k, v);
89 return 0;
f20e7c1e
BW
90 }
91
72549dfd 92 return git_default_config(k, v, cb);
737c5a9c
MS
93}
94
f20e7c1e
BW
95static int gitmodules_fetch_config(const char *var, const char *value, void *cb)
96{
97 if (!strcmp(var, "submodule.fetchjobs")) {
98 max_children = parse_submodule_fetchjobs(var, value);
99 return 0;
8fa29159
BW
100 } else if (!strcmp(var, "fetch.recursesubmodules")) {
101 recurse_submodules = parse_fetch_recurse_submodules_arg(var, value);
102 return 0;
f20e7c1e
BW
103 }
104
105 return 0;
106}
107
c5558f80
JH
108static int parse_refmap_arg(const struct option *opt, const char *arg, int unset)
109{
c5558f80
JH
110 /*
111 * "git fetch --refmap='' origin foo"
112 * can be used to tell the command not to store anywhere
113 */
e4cffacc
BW
114 refspec_append(&refmap, arg);
115
c5558f80
JH
116 return 0;
117}
118
83201998 119static struct option builtin_fetch_options[] = {
7f87aff2 120 OPT__VERBOSITY(&verbosity),
d5d09d47
SB
121 OPT_BOOL(0, "all", &all,
122 N_("fetch from all remotes")),
123 OPT_BOOL('a', "append", &append,
124 N_("append to .git/FETCH_HEAD instead of overwriting")),
719acedb
NTND
125 OPT_STRING(0, "upload-pack", &upload_pack, N_("path"),
126 N_("path to upload pack on remote end")),
1224781d 127 OPT__FORCE(&force, N_("force overwrite of local branch"), 0),
d5d09d47
SB
128 OPT_BOOL('m', "multiple", &multiple,
129 N_("fetch from multiple remotes")),
83201998 130 OPT_SET_INT('t', "tags", &tags,
719acedb 131 N_("fetch all tags and associated objects"), TAGS_SET),
e7951290 132 OPT_SET_INT('n', NULL, &tags,
719acedb 133 N_("do not fetch all tags (--no-tags)"), TAGS_UNSET),
62104ba1
SB
134 OPT_INTEGER('j', "jobs", &max_children,
135 N_("number of submodules fetched in parallel")),
d5d09d47
SB
136 OPT_BOOL('p', "prune", &prune,
137 N_("prune remote-tracking branches no longer on remote")),
97716d21
ÆAB
138 OPT_BOOL('P', "prune-tags", &prune_tags,
139 N_("prune local tags no longer on remote and clobber changed tags")),
886dc154 140 { OPTION_CALLBACK, 0, "recurse-submodules", &recurse_submodules, N_("on-demand"),
719acedb 141 N_("control recursive fetching of submodules"),
886dc154 142 PARSE_OPT_OPTARG, option_fetch_parse_recurse_submodules },
d5d09d47
SB
143 OPT_BOOL(0, "dry-run", &dry_run,
144 N_("dry run")),
145 OPT_BOOL('k', "keep", &keep, N_("keep downloaded pack")),
146 OPT_BOOL('u', "update-head-ok", &update_head_ok,
719acedb
NTND
147 N_("allow updating of HEAD ref")),
148 OPT_BOOL(0, "progress", &progress, N_("force progress reporting")),
149 OPT_STRING(0, "depth", &depth, N_("depth"),
150 N_("deepen history of shallow clone")),
508ea882
NTND
151 OPT_STRING(0, "shallow-since", &deepen_since, N_("time"),
152 N_("deepen history of shallow repository based on time")),
a45a2600 153 OPT_STRING_LIST(0, "shallow-exclude", &deepen_not, N_("revision"),
6d873865 154 N_("deepen history of shallow clone, excluding rev")),
cccf74e2
NTND
155 OPT_INTEGER(0, "deepen", &deepen_relative,
156 N_("deepen history of shallow clone")),
4dcb167f
NTND
157 { OPTION_SET_INT, 0, "unshallow", &unshallow, NULL,
158 N_("convert to a complete repository"),
159 PARSE_OPT_NONEG | PARSE_OPT_NOARG, NULL, 1 },
719acedb
NTND
160 { OPTION_STRING, 0, "submodule-prefix", &submodule_prefix, N_("dir"),
161 N_("prepend this to submodule path output"), PARSE_OPT_HIDDEN },
8c69832d
SB
162 { OPTION_CALLBACK, 0, "recurse-submodules-default",
163 &recurse_submodules_default, N_("on-demand"),
164 N_("default for recursive fetching of submodules "
165 "(lower priority than config files)"),
166 PARSE_OPT_HIDDEN, option_fetch_parse_recurse_submodules },
48d25cae
NTND
167 OPT_BOOL(0, "update-shallow", &update_shallow,
168 N_("accept refs that update .git/shallow")),
c5558f80
JH
169 { OPTION_CALLBACK, 0, "refmap", NULL, N_("refmap"),
170 N_("specify fetch refmap"), PARSE_OPT_NONEG, parse_refmap_arg },
c915f11e
EW
171 OPT_SET_INT('4', "ipv4", &family, N_("use IPv4 addresses only"),
172 TRANSPORT_FAMILY_IPV4),
173 OPT_SET_INT('6', "ipv6", &family, N_("use IPv6 addresses only"),
174 TRANSPORT_FAMILY_IPV6),
acb0c572 175 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
83201998
KH
176 OPT_END()
177};
178
e4022ed2
SP
179static void unlock_pack(void)
180{
af234459
JH
181 if (gtransport)
182 transport_unlock_pack(gtransport);
b26ed430
JH
183 if (gsecondary)
184 transport_unlock_pack(gsecondary);
e4022ed2
SP
185}
186
187static void unlock_pack_on_signal(int signo)
188{
189 unlock_pack();
4a16d072 190 sigchain_pop(signo);
e4022ed2
SP
191 raise(signo);
192}
b888d61c 193
85682c19 194static void add_merge_config(struct ref **head,
4577370e 195 const struct ref *remote_refs,
85682c19
SP
196 struct branch *branch,
197 struct ref ***tail)
b888d61c 198{
85682c19 199 int i;
b888d61c 200
85682c19
SP
201 for (i = 0; i < branch->merge_nr; i++) {
202 struct ref *rm, **old_tail = *tail;
0ad4a5ff 203 struct refspec_item refspec;
85682c19
SP
204
205 for (rm = *head; rm; rm = rm->next) {
206 if (branch_merge_matches(branch, i, rm->name)) {
900f2814 207 rm->fetch_head_status = FETCH_HEAD_MERGE;
85682c19
SP
208 break;
209 }
b888d61c 210 }
85682c19
SP
211 if (rm)
212 continue;
213
9ad7c5ae 214 /*
8b3f3f84 215 * Not fetched to a remote-tracking branch? We need to fetch
85682c19 216 * it anyway to allow this branch's "branch.$name.merge"
05207a28 217 * to be honored by 'git pull', but we do not have to
9ad7c5ae
JH
218 * fail if branch.$name.merge is misconfigured to point
219 * at a nonexisting branch. If we were indeed called by
05207a28 220 * 'git pull', it will notice the misconfiguration because
9ad7c5ae
JH
221 * there is no entry in the resulting FETCH_HEAD marked
222 * for merging.
85682c19 223 */
8da61a2a 224 memset(&refspec, 0, sizeof(refspec));
85682c19 225 refspec.src = branch->merge[i]->src;
9ad7c5ae 226 get_fetch_map(remote_refs, &refspec, tail, 1);
85682c19 227 for (rm = *old_tail; rm; rm = rm->next)
900f2814 228 rm->fetch_head_status = FETCH_HEAD_MERGE;
b888d61c
DB
229 }
230}
231
0e0b7de4 232static int add_existing(const char *refname, const struct object_id *oid,
a0fbb5a3
MH
233 int flag, void *cbdata)
234{
235 struct string_list *list = (struct string_list *)cbdata;
236 struct string_list_item *item = string_list_insert(list, refname);
0e0b7de4
MH
237 struct object_id *old_oid = xmalloc(sizeof(*old_oid));
238
239 oidcpy(old_oid, oid);
240 item->util = old_oid;
a0fbb5a3
MH
241 return 0;
242}
243
244static int will_fetch(struct ref **head, const unsigned char *sha1)
245{
246 struct ref *rm = *head;
247 while (rm) {
f4e54d02 248 if (!hashcmp(rm->old_oid.hash, sha1))
a0fbb5a3
MH
249 return 1;
250 rm = rm->next;
251 }
252 return 0;
253}
254
767f176a
SP
255static void find_non_local_tags(struct transport *transport,
256 struct ref **head,
a0fbb5a3
MH
257 struct ref ***tail)
258{
259 struct string_list existing_refs = STRING_LIST_INIT_DUP;
260 struct string_list remote_refs = STRING_LIST_INIT_NODUP;
261 const struct ref *ref;
262 struct string_list_item *item = NULL;
263
0e0b7de4 264 for_each_ref(add_existing, &existing_refs);
1af8ae1c 265 for (ref = transport_get_remote_refs(transport, NULL); ref; ref = ref->next) {
ad704485 266 if (!starts_with(ref->name, "refs/tags/"))
a0fbb5a3
MH
267 continue;
268
269 /*
270 * The peeled ref always follows the matching base
271 * ref, so if we see a peeled ref that we don't want
272 * to fetch then we can mark the ref entry in the list
273 * as one to ignore by setting util to NULL.
274 */
ad704485 275 if (ends_with(ref->name, "^{}")) {
5827a035 276 if (item &&
e83e71c5
JT
277 !has_object_file_with_flags(&ref->old_oid,
278 OBJECT_INFO_QUICK) &&
f4e54d02 279 !will_fetch(head, ref->old_oid.hash) &&
e83e71c5
JT
280 !has_sha1_file_with_flags(item->util,
281 OBJECT_INFO_QUICK) &&
a0fbb5a3
MH
282 !will_fetch(head, item->util))
283 item->util = NULL;
284 item = NULL;
285 continue;
286 }
287
288 /*
289 * If item is non-NULL here, then we previously saw a
290 * ref not followed by a peeled reference, so we need
291 * to check if it is a lightweight tag that we want to
292 * fetch.
293 */
5827a035 294 if (item &&
e83e71c5 295 !has_sha1_file_with_flags(item->util, OBJECT_INFO_QUICK) &&
a0fbb5a3
MH
296 !will_fetch(head, item->util))
297 item->util = NULL;
298
299 item = NULL;
300
301 /* skip duplicates and refs that we already have */
302 if (string_list_has_string(&remote_refs, ref->name) ||
303 string_list_has_string(&existing_refs, ref->name))
304 continue;
305
306 item = string_list_insert(&remote_refs, ref->name);
f4e54d02 307 item->util = (void *)&ref->old_oid;
a0fbb5a3
MH
308 }
309 string_list_clear(&existing_refs, 1);
310
311 /*
312 * We may have a final lightweight tag that needs to be
313 * checked to see if it needs fetching.
314 */
5827a035 315 if (item &&
e83e71c5 316 !has_sha1_file_with_flags(item->util, OBJECT_INFO_QUICK) &&
a0fbb5a3
MH
317 !will_fetch(head, item->util))
318 item->util = NULL;
319
320 /*
321 * For all the tags in the remote_refs string list,
322 * add them to the list of refs to be fetched
323 */
324 for_each_string_list_item(item, &remote_refs) {
325 /* Unless we have already decided to ignore this item... */
326 if (item->util)
327 {
328 struct ref *rm = alloc_ref(item->string);
329 rm->peer_ref = alloc_ref(item->string);
f4e54d02 330 oidcpy(&rm->old_oid, item->util);
a0fbb5a3
MH
331 **tail = rm;
332 *tail = &rm->next;
333 }
334 }
335
336 string_list_clear(&remote_refs, 0);
337}
767f176a 338
b888d61c 339static struct ref *get_ref_map(struct transport *transport,
65d96c8b 340 struct refspec *rs,
f137a45e 341 int tags, int *autotags)
b888d61c
DB
342{
343 int i;
344 struct ref *rm;
345 struct ref *ref_map = NULL;
346 struct ref **tail = &ref_map;
230d7dd3 347 struct argv_array ref_prefixes = ARGV_ARRAY_INIT;
b888d61c 348
c5a84e92
MH
349 /* opportunistically-updated references: */
350 struct ref *orefs = NULL, **oref_tail = &orefs;
b888d61c 351
230d7dd3
BW
352 const struct ref *remote_refs;
353
65d96c8b
BW
354 for (i = 0; i < rs->nr; i++) {
355 const struct refspec_item *item = &rs->items[i];
356 if (!item->exact_sha1) {
357 const char *glob = strchr(item->src, '*');
230d7dd3
BW
358 if (glob)
359 argv_array_pushf(&ref_prefixes, "%.*s",
65d96c8b
BW
360 (int)(glob - item->src),
361 item->src);
230d7dd3 362 else
65d96c8b 363 expand_ref_prefix(&ref_prefixes, item->src);
230d7dd3
BW
364 }
365 }
366
367 remote_refs = transport_get_remote_refs(transport, &ref_prefixes);
368
369 argv_array_clear(&ref_prefixes);
f2690487 370
65d96c8b
BW
371 if (rs->nr) {
372 struct refspec *fetch_refspec;
c5558f80 373
65d96c8b
BW
374 for (i = 0; i < rs->nr; i++) {
375 get_fetch_map(remote_refs, &rs->items[i], &tail, 0);
376 if (rs->items[i].dst && rs->items[i].dst[0])
b888d61c
DB
377 *autotags = 1;
378 }
0281c930 379 /* Merge everything on the command line (but not --tags) */
b888d61c 380 for (rm = ref_map; rm; rm = rm->next)
900f2814 381 rm->fetch_head_status = FETCH_HEAD_MERGE;
f2690487
JK
382
383 /*
0281c930
MH
384 * For any refs that we happen to be fetching via
385 * command-line arguments, the destination ref might
386 * have been missing or have been different than the
387 * remote-tracking ref that would be derived from the
388 * configured refspec. In these cases, we want to
389 * take the opportunity to update their configured
390 * remote-tracking reference. However, we do not want
391 * to mention these entries in FETCH_HEAD at all, as
392 * they would simply be duplicates of existing
393 * entries, so we set them FETCH_HEAD_IGNORE below.
394 *
395 * We compute these entries now, based only on the
396 * refspecs specified on the command line. But we add
397 * them to the list following the refspecs resulting
398 * from the tags option so that one of the latter,
399 * which has FETCH_HEAD_NOT_FOR_MERGE, is not removed
400 * by ref_remove_duplicates() in favor of one of these
401 * opportunistic entries with FETCH_HEAD_IGNORE.
f2690487 402 */
65d96c8b
BW
403 if (refmap.nr)
404 fetch_refspec = &refmap;
405 else
406 fetch_refspec = &transport->remote->fetch;
c5558f80 407
65d96c8b
BW
408 for (i = 0; i < fetch_refspec->nr; i++)
409 get_fetch_map(ref_map, &fetch_refspec->items[i], &oref_tail, 1);
e4cffacc 410 } else if (refmap.nr) {
c5558f80 411 die("--refmap option is only meaningful with command-line refspec(s).");
b888d61c
DB
412 } else {
413 /* Use the defaults */
414 struct remote *remote = transport->remote;
85682c19
SP
415 struct branch *branch = branch_get(NULL);
416 int has_merge = branch_has_merge_config(branch);
3ee1757b 417 if (remote &&
e5349abf 418 (remote->fetch.nr ||
f31dbdc7 419 /* Note: has_merge implies non-NULL branch->remote_name */
3ee1757b 420 (has_merge && !strcmp(branch->remote_name, remote->name)))) {
e5349abf
BW
421 for (i = 0; i < remote->fetch.nr; i++) {
422 get_fetch_map(remote_refs, &remote->fetch.items[i], &tail, 0);
423 if (remote->fetch.items[i].dst &&
424 remote->fetch.items[i].dst[0])
b888d61c 425 *autotags = 1;
85682c19 426 if (!i && !has_merge && ref_map &&
e5349abf 427 !remote->fetch.items[0].pattern)
900f2814 428 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
b888d61c 429 }
da0204df
JS
430 /*
431 * if the remote we're fetching from is the same
432 * as given in branch.<name>.remote, we add the
433 * ref given in branch.<name>.merge, too.
f31dbdc7
BC
434 *
435 * Note: has_merge implies non-NULL branch->remote_name
da0204df 436 */
9ad7c5ae
JH
437 if (has_merge &&
438 !strcmp(branch->remote_name, remote->name))
85682c19 439 add_merge_config(&ref_map, remote_refs, branch, &tail);
b888d61c
DB
440 } else {
441 ref_map = get_remote_ref(remote_refs, "HEAD");
9ad7c5ae 442 if (!ref_map)
bd4a51fc 443 die(_("Couldn't find remote ref HEAD"));
900f2814 444 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
5aaf7f2a 445 tail = &ref_map->next;
b888d61c
DB
446 }
447 }
0281c930 448
c5a84e92
MH
449 if (tags == TAGS_SET)
450 /* also fetch all tags */
451 get_fetch_map(remote_refs, tag_refspec, &tail, 0);
452 else if (tags == TAGS_DEFAULT && *autotags)
767f176a 453 find_non_local_tags(transport, &ref_map, &tail);
0281c930 454
c5a84e92
MH
455 /* Now append any refs to be updated opportunistically: */
456 *tail = orefs;
457 for (rm = orefs; rm; rm = rm->next) {
458 rm->fetch_head_status = FETCH_HEAD_IGNORE;
459 tail = &rm->next;
460 }
461
b9afe665 462 return ref_remove_duplicates(ref_map);
b888d61c
DB
463}
464
fa250759
JK
465#define STORE_REF_ERROR_OTHER 1
466#define STORE_REF_ERROR_DF_CONFLICT 2
467
b888d61c
DB
468static int s_update_ref(const char *action,
469 struct ref *ref,
470 int check_old)
471{
1412f762 472 char *msg;
b888d61c 473 char *rla = getenv("GIT_REFLOG_ACTION");
cd94f765
RS
474 struct ref_transaction *transaction;
475 struct strbuf err = STRBUF_INIT;
476 int ret, df_conflict = 0;
b888d61c 477
28a15401
JS
478 if (dry_run)
479 return 0;
b888d61c 480 if (!rla)
2d324efa 481 rla = default_rla.buf;
1412f762 482 msg = xstrfmt("%s: %s", rla, action);
cd94f765
RS
483
484 transaction = ref_transaction_begin(&err);
485 if (!transaction ||
1d147bdf 486 ref_transaction_update(transaction, ref->name,
89f3bbdd 487 &ref->new_oid,
488 check_old ? &ref->old_oid : NULL,
1d147bdf 489 0, msg, &err))
cd94f765
RS
490 goto fail;
491
492 ret = ref_transaction_commit(transaction, &err);
493 if (ret) {
494 df_conflict = (ret == TRANSACTION_NAME_CONFLICT);
495 goto fail;
496 }
497
498 ref_transaction_free(transaction);
499 strbuf_release(&err);
1412f762 500 free(msg);
b888d61c 501 return 0;
cd94f765
RS
502fail:
503 ref_transaction_free(transaction);
504 error("%s", err.buf);
505 strbuf_release(&err);
1412f762 506 free(msg);
cd94f765
RS
507 return df_conflict ? STORE_REF_ERROR_DF_CONFLICT
508 : STORE_REF_ERROR_OTHER;
b888d61c
DB
509}
510
6bc91f23 511static int refcol_width = 10;
bc437d10 512static int compact_format;
6bc91f23
NTND
513
514static void adjust_refcol_width(const struct ref *ref)
515{
516 int max, rlen, llen, len;
517
518 /* uptodate lines are only shown on high verbosity level */
519 if (!verbosity && !oidcmp(&ref->peer_ref->old_oid, &ref->old_oid))
520 return;
521
522 max = term_columns();
523 rlen = utf8_strwidth(prettify_refname(ref->name));
bc437d10 524
6bc91f23
NTND
525 llen = utf8_strwidth(prettify_refname(ref->peer_ref->name));
526
527 /*
528 * rough estimation to see if the output line is too long and
529 * should not be counted (we can't do precise calculation
530 * anyway because we don't know if the error explanation part
531 * will be printed in update_local_ref)
532 */
bc437d10
NTND
533 if (compact_format) {
534 llen = 0;
535 max = max * 2 / 3;
536 }
6bc91f23
NTND
537 len = 21 /* flag and summary */ + rlen + 4 /* -> */ + llen;
538 if (len >= max)
539 return;
540
bc437d10
NTND
541 /*
542 * Not precise calculation for compact mode because '*' can
543 * appear on the left hand side of '->' and shrink the column
544 * back.
545 */
6bc91f23
NTND
546 if (refcol_width < rlen)
547 refcol_width = rlen;
548}
549
550static void prepare_format_display(struct ref *ref_map)
551{
552 struct ref *rm;
bc437d10
NTND
553 const char *format = "full";
554
555 git_config_get_string_const("fetch.output", &format);
556 if (!strcasecmp(format, "full"))
557 compact_format = 0;
558 else if (!strcasecmp(format, "compact"))
559 compact_format = 1;
560 else
561 die(_("configuration fetch.output contains invalid value %s"),
562 format);
6bc91f23
NTND
563
564 for (rm = ref_map; rm; rm = rm->next) {
565 if (rm->status == REF_STATUS_REJECT_SHALLOW ||
566 !rm->peer_ref ||
567 !strcmp(rm->name, "HEAD"))
568 continue;
569
570 adjust_refcol_width(rm);
571 }
572}
165f3902 573
bc437d10
NTND
574static void print_remote_to_local(struct strbuf *display,
575 const char *remote, const char *local)
576{
577 strbuf_addf(display, "%-*s -> %s", refcol_width, remote, local);
578}
579
580static int find_and_replace(struct strbuf *haystack,
581 const char *needle,
582 const char *placeholder)
583{
584 const char *p = strstr(haystack->buf, needle);
585 int plen, nlen;
586
587 if (!p)
588 return 0;
589
590 if (p > haystack->buf && p[-1] != '/')
591 return 0;
592
593 plen = strlen(p);
594 nlen = strlen(needle);
595 if (plen > nlen && p[nlen] != '/')
596 return 0;
597
598 strbuf_splice(haystack, p - haystack->buf, nlen,
599 placeholder, strlen(placeholder));
600 return 1;
601}
602
603static void print_compact(struct strbuf *display,
604 const char *remote, const char *local)
605{
606 struct strbuf r = STRBUF_INIT;
607 struct strbuf l = STRBUF_INIT;
608
609 if (!strcmp(remote, local)) {
610 strbuf_addf(display, "%-*s -> *", refcol_width, remote);
611 return;
612 }
613
614 strbuf_addstr(&r, remote);
615 strbuf_addstr(&l, local);
616
617 if (!find_and_replace(&r, local, "*"))
618 find_and_replace(&l, remote, "*");
619 print_remote_to_local(display, r.buf, l.buf);
620
621 strbuf_release(&r);
622 strbuf_release(&l);
623}
624
d0b39a03
NTND
625static void format_display(struct strbuf *display, char code,
626 const char *summary, const char *error,
901f3d40
JH
627 const char *remote, const char *local,
628 int summary_width)
d0b39a03 629{
901f3d40
JH
630 int width = (summary_width + strlen(summary) - gettext_width(summary));
631
632 strbuf_addf(display, "%c %-*s ", code, width, summary);
bc437d10
NTND
633 if (!compact_format)
634 print_remote_to_local(display, remote, local);
635 else
636 print_compact(display, remote, local);
d0b39a03
NTND
637 if (error)
638 strbuf_addf(display, " (%s)", error);
639}
165f3902 640
b888d61c 641static int update_local_ref(struct ref *ref,
165f3902 642 const char *remote,
6da618d5 643 const struct ref *remote_ref,
901f3d40
JH
644 struct strbuf *display,
645 int summary_width)
b888d61c 646{
b888d61c
DB
647 struct commit *current = NULL, *updated;
648 enum object_type type;
649 struct branch *current_branch = branch_get(NULL);
4577e483 650 const char *pretty_ref = prettify_refname(ref->name);
b888d61c 651
abef9020 652 type = oid_object_info(&ref->new_oid, NULL);
b888d61c 653 if (type < 0)
f4e54d02 654 die(_("object %s not found"), oid_to_hex(&ref->new_oid));
b888d61c 655
f4e54d02 656 if (!oidcmp(&ref->old_oid, &ref->new_oid)) {
7f87aff2 657 if (verbosity > 0)
d0b39a03 658 format_display(display, '=', _("[up to date]"), NULL,
901f3d40 659 remote, pretty_ref, summary_width);
b888d61c
DB
660 return 0;
661 }
662
b3abdd9d
SP
663 if (current_branch &&
664 !strcmp(ref->name, current_branch->name) &&
b888d61c 665 !(update_head_ok || is_bare_repository()) &&
f4e54d02 666 !is_null_oid(&ref->old_oid)) {
b888d61c
DB
667 /*
668 * If this is the head, and it's not okay to update
669 * the head, and the old value of the head isn't empty...
670 */
d0b39a03
NTND
671 format_display(display, '!', _("[rejected]"),
672 _("can't fetch in current branch"),
901f3d40 673 remote, pretty_ref, summary_width);
b888d61c
DB
674 return 1;
675 }
676
f4e54d02 677 if (!is_null_oid(&ref->old_oid) &&
59556548 678 starts_with(ref->name, "refs/tags/")) {
6315472e
JK
679 int r;
680 r = s_update_ref("updating tag", ref, 0);
2cb040ba 681 format_display(display, r ? '!' : 't', _("[tag update]"),
d0b39a03 682 r ? _("unable to update local ref") : NULL,
901f3d40 683 remote, pretty_ref, summary_width);
6315472e 684 return r;
b888d61c
DB
685 }
686
bc83266a 687 current = lookup_commit_reference_gently(&ref->old_oid, 1);
688 updated = lookup_commit_reference_gently(&ref->new_oid, 1);
b888d61c 689 if (!current || !updated) {
165f3902
NP
690 const char *msg;
691 const char *what;
6315472e 692 int r;
0997adaa
MB
693 /*
694 * Nicely describe the new ref we're fetching.
695 * Base this on the remote's ref name, as it's
696 * more likely to follow a standard layout.
697 */
698 const char *name = remote_ref ? remote_ref->name : "";
59556548 699 if (starts_with(name, "refs/tags/")) {
b888d61c 700 msg = "storing tag";
f7b3742a 701 what = _("[new tag]");
59556548 702 } else if (starts_with(name, "refs/heads/")) {
b888d61c 703 msg = "storing head";
f7b3742a 704 what = _("[new branch]");
0997adaa
MB
705 } else {
706 msg = "storing ref";
707 what = _("[new ref]");
165f3902
NP
708 }
709
a6801adc
JL
710 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
711 (recurse_submodules != RECURSE_SUBMODULES_ON))
2eb80bcd 712 check_for_new_submodule_commits(&ref->new_oid);
6315472e 713 r = s_update_ref(msg, ref, 0);
d0b39a03
NTND
714 format_display(display, r ? '!' : '*', what,
715 r ? _("unable to update local ref") : NULL,
901f3d40 716 remote, pretty_ref, summary_width);
6315472e 717 return r;
b888d61c
DB
718 }
719
a20efee9 720 if (in_merge_bases(current, updated)) {
bd22d4ff 721 struct strbuf quickref = STRBUF_INIT;
6315472e 722 int r;
30e677e0 723 strbuf_add_unique_abbrev(&quickref, &current->object.oid, DEFAULT_ABBREV);
bd22d4ff 724 strbuf_addstr(&quickref, "..");
30e677e0 725 strbuf_add_unique_abbrev(&quickref, &ref->new_oid, DEFAULT_ABBREV);
88a21979
JL
726 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
727 (recurse_submodules != RECURSE_SUBMODULES_ON))
2eb80bcd 728 check_for_new_submodule_commits(&ref->new_oid);
a75d7b54 729 r = s_update_ref("fast-forward", ref, 1);
d0b39a03
NTND
730 format_display(display, r ? '!' : ' ', quickref.buf,
731 r ? _("unable to update local ref") : NULL,
901f3d40 732 remote, pretty_ref, summary_width);
bd22d4ff 733 strbuf_release(&quickref);
6315472e 734 return r;
165f3902 735 } else if (force || ref->force) {
bd22d4ff 736 struct strbuf quickref = STRBUF_INIT;
6315472e 737 int r;
30e677e0 738 strbuf_add_unique_abbrev(&quickref, &current->object.oid, DEFAULT_ABBREV);
bd22d4ff 739 strbuf_addstr(&quickref, "...");
30e677e0 740 strbuf_add_unique_abbrev(&quickref, &ref->new_oid, DEFAULT_ABBREV);
88a21979
JL
741 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
742 (recurse_submodules != RECURSE_SUBMODULES_ON))
2eb80bcd 743 check_for_new_submodule_commits(&ref->new_oid);
6315472e 744 r = s_update_ref("forced-update", ref, 1);
d0b39a03
NTND
745 format_display(display, r ? '!' : '+', quickref.buf,
746 r ? _("unable to update local ref") : _("forced update"),
901f3d40 747 remote, pretty_ref, summary_width);
bd22d4ff 748 strbuf_release(&quickref);
6315472e 749 return r;
165f3902 750 } else {
d0b39a03 751 format_display(display, '!', _("[rejected]"), _("non-fast-forward"),
901f3d40 752 remote, pretty_ref, summary_width);
b888d61c
DB
753 return 1;
754 }
b888d61c
DB
755}
756
6ccac9ee 757static int iterate_ref_map(void *cb_data, struct object_id *oid)
6b67e0dc 758{
f0e278b1
JH
759 struct ref **rm = cb_data;
760 struct ref *ref = *rm;
6b67e0dc 761
4820a33b
NTND
762 while (ref && ref->status == REF_STATUS_REJECT_SHALLOW)
763 ref = ref->next;
f0e278b1
JH
764 if (!ref)
765 return -1; /* end of the list */
766 *rm = ref->next;
6ccac9ee 767 oidcpy(oid, &ref->old_oid);
f0e278b1 768 return 0;
6b67e0dc
JH
769}
770
47abd85b 771static int store_updated_refs(const char *raw_url, const char *remote_name,
f3cb169b 772 struct ref *ref_map)
b888d61c
DB
773{
774 FILE *fp;
775 struct commit *commit;
4b3b33a7 776 int url_len, i, rc = 0;
5914f2d0 777 struct strbuf note = STRBUF_INIT;
b888d61c
DB
778 const char *what, *kind;
779 struct ref *rm;
dcf69262 780 char *url;
f932729c 781 const char *filename = dry_run ? "/dev/null" : git_path_fetch_head();
900f2814 782 int want_status;
11fd66de 783 int summary_width = transport_summary_width(ref_map);
b888d61c 784
d6617c7c
AGR
785 fp = fopen(filename, "a");
786 if (!fp)
6da31d7f 787 return error_errno(_("cannot open %s"), filename);
47abd85b 788
fb0cc87e
DB
789 if (raw_url)
790 url = transport_anonymize_url(raw_url);
791 else
792 url = xstrdup("foreign");
6b67e0dc 793
f0e278b1 794 rm = ref_map;
7043c707 795 if (check_connected(iterate_ref_map, &rm, NULL)) {
9516a598
TRC
796 rc = error(_("%s did not send all necessary objects\n"), url);
797 goto abort;
798 }
6b67e0dc 799
6bc91f23
NTND
800 prepare_format_display(ref_map);
801
96890f4c 802 /*
900f2814
JK
803 * We do a pass for each fetch_head_status type in their enum order, so
804 * merged entries are written before not-for-merge. That lets readers
805 * use FETCH_HEAD as a refname to refer to the ref to be merged.
96890f4c 806 */
900f2814
JK
807 for (want_status = FETCH_HEAD_MERGE;
808 want_status <= FETCH_HEAD_IGNORE;
809 want_status++) {
96890f4c
JH
810 for (rm = ref_map; rm; rm = rm->next) {
811 struct ref *ref = NULL;
900f2814 812 const char *merge_status_marker = "";
96890f4c 813
4820a33b
NTND
814 if (rm->status == REF_STATUS_REJECT_SHALLOW) {
815 if (want_status == FETCH_HEAD_MERGE)
816 warning(_("reject %s because shallow roots are not allowed to be updated"),
817 rm->peer_ref ? rm->peer_ref->name : rm->name);
818 continue;
819 }
820
bc83266a 821 commit = lookup_commit_reference_gently(&rm->old_oid,
822 1);
96890f4c 823 if (!commit)
900f2814 824 rm->fetch_head_status = FETCH_HEAD_NOT_FOR_MERGE;
96890f4c 825
900f2814 826 if (rm->fetch_head_status != want_status)
96890f4c
JH
827 continue;
828
829 if (rm->peer_ref) {
6f687c21 830 ref = alloc_ref(rm->peer_ref->name);
f4e54d02 831 oidcpy(&ref->old_oid, &rm->peer_ref->old_oid);
832 oidcpy(&ref->new_oid, &rm->old_oid);
96890f4c
JH
833 ref->force = rm->peer_ref->force;
834 }
b888d61c 835
b888d61c 836
96890f4c
JH
837 if (!strcmp(rm->name, "HEAD")) {
838 kind = "";
839 what = "";
840 }
59556548 841 else if (starts_with(rm->name, "refs/heads/")) {
96890f4c
JH
842 kind = "branch";
843 what = rm->name + 11;
844 }
59556548 845 else if (starts_with(rm->name, "refs/tags/")) {
96890f4c
JH
846 kind = "tag";
847 what = rm->name + 10;
848 }
59556548 849 else if (starts_with(rm->name, "refs/remotes/")) {
96890f4c
JH
850 kind = "remote-tracking branch";
851 what = rm->name + 13;
852 }
853 else {
854 kind = "";
855 what = rm->name;
856 }
b888d61c 857
96890f4c
JH
858 url_len = strlen(url);
859 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
860 ;
861 url_len = i + 1;
862 if (4 < i && !strncmp(".git", url + i - 3, 4))
863 url_len = i - 3;
864
865 strbuf_reset(&note);
866 if (*what) {
867 if (*kind)
868 strbuf_addf(&note, "%s ", kind);
869 strbuf_addf(&note, "'%s' of ", what);
870 }
900f2814
JK
871 switch (rm->fetch_head_status) {
872 case FETCH_HEAD_NOT_FOR_MERGE:
873 merge_status_marker = "not-for-merge";
874 /* fall-through */
875 case FETCH_HEAD_MERGE:
876 fprintf(fp, "%s\t%s\t%s",
f4e54d02 877 oid_to_hex(&rm->old_oid),
900f2814
JK
878 merge_status_marker,
879 note.buf);
880 for (i = 0; i < url_len; ++i)
881 if ('\n' == url[i])
882 fputs("\\n", fp);
883 else
884 fputc(url[i], fp);
885 fputc('\n', fp);
886 break;
887 default:
888 /* do not write anything to FETCH_HEAD */
889 break;
890 }
96890f4c
JH
891
892 strbuf_reset(&note);
893 if (ref) {
901f3d40
JH
894 rc |= update_local_ref(ref, what, rm, &note,
895 summary_width);
96890f4c
JH
896 free(ref);
897 } else
d0b39a03
NTND
898 format_display(&note, '*',
899 *kind ? kind : "branch", NULL,
900 *what ? what : "HEAD",
901f3d40 901 "FETCH_HEAD", summary_width);
96890f4c
JH
902 if (note.len) {
903 if (verbosity >= 0 && !shown_url) {
904 fprintf(stderr, _("From %.*s\n"),
905 url_len, url);
906 shown_url = 1;
907 }
908 if (verbosity >= 0)
909 fprintf(stderr, " %s\n", note.buf);
165f3902
NP
910 }
911 }
b888d61c 912 }
9516a598 913
fa250759 914 if (rc & STORE_REF_ERROR_DF_CONFLICT)
bd4a51fc 915 error(_("some local refs could not be updated; try running\n"
f3cb169b 916 " 'git remote prune %s' to remove any old, conflicting "
bd4a51fc 917 "branches"), remote_name);
9516a598
TRC
918
919 abort:
5914f2d0 920 strbuf_release(&note);
9516a598
TRC
921 free(url);
922 fclose(fp);
efb98b44 923 return rc;
b888d61c
DB
924}
925
4191c356
SP
926/*
927 * We would want to bypass the object transfer altogether if
d9eb0205 928 * everything we are going to fetch already exists and is connected
4191c356 929 * locally.
4191c356
SP
930 */
931static int quickfetch(struct ref *ref_map)
932{
f0e278b1 933 struct ref *rm = ref_map;
7043c707 934 struct check_connected_options opt = CHECK_CONNECTED_INIT;
f0e278b1 935
4191c356
SP
936 /*
937 * If we are deepening a shallow clone we already have these
938 * objects reachable. Running rev-list here will return with
939 * a good (0) exit status and we'll bypass the fetch that we
940 * really need to perform. Claiming failure now will ensure
941 * we perform the network exchange to deepen our history.
942 */
508ea882 943 if (deepen)
4191c356 944 return -1;
7043c707
JK
945 opt.quiet = 1;
946 return check_connected(iterate_ref_map, &rm, &opt);
4191c356
SP
947}
948
b888d61c
DB
949static int fetch_refs(struct transport *transport, struct ref *ref_map)
950{
4191c356
SP
951 int ret = quickfetch(ref_map);
952 if (ret)
953 ret = transport_fetch_refs(transport, ref_map);
b888d61c 954 if (!ret)
f3cb169b
JK
955 ret |= store_updated_refs(transport->url,
956 transport->remote->name,
957 ref_map);
1788c39c 958 transport_unlock_pack(transport);
b888d61c
DB
959 return ret;
960}
961
def11e71
BW
962static int prune_refs(struct refspec *rs, struct ref *ref_map,
963 const char *raw_url)
f360d844 964{
4b3b33a7 965 int url_len, i, result = 0;
def11e71 966 struct ref *ref, *stale_refs = get_stale_heads(rs->items, rs->nr, ref_map);
4b3b33a7 967 char *url;
11fd66de 968 int summary_width = transport_summary_width(stale_refs);
f360d844 969 const char *dangling_msg = dry_run
18986d53
NTND
970 ? _(" (%s will become dangling)")
971 : _(" (%s has become dangling)");
f360d844 972
4b3b33a7
TM
973 if (raw_url)
974 url = transport_anonymize_url(raw_url);
975 else
976 url = xstrdup("foreign");
977
978 url_len = strlen(url);
979 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
980 ;
981
982 url_len = i + 1;
983 if (4 < i && !strncmp(".git", url + i - 3, 4))
984 url_len = i - 3;
985
a087b432
MH
986 if (!dry_run) {
987 struct string_list refnames = STRING_LIST_INIT_NODUP;
988
989 for (ref = stale_refs; ref; ref = ref->next)
990 string_list_append(&refnames, ref->name);
991
64da4199 992 result = delete_refs("fetch: prune", &refnames, 0);
a087b432
MH
993 string_list_clear(&refnames, 0);
994 }
995
996 if (verbosity >= 0) {
997 for (ref = stale_refs; ref; ref = ref->next) {
d0b39a03 998 struct strbuf sb = STRBUF_INIT;
a087b432
MH
999 if (!shown_url) {
1000 fprintf(stderr, _("From %.*s\n"), url_len, url);
1001 shown_url = 1;
1002 }
2cb040ba 1003 format_display(&sb, '-', _("[deleted]"), NULL,
901f3d40
JH
1004 _("(none)"), prettify_refname(ref->name),
1005 summary_width);
d0b39a03
NTND
1006 fprintf(stderr, " %s\n",sb.buf);
1007 strbuf_release(&sb);
f360d844
JS
1008 warn_dangling_symref(stderr, dangling_msg, ref->name);
1009 }
1010 }
a087b432 1011
4b3b33a7 1012 free(url);
f360d844
JS
1013 free_refs(stale_refs);
1014 return result;
1015}
1016
8ee5d731
JS
1017static void check_not_current_branch(struct ref *ref_map)
1018{
1019 struct branch *current_branch = branch_get(NULL);
1020
1021 if (is_bare_repository() || !current_branch)
1022 return;
1023
1024 for (; ref_map; ref_map = ref_map->next)
1025 if (ref_map->peer_ref && !strcmp(current_branch->refname,
1026 ref_map->peer_ref->name))
bd4a51fc
ÆAB
1027 die(_("Refusing to fetch into current branch %s "
1028 "of non-bare repository"), current_branch->refname);
8ee5d731
JS
1029}
1030
e6cc5104
JH
1031static int truncate_fetch_head(void)
1032{
f932729c 1033 const char *filename = git_path_fetch_head();
ea56518d 1034 FILE *fp = fopen_for_writing(filename);
e6cc5104
JH
1035
1036 if (!fp)
6da31d7f 1037 return error_errno(_("cannot open %s"), filename);
e6cc5104
JH
1038 fclose(fp);
1039 return 0;
1040}
1041
db5723c6
JH
1042static void set_option(struct transport *transport, const char *name, const char *value)
1043{
1044 int r = transport_set_option(transport, name, value);
1045 if (r < 0)
1046 die(_("Option \"%s\" value \"%s\" is not valid for %s"),
1047 name, value, transport->url);
1048 if (r > 0)
1049 warning(_("Option \"%s\" is ignored for %s\n"),
1050 name, transport->url);
1051}
1052
508ea882 1053static struct transport *prepare_transport(struct remote *remote, int deepen)
db5723c6
JH
1054{
1055 struct transport *transport;
1056 transport = transport_get(remote, NULL);
1057 transport_set_verbosity(transport, verbosity, progress);
c915f11e 1058 transport->family = family;
db5723c6
JH
1059 if (upload_pack)
1060 set_option(transport, TRANS_OPT_UPLOADPACK, upload_pack);
1061 if (keep)
1062 set_option(transport, TRANS_OPT_KEEP, "yes");
1063 if (depth)
1064 set_option(transport, TRANS_OPT_DEPTH, depth);
508ea882
NTND
1065 if (deepen && deepen_since)
1066 set_option(transport, TRANS_OPT_DEEPEN_SINCE, deepen_since);
a45a2600
NTND
1067 if (deepen && deepen_not.nr)
1068 set_option(transport, TRANS_OPT_DEEPEN_NOT,
1069 (const char *)&deepen_not);
cccf74e2
NTND
1070 if (deepen_relative)
1071 set_option(transport, TRANS_OPT_DEEPEN_RELATIVE, "yes");
48d25cae
NTND
1072 if (update_shallow)
1073 set_option(transport, TRANS_OPT_UPDATE_SHALLOW, "yes");
acb0c572
JH
1074 if (filter_options.choice) {
1075 set_option(transport, TRANS_OPT_LIST_OBJECTS_FILTER,
1076 filter_options.filter_spec);
1077 set_option(transport, TRANS_OPT_FROM_PROMISOR, "1");
1078 }
db5723c6
JH
1079 return transport;
1080}
1081
069d5032
JH
1082static void backfill_tags(struct transport *transport, struct ref *ref_map)
1083{
508ea882
NTND
1084 int cannot_reuse;
1085
1086 /*
1087 * Once we have set TRANS_OPT_DEEPEN_SINCE, we can't unset it
1088 * when remote helper is used (setting it to an empty string
1089 * is not unsetting). We could extend the remote helper
1090 * protocol for that, but for now, just force a new connection
a45a2600 1091 * without deepen-since. Similar story for deepen-not.
508ea882 1092 */
a45a2600
NTND
1093 cannot_reuse = transport->cannot_reuse ||
1094 deepen_since || deepen_not.nr;
508ea882
NTND
1095 if (cannot_reuse) {
1096 gsecondary = prepare_transport(transport->remote, 0);
b26ed430
JH
1097 transport = gsecondary;
1098 }
1099
069d5032
JH
1100 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
1101 transport_set_option(transport, TRANS_OPT_DEPTH, "0");
cccf74e2 1102 transport_set_option(transport, TRANS_OPT_DEEPEN_RELATIVE, NULL);
069d5032 1103 fetch_refs(transport, ref_map);
b26ed430
JH
1104
1105 if (gsecondary) {
1106 transport_disconnect(gsecondary);
1107 gsecondary = NULL;
1108 }
069d5032
JH
1109}
1110
b888d61c 1111static int do_fetch(struct transport *transport,
65a1301f 1112 struct refspec *rs)
b888d61c 1113{
b87dbcc8 1114 struct string_list existing_refs = STRING_LIST_INIT_DUP;
7f98428d 1115 struct ref *ref_map;
b888d61c
DB
1116 struct ref *rm;
1117 int autotags = (transport->remote->fetch_tags == 1);
5b87d8d3 1118 int retcode = 0;
b1a01e1c 1119
0e0b7de4 1120 for_each_ref(add_existing, &existing_refs);
b1a01e1c 1121
ed368546
DJ
1122 if (tags == TAGS_DEFAULT) {
1123 if (transport->remote->fetch_tags == 2)
1124 tags = TAGS_SET;
1125 if (transport->remote->fetch_tags == -1)
1126 tags = TAGS_UNSET;
1127 }
b888d61c 1128
b888d61c 1129 /* if not appending, truncate FETCH_HEAD */
28a15401 1130 if (!append && !dry_run) {
5b87d8d3
MH
1131 retcode = truncate_fetch_head();
1132 if (retcode)
1133 goto cleanup;
d6617c7c 1134 }
b888d61c 1135
65d96c8b 1136 ref_map = get_ref_map(transport, rs, tags, &autotags);
8ee5d731
JS
1137 if (!update_head_ok)
1138 check_not_current_branch(ref_map);
b888d61c
DB
1139
1140 for (rm = ref_map; rm; rm = rm->next) {
b1a01e1c 1141 if (rm->peer_ref) {
6f64a16f
MH
1142 struct string_list_item *peer_item =
1143 string_list_lookup(&existing_refs,
1144 rm->peer_ref->name);
0e0b7de4
MH
1145 if (peer_item) {
1146 struct object_id *old_oid = peer_item->util;
f4e54d02 1147 oidcpy(&rm->peer_ref->old_oid, old_oid);
0e0b7de4 1148 }
b1a01e1c 1149 }
b888d61c
DB
1150 }
1151
41fa7d2e
SP
1152 if (tags == TAGS_DEFAULT && autotags)
1153 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
ed43de6e 1154 if (prune) {
0838bf47
MH
1155 /*
1156 * We only prune based on refspecs specified
1157 * explicitly (via command line or configuration); we
1158 * don't care whether --tags was specified.
1159 */
65a1301f 1160 if (rs->nr) {
def11e71 1161 prune_refs(rs, ref_map, transport->url);
e8c1e6c7 1162 } else {
def11e71 1163 prune_refs(&transport->remote->fetch,
4b3b33a7
TM
1164 ref_map,
1165 transport->url);
e8c1e6c7 1166 }
ed43de6e 1167 }
10a6cc88
TM
1168 if (fetch_refs(transport, ref_map)) {
1169 free_refs(ref_map);
1170 retcode = 1;
1171 goto cleanup;
1172 }
7f98428d 1173 free_refs(ref_map);
b888d61c
DB
1174
1175 /* if neither --no-tags nor --tags was specified, do automated tag
1176 * following ... */
83201998 1177 if (tags == TAGS_DEFAULT && autotags) {
c50b2b47
SP
1178 struct ref **tail = &ref_map;
1179 ref_map = NULL;
1180 find_non_local_tags(transport, &ref_map, &tail);
069d5032
JH
1181 if (ref_map)
1182 backfill_tags(transport, ref_map);
b888d61c
DB
1183 free_refs(ref_map);
1184 }
1185
5b87d8d3 1186 cleanup:
f83918ed 1187 string_list_clear(&existing_refs, 1);
5b87d8d3 1188 return retcode;
b888d61c
DB
1189}
1190
9c4a036b
BG
1191static int get_one_remote_for_fetch(struct remote *remote, void *priv)
1192{
1193 struct string_list *list = priv;
7cc91a2f 1194 if (!remote->skip_default_update)
1d2f80fa 1195 string_list_append(list, remote->name);
9c4a036b
BG
1196 return 0;
1197}
1198
1199struct remote_group_data {
1200 const char *name;
1201 struct string_list *list;
1202};
1203
1204static int get_remote_group(const char *key, const char *value, void *priv)
1205{
1206 struct remote_group_data *g = priv;
1207
bc598c32 1208 if (skip_prefix(key, "remotes.", &key) && !strcmp(key, g->name)) {
9c4a036b 1209 /* split list by white space */
9c4a036b 1210 while (*value) {
5f65499f
MH
1211 size_t wordlen = strcspn(value, " \t\n");
1212
e286542d 1213 if (wordlen >= 1)
b7410f61 1214 string_list_append_nodup(g->list,
e286542d
MH
1215 xstrndup(value, wordlen));
1216 value += wordlen + (value[wordlen] != '\0');
9c4a036b
BG
1217 }
1218 }
1219
1220 return 0;
1221}
1222
1223static int add_remote_or_group(const char *name, struct string_list *list)
1224{
1225 int prev_nr = list->nr;
66dbfd55
GV
1226 struct remote_group_data g;
1227 g.name = name; g.list = list;
9c4a036b
BG
1228
1229 git_config(get_remote_group, &g);
1230 if (list->nr == prev_nr) {
674468b3 1231 struct remote *remote = remote_get(name);
e459b073 1232 if (!remote_is_configured(remote, 0))
9c4a036b 1233 return 0;
1d2f80fa 1234 string_list_append(list, remote->name);
9c4a036b
BG
1235 }
1236 return 1;
1237}
1238
85556d4e 1239static void add_options_to_argv(struct argv_array *argv)
9c4a036b 1240{
28a15401 1241 if (dry_run)
85556d4e 1242 argv_array_push(argv, "--dry-run");
90765fa3
MH
1243 if (prune != -1)
1244 argv_array_push(argv, prune ? "--prune" : "--no-prune");
97716d21
ÆAB
1245 if (prune_tags != -1)
1246 argv_array_push(argv, prune_tags ? "--prune-tags" : "--no-prune-tags");
bba5322a 1247 if (update_head_ok)
85556d4e 1248 argv_array_push(argv, "--update-head-ok");
bba5322a 1249 if (force)
85556d4e 1250 argv_array_push(argv, "--force");
bba5322a 1251 if (keep)
85556d4e 1252 argv_array_push(argv, "--keep");
be254a0e 1253 if (recurse_submodules == RECURSE_SUBMODULES_ON)
85556d4e 1254 argv_array_push(argv, "--recurse-submodules");
8f0700dd 1255 else if (recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND)
85556d4e 1256 argv_array_push(argv, "--recurse-submodules=on-demand");
85566460
DJ
1257 if (tags == TAGS_SET)
1258 argv_array_push(argv, "--tags");
1259 else if (tags == TAGS_UNSET)
1260 argv_array_push(argv, "--no-tags");
9c4a036b 1261 if (verbosity >= 2)
85556d4e 1262 argv_array_push(argv, "-v");
9c4a036b 1263 if (verbosity >= 1)
85556d4e 1264 argv_array_push(argv, "-v");
9c4a036b 1265 else if (verbosity < 0)
85556d4e 1266 argv_array_push(argv, "-q");
7dce19d3
JL
1267
1268}
1269
1270static int fetch_multiple(struct string_list *list)
1271{
1272 int i, result = 0;
85556d4e 1273 struct argv_array argv = ARGV_ARRAY_INIT;
9c4a036b 1274
e6cc5104
JH
1275 if (!append && !dry_run) {
1276 int errcode = truncate_fetch_head();
1277 if (errcode)
1278 return errcode;
1279 }
1280
85556d4e
JK
1281 argv_array_pushl(&argv, "fetch", "--append", NULL);
1282 add_options_to_argv(&argv);
1283
9c4a036b
BG
1284 for (i = 0; i < list->nr; i++) {
1285 const char *name = list->items[i].string;
85556d4e 1286 argv_array_push(&argv, name);
9c4a036b 1287 if (verbosity >= 0)
bd4a51fc 1288 printf(_("Fetching %s\n"), name);
85556d4e 1289 if (run_command_v_opt(argv.argv, RUN_GIT_CMD)) {
bd4a51fc 1290 error(_("Could not fetch %s"), name);
9c4a036b
BG
1291 result = 1;
1292 }
85556d4e 1293 argv_array_pop(&argv);
9c4a036b
BG
1294 }
1295
85556d4e 1296 argv_array_clear(&argv);
9c4a036b
BG
1297 return result;
1298}
1299
aa57b871
JH
1300/*
1301 * Fetching from the promisor remote should use the given filter-spec
1302 * or inherit the default filter-spec from the config.
1303 */
1304static inline void fetch_one_setup_partial(struct remote *remote)
1305{
1306 /*
1307 * Explicit --no-filter argument overrides everything, regardless
1308 * of any prior partial clones and fetches.
1309 */
1310 if (filter_options.no_filter)
1311 return;
1312
1313 /*
1314 * If no prior partial clone/fetch and the current fetch DID NOT
1315 * request a partial-fetch, do a normal fetch.
1316 */
1317 if (!repository_format_partial_clone && !filter_options.choice)
1318 return;
1319
1320 /*
1321 * If this is the FIRST partial-fetch request, we enable partial
1322 * on this repo and remember the given filter-spec as the default
1323 * for subsequent fetches to this remote.
1324 */
1325 if (!repository_format_partial_clone && filter_options.choice) {
1326 partial_clone_register(remote->name, &filter_options);
1327 return;
1328 }
1329
1330 /*
1331 * We are currently limited to only ONE promisor remote and only
1332 * allow partial-fetches from the promisor remote.
1333 */
1334 if (strcmp(remote->name, repository_format_partial_clone)) {
1335 if (filter_options.choice)
1336 die(_("--filter can only be used with the remote configured in core.partialClone"));
1337 return;
1338 }
1339
1340 /*
1341 * Do a partial-fetch from the promisor remote using either the
1342 * explicitly given filter-spec or inherit the filter-spec from
1343 * the config.
1344 */
1345 if (!filter_options.choice)
1346 partial_clone_get_default_filter_spec(&filter_options);
1347 return;
1348}
1349
97716d21 1350static int fetch_one(struct remote *remote, int argc, const char **argv, int prune_tags_ok)
b888d61c 1351{
d7c8e307
BW
1352 struct refspec rs = REFSPEC_INIT_FETCH;
1353 int i;
7b7f39ea 1354 int exit_code;
6317972c
ÆAB
1355 int maybe_prune_tags;
1356 int remote_via_config = remote_is_configured(remote, 0);
b888d61c 1357
fa685bdf 1358 if (!remote)
bd4a51fc
ÆAB
1359 die(_("No remote repository specified. Please, specify either a URL or a\n"
1360 "remote name from which new revisions should be fetched."));
fa685bdf 1361
508ea882 1362 gtransport = prepare_transport(remote, 1);
737c5a9c
MS
1363
1364 if (prune < 0) {
1365 /* no command line request */
07118832
ÆAB
1366 if (0 <= remote->prune)
1367 prune = remote->prune;
737c5a9c
MS
1368 else if (0 <= fetch_prune_config)
1369 prune = fetch_prune_config;
1370 else
1371 prune = PRUNE_BY_DEFAULT;
1372 }
1373
97716d21
ÆAB
1374 if (prune_tags < 0) {
1375 /* no command line request */
1376 if (0 <= remote->prune_tags)
1377 prune_tags = remote->prune_tags;
1378 else if (0 <= fetch_prune_tags_config)
1379 prune_tags = fetch_prune_tags_config;
1380 else
1381 prune_tags = PRUNE_TAGS_BY_DEFAULT;
1382 }
1383
6317972c
ÆAB
1384 maybe_prune_tags = prune_tags_ok && prune_tags;
1385 if (maybe_prune_tags && remote_via_config)
95303500 1386 refspec_append(&remote->fetch, TAG_REFSPEC);
97716d21 1387
d7c8e307
BW
1388 if (maybe_prune_tags && (argc || !remote_via_config))
1389 refspec_append(&rs, TAG_REFSPEC);
6317972c 1390
d7c8e307
BW
1391 for (i = 0; i < argc; i++) {
1392 if (!strcmp(argv[i], "tag")) {
1393 char *tag;
1394 i++;
1395 if (i >= argc)
1396 die(_("You need to specify a tag name."));
1397
1398 tag = xstrfmt("refs/tags/%s:refs/tags/%s",
1399 argv[i], argv[i]);
1400 refspec_append(&rs, tag);
1401 free(tag);
1402 } else {
1403 refspec_append(&rs, argv[i]);
b888d61c 1404 }
b888d61c
DB
1405 }
1406
57b235a4 1407 sigchain_push_common(unlock_pack_on_signal);
e4022ed2 1408 atexit(unlock_pack);
65a1301f 1409 exit_code = do_fetch(gtransport, &rs);
d7c8e307 1410 refspec_clear(&rs);
af234459
JH
1411 transport_disconnect(gtransport);
1412 gtransport = NULL;
7b7f39ea 1413 return exit_code;
b888d61c 1414}
9c4a036b
BG
1415
1416int cmd_fetch(int argc, const char **argv, const char *prefix)
1417{
1418 int i;
b7410f61 1419 struct string_list list = STRING_LIST_INIT_DUP;
a1743343 1420 struct remote *remote = NULL;
9c4a036b 1421 int result = 0;
c1a7902f 1422 int prune_tags_ok = 1;
1991006c 1423 struct argv_array argv_gc_auto = ARGV_ARRAY_INIT;
9c4a036b 1424
bbc30f99
JK
1425 packet_trace_identity("fetch");
1426
acb0c572
JH
1427 fetch_if_missing = 0;
1428
9c4a036b
BG
1429 /* Record the command line for the reflog */
1430 strbuf_addstr(&default_rla, "fetch");
1431 for (i = 1; i < argc; i++)
1432 strbuf_addf(&default_rla, " %s", argv[i]);
1433
f20e7c1e 1434 config_from_gitmodules(gitmodules_fetch_config, NULL);
737c5a9c
MS
1435 git_config(git_fetch_config, NULL);
1436
9c4a036b
BG
1437 argc = parse_options(argc, argv, prefix,
1438 builtin_fetch_options, builtin_fetch_usage, 0);
1439
cccf74e2
NTND
1440 if (deepen_relative) {
1441 if (deepen_relative < 0)
1442 die(_("Negative depth in --deepen is not supported"));
1443 if (depth)
1444 die(_("--deepen and --depth are mutually exclusive"));
1445 depth = xstrfmt("%d", deepen_relative);
1446 }
4dcb167f
NTND
1447 if (unshallow) {
1448 if (depth)
1449 die(_("--depth and --unshallow cannot be used together"));
1450 else if (!is_repository_shallow())
1451 die(_("--unshallow on a complete repository does not make sense"));
2805bb59
JK
1452 else
1453 depth = xstrfmt("%d", INFINITE_DEPTH);
4dcb167f
NTND
1454 }
1455
5594bcad
NTND
1456 /* no need to be strict, transport_set_option() will validate it again */
1457 if (depth && atoi(depth) < 1)
1458 die(_("depth %s is not a positive number"), depth);
a45a2600 1459 if (depth || deepen_since || deepen_not.nr)
508ea882 1460 deepen = 1;
5594bcad 1461
acb0c572
JH
1462 if (filter_options.choice && !repository_format_partial_clone)
1463 die("--filter can only be used when extensions.partialClone is set");
1464
9c4a036b
BG
1465 if (all) {
1466 if (argc == 1)
bd4a51fc 1467 die(_("fetch --all does not take a repository argument"));
9c4a036b 1468 else if (argc > 1)
bd4a51fc 1469 die(_("fetch --all does not make sense with refspecs"));
9c4a036b 1470 (void) for_each_remote(get_one_remote_for_fetch, &list);
9c4a036b
BG
1471 } else if (argc == 0) {
1472 /* No arguments -- use default remote */
1473 remote = remote_get(NULL);
16679e37
BG
1474 } else if (multiple) {
1475 /* All arguments are assumed to be remotes or groups */
1476 for (i = 0; i < argc; i++)
1477 if (!add_remote_or_group(argv[i], &list))
bd4a51fc 1478 die(_("No such remote or remote group: %s"), argv[i]);
9c4a036b
BG
1479 } else {
1480 /* Single remote or group */
1481 (void) add_remote_or_group(argv[0], &list);
1482 if (list.nr > 1) {
1483 /* More than one remote */
1484 if (argc > 1)
bd4a51fc 1485 die(_("Fetching a group and specifying refspecs does not make sense"));
9c4a036b
BG
1486 } else {
1487 /* Zero or one remotes */
1488 remote = remote_get(argv[0]);
c1a7902f 1489 prune_tags_ok = (argc == 1);
a1743343
JT
1490 argc--;
1491 argv++;
9c4a036b
BG
1492 }
1493 }
1494
acb0c572 1495 if (remote) {
aa57b871
JH
1496 if (filter_options.choice || repository_format_partial_clone)
1497 fetch_one_setup_partial(remote);
c1a7902f 1498 result = fetch_one(remote, argc, argv, prune_tags_ok);
acb0c572
JH
1499 } else {
1500 if (filter_options.choice)
1501 die(_("--filter can only be used with the remote configured in core.partialClone"));
aa57b871 1502 /* TODO should this also die if we have a previous partial-clone? */
a1743343 1503 result = fetch_multiple(&list);
acb0c572 1504 }
a1743343 1505
be254a0e 1506 if (!result && (recurse_submodules != RECURSE_SUBMODULES_OFF)) {
85556d4e
JK
1507 struct argv_array options = ARGV_ARRAY_INIT;
1508
1509 add_options_to_argv(&options);
e724197f
BW
1510 result = fetch_populated_submodules(the_repository,
1511 &options,
7dce19d3 1512 submodule_prefix,
8f0700dd 1513 recurse_submodules,
8fa29159 1514 recurse_submodules_default,
62104ba1
SB
1515 verbosity < 0,
1516 max_children);
85556d4e 1517 argv_array_clear(&options);
7dce19d3
JL
1518 }
1519
9c4a036b
BG
1520 string_list_clear(&list, 0);
1521
d0b59866 1522 close_all_packs(the_repository->objects);
0898c962 1523
1991006c 1524 argv_array_pushl(&argv_gc_auto, "gc", "--auto", NULL);
6fceed3b
NTND
1525 if (verbosity < 0)
1526 argv_array_push(&argv_gc_auto, "--quiet");
1991006c
NTND
1527 run_command_v_opt(argv_gc_auto.argv, RUN_GIT_CMD);
1528 argv_array_clear(&argv_gc_auto);
131b8fcb 1529
9c4a036b
BG
1530 return result;
1531}