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