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