fetch: refactor code that prepares a transport
[git/jrn.git] / builtin / fetch.c
blob39a3fc8dea3172cb430eef4a242f0e526fb89f06
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 all, append, dry_run, force, keep, multiple, prune, update_head_ok, verbosity;
34 static int progress = -1, recurse_submodules = RECURSE_SUBMODULES_DEFAULT;
35 static int tags = TAGS_DEFAULT, unshallow;
36 static const char *depth;
37 static const char *upload_pack;
38 static struct strbuf default_rla = STRBUF_INIT;
39 static struct transport *gtransport;
40 static const char *submodule_prefix = "";
41 static const char *recurse_submodules_default;
43 static int option_parse_recurse_submodules(const struct option *opt,
44 const char *arg, int unset)
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;
54 return 0;
57 static struct option builtin_fetch_options[] = {
58 OPT__VERBOSITY(&verbosity),
59 OPT_BOOLEAN(0, "all", &all,
60 N_("fetch from all remotes")),
61 OPT_BOOLEAN('a', "append", &append,
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")),
66 OPT_BOOLEAN('m', "multiple", &multiple,
67 N_("fetch from multiple remotes")),
68 OPT_SET_INT('t', "tags", &tags,
69 N_("fetch all tags and associated objects"), TAGS_SET),
70 OPT_SET_INT('n', NULL, &tags,
71 N_("do not fetch all tags (--no-tags)"), TAGS_UNSET),
72 OPT_BOOLEAN('p', "prune", &prune,
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"),
76 PARSE_OPT_OPTARG, option_parse_recurse_submodules },
77 OPT_BOOLEAN(0, "dry-run", &dry_run,
78 N_("dry run")),
79 OPT_BOOLEAN('k', "keep", &keep, N_("keep downloaded pack")),
80 OPT_BOOLEAN('u', "update-head-ok", &update_head_ok,
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")),
85 { OPTION_SET_INT, 0, "unshallow", &unshallow, NULL,
86 N_("convert to a complete repository"),
87 PARSE_OPT_NONEG | PARSE_OPT_NOARG, NULL, 1 },
88 { OPTION_STRING, 0, "submodule-prefix", &submodule_prefix, N_("dir"),
89 N_("prepend this to submodule path output"), PARSE_OPT_HIDDEN },
90 { OPTION_STRING, 0, "recurse-submodules-default",
91 &recurse_submodules_default, NULL,
92 N_("default mode for recursion"), PARSE_OPT_HIDDEN },
93 OPT_END()
96 static void unlock_pack(void)
98 if (gtransport)
99 transport_unlock_pack(gtransport);
102 static void unlock_pack_on_signal(int signo)
104 unlock_pack();
105 sigchain_pop(signo);
106 raise(signo);
109 static void add_merge_config(struct ref **head,
110 const struct ref *remote_refs,
111 struct branch *branch,
112 struct ref ***tail)
114 int i;
116 for (i = 0; i < branch->merge_nr; i++) {
117 struct ref *rm, **old_tail = *tail;
118 struct refspec refspec;
120 for (rm = *head; rm; rm = rm->next) {
121 if (branch_merge_matches(branch, i, rm->name)) {
122 rm->fetch_head_status = FETCH_HEAD_MERGE;
123 break;
126 if (rm)
127 continue;
130 * Not fetched to a remote-tracking branch? We need to fetch
131 * it anyway to allow this branch's "branch.$name.merge"
132 * to be honored by 'git pull', but we do not have to
133 * fail if branch.$name.merge is misconfigured to point
134 * at a nonexisting branch. If we were indeed called by
135 * 'git pull', it will notice the misconfiguration because
136 * there is no entry in the resulting FETCH_HEAD marked
137 * for merging.
139 memset(&refspec, 0, sizeof(refspec));
140 refspec.src = branch->merge[i]->src;
141 get_fetch_map(remote_refs, &refspec, tail, 1);
142 for (rm = *old_tail; rm; rm = rm->next)
143 rm->fetch_head_status = FETCH_HEAD_MERGE;
147 static void find_non_local_tags(struct transport *transport,
148 struct ref **head,
149 struct ref ***tail);
151 static struct ref *get_ref_map(struct transport *transport,
152 struct refspec *refs, int ref_count, int tags,
153 int *autotags)
155 int i;
156 struct ref *rm;
157 struct ref *ref_map = NULL;
158 struct ref **tail = &ref_map;
160 const struct ref *remote_refs = transport_get_remote_refs(transport);
162 if (ref_count || tags == TAGS_SET) {
163 struct ref **old_tail;
165 for (i = 0; i < ref_count; i++) {
166 get_fetch_map(remote_refs, &refs[i], &tail, 0);
167 if (refs[i].dst && refs[i].dst[0])
168 *autotags = 1;
170 /* Merge everything on the command line, but not --tags */
171 for (rm = ref_map; rm; rm = rm->next)
172 rm->fetch_head_status = FETCH_HEAD_MERGE;
173 if (tags == TAGS_SET)
174 get_fetch_map(remote_refs, tag_refspec, &tail, 0);
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.
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, 1);
187 for (rm = *old_tail; rm; rm = rm->next)
188 rm->fetch_head_status = FETCH_HEAD_IGNORE;
189 } else {
190 /* Use the defaults */
191 struct remote *remote = transport->remote;
192 struct branch *branch = branch_get(NULL);
193 int has_merge = branch_has_merge_config(branch);
194 if (remote &&
195 (remote->fetch_refspec_nr ||
196 /* Note: has_merge implies non-NULL branch->remote_name */
197 (has_merge && !strcmp(branch->remote_name, remote->name)))) {
198 for (i = 0; i < remote->fetch_refspec_nr; i++) {
199 get_fetch_map(remote_refs, &remote->fetch[i], &tail, 0);
200 if (remote->fetch[i].dst &&
201 remote->fetch[i].dst[0])
202 *autotags = 1;
203 if (!i && !has_merge && ref_map &&
204 !remote->fetch[0].pattern)
205 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
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.
212 * Note: has_merge implies non-NULL branch->remote_name
214 if (has_merge &&
215 !strcmp(branch->remote_name, remote->name))
216 add_merge_config(&ref_map, remote_refs, branch, &tail);
217 } else {
218 ref_map = get_remote_ref(remote_refs, "HEAD");
219 if (!ref_map)
220 die(_("Couldn't find remote ref HEAD"));
221 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
222 tail = &ref_map->next;
225 if (tags == TAGS_DEFAULT && *autotags)
226 find_non_local_tags(transport, &ref_map, &tail);
227 ref_remove_duplicates(ref_map);
229 return ref_map;
232 #define STORE_REF_ERROR_OTHER 1
233 #define STORE_REF_ERROR_DF_CONFLICT 2
235 static int s_update_ref(const char *action,
236 struct ref *ref,
237 int check_old)
239 char msg[1024];
240 char *rla = getenv("GIT_REFLOG_ACTION");
241 static struct ref_lock *lock;
243 if (dry_run)
244 return 0;
245 if (!rla)
246 rla = default_rla.buf;
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)
251 return errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
252 STORE_REF_ERROR_OTHER;
253 if (write_ref_sha1(lock, ref->new_sha1, msg) < 0)
254 return errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
255 STORE_REF_ERROR_OTHER;
256 return 0;
259 #define REFCOL_WIDTH 10
261 static int update_local_ref(struct ref *ref,
262 const char *remote,
263 const struct ref *remote_ref,
264 struct strbuf *display)
266 struct commit *current = NULL, *updated;
267 enum object_type type;
268 struct branch *current_branch = branch_get(NULL);
269 const char *pretty_ref = prettify_refname(ref->name);
271 type = sha1_object_info(ref->new_sha1, NULL);
272 if (type < 0)
273 die(_("object %s not found"), sha1_to_hex(ref->new_sha1));
275 if (!hashcmp(ref->old_sha1, ref->new_sha1)) {
276 if (verbosity > 0)
277 strbuf_addf(display, "= %-*s %-*s -> %s",
278 TRANSPORT_SUMMARY(_("[up to date]")),
279 REFCOL_WIDTH, remote, pretty_ref);
280 return 0;
283 if (current_branch &&
284 !strcmp(ref->name, current_branch->name) &&
285 !(update_head_ok || is_bare_repository()) &&
286 !is_null_sha1(ref->old_sha1)) {
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...
291 strbuf_addf(display,
292 _("! %-*s %-*s -> %s (can't fetch in current branch)"),
293 TRANSPORT_SUMMARY(_("[rejected]")),
294 REFCOL_WIDTH, remote, pretty_ref);
295 return 1;
298 if (!is_null_sha1(ref->old_sha1) &&
299 !prefixcmp(ref->name, "refs/tags/")) {
300 int r;
301 r = s_update_ref("updating tag", ref, 0);
302 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
303 r ? '!' : '-',
304 TRANSPORT_SUMMARY(_("[tag update]")),
305 REFCOL_WIDTH, remote, pretty_ref,
306 r ? _(" (unable to update local ref)") : "");
307 return r;
310 current = lookup_commit_reference_gently(ref->old_sha1, 1);
311 updated = lookup_commit_reference_gently(ref->new_sha1, 1);
312 if (!current || !updated) {
313 const char *msg;
314 const char *what;
315 int r;
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.
321 const char *name = remote_ref ? remote_ref->name : "";
322 if (!prefixcmp(name, "refs/tags/")) {
323 msg = "storing tag";
324 what = _("[new tag]");
325 } else if (!prefixcmp(name, "refs/heads/")) {
326 msg = "storing head";
327 what = _("[new branch]");
328 } else {
329 msg = "storing ref";
330 what = _("[new ref]");
333 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
334 (recurse_submodules != RECURSE_SUBMODULES_ON))
335 check_for_new_submodule_commits(ref->new_sha1);
336 r = s_update_ref(msg, ref, 0);
337 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
338 r ? '!' : '*',
339 TRANSPORT_SUMMARY(what),
340 REFCOL_WIDTH, remote, pretty_ref,
341 r ? _(" (unable to update local ref)") : "");
342 return r;
345 if (in_merge_bases(current, updated)) {
346 char quickref[83];
347 int r;
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));
351 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
352 (recurse_submodules != RECURSE_SUBMODULES_ON))
353 check_for_new_submodule_commits(ref->new_sha1);
354 r = s_update_ref("fast-forward", ref, 1);
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)") : "");
360 return r;
361 } else if (force || ref->force) {
362 char quickref[84];
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("forced-update", 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") : _("forced update"));
376 return r;
377 } else {
378 strbuf_addf(display, "! %-*s %-*s -> %s %s",
379 TRANSPORT_SUMMARY(_("[rejected]")),
380 REFCOL_WIDTH, remote, pretty_ref,
381 _("(non-fast-forward)"));
382 return 1;
386 static int iterate_ref_map(void *cb_data, unsigned char sha1[20])
388 struct ref **rm = cb_data;
389 struct ref *ref = *rm;
391 if (!ref)
392 return -1; /* end of the list */
393 *rm = ref->next;
394 hashcpy(sha1, ref->old_sha1);
395 return 0;
398 static int store_updated_refs(const char *raw_url, const char *remote_name,
399 struct ref *ref_map)
401 FILE *fp;
402 struct commit *commit;
403 int url_len, i, shown_url = 0, rc = 0;
404 struct strbuf note = STRBUF_INIT;
405 const char *what, *kind;
406 struct ref *rm;
407 char *url, *filename = dry_run ? "/dev/null" : git_path("FETCH_HEAD");
408 int want_status;
410 fp = fopen(filename, "a");
411 if (!fp)
412 return error(_("cannot open %s: %s\n"), filename, strerror(errno));
414 if (raw_url)
415 url = transport_anonymize_url(raw_url);
416 else
417 url = xstrdup("foreign");
419 rm = ref_map;
420 if (check_everything_connected(iterate_ref_map, 0, &rm)) {
421 rc = error(_("%s did not send all necessary objects\n"), url);
422 goto abort;
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.
430 for (want_status = FETCH_HEAD_MERGE;
431 want_status <= FETCH_HEAD_IGNORE;
432 want_status++) {
433 for (rm = ref_map; rm; rm = rm->next) {
434 struct ref *ref = NULL;
435 const char *merge_status_marker = "";
437 commit = lookup_commit_reference_gently(rm->old_sha1, 1);
438 if (!commit)
439 rm->fetch_head_status = FETCH_HEAD_NOT_FOR_MERGE;
441 if (rm->fetch_head_status != want_status)
442 continue;
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;
453 if (!strcmp(rm->name, "HEAD")) {
454 kind = "";
455 what = "";
457 else if (!prefixcmp(rm->name, "refs/heads/")) {
458 kind = "branch";
459 what = rm->name + 11;
461 else if (!prefixcmp(rm->name, "refs/tags/")) {
462 kind = "tag";
463 what = rm->name + 10;
465 else if (!prefixcmp(rm->name, "refs/remotes/")) {
466 kind = "remote-tracking branch";
467 what = rm->name + 13;
469 else {
470 kind = "";
471 what = rm->name;
474 url_len = strlen(url);
475 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
477 url_len = i + 1;
478 if (4 < i && !strncmp(".git", url + i - 3, 4))
479 url_len = i - 3;
481 strbuf_reset(&note);
482 if (*what) {
483 if (*kind)
484 strbuf_addf(&note, "%s ", kind);
485 strbuf_addf(&note, "'%s' of ", what);
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;
508 strbuf_reset(&note);
509 if (ref) {
510 rc |= update_local_ref(ref, what, rm, &note);
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;
524 if (verbosity >= 0)
525 fprintf(stderr, " %s\n", note.buf);
530 if (rc & STORE_REF_ERROR_DF_CONFLICT)
531 error(_("some local refs could not be updated; try running\n"
532 " 'git remote prune %s' to remove any old, conflicting "
533 "branches"), remote_name);
535 abort:
536 strbuf_release(&note);
537 free(url);
538 fclose(fp);
539 return rc;
543 * We would want to bypass the object transfer altogether if
544 * everything we are going to fetch already exists and is connected
545 * locally.
547 static int quickfetch(struct ref *ref_map)
549 struct ref *rm = ref_map;
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.
558 if (depth)
559 return -1;
560 return check_everything_connected(iterate_ref_map, 1, &rm);
563 static int fetch_refs(struct transport *transport, struct ref *ref_map)
565 int ret = quickfetch(ref_map);
566 if (ret)
567 ret = transport_fetch_refs(transport, ref_map);
568 if (!ret)
569 ret |= store_updated_refs(transport->url,
570 transport->remote->name,
571 ref_map);
572 transport_unlock_pack(transport);
573 return ret;
576 static int prune_refs(struct refspec *refs, int ref_count, struct ref *ref_map)
578 int result = 0;
579 struct ref *ref, *stale_refs = get_stale_heads(refs, ref_count, ref_map);
580 const char *dangling_msg = dry_run
581 ? _(" (%s will become dangling)")
582 : _(" (%s has become dangling)");
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",
589 TRANSPORT_SUMMARY(_("[deleted]")),
590 REFCOL_WIDTH, _("(none)"), prettify_refname(ref->name));
591 warn_dangling_symref(stderr, dangling_msg, ref->name);
594 free_refs(stale_refs);
595 return result;
598 static int add_existing(const char *refname, const unsigned char *sha1,
599 int flag, void *cbdata)
601 struct string_list *list = (struct string_list *)cbdata;
602 struct string_list_item *item = string_list_insert(list, refname);
603 item->util = xmalloc(20);
604 hashcpy(item->util, sha1);
605 return 0;
608 static int will_fetch(struct ref **head, const unsigned char *sha1)
610 struct ref *rm = *head;
611 while (rm) {
612 if (!hashcmp(rm->old_sha1, sha1))
613 return 1;
614 rm = rm->next;
616 return 0;
619 static void find_non_local_tags(struct transport *transport,
620 struct ref **head,
621 struct ref ***tail)
623 struct string_list existing_refs = STRING_LIST_INIT_DUP;
624 struct string_list remote_refs = STRING_LIST_INIT_NODUP;
625 const struct ref *ref;
626 struct string_list_item *item = NULL;
628 for_each_ref(add_existing, &existing_refs);
629 for (ref = transport_get_remote_refs(transport); ref; ref = ref->next) {
630 if (prefixcmp(ref->name, "refs/tags/"))
631 continue;
634 * The peeled ref always follows the matching base
635 * ref, so if we see a peeled ref that we don't want
636 * to fetch then we can mark the ref entry in the list
637 * as one to ignore by setting util to NULL.
639 if (!suffixcmp(ref->name, "^{}")) {
640 if (item && !has_sha1_file(ref->old_sha1) &&
641 !will_fetch(head, ref->old_sha1) &&
642 !has_sha1_file(item->util) &&
643 !will_fetch(head, item->util))
644 item->util = NULL;
645 item = NULL;
646 continue;
650 * If item is non-NULL here, then we previously saw a
651 * ref not followed by a peeled reference, so we need
652 * to check if it is a lightweight tag that we want to
653 * fetch.
655 if (item && !has_sha1_file(item->util) &&
656 !will_fetch(head, item->util))
657 item->util = NULL;
659 item = NULL;
661 /* skip duplicates and refs that we already have */
662 if (string_list_has_string(&remote_refs, ref->name) ||
663 string_list_has_string(&existing_refs, ref->name))
664 continue;
666 item = string_list_insert(&remote_refs, ref->name);
667 item->util = (void *)ref->old_sha1;
669 string_list_clear(&existing_refs, 1);
672 * We may have a final lightweight tag that needs to be
673 * checked to see if it needs fetching.
675 if (item && !has_sha1_file(item->util) &&
676 !will_fetch(head, item->util))
677 item->util = NULL;
680 * For all the tags in the remote_refs string list,
681 * add them to the list of refs to be fetched
683 for_each_string_list_item(item, &remote_refs) {
684 /* Unless we have already decided to ignore this item... */
685 if (item->util)
687 struct ref *rm = alloc_ref(item->string);
688 rm->peer_ref = alloc_ref(item->string);
689 hashcpy(rm->old_sha1, item->util);
690 **tail = rm;
691 *tail = &rm->next;
695 string_list_clear(&remote_refs, 0);
698 static void check_not_current_branch(struct ref *ref_map)
700 struct branch *current_branch = branch_get(NULL);
702 if (is_bare_repository() || !current_branch)
703 return;
705 for (; ref_map; ref_map = ref_map->next)
706 if (ref_map->peer_ref && !strcmp(current_branch->refname,
707 ref_map->peer_ref->name))
708 die(_("Refusing to fetch into current branch %s "
709 "of non-bare repository"), current_branch->refname);
712 static int truncate_fetch_head(void)
714 char *filename = git_path("FETCH_HEAD");
715 FILE *fp = fopen(filename, "w");
717 if (!fp)
718 return error(_("cannot open %s: %s\n"), filename, strerror(errno));
719 fclose(fp);
720 return 0;
723 static void set_option(struct transport *transport, const char *name, const char *value)
725 int r = transport_set_option(transport, name, value);
726 if (r < 0)
727 die(_("Option \"%s\" value \"%s\" is not valid for %s"),
728 name, value, transport->url);
729 if (r > 0)
730 warning(_("Option \"%s\" is ignored for %s\n"),
731 name, transport->url);
734 struct transport *prepare_transport(struct remote *remote)
736 struct transport *transport;
737 transport = transport_get(remote, NULL);
738 transport_set_verbosity(transport, verbosity, progress);
739 if (upload_pack)
740 set_option(transport, TRANS_OPT_UPLOADPACK, upload_pack);
741 if (keep)
742 set_option(transport, TRANS_OPT_KEEP, "yes");
743 if (depth)
744 set_option(transport, TRANS_OPT_DEPTH, depth);
745 return transport;
748 static int do_fetch(struct transport *transport,
749 struct refspec *refs, int ref_count)
751 struct string_list existing_refs = STRING_LIST_INIT_DUP;
752 struct ref *ref_map;
753 struct ref *rm;
754 int autotags = (transport->remote->fetch_tags == 1);
755 int retcode = 0;
757 for_each_ref(add_existing, &existing_refs);
759 if (tags == TAGS_DEFAULT) {
760 if (transport->remote->fetch_tags == 2)
761 tags = TAGS_SET;
762 if (transport->remote->fetch_tags == -1)
763 tags = TAGS_UNSET;
766 if (!transport->get_refs_list || !transport->fetch)
767 die(_("Don't know how to fetch from %s"), transport->url);
769 /* if not appending, truncate FETCH_HEAD */
770 if (!append && !dry_run) {
771 retcode = truncate_fetch_head();
772 if (retcode)
773 goto cleanup;
776 ref_map = get_ref_map(transport, refs, ref_count, tags, &autotags);
777 if (!update_head_ok)
778 check_not_current_branch(ref_map);
780 for (rm = ref_map; rm; rm = rm->next) {
781 if (rm->peer_ref) {
782 struct string_list_item *peer_item =
783 string_list_lookup(&existing_refs,
784 rm->peer_ref->name);
785 if (peer_item)
786 hashcpy(rm->peer_ref->old_sha1,
787 peer_item->util);
791 if (tags == TAGS_DEFAULT && autotags)
792 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
793 if (fetch_refs(transport, ref_map)) {
794 free_refs(ref_map);
795 retcode = 1;
796 goto cleanup;
798 if (prune) {
799 /* If --tags was specified, pretend the user gave us the canonical tags refspec */
800 if (tags == TAGS_SET) {
801 const char *tags_str = "refs/tags/*:refs/tags/*";
802 struct refspec *tags_refspec, *refspec;
804 /* Copy the refspec and add the tags to it */
805 refspec = xcalloc(ref_count + 1, sizeof(struct refspec));
806 tags_refspec = parse_fetch_refspec(1, &tags_str);
807 memcpy(refspec, refs, ref_count * sizeof(struct refspec));
808 memcpy(&refspec[ref_count], tags_refspec, sizeof(struct refspec));
809 ref_count++;
811 prune_refs(refspec, ref_count, ref_map);
813 ref_count--;
814 /* The rest of the strings belong to fetch_one */
815 free_refspec(1, tags_refspec);
816 free(refspec);
817 } else if (ref_count) {
818 prune_refs(refs, ref_count, ref_map);
819 } else {
820 prune_refs(transport->remote->fetch, transport->remote->fetch_refspec_nr, ref_map);
823 free_refs(ref_map);
825 /* if neither --no-tags nor --tags was specified, do automated tag
826 * following ... */
827 if (tags == TAGS_DEFAULT && autotags) {
828 struct ref **tail = &ref_map;
829 ref_map = NULL;
830 find_non_local_tags(transport, &ref_map, &tail);
831 if (ref_map) {
832 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
833 transport_set_option(transport, TRANS_OPT_DEPTH, "0");
834 fetch_refs(transport, ref_map);
836 free_refs(ref_map);
839 cleanup:
840 string_list_clear(&existing_refs, 1);
841 return retcode;
844 static int get_one_remote_for_fetch(struct remote *remote, void *priv)
846 struct string_list *list = priv;
847 if (!remote->skip_default_update)
848 string_list_append(list, remote->name);
849 return 0;
852 struct remote_group_data {
853 const char *name;
854 struct string_list *list;
857 static int get_remote_group(const char *key, const char *value, void *priv)
859 struct remote_group_data *g = priv;
861 if (!prefixcmp(key, "remotes.") &&
862 !strcmp(key + 8, g->name)) {
863 /* split list by white space */
864 int space = strcspn(value, " \t\n");
865 while (*value) {
866 if (space > 1) {
867 string_list_append(g->list,
868 xstrndup(value, space));
870 value += space + (value[space] != '\0');
871 space = strcspn(value, " \t\n");
875 return 0;
878 static int add_remote_or_group(const char *name, struct string_list *list)
880 int prev_nr = list->nr;
881 struct remote_group_data g;
882 g.name = name; g.list = list;
884 git_config(get_remote_group, &g);
885 if (list->nr == prev_nr) {
886 struct remote *remote;
887 if (!remote_is_configured(name))
888 return 0;
889 remote = remote_get(name);
890 string_list_append(list, remote->name);
892 return 1;
895 static void add_options_to_argv(struct argv_array *argv)
897 if (dry_run)
898 argv_array_push(argv, "--dry-run");
899 if (prune)
900 argv_array_push(argv, "--prune");
901 if (update_head_ok)
902 argv_array_push(argv, "--update-head-ok");
903 if (force)
904 argv_array_push(argv, "--force");
905 if (keep)
906 argv_array_push(argv, "--keep");
907 if (recurse_submodules == RECURSE_SUBMODULES_ON)
908 argv_array_push(argv, "--recurse-submodules");
909 else if (recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND)
910 argv_array_push(argv, "--recurse-submodules=on-demand");
911 if (tags == TAGS_SET)
912 argv_array_push(argv, "--tags");
913 else if (tags == TAGS_UNSET)
914 argv_array_push(argv, "--no-tags");
915 if (verbosity >= 2)
916 argv_array_push(argv, "-v");
917 if (verbosity >= 1)
918 argv_array_push(argv, "-v");
919 else if (verbosity < 0)
920 argv_array_push(argv, "-q");
924 static int fetch_multiple(struct string_list *list)
926 int i, result = 0;
927 struct argv_array argv = ARGV_ARRAY_INIT;
929 if (!append && !dry_run) {
930 int errcode = truncate_fetch_head();
931 if (errcode)
932 return errcode;
935 argv_array_pushl(&argv, "fetch", "--append", NULL);
936 add_options_to_argv(&argv);
938 for (i = 0; i < list->nr; i++) {
939 const char *name = list->items[i].string;
940 argv_array_push(&argv, name);
941 if (verbosity >= 0)
942 printf(_("Fetching %s\n"), name);
943 if (run_command_v_opt(argv.argv, RUN_GIT_CMD)) {
944 error(_("Could not fetch %s"), name);
945 result = 1;
947 argv_array_pop(&argv);
950 argv_array_clear(&argv);
951 return result;
954 static int fetch_one(struct remote *remote, int argc, const char **argv)
956 int i;
957 static const char **refs = NULL;
958 struct refspec *refspec;
959 int ref_nr = 0;
960 int exit_code;
962 if (!remote)
963 die(_("No remote repository specified. Please, specify either a URL or a\n"
964 "remote name from which new revisions should be fetched."));
966 gtransport = prepare_transport(remote);
967 if (argc > 0) {
968 int j = 0;
969 refs = xcalloc(argc + 1, sizeof(const char *));
970 for (i = 0; i < argc; i++) {
971 if (!strcmp(argv[i], "tag")) {
972 char *ref;
973 i++;
974 if (i >= argc)
975 die(_("You need to specify a tag name."));
976 ref = xmalloc(strlen(argv[i]) * 2 + 22);
977 strcpy(ref, "refs/tags/");
978 strcat(ref, argv[i]);
979 strcat(ref, ":refs/tags/");
980 strcat(ref, argv[i]);
981 refs[j++] = ref;
982 } else
983 refs[j++] = argv[i];
985 refs[j] = NULL;
986 ref_nr = j;
989 sigchain_push_common(unlock_pack_on_signal);
990 atexit(unlock_pack);
991 refspec = parse_fetch_refspec(ref_nr, refs);
992 exit_code = do_fetch(gtransport, refspec, ref_nr);
993 free_refspec(ref_nr, refspec);
994 transport_disconnect(gtransport);
995 gtransport = NULL;
996 return exit_code;
999 int cmd_fetch(int argc, const char **argv, const char *prefix)
1001 int i;
1002 struct string_list list = STRING_LIST_INIT_NODUP;
1003 struct remote *remote;
1004 int result = 0;
1005 static const char *argv_gc_auto[] = {
1006 "gc", "--auto", NULL,
1009 packet_trace_identity("fetch");
1011 /* Record the command line for the reflog */
1012 strbuf_addstr(&default_rla, "fetch");
1013 for (i = 1; i < argc; i++)
1014 strbuf_addf(&default_rla, " %s", argv[i]);
1016 argc = parse_options(argc, argv, prefix,
1017 builtin_fetch_options, builtin_fetch_usage, 0);
1019 if (unshallow) {
1020 if (depth)
1021 die(_("--depth and --unshallow cannot be used together"));
1022 else if (!is_repository_shallow())
1023 die(_("--unshallow on a complete repository does not make sense"));
1024 else {
1025 static char inf_depth[12];
1026 sprintf(inf_depth, "%d", INFINITE_DEPTH);
1027 depth = inf_depth;
1031 if (recurse_submodules != RECURSE_SUBMODULES_OFF) {
1032 if (recurse_submodules_default) {
1033 int arg = parse_fetch_recurse_submodules_arg("--recurse-submodules-default", recurse_submodules_default);
1034 set_config_fetch_recurse_submodules(arg);
1036 gitmodules_config();
1037 git_config(submodule_config, NULL);
1040 if (all) {
1041 if (argc == 1)
1042 die(_("fetch --all does not take a repository argument"));
1043 else if (argc > 1)
1044 die(_("fetch --all does not make sense with refspecs"));
1045 (void) for_each_remote(get_one_remote_for_fetch, &list);
1046 result = fetch_multiple(&list);
1047 } else if (argc == 0) {
1048 /* No arguments -- use default remote */
1049 remote = remote_get(NULL);
1050 result = fetch_one(remote, argc, argv);
1051 } else if (multiple) {
1052 /* All arguments are assumed to be remotes or groups */
1053 for (i = 0; i < argc; i++)
1054 if (!add_remote_or_group(argv[i], &list))
1055 die(_("No such remote or remote group: %s"), argv[i]);
1056 result = fetch_multiple(&list);
1057 } else {
1058 /* Single remote or group */
1059 (void) add_remote_or_group(argv[0], &list);
1060 if (list.nr > 1) {
1061 /* More than one remote */
1062 if (argc > 1)
1063 die(_("Fetching a group and specifying refspecs does not make sense"));
1064 result = fetch_multiple(&list);
1065 } else {
1066 /* Zero or one remotes */
1067 remote = remote_get(argv[0]);
1068 result = fetch_one(remote, argc-1, argv+1);
1072 if (!result && (recurse_submodules != RECURSE_SUBMODULES_OFF)) {
1073 struct argv_array options = ARGV_ARRAY_INIT;
1075 add_options_to_argv(&options);
1076 result = fetch_populated_submodules(&options,
1077 submodule_prefix,
1078 recurse_submodules,
1079 verbosity < 0);
1080 argv_array_clear(&options);
1083 /* All names were strdup()ed or strndup()ed */
1084 list.strdup_strings = 1;
1085 string_list_clear(&list, 0);
1087 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
1089 return result;