Merge branch 'jc/transport-do-not-use-connect-twice-in-fetch'
[git.git] / builtin / fetch.c
blob9e654efa3bb725edd91f6eb7059b263668e622bc
1 /*
2 * "git fetch"
3 */
4 #include "cache.h"
5 #include "refs.h"
6 #include "commit.h"
7 #include "builtin.h"
8 #include "string-list.h"
9 #include "remote.h"
10 #include "transport.h"
11 #include "run-command.h"
12 #include "parse-options.h"
13 #include "sigchain.h"
14 #include "transport.h"
15 #include "submodule.h"
16 #include "connected.h"
17 #include "argv-array.h"
19 static const char * const builtin_fetch_usage[] = {
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>]"),
24 NULL
27 enum {
28 TAGS_UNSET = 0,
29 TAGS_DEFAULT = 1,
30 TAGS_SET = 2
33 static int fetch_prune_config = -1; /* unspecified */
34 static int prune = -1; /* unspecified */
35 #define PRUNE_BY_DEFAULT 0 /* do we prune by default? */
37 static int all, append, dry_run, force, keep, multiple, update_head_ok, verbosity;
38 static int progress = -1, recurse_submodules = RECURSE_SUBMODULES_DEFAULT;
39 static int tags = TAGS_DEFAULT, unshallow;
40 static const char *depth;
41 static const char *upload_pack;
42 static struct strbuf default_rla = STRBUF_INIT;
43 static struct transport *gtransport;
44 static struct transport *gsecondary;
45 static const char *submodule_prefix = "";
46 static const char *recurse_submodules_default;
48 static int option_parse_recurse_submodules(const struct option *opt,
49 const char *arg, int unset)
51 if (unset) {
52 recurse_submodules = RECURSE_SUBMODULES_OFF;
53 } else {
54 if (arg)
55 recurse_submodules = parse_fetch_recurse_submodules_arg(opt->long_name, arg);
56 else
57 recurse_submodules = RECURSE_SUBMODULES_ON;
59 return 0;
62 static int git_fetch_config(const char *k, const char *v, void *cb)
64 if (!strcmp(k, "fetch.prune")) {
65 fetch_prune_config = git_config_bool(k, v);
66 return 0;
68 return 0;
71 static struct option builtin_fetch_options[] = {
72 OPT__VERBOSITY(&verbosity),
73 OPT_BOOL(0, "all", &all,
74 N_("fetch from all remotes")),
75 OPT_BOOL('a', "append", &append,
76 N_("append to .git/FETCH_HEAD instead of overwriting")),
77 OPT_STRING(0, "upload-pack", &upload_pack, N_("path"),
78 N_("path to upload pack on remote end")),
79 OPT__FORCE(&force, N_("force overwrite of local branch")),
80 OPT_BOOL('m', "multiple", &multiple,
81 N_("fetch from multiple remotes")),
82 OPT_SET_INT('t', "tags", &tags,
83 N_("fetch all tags and associated objects"), TAGS_SET),
84 OPT_SET_INT('n', NULL, &tags,
85 N_("do not fetch all tags (--no-tags)"), TAGS_UNSET),
86 OPT_BOOL('p', "prune", &prune,
87 N_("prune remote-tracking branches no longer on remote")),
88 { OPTION_CALLBACK, 0, "recurse-submodules", NULL, N_("on-demand"),
89 N_("control recursive fetching of submodules"),
90 PARSE_OPT_OPTARG, option_parse_recurse_submodules },
91 OPT_BOOL(0, "dry-run", &dry_run,
92 N_("dry run")),
93 OPT_BOOL('k', "keep", &keep, N_("keep downloaded pack")),
94 OPT_BOOL('u', "update-head-ok", &update_head_ok,
95 N_("allow updating of HEAD ref")),
96 OPT_BOOL(0, "progress", &progress, N_("force progress reporting")),
97 OPT_STRING(0, "depth", &depth, N_("depth"),
98 N_("deepen history of shallow clone")),
99 { OPTION_SET_INT, 0, "unshallow", &unshallow, NULL,
100 N_("convert to a complete repository"),
101 PARSE_OPT_NONEG | PARSE_OPT_NOARG, NULL, 1 },
102 { OPTION_STRING, 0, "submodule-prefix", &submodule_prefix, N_("dir"),
103 N_("prepend this to submodule path output"), PARSE_OPT_HIDDEN },
104 { OPTION_STRING, 0, "recurse-submodules-default",
105 &recurse_submodules_default, NULL,
106 N_("default mode for recursion"), PARSE_OPT_HIDDEN },
107 OPT_END()
110 static void unlock_pack(void)
112 if (gtransport)
113 transport_unlock_pack(gtransport);
114 if (gsecondary)
115 transport_unlock_pack(gsecondary);
118 static void unlock_pack_on_signal(int signo)
120 unlock_pack();
121 sigchain_pop(signo);
122 raise(signo);
125 static void add_merge_config(struct ref **head,
126 const struct ref *remote_refs,
127 struct branch *branch,
128 struct ref ***tail)
130 int i;
132 for (i = 0; i < branch->merge_nr; i++) {
133 struct ref *rm, **old_tail = *tail;
134 struct refspec refspec;
136 for (rm = *head; rm; rm = rm->next) {
137 if (branch_merge_matches(branch, i, rm->name)) {
138 rm->fetch_head_status = FETCH_HEAD_MERGE;
139 break;
142 if (rm)
143 continue;
146 * Not fetched to a remote-tracking branch? We need to fetch
147 * it anyway to allow this branch's "branch.$name.merge"
148 * to be honored by 'git pull', but we do not have to
149 * fail if branch.$name.merge is misconfigured to point
150 * at a nonexisting branch. If we were indeed called by
151 * 'git pull', it will notice the misconfiguration because
152 * there is no entry in the resulting FETCH_HEAD marked
153 * for merging.
155 memset(&refspec, 0, sizeof(refspec));
156 refspec.src = branch->merge[i]->src;
157 get_fetch_map(remote_refs, &refspec, tail, 1);
158 for (rm = *old_tail; rm; rm = rm->next)
159 rm->fetch_head_status = FETCH_HEAD_MERGE;
163 static void find_non_local_tags(struct transport *transport,
164 struct ref **head,
165 struct ref ***tail);
167 static struct ref *get_ref_map(struct transport *transport,
168 struct refspec *refs, int ref_count, int tags,
169 int *autotags)
171 int i;
172 struct ref *rm;
173 struct ref *ref_map = NULL;
174 struct ref **tail = &ref_map;
176 const struct ref *remote_refs = transport_get_remote_refs(transport);
178 if (ref_count || tags == TAGS_SET) {
179 struct ref **old_tail;
181 for (i = 0; i < ref_count; i++) {
182 get_fetch_map(remote_refs, &refs[i], &tail, 0);
183 if (refs[i].dst && refs[i].dst[0])
184 *autotags = 1;
186 /* Merge everything on the command line, but not --tags */
187 for (rm = ref_map; rm; rm = rm->next)
188 rm->fetch_head_status = FETCH_HEAD_MERGE;
189 if (tags == TAGS_SET)
190 get_fetch_map(remote_refs, tag_refspec, &tail, 0);
193 * For any refs that we happen to be fetching via command-line
194 * arguments, take the opportunity to update their configured
195 * counterparts. However, we do not want to mention these
196 * entries in FETCH_HEAD at all, as they would simply be
197 * duplicates of existing entries.
199 old_tail = tail;
200 for (i = 0; i < transport->remote->fetch_refspec_nr; i++)
201 get_fetch_map(ref_map, &transport->remote->fetch[i],
202 &tail, 1);
203 for (rm = *old_tail; rm; rm = rm->next)
204 rm->fetch_head_status = FETCH_HEAD_IGNORE;
205 } else {
206 /* Use the defaults */
207 struct remote *remote = transport->remote;
208 struct branch *branch = branch_get(NULL);
209 int has_merge = branch_has_merge_config(branch);
210 if (remote &&
211 (remote->fetch_refspec_nr ||
212 /* Note: has_merge implies non-NULL branch->remote_name */
213 (has_merge && !strcmp(branch->remote_name, remote->name)))) {
214 for (i = 0; i < remote->fetch_refspec_nr; i++) {
215 get_fetch_map(remote_refs, &remote->fetch[i], &tail, 0);
216 if (remote->fetch[i].dst &&
217 remote->fetch[i].dst[0])
218 *autotags = 1;
219 if (!i && !has_merge && ref_map &&
220 !remote->fetch[0].pattern)
221 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
224 * if the remote we're fetching from is the same
225 * as given in branch.<name>.remote, we add the
226 * ref given in branch.<name>.merge, too.
228 * Note: has_merge implies non-NULL branch->remote_name
230 if (has_merge &&
231 !strcmp(branch->remote_name, remote->name))
232 add_merge_config(&ref_map, remote_refs, branch, &tail);
233 } else {
234 ref_map = get_remote_ref(remote_refs, "HEAD");
235 if (!ref_map)
236 die(_("Couldn't find remote ref HEAD"));
237 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
238 tail = &ref_map->next;
241 if (tags == TAGS_DEFAULT && *autotags)
242 find_non_local_tags(transport, &ref_map, &tail);
243 ref_remove_duplicates(ref_map);
245 return ref_map;
248 #define STORE_REF_ERROR_OTHER 1
249 #define STORE_REF_ERROR_DF_CONFLICT 2
251 static int s_update_ref(const char *action,
252 struct ref *ref,
253 int check_old)
255 char msg[1024];
256 char *rla = getenv("GIT_REFLOG_ACTION");
257 static struct ref_lock *lock;
259 if (dry_run)
260 return 0;
261 if (!rla)
262 rla = default_rla.buf;
263 snprintf(msg, sizeof(msg), "%s: %s", rla, action);
264 lock = lock_any_ref_for_update(ref->name,
265 check_old ? ref->old_sha1 : NULL, 0);
266 if (!lock)
267 return errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
268 STORE_REF_ERROR_OTHER;
269 if (write_ref_sha1(lock, ref->new_sha1, msg) < 0)
270 return errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
271 STORE_REF_ERROR_OTHER;
272 return 0;
275 #define REFCOL_WIDTH 10
277 static int update_local_ref(struct ref *ref,
278 const char *remote,
279 const struct ref *remote_ref,
280 struct strbuf *display)
282 struct commit *current = NULL, *updated;
283 enum object_type type;
284 struct branch *current_branch = branch_get(NULL);
285 const char *pretty_ref = prettify_refname(ref->name);
287 type = sha1_object_info(ref->new_sha1, NULL);
288 if (type < 0)
289 die(_("object %s not found"), sha1_to_hex(ref->new_sha1));
291 if (!hashcmp(ref->old_sha1, ref->new_sha1)) {
292 if (verbosity > 0)
293 strbuf_addf(display, "= %-*s %-*s -> %s",
294 TRANSPORT_SUMMARY(_("[up to date]")),
295 REFCOL_WIDTH, remote, pretty_ref);
296 return 0;
299 if (current_branch &&
300 !strcmp(ref->name, current_branch->name) &&
301 !(update_head_ok || is_bare_repository()) &&
302 !is_null_sha1(ref->old_sha1)) {
304 * If this is the head, and it's not okay to update
305 * the head, and the old value of the head isn't empty...
307 strbuf_addf(display,
308 _("! %-*s %-*s -> %s (can't fetch in current branch)"),
309 TRANSPORT_SUMMARY(_("[rejected]")),
310 REFCOL_WIDTH, remote, pretty_ref);
311 return 1;
314 if (!is_null_sha1(ref->old_sha1) &&
315 !prefixcmp(ref->name, "refs/tags/")) {
316 int r;
317 r = s_update_ref("updating tag", ref, 0);
318 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
319 r ? '!' : '-',
320 TRANSPORT_SUMMARY(_("[tag update]")),
321 REFCOL_WIDTH, remote, pretty_ref,
322 r ? _(" (unable to update local ref)") : "");
323 return r;
326 current = lookup_commit_reference_gently(ref->old_sha1, 1);
327 updated = lookup_commit_reference_gently(ref->new_sha1, 1);
328 if (!current || !updated) {
329 const char *msg;
330 const char *what;
331 int r;
333 * Nicely describe the new ref we're fetching.
334 * Base this on the remote's ref name, as it's
335 * more likely to follow a standard layout.
337 const char *name = remote_ref ? remote_ref->name : "";
338 if (!prefixcmp(name, "refs/tags/")) {
339 msg = "storing tag";
340 what = _("[new tag]");
341 } else if (!prefixcmp(name, "refs/heads/")) {
342 msg = "storing head";
343 what = _("[new branch]");
344 } else {
345 msg = "storing ref";
346 what = _("[new ref]");
349 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
350 (recurse_submodules != RECURSE_SUBMODULES_ON))
351 check_for_new_submodule_commits(ref->new_sha1);
352 r = s_update_ref(msg, ref, 0);
353 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
354 r ? '!' : '*',
355 TRANSPORT_SUMMARY(what),
356 REFCOL_WIDTH, remote, pretty_ref,
357 r ? _(" (unable to update local ref)") : "");
358 return r;
361 if (in_merge_bases(current, updated)) {
362 char quickref[83];
363 int r;
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));
367 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
368 (recurse_submodules != RECURSE_SUBMODULES_ON))
369 check_for_new_submodule_commits(ref->new_sha1);
370 r = s_update_ref("fast-forward", ref, 1);
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)") : "");
376 return r;
377 } else if (force || ref->force) {
378 char quickref[84];
379 int r;
380 strcpy(quickref, find_unique_abbrev(current->object.sha1, DEFAULT_ABBREV));
381 strcat(quickref, "...");
382 strcat(quickref, find_unique_abbrev(ref->new_sha1, DEFAULT_ABBREV));
383 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
384 (recurse_submodules != RECURSE_SUBMODULES_ON))
385 check_for_new_submodule_commits(ref->new_sha1);
386 r = s_update_ref("forced-update", ref, 1);
387 strbuf_addf(display, "%c %-*s %-*s -> %s (%s)",
388 r ? '!' : '+',
389 TRANSPORT_SUMMARY_WIDTH, quickref,
390 REFCOL_WIDTH, remote, pretty_ref,
391 r ? _("unable to update local ref") : _("forced update"));
392 return r;
393 } else {
394 strbuf_addf(display, "! %-*s %-*s -> %s %s",
395 TRANSPORT_SUMMARY(_("[rejected]")),
396 REFCOL_WIDTH, remote, pretty_ref,
397 _("(non-fast-forward)"));
398 return 1;
402 static int iterate_ref_map(void *cb_data, unsigned char sha1[20])
404 struct ref **rm = cb_data;
405 struct ref *ref = *rm;
407 if (!ref)
408 return -1; /* end of the list */
409 *rm = ref->next;
410 hashcpy(sha1, ref->old_sha1);
411 return 0;
414 static int store_updated_refs(const char *raw_url, const char *remote_name,
415 struct ref *ref_map)
417 FILE *fp;
418 struct commit *commit;
419 int url_len, i, shown_url = 0, rc = 0;
420 struct strbuf note = STRBUF_INIT;
421 const char *what, *kind;
422 struct ref *rm;
423 char *url, *filename = dry_run ? "/dev/null" : git_path("FETCH_HEAD");
424 int want_status;
426 fp = fopen(filename, "a");
427 if (!fp)
428 return error(_("cannot open %s: %s\n"), filename, strerror(errno));
430 if (raw_url)
431 url = transport_anonymize_url(raw_url);
432 else
433 url = xstrdup("foreign");
435 rm = ref_map;
436 if (check_everything_connected(iterate_ref_map, 0, &rm)) {
437 rc = error(_("%s did not send all necessary objects\n"), url);
438 goto abort;
442 * We do a pass for each fetch_head_status type in their enum order, so
443 * merged entries are written before not-for-merge. That lets readers
444 * use FETCH_HEAD as a refname to refer to the ref to be merged.
446 for (want_status = FETCH_HEAD_MERGE;
447 want_status <= FETCH_HEAD_IGNORE;
448 want_status++) {
449 for (rm = ref_map; rm; rm = rm->next) {
450 struct ref *ref = NULL;
451 const char *merge_status_marker = "";
453 commit = lookup_commit_reference_gently(rm->old_sha1, 1);
454 if (!commit)
455 rm->fetch_head_status = FETCH_HEAD_NOT_FOR_MERGE;
457 if (rm->fetch_head_status != want_status)
458 continue;
460 if (rm->peer_ref) {
461 ref = xcalloc(1, sizeof(*ref) + strlen(rm->peer_ref->name) + 1);
462 strcpy(ref->name, rm->peer_ref->name);
463 hashcpy(ref->old_sha1, rm->peer_ref->old_sha1);
464 hashcpy(ref->new_sha1, rm->old_sha1);
465 ref->force = rm->peer_ref->force;
469 if (!strcmp(rm->name, "HEAD")) {
470 kind = "";
471 what = "";
473 else if (!prefixcmp(rm->name, "refs/heads/")) {
474 kind = "branch";
475 what = rm->name + 11;
477 else if (!prefixcmp(rm->name, "refs/tags/")) {
478 kind = "tag";
479 what = rm->name + 10;
481 else if (!prefixcmp(rm->name, "refs/remotes/")) {
482 kind = "remote-tracking branch";
483 what = rm->name + 13;
485 else {
486 kind = "";
487 what = rm->name;
490 url_len = strlen(url);
491 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
493 url_len = i + 1;
494 if (4 < i && !strncmp(".git", url + i - 3, 4))
495 url_len = i - 3;
497 strbuf_reset(&note);
498 if (*what) {
499 if (*kind)
500 strbuf_addf(&note, "%s ", kind);
501 strbuf_addf(&note, "'%s' of ", what);
503 switch (rm->fetch_head_status) {
504 case FETCH_HEAD_NOT_FOR_MERGE:
505 merge_status_marker = "not-for-merge";
506 /* fall-through */
507 case FETCH_HEAD_MERGE:
508 fprintf(fp, "%s\t%s\t%s",
509 sha1_to_hex(rm->old_sha1),
510 merge_status_marker,
511 note.buf);
512 for (i = 0; i < url_len; ++i)
513 if ('\n' == url[i])
514 fputs("\\n", fp);
515 else
516 fputc(url[i], fp);
517 fputc('\n', fp);
518 break;
519 default:
520 /* do not write anything to FETCH_HEAD */
521 break;
524 strbuf_reset(&note);
525 if (ref) {
526 rc |= update_local_ref(ref, what, rm, &note);
527 free(ref);
528 } else
529 strbuf_addf(&note, "* %-*s %-*s -> FETCH_HEAD",
530 TRANSPORT_SUMMARY_WIDTH,
531 *kind ? kind : "branch",
532 REFCOL_WIDTH,
533 *what ? what : "HEAD");
534 if (note.len) {
535 if (verbosity >= 0 && !shown_url) {
536 fprintf(stderr, _("From %.*s\n"),
537 url_len, url);
538 shown_url = 1;
540 if (verbosity >= 0)
541 fprintf(stderr, " %s\n", note.buf);
546 if (rc & STORE_REF_ERROR_DF_CONFLICT)
547 error(_("some local refs could not be updated; try running\n"
548 " 'git remote prune %s' to remove any old, conflicting "
549 "branches"), remote_name);
551 abort:
552 strbuf_release(&note);
553 free(url);
554 fclose(fp);
555 return rc;
559 * We would want to bypass the object transfer altogether if
560 * everything we are going to fetch already exists and is connected
561 * locally.
563 static int quickfetch(struct ref *ref_map)
565 struct ref *rm = ref_map;
568 * If we are deepening a shallow clone we already have these
569 * objects reachable. Running rev-list here will return with
570 * a good (0) exit status and we'll bypass the fetch that we
571 * really need to perform. Claiming failure now will ensure
572 * we perform the network exchange to deepen our history.
574 if (depth)
575 return -1;
576 return check_everything_connected(iterate_ref_map, 1, &rm);
579 static int fetch_refs(struct transport *transport, struct ref *ref_map)
581 int ret = quickfetch(ref_map);
582 if (ret)
583 ret = transport_fetch_refs(transport, ref_map);
584 if (!ret)
585 ret |= store_updated_refs(transport->url,
586 transport->remote->name,
587 ref_map);
588 transport_unlock_pack(transport);
589 return ret;
592 static int prune_refs(struct refspec *refs, int ref_count, struct ref *ref_map)
594 int result = 0;
595 struct ref *ref, *stale_refs = get_stale_heads(refs, ref_count, ref_map);
596 const char *dangling_msg = dry_run
597 ? _(" (%s will become dangling)")
598 : _(" (%s has become dangling)");
600 for (ref = stale_refs; ref; ref = ref->next) {
601 if (!dry_run)
602 result |= delete_ref(ref->name, NULL, 0);
603 if (verbosity >= 0) {
604 fprintf(stderr, " x %-*s %-*s -> %s\n",
605 TRANSPORT_SUMMARY(_("[deleted]")),
606 REFCOL_WIDTH, _("(none)"), prettify_refname(ref->name));
607 warn_dangling_symref(stderr, dangling_msg, ref->name);
610 free_refs(stale_refs);
611 return result;
614 static int add_existing(const char *refname, const unsigned char *sha1,
615 int flag, void *cbdata)
617 struct string_list *list = (struct string_list *)cbdata;
618 struct string_list_item *item = string_list_insert(list, refname);
619 item->util = xmalloc(20);
620 hashcpy(item->util, sha1);
621 return 0;
624 static int will_fetch(struct ref **head, const unsigned char *sha1)
626 struct ref *rm = *head;
627 while (rm) {
628 if (!hashcmp(rm->old_sha1, sha1))
629 return 1;
630 rm = rm->next;
632 return 0;
635 static void find_non_local_tags(struct transport *transport,
636 struct ref **head,
637 struct ref ***tail)
639 struct string_list existing_refs = STRING_LIST_INIT_DUP;
640 struct string_list remote_refs = STRING_LIST_INIT_NODUP;
641 const struct ref *ref;
642 struct string_list_item *item = NULL;
644 for_each_ref(add_existing, &existing_refs);
645 for (ref = transport_get_remote_refs(transport); ref; ref = ref->next) {
646 if (prefixcmp(ref->name, "refs/tags/"))
647 continue;
650 * The peeled ref always follows the matching base
651 * ref, so if we see a peeled ref that we don't want
652 * to fetch then we can mark the ref entry in the list
653 * as one to ignore by setting util to NULL.
655 if (!suffixcmp(ref->name, "^{}")) {
656 if (item && !has_sha1_file(ref->old_sha1) &&
657 !will_fetch(head, ref->old_sha1) &&
658 !has_sha1_file(item->util) &&
659 !will_fetch(head, item->util))
660 item->util = NULL;
661 item = NULL;
662 continue;
666 * If item is non-NULL here, then we previously saw a
667 * ref not followed by a peeled reference, so we need
668 * to check if it is a lightweight tag that we want to
669 * fetch.
671 if (item && !has_sha1_file(item->util) &&
672 !will_fetch(head, item->util))
673 item->util = NULL;
675 item = NULL;
677 /* skip duplicates and refs that we already have */
678 if (string_list_has_string(&remote_refs, ref->name) ||
679 string_list_has_string(&existing_refs, ref->name))
680 continue;
682 item = string_list_insert(&remote_refs, ref->name);
683 item->util = (void *)ref->old_sha1;
685 string_list_clear(&existing_refs, 1);
688 * We may have a final lightweight tag that needs to be
689 * checked to see if it needs fetching.
691 if (item && !has_sha1_file(item->util) &&
692 !will_fetch(head, item->util))
693 item->util = NULL;
696 * For all the tags in the remote_refs string list,
697 * add them to the list of refs to be fetched
699 for_each_string_list_item(item, &remote_refs) {
700 /* Unless we have already decided to ignore this item... */
701 if (item->util)
703 struct ref *rm = alloc_ref(item->string);
704 rm->peer_ref = alloc_ref(item->string);
705 hashcpy(rm->old_sha1, item->util);
706 **tail = rm;
707 *tail = &rm->next;
711 string_list_clear(&remote_refs, 0);
714 static void check_not_current_branch(struct ref *ref_map)
716 struct branch *current_branch = branch_get(NULL);
718 if (is_bare_repository() || !current_branch)
719 return;
721 for (; ref_map; ref_map = ref_map->next)
722 if (ref_map->peer_ref && !strcmp(current_branch->refname,
723 ref_map->peer_ref->name))
724 die(_("Refusing to fetch into current branch %s "
725 "of non-bare repository"), current_branch->refname);
728 static int truncate_fetch_head(void)
730 char *filename = git_path("FETCH_HEAD");
731 FILE *fp = fopen(filename, "w");
733 if (!fp)
734 return error(_("cannot open %s: %s\n"), filename, strerror(errno));
735 fclose(fp);
736 return 0;
739 static void set_option(struct transport *transport, const char *name, const char *value)
741 int r = transport_set_option(transport, name, value);
742 if (r < 0)
743 die(_("Option \"%s\" value \"%s\" is not valid for %s"),
744 name, value, transport->url);
745 if (r > 0)
746 warning(_("Option \"%s\" is ignored for %s\n"),
747 name, transport->url);
750 static struct transport *prepare_transport(struct remote *remote)
752 struct transport *transport;
753 transport = transport_get(remote, NULL);
754 transport_set_verbosity(transport, verbosity, progress);
755 if (upload_pack)
756 set_option(transport, TRANS_OPT_UPLOADPACK, upload_pack);
757 if (keep)
758 set_option(transport, TRANS_OPT_KEEP, "yes");
759 if (depth)
760 set_option(transport, TRANS_OPT_DEPTH, depth);
761 return transport;
764 static void backfill_tags(struct transport *transport, struct ref *ref_map)
766 if (transport->cannot_reuse) {
767 gsecondary = prepare_transport(transport->remote);
768 transport = gsecondary;
771 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
772 transport_set_option(transport, TRANS_OPT_DEPTH, "0");
773 fetch_refs(transport, ref_map);
775 if (gsecondary) {
776 transport_disconnect(gsecondary);
777 gsecondary = NULL;
781 static int do_fetch(struct transport *transport,
782 struct refspec *refs, int ref_count)
784 struct string_list existing_refs = STRING_LIST_INIT_DUP;
785 struct ref *ref_map;
786 struct ref *rm;
787 int autotags = (transport->remote->fetch_tags == 1);
788 int retcode = 0;
790 for_each_ref(add_existing, &existing_refs);
792 if (tags == TAGS_DEFAULT) {
793 if (transport->remote->fetch_tags == 2)
794 tags = TAGS_SET;
795 if (transport->remote->fetch_tags == -1)
796 tags = TAGS_UNSET;
799 if (!transport->get_refs_list || !transport->fetch)
800 die(_("Don't know how to fetch from %s"), transport->url);
802 /* if not appending, truncate FETCH_HEAD */
803 if (!append && !dry_run) {
804 retcode = truncate_fetch_head();
805 if (retcode)
806 goto cleanup;
809 ref_map = get_ref_map(transport, refs, ref_count, tags, &autotags);
810 if (!update_head_ok)
811 check_not_current_branch(ref_map);
813 for (rm = ref_map; rm; rm = rm->next) {
814 if (rm->peer_ref) {
815 struct string_list_item *peer_item =
816 string_list_lookup(&existing_refs,
817 rm->peer_ref->name);
818 if (peer_item)
819 hashcpy(rm->peer_ref->old_sha1,
820 peer_item->util);
824 if (tags == TAGS_DEFAULT && autotags)
825 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
826 if (fetch_refs(transport, ref_map)) {
827 free_refs(ref_map);
828 retcode = 1;
829 goto cleanup;
831 if (prune) {
833 * If --tags was specified, pretend that the user gave us
834 * the canonical tags refspec
836 if (tags == TAGS_SET) {
837 const char *tags_str = "refs/tags/*:refs/tags/*";
838 struct refspec *tags_refspec, *refspec;
840 /* Copy the refspec and add the tags to it */
841 refspec = xcalloc(ref_count + 1, sizeof(struct refspec));
842 tags_refspec = parse_fetch_refspec(1, &tags_str);
843 memcpy(refspec, refs, ref_count * sizeof(struct refspec));
844 memcpy(&refspec[ref_count], tags_refspec, sizeof(struct refspec));
845 ref_count++;
847 prune_refs(refspec, ref_count, ref_map);
849 ref_count--;
850 /* The rest of the strings belong to fetch_one */
851 free_refspec(1, tags_refspec);
852 free(refspec);
853 } else if (ref_count) {
854 prune_refs(refs, ref_count, ref_map);
855 } else {
856 prune_refs(transport->remote->fetch, transport->remote->fetch_refspec_nr, ref_map);
859 free_refs(ref_map);
861 /* if neither --no-tags nor --tags was specified, do automated tag
862 * following ... */
863 if (tags == TAGS_DEFAULT && autotags) {
864 struct ref **tail = &ref_map;
865 ref_map = NULL;
866 find_non_local_tags(transport, &ref_map, &tail);
867 if (ref_map)
868 backfill_tags(transport, ref_map);
869 free_refs(ref_map);
872 cleanup:
873 string_list_clear(&existing_refs, 1);
874 return retcode;
877 static int get_one_remote_for_fetch(struct remote *remote, void *priv)
879 struct string_list *list = priv;
880 if (!remote->skip_default_update)
881 string_list_append(list, remote->name);
882 return 0;
885 struct remote_group_data {
886 const char *name;
887 struct string_list *list;
890 static int get_remote_group(const char *key, const char *value, void *priv)
892 struct remote_group_data *g = priv;
894 if (!prefixcmp(key, "remotes.") &&
895 !strcmp(key + 8, g->name)) {
896 /* split list by white space */
897 int space = strcspn(value, " \t\n");
898 while (*value) {
899 if (space > 1) {
900 string_list_append(g->list,
901 xstrndup(value, space));
903 value += space + (value[space] != '\0');
904 space = strcspn(value, " \t\n");
908 return 0;
911 static int add_remote_or_group(const char *name, struct string_list *list)
913 int prev_nr = list->nr;
914 struct remote_group_data g;
915 g.name = name; g.list = list;
917 git_config(get_remote_group, &g);
918 if (list->nr == prev_nr) {
919 struct remote *remote;
920 if (!remote_is_configured(name))
921 return 0;
922 remote = remote_get(name);
923 string_list_append(list, remote->name);
925 return 1;
928 static void add_options_to_argv(struct argv_array *argv)
930 if (dry_run)
931 argv_array_push(argv, "--dry-run");
932 if (prune > 0)
933 argv_array_push(argv, "--prune");
934 if (update_head_ok)
935 argv_array_push(argv, "--update-head-ok");
936 if (force)
937 argv_array_push(argv, "--force");
938 if (keep)
939 argv_array_push(argv, "--keep");
940 if (recurse_submodules == RECURSE_SUBMODULES_ON)
941 argv_array_push(argv, "--recurse-submodules");
942 else if (recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND)
943 argv_array_push(argv, "--recurse-submodules=on-demand");
944 if (tags == TAGS_SET)
945 argv_array_push(argv, "--tags");
946 else if (tags == TAGS_UNSET)
947 argv_array_push(argv, "--no-tags");
948 if (verbosity >= 2)
949 argv_array_push(argv, "-v");
950 if (verbosity >= 1)
951 argv_array_push(argv, "-v");
952 else if (verbosity < 0)
953 argv_array_push(argv, "-q");
957 static int fetch_multiple(struct string_list *list)
959 int i, result = 0;
960 struct argv_array argv = ARGV_ARRAY_INIT;
962 if (!append && !dry_run) {
963 int errcode = truncate_fetch_head();
964 if (errcode)
965 return errcode;
968 argv_array_pushl(&argv, "fetch", "--append", NULL);
969 add_options_to_argv(&argv);
971 for (i = 0; i < list->nr; i++) {
972 const char *name = list->items[i].string;
973 argv_array_push(&argv, name);
974 if (verbosity >= 0)
975 printf(_("Fetching %s\n"), name);
976 if (run_command_v_opt(argv.argv, RUN_GIT_CMD)) {
977 error(_("Could not fetch %s"), name);
978 result = 1;
980 argv_array_pop(&argv);
983 argv_array_clear(&argv);
984 return result;
987 static int fetch_one(struct remote *remote, int argc, const char **argv)
989 int i;
990 static const char **refs = NULL;
991 struct refspec *refspec;
992 int ref_nr = 0;
993 int exit_code;
995 if (!remote)
996 die(_("No remote repository specified. Please, specify either a URL or a\n"
997 "remote name from which new revisions should be fetched."));
999 gtransport = prepare_transport(remote);
1001 if (prune < 0) {
1002 /* no command line request */
1003 if (0 <= gtransport->remote->prune)
1004 prune = gtransport->remote->prune;
1005 else if (0 <= fetch_prune_config)
1006 prune = fetch_prune_config;
1007 else
1008 prune = PRUNE_BY_DEFAULT;
1011 if (argc > 0) {
1012 int j = 0;
1013 refs = xcalloc(argc + 1, sizeof(const char *));
1014 for (i = 0; i < argc; i++) {
1015 if (!strcmp(argv[i], "tag")) {
1016 char *ref;
1017 i++;
1018 if (i >= argc)
1019 die(_("You need to specify a tag name."));
1020 ref = xmalloc(strlen(argv[i]) * 2 + 22);
1021 strcpy(ref, "refs/tags/");
1022 strcat(ref, argv[i]);
1023 strcat(ref, ":refs/tags/");
1024 strcat(ref, argv[i]);
1025 refs[j++] = ref;
1026 } else
1027 refs[j++] = argv[i];
1029 refs[j] = NULL;
1030 ref_nr = j;
1033 sigchain_push_common(unlock_pack_on_signal);
1034 atexit(unlock_pack);
1035 refspec = parse_fetch_refspec(ref_nr, refs);
1036 exit_code = do_fetch(gtransport, refspec, ref_nr);
1037 free_refspec(ref_nr, refspec);
1038 transport_disconnect(gtransport);
1039 gtransport = NULL;
1040 return exit_code;
1043 int cmd_fetch(int argc, const char **argv, const char *prefix)
1045 int i;
1046 struct string_list list = STRING_LIST_INIT_NODUP;
1047 struct remote *remote;
1048 int result = 0;
1049 static const char *argv_gc_auto[] = {
1050 "gc", "--auto", NULL,
1053 packet_trace_identity("fetch");
1055 /* Record the command line for the reflog */
1056 strbuf_addstr(&default_rla, "fetch");
1057 for (i = 1; i < argc; i++)
1058 strbuf_addf(&default_rla, " %s", argv[i]);
1060 git_config(git_fetch_config, NULL);
1062 argc = parse_options(argc, argv, prefix,
1063 builtin_fetch_options, builtin_fetch_usage, 0);
1065 if (unshallow) {
1066 if (depth)
1067 die(_("--depth and --unshallow cannot be used together"));
1068 else if (!is_repository_shallow())
1069 die(_("--unshallow on a complete repository does not make sense"));
1070 else {
1071 static char inf_depth[12];
1072 sprintf(inf_depth, "%d", INFINITE_DEPTH);
1073 depth = inf_depth;
1077 if (recurse_submodules != RECURSE_SUBMODULES_OFF) {
1078 if (recurse_submodules_default) {
1079 int arg = parse_fetch_recurse_submodules_arg("--recurse-submodules-default", recurse_submodules_default);
1080 set_config_fetch_recurse_submodules(arg);
1082 gitmodules_config();
1083 git_config(submodule_config, NULL);
1086 if (all) {
1087 if (argc == 1)
1088 die(_("fetch --all does not take a repository argument"));
1089 else if (argc > 1)
1090 die(_("fetch --all does not make sense with refspecs"));
1091 (void) for_each_remote(get_one_remote_for_fetch, &list);
1092 result = fetch_multiple(&list);
1093 } else if (argc == 0) {
1094 /* No arguments -- use default remote */
1095 remote = remote_get(NULL);
1096 result = fetch_one(remote, argc, argv);
1097 } else if (multiple) {
1098 /* All arguments are assumed to be remotes or groups */
1099 for (i = 0; i < argc; i++)
1100 if (!add_remote_or_group(argv[i], &list))
1101 die(_("No such remote or remote group: %s"), argv[i]);
1102 result = fetch_multiple(&list);
1103 } else {
1104 /* Single remote or group */
1105 (void) add_remote_or_group(argv[0], &list);
1106 if (list.nr > 1) {
1107 /* More than one remote */
1108 if (argc > 1)
1109 die(_("Fetching a group and specifying refspecs does not make sense"));
1110 result = fetch_multiple(&list);
1111 } else {
1112 /* Zero or one remotes */
1113 remote = remote_get(argv[0]);
1114 result = fetch_one(remote, argc-1, argv+1);
1118 if (!result && (recurse_submodules != RECURSE_SUBMODULES_OFF)) {
1119 struct argv_array options = ARGV_ARRAY_INIT;
1121 add_options_to_argv(&options);
1122 result = fetch_populated_submodules(&options,
1123 submodule_prefix,
1124 recurse_submodules,
1125 verbosity < 0);
1126 argv_array_clear(&options);
1129 /* All names were strdup()ed or strndup()ed */
1130 list.strdup_strings = 1;
1131 string_list_clear(&list, 0);
1133 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
1135 return result;