l10n: zh_CN: Add translations for Git glossary
[git/mingw.git] / builtin / fetch.c
blob8d5b2dba2bc4251a7c35bc6aa6ff260ea72b7455
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.h"
15 #include "connected.h"
16 #include "argv-array.h"
18 static const char * const builtin_fetch_usage[] = {
19 N_("git fetch [<options>] [<repository> [<refspec>...]]"),
20 N_("git fetch [<options>] <group>"),
21 N_("git fetch --multiple [<options>] [(<repository> | <group>)...]"),
22 N_("git fetch --all [<options>]"),
23 NULL
26 enum {
27 TAGS_UNSET = 0,
28 TAGS_DEFAULT = 1,
29 TAGS_SET = 2
32 static int fetch_prune_config = -1; /* unspecified */
33 static int prune = -1; /* unspecified */
34 #define PRUNE_BY_DEFAULT 0 /* do we prune by default? */
36 static int all, append, dry_run, force, keep, multiple, update_head_ok, verbosity;
37 static int progress = -1, recurse_submodules = RECURSE_SUBMODULES_DEFAULT;
38 static int tags = TAGS_DEFAULT, unshallow, update_shallow;
39 static const char *depth;
40 static const char *upload_pack;
41 static struct strbuf default_rla = STRBUF_INIT;
42 static struct transport *gtransport;
43 static struct transport *gsecondary;
44 static const char *submodule_prefix = "";
45 static const char *recurse_submodules_default;
46 static int shown_url = 0;
47 static int refmap_alloc, refmap_nr;
48 static const char **refmap_array;
50 static int option_parse_recurse_submodules(const struct option *opt,
51 const char *arg, int unset)
53 if (unset) {
54 recurse_submodules = RECURSE_SUBMODULES_OFF;
55 } else {
56 if (arg)
57 recurse_submodules = parse_fetch_recurse_submodules_arg(opt->long_name, arg);
58 else
59 recurse_submodules = RECURSE_SUBMODULES_ON;
61 return 0;
64 static int git_fetch_config(const char *k, const char *v, void *cb)
66 if (!strcmp(k, "fetch.prune")) {
67 fetch_prune_config = git_config_bool(k, v);
68 return 0;
70 return git_default_config(k, v, cb);
73 static int parse_refmap_arg(const struct option *opt, const char *arg, int unset)
75 ALLOC_GROW(refmap_array, refmap_nr + 1, refmap_alloc);
78 * "git fetch --refmap='' origin foo"
79 * can be used to tell the command not to store anywhere
81 if (*arg)
82 refmap_array[refmap_nr++] = arg;
83 return 0;
86 static struct option builtin_fetch_options[] = {
87 OPT__VERBOSITY(&verbosity),
88 OPT_BOOL(0, "all", &all,
89 N_("fetch from all remotes")),
90 OPT_BOOL('a', "append", &append,
91 N_("append to .git/FETCH_HEAD instead of overwriting")),
92 OPT_STRING(0, "upload-pack", &upload_pack, N_("path"),
93 N_("path to upload pack on remote end")),
94 OPT__FORCE(&force, N_("force overwrite of local branch")),
95 OPT_BOOL('m', "multiple", &multiple,
96 N_("fetch from multiple remotes")),
97 OPT_SET_INT('t', "tags", &tags,
98 N_("fetch all tags and associated objects"), TAGS_SET),
99 OPT_SET_INT('n', NULL, &tags,
100 N_("do not fetch all tags (--no-tags)"), TAGS_UNSET),
101 OPT_BOOL('p', "prune", &prune,
102 N_("prune remote-tracking branches no longer on remote")),
103 { OPTION_CALLBACK, 0, "recurse-submodules", NULL, N_("on-demand"),
104 N_("control recursive fetching of submodules"),
105 PARSE_OPT_OPTARG, option_parse_recurse_submodules },
106 OPT_BOOL(0, "dry-run", &dry_run,
107 N_("dry run")),
108 OPT_BOOL('k', "keep", &keep, N_("keep downloaded pack")),
109 OPT_BOOL('u', "update-head-ok", &update_head_ok,
110 N_("allow updating of HEAD ref")),
111 OPT_BOOL(0, "progress", &progress, N_("force progress reporting")),
112 OPT_STRING(0, "depth", &depth, N_("depth"),
113 N_("deepen history of shallow clone")),
114 { OPTION_SET_INT, 0, "unshallow", &unshallow, NULL,
115 N_("convert to a complete repository"),
116 PARSE_OPT_NONEG | PARSE_OPT_NOARG, NULL, 1 },
117 { OPTION_STRING, 0, "submodule-prefix", &submodule_prefix, N_("dir"),
118 N_("prepend this to submodule path output"), PARSE_OPT_HIDDEN },
119 { OPTION_STRING, 0, "recurse-submodules-default",
120 &recurse_submodules_default, NULL,
121 N_("default mode for recursion"), PARSE_OPT_HIDDEN },
122 OPT_BOOL(0, "update-shallow", &update_shallow,
123 N_("accept refs that update .git/shallow")),
124 { OPTION_CALLBACK, 0, "refmap", NULL, N_("refmap"),
125 N_("specify fetch refmap"), PARSE_OPT_NONEG, parse_refmap_arg },
126 OPT_END()
129 static void unlock_pack(void)
131 if (gtransport)
132 transport_unlock_pack(gtransport);
133 if (gsecondary)
134 transport_unlock_pack(gsecondary);
137 static void unlock_pack_on_signal(int signo)
139 unlock_pack();
140 sigchain_pop(signo);
141 raise(signo);
144 static void add_merge_config(struct ref **head,
145 const struct ref *remote_refs,
146 struct branch *branch,
147 struct ref ***tail)
149 int i;
151 for (i = 0; i < branch->merge_nr; i++) {
152 struct ref *rm, **old_tail = *tail;
153 struct refspec refspec;
155 for (rm = *head; rm; rm = rm->next) {
156 if (branch_merge_matches(branch, i, rm->name)) {
157 rm->fetch_head_status = FETCH_HEAD_MERGE;
158 break;
161 if (rm)
162 continue;
165 * Not fetched to a remote-tracking branch? We need to fetch
166 * it anyway to allow this branch's "branch.$name.merge"
167 * to be honored by 'git pull', but we do not have to
168 * fail if branch.$name.merge is misconfigured to point
169 * at a nonexisting branch. If we were indeed called by
170 * 'git pull', it will notice the misconfiguration because
171 * there is no entry in the resulting FETCH_HEAD marked
172 * for merging.
174 memset(&refspec, 0, sizeof(refspec));
175 refspec.src = branch->merge[i]->src;
176 get_fetch_map(remote_refs, &refspec, tail, 1);
177 for (rm = *old_tail; rm; rm = rm->next)
178 rm->fetch_head_status = FETCH_HEAD_MERGE;
182 static int add_existing(const char *refname, const struct object_id *oid,
183 int flag, void *cbdata)
185 struct string_list *list = (struct string_list *)cbdata;
186 struct string_list_item *item = string_list_insert(list, refname);
187 struct object_id *old_oid = xmalloc(sizeof(*old_oid));
189 oidcpy(old_oid, oid);
190 item->util = old_oid;
191 return 0;
194 static int will_fetch(struct ref **head, const unsigned char *sha1)
196 struct ref *rm = *head;
197 while (rm) {
198 if (!hashcmp(rm->old_sha1, sha1))
199 return 1;
200 rm = rm->next;
202 return 0;
205 static void find_non_local_tags(struct transport *transport,
206 struct ref **head,
207 struct ref ***tail)
209 struct string_list existing_refs = STRING_LIST_INIT_DUP;
210 struct string_list remote_refs = STRING_LIST_INIT_NODUP;
211 const struct ref *ref;
212 struct string_list_item *item = NULL;
214 for_each_ref(add_existing, &existing_refs);
215 for (ref = transport_get_remote_refs(transport); ref; ref = ref->next) {
216 if (!starts_with(ref->name, "refs/tags/"))
217 continue;
220 * The peeled ref always follows the matching base
221 * ref, so if we see a peeled ref that we don't want
222 * to fetch then we can mark the ref entry in the list
223 * as one to ignore by setting util to NULL.
225 if (ends_with(ref->name, "^{}")) {
226 if (item && !has_sha1_file(ref->old_sha1) &&
227 !will_fetch(head, ref->old_sha1) &&
228 !has_sha1_file(item->util) &&
229 !will_fetch(head, item->util))
230 item->util = NULL;
231 item = NULL;
232 continue;
236 * If item is non-NULL here, then we previously saw a
237 * ref not followed by a peeled reference, so we need
238 * to check if it is a lightweight tag that we want to
239 * fetch.
241 if (item && !has_sha1_file(item->util) &&
242 !will_fetch(head, item->util))
243 item->util = NULL;
245 item = NULL;
247 /* skip duplicates and refs that we already have */
248 if (string_list_has_string(&remote_refs, ref->name) ||
249 string_list_has_string(&existing_refs, ref->name))
250 continue;
252 item = string_list_insert(&remote_refs, ref->name);
253 item->util = (void *)ref->old_sha1;
255 string_list_clear(&existing_refs, 1);
258 * We may have a final lightweight tag that needs to be
259 * checked to see if it needs fetching.
261 if (item && !has_sha1_file(item->util) &&
262 !will_fetch(head, item->util))
263 item->util = NULL;
266 * For all the tags in the remote_refs string list,
267 * add them to the list of refs to be fetched
269 for_each_string_list_item(item, &remote_refs) {
270 /* Unless we have already decided to ignore this item... */
271 if (item->util)
273 struct ref *rm = alloc_ref(item->string);
274 rm->peer_ref = alloc_ref(item->string);
275 hashcpy(rm->old_sha1, item->util);
276 **tail = rm;
277 *tail = &rm->next;
281 string_list_clear(&remote_refs, 0);
284 static struct ref *get_ref_map(struct transport *transport,
285 struct refspec *refspecs, int refspec_count,
286 int tags, int *autotags)
288 int i;
289 struct ref *rm;
290 struct ref *ref_map = NULL;
291 struct ref **tail = &ref_map;
293 /* opportunistically-updated references: */
294 struct ref *orefs = NULL, **oref_tail = &orefs;
296 const struct ref *remote_refs = transport_get_remote_refs(transport);
298 if (refspec_count) {
299 struct refspec *fetch_refspec;
300 int fetch_refspec_nr;
302 for (i = 0; i < refspec_count; i++) {
303 get_fetch_map(remote_refs, &refspecs[i], &tail, 0);
304 if (refspecs[i].dst && refspecs[i].dst[0])
305 *autotags = 1;
307 /* Merge everything on the command line (but not --tags) */
308 for (rm = ref_map; rm; rm = rm->next)
309 rm->fetch_head_status = FETCH_HEAD_MERGE;
312 * For any refs that we happen to be fetching via
313 * command-line arguments, the destination ref might
314 * have been missing or have been different than the
315 * remote-tracking ref that would be derived from the
316 * configured refspec. In these cases, we want to
317 * take the opportunity to update their configured
318 * remote-tracking reference. However, we do not want
319 * to mention these entries in FETCH_HEAD at all, as
320 * they would simply be duplicates of existing
321 * entries, so we set them FETCH_HEAD_IGNORE below.
323 * We compute these entries now, based only on the
324 * refspecs specified on the command line. But we add
325 * them to the list following the refspecs resulting
326 * from the tags option so that one of the latter,
327 * which has FETCH_HEAD_NOT_FOR_MERGE, is not removed
328 * by ref_remove_duplicates() in favor of one of these
329 * opportunistic entries with FETCH_HEAD_IGNORE.
331 if (refmap_array) {
332 fetch_refspec = parse_fetch_refspec(refmap_nr, refmap_array);
333 fetch_refspec_nr = refmap_nr;
334 } else {
335 fetch_refspec = transport->remote->fetch;
336 fetch_refspec_nr = transport->remote->fetch_refspec_nr;
339 for (i = 0; i < fetch_refspec_nr; i++)
340 get_fetch_map(ref_map, &fetch_refspec[i], &oref_tail, 1);
342 if (tags == TAGS_SET)
343 get_fetch_map(remote_refs, tag_refspec, &tail, 0);
344 } else if (refmap_array) {
345 die("--refmap option is only meaningful with command-line refspec(s).");
346 } else {
347 /* Use the defaults */
348 struct remote *remote = transport->remote;
349 struct branch *branch = branch_get(NULL);
350 int has_merge = branch_has_merge_config(branch);
351 if (remote &&
352 (remote->fetch_refspec_nr ||
353 /* Note: has_merge implies non-NULL branch->remote_name */
354 (has_merge && !strcmp(branch->remote_name, remote->name)))) {
355 for (i = 0; i < remote->fetch_refspec_nr; i++) {
356 get_fetch_map(remote_refs, &remote->fetch[i], &tail, 0);
357 if (remote->fetch[i].dst &&
358 remote->fetch[i].dst[0])
359 *autotags = 1;
360 if (!i && !has_merge && ref_map &&
361 !remote->fetch[0].pattern)
362 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
365 * if the remote we're fetching from is the same
366 * as given in branch.<name>.remote, we add the
367 * ref given in branch.<name>.merge, too.
369 * Note: has_merge implies non-NULL branch->remote_name
371 if (has_merge &&
372 !strcmp(branch->remote_name, remote->name))
373 add_merge_config(&ref_map, remote_refs, branch, &tail);
374 } else {
375 ref_map = get_remote_ref(remote_refs, "HEAD");
376 if (!ref_map)
377 die(_("Couldn't find remote ref HEAD"));
378 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
379 tail = &ref_map->next;
383 if (tags == TAGS_SET)
384 /* also fetch all tags */
385 get_fetch_map(remote_refs, tag_refspec, &tail, 0);
386 else if (tags == TAGS_DEFAULT && *autotags)
387 find_non_local_tags(transport, &ref_map, &tail);
389 /* Now append any refs to be updated opportunistically: */
390 *tail = orefs;
391 for (rm = orefs; rm; rm = rm->next) {
392 rm->fetch_head_status = FETCH_HEAD_IGNORE;
393 tail = &rm->next;
396 return ref_remove_duplicates(ref_map);
399 #define STORE_REF_ERROR_OTHER 1
400 #define STORE_REF_ERROR_DF_CONFLICT 2
402 static int s_update_ref(const char *action,
403 struct ref *ref,
404 int check_old)
406 char msg[1024];
407 char *rla = getenv("GIT_REFLOG_ACTION");
408 struct ref_transaction *transaction;
409 struct strbuf err = STRBUF_INIT;
410 int ret, df_conflict = 0;
412 if (dry_run)
413 return 0;
414 if (!rla)
415 rla = default_rla.buf;
416 snprintf(msg, sizeof(msg), "%s: %s", rla, action);
418 transaction = ref_transaction_begin(&err);
419 if (!transaction ||
420 ref_transaction_update(transaction, ref->name,
421 ref->new_sha1,
422 check_old ? ref->old_sha1 : NULL,
423 0, msg, &err))
424 goto fail;
426 ret = ref_transaction_commit(transaction, &err);
427 if (ret) {
428 df_conflict = (ret == TRANSACTION_NAME_CONFLICT);
429 goto fail;
432 ref_transaction_free(transaction);
433 strbuf_release(&err);
434 return 0;
435 fail:
436 ref_transaction_free(transaction);
437 error("%s", err.buf);
438 strbuf_release(&err);
439 return df_conflict ? STORE_REF_ERROR_DF_CONFLICT
440 : STORE_REF_ERROR_OTHER;
443 #define REFCOL_WIDTH 10
445 static int update_local_ref(struct ref *ref,
446 const char *remote,
447 const struct ref *remote_ref,
448 struct strbuf *display)
450 struct commit *current = NULL, *updated;
451 enum object_type type;
452 struct branch *current_branch = branch_get(NULL);
453 const char *pretty_ref = prettify_refname(ref->name);
455 type = sha1_object_info(ref->new_sha1, NULL);
456 if (type < 0)
457 die(_("object %s not found"), sha1_to_hex(ref->new_sha1));
459 if (!hashcmp(ref->old_sha1, ref->new_sha1)) {
460 if (verbosity > 0)
461 strbuf_addf(display, "= %-*s %-*s -> %s",
462 TRANSPORT_SUMMARY(_("[up to date]")),
463 REFCOL_WIDTH, remote, pretty_ref);
464 return 0;
467 if (current_branch &&
468 !strcmp(ref->name, current_branch->name) &&
469 !(update_head_ok || is_bare_repository()) &&
470 !is_null_sha1(ref->old_sha1)) {
472 * If this is the head, and it's not okay to update
473 * the head, and the old value of the head isn't empty...
475 strbuf_addf(display,
476 _("! %-*s %-*s -> %s (can't fetch in current branch)"),
477 TRANSPORT_SUMMARY(_("[rejected]")),
478 REFCOL_WIDTH, remote, pretty_ref);
479 return 1;
482 if (!is_null_sha1(ref->old_sha1) &&
483 starts_with(ref->name, "refs/tags/")) {
484 int r;
485 r = s_update_ref("updating tag", ref, 0);
486 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
487 r ? '!' : '-',
488 TRANSPORT_SUMMARY(_("[tag update]")),
489 REFCOL_WIDTH, remote, pretty_ref,
490 r ? _(" (unable to update local ref)") : "");
491 return r;
494 current = lookup_commit_reference_gently(ref->old_sha1, 1);
495 updated = lookup_commit_reference_gently(ref->new_sha1, 1);
496 if (!current || !updated) {
497 const char *msg;
498 const char *what;
499 int r;
501 * Nicely describe the new ref we're fetching.
502 * Base this on the remote's ref name, as it's
503 * more likely to follow a standard layout.
505 const char *name = remote_ref ? remote_ref->name : "";
506 if (starts_with(name, "refs/tags/")) {
507 msg = "storing tag";
508 what = _("[new tag]");
509 } else if (starts_with(name, "refs/heads/")) {
510 msg = "storing head";
511 what = _("[new branch]");
512 } else {
513 msg = "storing ref";
514 what = _("[new ref]");
517 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
518 (recurse_submodules != RECURSE_SUBMODULES_ON))
519 check_for_new_submodule_commits(ref->new_sha1);
520 r = s_update_ref(msg, ref, 0);
521 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
522 r ? '!' : '*',
523 TRANSPORT_SUMMARY(what),
524 REFCOL_WIDTH, remote, pretty_ref,
525 r ? _(" (unable to update local ref)") : "");
526 return r;
529 if (in_merge_bases(current, updated)) {
530 char quickref[83];
531 int r;
532 strcpy(quickref, find_unique_abbrev(current->object.sha1, DEFAULT_ABBREV));
533 strcat(quickref, "..");
534 strcat(quickref, find_unique_abbrev(ref->new_sha1, DEFAULT_ABBREV));
535 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
536 (recurse_submodules != RECURSE_SUBMODULES_ON))
537 check_for_new_submodule_commits(ref->new_sha1);
538 r = s_update_ref("fast-forward", ref, 1);
539 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
540 r ? '!' : ' ',
541 TRANSPORT_SUMMARY_WIDTH, quickref,
542 REFCOL_WIDTH, remote, pretty_ref,
543 r ? _(" (unable to update local ref)") : "");
544 return r;
545 } else if (force || ref->force) {
546 char quickref[84];
547 int r;
548 strcpy(quickref, find_unique_abbrev(current->object.sha1, DEFAULT_ABBREV));
549 strcat(quickref, "...");
550 strcat(quickref, find_unique_abbrev(ref->new_sha1, DEFAULT_ABBREV));
551 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
552 (recurse_submodules != RECURSE_SUBMODULES_ON))
553 check_for_new_submodule_commits(ref->new_sha1);
554 r = s_update_ref("forced-update", ref, 1);
555 strbuf_addf(display, "%c %-*s %-*s -> %s (%s)",
556 r ? '!' : '+',
557 TRANSPORT_SUMMARY_WIDTH, quickref,
558 REFCOL_WIDTH, remote, pretty_ref,
559 r ? _("unable to update local ref") : _("forced update"));
560 return r;
561 } else {
562 strbuf_addf(display, "! %-*s %-*s -> %s %s",
563 TRANSPORT_SUMMARY(_("[rejected]")),
564 REFCOL_WIDTH, remote, pretty_ref,
565 _("(non-fast-forward)"));
566 return 1;
570 static int iterate_ref_map(void *cb_data, unsigned char sha1[20])
572 struct ref **rm = cb_data;
573 struct ref *ref = *rm;
575 while (ref && ref->status == REF_STATUS_REJECT_SHALLOW)
576 ref = ref->next;
577 if (!ref)
578 return -1; /* end of the list */
579 *rm = ref->next;
580 hashcpy(sha1, ref->old_sha1);
581 return 0;
584 static int store_updated_refs(const char *raw_url, const char *remote_name,
585 struct ref *ref_map)
587 FILE *fp;
588 struct commit *commit;
589 int url_len, i, rc = 0;
590 struct strbuf note = STRBUF_INIT;
591 const char *what, *kind;
592 struct ref *rm;
593 char *url;
594 const char *filename = dry_run ? "/dev/null" : git_path("FETCH_HEAD");
595 int want_status;
597 fp = fopen(filename, "a");
598 if (!fp)
599 return error(_("cannot open %s: %s\n"), filename, strerror(errno));
601 if (raw_url)
602 url = transport_anonymize_url(raw_url);
603 else
604 url = xstrdup("foreign");
606 rm = ref_map;
607 if (check_everything_connected(iterate_ref_map, 0, &rm)) {
608 rc = error(_("%s did not send all necessary objects\n"), url);
609 goto abort;
613 * We do a pass for each fetch_head_status type in their enum order, so
614 * merged entries are written before not-for-merge. That lets readers
615 * use FETCH_HEAD as a refname to refer to the ref to be merged.
617 for (want_status = FETCH_HEAD_MERGE;
618 want_status <= FETCH_HEAD_IGNORE;
619 want_status++) {
620 for (rm = ref_map; rm; rm = rm->next) {
621 struct ref *ref = NULL;
622 const char *merge_status_marker = "";
624 if (rm->status == REF_STATUS_REJECT_SHALLOW) {
625 if (want_status == FETCH_HEAD_MERGE)
626 warning(_("reject %s because shallow roots are not allowed to be updated"),
627 rm->peer_ref ? rm->peer_ref->name : rm->name);
628 continue;
631 commit = lookup_commit_reference_gently(rm->old_sha1, 1);
632 if (!commit)
633 rm->fetch_head_status = FETCH_HEAD_NOT_FOR_MERGE;
635 if (rm->fetch_head_status != want_status)
636 continue;
638 if (rm->peer_ref) {
639 ref = xcalloc(1, sizeof(*ref) + strlen(rm->peer_ref->name) + 1);
640 strcpy(ref->name, rm->peer_ref->name);
641 hashcpy(ref->old_sha1, rm->peer_ref->old_sha1);
642 hashcpy(ref->new_sha1, rm->old_sha1);
643 ref->force = rm->peer_ref->force;
647 if (!strcmp(rm->name, "HEAD")) {
648 kind = "";
649 what = "";
651 else if (starts_with(rm->name, "refs/heads/")) {
652 kind = "branch";
653 what = rm->name + 11;
655 else if (starts_with(rm->name, "refs/tags/")) {
656 kind = "tag";
657 what = rm->name + 10;
659 else if (starts_with(rm->name, "refs/remotes/")) {
660 kind = "remote-tracking branch";
661 what = rm->name + 13;
663 else {
664 kind = "";
665 what = rm->name;
668 url_len = strlen(url);
669 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
671 url_len = i + 1;
672 if (4 < i && !strncmp(".git", url + i - 3, 4))
673 url_len = i - 3;
675 strbuf_reset(&note);
676 if (*what) {
677 if (*kind)
678 strbuf_addf(&note, "%s ", kind);
679 strbuf_addf(&note, "'%s' of ", what);
681 switch (rm->fetch_head_status) {
682 case FETCH_HEAD_NOT_FOR_MERGE:
683 merge_status_marker = "not-for-merge";
684 /* fall-through */
685 case FETCH_HEAD_MERGE:
686 fprintf(fp, "%s\t%s\t%s",
687 sha1_to_hex(rm->old_sha1),
688 merge_status_marker,
689 note.buf);
690 for (i = 0; i < url_len; ++i)
691 if ('\n' == url[i])
692 fputs("\\n", fp);
693 else
694 fputc(url[i], fp);
695 fputc('\n', fp);
696 break;
697 default:
698 /* do not write anything to FETCH_HEAD */
699 break;
702 strbuf_reset(&note);
703 if (ref) {
704 rc |= update_local_ref(ref, what, rm, &note);
705 free(ref);
706 } else
707 strbuf_addf(&note, "* %-*s %-*s -> FETCH_HEAD",
708 TRANSPORT_SUMMARY_WIDTH,
709 *kind ? kind : "branch",
710 REFCOL_WIDTH,
711 *what ? what : "HEAD");
712 if (note.len) {
713 if (verbosity >= 0 && !shown_url) {
714 fprintf(stderr, _("From %.*s\n"),
715 url_len, url);
716 shown_url = 1;
718 if (verbosity >= 0)
719 fprintf(stderr, " %s\n", note.buf);
724 if (rc & STORE_REF_ERROR_DF_CONFLICT)
725 error(_("some local refs could not be updated; try running\n"
726 " 'git remote prune %s' to remove any old, conflicting "
727 "branches"), remote_name);
729 abort:
730 strbuf_release(&note);
731 free(url);
732 fclose(fp);
733 return rc;
737 * We would want to bypass the object transfer altogether if
738 * everything we are going to fetch already exists and is connected
739 * locally.
741 static int quickfetch(struct ref *ref_map)
743 struct ref *rm = ref_map;
746 * If we are deepening a shallow clone we already have these
747 * objects reachable. Running rev-list here will return with
748 * a good (0) exit status and we'll bypass the fetch that we
749 * really need to perform. Claiming failure now will ensure
750 * we perform the network exchange to deepen our history.
752 if (depth)
753 return -1;
754 return check_everything_connected(iterate_ref_map, 1, &rm);
757 static int fetch_refs(struct transport *transport, struct ref *ref_map)
759 int ret = quickfetch(ref_map);
760 if (ret)
761 ret = transport_fetch_refs(transport, ref_map);
762 if (!ret)
763 ret |= store_updated_refs(transport->url,
764 transport->remote->name,
765 ref_map);
766 transport_unlock_pack(transport);
767 return ret;
770 static int prune_refs(struct refspec *refs, int ref_count, struct ref *ref_map,
771 const char *raw_url)
773 int url_len, i, result = 0;
774 struct ref *ref, *stale_refs = get_stale_heads(refs, ref_count, ref_map);
775 char *url;
776 const char *dangling_msg = dry_run
777 ? _(" (%s will become dangling)")
778 : _(" (%s has become dangling)");
780 if (raw_url)
781 url = transport_anonymize_url(raw_url);
782 else
783 url = xstrdup("foreign");
785 url_len = strlen(url);
786 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
789 url_len = i + 1;
790 if (4 < i && !strncmp(".git", url + i - 3, 4))
791 url_len = i - 3;
793 for (ref = stale_refs; ref; ref = ref->next) {
794 if (!dry_run)
795 result |= delete_ref(ref->name, NULL, 0);
796 if (verbosity >= 0 && !shown_url) {
797 fprintf(stderr, _("From %.*s\n"), url_len, url);
798 shown_url = 1;
800 if (verbosity >= 0) {
801 fprintf(stderr, " x %-*s %-*s -> %s\n",
802 TRANSPORT_SUMMARY(_("[deleted]")),
803 REFCOL_WIDTH, _("(none)"), prettify_refname(ref->name));
804 warn_dangling_symref(stderr, dangling_msg, ref->name);
807 free(url);
808 free_refs(stale_refs);
809 return result;
812 static void check_not_current_branch(struct ref *ref_map)
814 struct branch *current_branch = branch_get(NULL);
816 if (is_bare_repository() || !current_branch)
817 return;
819 for (; ref_map; ref_map = ref_map->next)
820 if (ref_map->peer_ref && !strcmp(current_branch->refname,
821 ref_map->peer_ref->name))
822 die(_("Refusing to fetch into current branch %s "
823 "of non-bare repository"), current_branch->refname);
826 static int truncate_fetch_head(void)
828 const char *filename = git_path("FETCH_HEAD");
829 FILE *fp = fopen(filename, "w");
831 if (!fp)
832 return error(_("cannot open %s: %s\n"), filename, strerror(errno));
833 fclose(fp);
834 return 0;
837 static void set_option(struct transport *transport, const char *name, const char *value)
839 int r = transport_set_option(transport, name, value);
840 if (r < 0)
841 die(_("Option \"%s\" value \"%s\" is not valid for %s"),
842 name, value, transport->url);
843 if (r > 0)
844 warning(_("Option \"%s\" is ignored for %s\n"),
845 name, transport->url);
848 static struct transport *prepare_transport(struct remote *remote)
850 struct transport *transport;
851 transport = transport_get(remote, NULL);
852 transport_set_verbosity(transport, verbosity, progress);
853 if (upload_pack)
854 set_option(transport, TRANS_OPT_UPLOADPACK, upload_pack);
855 if (keep)
856 set_option(transport, TRANS_OPT_KEEP, "yes");
857 if (depth)
858 set_option(transport, TRANS_OPT_DEPTH, depth);
859 if (update_shallow)
860 set_option(transport, TRANS_OPT_UPDATE_SHALLOW, "yes");
861 return transport;
864 static void backfill_tags(struct transport *transport, struct ref *ref_map)
866 if (transport->cannot_reuse) {
867 gsecondary = prepare_transport(transport->remote);
868 transport = gsecondary;
871 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
872 transport_set_option(transport, TRANS_OPT_DEPTH, "0");
873 fetch_refs(transport, ref_map);
875 if (gsecondary) {
876 transport_disconnect(gsecondary);
877 gsecondary = NULL;
881 static int do_fetch(struct transport *transport,
882 struct refspec *refs, int ref_count)
884 struct string_list existing_refs = STRING_LIST_INIT_DUP;
885 struct ref *ref_map;
886 struct ref *rm;
887 int autotags = (transport->remote->fetch_tags == 1);
888 int retcode = 0;
890 for_each_ref(add_existing, &existing_refs);
892 if (tags == TAGS_DEFAULT) {
893 if (transport->remote->fetch_tags == 2)
894 tags = TAGS_SET;
895 if (transport->remote->fetch_tags == -1)
896 tags = TAGS_UNSET;
899 if (!transport->get_refs_list || !transport->fetch)
900 die(_("Don't know how to fetch from %s"), transport->url);
902 /* if not appending, truncate FETCH_HEAD */
903 if (!append && !dry_run) {
904 retcode = truncate_fetch_head();
905 if (retcode)
906 goto cleanup;
909 ref_map = get_ref_map(transport, refs, ref_count, tags, &autotags);
910 if (!update_head_ok)
911 check_not_current_branch(ref_map);
913 for (rm = ref_map; rm; rm = rm->next) {
914 if (rm->peer_ref) {
915 struct string_list_item *peer_item =
916 string_list_lookup(&existing_refs,
917 rm->peer_ref->name);
918 if (peer_item) {
919 struct object_id *old_oid = peer_item->util;
920 hashcpy(rm->peer_ref->old_sha1, old_oid->hash);
925 if (tags == TAGS_DEFAULT && autotags)
926 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
927 if (prune) {
929 * We only prune based on refspecs specified
930 * explicitly (via command line or configuration); we
931 * don't care whether --tags was specified.
933 if (ref_count) {
934 prune_refs(refs, ref_count, ref_map, transport->url);
935 } else {
936 prune_refs(transport->remote->fetch,
937 transport->remote->fetch_refspec_nr,
938 ref_map,
939 transport->url);
942 if (fetch_refs(transport, ref_map)) {
943 free_refs(ref_map);
944 retcode = 1;
945 goto cleanup;
947 free_refs(ref_map);
949 /* if neither --no-tags nor --tags was specified, do automated tag
950 * following ... */
951 if (tags == TAGS_DEFAULT && autotags) {
952 struct ref **tail = &ref_map;
953 ref_map = NULL;
954 find_non_local_tags(transport, &ref_map, &tail);
955 if (ref_map)
956 backfill_tags(transport, ref_map);
957 free_refs(ref_map);
960 cleanup:
961 string_list_clear(&existing_refs, 1);
962 return retcode;
965 static int get_one_remote_for_fetch(struct remote *remote, void *priv)
967 struct string_list *list = priv;
968 if (!remote->skip_default_update)
969 string_list_append(list, remote->name);
970 return 0;
973 struct remote_group_data {
974 const char *name;
975 struct string_list *list;
978 static int get_remote_group(const char *key, const char *value, void *priv)
980 struct remote_group_data *g = priv;
982 if (starts_with(key, "remotes.") &&
983 !strcmp(key + 8, g->name)) {
984 /* split list by white space */
985 int space = strcspn(value, " \t\n");
986 while (*value) {
987 if (space > 1) {
988 string_list_append(g->list,
989 xstrndup(value, space));
991 value += space + (value[space] != '\0');
992 space = strcspn(value, " \t\n");
996 return 0;
999 static int add_remote_or_group(const char *name, struct string_list *list)
1001 int prev_nr = list->nr;
1002 struct remote_group_data g;
1003 g.name = name; g.list = list;
1005 git_config(get_remote_group, &g);
1006 if (list->nr == prev_nr) {
1007 struct remote *remote;
1008 if (!remote_is_configured(name))
1009 return 0;
1010 remote = remote_get(name);
1011 string_list_append(list, remote->name);
1013 return 1;
1016 static void add_options_to_argv(struct argv_array *argv)
1018 if (dry_run)
1019 argv_array_push(argv, "--dry-run");
1020 if (prune != -1)
1021 argv_array_push(argv, prune ? "--prune" : "--no-prune");
1022 if (update_head_ok)
1023 argv_array_push(argv, "--update-head-ok");
1024 if (force)
1025 argv_array_push(argv, "--force");
1026 if (keep)
1027 argv_array_push(argv, "--keep");
1028 if (recurse_submodules == RECURSE_SUBMODULES_ON)
1029 argv_array_push(argv, "--recurse-submodules");
1030 else if (recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND)
1031 argv_array_push(argv, "--recurse-submodules=on-demand");
1032 if (tags == TAGS_SET)
1033 argv_array_push(argv, "--tags");
1034 else if (tags == TAGS_UNSET)
1035 argv_array_push(argv, "--no-tags");
1036 if (verbosity >= 2)
1037 argv_array_push(argv, "-v");
1038 if (verbosity >= 1)
1039 argv_array_push(argv, "-v");
1040 else if (verbosity < 0)
1041 argv_array_push(argv, "-q");
1045 static int fetch_multiple(struct string_list *list)
1047 int i, result = 0;
1048 struct argv_array argv = ARGV_ARRAY_INIT;
1050 if (!append && !dry_run) {
1051 int errcode = truncate_fetch_head();
1052 if (errcode)
1053 return errcode;
1056 argv_array_pushl(&argv, "fetch", "--append", NULL);
1057 add_options_to_argv(&argv);
1059 for (i = 0; i < list->nr; i++) {
1060 const char *name = list->items[i].string;
1061 argv_array_push(&argv, name);
1062 if (verbosity >= 0)
1063 printf(_("Fetching %s\n"), name);
1064 if (run_command_v_opt(argv.argv, RUN_GIT_CMD)) {
1065 error(_("Could not fetch %s"), name);
1066 result = 1;
1068 argv_array_pop(&argv);
1071 argv_array_clear(&argv);
1072 return result;
1075 static int fetch_one(struct remote *remote, int argc, const char **argv)
1077 static const char **refs = NULL;
1078 struct refspec *refspec;
1079 int ref_nr = 0;
1080 int exit_code;
1082 if (!remote)
1083 die(_("No remote repository specified. Please, specify either a URL or a\n"
1084 "remote name from which new revisions should be fetched."));
1086 gtransport = prepare_transport(remote);
1088 if (prune < 0) {
1089 /* no command line request */
1090 if (0 <= gtransport->remote->prune)
1091 prune = gtransport->remote->prune;
1092 else if (0 <= fetch_prune_config)
1093 prune = fetch_prune_config;
1094 else
1095 prune = PRUNE_BY_DEFAULT;
1098 if (argc > 0) {
1099 int j = 0;
1100 int i;
1101 refs = xcalloc(argc + 1, sizeof(const char *));
1102 for (i = 0; i < argc; i++) {
1103 if (!strcmp(argv[i], "tag")) {
1104 i++;
1105 if (i >= argc)
1106 die(_("You need to specify a tag name."));
1107 refs[j++] = xstrfmt("refs/tags/%s:refs/tags/%s",
1108 argv[i], argv[i]);
1109 } else
1110 refs[j++] = argv[i];
1112 refs[j] = NULL;
1113 ref_nr = j;
1116 sigchain_push_common(unlock_pack_on_signal);
1117 atexit(unlock_pack);
1118 refspec = parse_fetch_refspec(ref_nr, refs);
1119 exit_code = do_fetch(gtransport, refspec, ref_nr);
1120 free_refspec(ref_nr, refspec);
1121 transport_disconnect(gtransport);
1122 gtransport = NULL;
1123 return exit_code;
1126 int cmd_fetch(int argc, const char **argv, const char *prefix)
1128 int i;
1129 struct string_list list = STRING_LIST_INIT_NODUP;
1130 struct remote *remote;
1131 int result = 0;
1132 struct argv_array argv_gc_auto = ARGV_ARRAY_INIT;
1134 packet_trace_identity("fetch");
1136 /* Record the command line for the reflog */
1137 strbuf_addstr(&default_rla, "fetch");
1138 for (i = 1; i < argc; i++)
1139 strbuf_addf(&default_rla, " %s", argv[i]);
1141 git_config(git_fetch_config, NULL);
1143 argc = parse_options(argc, argv, prefix,
1144 builtin_fetch_options, builtin_fetch_usage, 0);
1146 if (unshallow) {
1147 if (depth)
1148 die(_("--depth and --unshallow cannot be used together"));
1149 else if (!is_repository_shallow())
1150 die(_("--unshallow on a complete repository does not make sense"));
1151 else {
1152 static char inf_depth[12];
1153 sprintf(inf_depth, "%d", INFINITE_DEPTH);
1154 depth = inf_depth;
1158 /* no need to be strict, transport_set_option() will validate it again */
1159 if (depth && atoi(depth) < 1)
1160 die(_("depth %s is not a positive number"), depth);
1162 if (recurse_submodules != RECURSE_SUBMODULES_OFF) {
1163 if (recurse_submodules_default) {
1164 int arg = parse_fetch_recurse_submodules_arg("--recurse-submodules-default", recurse_submodules_default);
1165 set_config_fetch_recurse_submodules(arg);
1167 gitmodules_config();
1168 git_config(submodule_config, NULL);
1171 if (all) {
1172 if (argc == 1)
1173 die(_("fetch --all does not take a repository argument"));
1174 else if (argc > 1)
1175 die(_("fetch --all does not make sense with refspecs"));
1176 (void) for_each_remote(get_one_remote_for_fetch, &list);
1177 result = fetch_multiple(&list);
1178 } else if (argc == 0) {
1179 /* No arguments -- use default remote */
1180 remote = remote_get(NULL);
1181 result = fetch_one(remote, argc, argv);
1182 } else if (multiple) {
1183 /* All arguments are assumed to be remotes or groups */
1184 for (i = 0; i < argc; i++)
1185 if (!add_remote_or_group(argv[i], &list))
1186 die(_("No such remote or remote group: %s"), argv[i]);
1187 result = fetch_multiple(&list);
1188 } else {
1189 /* Single remote or group */
1190 (void) add_remote_or_group(argv[0], &list);
1191 if (list.nr > 1) {
1192 /* More than one remote */
1193 if (argc > 1)
1194 die(_("Fetching a group and specifying refspecs does not make sense"));
1195 result = fetch_multiple(&list);
1196 } else {
1197 /* Zero or one remotes */
1198 remote = remote_get(argv[0]);
1199 result = fetch_one(remote, argc-1, argv+1);
1203 if (!result && (recurse_submodules != RECURSE_SUBMODULES_OFF)) {
1204 struct argv_array options = ARGV_ARRAY_INIT;
1206 add_options_to_argv(&options);
1207 result = fetch_populated_submodules(&options,
1208 submodule_prefix,
1209 recurse_submodules,
1210 verbosity < 0);
1211 argv_array_clear(&options);
1214 /* All names were strdup()ed or strndup()ed */
1215 list.strdup_strings = 1;
1216 string_list_clear(&list, 0);
1218 argv_array_pushl(&argv_gc_auto, "gc", "--auto", NULL);
1219 if (verbosity < 0)
1220 argv_array_push(&argv_gc_auto, "--quiet");
1221 run_command_v_opt(argv_gc_auto.argv, RUN_GIT_CMD);
1222 argv_array_clear(&argv_gc_auto);
1224 return result;