connect & http: support -4 and -6 switches for remote operations
[git.git] / builtin / fetch.c
blob89b71a8f852780dddd902a519d1183608040fe47
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 "submodule-config.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, update_shallow;
40 static enum transport_family family;
41 static const char *depth;
42 static const char *upload_pack;
43 static struct strbuf default_rla = STRBUF_INIT;
44 static struct transport *gtransport;
45 static struct transport *gsecondary;
46 static const char *submodule_prefix = "";
47 static const char *recurse_submodules_default;
48 static int shown_url = 0;
49 static int refmap_alloc, refmap_nr;
50 static const char **refmap_array;
52 static int option_parse_recurse_submodules(const struct option *opt,
53 const char *arg, int unset)
55 if (unset) {
56 recurse_submodules = RECURSE_SUBMODULES_OFF;
57 } else {
58 if (arg)
59 recurse_submodules = parse_fetch_recurse_submodules_arg(opt->long_name, arg);
60 else
61 recurse_submodules = RECURSE_SUBMODULES_ON;
63 return 0;
66 static int git_fetch_config(const char *k, const char *v, void *cb)
68 if (!strcmp(k, "fetch.prune")) {
69 fetch_prune_config = git_config_bool(k, v);
70 return 0;
72 return git_default_config(k, v, cb);
75 static int parse_refmap_arg(const struct option *opt, const char *arg, int unset)
77 ALLOC_GROW(refmap_array, refmap_nr + 1, refmap_alloc);
80 * "git fetch --refmap='' origin foo"
81 * can be used to tell the command not to store anywhere
83 if (*arg)
84 refmap_array[refmap_nr++] = arg;
85 return 0;
88 static struct option builtin_fetch_options[] = {
89 OPT__VERBOSITY(&verbosity),
90 OPT_BOOL(0, "all", &all,
91 N_("fetch from all remotes")),
92 OPT_BOOL('a', "append", &append,
93 N_("append to .git/FETCH_HEAD instead of overwriting")),
94 OPT_STRING(0, "upload-pack", &upload_pack, N_("path"),
95 N_("path to upload pack on remote end")),
96 OPT__FORCE(&force, N_("force overwrite of local branch")),
97 OPT_BOOL('m', "multiple", &multiple,
98 N_("fetch from multiple remotes")),
99 OPT_SET_INT('t', "tags", &tags,
100 N_("fetch all tags and associated objects"), TAGS_SET),
101 OPT_SET_INT('n', NULL, &tags,
102 N_("do not fetch all tags (--no-tags)"), TAGS_UNSET),
103 OPT_BOOL('p', "prune", &prune,
104 N_("prune remote-tracking branches no longer on remote")),
105 { OPTION_CALLBACK, 0, "recurse-submodules", NULL, N_("on-demand"),
106 N_("control recursive fetching of submodules"),
107 PARSE_OPT_OPTARG, option_parse_recurse_submodules },
108 OPT_BOOL(0, "dry-run", &dry_run,
109 N_("dry run")),
110 OPT_BOOL('k', "keep", &keep, N_("keep downloaded pack")),
111 OPT_BOOL('u', "update-head-ok", &update_head_ok,
112 N_("allow updating of HEAD ref")),
113 OPT_BOOL(0, "progress", &progress, N_("force progress reporting")),
114 OPT_STRING(0, "depth", &depth, N_("depth"),
115 N_("deepen history of shallow clone")),
116 { OPTION_SET_INT, 0, "unshallow", &unshallow, NULL,
117 N_("convert to a complete repository"),
118 PARSE_OPT_NONEG | PARSE_OPT_NOARG, NULL, 1 },
119 { OPTION_STRING, 0, "submodule-prefix", &submodule_prefix, N_("dir"),
120 N_("prepend this to submodule path output"), PARSE_OPT_HIDDEN },
121 { OPTION_STRING, 0, "recurse-submodules-default",
122 &recurse_submodules_default, NULL,
123 N_("default mode for recursion"), PARSE_OPT_HIDDEN },
124 OPT_BOOL(0, "update-shallow", &update_shallow,
125 N_("accept refs that update .git/shallow")),
126 { OPTION_CALLBACK, 0, "refmap", NULL, N_("refmap"),
127 N_("specify fetch refmap"), PARSE_OPT_NONEG, parse_refmap_arg },
128 OPT_SET_INT('4', "ipv4", &family, N_("use IPv4 addresses only"),
129 TRANSPORT_FAMILY_IPV4),
130 OPT_SET_INT('6', "ipv6", &family, N_("use IPv6 addresses only"),
131 TRANSPORT_FAMILY_IPV6),
132 OPT_END()
135 static void unlock_pack(void)
137 if (gtransport)
138 transport_unlock_pack(gtransport);
139 if (gsecondary)
140 transport_unlock_pack(gsecondary);
143 static void unlock_pack_on_signal(int signo)
145 unlock_pack();
146 sigchain_pop(signo);
147 raise(signo);
150 static void add_merge_config(struct ref **head,
151 const struct ref *remote_refs,
152 struct branch *branch,
153 struct ref ***tail)
155 int i;
157 for (i = 0; i < branch->merge_nr; i++) {
158 struct ref *rm, **old_tail = *tail;
159 struct refspec refspec;
161 for (rm = *head; rm; rm = rm->next) {
162 if (branch_merge_matches(branch, i, rm->name)) {
163 rm->fetch_head_status = FETCH_HEAD_MERGE;
164 break;
167 if (rm)
168 continue;
171 * Not fetched to a remote-tracking branch? We need to fetch
172 * it anyway to allow this branch's "branch.$name.merge"
173 * to be honored by 'git pull', but we do not have to
174 * fail if branch.$name.merge is misconfigured to point
175 * at a nonexisting branch. If we were indeed called by
176 * 'git pull', it will notice the misconfiguration because
177 * there is no entry in the resulting FETCH_HEAD marked
178 * for merging.
180 memset(&refspec, 0, sizeof(refspec));
181 refspec.src = branch->merge[i]->src;
182 get_fetch_map(remote_refs, &refspec, tail, 1);
183 for (rm = *old_tail; rm; rm = rm->next)
184 rm->fetch_head_status = FETCH_HEAD_MERGE;
188 static int add_existing(const char *refname, const struct object_id *oid,
189 int flag, void *cbdata)
191 struct string_list *list = (struct string_list *)cbdata;
192 struct string_list_item *item = string_list_insert(list, refname);
193 struct object_id *old_oid = xmalloc(sizeof(*old_oid));
195 oidcpy(old_oid, oid);
196 item->util = old_oid;
197 return 0;
200 static int will_fetch(struct ref **head, const unsigned char *sha1)
202 struct ref *rm = *head;
203 while (rm) {
204 if (!hashcmp(rm->old_oid.hash, sha1))
205 return 1;
206 rm = rm->next;
208 return 0;
211 static void find_non_local_tags(struct transport *transport,
212 struct ref **head,
213 struct ref ***tail)
215 struct string_list existing_refs = STRING_LIST_INIT_DUP;
216 struct string_list remote_refs = STRING_LIST_INIT_NODUP;
217 const struct ref *ref;
218 struct string_list_item *item = NULL;
220 for_each_ref(add_existing, &existing_refs);
221 for (ref = transport_get_remote_refs(transport); ref; ref = ref->next) {
222 if (!starts_with(ref->name, "refs/tags/"))
223 continue;
226 * The peeled ref always follows the matching base
227 * ref, so if we see a peeled ref that we don't want
228 * to fetch then we can mark the ref entry in the list
229 * as one to ignore by setting util to NULL.
231 if (ends_with(ref->name, "^{}")) {
232 if (item && !has_object_file(&ref->old_oid) &&
233 !will_fetch(head, ref->old_oid.hash) &&
234 !has_sha1_file(item->util) &&
235 !will_fetch(head, item->util))
236 item->util = NULL;
237 item = NULL;
238 continue;
242 * If item is non-NULL here, then we previously saw a
243 * ref not followed by a peeled reference, so we need
244 * to check if it is a lightweight tag that we want to
245 * fetch.
247 if (item && !has_sha1_file(item->util) &&
248 !will_fetch(head, item->util))
249 item->util = NULL;
251 item = NULL;
253 /* skip duplicates and refs that we already have */
254 if (string_list_has_string(&remote_refs, ref->name) ||
255 string_list_has_string(&existing_refs, ref->name))
256 continue;
258 item = string_list_insert(&remote_refs, ref->name);
259 item->util = (void *)&ref->old_oid;
261 string_list_clear(&existing_refs, 1);
264 * We may have a final lightweight tag that needs to be
265 * checked to see if it needs fetching.
267 if (item && !has_sha1_file(item->util) &&
268 !will_fetch(head, item->util))
269 item->util = NULL;
272 * For all the tags in the remote_refs string list,
273 * add them to the list of refs to be fetched
275 for_each_string_list_item(item, &remote_refs) {
276 /* Unless we have already decided to ignore this item... */
277 if (item->util)
279 struct ref *rm = alloc_ref(item->string);
280 rm->peer_ref = alloc_ref(item->string);
281 oidcpy(&rm->old_oid, item->util);
282 **tail = rm;
283 *tail = &rm->next;
287 string_list_clear(&remote_refs, 0);
290 static struct ref *get_ref_map(struct transport *transport,
291 struct refspec *refspecs, int refspec_count,
292 int tags, int *autotags)
294 int i;
295 struct ref *rm;
296 struct ref *ref_map = NULL;
297 struct ref **tail = &ref_map;
299 /* opportunistically-updated references: */
300 struct ref *orefs = NULL, **oref_tail = &orefs;
302 const struct ref *remote_refs = transport_get_remote_refs(transport);
304 if (refspec_count) {
305 struct refspec *fetch_refspec;
306 int fetch_refspec_nr;
308 for (i = 0; i < refspec_count; i++) {
309 get_fetch_map(remote_refs, &refspecs[i], &tail, 0);
310 if (refspecs[i].dst && refspecs[i].dst[0])
311 *autotags = 1;
313 /* Merge everything on the command line (but not --tags) */
314 for (rm = ref_map; rm; rm = rm->next)
315 rm->fetch_head_status = FETCH_HEAD_MERGE;
318 * For any refs that we happen to be fetching via
319 * command-line arguments, the destination ref might
320 * have been missing or have been different than the
321 * remote-tracking ref that would be derived from the
322 * configured refspec. In these cases, we want to
323 * take the opportunity to update their configured
324 * remote-tracking reference. However, we do not want
325 * to mention these entries in FETCH_HEAD at all, as
326 * they would simply be duplicates of existing
327 * entries, so we set them FETCH_HEAD_IGNORE below.
329 * We compute these entries now, based only on the
330 * refspecs specified on the command line. But we add
331 * them to the list following the refspecs resulting
332 * from the tags option so that one of the latter,
333 * which has FETCH_HEAD_NOT_FOR_MERGE, is not removed
334 * by ref_remove_duplicates() in favor of one of these
335 * opportunistic entries with FETCH_HEAD_IGNORE.
337 if (refmap_array) {
338 fetch_refspec = parse_fetch_refspec(refmap_nr, refmap_array);
339 fetch_refspec_nr = refmap_nr;
340 } else {
341 fetch_refspec = transport->remote->fetch;
342 fetch_refspec_nr = transport->remote->fetch_refspec_nr;
345 for (i = 0; i < fetch_refspec_nr; i++)
346 get_fetch_map(ref_map, &fetch_refspec[i], &oref_tail, 1);
348 if (tags == TAGS_SET)
349 get_fetch_map(remote_refs, tag_refspec, &tail, 0);
350 } else if (refmap_array) {
351 die("--refmap option is only meaningful with command-line refspec(s).");
352 } else {
353 /* Use the defaults */
354 struct remote *remote = transport->remote;
355 struct branch *branch = branch_get(NULL);
356 int has_merge = branch_has_merge_config(branch);
357 if (remote &&
358 (remote->fetch_refspec_nr ||
359 /* Note: has_merge implies non-NULL branch->remote_name */
360 (has_merge && !strcmp(branch->remote_name, remote->name)))) {
361 for (i = 0; i < remote->fetch_refspec_nr; i++) {
362 get_fetch_map(remote_refs, &remote->fetch[i], &tail, 0);
363 if (remote->fetch[i].dst &&
364 remote->fetch[i].dst[0])
365 *autotags = 1;
366 if (!i && !has_merge && ref_map &&
367 !remote->fetch[0].pattern)
368 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
371 * if the remote we're fetching from is the same
372 * as given in branch.<name>.remote, we add the
373 * ref given in branch.<name>.merge, too.
375 * Note: has_merge implies non-NULL branch->remote_name
377 if (has_merge &&
378 !strcmp(branch->remote_name, remote->name))
379 add_merge_config(&ref_map, remote_refs, branch, &tail);
380 } else {
381 ref_map = get_remote_ref(remote_refs, "HEAD");
382 if (!ref_map)
383 die(_("Couldn't find remote ref HEAD"));
384 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
385 tail = &ref_map->next;
389 if (tags == TAGS_SET)
390 /* also fetch all tags */
391 get_fetch_map(remote_refs, tag_refspec, &tail, 0);
392 else if (tags == TAGS_DEFAULT && *autotags)
393 find_non_local_tags(transport, &ref_map, &tail);
395 /* Now append any refs to be updated opportunistically: */
396 *tail = orefs;
397 for (rm = orefs; rm; rm = rm->next) {
398 rm->fetch_head_status = FETCH_HEAD_IGNORE;
399 tail = &rm->next;
402 return ref_remove_duplicates(ref_map);
405 #define STORE_REF_ERROR_OTHER 1
406 #define STORE_REF_ERROR_DF_CONFLICT 2
408 static int s_update_ref(const char *action,
409 struct ref *ref,
410 int check_old)
412 char msg[1024];
413 char *rla = getenv("GIT_REFLOG_ACTION");
414 struct ref_transaction *transaction;
415 struct strbuf err = STRBUF_INIT;
416 int ret, df_conflict = 0;
418 if (dry_run)
419 return 0;
420 if (!rla)
421 rla = default_rla.buf;
422 snprintf(msg, sizeof(msg), "%s: %s", rla, action);
424 transaction = ref_transaction_begin(&err);
425 if (!transaction ||
426 ref_transaction_update(transaction, ref->name,
427 ref->new_oid.hash,
428 check_old ? ref->old_oid.hash : NULL,
429 0, msg, &err))
430 goto fail;
432 ret = ref_transaction_commit(transaction, &err);
433 if (ret) {
434 df_conflict = (ret == TRANSACTION_NAME_CONFLICT);
435 goto fail;
438 ref_transaction_free(transaction);
439 strbuf_release(&err);
440 return 0;
441 fail:
442 ref_transaction_free(transaction);
443 error("%s", err.buf);
444 strbuf_release(&err);
445 return df_conflict ? STORE_REF_ERROR_DF_CONFLICT
446 : STORE_REF_ERROR_OTHER;
449 #define REFCOL_WIDTH 10
451 static int update_local_ref(struct ref *ref,
452 const char *remote,
453 const struct ref *remote_ref,
454 struct strbuf *display)
456 struct commit *current = NULL, *updated;
457 enum object_type type;
458 struct branch *current_branch = branch_get(NULL);
459 const char *pretty_ref = prettify_refname(ref->name);
461 type = sha1_object_info(ref->new_oid.hash, NULL);
462 if (type < 0)
463 die(_("object %s not found"), oid_to_hex(&ref->new_oid));
465 if (!oidcmp(&ref->old_oid, &ref->new_oid)) {
466 if (verbosity > 0)
467 strbuf_addf(display, "= %-*s %-*s -> %s",
468 TRANSPORT_SUMMARY(_("[up to date]")),
469 REFCOL_WIDTH, remote, pretty_ref);
470 return 0;
473 if (current_branch &&
474 !strcmp(ref->name, current_branch->name) &&
475 !(update_head_ok || is_bare_repository()) &&
476 !is_null_oid(&ref->old_oid)) {
478 * If this is the head, and it's not okay to update
479 * the head, and the old value of the head isn't empty...
481 strbuf_addf(display,
482 _("! %-*s %-*s -> %s (can't fetch in current branch)"),
483 TRANSPORT_SUMMARY(_("[rejected]")),
484 REFCOL_WIDTH, remote, pretty_ref);
485 return 1;
488 if (!is_null_oid(&ref->old_oid) &&
489 starts_with(ref->name, "refs/tags/")) {
490 int r;
491 r = s_update_ref("updating tag", ref, 0);
492 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
493 r ? '!' : '-',
494 TRANSPORT_SUMMARY(_("[tag update]")),
495 REFCOL_WIDTH, remote, pretty_ref,
496 r ? _(" (unable to update local ref)") : "");
497 return r;
500 current = lookup_commit_reference_gently(ref->old_oid.hash, 1);
501 updated = lookup_commit_reference_gently(ref->new_oid.hash, 1);
502 if (!current || !updated) {
503 const char *msg;
504 const char *what;
505 int r;
507 * Nicely describe the new ref we're fetching.
508 * Base this on the remote's ref name, as it's
509 * more likely to follow a standard layout.
511 const char *name = remote_ref ? remote_ref->name : "";
512 if (starts_with(name, "refs/tags/")) {
513 msg = "storing tag";
514 what = _("[new tag]");
515 } else if (starts_with(name, "refs/heads/")) {
516 msg = "storing head";
517 what = _("[new branch]");
518 } else {
519 msg = "storing ref";
520 what = _("[new ref]");
523 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
524 (recurse_submodules != RECURSE_SUBMODULES_ON))
525 check_for_new_submodule_commits(ref->new_oid.hash);
526 r = s_update_ref(msg, ref, 0);
527 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
528 r ? '!' : '*',
529 TRANSPORT_SUMMARY(what),
530 REFCOL_WIDTH, remote, pretty_ref,
531 r ? _(" (unable to update local ref)") : "");
532 return r;
535 if (in_merge_bases(current, updated)) {
536 struct strbuf quickref = STRBUF_INIT;
537 int r;
538 strbuf_add_unique_abbrev(&quickref, current->object.oid.hash, DEFAULT_ABBREV);
539 strbuf_addstr(&quickref, "..");
540 strbuf_add_unique_abbrev(&quickref, ref->new_oid.hash, DEFAULT_ABBREV);
541 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
542 (recurse_submodules != RECURSE_SUBMODULES_ON))
543 check_for_new_submodule_commits(ref->new_oid.hash);
544 r = s_update_ref("fast-forward", ref, 1);
545 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
546 r ? '!' : ' ',
547 TRANSPORT_SUMMARY_WIDTH, quickref.buf,
548 REFCOL_WIDTH, remote, pretty_ref,
549 r ? _(" (unable to update local ref)") : "");
550 strbuf_release(&quickref);
551 return r;
552 } else if (force || ref->force) {
553 struct strbuf quickref = STRBUF_INIT;
554 int r;
555 strbuf_add_unique_abbrev(&quickref, current->object.oid.hash, DEFAULT_ABBREV);
556 strbuf_addstr(&quickref, "...");
557 strbuf_add_unique_abbrev(&quickref, ref->new_oid.hash, DEFAULT_ABBREV);
558 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
559 (recurse_submodules != RECURSE_SUBMODULES_ON))
560 check_for_new_submodule_commits(ref->new_oid.hash);
561 r = s_update_ref("forced-update", ref, 1);
562 strbuf_addf(display, "%c %-*s %-*s -> %s (%s)",
563 r ? '!' : '+',
564 TRANSPORT_SUMMARY_WIDTH, quickref.buf,
565 REFCOL_WIDTH, remote, pretty_ref,
566 r ? _("unable to update local ref") : _("forced update"));
567 strbuf_release(&quickref);
568 return r;
569 } else {
570 strbuf_addf(display, "! %-*s %-*s -> %s %s",
571 TRANSPORT_SUMMARY(_("[rejected]")),
572 REFCOL_WIDTH, remote, pretty_ref,
573 _("(non-fast-forward)"));
574 return 1;
578 static int iterate_ref_map(void *cb_data, unsigned char sha1[20])
580 struct ref **rm = cb_data;
581 struct ref *ref = *rm;
583 while (ref && ref->status == REF_STATUS_REJECT_SHALLOW)
584 ref = ref->next;
585 if (!ref)
586 return -1; /* end of the list */
587 *rm = ref->next;
588 hashcpy(sha1, ref->old_oid.hash);
589 return 0;
592 static int store_updated_refs(const char *raw_url, const char *remote_name,
593 struct ref *ref_map)
595 FILE *fp;
596 struct commit *commit;
597 int url_len, i, rc = 0;
598 struct strbuf note = STRBUF_INIT;
599 const char *what, *kind;
600 struct ref *rm;
601 char *url;
602 const char *filename = dry_run ? "/dev/null" : git_path_fetch_head();
603 int want_status;
605 fp = fopen(filename, "a");
606 if (!fp)
607 return error(_("cannot open %s: %s\n"), filename, strerror(errno));
609 if (raw_url)
610 url = transport_anonymize_url(raw_url);
611 else
612 url = xstrdup("foreign");
614 rm = ref_map;
615 if (check_everything_connected(iterate_ref_map, 0, &rm)) {
616 rc = error(_("%s did not send all necessary objects\n"), url);
617 goto abort;
621 * We do a pass for each fetch_head_status type in their enum order, so
622 * merged entries are written before not-for-merge. That lets readers
623 * use FETCH_HEAD as a refname to refer to the ref to be merged.
625 for (want_status = FETCH_HEAD_MERGE;
626 want_status <= FETCH_HEAD_IGNORE;
627 want_status++) {
628 for (rm = ref_map; rm; rm = rm->next) {
629 struct ref *ref = NULL;
630 const char *merge_status_marker = "";
632 if (rm->status == REF_STATUS_REJECT_SHALLOW) {
633 if (want_status == FETCH_HEAD_MERGE)
634 warning(_("reject %s because shallow roots are not allowed to be updated"),
635 rm->peer_ref ? rm->peer_ref->name : rm->name);
636 continue;
639 commit = lookup_commit_reference_gently(rm->old_oid.hash, 1);
640 if (!commit)
641 rm->fetch_head_status = FETCH_HEAD_NOT_FOR_MERGE;
643 if (rm->fetch_head_status != want_status)
644 continue;
646 if (rm->peer_ref) {
647 ref = alloc_ref(rm->peer_ref->name);
648 oidcpy(&ref->old_oid, &rm->peer_ref->old_oid);
649 oidcpy(&ref->new_oid, &rm->old_oid);
650 ref->force = rm->peer_ref->force;
654 if (!strcmp(rm->name, "HEAD")) {
655 kind = "";
656 what = "";
658 else if (starts_with(rm->name, "refs/heads/")) {
659 kind = "branch";
660 what = rm->name + 11;
662 else if (starts_with(rm->name, "refs/tags/")) {
663 kind = "tag";
664 what = rm->name + 10;
666 else if (starts_with(rm->name, "refs/remotes/")) {
667 kind = "remote-tracking branch";
668 what = rm->name + 13;
670 else {
671 kind = "";
672 what = rm->name;
675 url_len = strlen(url);
676 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
678 url_len = i + 1;
679 if (4 < i && !strncmp(".git", url + i - 3, 4))
680 url_len = i - 3;
682 strbuf_reset(&note);
683 if (*what) {
684 if (*kind)
685 strbuf_addf(&note, "%s ", kind);
686 strbuf_addf(&note, "'%s' of ", what);
688 switch (rm->fetch_head_status) {
689 case FETCH_HEAD_NOT_FOR_MERGE:
690 merge_status_marker = "not-for-merge";
691 /* fall-through */
692 case FETCH_HEAD_MERGE:
693 fprintf(fp, "%s\t%s\t%s",
694 oid_to_hex(&rm->old_oid),
695 merge_status_marker,
696 note.buf);
697 for (i = 0; i < url_len; ++i)
698 if ('\n' == url[i])
699 fputs("\\n", fp);
700 else
701 fputc(url[i], fp);
702 fputc('\n', fp);
703 break;
704 default:
705 /* do not write anything to FETCH_HEAD */
706 break;
709 strbuf_reset(&note);
710 if (ref) {
711 rc |= update_local_ref(ref, what, rm, &note);
712 free(ref);
713 } else
714 strbuf_addf(&note, "* %-*s %-*s -> FETCH_HEAD",
715 TRANSPORT_SUMMARY_WIDTH,
716 *kind ? kind : "branch",
717 REFCOL_WIDTH,
718 *what ? what : "HEAD");
719 if (note.len) {
720 if (verbosity >= 0 && !shown_url) {
721 fprintf(stderr, _("From %.*s\n"),
722 url_len, url);
723 shown_url = 1;
725 if (verbosity >= 0)
726 fprintf(stderr, " %s\n", note.buf);
731 if (rc & STORE_REF_ERROR_DF_CONFLICT)
732 error(_("some local refs could not be updated; try running\n"
733 " 'git remote prune %s' to remove any old, conflicting "
734 "branches"), remote_name);
736 abort:
737 strbuf_release(&note);
738 free(url);
739 fclose(fp);
740 return rc;
744 * We would want to bypass the object transfer altogether if
745 * everything we are going to fetch already exists and is connected
746 * locally.
748 static int quickfetch(struct ref *ref_map)
750 struct ref *rm = ref_map;
753 * If we are deepening a shallow clone we already have these
754 * objects reachable. Running rev-list here will return with
755 * a good (0) exit status and we'll bypass the fetch that we
756 * really need to perform. Claiming failure now will ensure
757 * we perform the network exchange to deepen our history.
759 if (depth)
760 return -1;
761 return check_everything_connected(iterate_ref_map, 1, &rm);
764 static int fetch_refs(struct transport *transport, struct ref *ref_map)
766 int ret = quickfetch(ref_map);
767 if (ret)
768 ret = transport_fetch_refs(transport, ref_map);
769 if (!ret)
770 ret |= store_updated_refs(transport->url,
771 transport->remote->name,
772 ref_map);
773 transport_unlock_pack(transport);
774 return ret;
777 static int prune_refs(struct refspec *refs, int ref_count, struct ref *ref_map,
778 const char *raw_url)
780 int url_len, i, result = 0;
781 struct ref *ref, *stale_refs = get_stale_heads(refs, ref_count, ref_map);
782 char *url;
783 const char *dangling_msg = dry_run
784 ? _(" (%s will become dangling)")
785 : _(" (%s has become dangling)");
787 if (raw_url)
788 url = transport_anonymize_url(raw_url);
789 else
790 url = xstrdup("foreign");
792 url_len = strlen(url);
793 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
796 url_len = i + 1;
797 if (4 < i && !strncmp(".git", url + i - 3, 4))
798 url_len = i - 3;
800 if (!dry_run) {
801 struct string_list refnames = STRING_LIST_INIT_NODUP;
803 for (ref = stale_refs; ref; ref = ref->next)
804 string_list_append(&refnames, ref->name);
806 result = delete_refs(&refnames);
807 string_list_clear(&refnames, 0);
810 if (verbosity >= 0) {
811 for (ref = stale_refs; ref; ref = ref->next) {
812 if (!shown_url) {
813 fprintf(stderr, _("From %.*s\n"), url_len, url);
814 shown_url = 1;
816 fprintf(stderr, " x %-*s %-*s -> %s\n",
817 TRANSPORT_SUMMARY(_("[deleted]")),
818 REFCOL_WIDTH, _("(none)"), prettify_refname(ref->name));
819 warn_dangling_symref(stderr, dangling_msg, ref->name);
823 free(url);
824 free_refs(stale_refs);
825 return result;
828 static void check_not_current_branch(struct ref *ref_map)
830 struct branch *current_branch = branch_get(NULL);
832 if (is_bare_repository() || !current_branch)
833 return;
835 for (; ref_map; ref_map = ref_map->next)
836 if (ref_map->peer_ref && !strcmp(current_branch->refname,
837 ref_map->peer_ref->name))
838 die(_("Refusing to fetch into current branch %s "
839 "of non-bare repository"), current_branch->refname);
842 static int truncate_fetch_head(void)
844 const char *filename = git_path_fetch_head();
845 FILE *fp = fopen(filename, "w");
847 if (!fp)
848 return error(_("cannot open %s: %s\n"), filename, strerror(errno));
849 fclose(fp);
850 return 0;
853 static void set_option(struct transport *transport, const char *name, const char *value)
855 int r = transport_set_option(transport, name, value);
856 if (r < 0)
857 die(_("Option \"%s\" value \"%s\" is not valid for %s"),
858 name, value, transport->url);
859 if (r > 0)
860 warning(_("Option \"%s\" is ignored for %s\n"),
861 name, transport->url);
864 static struct transport *prepare_transport(struct remote *remote)
866 struct transport *transport;
867 transport = transport_get(remote, NULL);
868 transport_set_verbosity(transport, verbosity, progress);
869 transport->family = family;
870 if (upload_pack)
871 set_option(transport, TRANS_OPT_UPLOADPACK, upload_pack);
872 if (keep)
873 set_option(transport, TRANS_OPT_KEEP, "yes");
874 if (depth)
875 set_option(transport, TRANS_OPT_DEPTH, depth);
876 if (update_shallow)
877 set_option(transport, TRANS_OPT_UPDATE_SHALLOW, "yes");
878 return transport;
881 static void backfill_tags(struct transport *transport, struct ref *ref_map)
883 if (transport->cannot_reuse) {
884 gsecondary = prepare_transport(transport->remote);
885 transport = gsecondary;
888 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
889 transport_set_option(transport, TRANS_OPT_DEPTH, "0");
890 fetch_refs(transport, ref_map);
892 if (gsecondary) {
893 transport_disconnect(gsecondary);
894 gsecondary = NULL;
898 static int do_fetch(struct transport *transport,
899 struct refspec *refs, int ref_count)
901 struct string_list existing_refs = STRING_LIST_INIT_DUP;
902 struct ref *ref_map;
903 struct ref *rm;
904 int autotags = (transport->remote->fetch_tags == 1);
905 int retcode = 0;
907 for_each_ref(add_existing, &existing_refs);
909 if (tags == TAGS_DEFAULT) {
910 if (transport->remote->fetch_tags == 2)
911 tags = TAGS_SET;
912 if (transport->remote->fetch_tags == -1)
913 tags = TAGS_UNSET;
916 if (!transport->get_refs_list || !transport->fetch)
917 die(_("Don't know how to fetch from %s"), transport->url);
919 /* if not appending, truncate FETCH_HEAD */
920 if (!append && !dry_run) {
921 retcode = truncate_fetch_head();
922 if (retcode)
923 goto cleanup;
926 ref_map = get_ref_map(transport, refs, ref_count, tags, &autotags);
927 if (!update_head_ok)
928 check_not_current_branch(ref_map);
930 for (rm = ref_map; rm; rm = rm->next) {
931 if (rm->peer_ref) {
932 struct string_list_item *peer_item =
933 string_list_lookup(&existing_refs,
934 rm->peer_ref->name);
935 if (peer_item) {
936 struct object_id *old_oid = peer_item->util;
937 oidcpy(&rm->peer_ref->old_oid, old_oid);
942 if (tags == TAGS_DEFAULT && autotags)
943 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
944 if (prune) {
946 * We only prune based on refspecs specified
947 * explicitly (via command line or configuration); we
948 * don't care whether --tags was specified.
950 if (ref_count) {
951 prune_refs(refs, ref_count, ref_map, transport->url);
952 } else {
953 prune_refs(transport->remote->fetch,
954 transport->remote->fetch_refspec_nr,
955 ref_map,
956 transport->url);
959 if (fetch_refs(transport, ref_map)) {
960 free_refs(ref_map);
961 retcode = 1;
962 goto cleanup;
964 free_refs(ref_map);
966 /* if neither --no-tags nor --tags was specified, do automated tag
967 * following ... */
968 if (tags == TAGS_DEFAULT && autotags) {
969 struct ref **tail = &ref_map;
970 ref_map = NULL;
971 find_non_local_tags(transport, &ref_map, &tail);
972 if (ref_map)
973 backfill_tags(transport, ref_map);
974 free_refs(ref_map);
977 cleanup:
978 string_list_clear(&existing_refs, 1);
979 return retcode;
982 static int get_one_remote_for_fetch(struct remote *remote, void *priv)
984 struct string_list *list = priv;
985 if (!remote->skip_default_update)
986 string_list_append(list, remote->name);
987 return 0;
990 struct remote_group_data {
991 const char *name;
992 struct string_list *list;
995 static int get_remote_group(const char *key, const char *value, void *priv)
997 struct remote_group_data *g = priv;
999 if (skip_prefix(key, "remotes.", &key) && !strcmp(key, g->name)) {
1000 /* split list by white space */
1001 while (*value) {
1002 size_t wordlen = strcspn(value, " \t\n");
1004 if (wordlen >= 1)
1005 string_list_append(g->list,
1006 xstrndup(value, wordlen));
1007 value += wordlen + (value[wordlen] != '\0');
1011 return 0;
1014 static int add_remote_or_group(const char *name, struct string_list *list)
1016 int prev_nr = list->nr;
1017 struct remote_group_data g;
1018 g.name = name; g.list = list;
1020 git_config(get_remote_group, &g);
1021 if (list->nr == prev_nr) {
1022 struct remote *remote;
1023 if (!remote_is_configured(name))
1024 return 0;
1025 remote = remote_get(name);
1026 string_list_append(list, remote->name);
1028 return 1;
1031 static void add_options_to_argv(struct argv_array *argv)
1033 if (dry_run)
1034 argv_array_push(argv, "--dry-run");
1035 if (prune != -1)
1036 argv_array_push(argv, prune ? "--prune" : "--no-prune");
1037 if (update_head_ok)
1038 argv_array_push(argv, "--update-head-ok");
1039 if (force)
1040 argv_array_push(argv, "--force");
1041 if (keep)
1042 argv_array_push(argv, "--keep");
1043 if (recurse_submodules == RECURSE_SUBMODULES_ON)
1044 argv_array_push(argv, "--recurse-submodules");
1045 else if (recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND)
1046 argv_array_push(argv, "--recurse-submodules=on-demand");
1047 if (tags == TAGS_SET)
1048 argv_array_push(argv, "--tags");
1049 else if (tags == TAGS_UNSET)
1050 argv_array_push(argv, "--no-tags");
1051 if (verbosity >= 2)
1052 argv_array_push(argv, "-v");
1053 if (verbosity >= 1)
1054 argv_array_push(argv, "-v");
1055 else if (verbosity < 0)
1056 argv_array_push(argv, "-q");
1060 static int fetch_multiple(struct string_list *list)
1062 int i, result = 0;
1063 struct argv_array argv = ARGV_ARRAY_INIT;
1065 if (!append && !dry_run) {
1066 int errcode = truncate_fetch_head();
1067 if (errcode)
1068 return errcode;
1071 argv_array_pushl(&argv, "fetch", "--append", NULL);
1072 add_options_to_argv(&argv);
1074 for (i = 0; i < list->nr; i++) {
1075 const char *name = list->items[i].string;
1076 argv_array_push(&argv, name);
1077 if (verbosity >= 0)
1078 printf(_("Fetching %s\n"), name);
1079 if (run_command_v_opt(argv.argv, RUN_GIT_CMD)) {
1080 error(_("Could not fetch %s"), name);
1081 result = 1;
1083 argv_array_pop(&argv);
1086 argv_array_clear(&argv);
1087 return result;
1090 static int fetch_one(struct remote *remote, int argc, const char **argv)
1092 static const char **refs = NULL;
1093 struct refspec *refspec;
1094 int ref_nr = 0;
1095 int exit_code;
1097 if (!remote)
1098 die(_("No remote repository specified. Please, specify either a URL or a\n"
1099 "remote name from which new revisions should be fetched."));
1101 gtransport = prepare_transport(remote);
1103 if (prune < 0) {
1104 /* no command line request */
1105 if (0 <= gtransport->remote->prune)
1106 prune = gtransport->remote->prune;
1107 else if (0 <= fetch_prune_config)
1108 prune = fetch_prune_config;
1109 else
1110 prune = PRUNE_BY_DEFAULT;
1113 if (argc > 0) {
1114 int j = 0;
1115 int i;
1116 refs = xcalloc(argc + 1, sizeof(const char *));
1117 for (i = 0; i < argc; i++) {
1118 if (!strcmp(argv[i], "tag")) {
1119 i++;
1120 if (i >= argc)
1121 die(_("You need to specify a tag name."));
1122 refs[j++] = xstrfmt("refs/tags/%s:refs/tags/%s",
1123 argv[i], argv[i]);
1124 } else
1125 refs[j++] = argv[i];
1127 refs[j] = NULL;
1128 ref_nr = j;
1131 sigchain_push_common(unlock_pack_on_signal);
1132 atexit(unlock_pack);
1133 refspec = parse_fetch_refspec(ref_nr, refs);
1134 exit_code = do_fetch(gtransport, refspec, ref_nr);
1135 free_refspec(ref_nr, refspec);
1136 transport_disconnect(gtransport);
1137 gtransport = NULL;
1138 return exit_code;
1141 int cmd_fetch(int argc, const char **argv, const char *prefix)
1143 int i;
1144 struct string_list list = STRING_LIST_INIT_NODUP;
1145 struct remote *remote;
1146 int result = 0;
1147 struct argv_array argv_gc_auto = ARGV_ARRAY_INIT;
1149 packet_trace_identity("fetch");
1151 /* Record the command line for the reflog */
1152 strbuf_addstr(&default_rla, "fetch");
1153 for (i = 1; i < argc; i++)
1154 strbuf_addf(&default_rla, " %s", argv[i]);
1156 git_config(git_fetch_config, NULL);
1158 argc = parse_options(argc, argv, prefix,
1159 builtin_fetch_options, builtin_fetch_usage, 0);
1161 if (unshallow) {
1162 if (depth)
1163 die(_("--depth and --unshallow cannot be used together"));
1164 else if (!is_repository_shallow())
1165 die(_("--unshallow on a complete repository does not make sense"));
1166 else
1167 depth = xstrfmt("%d", INFINITE_DEPTH);
1170 /* no need to be strict, transport_set_option() will validate it again */
1171 if (depth && atoi(depth) < 1)
1172 die(_("depth %s is not a positive number"), depth);
1174 if (recurse_submodules != RECURSE_SUBMODULES_OFF) {
1175 if (recurse_submodules_default) {
1176 int arg = parse_fetch_recurse_submodules_arg("--recurse-submodules-default", recurse_submodules_default);
1177 set_config_fetch_recurse_submodules(arg);
1179 gitmodules_config();
1180 git_config(submodule_config, NULL);
1183 if (all) {
1184 if (argc == 1)
1185 die(_("fetch --all does not take a repository argument"));
1186 else if (argc > 1)
1187 die(_("fetch --all does not make sense with refspecs"));
1188 (void) for_each_remote(get_one_remote_for_fetch, &list);
1189 result = fetch_multiple(&list);
1190 } else if (argc == 0) {
1191 /* No arguments -- use default remote */
1192 remote = remote_get(NULL);
1193 result = fetch_one(remote, argc, argv);
1194 } else if (multiple) {
1195 /* All arguments are assumed to be remotes or groups */
1196 for (i = 0; i < argc; i++)
1197 if (!add_remote_or_group(argv[i], &list))
1198 die(_("No such remote or remote group: %s"), argv[i]);
1199 result = fetch_multiple(&list);
1200 } else {
1201 /* Single remote or group */
1202 (void) add_remote_or_group(argv[0], &list);
1203 if (list.nr > 1) {
1204 /* More than one remote */
1205 if (argc > 1)
1206 die(_("Fetching a group and specifying refspecs does not make sense"));
1207 result = fetch_multiple(&list);
1208 } else {
1209 /* Zero or one remotes */
1210 remote = remote_get(argv[0]);
1211 result = fetch_one(remote, argc-1, argv+1);
1215 if (!result && (recurse_submodules != RECURSE_SUBMODULES_OFF)) {
1216 struct argv_array options = ARGV_ARRAY_INIT;
1218 add_options_to_argv(&options);
1219 result = fetch_populated_submodules(&options,
1220 submodule_prefix,
1221 recurse_submodules,
1222 verbosity < 0);
1223 argv_array_clear(&options);
1226 /* All names were strdup()ed or strndup()ed */
1227 list.strdup_strings = 1;
1228 string_list_clear(&list, 0);
1230 argv_array_pushl(&argv_gc_auto, "gc", "--auto", NULL);
1231 if (verbosity < 0)
1232 argv_array_push(&argv_gc_auto, "--quiet");
1233 run_command_v_opt(argv_gc_auto.argv, RUN_GIT_CMD);
1234 argv_array_clear(&argv_gc_auto);
1236 return result;