builtin/fetch.c: reorder function definitions
[git/mingw.git] / builtin / fetch.c
blob61e8117c4a320c62a0cfa9e64378ccc6be0960ce
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 int add_existing(const char *refname, const unsigned char *sha1,
164 int flag, void *cbdata)
166 struct string_list *list = (struct string_list *)cbdata;
167 struct string_list_item *item = string_list_insert(list, refname);
168 item->util = xmalloc(20);
169 hashcpy(item->util, sha1);
170 return 0;
173 static int will_fetch(struct ref **head, const unsigned char *sha1)
175 struct ref *rm = *head;
176 while (rm) {
177 if (!hashcmp(rm->old_sha1, sha1))
178 return 1;
179 rm = rm->next;
181 return 0;
184 static void find_non_local_tags(struct transport *transport,
185 struct ref **head,
186 struct ref ***tail)
188 struct string_list existing_refs = STRING_LIST_INIT_DUP;
189 struct string_list remote_refs = STRING_LIST_INIT_NODUP;
190 const struct ref *ref;
191 struct string_list_item *item = NULL;
193 for_each_ref(add_existing, &existing_refs);
194 for (ref = transport_get_remote_refs(transport); ref; ref = ref->next) {
195 if (prefixcmp(ref->name, "refs/tags/"))
196 continue;
199 * The peeled ref always follows the matching base
200 * ref, so if we see a peeled ref that we don't want
201 * to fetch then we can mark the ref entry in the list
202 * as one to ignore by setting util to NULL.
204 if (!suffixcmp(ref->name, "^{}")) {
205 if (item && !has_sha1_file(ref->old_sha1) &&
206 !will_fetch(head, ref->old_sha1) &&
207 !has_sha1_file(item->util) &&
208 !will_fetch(head, item->util))
209 item->util = NULL;
210 item = NULL;
211 continue;
215 * If item is non-NULL here, then we previously saw a
216 * ref not followed by a peeled reference, so we need
217 * to check if it is a lightweight tag that we want to
218 * fetch.
220 if (item && !has_sha1_file(item->util) &&
221 !will_fetch(head, item->util))
222 item->util = NULL;
224 item = NULL;
226 /* skip duplicates and refs that we already have */
227 if (string_list_has_string(&remote_refs, ref->name) ||
228 string_list_has_string(&existing_refs, ref->name))
229 continue;
231 item = string_list_insert(&remote_refs, ref->name);
232 item->util = (void *)ref->old_sha1;
234 string_list_clear(&existing_refs, 1);
237 * We may have a final lightweight tag that needs to be
238 * checked to see if it needs fetching.
240 if (item && !has_sha1_file(item->util) &&
241 !will_fetch(head, item->util))
242 item->util = NULL;
245 * For all the tags in the remote_refs string list,
246 * add them to the list of refs to be fetched
248 for_each_string_list_item(item, &remote_refs) {
249 /* Unless we have already decided to ignore this item... */
250 if (item->util)
252 struct ref *rm = alloc_ref(item->string);
253 rm->peer_ref = alloc_ref(item->string);
254 hashcpy(rm->old_sha1, item->util);
255 **tail = rm;
256 *tail = &rm->next;
260 string_list_clear(&remote_refs, 0);
263 static struct ref *get_ref_map(struct transport *transport,
264 struct refspec *refspecs, int refspec_count,
265 int tags, int *autotags)
267 int i;
268 struct ref *rm;
269 struct ref *ref_map = NULL;
270 struct ref **tail = &ref_map;
272 const struct ref *remote_refs = transport_get_remote_refs(transport);
274 if (refspec_count || tags == TAGS_SET) {
275 struct ref **old_tail;
277 for (i = 0; i < refspec_count; i++) {
278 get_fetch_map(remote_refs, &refspecs[i], &tail, 0);
279 if (refspecs[i].dst && refspecs[i].dst[0])
280 *autotags = 1;
282 /* Merge everything on the command line, but not --tags */
283 for (rm = ref_map; rm; rm = rm->next)
284 rm->fetch_head_status = FETCH_HEAD_MERGE;
285 if (tags == TAGS_SET)
286 get_fetch_map(remote_refs, tag_refspec, &tail, 0);
289 * For any refs that we happen to be fetching via command-line
290 * arguments, take the opportunity to update their configured
291 * counterparts. However, we do not want to mention these
292 * entries in FETCH_HEAD at all, as they would simply be
293 * duplicates of existing entries.
295 old_tail = tail;
296 for (i = 0; i < transport->remote->fetch_refspec_nr; i++)
297 get_fetch_map(ref_map, &transport->remote->fetch[i],
298 &tail, 1);
299 for (rm = *old_tail; rm; rm = rm->next)
300 rm->fetch_head_status = FETCH_HEAD_IGNORE;
301 } else {
302 /* Use the defaults */
303 struct remote *remote = transport->remote;
304 struct branch *branch = branch_get(NULL);
305 int has_merge = branch_has_merge_config(branch);
306 if (remote &&
307 (remote->fetch_refspec_nr ||
308 /* Note: has_merge implies non-NULL branch->remote_name */
309 (has_merge && !strcmp(branch->remote_name, remote->name)))) {
310 for (i = 0; i < remote->fetch_refspec_nr; i++) {
311 get_fetch_map(remote_refs, &remote->fetch[i], &tail, 0);
312 if (remote->fetch[i].dst &&
313 remote->fetch[i].dst[0])
314 *autotags = 1;
315 if (!i && !has_merge && ref_map &&
316 !remote->fetch[0].pattern)
317 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
320 * if the remote we're fetching from is the same
321 * as given in branch.<name>.remote, we add the
322 * ref given in branch.<name>.merge, too.
324 * Note: has_merge implies non-NULL branch->remote_name
326 if (has_merge &&
327 !strcmp(branch->remote_name, remote->name))
328 add_merge_config(&ref_map, remote_refs, branch, &tail);
329 } else {
330 ref_map = get_remote_ref(remote_refs, "HEAD");
331 if (!ref_map)
332 die(_("Couldn't find remote ref HEAD"));
333 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
334 tail = &ref_map->next;
337 if (tags == TAGS_DEFAULT && *autotags)
338 find_non_local_tags(transport, &ref_map, &tail);
339 ref_remove_duplicates(ref_map);
341 return ref_map;
344 #define STORE_REF_ERROR_OTHER 1
345 #define STORE_REF_ERROR_DF_CONFLICT 2
347 static int s_update_ref(const char *action,
348 struct ref *ref,
349 int check_old)
351 char msg[1024];
352 char *rla = getenv("GIT_REFLOG_ACTION");
353 static struct ref_lock *lock;
355 if (dry_run)
356 return 0;
357 if (!rla)
358 rla = default_rla.buf;
359 snprintf(msg, sizeof(msg), "%s: %s", rla, action);
360 lock = lock_any_ref_for_update(ref->name,
361 check_old ? ref->old_sha1 : NULL,
362 0, NULL);
363 if (!lock)
364 return errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
365 STORE_REF_ERROR_OTHER;
366 if (write_ref_sha1(lock, ref->new_sha1, msg) < 0)
367 return errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
368 STORE_REF_ERROR_OTHER;
369 return 0;
372 #define REFCOL_WIDTH 10
374 static int update_local_ref(struct ref *ref,
375 const char *remote,
376 const struct ref *remote_ref,
377 struct strbuf *display)
379 struct commit *current = NULL, *updated;
380 enum object_type type;
381 struct branch *current_branch = branch_get(NULL);
382 const char *pretty_ref = prettify_refname(ref->name);
384 type = sha1_object_info(ref->new_sha1, NULL);
385 if (type < 0)
386 die(_("object %s not found"), sha1_to_hex(ref->new_sha1));
388 if (!hashcmp(ref->old_sha1, ref->new_sha1)) {
389 if (verbosity > 0)
390 strbuf_addf(display, "= %-*s %-*s -> %s",
391 TRANSPORT_SUMMARY(_("[up to date]")),
392 REFCOL_WIDTH, remote, pretty_ref);
393 return 0;
396 if (current_branch &&
397 !strcmp(ref->name, current_branch->name) &&
398 !(update_head_ok || is_bare_repository()) &&
399 !is_null_sha1(ref->old_sha1)) {
401 * If this is the head, and it's not okay to update
402 * the head, and the old value of the head isn't empty...
404 strbuf_addf(display,
405 _("! %-*s %-*s -> %s (can't fetch in current branch)"),
406 TRANSPORT_SUMMARY(_("[rejected]")),
407 REFCOL_WIDTH, remote, pretty_ref);
408 return 1;
411 if (!is_null_sha1(ref->old_sha1) &&
412 !prefixcmp(ref->name, "refs/tags/")) {
413 int r;
414 r = s_update_ref("updating tag", ref, 0);
415 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
416 r ? '!' : '-',
417 TRANSPORT_SUMMARY(_("[tag update]")),
418 REFCOL_WIDTH, remote, pretty_ref,
419 r ? _(" (unable to update local ref)") : "");
420 return r;
423 current = lookup_commit_reference_gently(ref->old_sha1, 1);
424 updated = lookup_commit_reference_gently(ref->new_sha1, 1);
425 if (!current || !updated) {
426 const char *msg;
427 const char *what;
428 int r;
430 * Nicely describe the new ref we're fetching.
431 * Base this on the remote's ref name, as it's
432 * more likely to follow a standard layout.
434 const char *name = remote_ref ? remote_ref->name : "";
435 if (!prefixcmp(name, "refs/tags/")) {
436 msg = "storing tag";
437 what = _("[new tag]");
438 } else if (!prefixcmp(name, "refs/heads/")) {
439 msg = "storing head";
440 what = _("[new branch]");
441 } else {
442 msg = "storing ref";
443 what = _("[new ref]");
446 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
447 (recurse_submodules != RECURSE_SUBMODULES_ON))
448 check_for_new_submodule_commits(ref->new_sha1);
449 r = s_update_ref(msg, ref, 0);
450 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
451 r ? '!' : '*',
452 TRANSPORT_SUMMARY(what),
453 REFCOL_WIDTH, remote, pretty_ref,
454 r ? _(" (unable to update local ref)") : "");
455 return r;
458 if (in_merge_bases(current, updated)) {
459 char quickref[83];
460 int r;
461 strcpy(quickref, find_unique_abbrev(current->object.sha1, DEFAULT_ABBREV));
462 strcat(quickref, "..");
463 strcat(quickref, find_unique_abbrev(ref->new_sha1, DEFAULT_ABBREV));
464 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
465 (recurse_submodules != RECURSE_SUBMODULES_ON))
466 check_for_new_submodule_commits(ref->new_sha1);
467 r = s_update_ref("fast-forward", ref, 1);
468 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
469 r ? '!' : ' ',
470 TRANSPORT_SUMMARY_WIDTH, quickref,
471 REFCOL_WIDTH, remote, pretty_ref,
472 r ? _(" (unable to update local ref)") : "");
473 return r;
474 } else if (force || ref->force) {
475 char quickref[84];
476 int r;
477 strcpy(quickref, find_unique_abbrev(current->object.sha1, DEFAULT_ABBREV));
478 strcat(quickref, "...");
479 strcat(quickref, find_unique_abbrev(ref->new_sha1, DEFAULT_ABBREV));
480 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
481 (recurse_submodules != RECURSE_SUBMODULES_ON))
482 check_for_new_submodule_commits(ref->new_sha1);
483 r = s_update_ref("forced-update", ref, 1);
484 strbuf_addf(display, "%c %-*s %-*s -> %s (%s)",
485 r ? '!' : '+',
486 TRANSPORT_SUMMARY_WIDTH, quickref,
487 REFCOL_WIDTH, remote, pretty_ref,
488 r ? _("unable to update local ref") : _("forced update"));
489 return r;
490 } else {
491 strbuf_addf(display, "! %-*s %-*s -> %s %s",
492 TRANSPORT_SUMMARY(_("[rejected]")),
493 REFCOL_WIDTH, remote, pretty_ref,
494 _("(non-fast-forward)"));
495 return 1;
499 static int iterate_ref_map(void *cb_data, unsigned char sha1[20])
501 struct ref **rm = cb_data;
502 struct ref *ref = *rm;
504 if (!ref)
505 return -1; /* end of the list */
506 *rm = ref->next;
507 hashcpy(sha1, ref->old_sha1);
508 return 0;
511 static int store_updated_refs(const char *raw_url, const char *remote_name,
512 struct ref *ref_map)
514 FILE *fp;
515 struct commit *commit;
516 int url_len, i, shown_url = 0, rc = 0;
517 struct strbuf note = STRBUF_INIT;
518 const char *what, *kind;
519 struct ref *rm;
520 char *url, *filename = dry_run ? "/dev/null" : git_path("FETCH_HEAD");
521 int want_status;
523 fp = fopen(filename, "a");
524 if (!fp)
525 return error(_("cannot open %s: %s\n"), filename, strerror(errno));
527 if (raw_url)
528 url = transport_anonymize_url(raw_url);
529 else
530 url = xstrdup("foreign");
532 rm = ref_map;
533 if (check_everything_connected(iterate_ref_map, 0, &rm)) {
534 rc = error(_("%s did not send all necessary objects\n"), url);
535 goto abort;
539 * We do a pass for each fetch_head_status type in their enum order, so
540 * merged entries are written before not-for-merge. That lets readers
541 * use FETCH_HEAD as a refname to refer to the ref to be merged.
543 for (want_status = FETCH_HEAD_MERGE;
544 want_status <= FETCH_HEAD_IGNORE;
545 want_status++) {
546 for (rm = ref_map; rm; rm = rm->next) {
547 struct ref *ref = NULL;
548 const char *merge_status_marker = "";
550 commit = lookup_commit_reference_gently(rm->old_sha1, 1);
551 if (!commit)
552 rm->fetch_head_status = FETCH_HEAD_NOT_FOR_MERGE;
554 if (rm->fetch_head_status != want_status)
555 continue;
557 if (rm->peer_ref) {
558 ref = xcalloc(1, sizeof(*ref) + strlen(rm->peer_ref->name) + 1);
559 strcpy(ref->name, rm->peer_ref->name);
560 hashcpy(ref->old_sha1, rm->peer_ref->old_sha1);
561 hashcpy(ref->new_sha1, rm->old_sha1);
562 ref->force = rm->peer_ref->force;
566 if (!strcmp(rm->name, "HEAD")) {
567 kind = "";
568 what = "";
570 else if (!prefixcmp(rm->name, "refs/heads/")) {
571 kind = "branch";
572 what = rm->name + 11;
574 else if (!prefixcmp(rm->name, "refs/tags/")) {
575 kind = "tag";
576 what = rm->name + 10;
578 else if (!prefixcmp(rm->name, "refs/remotes/")) {
579 kind = "remote-tracking branch";
580 what = rm->name + 13;
582 else {
583 kind = "";
584 what = rm->name;
587 url_len = strlen(url);
588 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
590 url_len = i + 1;
591 if (4 < i && !strncmp(".git", url + i - 3, 4))
592 url_len = i - 3;
594 strbuf_reset(&note);
595 if (*what) {
596 if (*kind)
597 strbuf_addf(&note, "%s ", kind);
598 strbuf_addf(&note, "'%s' of ", what);
600 switch (rm->fetch_head_status) {
601 case FETCH_HEAD_NOT_FOR_MERGE:
602 merge_status_marker = "not-for-merge";
603 /* fall-through */
604 case FETCH_HEAD_MERGE:
605 fprintf(fp, "%s\t%s\t%s",
606 sha1_to_hex(rm->old_sha1),
607 merge_status_marker,
608 note.buf);
609 for (i = 0; i < url_len; ++i)
610 if ('\n' == url[i])
611 fputs("\\n", fp);
612 else
613 fputc(url[i], fp);
614 fputc('\n', fp);
615 break;
616 default:
617 /* do not write anything to FETCH_HEAD */
618 break;
621 strbuf_reset(&note);
622 if (ref) {
623 rc |= update_local_ref(ref, what, rm, &note);
624 free(ref);
625 } else
626 strbuf_addf(&note, "* %-*s %-*s -> FETCH_HEAD",
627 TRANSPORT_SUMMARY_WIDTH,
628 *kind ? kind : "branch",
629 REFCOL_WIDTH,
630 *what ? what : "HEAD");
631 if (note.len) {
632 if (verbosity >= 0 && !shown_url) {
633 fprintf(stderr, _("From %.*s\n"),
634 url_len, url);
635 shown_url = 1;
637 if (verbosity >= 0)
638 fprintf(stderr, " %s\n", note.buf);
643 if (rc & STORE_REF_ERROR_DF_CONFLICT)
644 error(_("some local refs could not be updated; try running\n"
645 " 'git remote prune %s' to remove any old, conflicting "
646 "branches"), remote_name);
648 abort:
649 strbuf_release(&note);
650 free(url);
651 fclose(fp);
652 return rc;
656 * We would want to bypass the object transfer altogether if
657 * everything we are going to fetch already exists and is connected
658 * locally.
660 static int quickfetch(struct ref *ref_map)
662 struct ref *rm = ref_map;
665 * If we are deepening a shallow clone we already have these
666 * objects reachable. Running rev-list here will return with
667 * a good (0) exit status and we'll bypass the fetch that we
668 * really need to perform. Claiming failure now will ensure
669 * we perform the network exchange to deepen our history.
671 if (depth)
672 return -1;
673 return check_everything_connected(iterate_ref_map, 1, &rm);
676 static int fetch_refs(struct transport *transport, struct ref *ref_map)
678 int ret = quickfetch(ref_map);
679 if (ret)
680 ret = transport_fetch_refs(transport, ref_map);
681 if (!ret)
682 ret |= store_updated_refs(transport->url,
683 transport->remote->name,
684 ref_map);
685 transport_unlock_pack(transport);
686 return ret;
689 static int prune_refs(struct refspec *refs, int ref_count, struct ref *ref_map)
691 int result = 0;
692 struct ref *ref, *stale_refs = get_stale_heads(refs, ref_count, ref_map);
693 const char *dangling_msg = dry_run
694 ? _(" (%s will become dangling)")
695 : _(" (%s has become dangling)");
697 for (ref = stale_refs; ref; ref = ref->next) {
698 if (!dry_run)
699 result |= delete_ref(ref->name, NULL, 0);
700 if (verbosity >= 0) {
701 fprintf(stderr, " x %-*s %-*s -> %s\n",
702 TRANSPORT_SUMMARY(_("[deleted]")),
703 REFCOL_WIDTH, _("(none)"), prettify_refname(ref->name));
704 warn_dangling_symref(stderr, dangling_msg, ref->name);
707 free_refs(stale_refs);
708 return result;
711 static void check_not_current_branch(struct ref *ref_map)
713 struct branch *current_branch = branch_get(NULL);
715 if (is_bare_repository() || !current_branch)
716 return;
718 for (; ref_map; ref_map = ref_map->next)
719 if (ref_map->peer_ref && !strcmp(current_branch->refname,
720 ref_map->peer_ref->name))
721 die(_("Refusing to fetch into current branch %s "
722 "of non-bare repository"), current_branch->refname);
725 static int truncate_fetch_head(void)
727 char *filename = git_path("FETCH_HEAD");
728 FILE *fp = fopen(filename, "w");
730 if (!fp)
731 return error(_("cannot open %s: %s\n"), filename, strerror(errno));
732 fclose(fp);
733 return 0;
736 static void set_option(struct transport *transport, const char *name, const char *value)
738 int r = transport_set_option(transport, name, value);
739 if (r < 0)
740 die(_("Option \"%s\" value \"%s\" is not valid for %s"),
741 name, value, transport->url);
742 if (r > 0)
743 warning(_("Option \"%s\" is ignored for %s\n"),
744 name, transport->url);
747 static struct transport *prepare_transport(struct remote *remote)
749 struct transport *transport;
750 transport = transport_get(remote, NULL);
751 transport_set_verbosity(transport, verbosity, progress);
752 if (upload_pack)
753 set_option(transport, TRANS_OPT_UPLOADPACK, upload_pack);
754 if (keep)
755 set_option(transport, TRANS_OPT_KEEP, "yes");
756 if (depth)
757 set_option(transport, TRANS_OPT_DEPTH, depth);
758 return transport;
761 static void backfill_tags(struct transport *transport, struct ref *ref_map)
763 if (transport->cannot_reuse) {
764 gsecondary = prepare_transport(transport->remote);
765 transport = gsecondary;
768 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
769 transport_set_option(transport, TRANS_OPT_DEPTH, "0");
770 fetch_refs(transport, ref_map);
772 if (gsecondary) {
773 transport_disconnect(gsecondary);
774 gsecondary = NULL;
778 static int do_fetch(struct transport *transport,
779 struct refspec *refs, int ref_count)
781 struct string_list existing_refs = STRING_LIST_INIT_DUP;
782 struct ref *ref_map;
783 struct ref *rm;
784 int autotags = (transport->remote->fetch_tags == 1);
785 int retcode = 0;
787 for_each_ref(add_existing, &existing_refs);
789 if (tags == TAGS_DEFAULT) {
790 if (transport->remote->fetch_tags == 2)
791 tags = TAGS_SET;
792 if (transport->remote->fetch_tags == -1)
793 tags = TAGS_UNSET;
796 if (!transport->get_refs_list || !transport->fetch)
797 die(_("Don't know how to fetch from %s"), transport->url);
799 /* if not appending, truncate FETCH_HEAD */
800 if (!append && !dry_run) {
801 retcode = truncate_fetch_head();
802 if (retcode)
803 goto cleanup;
806 ref_map = get_ref_map(transport, refs, ref_count, tags, &autotags);
807 if (!update_head_ok)
808 check_not_current_branch(ref_map);
810 for (rm = ref_map; rm; rm = rm->next) {
811 if (rm->peer_ref) {
812 struct string_list_item *peer_item =
813 string_list_lookup(&existing_refs,
814 rm->peer_ref->name);
815 if (peer_item)
816 hashcpy(rm->peer_ref->old_sha1,
817 peer_item->util);
821 if (tags == TAGS_DEFAULT && autotags)
822 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
823 if (fetch_refs(transport, ref_map)) {
824 free_refs(ref_map);
825 retcode = 1;
826 goto cleanup;
828 if (prune) {
830 * If --tags was specified, pretend that the user gave us
831 * the canonical tags refspec
833 if (tags == TAGS_SET) {
834 const char *tags_str = "refs/tags/*:refs/tags/*";
835 struct refspec *tags_refspec, *refspec;
837 /* Copy the refspec and add the tags to it */
838 refspec = xcalloc(ref_count + 1, sizeof(struct refspec));
839 tags_refspec = parse_fetch_refspec(1, &tags_str);
840 memcpy(refspec, refs, ref_count * sizeof(struct refspec));
841 memcpy(&refspec[ref_count], tags_refspec, sizeof(struct refspec));
842 ref_count++;
844 prune_refs(refspec, ref_count, ref_map);
846 ref_count--;
847 /* The rest of the strings belong to fetch_one */
848 free_refspec(1, tags_refspec);
849 free(refspec);
850 } else if (ref_count) {
851 prune_refs(refs, ref_count, ref_map);
852 } else {
853 prune_refs(transport->remote->fetch, transport->remote->fetch_refspec_nr, ref_map);
856 free_refs(ref_map);
858 /* if neither --no-tags nor --tags was specified, do automated tag
859 * following ... */
860 if (tags == TAGS_DEFAULT && autotags) {
861 struct ref **tail = &ref_map;
862 ref_map = NULL;
863 find_non_local_tags(transport, &ref_map, &tail);
864 if (ref_map)
865 backfill_tags(transport, ref_map);
866 free_refs(ref_map);
869 cleanup:
870 string_list_clear(&existing_refs, 1);
871 return retcode;
874 static int get_one_remote_for_fetch(struct remote *remote, void *priv)
876 struct string_list *list = priv;
877 if (!remote->skip_default_update)
878 string_list_append(list, remote->name);
879 return 0;
882 struct remote_group_data {
883 const char *name;
884 struct string_list *list;
887 static int get_remote_group(const char *key, const char *value, void *priv)
889 struct remote_group_data *g = priv;
891 if (!prefixcmp(key, "remotes.") &&
892 !strcmp(key + 8, g->name)) {
893 /* split list by white space */
894 int space = strcspn(value, " \t\n");
895 while (*value) {
896 if (space > 1) {
897 string_list_append(g->list,
898 xstrndup(value, space));
900 value += space + (value[space] != '\0');
901 space = strcspn(value, " \t\n");
905 return 0;
908 static int add_remote_or_group(const char *name, struct string_list *list)
910 int prev_nr = list->nr;
911 struct remote_group_data g;
912 g.name = name; g.list = list;
914 git_config(get_remote_group, &g);
915 if (list->nr == prev_nr) {
916 struct remote *remote;
917 if (!remote_is_configured(name))
918 return 0;
919 remote = remote_get(name);
920 string_list_append(list, remote->name);
922 return 1;
925 static void add_options_to_argv(struct argv_array *argv)
927 if (dry_run)
928 argv_array_push(argv, "--dry-run");
929 if (prune > 0)
930 argv_array_push(argv, "--prune");
931 if (update_head_ok)
932 argv_array_push(argv, "--update-head-ok");
933 if (force)
934 argv_array_push(argv, "--force");
935 if (keep)
936 argv_array_push(argv, "--keep");
937 if (recurse_submodules == RECURSE_SUBMODULES_ON)
938 argv_array_push(argv, "--recurse-submodules");
939 else if (recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND)
940 argv_array_push(argv, "--recurse-submodules=on-demand");
941 if (tags == TAGS_SET)
942 argv_array_push(argv, "--tags");
943 else if (tags == TAGS_UNSET)
944 argv_array_push(argv, "--no-tags");
945 if (verbosity >= 2)
946 argv_array_push(argv, "-v");
947 if (verbosity >= 1)
948 argv_array_push(argv, "-v");
949 else if (verbosity < 0)
950 argv_array_push(argv, "-q");
954 static int fetch_multiple(struct string_list *list)
956 int i, result = 0;
957 struct argv_array argv = ARGV_ARRAY_INIT;
959 if (!append && !dry_run) {
960 int errcode = truncate_fetch_head();
961 if (errcode)
962 return errcode;
965 argv_array_pushl(&argv, "fetch", "--append", NULL);
966 add_options_to_argv(&argv);
968 for (i = 0; i < list->nr; i++) {
969 const char *name = list->items[i].string;
970 argv_array_push(&argv, name);
971 if (verbosity >= 0)
972 printf(_("Fetching %s\n"), name);
973 if (run_command_v_opt(argv.argv, RUN_GIT_CMD)) {
974 error(_("Could not fetch %s"), name);
975 result = 1;
977 argv_array_pop(&argv);
980 argv_array_clear(&argv);
981 return result;
984 static int fetch_one(struct remote *remote, int argc, const char **argv)
986 int i;
987 static const char **refs = NULL;
988 struct refspec *refspec;
989 int ref_nr = 0;
990 int exit_code;
992 if (!remote)
993 die(_("No remote repository specified. Please, specify either a URL or a\n"
994 "remote name from which new revisions should be fetched."));
996 gtransport = prepare_transport(remote);
998 if (prune < 0) {
999 /* no command line request */
1000 if (0 <= gtransport->remote->prune)
1001 prune = gtransport->remote->prune;
1002 else if (0 <= fetch_prune_config)
1003 prune = fetch_prune_config;
1004 else
1005 prune = PRUNE_BY_DEFAULT;
1008 if (argc > 0) {
1009 int j = 0;
1010 refs = xcalloc(argc + 1, sizeof(const char *));
1011 for (i = 0; i < argc; i++) {
1012 if (!strcmp(argv[i], "tag")) {
1013 char *ref;
1014 i++;
1015 if (i >= argc)
1016 die(_("You need to specify a tag name."));
1017 ref = xmalloc(strlen(argv[i]) * 2 + 22);
1018 strcpy(ref, "refs/tags/");
1019 strcat(ref, argv[i]);
1020 strcat(ref, ":refs/tags/");
1021 strcat(ref, argv[i]);
1022 refs[j++] = ref;
1023 } else
1024 refs[j++] = argv[i];
1026 refs[j] = NULL;
1027 ref_nr = j;
1030 sigchain_push_common(unlock_pack_on_signal);
1031 atexit(unlock_pack);
1032 refspec = parse_fetch_refspec(ref_nr, refs);
1033 exit_code = do_fetch(gtransport, refspec, ref_nr);
1034 free_refspec(ref_nr, refspec);
1035 transport_disconnect(gtransport);
1036 gtransport = NULL;
1037 return exit_code;
1040 int cmd_fetch(int argc, const char **argv, const char *prefix)
1042 int i;
1043 struct string_list list = STRING_LIST_INIT_NODUP;
1044 struct remote *remote;
1045 int result = 0;
1046 static const char *argv_gc_auto[] = {
1047 "gc", "--auto", NULL,
1050 packet_trace_identity("fetch");
1052 /* Record the command line for the reflog */
1053 strbuf_addstr(&default_rla, "fetch");
1054 for (i = 1; i < argc; i++)
1055 strbuf_addf(&default_rla, " %s", argv[i]);
1057 git_config(git_fetch_config, NULL);
1059 argc = parse_options(argc, argv, prefix,
1060 builtin_fetch_options, builtin_fetch_usage, 0);
1062 if (unshallow) {
1063 if (depth)
1064 die(_("--depth and --unshallow cannot be used together"));
1065 else if (!is_repository_shallow())
1066 die(_("--unshallow on a complete repository does not make sense"));
1067 else {
1068 static char inf_depth[12];
1069 sprintf(inf_depth, "%d", INFINITE_DEPTH);
1070 depth = inf_depth;
1074 if (recurse_submodules != RECURSE_SUBMODULES_OFF) {
1075 if (recurse_submodules_default) {
1076 int arg = parse_fetch_recurse_submodules_arg("--recurse-submodules-default", recurse_submodules_default);
1077 set_config_fetch_recurse_submodules(arg);
1079 gitmodules_config();
1080 git_config(submodule_config, NULL);
1083 if (all) {
1084 if (argc == 1)
1085 die(_("fetch --all does not take a repository argument"));
1086 else if (argc > 1)
1087 die(_("fetch --all does not make sense with refspecs"));
1088 (void) for_each_remote(get_one_remote_for_fetch, &list);
1089 result = fetch_multiple(&list);
1090 } else if (argc == 0) {
1091 /* No arguments -- use default remote */
1092 remote = remote_get(NULL);
1093 result = fetch_one(remote, argc, argv);
1094 } else if (multiple) {
1095 /* All arguments are assumed to be remotes or groups */
1096 for (i = 0; i < argc; i++)
1097 if (!add_remote_or_group(argv[i], &list))
1098 die(_("No such remote or remote group: %s"), argv[i]);
1099 result = fetch_multiple(&list);
1100 } else {
1101 /* Single remote or group */
1102 (void) add_remote_or_group(argv[0], &list);
1103 if (list.nr > 1) {
1104 /* More than one remote */
1105 if (argc > 1)
1106 die(_("Fetching a group and specifying refspecs does not make sense"));
1107 result = fetch_multiple(&list);
1108 } else {
1109 /* Zero or one remotes */
1110 remote = remote_get(argv[0]);
1111 result = fetch_one(remote, argc-1, argv+1);
1115 if (!result && (recurse_submodules != RECURSE_SUBMODULES_OFF)) {
1116 struct argv_array options = ARGV_ARRAY_INIT;
1118 add_options_to_argv(&options);
1119 result = fetch_populated_submodules(&options,
1120 submodule_prefix,
1121 recurse_submodules,
1122 verbosity < 0);
1123 argv_array_clear(&options);
1126 /* All names were strdup()ed or strndup()ed */
1127 list.strdup_strings = 1;
1128 string_list_clear(&list, 0);
1130 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
1132 return result;