Merge branch 'js/close-packs-before-gc'
[git/gitweb.git] / builtin / fetch.c
blob8e742135f049c2792bfc5a20299dac88518929cc
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 int max_children = 1;
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_INTEGER('j', "jobs", &max_children,
104 N_("number of submodules fetched in parallel")),
105 OPT_BOOL('p', "prune", &prune,
106 N_("prune remote-tracking branches no longer on remote")),
107 { OPTION_CALLBACK, 0, "recurse-submodules", NULL, N_("on-demand"),
108 N_("control recursive fetching of submodules"),
109 PARSE_OPT_OPTARG, option_parse_recurse_submodules },
110 OPT_BOOL(0, "dry-run", &dry_run,
111 N_("dry run")),
112 OPT_BOOL('k', "keep", &keep, N_("keep downloaded pack")),
113 OPT_BOOL('u', "update-head-ok", &update_head_ok,
114 N_("allow updating of HEAD ref")),
115 OPT_BOOL(0, "progress", &progress, N_("force progress reporting")),
116 OPT_STRING(0, "depth", &depth, N_("depth"),
117 N_("deepen history of shallow clone")),
118 { OPTION_SET_INT, 0, "unshallow", &unshallow, NULL,
119 N_("convert to a complete repository"),
120 PARSE_OPT_NONEG | PARSE_OPT_NOARG, NULL, 1 },
121 { OPTION_STRING, 0, "submodule-prefix", &submodule_prefix, N_("dir"),
122 N_("prepend this to submodule path output"), PARSE_OPT_HIDDEN },
123 { OPTION_STRING, 0, "recurse-submodules-default",
124 &recurse_submodules_default, NULL,
125 N_("default mode for recursion"), PARSE_OPT_HIDDEN },
126 OPT_BOOL(0, "update-shallow", &update_shallow,
127 N_("accept refs that update .git/shallow")),
128 { OPTION_CALLBACK, 0, "refmap", NULL, N_("refmap"),
129 N_("specify fetch refmap"), PARSE_OPT_NONEG, parse_refmap_arg },
130 OPT_END()
133 static void unlock_pack(void)
135 if (gtransport)
136 transport_unlock_pack(gtransport);
137 if (gsecondary)
138 transport_unlock_pack(gsecondary);
141 static void unlock_pack_on_signal(int signo)
143 unlock_pack();
144 sigchain_pop(signo);
145 raise(signo);
148 static void add_merge_config(struct ref **head,
149 const struct ref *remote_refs,
150 struct branch *branch,
151 struct ref ***tail)
153 int i;
155 for (i = 0; i < branch->merge_nr; i++) {
156 struct ref *rm, **old_tail = *tail;
157 struct refspec refspec;
159 for (rm = *head; rm; rm = rm->next) {
160 if (branch_merge_matches(branch, i, rm->name)) {
161 rm->fetch_head_status = FETCH_HEAD_MERGE;
162 break;
165 if (rm)
166 continue;
169 * Not fetched to a remote-tracking branch? We need to fetch
170 * it anyway to allow this branch's "branch.$name.merge"
171 * to be honored by 'git pull', but we do not have to
172 * fail if branch.$name.merge is misconfigured to point
173 * at a nonexisting branch. If we were indeed called by
174 * 'git pull', it will notice the misconfiguration because
175 * there is no entry in the resulting FETCH_HEAD marked
176 * for merging.
178 memset(&refspec, 0, sizeof(refspec));
179 refspec.src = branch->merge[i]->src;
180 get_fetch_map(remote_refs, &refspec, tail, 1);
181 for (rm = *old_tail; rm; rm = rm->next)
182 rm->fetch_head_status = FETCH_HEAD_MERGE;
186 static int add_existing(const char *refname, const struct object_id *oid,
187 int flag, void *cbdata)
189 struct string_list *list = (struct string_list *)cbdata;
190 struct string_list_item *item = string_list_insert(list, refname);
191 struct object_id *old_oid = xmalloc(sizeof(*old_oid));
193 oidcpy(old_oid, oid);
194 item->util = old_oid;
195 return 0;
198 static int will_fetch(struct ref **head, const unsigned char *sha1)
200 struct ref *rm = *head;
201 while (rm) {
202 if (!hashcmp(rm->old_oid.hash, sha1))
203 return 1;
204 rm = rm->next;
206 return 0;
209 static void find_non_local_tags(struct transport *transport,
210 struct ref **head,
211 struct ref ***tail)
213 struct string_list existing_refs = STRING_LIST_INIT_DUP;
214 struct string_list remote_refs = STRING_LIST_INIT_NODUP;
215 const struct ref *ref;
216 struct string_list_item *item = NULL;
218 for_each_ref(add_existing, &existing_refs);
219 for (ref = transport_get_remote_refs(transport); ref; ref = ref->next) {
220 if (!starts_with(ref->name, "refs/tags/"))
221 continue;
224 * The peeled ref always follows the matching base
225 * ref, so if we see a peeled ref that we don't want
226 * to fetch then we can mark the ref entry in the list
227 * as one to ignore by setting util to NULL.
229 if (ends_with(ref->name, "^{}")) {
230 if (item && !has_object_file(&ref->old_oid) &&
231 !will_fetch(head, ref->old_oid.hash) &&
232 !has_sha1_file(item->util) &&
233 !will_fetch(head, item->util))
234 item->util = NULL;
235 item = NULL;
236 continue;
240 * If item is non-NULL here, then we previously saw a
241 * ref not followed by a peeled reference, so we need
242 * to check if it is a lightweight tag that we want to
243 * fetch.
245 if (item && !has_sha1_file(item->util) &&
246 !will_fetch(head, item->util))
247 item->util = NULL;
249 item = NULL;
251 /* skip duplicates and refs that we already have */
252 if (string_list_has_string(&remote_refs, ref->name) ||
253 string_list_has_string(&existing_refs, ref->name))
254 continue;
256 item = string_list_insert(&remote_refs, ref->name);
257 item->util = (void *)&ref->old_oid;
259 string_list_clear(&existing_refs, 1);
262 * We may have a final lightweight tag that needs to be
263 * checked to see if it needs fetching.
265 if (item && !has_sha1_file(item->util) &&
266 !will_fetch(head, item->util))
267 item->util = NULL;
270 * For all the tags in the remote_refs string list,
271 * add them to the list of refs to be fetched
273 for_each_string_list_item(item, &remote_refs) {
274 /* Unless we have already decided to ignore this item... */
275 if (item->util)
277 struct ref *rm = alloc_ref(item->string);
278 rm->peer_ref = alloc_ref(item->string);
279 oidcpy(&rm->old_oid, item->util);
280 **tail = rm;
281 *tail = &rm->next;
285 string_list_clear(&remote_refs, 0);
288 static struct ref *get_ref_map(struct transport *transport,
289 struct refspec *refspecs, int refspec_count,
290 int tags, int *autotags)
292 int i;
293 struct ref *rm;
294 struct ref *ref_map = NULL;
295 struct ref **tail = &ref_map;
297 /* opportunistically-updated references: */
298 struct ref *orefs = NULL, **oref_tail = &orefs;
300 const struct ref *remote_refs = transport_get_remote_refs(transport);
302 if (refspec_count) {
303 struct refspec *fetch_refspec;
304 int fetch_refspec_nr;
306 for (i = 0; i < refspec_count; i++) {
307 get_fetch_map(remote_refs, &refspecs[i], &tail, 0);
308 if (refspecs[i].dst && refspecs[i].dst[0])
309 *autotags = 1;
311 /* Merge everything on the command line (but not --tags) */
312 for (rm = ref_map; rm; rm = rm->next)
313 rm->fetch_head_status = FETCH_HEAD_MERGE;
316 * For any refs that we happen to be fetching via
317 * command-line arguments, the destination ref might
318 * have been missing or have been different than the
319 * remote-tracking ref that would be derived from the
320 * configured refspec. In these cases, we want to
321 * take the opportunity to update their configured
322 * remote-tracking reference. However, we do not want
323 * to mention these entries in FETCH_HEAD at all, as
324 * they would simply be duplicates of existing
325 * entries, so we set them FETCH_HEAD_IGNORE below.
327 * We compute these entries now, based only on the
328 * refspecs specified on the command line. But we add
329 * them to the list following the refspecs resulting
330 * from the tags option so that one of the latter,
331 * which has FETCH_HEAD_NOT_FOR_MERGE, is not removed
332 * by ref_remove_duplicates() in favor of one of these
333 * opportunistic entries with FETCH_HEAD_IGNORE.
335 if (refmap_array) {
336 fetch_refspec = parse_fetch_refspec(refmap_nr, refmap_array);
337 fetch_refspec_nr = refmap_nr;
338 } else {
339 fetch_refspec = transport->remote->fetch;
340 fetch_refspec_nr = transport->remote->fetch_refspec_nr;
343 for (i = 0; i < fetch_refspec_nr; i++)
344 get_fetch_map(ref_map, &fetch_refspec[i], &oref_tail, 1);
346 if (tags == TAGS_SET)
347 get_fetch_map(remote_refs, tag_refspec, &tail, 0);
348 } else if (refmap_array) {
349 die("--refmap option is only meaningful with command-line refspec(s).");
350 } else {
351 /* Use the defaults */
352 struct remote *remote = transport->remote;
353 struct branch *branch = branch_get(NULL);
354 int has_merge = branch_has_merge_config(branch);
355 if (remote &&
356 (remote->fetch_refspec_nr ||
357 /* Note: has_merge implies non-NULL branch->remote_name */
358 (has_merge && !strcmp(branch->remote_name, remote->name)))) {
359 for (i = 0; i < remote->fetch_refspec_nr; i++) {
360 get_fetch_map(remote_refs, &remote->fetch[i], &tail, 0);
361 if (remote->fetch[i].dst &&
362 remote->fetch[i].dst[0])
363 *autotags = 1;
364 if (!i && !has_merge && ref_map &&
365 !remote->fetch[0].pattern)
366 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
369 * if the remote we're fetching from is the same
370 * as given in branch.<name>.remote, we add the
371 * ref given in branch.<name>.merge, too.
373 * Note: has_merge implies non-NULL branch->remote_name
375 if (has_merge &&
376 !strcmp(branch->remote_name, remote->name))
377 add_merge_config(&ref_map, remote_refs, branch, &tail);
378 } else {
379 ref_map = get_remote_ref(remote_refs, "HEAD");
380 if (!ref_map)
381 die(_("Couldn't find remote ref HEAD"));
382 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
383 tail = &ref_map->next;
387 if (tags == TAGS_SET)
388 /* also fetch all tags */
389 get_fetch_map(remote_refs, tag_refspec, &tail, 0);
390 else if (tags == TAGS_DEFAULT && *autotags)
391 find_non_local_tags(transport, &ref_map, &tail);
393 /* Now append any refs to be updated opportunistically: */
394 *tail = orefs;
395 for (rm = orefs; rm; rm = rm->next) {
396 rm->fetch_head_status = FETCH_HEAD_IGNORE;
397 tail = &rm->next;
400 return ref_remove_duplicates(ref_map);
403 #define STORE_REF_ERROR_OTHER 1
404 #define STORE_REF_ERROR_DF_CONFLICT 2
406 static int s_update_ref(const char *action,
407 struct ref *ref,
408 int check_old)
410 char msg[1024];
411 char *rla = getenv("GIT_REFLOG_ACTION");
412 struct ref_transaction *transaction;
413 struct strbuf err = STRBUF_INIT;
414 int ret, df_conflict = 0;
416 if (dry_run)
417 return 0;
418 if (!rla)
419 rla = default_rla.buf;
420 snprintf(msg, sizeof(msg), "%s: %s", rla, action);
422 transaction = ref_transaction_begin(&err);
423 if (!transaction ||
424 ref_transaction_update(transaction, ref->name,
425 ref->new_oid.hash,
426 check_old ? ref->old_oid.hash : NULL,
427 0, msg, &err))
428 goto fail;
430 ret = ref_transaction_commit(transaction, &err);
431 if (ret) {
432 df_conflict = (ret == TRANSACTION_NAME_CONFLICT);
433 goto fail;
436 ref_transaction_free(transaction);
437 strbuf_release(&err);
438 return 0;
439 fail:
440 ref_transaction_free(transaction);
441 error("%s", err.buf);
442 strbuf_release(&err);
443 return df_conflict ? STORE_REF_ERROR_DF_CONFLICT
444 : STORE_REF_ERROR_OTHER;
447 #define REFCOL_WIDTH 10
449 static int update_local_ref(struct ref *ref,
450 const char *remote,
451 const struct ref *remote_ref,
452 struct strbuf *display)
454 struct commit *current = NULL, *updated;
455 enum object_type type;
456 struct branch *current_branch = branch_get(NULL);
457 const char *pretty_ref = prettify_refname(ref->name);
459 type = sha1_object_info(ref->new_oid.hash, NULL);
460 if (type < 0)
461 die(_("object %s not found"), oid_to_hex(&ref->new_oid));
463 if (!oidcmp(&ref->old_oid, &ref->new_oid)) {
464 if (verbosity > 0)
465 strbuf_addf(display, "= %-*s %-*s -> %s",
466 TRANSPORT_SUMMARY(_("[up to date]")),
467 REFCOL_WIDTH, remote, pretty_ref);
468 return 0;
471 if (current_branch &&
472 !strcmp(ref->name, current_branch->name) &&
473 !(update_head_ok || is_bare_repository()) &&
474 !is_null_oid(&ref->old_oid)) {
476 * If this is the head, and it's not okay to update
477 * the head, and the old value of the head isn't empty...
479 strbuf_addf(display,
480 _("! %-*s %-*s -> %s (can't fetch in current branch)"),
481 TRANSPORT_SUMMARY(_("[rejected]")),
482 REFCOL_WIDTH, remote, pretty_ref);
483 return 1;
486 if (!is_null_oid(&ref->old_oid) &&
487 starts_with(ref->name, "refs/tags/")) {
488 int r;
489 r = s_update_ref("updating tag", ref, 0);
490 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
491 r ? '!' : '-',
492 TRANSPORT_SUMMARY(_("[tag update]")),
493 REFCOL_WIDTH, remote, pretty_ref,
494 r ? _(" (unable to update local ref)") : "");
495 return r;
498 current = lookup_commit_reference_gently(ref->old_oid.hash, 1);
499 updated = lookup_commit_reference_gently(ref->new_oid.hash, 1);
500 if (!current || !updated) {
501 const char *msg;
502 const char *what;
503 int r;
505 * Nicely describe the new ref we're fetching.
506 * Base this on the remote's ref name, as it's
507 * more likely to follow a standard layout.
509 const char *name = remote_ref ? remote_ref->name : "";
510 if (starts_with(name, "refs/tags/")) {
511 msg = "storing tag";
512 what = _("[new tag]");
513 } else if (starts_with(name, "refs/heads/")) {
514 msg = "storing head";
515 what = _("[new branch]");
516 } else {
517 msg = "storing ref";
518 what = _("[new ref]");
521 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
522 (recurse_submodules != RECURSE_SUBMODULES_ON))
523 check_for_new_submodule_commits(ref->new_oid.hash);
524 r = s_update_ref(msg, ref, 0);
525 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
526 r ? '!' : '*',
527 TRANSPORT_SUMMARY(what),
528 REFCOL_WIDTH, remote, pretty_ref,
529 r ? _(" (unable to update local ref)") : "");
530 return r;
533 if (in_merge_bases(current, updated)) {
534 struct strbuf quickref = STRBUF_INIT;
535 int r;
536 strbuf_add_unique_abbrev(&quickref, current->object.oid.hash, DEFAULT_ABBREV);
537 strbuf_addstr(&quickref, "..");
538 strbuf_add_unique_abbrev(&quickref, ref->new_oid.hash, DEFAULT_ABBREV);
539 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
540 (recurse_submodules != RECURSE_SUBMODULES_ON))
541 check_for_new_submodule_commits(ref->new_oid.hash);
542 r = s_update_ref("fast-forward", ref, 1);
543 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
544 r ? '!' : ' ',
545 TRANSPORT_SUMMARY_WIDTH, quickref.buf,
546 REFCOL_WIDTH, remote, pretty_ref,
547 r ? _(" (unable to update local ref)") : "");
548 strbuf_release(&quickref);
549 return r;
550 } else if (force || ref->force) {
551 struct strbuf quickref = STRBUF_INIT;
552 int r;
553 strbuf_add_unique_abbrev(&quickref, current->object.oid.hash, DEFAULT_ABBREV);
554 strbuf_addstr(&quickref, "...");
555 strbuf_add_unique_abbrev(&quickref, ref->new_oid.hash, DEFAULT_ABBREV);
556 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
557 (recurse_submodules != RECURSE_SUBMODULES_ON))
558 check_for_new_submodule_commits(ref->new_oid.hash);
559 r = s_update_ref("forced-update", ref, 1);
560 strbuf_addf(display, "%c %-*s %-*s -> %s (%s)",
561 r ? '!' : '+',
562 TRANSPORT_SUMMARY_WIDTH, quickref.buf,
563 REFCOL_WIDTH, remote, pretty_ref,
564 r ? _("unable to update local ref") : _("forced update"));
565 strbuf_release(&quickref);
566 return r;
567 } else {
568 strbuf_addf(display, "! %-*s %-*s -> %s %s",
569 TRANSPORT_SUMMARY(_("[rejected]")),
570 REFCOL_WIDTH, remote, pretty_ref,
571 _("(non-fast-forward)"));
572 return 1;
576 static int iterate_ref_map(void *cb_data, unsigned char sha1[20])
578 struct ref **rm = cb_data;
579 struct ref *ref = *rm;
581 while (ref && ref->status == REF_STATUS_REJECT_SHALLOW)
582 ref = ref->next;
583 if (!ref)
584 return -1; /* end of the list */
585 *rm = ref->next;
586 hashcpy(sha1, ref->old_oid.hash);
587 return 0;
590 static int store_updated_refs(const char *raw_url, const char *remote_name,
591 struct ref *ref_map)
593 FILE *fp;
594 struct commit *commit;
595 int url_len, i, rc = 0;
596 struct strbuf note = STRBUF_INIT;
597 const char *what, *kind;
598 struct ref *rm;
599 char *url;
600 const char *filename = dry_run ? "/dev/null" : git_path_fetch_head();
601 int want_status;
603 fp = fopen(filename, "a");
604 if (!fp)
605 return error(_("cannot open %s: %s\n"), filename, strerror(errno));
607 if (raw_url)
608 url = transport_anonymize_url(raw_url);
609 else
610 url = xstrdup("foreign");
612 rm = ref_map;
613 if (check_everything_connected(iterate_ref_map, 0, &rm)) {
614 rc = error(_("%s did not send all necessary objects\n"), url);
615 goto abort;
619 * We do a pass for each fetch_head_status type in their enum order, so
620 * merged entries are written before not-for-merge. That lets readers
621 * use FETCH_HEAD as a refname to refer to the ref to be merged.
623 for (want_status = FETCH_HEAD_MERGE;
624 want_status <= FETCH_HEAD_IGNORE;
625 want_status++) {
626 for (rm = ref_map; rm; rm = rm->next) {
627 struct ref *ref = NULL;
628 const char *merge_status_marker = "";
630 if (rm->status == REF_STATUS_REJECT_SHALLOW) {
631 if (want_status == FETCH_HEAD_MERGE)
632 warning(_("reject %s because shallow roots are not allowed to be updated"),
633 rm->peer_ref ? rm->peer_ref->name : rm->name);
634 continue;
637 commit = lookup_commit_reference_gently(rm->old_oid.hash, 1);
638 if (!commit)
639 rm->fetch_head_status = FETCH_HEAD_NOT_FOR_MERGE;
641 if (rm->fetch_head_status != want_status)
642 continue;
644 if (rm->peer_ref) {
645 ref = alloc_ref(rm->peer_ref->name);
646 oidcpy(&ref->old_oid, &rm->peer_ref->old_oid);
647 oidcpy(&ref->new_oid, &rm->old_oid);
648 ref->force = rm->peer_ref->force;
652 if (!strcmp(rm->name, "HEAD")) {
653 kind = "";
654 what = "";
656 else if (starts_with(rm->name, "refs/heads/")) {
657 kind = "branch";
658 what = rm->name + 11;
660 else if (starts_with(rm->name, "refs/tags/")) {
661 kind = "tag";
662 what = rm->name + 10;
664 else if (starts_with(rm->name, "refs/remotes/")) {
665 kind = "remote-tracking branch";
666 what = rm->name + 13;
668 else {
669 kind = "";
670 what = rm->name;
673 url_len = strlen(url);
674 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
676 url_len = i + 1;
677 if (4 < i && !strncmp(".git", url + i - 3, 4))
678 url_len = i - 3;
680 strbuf_reset(&note);
681 if (*what) {
682 if (*kind)
683 strbuf_addf(&note, "%s ", kind);
684 strbuf_addf(&note, "'%s' of ", what);
686 switch (rm->fetch_head_status) {
687 case FETCH_HEAD_NOT_FOR_MERGE:
688 merge_status_marker = "not-for-merge";
689 /* fall-through */
690 case FETCH_HEAD_MERGE:
691 fprintf(fp, "%s\t%s\t%s",
692 oid_to_hex(&rm->old_oid),
693 merge_status_marker,
694 note.buf);
695 for (i = 0; i < url_len; ++i)
696 if ('\n' == url[i])
697 fputs("\\n", fp);
698 else
699 fputc(url[i], fp);
700 fputc('\n', fp);
701 break;
702 default:
703 /* do not write anything to FETCH_HEAD */
704 break;
707 strbuf_reset(&note);
708 if (ref) {
709 rc |= update_local_ref(ref, what, rm, &note);
710 free(ref);
711 } else
712 strbuf_addf(&note, "* %-*s %-*s -> FETCH_HEAD",
713 TRANSPORT_SUMMARY_WIDTH,
714 *kind ? kind : "branch",
715 REFCOL_WIDTH,
716 *what ? what : "HEAD");
717 if (note.len) {
718 if (verbosity >= 0 && !shown_url) {
719 fprintf(stderr, _("From %.*s\n"),
720 url_len, url);
721 shown_url = 1;
723 if (verbosity >= 0)
724 fprintf(stderr, " %s\n", note.buf);
729 if (rc & STORE_REF_ERROR_DF_CONFLICT)
730 error(_("some local refs could not be updated; try running\n"
731 " 'git remote prune %s' to remove any old, conflicting "
732 "branches"), remote_name);
734 abort:
735 strbuf_release(&note);
736 free(url);
737 fclose(fp);
738 return rc;
742 * We would want to bypass the object transfer altogether if
743 * everything we are going to fetch already exists and is connected
744 * locally.
746 static int quickfetch(struct ref *ref_map)
748 struct ref *rm = ref_map;
751 * If we are deepening a shallow clone we already have these
752 * objects reachable. Running rev-list here will return with
753 * a good (0) exit status and we'll bypass the fetch that we
754 * really need to perform. Claiming failure now will ensure
755 * we perform the network exchange to deepen our history.
757 if (depth)
758 return -1;
759 return check_everything_connected(iterate_ref_map, 1, &rm);
762 static int fetch_refs(struct transport *transport, struct ref *ref_map)
764 int ret = quickfetch(ref_map);
765 if (ret)
766 ret = transport_fetch_refs(transport, ref_map);
767 if (!ret)
768 ret |= store_updated_refs(transport->url,
769 transport->remote->name,
770 ref_map);
771 transport_unlock_pack(transport);
772 return ret;
775 static int prune_refs(struct refspec *refs, int ref_count, struct ref *ref_map,
776 const char *raw_url)
778 int url_len, i, result = 0;
779 struct ref *ref, *stale_refs = get_stale_heads(refs, ref_count, ref_map);
780 char *url;
781 const char *dangling_msg = dry_run
782 ? _(" (%s will become dangling)")
783 : _(" (%s has become dangling)");
785 if (raw_url)
786 url = transport_anonymize_url(raw_url);
787 else
788 url = xstrdup("foreign");
790 url_len = strlen(url);
791 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
794 url_len = i + 1;
795 if (4 < i && !strncmp(".git", url + i - 3, 4))
796 url_len = i - 3;
798 if (!dry_run) {
799 struct string_list refnames = STRING_LIST_INIT_NODUP;
801 for (ref = stale_refs; ref; ref = ref->next)
802 string_list_append(&refnames, ref->name);
804 result = delete_refs(&refnames);
805 string_list_clear(&refnames, 0);
808 if (verbosity >= 0) {
809 for (ref = stale_refs; ref; ref = ref->next) {
810 if (!shown_url) {
811 fprintf(stderr, _("From %.*s\n"), url_len, url);
812 shown_url = 1;
814 fprintf(stderr, " x %-*s %-*s -> %s\n",
815 TRANSPORT_SUMMARY(_("[deleted]")),
816 REFCOL_WIDTH, _("(none)"), prettify_refname(ref->name));
817 warn_dangling_symref(stderr, dangling_msg, ref->name);
821 free(url);
822 free_refs(stale_refs);
823 return result;
826 static void check_not_current_branch(struct ref *ref_map)
828 struct branch *current_branch = branch_get(NULL);
830 if (is_bare_repository() || !current_branch)
831 return;
833 for (; ref_map; ref_map = ref_map->next)
834 if (ref_map->peer_ref && !strcmp(current_branch->refname,
835 ref_map->peer_ref->name))
836 die(_("Refusing to fetch into current branch %s "
837 "of non-bare repository"), current_branch->refname);
840 static int truncate_fetch_head(void)
842 const char *filename = git_path_fetch_head();
843 FILE *fp = fopen_for_writing(filename);
845 if (!fp)
846 return error(_("cannot open %s: %s\n"), filename, strerror(errno));
847 fclose(fp);
848 return 0;
851 static void set_option(struct transport *transport, const char *name, const char *value)
853 int r = transport_set_option(transport, name, value);
854 if (r < 0)
855 die(_("Option \"%s\" value \"%s\" is not valid for %s"),
856 name, value, transport->url);
857 if (r > 0)
858 warning(_("Option \"%s\" is ignored for %s\n"),
859 name, transport->url);
862 static struct transport *prepare_transport(struct remote *remote)
864 struct transport *transport;
865 transport = transport_get(remote, NULL);
866 transport_set_verbosity(transport, verbosity, progress);
867 if (upload_pack)
868 set_option(transport, TRANS_OPT_UPLOADPACK, upload_pack);
869 if (keep)
870 set_option(transport, TRANS_OPT_KEEP, "yes");
871 if (depth)
872 set_option(transport, TRANS_OPT_DEPTH, depth);
873 if (update_shallow)
874 set_option(transport, TRANS_OPT_UPDATE_SHALLOW, "yes");
875 return transport;
878 static void backfill_tags(struct transport *transport, struct ref *ref_map)
880 if (transport->cannot_reuse) {
881 gsecondary = prepare_transport(transport->remote);
882 transport = gsecondary;
885 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
886 transport_set_option(transport, TRANS_OPT_DEPTH, "0");
887 fetch_refs(transport, ref_map);
889 if (gsecondary) {
890 transport_disconnect(gsecondary);
891 gsecondary = NULL;
895 static int do_fetch(struct transport *transport,
896 struct refspec *refs, int ref_count)
898 struct string_list existing_refs = STRING_LIST_INIT_DUP;
899 struct ref *ref_map;
900 struct ref *rm;
901 int autotags = (transport->remote->fetch_tags == 1);
902 int retcode = 0;
904 for_each_ref(add_existing, &existing_refs);
906 if (tags == TAGS_DEFAULT) {
907 if (transport->remote->fetch_tags == 2)
908 tags = TAGS_SET;
909 if (transport->remote->fetch_tags == -1)
910 tags = TAGS_UNSET;
913 if (!transport->get_refs_list || !transport->fetch)
914 die(_("Don't know how to fetch from %s"), transport->url);
916 /* if not appending, truncate FETCH_HEAD */
917 if (!append && !dry_run) {
918 retcode = truncate_fetch_head();
919 if (retcode)
920 goto cleanup;
923 ref_map = get_ref_map(transport, refs, ref_count, tags, &autotags);
924 if (!update_head_ok)
925 check_not_current_branch(ref_map);
927 for (rm = ref_map; rm; rm = rm->next) {
928 if (rm->peer_ref) {
929 struct string_list_item *peer_item =
930 string_list_lookup(&existing_refs,
931 rm->peer_ref->name);
932 if (peer_item) {
933 struct object_id *old_oid = peer_item->util;
934 oidcpy(&rm->peer_ref->old_oid, old_oid);
939 if (tags == TAGS_DEFAULT && autotags)
940 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
941 if (prune) {
943 * We only prune based on refspecs specified
944 * explicitly (via command line or configuration); we
945 * don't care whether --tags was specified.
947 if (ref_count) {
948 prune_refs(refs, ref_count, ref_map, transport->url);
949 } else {
950 prune_refs(transport->remote->fetch,
951 transport->remote->fetch_refspec_nr,
952 ref_map,
953 transport->url);
956 if (fetch_refs(transport, ref_map)) {
957 free_refs(ref_map);
958 retcode = 1;
959 goto cleanup;
961 free_refs(ref_map);
963 /* if neither --no-tags nor --tags was specified, do automated tag
964 * following ... */
965 if (tags == TAGS_DEFAULT && autotags) {
966 struct ref **tail = &ref_map;
967 ref_map = NULL;
968 find_non_local_tags(transport, &ref_map, &tail);
969 if (ref_map)
970 backfill_tags(transport, ref_map);
971 free_refs(ref_map);
974 cleanup:
975 string_list_clear(&existing_refs, 1);
976 return retcode;
979 static int get_one_remote_for_fetch(struct remote *remote, void *priv)
981 struct string_list *list = priv;
982 if (!remote->skip_default_update)
983 string_list_append(list, remote->name);
984 return 0;
987 struct remote_group_data {
988 const char *name;
989 struct string_list *list;
992 static int get_remote_group(const char *key, const char *value, void *priv)
994 struct remote_group_data *g = priv;
996 if (skip_prefix(key, "remotes.", &key) && !strcmp(key, g->name)) {
997 /* split list by white space */
998 while (*value) {
999 size_t wordlen = strcspn(value, " \t\n");
1001 if (wordlen >= 1)
1002 string_list_append(g->list,
1003 xstrndup(value, wordlen));
1004 value += wordlen + (value[wordlen] != '\0');
1008 return 0;
1011 static int add_remote_or_group(const char *name, struct string_list *list)
1013 int prev_nr = list->nr;
1014 struct remote_group_data g;
1015 g.name = name; g.list = list;
1017 git_config(get_remote_group, &g);
1018 if (list->nr == prev_nr) {
1019 struct remote *remote;
1020 if (!remote_is_configured(name))
1021 return 0;
1022 remote = remote_get(name);
1023 string_list_append(list, remote->name);
1025 return 1;
1028 static void add_options_to_argv(struct argv_array *argv)
1030 if (dry_run)
1031 argv_array_push(argv, "--dry-run");
1032 if (prune != -1)
1033 argv_array_push(argv, prune ? "--prune" : "--no-prune");
1034 if (update_head_ok)
1035 argv_array_push(argv, "--update-head-ok");
1036 if (force)
1037 argv_array_push(argv, "--force");
1038 if (keep)
1039 argv_array_push(argv, "--keep");
1040 if (recurse_submodules == RECURSE_SUBMODULES_ON)
1041 argv_array_push(argv, "--recurse-submodules");
1042 else if (recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND)
1043 argv_array_push(argv, "--recurse-submodules=on-demand");
1044 if (tags == TAGS_SET)
1045 argv_array_push(argv, "--tags");
1046 else if (tags == TAGS_UNSET)
1047 argv_array_push(argv, "--no-tags");
1048 if (verbosity >= 2)
1049 argv_array_push(argv, "-v");
1050 if (verbosity >= 1)
1051 argv_array_push(argv, "-v");
1052 else if (verbosity < 0)
1053 argv_array_push(argv, "-q");
1057 static int fetch_multiple(struct string_list *list)
1059 int i, result = 0;
1060 struct argv_array argv = ARGV_ARRAY_INIT;
1062 if (!append && !dry_run) {
1063 int errcode = truncate_fetch_head();
1064 if (errcode)
1065 return errcode;
1068 argv_array_pushl(&argv, "fetch", "--append", NULL);
1069 add_options_to_argv(&argv);
1071 for (i = 0; i < list->nr; i++) {
1072 const char *name = list->items[i].string;
1073 argv_array_push(&argv, name);
1074 if (verbosity >= 0)
1075 printf(_("Fetching %s\n"), name);
1076 if (run_command_v_opt(argv.argv, RUN_GIT_CMD)) {
1077 error(_("Could not fetch %s"), name);
1078 result = 1;
1080 argv_array_pop(&argv);
1083 argv_array_clear(&argv);
1084 return result;
1087 static int fetch_one(struct remote *remote, int argc, const char **argv)
1089 static const char **refs = NULL;
1090 struct refspec *refspec;
1091 int ref_nr = 0;
1092 int exit_code;
1094 if (!remote)
1095 die(_("No remote repository specified. Please, specify either a URL or a\n"
1096 "remote name from which new revisions should be fetched."));
1098 gtransport = prepare_transport(remote);
1100 if (prune < 0) {
1101 /* no command line request */
1102 if (0 <= gtransport->remote->prune)
1103 prune = gtransport->remote->prune;
1104 else if (0 <= fetch_prune_config)
1105 prune = fetch_prune_config;
1106 else
1107 prune = PRUNE_BY_DEFAULT;
1110 if (argc > 0) {
1111 int j = 0;
1112 int i;
1113 refs = xcalloc(argc + 1, sizeof(const char *));
1114 for (i = 0; i < argc; i++) {
1115 if (!strcmp(argv[i], "tag")) {
1116 i++;
1117 if (i >= argc)
1118 die(_("You need to specify a tag name."));
1119 refs[j++] = xstrfmt("refs/tags/%s:refs/tags/%s",
1120 argv[i], argv[i]);
1121 } else
1122 refs[j++] = argv[i];
1124 refs[j] = NULL;
1125 ref_nr = j;
1128 sigchain_push_common(unlock_pack_on_signal);
1129 atexit(unlock_pack);
1130 refspec = parse_fetch_refspec(ref_nr, refs);
1131 exit_code = do_fetch(gtransport, refspec, ref_nr);
1132 free_refspec(ref_nr, refspec);
1133 transport_disconnect(gtransport);
1134 gtransport = NULL;
1135 return exit_code;
1138 int cmd_fetch(int argc, const char **argv, const char *prefix)
1140 int i;
1141 struct string_list list = STRING_LIST_INIT_NODUP;
1142 struct remote *remote;
1143 int result = 0;
1144 struct argv_array argv_gc_auto = ARGV_ARRAY_INIT;
1146 packet_trace_identity("fetch");
1148 /* Record the command line for the reflog */
1149 strbuf_addstr(&default_rla, "fetch");
1150 for (i = 1; i < argc; i++)
1151 strbuf_addf(&default_rla, " %s", argv[i]);
1153 git_config(git_fetch_config, NULL);
1155 argc = parse_options(argc, argv, prefix,
1156 builtin_fetch_options, builtin_fetch_usage, 0);
1158 if (unshallow) {
1159 if (depth)
1160 die(_("--depth and --unshallow cannot be used together"));
1161 else if (!is_repository_shallow())
1162 die(_("--unshallow on a complete repository does not make sense"));
1163 else
1164 depth = xstrfmt("%d", INFINITE_DEPTH);
1167 /* no need to be strict, transport_set_option() will validate it again */
1168 if (depth && atoi(depth) < 1)
1169 die(_("depth %s is not a positive number"), depth);
1171 if (recurse_submodules != RECURSE_SUBMODULES_OFF) {
1172 if (recurse_submodules_default) {
1173 int arg = parse_fetch_recurse_submodules_arg("--recurse-submodules-default", recurse_submodules_default);
1174 set_config_fetch_recurse_submodules(arg);
1176 gitmodules_config();
1177 git_config(submodule_config, NULL);
1180 if (all) {
1181 if (argc == 1)
1182 die(_("fetch --all does not take a repository argument"));
1183 else if (argc > 1)
1184 die(_("fetch --all does not make sense with refspecs"));
1185 (void) for_each_remote(get_one_remote_for_fetch, &list);
1186 result = fetch_multiple(&list);
1187 } else if (argc == 0) {
1188 /* No arguments -- use default remote */
1189 remote = remote_get(NULL);
1190 result = fetch_one(remote, argc, argv);
1191 } else if (multiple) {
1192 /* All arguments are assumed to be remotes or groups */
1193 for (i = 0; i < argc; i++)
1194 if (!add_remote_or_group(argv[i], &list))
1195 die(_("No such remote or remote group: %s"), argv[i]);
1196 result = fetch_multiple(&list);
1197 } else {
1198 /* Single remote or group */
1199 (void) add_remote_or_group(argv[0], &list);
1200 if (list.nr > 1) {
1201 /* More than one remote */
1202 if (argc > 1)
1203 die(_("Fetching a group and specifying refspecs does not make sense"));
1204 result = fetch_multiple(&list);
1205 } else {
1206 /* Zero or one remotes */
1207 remote = remote_get(argv[0]);
1208 result = fetch_one(remote, argc-1, argv+1);
1212 if (!result && (recurse_submodules != RECURSE_SUBMODULES_OFF)) {
1213 struct argv_array options = ARGV_ARRAY_INIT;
1215 add_options_to_argv(&options);
1216 result = fetch_populated_submodules(&options,
1217 submodule_prefix,
1218 recurse_submodules,
1219 verbosity < 0,
1220 max_children);
1221 argv_array_clear(&options);
1224 /* All names were strdup()ed or strndup()ed */
1225 list.strdup_strings = 1;
1226 string_list_clear(&list, 0);
1228 close_all_packs();
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;