fetch: opportunistically update tracking refs
[git/git.git] / builtin / fetch.c
CommitLineData
b888d61c
DB
1/*
2 * "git fetch"
3 */
4#include "cache.h"
5#include "refs.h"
6#include "commit.h"
7#include "builtin.h"
c455c87c 8#include "string-list.h"
b888d61c
DB
9#include "remote.h"
10#include "transport.h"
4191c356 11#include "run-command.h"
83201998 12#include "parse-options.h"
4a16d072 13#include "sigchain.h"
f1863d0d 14#include "transport.h"
7dce19d3 15#include "submodule.h"
f96400cb 16#include "connected.h"
85556d4e 17#include "argv-array.h"
b888d61c 18
83201998 19static const char * const builtin_fetch_usage[] = {
719acedb
NTND
20 N_("git fetch [<options>] [<repository> [<refspec>...]]"),
21 N_("git fetch [<options>] <group>"),
22 N_("git fetch --multiple [<options>] [(<repository> | <group>)...]"),
23 N_("git fetch --all [<options>]"),
83201998
KH
24 NULL
25};
b888d61c 26
83201998
KH
27enum {
28 TAGS_UNSET = 0,
29 TAGS_DEFAULT = 1,
30 TAGS_SET = 2
31};
32
28a15401 33static int all, append, dry_run, force, keep, multiple, prune, update_head_ok, verbosity;
01fdc21f 34static int progress = -1, recurse_submodules = RECURSE_SUBMODULES_DEFAULT;
4dcb167f 35static int tags = TAGS_DEFAULT, unshallow;
4191c356 36static const char *depth;
83201998 37static const char *upload_pack;
2d324efa 38static struct strbuf default_rla = STRBUF_INIT;
e4022ed2 39static struct transport *transport;
7dce19d3 40static const char *submodule_prefix = "";
88a21979 41static const char *recurse_submodules_default;
e4022ed2 42
8f0700dd
JL
43static int option_parse_recurse_submodules(const struct option *opt,
44 const char *arg, int unset)
45{
46 if (unset) {
47 recurse_submodules = RECURSE_SUBMODULES_OFF;
48 } else {
49 if (arg)
50 recurse_submodules = parse_fetch_recurse_submodules_arg(opt->long_name, arg);
51 else
52 recurse_submodules = RECURSE_SUBMODULES_ON;
53 }
54 return 0;
55}
e4022ed2 56
83201998 57static struct option builtin_fetch_options[] = {
7f87aff2 58 OPT__VERBOSITY(&verbosity),
9c4a036b 59 OPT_BOOLEAN(0, "all", &all,
719acedb 60 N_("fetch from all remotes")),
83201998 61 OPT_BOOLEAN('a', "append", &append,
719acedb
NTND
62 N_("append to .git/FETCH_HEAD instead of overwriting")),
63 OPT_STRING(0, "upload-pack", &upload_pack, N_("path"),
64 N_("path to upload pack on remote end")),
65 OPT__FORCE(&force, N_("force overwrite of local branch")),
16679e37 66 OPT_BOOLEAN('m', "multiple", &multiple,
719acedb 67 N_("fetch from multiple remotes")),
83201998 68 OPT_SET_INT('t', "tags", &tags,
719acedb 69 N_("fetch all tags and associated objects"), TAGS_SET),
e7951290 70 OPT_SET_INT('n', NULL, &tags,
719acedb 71 N_("do not fetch all tags (--no-tags)"), TAGS_UNSET),
f360d844 72 OPT_BOOLEAN('p', "prune", &prune,
719acedb
NTND
73 N_("prune remote-tracking branches no longer on remote")),
74 { OPTION_CALLBACK, 0, "recurse-submodules", NULL, N_("on-demand"),
75 N_("control recursive fetching of submodules"),
8f0700dd 76 PARSE_OPT_OPTARG, option_parse_recurse_submodules },
28a15401 77 OPT_BOOLEAN(0, "dry-run", &dry_run,
719acedb
NTND
78 N_("dry run")),
79 OPT_BOOLEAN('k', "keep", &keep, N_("keep downloaded pack")),
83201998 80 OPT_BOOLEAN('u', "update-head-ok", &update_head_ok,
719acedb
NTND
81 N_("allow updating of HEAD ref")),
82 OPT_BOOL(0, "progress", &progress, N_("force progress reporting")),
83 OPT_STRING(0, "depth", &depth, N_("depth"),
84 N_("deepen history of shallow clone")),
4dcb167f
NTND
85 { OPTION_SET_INT, 0, "unshallow", &unshallow, NULL,
86 N_("convert to a complete repository"),
87 PARSE_OPT_NONEG | PARSE_OPT_NOARG, NULL, 1 },
719acedb
NTND
88 { OPTION_STRING, 0, "submodule-prefix", &submodule_prefix, N_("dir"),
89 N_("prepend this to submodule path output"), PARSE_OPT_HIDDEN },
88a21979
JL
90 { OPTION_STRING, 0, "recurse-submodules-default",
91 &recurse_submodules_default, NULL,
719acedb 92 N_("default mode for recursion"), PARSE_OPT_HIDDEN },
83201998
KH
93 OPT_END()
94};
95
e4022ed2
SP
96static void unlock_pack(void)
97{
98 if (transport)
99 transport_unlock_pack(transport);
100}
101
102static void unlock_pack_on_signal(int signo)
103{
104 unlock_pack();
4a16d072 105 sigchain_pop(signo);
e4022ed2
SP
106 raise(signo);
107}
b888d61c 108
85682c19 109static void add_merge_config(struct ref **head,
4577370e 110 const struct ref *remote_refs,
85682c19
SP
111 struct branch *branch,
112 struct ref ***tail)
b888d61c 113{
85682c19 114 int i;
b888d61c 115
85682c19
SP
116 for (i = 0; i < branch->merge_nr; i++) {
117 struct ref *rm, **old_tail = *tail;
118 struct refspec refspec;
119
120 for (rm = *head; rm; rm = rm->next) {
121 if (branch_merge_matches(branch, i, rm->name)) {
900f2814 122 rm->fetch_head_status = FETCH_HEAD_MERGE;
85682c19
SP
123 break;
124 }
b888d61c 125 }
85682c19
SP
126 if (rm)
127 continue;
128
9ad7c5ae 129 /*
8b3f3f84 130 * Not fetched to a remote-tracking branch? We need to fetch
85682c19 131 * it anyway to allow this branch's "branch.$name.merge"
05207a28 132 * to be honored by 'git pull', but we do not have to
9ad7c5ae
JH
133 * fail if branch.$name.merge is misconfigured to point
134 * at a nonexisting branch. If we were indeed called by
05207a28 135 * 'git pull', it will notice the misconfiguration because
9ad7c5ae
JH
136 * there is no entry in the resulting FETCH_HEAD marked
137 * for merging.
85682c19 138 */
8da61a2a 139 memset(&refspec, 0, sizeof(refspec));
85682c19 140 refspec.src = branch->merge[i]->src;
9ad7c5ae 141 get_fetch_map(remote_refs, &refspec, tail, 1);
85682c19 142 for (rm = *old_tail; rm; rm = rm->next)
900f2814 143 rm->fetch_head_status = FETCH_HEAD_MERGE;
b888d61c
DB
144 }
145}
146
767f176a
SP
147static void find_non_local_tags(struct transport *transport,
148 struct ref **head,
149 struct ref ***tail);
150
b888d61c
DB
151static struct ref *get_ref_map(struct transport *transport,
152 struct refspec *refs, int ref_count, int tags,
153 int *autotags)
154{
155 int i;
156 struct ref *rm;
157 struct ref *ref_map = NULL;
158 struct ref **tail = &ref_map;
159
4577370e 160 const struct ref *remote_refs = transport_get_remote_refs(transport);
b888d61c 161
83201998 162 if (ref_count || tags == TAGS_SET) {
f2690487
JK
163 struct ref **old_tail;
164
b888d61c 165 for (i = 0; i < ref_count; i++) {
9ad7c5ae 166 get_fetch_map(remote_refs, &refs[i], &tail, 0);
b888d61c
DB
167 if (refs[i].dst && refs[i].dst[0])
168 *autotags = 1;
169 }
170 /* Merge everything on the command line, but not --tags */
171 for (rm = ref_map; rm; rm = rm->next)
900f2814 172 rm->fetch_head_status = FETCH_HEAD_MERGE;
e0aaa29f
DB
173 if (tags == TAGS_SET)
174 get_fetch_map(remote_refs, tag_refspec, &tail, 0);
f2690487
JK
175
176 /*
177 * For any refs that we happen to be fetching via command-line
178 * arguments, take the opportunity to update their configured
179 * counterparts. However, we do not want to mention these
180 * entries in FETCH_HEAD at all, as they would simply be
181 * duplicates of existing entries.
182 */
183 old_tail = tail;
184 for (i = 0; i < transport->remote->fetch_refspec_nr; i++)
185 get_fetch_map(ref_map, &transport->remote->fetch[i],
186 &tail, 0);
187 for (rm = *old_tail; rm; rm = rm->next)
188 rm->fetch_head_status = FETCH_HEAD_IGNORE;
b888d61c
DB
189 } else {
190 /* Use the defaults */
191 struct remote *remote = transport->remote;
85682c19
SP
192 struct branch *branch = branch_get(NULL);
193 int has_merge = branch_has_merge_config(branch);
3ee1757b
BC
194 if (remote &&
195 (remote->fetch_refspec_nr ||
f31dbdc7 196 /* Note: has_merge implies non-NULL branch->remote_name */
3ee1757b 197 (has_merge && !strcmp(branch->remote_name, remote->name)))) {
b888d61c 198 for (i = 0; i < remote->fetch_refspec_nr; i++) {
9ad7c5ae 199 get_fetch_map(remote_refs, &remote->fetch[i], &tail, 0);
b888d61c
DB
200 if (remote->fetch[i].dst &&
201 remote->fetch[i].dst[0])
202 *autotags = 1;
85682c19 203 if (!i && !has_merge && ref_map &&
cfb8f898 204 !remote->fetch[0].pattern)
900f2814 205 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
b888d61c 206 }
da0204df
JS
207 /*
208 * if the remote we're fetching from is the same
209 * as given in branch.<name>.remote, we add the
210 * ref given in branch.<name>.merge, too.
f31dbdc7
BC
211 *
212 * Note: has_merge implies non-NULL branch->remote_name
da0204df 213 */
9ad7c5ae
JH
214 if (has_merge &&
215 !strcmp(branch->remote_name, remote->name))
85682c19 216 add_merge_config(&ref_map, remote_refs, branch, &tail);
b888d61c
DB
217 } else {
218 ref_map = get_remote_ref(remote_refs, "HEAD");
9ad7c5ae 219 if (!ref_map)
bd4a51fc 220 die(_("Couldn't find remote ref HEAD"));
900f2814 221 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
5aaf7f2a 222 tail = &ref_map->next;
b888d61c
DB
223 }
224 }
767f176a
SP
225 if (tags == TAGS_DEFAULT && *autotags)
226 find_non_local_tags(transport, &ref_map, &tail);
2467a4fa 227 ref_remove_duplicates(ref_map);
b888d61c
DB
228
229 return ref_map;
230}
231
fa250759
JK
232#define STORE_REF_ERROR_OTHER 1
233#define STORE_REF_ERROR_DF_CONFLICT 2
234
b888d61c
DB
235static int s_update_ref(const char *action,
236 struct ref *ref,
237 int check_old)
238{
239 char msg[1024];
240 char *rla = getenv("GIT_REFLOG_ACTION");
241 static struct ref_lock *lock;
242
28a15401
JS
243 if (dry_run)
244 return 0;
b888d61c 245 if (!rla)
2d324efa 246 rla = default_rla.buf;
b888d61c
DB
247 snprintf(msg, sizeof(msg), "%s: %s", rla, action);
248 lock = lock_any_ref_for_update(ref->name,
249 check_old ? ref->old_sha1 : NULL, 0);
250 if (!lock)
fa250759
JK
251 return errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
252 STORE_REF_ERROR_OTHER;
b888d61c 253 if (write_ref_sha1(lock, ref->new_sha1, msg) < 0)
fa250759
JK
254 return errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
255 STORE_REF_ERROR_OTHER;
b888d61c
DB
256 return 0;
257}
258
9ef4272b 259#define REFCOL_WIDTH 10
165f3902 260
b888d61c 261static int update_local_ref(struct ref *ref,
165f3902 262 const char *remote,
6da618d5 263 const struct ref *remote_ref,
5914f2d0 264 struct strbuf *display)
b888d61c 265{
b888d61c
DB
266 struct commit *current = NULL, *updated;
267 enum object_type type;
268 struct branch *current_branch = branch_get(NULL);
4577e483 269 const char *pretty_ref = prettify_refname(ref->name);
b888d61c
DB
270
271 type = sha1_object_info(ref->new_sha1, NULL);
272 if (type < 0)
bd4a51fc 273 die(_("object %s not found"), sha1_to_hex(ref->new_sha1));
b888d61c 274
b888d61c 275 if (!hashcmp(ref->old_sha1, ref->new_sha1)) {
7f87aff2 276 if (verbosity > 0)
5914f2d0 277 strbuf_addf(display, "= %-*s %-*s -> %s",
754395d3
NTND
278 TRANSPORT_SUMMARY(_("[up to date]")),
279 REFCOL_WIDTH, remote, pretty_ref);
b888d61c
DB
280 return 0;
281 }
282
b3abdd9d
SP
283 if (current_branch &&
284 !strcmp(ref->name, current_branch->name) &&
b888d61c
DB
285 !(update_head_ok || is_bare_repository()) &&
286 !is_null_sha1(ref->old_sha1)) {
287 /*
288 * If this is the head, and it's not okay to update
289 * the head, and the old value of the head isn't empty...
290 */
5914f2d0
JK
291 strbuf_addf(display,
292 _("! %-*s %-*s -> %s (can't fetch in current branch)"),
754395d3 293 TRANSPORT_SUMMARY(_("[rejected]")),
5914f2d0 294 REFCOL_WIDTH, remote, pretty_ref);
b888d61c
DB
295 return 1;
296 }
297
298 if (!is_null_sha1(ref->old_sha1) &&
299 !prefixcmp(ref->name, "refs/tags/")) {
6315472e
JK
300 int r;
301 r = s_update_ref("updating tag", ref, 0);
5914f2d0
JK
302 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
303 r ? '!' : '-',
754395d3 304 TRANSPORT_SUMMARY(_("[tag update]")),
5914f2d0
JK
305 REFCOL_WIDTH, remote, pretty_ref,
306 r ? _(" (unable to update local ref)") : "");
6315472e 307 return r;
b888d61c
DB
308 }
309
cfa5b2b7
SP
310 current = lookup_commit_reference_gently(ref->old_sha1, 1);
311 updated = lookup_commit_reference_gently(ref->new_sha1, 1);
b888d61c 312 if (!current || !updated) {
165f3902
NP
313 const char *msg;
314 const char *what;
6315472e 315 int r;
0997adaa
MB
316 /*
317 * Nicely describe the new ref we're fetching.
318 * Base this on the remote's ref name, as it's
319 * more likely to follow a standard layout.
320 */
321 const char *name = remote_ref ? remote_ref->name : "";
322 if (!prefixcmp(name, "refs/tags/")) {
b888d61c 323 msg = "storing tag";
f7b3742a 324 what = _("[new tag]");
0997adaa 325 } else if (!prefixcmp(name, "refs/heads/")) {
b888d61c 326 msg = "storing head";
f7b3742a 327 what = _("[new branch]");
0997adaa
MB
328 } else {
329 msg = "storing ref";
330 what = _("[new ref]");
165f3902
NP
331 }
332
a6801adc
JL
333 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
334 (recurse_submodules != RECURSE_SUBMODULES_ON))
335 check_for_new_submodule_commits(ref->new_sha1);
6315472e 336 r = s_update_ref(msg, ref, 0);
5914f2d0
JK
337 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
338 r ? '!' : '*',
754395d3 339 TRANSPORT_SUMMARY(what),
5914f2d0
JK
340 REFCOL_WIDTH, remote, pretty_ref,
341 r ? _(" (unable to update local ref)") : "");
6315472e 342 return r;
b888d61c
DB
343 }
344
a20efee9 345 if (in_merge_bases(current, updated)) {
165f3902 346 char quickref[83];
6315472e 347 int r;
165f3902
NP
348 strcpy(quickref, find_unique_abbrev(current->object.sha1, DEFAULT_ABBREV));
349 strcat(quickref, "..");
350 strcat(quickref, find_unique_abbrev(ref->new_sha1, DEFAULT_ABBREV));
88a21979
JL
351 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
352 (recurse_submodules != RECURSE_SUBMODULES_ON))
353 check_for_new_submodule_commits(ref->new_sha1);
a75d7b54 354 r = s_update_ref("fast-forward", ref, 1);
5914f2d0
JK
355 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
356 r ? '!' : ' ',
357 TRANSPORT_SUMMARY_WIDTH, quickref,
358 REFCOL_WIDTH, remote, pretty_ref,
359 r ? _(" (unable to update local ref)") : "");
6315472e 360 return r;
165f3902
NP
361 } else if (force || ref->force) {
362 char quickref[84];
6315472e 363 int r;
165f3902
NP
364 strcpy(quickref, find_unique_abbrev(current->object.sha1, DEFAULT_ABBREV));
365 strcat(quickref, "...");
366 strcat(quickref, find_unique_abbrev(ref->new_sha1, DEFAULT_ABBREV));
88a21979
JL
367 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
368 (recurse_submodules != RECURSE_SUBMODULES_ON))
369 check_for_new_submodule_commits(ref->new_sha1);
6315472e 370 r = s_update_ref("forced-update", ref, 1);
5914f2d0
JK
371 strbuf_addf(display, "%c %-*s %-*s -> %s (%s)",
372 r ? '!' : '+',
373 TRANSPORT_SUMMARY_WIDTH, quickref,
374 REFCOL_WIDTH, remote, pretty_ref,
375 r ? _("unable to update local ref") : _("forced update"));
6315472e 376 return r;
165f3902 377 } else {
5914f2d0 378 strbuf_addf(display, "! %-*s %-*s -> %s %s",
754395d3 379 TRANSPORT_SUMMARY(_("[rejected]")),
5914f2d0
JK
380 REFCOL_WIDTH, remote, pretty_ref,
381 _("(non-fast-forward)"));
b888d61c
DB
382 return 1;
383 }
b888d61c
DB
384}
385
f0e278b1 386static int iterate_ref_map(void *cb_data, unsigned char sha1[20])
6b67e0dc 387{
f0e278b1
JH
388 struct ref **rm = cb_data;
389 struct ref *ref = *rm;
6b67e0dc 390
f0e278b1
JH
391 if (!ref)
392 return -1; /* end of the list */
393 *rm = ref->next;
394 hashcpy(sha1, ref->old_sha1);
395 return 0;
6b67e0dc
JH
396}
397
47abd85b 398static int store_updated_refs(const char *raw_url, const char *remote_name,
f3cb169b 399 struct ref *ref_map)
b888d61c
DB
400{
401 FILE *fp;
402 struct commit *commit;
5914f2d0
JK
403 int url_len, i, shown_url = 0, rc = 0;
404 struct strbuf note = STRBUF_INIT;
b888d61c
DB
405 const char *what, *kind;
406 struct ref *rm;
28a15401 407 char *url, *filename = dry_run ? "/dev/null" : git_path("FETCH_HEAD");
900f2814 408 int want_status;
b888d61c 409
d6617c7c
AGR
410 fp = fopen(filename, "a");
411 if (!fp)
bd4a51fc 412 return error(_("cannot open %s: %s\n"), filename, strerror(errno));
47abd85b 413
fb0cc87e
DB
414 if (raw_url)
415 url = transport_anonymize_url(raw_url);
416 else
417 url = xstrdup("foreign");
6b67e0dc 418
f0e278b1 419 rm = ref_map;
3f7d11c4 420 if (check_everything_connected(iterate_ref_map, 0, &rm)) {
9516a598
TRC
421 rc = error(_("%s did not send all necessary objects\n"), url);
422 goto abort;
423 }
6b67e0dc 424
96890f4c 425 /*
900f2814
JK
426 * We do a pass for each fetch_head_status type in their enum order, so
427 * merged entries are written before not-for-merge. That lets readers
428 * use FETCH_HEAD as a refname to refer to the ref to be merged.
96890f4c 429 */
900f2814
JK
430 for (want_status = FETCH_HEAD_MERGE;
431 want_status <= FETCH_HEAD_IGNORE;
432 want_status++) {
96890f4c
JH
433 for (rm = ref_map; rm; rm = rm->next) {
434 struct ref *ref = NULL;
900f2814 435 const char *merge_status_marker = "";
96890f4c
JH
436
437 commit = lookup_commit_reference_gently(rm->old_sha1, 1);
438 if (!commit)
900f2814 439 rm->fetch_head_status = FETCH_HEAD_NOT_FOR_MERGE;
96890f4c 440
900f2814 441 if (rm->fetch_head_status != want_status)
96890f4c
JH
442 continue;
443
444 if (rm->peer_ref) {
445 ref = xcalloc(1, sizeof(*ref) + strlen(rm->peer_ref->name) + 1);
446 strcpy(ref->name, rm->peer_ref->name);
447 hashcpy(ref->old_sha1, rm->peer_ref->old_sha1);
448 hashcpy(ref->new_sha1, rm->old_sha1);
449 ref->force = rm->peer_ref->force;
450 }
b888d61c 451
b888d61c 452
96890f4c
JH
453 if (!strcmp(rm->name, "HEAD")) {
454 kind = "";
455 what = "";
456 }
457 else if (!prefixcmp(rm->name, "refs/heads/")) {
458 kind = "branch";
459 what = rm->name + 11;
460 }
461 else if (!prefixcmp(rm->name, "refs/tags/")) {
462 kind = "tag";
463 what = rm->name + 10;
464 }
465 else if (!prefixcmp(rm->name, "refs/remotes/")) {
466 kind = "remote-tracking branch";
467 what = rm->name + 13;
468 }
469 else {
470 kind = "";
471 what = rm->name;
472 }
b888d61c 473
96890f4c
JH
474 url_len = strlen(url);
475 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
476 ;
477 url_len = i + 1;
478 if (4 < i && !strncmp(".git", url + i - 3, 4))
479 url_len = i - 3;
480
481 strbuf_reset(&note);
482 if (*what) {
483 if (*kind)
484 strbuf_addf(&note, "%s ", kind);
485 strbuf_addf(&note, "'%s' of ", what);
486 }
900f2814
JK
487 switch (rm->fetch_head_status) {
488 case FETCH_HEAD_NOT_FOR_MERGE:
489 merge_status_marker = "not-for-merge";
490 /* fall-through */
491 case FETCH_HEAD_MERGE:
492 fprintf(fp, "%s\t%s\t%s",
493 sha1_to_hex(rm->old_sha1),
494 merge_status_marker,
495 note.buf);
496 for (i = 0; i < url_len; ++i)
497 if ('\n' == url[i])
498 fputs("\\n", fp);
499 else
500 fputc(url[i], fp);
501 fputc('\n', fp);
502 break;
503 default:
504 /* do not write anything to FETCH_HEAD */
505 break;
506 }
96890f4c
JH
507
508 strbuf_reset(&note);
509 if (ref) {
6da618d5 510 rc |= update_local_ref(ref, what, rm, &note);
96890f4c
JH
511 free(ref);
512 } else
513 strbuf_addf(&note, "* %-*s %-*s -> FETCH_HEAD",
514 TRANSPORT_SUMMARY_WIDTH,
515 *kind ? kind : "branch",
516 REFCOL_WIDTH,
517 *what ? what : "HEAD");
518 if (note.len) {
519 if (verbosity >= 0 && !shown_url) {
520 fprintf(stderr, _("From %.*s\n"),
521 url_len, url);
522 shown_url = 1;
523 }
524 if (verbosity >= 0)
525 fprintf(stderr, " %s\n", note.buf);
165f3902
NP
526 }
527 }
b888d61c 528 }
9516a598 529
fa250759 530 if (rc & STORE_REF_ERROR_DF_CONFLICT)
bd4a51fc 531 error(_("some local refs could not be updated; try running\n"
f3cb169b 532 " 'git remote prune %s' to remove any old, conflicting "
bd4a51fc 533 "branches"), remote_name);
9516a598
TRC
534
535 abort:
5914f2d0 536 strbuf_release(&note);
9516a598
TRC
537 free(url);
538 fclose(fp);
efb98b44 539 return rc;
b888d61c
DB
540}
541
4191c356
SP
542/*
543 * We would want to bypass the object transfer altogether if
d9eb0205 544 * everything we are going to fetch already exists and is connected
4191c356 545 * locally.
4191c356
SP
546 */
547static int quickfetch(struct ref *ref_map)
548{
f0e278b1
JH
549 struct ref *rm = ref_map;
550
4191c356
SP
551 /*
552 * If we are deepening a shallow clone we already have these
553 * objects reachable. Running rev-list here will return with
554 * a good (0) exit status and we'll bypass the fetch that we
555 * really need to perform. Claiming failure now will ensure
556 * we perform the network exchange to deepen our history.
557 */
558 if (depth)
559 return -1;
f0e278b1 560 return check_everything_connected(iterate_ref_map, 1, &rm);
4191c356
SP
561}
562
b888d61c
DB
563static int fetch_refs(struct transport *transport, struct ref *ref_map)
564{
4191c356
SP
565 int ret = quickfetch(ref_map);
566 if (ret)
567 ret = transport_fetch_refs(transport, ref_map);
b888d61c 568 if (!ret)
f3cb169b
JK
569 ret |= store_updated_refs(transport->url,
570 transport->remote->name,
571 ref_map);
1788c39c 572 transport_unlock_pack(transport);
b888d61c
DB
573 return ret;
574}
575
ed43de6e 576static int prune_refs(struct refspec *refs, int ref_count, struct ref *ref_map)
f360d844
JS
577{
578 int result = 0;
ed43de6e 579 struct ref *ref, *stale_refs = get_stale_heads(refs, ref_count, ref_map);
f360d844 580 const char *dangling_msg = dry_run
18986d53
NTND
581 ? _(" (%s will become dangling)")
582 : _(" (%s has become dangling)");
f360d844
JS
583
584 for (ref = stale_refs; ref; ref = ref->next) {
585 if (!dry_run)
586 result |= delete_ref(ref->name, NULL, 0);
587 if (verbosity >= 0) {
588 fprintf(stderr, " x %-*s %-*s -> %s\n",
754395d3 589 TRANSPORT_SUMMARY(_("[deleted]")),
502681cd 590 REFCOL_WIDTH, _("(none)"), prettify_refname(ref->name));
f360d844
JS
591 warn_dangling_symref(stderr, dangling_msg, ref->name);
592 }
593 }
594 free_refs(stale_refs);
595 return result;
596}
597
b888d61c
DB
598static int add_existing(const char *refname, const unsigned char *sha1,
599 int flag, void *cbdata)
600{
c455c87c 601 struct string_list *list = (struct string_list *)cbdata;
78a395d3 602 struct string_list_item *item = string_list_insert(list, refname);
b1a01e1c 603 item->util = (void *)sha1;
b888d61c
DB
604 return 0;
605}
606
cf7f929a
SP
607static int will_fetch(struct ref **head, const unsigned char *sha1)
608{
609 struct ref *rm = *head;
610 while (rm) {
611 if (!hashcmp(rm->old_sha1, sha1))
612 return 1;
613 rm = rm->next;
614 }
615 return 0;
616}
617
c50b2b47
SP
618static void find_non_local_tags(struct transport *transport,
619 struct ref **head,
620 struct ref ***tail)
b888d61c 621{
183113a5
TF
622 struct string_list existing_refs = STRING_LIST_INIT_NODUP;
623 struct string_list remote_refs = STRING_LIST_INIT_NODUP;
4577370e 624 const struct ref *ref;
e984c54a 625 struct string_list_item *item = NULL;
b888d61c
DB
626
627 for_each_ref(add_existing, &existing_refs);
628 for (ref = transport_get_remote_refs(transport); ref; ref = ref->next) {
97ba642b 629 if (prefixcmp(ref->name, "refs/tags/"))
b888d61c
DB
630 continue;
631
e984c54a
JP
632 /*
633 * The peeled ref always follows the matching base
634 * ref, so if we see a peeled ref that we don't want
635 * to fetch then we can mark the ref entry in the list
636 * as one to ignore by setting util to NULL.
637 */
aac1d7b8 638 if (!suffixcmp(ref->name, "^{}")) {
e984c54a
JP
639 if (item && !has_sha1_file(ref->old_sha1) &&
640 !will_fetch(head, ref->old_sha1) &&
641 !has_sha1_file(item->util) &&
642 !will_fetch(head, item->util))
643 item->util = NULL;
644 item = NULL;
645 continue;
b888d61c
DB
646 }
647
e984c54a
JP
648 /*
649 * If item is non-NULL here, then we previously saw a
650 * ref not followed by a peeled reference, so we need
651 * to check if it is a lightweight tag that we want to
652 * fetch.
653 */
654 if (item && !has_sha1_file(item->util) &&
655 !will_fetch(head, item->util))
656 item->util = NULL;
b888d61c 657
e984c54a 658 item = NULL;
b888d61c 659
e984c54a
JP
660 /* skip duplicates and refs that we already have */
661 if (string_list_has_string(&remote_refs, ref->name) ||
662 string_list_has_string(&existing_refs, ref->name))
663 continue;
664
78a395d3 665 item = string_list_insert(&remote_refs, ref->name);
e984c54a 666 item->util = (void *)ref->old_sha1;
b888d61c 667 }
c455c87c 668 string_list_clear(&existing_refs, 0);
e984c54a
JP
669
670 /*
671 * We may have a final lightweight tag that needs to be
672 * checked to see if it needs fetching.
673 */
674 if (item && !has_sha1_file(item->util) &&
675 !will_fetch(head, item->util))
676 item->util = NULL;
677
678 /*
8a57c6e9
AR
679 * For all the tags in the remote_refs string list,
680 * add them to the list of refs to be fetched
e984c54a 681 */
8a57c6e9
AR
682 for_each_string_list_item(item, &remote_refs) {
683 /* Unless we have already decided to ignore this item... */
684 if (item->util)
685 {
686 struct ref *rm = alloc_ref(item->string);
687 rm->peer_ref = alloc_ref(item->string);
688 hashcpy(rm->old_sha1, item->util);
689 **tail = rm;
690 *tail = &rm->next;
691 }
692 }
e984c54a
JP
693
694 string_list_clear(&remote_refs, 0);
b888d61c
DB
695}
696
8ee5d731
JS
697static void check_not_current_branch(struct ref *ref_map)
698{
699 struct branch *current_branch = branch_get(NULL);
700
701 if (is_bare_repository() || !current_branch)
702 return;
703
704 for (; ref_map; ref_map = ref_map->next)
705 if (ref_map->peer_ref && !strcmp(current_branch->refname,
706 ref_map->peer_ref->name))
bd4a51fc
ÆAB
707 die(_("Refusing to fetch into current branch %s "
708 "of non-bare repository"), current_branch->refname);
8ee5d731
JS
709}
710
e6cc5104
JH
711static int truncate_fetch_head(void)
712{
713 char *filename = git_path("FETCH_HEAD");
714 FILE *fp = fopen(filename, "w");
715
716 if (!fp)
bd4a51fc 717 return error(_("cannot open %s: %s\n"), filename, strerror(errno));
e6cc5104
JH
718 fclose(fp);
719 return 0;
720}
721
b888d61c
DB
722static int do_fetch(struct transport *transport,
723 struct refspec *refs, int ref_count)
724{
183113a5 725 struct string_list existing_refs = STRING_LIST_INIT_NODUP;
b1a01e1c 726 struct string_list_item *peer_item = NULL;
7f98428d 727 struct ref *ref_map;
b888d61c
DB
728 struct ref *rm;
729 int autotags = (transport->remote->fetch_tags == 1);
b1a01e1c
JP
730
731 for_each_ref(add_existing, &existing_refs);
732
ed368546
DJ
733 if (tags == TAGS_DEFAULT) {
734 if (transport->remote->fetch_tags == 2)
735 tags = TAGS_SET;
736 if (transport->remote->fetch_tags == -1)
737 tags = TAGS_UNSET;
738 }
b888d61c 739
824d5776 740 if (!transport->get_refs_list || !transport->fetch)
bd4a51fc 741 die(_("Don't know how to fetch from %s"), transport->url);
b888d61c
DB
742
743 /* if not appending, truncate FETCH_HEAD */
28a15401 744 if (!append && !dry_run) {
e6cc5104
JH
745 int errcode = truncate_fetch_head();
746 if (errcode)
747 return errcode;
d6617c7c 748 }
b888d61c
DB
749
750 ref_map = get_ref_map(transport, refs, ref_count, tags, &autotags);
8ee5d731
JS
751 if (!update_head_ok)
752 check_not_current_branch(ref_map);
b888d61c
DB
753
754 for (rm = ref_map; rm; rm = rm->next) {
b1a01e1c 755 if (rm->peer_ref) {
e8c8b713
JP
756 peer_item = string_list_lookup(&existing_refs,
757 rm->peer_ref->name);
b1a01e1c
JP
758 if (peer_item)
759 hashcpy(rm->peer_ref->old_sha1,
760 peer_item->util);
761 }
b888d61c
DB
762 }
763
41fa7d2e
SP
764 if (tags == TAGS_DEFAULT && autotags)
765 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
b888d61c
DB
766 if (fetch_refs(transport, ref_map)) {
767 free_refs(ref_map);
768 return 1;
769 }
ed43de6e 770 if (prune) {
e8c1e6c7
CMN
771 /* If --tags was specified, pretend the user gave us the canonical tags refspec */
772 if (tags == TAGS_SET) {
773 const char *tags_str = "refs/tags/*:refs/tags/*";
774 struct refspec *tags_refspec, *refspec;
775
776 /* Copy the refspec and add the tags to it */
777 refspec = xcalloc(ref_count + 1, sizeof(struct refspec));
778 tags_refspec = parse_fetch_refspec(1, &tags_str);
779 memcpy(refspec, refs, ref_count * sizeof(struct refspec));
780 memcpy(&refspec[ref_count], tags_refspec, sizeof(struct refspec));
781 ref_count++;
782
783 prune_refs(refspec, ref_count, ref_map);
784
785 ref_count--;
786 /* The rest of the strings belong to fetch_one */
787 free_refspec(1, tags_refspec);
788 free(refspec);
789 } else if (ref_count) {
ed43de6e 790 prune_refs(refs, ref_count, ref_map);
e8c1e6c7 791 } else {
ed43de6e 792 prune_refs(transport->remote->fetch, transport->remote->fetch_refspec_nr, ref_map);
e8c1e6c7 793 }
ed43de6e 794 }
7f98428d 795 free_refs(ref_map);
b888d61c
DB
796
797 /* if neither --no-tags nor --tags was specified, do automated tag
798 * following ... */
83201998 799 if (tags == TAGS_DEFAULT && autotags) {
c50b2b47
SP
800 struct ref **tail = &ref_map;
801 ref_map = NULL;
802 find_non_local_tags(transport, &ref_map, &tail);
b888d61c 803 if (ref_map) {
41fa7d2e 804 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
b888d61c
DB
805 transport_set_option(transport, TRANS_OPT_DEPTH, "0");
806 fetch_refs(transport, ref_map);
807 }
808 free_refs(ref_map);
809 }
810
b888d61c
DB
811 return 0;
812}
813
ab865e6e
SP
814static void set_option(const char *name, const char *value)
815{
816 int r = transport_set_option(transport, name, value);
817 if (r < 0)
bd4a51fc 818 die(_("Option \"%s\" value \"%s\" is not valid for %s"),
ab865e6e
SP
819 name, value, transport->url);
820 if (r > 0)
bd4a51fc 821 warning(_("Option \"%s\" is ignored for %s\n"),
ab865e6e
SP
822 name, transport->url);
823}
824
9c4a036b
BG
825static int get_one_remote_for_fetch(struct remote *remote, void *priv)
826{
827 struct string_list *list = priv;
7cc91a2f 828 if (!remote->skip_default_update)
1d2f80fa 829 string_list_append(list, remote->name);
9c4a036b
BG
830 return 0;
831}
832
833struct remote_group_data {
834 const char *name;
835 struct string_list *list;
836};
837
838static int get_remote_group(const char *key, const char *value, void *priv)
839{
840 struct remote_group_data *g = priv;
841
842 if (!prefixcmp(key, "remotes.") &&
843 !strcmp(key + 8, g->name)) {
844 /* split list by white space */
845 int space = strcspn(value, " \t\n");
846 while (*value) {
847 if (space > 1) {
1d2f80fa
JP
848 string_list_append(g->list,
849 xstrndup(value, space));
9c4a036b
BG
850 }
851 value += space + (value[space] != '\0');
852 space = strcspn(value, " \t\n");
853 }
854 }
855
856 return 0;
857}
858
859static int add_remote_or_group(const char *name, struct string_list *list)
860{
861 int prev_nr = list->nr;
66dbfd55
GV
862 struct remote_group_data g;
863 g.name = name; g.list = list;
9c4a036b
BG
864
865 git_config(get_remote_group, &g);
866 if (list->nr == prev_nr) {
867 struct remote *remote;
868 if (!remote_is_configured(name))
869 return 0;
870 remote = remote_get(name);
1d2f80fa 871 string_list_append(list, remote->name);
9c4a036b
BG
872 }
873 return 1;
874}
875
85556d4e 876static void add_options_to_argv(struct argv_array *argv)
9c4a036b 877{
28a15401 878 if (dry_run)
85556d4e 879 argv_array_push(argv, "--dry-run");
f360d844 880 if (prune)
85556d4e 881 argv_array_push(argv, "--prune");
bba5322a 882 if (update_head_ok)
85556d4e 883 argv_array_push(argv, "--update-head-ok");
bba5322a 884 if (force)
85556d4e 885 argv_array_push(argv, "--force");
bba5322a 886 if (keep)
85556d4e 887 argv_array_push(argv, "--keep");
be254a0e 888 if (recurse_submodules == RECURSE_SUBMODULES_ON)
85556d4e 889 argv_array_push(argv, "--recurse-submodules");
8f0700dd 890 else if (recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND)
85556d4e 891 argv_array_push(argv, "--recurse-submodules=on-demand");
85566460
DJ
892 if (tags == TAGS_SET)
893 argv_array_push(argv, "--tags");
894 else if (tags == TAGS_UNSET)
895 argv_array_push(argv, "--no-tags");
9c4a036b 896 if (verbosity >= 2)
85556d4e 897 argv_array_push(argv, "-v");
9c4a036b 898 if (verbosity >= 1)
85556d4e 899 argv_array_push(argv, "-v");
9c4a036b 900 else if (verbosity < 0)
85556d4e 901 argv_array_push(argv, "-q");
7dce19d3
JL
902
903}
904
905static int fetch_multiple(struct string_list *list)
906{
907 int i, result = 0;
85556d4e 908 struct argv_array argv = ARGV_ARRAY_INIT;
9c4a036b 909
e6cc5104
JH
910 if (!append && !dry_run) {
911 int errcode = truncate_fetch_head();
912 if (errcode)
913 return errcode;
914 }
915
85556d4e
JK
916 argv_array_pushl(&argv, "fetch", "--append", NULL);
917 add_options_to_argv(&argv);
918
9c4a036b
BG
919 for (i = 0; i < list->nr; i++) {
920 const char *name = list->items[i].string;
85556d4e 921 argv_array_push(&argv, name);
9c4a036b 922 if (verbosity >= 0)
bd4a51fc 923 printf(_("Fetching %s\n"), name);
85556d4e 924 if (run_command_v_opt(argv.argv, RUN_GIT_CMD)) {
bd4a51fc 925 error(_("Could not fetch %s"), name);
9c4a036b
BG
926 result = 1;
927 }
85556d4e 928 argv_array_pop(&argv);
9c4a036b
BG
929 }
930
85556d4e 931 argv_array_clear(&argv);
9c4a036b
BG
932 return result;
933}
934
935static int fetch_one(struct remote *remote, int argc, const char **argv)
b888d61c 936{
2d324efa 937 int i;
b888d61c 938 static const char **refs = NULL;
d8ead159 939 struct refspec *refspec;
b888d61c 940 int ref_nr = 0;
7b7f39ea 941 int exit_code;
b888d61c 942
fa685bdf 943 if (!remote)
bd4a51fc
ÆAB
944 die(_("No remote repository specified. Please, specify either a URL or a\n"
945 "remote name from which new revisions should be fetched."));
fa685bdf 946
fb0cc87e 947 transport = transport_get(remote, NULL);
9839018e 948 transport_set_verbosity(transport, verbosity, progress);
b888d61c 949 if (upload_pack)
ab865e6e 950 set_option(TRANS_OPT_UPLOADPACK, upload_pack);
b888d61c 951 if (keep)
ab865e6e
SP
952 set_option(TRANS_OPT_KEEP, "yes");
953 if (depth)
954 set_option(TRANS_OPT_DEPTH, depth);
b888d61c 955
9c4a036b 956 if (argc > 0) {
b888d61c 957 int j = 0;
83201998 958 refs = xcalloc(argc + 1, sizeof(const char *));
9c4a036b 959 for (i = 0; i < argc; i++) {
b888d61c
DB
960 if (!strcmp(argv[i], "tag")) {
961 char *ref;
962 i++;
f53423b0 963 if (i >= argc)
bd4a51fc 964 die(_("You need to specify a tag name."));
b888d61c
DB
965 ref = xmalloc(strlen(argv[i]) * 2 + 22);
966 strcpy(ref, "refs/tags/");
967 strcat(ref, argv[i]);
968 strcat(ref, ":refs/tags/");
969 strcat(ref, argv[i]);
970 refs[j++] = ref;
971 } else
972 refs[j++] = argv[i];
b888d61c
DB
973 }
974 refs[j] = NULL;
975 ref_nr = j;
b888d61c
DB
976 }
977
57b235a4 978 sigchain_push_common(unlock_pack_on_signal);
e4022ed2 979 atexit(unlock_pack);
d8ead159
JM
980 refspec = parse_fetch_refspec(ref_nr, refs);
981 exit_code = do_fetch(transport, refspec, ref_nr);
5caf1973 982 free_refspec(ref_nr, refspec);
7b7f39ea
AR
983 transport_disconnect(transport);
984 transport = NULL;
985 return exit_code;
b888d61c 986}
9c4a036b
BG
987
988int cmd_fetch(int argc, const char **argv, const char *prefix)
989{
990 int i;
183113a5 991 struct string_list list = STRING_LIST_INIT_NODUP;
9c4a036b
BG
992 struct remote *remote;
993 int result = 0;
131b8fcb
JK
994 static const char *argv_gc_auto[] = {
995 "gc", "--auto", NULL,
996 };
9c4a036b 997
bbc30f99
JK
998 packet_trace_identity("fetch");
999
9c4a036b
BG
1000 /* Record the command line for the reflog */
1001 strbuf_addstr(&default_rla, "fetch");
1002 for (i = 1; i < argc; i++)
1003 strbuf_addf(&default_rla, " %s", argv[i]);
1004
1005 argc = parse_options(argc, argv, prefix,
1006 builtin_fetch_options, builtin_fetch_usage, 0);
1007
4dcb167f
NTND
1008 if (unshallow) {
1009 if (depth)
1010 die(_("--depth and --unshallow cannot be used together"));
1011 else if (!is_repository_shallow())
1012 die(_("--unshallow on a complete repository does not make sense"));
1013 else {
1014 static char inf_depth[12];
1015 sprintf(inf_depth, "%d", INFINITE_DEPTH);
1016 depth = inf_depth;
1017 }
1018 }
1019
18322bad
JL
1020 if (recurse_submodules != RECURSE_SUBMODULES_OFF) {
1021 if (recurse_submodules_default) {
1022 int arg = parse_fetch_recurse_submodules_arg("--recurse-submodules-default", recurse_submodules_default);
1023 set_config_fetch_recurse_submodules(arg);
1024 }
1025 gitmodules_config();
1026 git_config(submodule_config, NULL);
1027 }
1028
9c4a036b
BG
1029 if (all) {
1030 if (argc == 1)
bd4a51fc 1031 die(_("fetch --all does not take a repository argument"));
9c4a036b 1032 else if (argc > 1)
bd4a51fc 1033 die(_("fetch --all does not make sense with refspecs"));
9c4a036b
BG
1034 (void) for_each_remote(get_one_remote_for_fetch, &list);
1035 result = fetch_multiple(&list);
1036 } else if (argc == 0) {
1037 /* No arguments -- use default remote */
1038 remote = remote_get(NULL);
1039 result = fetch_one(remote, argc, argv);
16679e37
BG
1040 } else if (multiple) {
1041 /* All arguments are assumed to be remotes or groups */
1042 for (i = 0; i < argc; i++)
1043 if (!add_remote_or_group(argv[i], &list))
bd4a51fc 1044 die(_("No such remote or remote group: %s"), argv[i]);
16679e37 1045 result = fetch_multiple(&list);
9c4a036b
BG
1046 } else {
1047 /* Single remote or group */
1048 (void) add_remote_or_group(argv[0], &list);
1049 if (list.nr > 1) {
1050 /* More than one remote */
1051 if (argc > 1)
bd4a51fc 1052 die(_("Fetching a group and specifying refspecs does not make sense"));
9c4a036b
BG
1053 result = fetch_multiple(&list);
1054 } else {
1055 /* Zero or one remotes */
1056 remote = remote_get(argv[0]);
1057 result = fetch_one(remote, argc-1, argv+1);
1058 }
1059 }
1060
be254a0e 1061 if (!result && (recurse_submodules != RECURSE_SUBMODULES_OFF)) {
85556d4e
JK
1062 struct argv_array options = ARGV_ARRAY_INIT;
1063
1064 add_options_to_argv(&options);
50d89ad6 1065 result = fetch_populated_submodules(&options,
7dce19d3 1066 submodule_prefix,
8f0700dd 1067 recurse_submodules,
7dce19d3 1068 verbosity < 0);
85556d4e 1069 argv_array_clear(&options);
7dce19d3
JL
1070 }
1071
9c4a036b
BG
1072 /* All names were strdup()ed or strndup()ed */
1073 list.strdup_strings = 1;
1074 string_list_clear(&list, 0);
1075
131b8fcb
JK
1076 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
1077
9c4a036b
BG
1078 return result;
1079}