Merge branch 'ds/partial-bundles'
[alt-git.git] / builtin / clone.c
blob52316563795fe34638b3ae22263ebf4e5f456ca5
1 /*
2 * Builtin "git clone"
4 * Copyright (c) 2007 Kristian Høgsberg <krh@redhat.com>,
5 * 2008 Daniel Barkalow <barkalow@iabervon.org>
6 * Based on git-commit.sh by Junio C Hamano and Linus Torvalds
8 * Clone a repository into a different directory that does not yet exist.
9 */
11 #define USE_THE_INDEX_COMPATIBILITY_MACROS
12 #include "builtin.h"
13 #include "config.h"
14 #include "lockfile.h"
15 #include "parse-options.h"
16 #include "fetch-pack.h"
17 #include "refs.h"
18 #include "refspec.h"
19 #include "object-store.h"
20 #include "tree.h"
21 #include "tree-walk.h"
22 #include "unpack-trees.h"
23 #include "transport.h"
24 #include "strbuf.h"
25 #include "dir.h"
26 #include "dir-iterator.h"
27 #include "iterator.h"
28 #include "sigchain.h"
29 #include "branch.h"
30 #include "remote.h"
31 #include "run-command.h"
32 #include "connected.h"
33 #include "packfile.h"
34 #include "list-objects-filter-options.h"
35 #include "hook.h"
36 #include "bundle.h"
39 * Overall FIXMEs:
40 * - respect DB_ENVIRONMENT for .git/objects.
42 * Implementation notes:
43 * - dropping use-separate-remote and no-separate-remote compatibility
46 static const char * const builtin_clone_usage[] = {
47 N_("git clone [<options>] [--] <repo> [<dir>]"),
48 NULL
51 static int option_no_checkout, option_bare, option_mirror, option_single_branch = -1;
52 static int option_local = -1, option_no_hardlinks, option_shared;
53 static int option_no_tags;
54 static int option_shallow_submodules;
55 static int option_reject_shallow = -1; /* unspecified */
56 static int config_reject_shallow = -1; /* unspecified */
57 static int deepen;
58 static char *option_template, *option_depth, *option_since;
59 static char *option_origin = NULL;
60 static char *remote_name = NULL;
61 static char *option_branch = NULL;
62 static struct string_list option_not = STRING_LIST_INIT_NODUP;
63 static const char *real_git_dir;
64 static char *option_upload_pack = "git-upload-pack";
65 static int option_verbosity;
66 static int option_progress = -1;
67 static int option_sparse_checkout;
68 static enum transport_family family;
69 static struct string_list option_config = STRING_LIST_INIT_NODUP;
70 static struct string_list option_required_reference = STRING_LIST_INIT_NODUP;
71 static struct string_list option_optional_reference = STRING_LIST_INIT_NODUP;
72 static int option_dissociate;
73 static int max_jobs = -1;
74 static struct string_list option_recurse_submodules = STRING_LIST_INIT_NODUP;
75 static struct list_objects_filter_options filter_options;
76 static int option_filter_submodules = -1; /* unspecified */
77 static int config_filter_submodules = -1; /* unspecified */
78 static struct string_list server_options = STRING_LIST_INIT_NODUP;
79 static int option_remote_submodules;
81 static int recurse_submodules_cb(const struct option *opt,
82 const char *arg, int unset)
84 if (unset)
85 string_list_clear((struct string_list *)opt->value, 0);
86 else if (arg)
87 string_list_append((struct string_list *)opt->value, arg);
88 else
89 string_list_append((struct string_list *)opt->value,
90 (const char *)opt->defval);
92 return 0;
95 static struct option builtin_clone_options[] = {
96 OPT__VERBOSITY(&option_verbosity),
97 OPT_BOOL(0, "progress", &option_progress,
98 N_("force progress reporting")),
99 OPT_BOOL(0, "reject-shallow", &option_reject_shallow,
100 N_("don't clone shallow repository")),
101 OPT_BOOL('n', "no-checkout", &option_no_checkout,
102 N_("don't create a checkout")),
103 OPT_BOOL(0, "bare", &option_bare, N_("create a bare repository")),
104 OPT_HIDDEN_BOOL(0, "naked", &option_bare,
105 N_("create a bare repository")),
106 OPT_BOOL(0, "mirror", &option_mirror,
107 N_("create a mirror repository (implies bare)")),
108 OPT_BOOL('l', "local", &option_local,
109 N_("to clone from a local repository")),
110 OPT_BOOL(0, "no-hardlinks", &option_no_hardlinks,
111 N_("don't use local hardlinks, always copy")),
112 OPT_BOOL('s', "shared", &option_shared,
113 N_("setup as shared repository")),
114 { OPTION_CALLBACK, 0, "recurse-submodules", &option_recurse_submodules,
115 N_("pathspec"), N_("initialize submodules in the clone"),
116 PARSE_OPT_OPTARG, recurse_submodules_cb, (intptr_t)"." },
117 OPT_ALIAS(0, "recursive", "recurse-submodules"),
118 OPT_INTEGER('j', "jobs", &max_jobs,
119 N_("number of submodules cloned in parallel")),
120 OPT_STRING(0, "template", &option_template, N_("template-directory"),
121 N_("directory from which templates will be used")),
122 OPT_STRING_LIST(0, "reference", &option_required_reference, N_("repo"),
123 N_("reference repository")),
124 OPT_STRING_LIST(0, "reference-if-able", &option_optional_reference,
125 N_("repo"), N_("reference repository")),
126 OPT_BOOL(0, "dissociate", &option_dissociate,
127 N_("use --reference only while cloning")),
128 OPT_STRING('o', "origin", &option_origin, N_("name"),
129 N_("use <name> instead of 'origin' to track upstream")),
130 OPT_STRING('b', "branch", &option_branch, N_("branch"),
131 N_("checkout <branch> instead of the remote's HEAD")),
132 OPT_STRING('u', "upload-pack", &option_upload_pack, N_("path"),
133 N_("path to git-upload-pack on the remote")),
134 OPT_STRING(0, "depth", &option_depth, N_("depth"),
135 N_("create a shallow clone of that depth")),
136 OPT_STRING(0, "shallow-since", &option_since, N_("time"),
137 N_("create a shallow clone since a specific time")),
138 OPT_STRING_LIST(0, "shallow-exclude", &option_not, N_("revision"),
139 N_("deepen history of shallow clone, excluding rev")),
140 OPT_BOOL(0, "single-branch", &option_single_branch,
141 N_("clone only one branch, HEAD or --branch")),
142 OPT_BOOL(0, "no-tags", &option_no_tags,
143 N_("don't clone any tags, and make later fetches not to follow them")),
144 OPT_BOOL(0, "shallow-submodules", &option_shallow_submodules,
145 N_("any cloned submodules will be shallow")),
146 OPT_STRING(0, "separate-git-dir", &real_git_dir, N_("gitdir"),
147 N_("separate git dir from working tree")),
148 OPT_STRING_LIST('c', "config", &option_config, N_("key=value"),
149 N_("set config inside the new repository")),
150 OPT_STRING_LIST(0, "server-option", &server_options,
151 N_("server-specific"), N_("option to transmit")),
152 OPT_SET_INT('4', "ipv4", &family, N_("use IPv4 addresses only"),
153 TRANSPORT_FAMILY_IPV4),
154 OPT_SET_INT('6', "ipv6", &family, N_("use IPv6 addresses only"),
155 TRANSPORT_FAMILY_IPV6),
156 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
157 OPT_BOOL(0, "also-filter-submodules", &option_filter_submodules,
158 N_("apply partial clone filters to submodules")),
159 OPT_BOOL(0, "remote-submodules", &option_remote_submodules,
160 N_("any cloned submodules will use their remote-tracking branch")),
161 OPT_BOOL(0, "sparse", &option_sparse_checkout,
162 N_("initialize sparse-checkout file to include only files at root")),
163 OPT_END()
166 static const char *get_repo_path_1(struct strbuf *path, int *is_bundle)
168 static char *suffix[] = { "/.git", "", ".git/.git", ".git" };
169 static char *bundle_suffix[] = { ".bundle", "" };
170 size_t baselen = path->len;
171 struct stat st;
172 int i;
174 for (i = 0; i < ARRAY_SIZE(suffix); i++) {
175 strbuf_setlen(path, baselen);
176 strbuf_addstr(path, suffix[i]);
177 if (stat(path->buf, &st))
178 continue;
179 if (S_ISDIR(st.st_mode) && is_git_directory(path->buf)) {
180 *is_bundle = 0;
181 return path->buf;
182 } else if (S_ISREG(st.st_mode) && st.st_size > 8) {
183 /* Is it a "gitfile"? */
184 char signature[8];
185 const char *dst;
186 int len, fd = open(path->buf, O_RDONLY);
187 if (fd < 0)
188 continue;
189 len = read_in_full(fd, signature, 8);
190 close(fd);
191 if (len != 8 || strncmp(signature, "gitdir: ", 8))
192 continue;
193 dst = read_gitfile(path->buf);
194 if (dst) {
195 *is_bundle = 0;
196 return dst;
201 for (i = 0; i < ARRAY_SIZE(bundle_suffix); i++) {
202 strbuf_setlen(path, baselen);
203 strbuf_addstr(path, bundle_suffix[i]);
204 if (!stat(path->buf, &st) && S_ISREG(st.st_mode)) {
205 *is_bundle = 1;
206 return path->buf;
210 return NULL;
213 static char *get_repo_path(const char *repo, int *is_bundle)
215 struct strbuf path = STRBUF_INIT;
216 const char *raw;
217 char *canon;
219 strbuf_addstr(&path, repo);
220 raw = get_repo_path_1(&path, is_bundle);
221 canon = raw ? absolute_pathdup(raw) : NULL;
222 strbuf_release(&path);
223 return canon;
226 static int add_one_reference(struct string_list_item *item, void *cb_data)
228 struct strbuf err = STRBUF_INIT;
229 int *required = cb_data;
230 char *ref_git = compute_alternate_path(item->string, &err);
232 if (!ref_git) {
233 if (*required)
234 die("%s", err.buf);
235 else
236 fprintf(stderr,
237 _("info: Could not add alternate for '%s': %s\n"),
238 item->string, err.buf);
239 } else {
240 struct strbuf sb = STRBUF_INIT;
241 strbuf_addf(&sb, "%s/objects", ref_git);
242 add_to_alternates_file(sb.buf);
243 strbuf_release(&sb);
246 strbuf_release(&err);
247 free(ref_git);
248 return 0;
251 static void setup_reference(void)
253 int required = 1;
254 for_each_string_list(&option_required_reference,
255 add_one_reference, &required);
256 required = 0;
257 for_each_string_list(&option_optional_reference,
258 add_one_reference, &required);
261 static void copy_alternates(struct strbuf *src, const char *src_repo)
264 * Read from the source objects/info/alternates file
265 * and copy the entries to corresponding file in the
266 * destination repository with add_to_alternates_file().
267 * Both src and dst have "$path/objects/info/alternates".
269 * Instead of copying bit-for-bit from the original,
270 * we need to append to existing one so that the already
271 * created entry via "clone -s" is not lost, and also
272 * to turn entries with paths relative to the original
273 * absolute, so that they can be used in the new repository.
275 FILE *in = xfopen(src->buf, "r");
276 struct strbuf line = STRBUF_INIT;
278 while (strbuf_getline(&line, in) != EOF) {
279 char *abs_path;
280 if (!line.len || line.buf[0] == '#')
281 continue;
282 if (is_absolute_path(line.buf)) {
283 add_to_alternates_file(line.buf);
284 continue;
286 abs_path = mkpathdup("%s/objects/%s", src_repo, line.buf);
287 if (!normalize_path_copy(abs_path, abs_path))
288 add_to_alternates_file(abs_path);
289 else
290 warning("skipping invalid relative alternate: %s/%s",
291 src_repo, line.buf);
292 free(abs_path);
294 strbuf_release(&line);
295 fclose(in);
298 static void mkdir_if_missing(const char *pathname, mode_t mode)
300 struct stat st;
302 if (!mkdir(pathname, mode))
303 return;
305 if (errno != EEXIST)
306 die_errno(_("failed to create directory '%s'"), pathname);
307 else if (stat(pathname, &st))
308 die_errno(_("failed to stat '%s'"), pathname);
309 else if (!S_ISDIR(st.st_mode))
310 die(_("%s exists and is not a directory"), pathname);
313 static void copy_or_link_directory(struct strbuf *src, struct strbuf *dest,
314 const char *src_repo)
316 int src_len, dest_len;
317 struct dir_iterator *iter;
318 int iter_status;
319 unsigned int flags;
320 struct strbuf realpath = STRBUF_INIT;
322 mkdir_if_missing(dest->buf, 0777);
324 flags = DIR_ITERATOR_PEDANTIC | DIR_ITERATOR_FOLLOW_SYMLINKS;
325 iter = dir_iterator_begin(src->buf, flags);
327 if (!iter)
328 die_errno(_("failed to start iterator over '%s'"), src->buf);
330 strbuf_addch(src, '/');
331 src_len = src->len;
332 strbuf_addch(dest, '/');
333 dest_len = dest->len;
335 while ((iter_status = dir_iterator_advance(iter)) == ITER_OK) {
336 strbuf_setlen(src, src_len);
337 strbuf_addstr(src, iter->relative_path);
338 strbuf_setlen(dest, dest_len);
339 strbuf_addstr(dest, iter->relative_path);
341 if (S_ISDIR(iter->st.st_mode)) {
342 mkdir_if_missing(dest->buf, 0777);
343 continue;
346 /* Files that cannot be copied bit-for-bit... */
347 if (!fspathcmp(iter->relative_path, "info/alternates")) {
348 copy_alternates(src, src_repo);
349 continue;
352 if (unlink(dest->buf) && errno != ENOENT)
353 die_errno(_("failed to unlink '%s'"), dest->buf);
354 if (!option_no_hardlinks) {
355 strbuf_realpath(&realpath, src->buf, 1);
356 if (!link(realpath.buf, dest->buf))
357 continue;
358 if (option_local > 0)
359 die_errno(_("failed to create link '%s'"), dest->buf);
360 option_no_hardlinks = 1;
362 if (copy_file_with_time(dest->buf, src->buf, 0666))
363 die_errno(_("failed to copy file to '%s'"), dest->buf);
366 if (iter_status != ITER_DONE) {
367 strbuf_setlen(src, src_len);
368 die(_("failed to iterate over '%s'"), src->buf);
371 strbuf_release(&realpath);
374 static void clone_local(const char *src_repo, const char *dest_repo)
376 if (option_shared) {
377 struct strbuf alt = STRBUF_INIT;
378 get_common_dir(&alt, src_repo);
379 strbuf_addstr(&alt, "/objects");
380 add_to_alternates_file(alt.buf);
381 strbuf_release(&alt);
382 } else {
383 struct strbuf src = STRBUF_INIT;
384 struct strbuf dest = STRBUF_INIT;
385 get_common_dir(&src, src_repo);
386 get_common_dir(&dest, dest_repo);
387 strbuf_addstr(&src, "/objects");
388 strbuf_addstr(&dest, "/objects");
389 copy_or_link_directory(&src, &dest, src_repo);
390 strbuf_release(&src);
391 strbuf_release(&dest);
394 if (0 <= option_verbosity)
395 fprintf(stderr, _("done.\n"));
398 static const char *junk_work_tree;
399 static int junk_work_tree_flags;
400 static const char *junk_git_dir;
401 static int junk_git_dir_flags;
402 static enum {
403 JUNK_LEAVE_NONE,
404 JUNK_LEAVE_REPO,
405 JUNK_LEAVE_ALL
406 } junk_mode = JUNK_LEAVE_NONE;
408 static const char junk_leave_repo_msg[] =
409 N_("Clone succeeded, but checkout failed.\n"
410 "You can inspect what was checked out with 'git status'\n"
411 "and retry with 'git restore --source=HEAD :/'\n");
413 static void remove_junk(void)
415 struct strbuf sb = STRBUF_INIT;
417 switch (junk_mode) {
418 case JUNK_LEAVE_REPO:
419 warning("%s", _(junk_leave_repo_msg));
420 /* fall-through */
421 case JUNK_LEAVE_ALL:
422 return;
423 default:
424 /* proceed to removal */
425 break;
428 if (junk_git_dir) {
429 strbuf_addstr(&sb, junk_git_dir);
430 remove_dir_recursively(&sb, junk_git_dir_flags);
431 strbuf_reset(&sb);
433 if (junk_work_tree) {
434 strbuf_addstr(&sb, junk_work_tree);
435 remove_dir_recursively(&sb, junk_work_tree_flags);
437 strbuf_release(&sb);
440 static void remove_junk_on_signal(int signo)
442 remove_junk();
443 sigchain_pop(signo);
444 raise(signo);
447 static struct ref *find_remote_branch(const struct ref *refs, const char *branch)
449 struct ref *ref;
450 struct strbuf head = STRBUF_INIT;
451 strbuf_addstr(&head, "refs/heads/");
452 strbuf_addstr(&head, branch);
453 ref = find_ref_by_name(refs, head.buf);
454 strbuf_release(&head);
456 if (ref)
457 return ref;
459 strbuf_addstr(&head, "refs/tags/");
460 strbuf_addstr(&head, branch);
461 ref = find_ref_by_name(refs, head.buf);
462 strbuf_release(&head);
464 return ref;
467 static struct ref *wanted_peer_refs(const struct ref *refs,
468 struct refspec *refspec)
470 struct ref *head = copy_ref(find_ref_by_name(refs, "HEAD"));
471 struct ref *local_refs = head;
472 struct ref **tail = head ? &head->next : &local_refs;
474 if (option_single_branch) {
475 struct ref *remote_head = NULL;
477 if (!option_branch)
478 remote_head = guess_remote_head(head, refs, 0);
479 else {
480 local_refs = NULL;
481 tail = &local_refs;
482 remote_head = copy_ref(find_remote_branch(refs, option_branch));
485 if (!remote_head && option_branch)
486 warning(_("Could not find remote branch %s to clone."),
487 option_branch);
488 else {
489 int i;
490 for (i = 0; i < refspec->nr; i++)
491 get_fetch_map(remote_head, &refspec->items[i],
492 &tail, 0);
494 /* if --branch=tag, pull the requested tag explicitly */
495 get_fetch_map(remote_head, tag_refspec, &tail, 0);
497 } else {
498 int i;
499 for (i = 0; i < refspec->nr; i++)
500 get_fetch_map(refs, &refspec->items[i], &tail, 0);
503 if (!option_mirror && !option_single_branch && !option_no_tags)
504 get_fetch_map(refs, tag_refspec, &tail, 0);
506 return local_refs;
509 static void write_remote_refs(const struct ref *local_refs)
511 const struct ref *r;
513 struct ref_transaction *t;
514 struct strbuf err = STRBUF_INIT;
516 t = ref_transaction_begin(&err);
517 if (!t)
518 die("%s", err.buf);
520 for (r = local_refs; r; r = r->next) {
521 if (!r->peer_ref)
522 continue;
523 if (ref_transaction_create(t, r->peer_ref->name, &r->old_oid,
524 0, NULL, &err))
525 die("%s", err.buf);
528 if (initial_ref_transaction_commit(t, &err))
529 die("%s", err.buf);
531 strbuf_release(&err);
532 ref_transaction_free(t);
535 static void write_followtags(const struct ref *refs, const char *msg)
537 const struct ref *ref;
538 for (ref = refs; ref; ref = ref->next) {
539 if (!starts_with(ref->name, "refs/tags/"))
540 continue;
541 if (ends_with(ref->name, "^{}"))
542 continue;
543 if (!has_object_file_with_flags(&ref->old_oid,
544 OBJECT_INFO_QUICK |
545 OBJECT_INFO_SKIP_FETCH_OBJECT))
546 continue;
547 update_ref(msg, ref->name, &ref->old_oid, NULL, 0,
548 UPDATE_REFS_DIE_ON_ERR);
552 static const struct object_id *iterate_ref_map(void *cb_data)
554 struct ref **rm = cb_data;
555 struct ref *ref = *rm;
558 * Skip anything missing a peer_ref, which we are not
559 * actually going to write a ref for.
561 while (ref && !ref->peer_ref)
562 ref = ref->next;
563 if (!ref)
564 return NULL;
566 *rm = ref->next;
567 return &ref->old_oid;
570 static void update_remote_refs(const struct ref *refs,
571 const struct ref *mapped_refs,
572 const struct ref *remote_head_points_at,
573 const char *branch_top,
574 const char *msg,
575 struct transport *transport,
576 int check_connectivity)
578 const struct ref *rm = mapped_refs;
580 if (check_connectivity) {
581 struct check_connected_options opt = CHECK_CONNECTED_INIT;
583 opt.transport = transport;
584 opt.progress = transport->progress;
586 if (check_connected(iterate_ref_map, &rm, &opt))
587 die(_("remote did not send all necessary objects"));
590 if (refs) {
591 write_remote_refs(mapped_refs);
592 if (option_single_branch && !option_no_tags)
593 write_followtags(refs, msg);
596 if (remote_head_points_at && !option_bare) {
597 struct strbuf head_ref = STRBUF_INIT;
598 strbuf_addstr(&head_ref, branch_top);
599 strbuf_addstr(&head_ref, "HEAD");
600 if (create_symref(head_ref.buf,
601 remote_head_points_at->peer_ref->name,
602 msg) < 0)
603 die(_("unable to update %s"), head_ref.buf);
604 strbuf_release(&head_ref);
608 static void update_head(const struct ref *our, const struct ref *remote,
609 const char *msg)
611 const char *head;
612 if (our && skip_prefix(our->name, "refs/heads/", &head)) {
613 /* Local default branch link */
614 if (create_symref("HEAD", our->name, NULL) < 0)
615 die(_("unable to update HEAD"));
616 if (!option_bare) {
617 update_ref(msg, "HEAD", &our->old_oid, NULL, 0,
618 UPDATE_REFS_DIE_ON_ERR);
619 install_branch_config(0, head, remote_name, our->name);
621 } else if (our) {
622 struct commit *c = lookup_commit_reference(the_repository,
623 &our->old_oid);
624 /* --branch specifies a non-branch (i.e. tags), detach HEAD */
625 update_ref(msg, "HEAD", &c->object.oid, NULL, REF_NO_DEREF,
626 UPDATE_REFS_DIE_ON_ERR);
627 } else if (remote) {
629 * We know remote HEAD points to a non-branch, or
630 * HEAD points to a branch but we don't know which one.
631 * Detach HEAD in all these cases.
633 update_ref(msg, "HEAD", &remote->old_oid, NULL, REF_NO_DEREF,
634 UPDATE_REFS_DIE_ON_ERR);
638 static int git_sparse_checkout_init(const char *repo)
640 struct strvec argv = STRVEC_INIT;
641 int result = 0;
642 strvec_pushl(&argv, "-C", repo, "sparse-checkout", "set", NULL);
645 * We must apply the setting in the current process
646 * for the later checkout to use the sparse-checkout file.
648 core_apply_sparse_checkout = 1;
650 if (run_command_v_opt(argv.v, RUN_GIT_CMD)) {
651 error(_("failed to initialize sparse-checkout"));
652 result = 1;
655 strvec_clear(&argv);
656 return result;
659 static int checkout(int submodule_progress, int filter_submodules)
661 struct object_id oid;
662 char *head;
663 struct lock_file lock_file = LOCK_INIT;
664 struct unpack_trees_options opts;
665 struct tree *tree;
666 struct tree_desc t;
667 int err = 0;
669 if (option_no_checkout)
670 return 0;
672 head = resolve_refdup("HEAD", RESOLVE_REF_READING, &oid, NULL);
673 if (!head) {
674 warning(_("remote HEAD refers to nonexistent ref, "
675 "unable to checkout.\n"));
676 return 0;
678 if (!strcmp(head, "HEAD")) {
679 if (advice_enabled(ADVICE_DETACHED_HEAD))
680 detach_advice(oid_to_hex(&oid));
681 FREE_AND_NULL(head);
682 } else {
683 if (!starts_with(head, "refs/heads/"))
684 die(_("HEAD not found below refs/heads!"));
687 /* We need to be in the new work tree for the checkout */
688 setup_work_tree();
690 hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
692 memset(&opts, 0, sizeof opts);
693 opts.update = 1;
694 opts.merge = 1;
695 opts.clone = 1;
696 opts.preserve_ignored = 0;
697 opts.fn = oneway_merge;
698 opts.verbose_update = (option_verbosity >= 0);
699 opts.src_index = &the_index;
700 opts.dst_index = &the_index;
701 init_checkout_metadata(&opts.meta, head, &oid, NULL);
703 tree = parse_tree_indirect(&oid);
704 if (!tree)
705 die(_("unable to parse commit %s"), oid_to_hex(&oid));
706 parse_tree(tree);
707 init_tree_desc(&t, tree->buffer, tree->size);
708 if (unpack_trees(1, &t, &opts) < 0)
709 die(_("unable to checkout working tree"));
711 free(head);
713 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
714 die(_("unable to write new index file"));
716 err |= run_hooks_l("post-checkout", oid_to_hex(null_oid()),
717 oid_to_hex(&oid), "1", NULL);
719 if (!err && (option_recurse_submodules.nr > 0)) {
720 struct strvec args = STRVEC_INIT;
721 strvec_pushl(&args, "submodule", "update", "--require-init", "--recursive", NULL);
723 if (option_shallow_submodules == 1)
724 strvec_push(&args, "--depth=1");
726 if (max_jobs != -1)
727 strvec_pushf(&args, "--jobs=%d", max_jobs);
729 if (submodule_progress)
730 strvec_push(&args, "--progress");
732 if (option_verbosity < 0)
733 strvec_push(&args, "--quiet");
735 if (option_remote_submodules) {
736 strvec_push(&args, "--remote");
737 strvec_push(&args, "--no-fetch");
740 if (filter_submodules && filter_options.choice)
741 strvec_pushf(&args, "--filter=%s",
742 expand_list_objects_filter_spec(&filter_options));
744 if (option_single_branch >= 0)
745 strvec_push(&args, option_single_branch ?
746 "--single-branch" :
747 "--no-single-branch");
749 err = run_command_v_opt(args.v, RUN_GIT_CMD);
750 strvec_clear(&args);
753 return err;
756 static int git_clone_config(const char *k, const char *v, void *cb)
758 if (!strcmp(k, "clone.defaultremotename")) {
759 free(remote_name);
760 remote_name = xstrdup(v);
762 if (!strcmp(k, "clone.rejectshallow"))
763 config_reject_shallow = git_config_bool(k, v);
764 if (!strcmp(k, "clone.filtersubmodules"))
765 config_filter_submodules = git_config_bool(k, v);
767 return git_default_config(k, v, cb);
770 static int write_one_config(const char *key, const char *value, void *data)
773 * give git_clone_config a chance to write config values back to the
774 * environment, since git_config_set_multivar_gently only deals with
775 * config-file writes
777 int apply_failed = git_clone_config(key, value, data);
778 if (apply_failed)
779 return apply_failed;
781 return git_config_set_multivar_gently(key,
782 value ? value : "true",
783 CONFIG_REGEX_NONE, 0);
786 static void write_config(struct string_list *config)
788 int i;
790 for (i = 0; i < config->nr; i++) {
791 if (git_config_parse_parameter(config->items[i].string,
792 write_one_config, NULL) < 0)
793 die(_("unable to write parameters to config file"));
797 static void write_refspec_config(const char *src_ref_prefix,
798 const struct ref *our_head_points_at,
799 const struct ref *remote_head_points_at,
800 struct strbuf *branch_top)
802 struct strbuf key = STRBUF_INIT;
803 struct strbuf value = STRBUF_INIT;
805 if (option_mirror || !option_bare) {
806 if (option_single_branch && !option_mirror) {
807 if (option_branch) {
808 if (starts_with(our_head_points_at->name, "refs/tags/"))
809 strbuf_addf(&value, "+%s:%s", our_head_points_at->name,
810 our_head_points_at->name);
811 else
812 strbuf_addf(&value, "+%s:%s%s", our_head_points_at->name,
813 branch_top->buf, option_branch);
814 } else if (remote_head_points_at) {
815 const char *head = remote_head_points_at->name;
816 if (!skip_prefix(head, "refs/heads/", &head))
817 BUG("remote HEAD points at non-head?");
819 strbuf_addf(&value, "+%s:%s%s", remote_head_points_at->name,
820 branch_top->buf, head);
823 * otherwise, the next "git fetch" will
824 * simply fetch from HEAD without updating
825 * any remote-tracking branch, which is what
826 * we want.
828 } else {
829 strbuf_addf(&value, "+%s*:%s*", src_ref_prefix, branch_top->buf);
831 /* Configure the remote */
832 if (value.len) {
833 strbuf_addf(&key, "remote.%s.fetch", remote_name);
834 git_config_set_multivar(key.buf, value.buf, "^$", 0);
835 strbuf_reset(&key);
837 if (option_mirror) {
838 strbuf_addf(&key, "remote.%s.mirror", remote_name);
839 git_config_set(key.buf, "true");
840 strbuf_reset(&key);
845 strbuf_release(&key);
846 strbuf_release(&value);
849 static void dissociate_from_references(void)
851 static const char* argv[] = { "repack", "-a", "-d", NULL };
852 char *alternates = git_pathdup("objects/info/alternates");
854 if (!access(alternates, F_OK)) {
855 if (run_command_v_opt(argv, RUN_GIT_CMD|RUN_COMMAND_NO_STDIN))
856 die(_("cannot repack to clean up"));
857 if (unlink(alternates) && errno != ENOENT)
858 die_errno(_("cannot unlink temporary alternates file"));
860 free(alternates);
863 static int path_exists(const char *path)
865 struct stat sb;
866 return !stat(path, &sb);
869 int cmd_clone(int argc, const char **argv, const char *prefix)
871 int is_bundle = 0, is_local;
872 int reject_shallow = 0;
873 const char *repo_name, *repo, *work_tree, *git_dir;
874 char *path = NULL, *dir, *display_repo = NULL;
875 int dest_exists, real_dest_exists = 0;
876 const struct ref *refs, *remote_head;
877 struct ref *remote_head_points_at = NULL;
878 const struct ref *our_head_points_at;
879 struct ref *mapped_refs = NULL;
880 const struct ref *ref;
881 struct strbuf key = STRBUF_INIT;
882 struct strbuf branch_top = STRBUF_INIT, reflog_msg = STRBUF_INIT;
883 struct transport *transport = NULL;
884 const char *src_ref_prefix = "refs/heads/";
885 struct remote *remote;
886 int err = 0, complete_refs_before_fetch = 1;
887 int submodule_progress;
888 int filter_submodules = 0;
890 struct transport_ls_refs_options transport_ls_refs_options =
891 TRANSPORT_LS_REFS_OPTIONS_INIT;
893 packet_trace_identity("clone");
895 git_config(git_clone_config, NULL);
897 argc = parse_options(argc, argv, prefix, builtin_clone_options,
898 builtin_clone_usage, 0);
900 if (argc > 2)
901 usage_msg_opt(_("Too many arguments."),
902 builtin_clone_usage, builtin_clone_options);
904 if (argc == 0)
905 usage_msg_opt(_("You must specify a repository to clone."),
906 builtin_clone_usage, builtin_clone_options);
908 if (option_depth || option_since || option_not.nr)
909 deepen = 1;
910 if (option_single_branch == -1)
911 option_single_branch = deepen ? 1 : 0;
913 if (option_mirror)
914 option_bare = 1;
916 if (option_bare) {
917 if (option_origin)
918 die(_("options '%s' and '%s %s' cannot be used together"),
919 "--bare", "--origin", option_origin);
920 if (real_git_dir)
921 die(_("options '%s' and '%s' cannot be used together"), "--bare", "--separate-git-dir");
922 option_no_checkout = 1;
925 repo_name = argv[0];
927 path = get_repo_path(repo_name, &is_bundle);
928 if (path) {
929 FREE_AND_NULL(path);
930 repo = absolute_pathdup(repo_name);
931 } else if (strchr(repo_name, ':')) {
932 repo = repo_name;
933 display_repo = transport_anonymize_url(repo);
934 } else
935 die(_("repository '%s' does not exist"), repo_name);
937 /* no need to be strict, transport_set_option() will validate it again */
938 if (option_depth && atoi(option_depth) < 1)
939 die(_("depth %s is not a positive number"), option_depth);
941 if (argc == 2)
942 dir = xstrdup(argv[1]);
943 else
944 dir = git_url_basename(repo_name, is_bundle, option_bare);
945 strip_dir_trailing_slashes(dir);
947 dest_exists = path_exists(dir);
948 if (dest_exists && !is_empty_dir(dir))
949 die(_("destination path '%s' already exists and is not "
950 "an empty directory."), dir);
952 if (real_git_dir) {
953 real_dest_exists = path_exists(real_git_dir);
954 if (real_dest_exists && !is_empty_dir(real_git_dir))
955 die(_("repository path '%s' already exists and is not "
956 "an empty directory."), real_git_dir);
960 strbuf_addf(&reflog_msg, "clone: from %s",
961 display_repo ? display_repo : repo);
962 free(display_repo);
964 if (option_bare)
965 work_tree = NULL;
966 else {
967 work_tree = getenv("GIT_WORK_TREE");
968 if (work_tree && path_exists(work_tree))
969 die(_("working tree '%s' already exists."), work_tree);
972 if (option_bare || work_tree)
973 git_dir = xstrdup(dir);
974 else {
975 work_tree = dir;
976 git_dir = mkpathdup("%s/.git", dir);
979 atexit(remove_junk);
980 sigchain_push_common(remove_junk_on_signal);
982 if (!option_bare) {
983 if (safe_create_leading_directories_const(work_tree) < 0)
984 die_errno(_("could not create leading directories of '%s'"),
985 work_tree);
986 if (dest_exists)
987 junk_work_tree_flags |= REMOVE_DIR_KEEP_TOPLEVEL;
988 else if (mkdir(work_tree, 0777))
989 die_errno(_("could not create work tree dir '%s'"),
990 work_tree);
991 junk_work_tree = work_tree;
992 set_git_work_tree(work_tree);
995 if (real_git_dir) {
996 if (real_dest_exists)
997 junk_git_dir_flags |= REMOVE_DIR_KEEP_TOPLEVEL;
998 junk_git_dir = real_git_dir;
999 } else {
1000 if (dest_exists)
1001 junk_git_dir_flags |= REMOVE_DIR_KEEP_TOPLEVEL;
1002 junk_git_dir = git_dir;
1004 if (safe_create_leading_directories_const(git_dir) < 0)
1005 die(_("could not create leading directories of '%s'"), git_dir);
1007 if (0 <= option_verbosity) {
1008 if (option_bare)
1009 fprintf(stderr, _("Cloning into bare repository '%s'...\n"), dir);
1010 else
1011 fprintf(stderr, _("Cloning into '%s'...\n"), dir);
1014 if (option_recurse_submodules.nr > 0) {
1015 struct string_list_item *item;
1016 struct strbuf sb = STRBUF_INIT;
1017 int val;
1019 /* remove duplicates */
1020 string_list_sort(&option_recurse_submodules);
1021 string_list_remove_duplicates(&option_recurse_submodules, 0);
1024 * NEEDSWORK: In a multi-working-tree world, this needs to be
1025 * set in the per-worktree config.
1027 for_each_string_list_item(item, &option_recurse_submodules) {
1028 strbuf_addf(&sb, "submodule.active=%s",
1029 item->string);
1030 string_list_append(&option_config,
1031 strbuf_detach(&sb, NULL));
1034 if (!git_config_get_bool("submodule.stickyRecursiveClone", &val) &&
1035 val)
1036 string_list_append(&option_config, "submodule.recurse=true");
1038 if (option_required_reference.nr &&
1039 option_optional_reference.nr)
1040 die(_("clone --recursive is not compatible with "
1041 "both --reference and --reference-if-able"));
1042 else if (option_required_reference.nr) {
1043 string_list_append(&option_config,
1044 "submodule.alternateLocation=superproject");
1045 string_list_append(&option_config,
1046 "submodule.alternateErrorStrategy=die");
1047 } else if (option_optional_reference.nr) {
1048 string_list_append(&option_config,
1049 "submodule.alternateLocation=superproject");
1050 string_list_append(&option_config,
1051 "submodule.alternateErrorStrategy=info");
1055 init_db(git_dir, real_git_dir, option_template, GIT_HASH_UNKNOWN, NULL,
1056 INIT_DB_QUIET);
1058 if (real_git_dir) {
1059 free((char *)git_dir);
1060 git_dir = real_git_dir;
1064 * additional config can be injected with -c, make sure it's included
1065 * after init_db, which clears the entire config environment.
1067 write_config(&option_config);
1070 * re-read config after init_db and write_config to pick up any config
1071 * injected by --template and --config, respectively.
1073 git_config(git_clone_config, NULL);
1076 * If option_reject_shallow is specified from CLI option,
1077 * ignore config_reject_shallow from git_clone_config.
1079 if (config_reject_shallow != -1)
1080 reject_shallow = config_reject_shallow;
1081 if (option_reject_shallow != -1)
1082 reject_shallow = option_reject_shallow;
1085 * If option_filter_submodules is specified from CLI option,
1086 * ignore config_filter_submodules from git_clone_config.
1088 if (config_filter_submodules != -1)
1089 filter_submodules = config_filter_submodules;
1090 if (option_filter_submodules != -1)
1091 filter_submodules = option_filter_submodules;
1094 * Exit if the user seems to be doing something silly with submodule
1095 * filter flags (but not with filter configs, as those should be
1096 * set-and-forget).
1098 if (option_filter_submodules > 0 && !filter_options.choice)
1099 die(_("the option '%s' requires '%s'"),
1100 "--also-filter-submodules", "--filter");
1101 if (option_filter_submodules > 0 && !option_recurse_submodules.nr)
1102 die(_("the option '%s' requires '%s'"),
1103 "--also-filter-submodules", "--recurse-submodules");
1106 * apply the remote name provided by --origin only after this second
1107 * call to git_config, to ensure it overrides all config-based values.
1109 if (option_origin != NULL)
1110 remote_name = xstrdup(option_origin);
1112 if (remote_name == NULL)
1113 remote_name = xstrdup("origin");
1115 if (!valid_remote_name(remote_name))
1116 die(_("'%s' is not a valid remote name"), remote_name);
1118 if (option_bare) {
1119 if (option_mirror)
1120 src_ref_prefix = "refs/";
1121 strbuf_addstr(&branch_top, src_ref_prefix);
1123 git_config_set("core.bare", "true");
1124 } else {
1125 strbuf_addf(&branch_top, "refs/remotes/%s/", remote_name);
1128 strbuf_addf(&key, "remote.%s.url", remote_name);
1129 git_config_set(key.buf, repo);
1130 strbuf_reset(&key);
1132 if (option_no_tags) {
1133 strbuf_addf(&key, "remote.%s.tagOpt", remote_name);
1134 git_config_set(key.buf, "--no-tags");
1135 strbuf_reset(&key);
1138 if (option_required_reference.nr || option_optional_reference.nr)
1139 setup_reference();
1141 if (option_sparse_checkout && git_sparse_checkout_init(dir))
1142 return 1;
1144 remote = remote_get(remote_name);
1146 refspec_appendf(&remote->fetch, "+%s*:%s*", src_ref_prefix,
1147 branch_top.buf);
1149 transport = transport_get(remote, remote->url[0]);
1150 transport_set_verbosity(transport, option_verbosity, option_progress);
1151 transport->family = family;
1153 path = get_repo_path(remote->url[0], &is_bundle);
1154 is_local = option_local != 0 && path && !is_bundle;
1155 if (is_local) {
1156 if (option_depth)
1157 warning(_("--depth is ignored in local clones; use file:// instead."));
1158 if (option_since)
1159 warning(_("--shallow-since is ignored in local clones; use file:// instead."));
1160 if (option_not.nr)
1161 warning(_("--shallow-exclude is ignored in local clones; use file:// instead."));
1162 if (filter_options.choice)
1163 warning(_("--filter is ignored in local clones; use file:// instead."));
1164 if (!access(mkpath("%s/shallow", path), F_OK)) {
1165 if (reject_shallow)
1166 die(_("source repository is shallow, reject to clone."));
1167 if (option_local > 0)
1168 warning(_("source repository is shallow, ignoring --local"));
1169 is_local = 0;
1172 if (option_local > 0 && !is_local)
1173 warning(_("--local is ignored"));
1174 transport->cloning = 1;
1176 if (is_bundle) {
1177 struct bundle_header header = BUNDLE_HEADER_INIT;
1178 int fd = read_bundle_header(path, &header);
1179 int has_filter = header.filter.choice != LOFC_DISABLED;
1181 if (fd > 0)
1182 close(fd);
1183 bundle_header_release(&header);
1184 if (has_filter)
1185 die(_("cannot clone from filtered bundle"));
1188 transport_set_option(transport, TRANS_OPT_KEEP, "yes");
1190 if (reject_shallow)
1191 transport_set_option(transport, TRANS_OPT_REJECT_SHALLOW, "1");
1192 if (option_depth)
1193 transport_set_option(transport, TRANS_OPT_DEPTH,
1194 option_depth);
1195 if (option_since)
1196 transport_set_option(transport, TRANS_OPT_DEEPEN_SINCE,
1197 option_since);
1198 if (option_not.nr)
1199 transport_set_option(transport, TRANS_OPT_DEEPEN_NOT,
1200 (const char *)&option_not);
1201 if (option_single_branch)
1202 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
1204 if (option_upload_pack)
1205 transport_set_option(transport, TRANS_OPT_UPLOADPACK,
1206 option_upload_pack);
1208 if (server_options.nr)
1209 transport->server_options = &server_options;
1211 if (filter_options.choice) {
1212 const char *spec =
1213 expand_list_objects_filter_spec(&filter_options);
1214 transport_set_option(transport, TRANS_OPT_LIST_OBJECTS_FILTER,
1215 spec);
1216 transport_set_option(transport, TRANS_OPT_FROM_PROMISOR, "1");
1219 if (transport->smart_options && !deepen && !filter_options.choice)
1220 transport->smart_options->check_self_contained_and_connected = 1;
1223 strvec_push(&transport_ls_refs_options.ref_prefixes, "HEAD");
1224 refspec_ref_prefixes(&remote->fetch,
1225 &transport_ls_refs_options.ref_prefixes);
1226 if (option_branch)
1227 expand_ref_prefix(&transport_ls_refs_options.ref_prefixes,
1228 option_branch);
1229 if (!option_no_tags)
1230 strvec_push(&transport_ls_refs_options.ref_prefixes,
1231 "refs/tags/");
1233 refs = transport_get_remote_refs(transport, &transport_ls_refs_options);
1235 if (refs)
1236 mapped_refs = wanted_peer_refs(refs, &remote->fetch);
1238 if (mapped_refs) {
1239 int hash_algo = hash_algo_by_ptr(transport_get_hash_algo(transport));
1242 * Now that we know what algorithm the remote side is using,
1243 * let's set ours to the same thing.
1245 initialize_repository_version(hash_algo, 1);
1246 repo_set_hash_algo(the_repository, hash_algo);
1248 * transport_get_remote_refs() may return refs with null sha-1
1249 * in mapped_refs (see struct transport->get_refs_list
1250 * comment). In that case we need fetch it early because
1251 * remote_head code below relies on it.
1253 * for normal clones, transport_get_remote_refs() should
1254 * return reliable ref set, we can delay cloning until after
1255 * remote HEAD check.
1257 for (ref = refs; ref; ref = ref->next)
1258 if (is_null_oid(&ref->old_oid)) {
1259 complete_refs_before_fetch = 0;
1260 break;
1263 if (!is_local && !complete_refs_before_fetch) {
1264 if (transport_fetch_refs(transport, mapped_refs))
1265 die(_("remote transport reported error"));
1268 remote_head = find_ref_by_name(refs, "HEAD");
1269 remote_head_points_at =
1270 guess_remote_head(remote_head, mapped_refs, 0);
1272 if (option_branch) {
1273 our_head_points_at =
1274 find_remote_branch(mapped_refs, option_branch);
1276 if (!our_head_points_at)
1277 die(_("Remote branch %s not found in upstream %s"),
1278 option_branch, remote_name);
1280 else
1281 our_head_points_at = remote_head_points_at;
1283 else {
1284 const char *branch;
1285 const char *ref;
1286 char *ref_free = NULL;
1288 if (option_branch)
1289 die(_("Remote branch %s not found in upstream %s"),
1290 option_branch, remote_name);
1292 warning(_("You appear to have cloned an empty repository."));
1293 our_head_points_at = NULL;
1294 remote_head_points_at = NULL;
1295 remote_head = NULL;
1296 option_no_checkout = 1;
1298 if (transport_ls_refs_options.unborn_head_target &&
1299 skip_prefix(transport_ls_refs_options.unborn_head_target,
1300 "refs/heads/", &branch)) {
1301 ref = transport_ls_refs_options.unborn_head_target;
1302 create_symref("HEAD", ref, reflog_msg.buf);
1303 } else {
1304 branch = git_default_branch_name(0);
1305 ref_free = xstrfmt("refs/heads/%s", branch);
1306 ref = ref_free;
1309 if (!option_bare)
1310 install_branch_config(0, branch, remote_name, ref);
1311 free(ref_free);
1314 write_refspec_config(src_ref_prefix, our_head_points_at,
1315 remote_head_points_at, &branch_top);
1317 if (filter_options.choice)
1318 partial_clone_register(remote_name, &filter_options);
1320 if (is_local)
1321 clone_local(path, git_dir);
1322 else if (mapped_refs && complete_refs_before_fetch) {
1323 if (transport_fetch_refs(transport, mapped_refs))
1324 die(_("remote transport reported error"));
1327 update_remote_refs(refs, mapped_refs, remote_head_points_at,
1328 branch_top.buf, reflog_msg.buf, transport,
1329 !is_local);
1331 update_head(our_head_points_at, remote_head, reflog_msg.buf);
1334 * We want to show progress for recursive submodule clones iff
1335 * we did so for the main clone. But only the transport knows
1336 * the final decision for this flag, so we need to rescue the value
1337 * before we free the transport.
1339 submodule_progress = transport->progress;
1341 transport_unlock_pack(transport, 0);
1342 transport_disconnect(transport);
1344 if (option_dissociate) {
1345 close_object_store(the_repository->objects);
1346 dissociate_from_references();
1349 junk_mode = JUNK_LEAVE_REPO;
1350 err = checkout(submodule_progress, filter_submodules);
1352 free(remote_name);
1353 strbuf_release(&reflog_msg);
1354 strbuf_release(&branch_top);
1355 strbuf_release(&key);
1356 free_refs(mapped_refs);
1357 free_refs(remote_head_points_at);
1358 free(dir);
1359 free(path);
1360 UNLEAK(repo);
1361 junk_mode = JUNK_LEAVE_ALL;
1363 transport_ls_refs_options_release(&transport_ls_refs_options);
1364 return err;