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.
11 #define USE_THE_INDEX_VARIABLE
15 #include "environment.h"
19 #include "parse-options.h"
20 #include "fetch-pack.h"
23 #include "object-store.h"
25 #include "tree-walk.h"
26 #include "unpack-trees.h"
27 #include "transport.h"
30 #include "dir-iterator.h"
35 #include "run-command.h"
37 #include "connected.h"
39 #include "list-objects-filter-options.h"
42 #include "bundle-uri.h"
46 * - respect DB_ENVIRONMENT for .git/objects.
48 * Implementation notes:
49 * - dropping use-separate-remote and no-separate-remote compatibility
52 static const char * const builtin_clone_usage
[] = {
53 N_("git clone [<options>] [--] <repo> [<dir>]"),
57 static int option_no_checkout
, option_bare
, option_mirror
, option_single_branch
= -1;
58 static int option_local
= -1, option_no_hardlinks
, option_shared
;
59 static int option_no_tags
;
60 static int option_shallow_submodules
;
61 static int option_reject_shallow
= -1; /* unspecified */
62 static int config_reject_shallow
= -1; /* unspecified */
64 static char *option_template
, *option_depth
, *option_since
;
65 static char *option_origin
= NULL
;
66 static char *remote_name
= NULL
;
67 static char *option_branch
= NULL
;
68 static struct string_list option_not
= STRING_LIST_INIT_NODUP
;
69 static const char *real_git_dir
;
70 static char *option_upload_pack
= "git-upload-pack";
71 static int option_verbosity
;
72 static int option_progress
= -1;
73 static int option_sparse_checkout
;
74 static enum transport_family family
;
75 static struct string_list option_config
= STRING_LIST_INIT_NODUP
;
76 static struct string_list option_required_reference
= STRING_LIST_INIT_NODUP
;
77 static struct string_list option_optional_reference
= STRING_LIST_INIT_NODUP
;
78 static int option_dissociate
;
79 static int max_jobs
= -1;
80 static struct string_list option_recurse_submodules
= STRING_LIST_INIT_NODUP
;
81 static struct list_objects_filter_options filter_options
= LIST_OBJECTS_FILTER_INIT
;
82 static int option_filter_submodules
= -1; /* unspecified */
83 static int config_filter_submodules
= -1; /* unspecified */
84 static struct string_list server_options
= STRING_LIST_INIT_NODUP
;
85 static int option_remote_submodules
;
86 static const char *bundle_uri
;
88 static int recurse_submodules_cb(const struct option
*opt
,
89 const char *arg
, int unset
)
92 string_list_clear((struct string_list
*)opt
->value
, 0);
94 string_list_append((struct string_list
*)opt
->value
, arg
);
96 string_list_append((struct string_list
*)opt
->value
,
97 (const char *)opt
->defval
);
102 static struct option builtin_clone_options
[] = {
103 OPT__VERBOSITY(&option_verbosity
),
104 OPT_BOOL(0, "progress", &option_progress
,
105 N_("force progress reporting")),
106 OPT_BOOL(0, "reject-shallow", &option_reject_shallow
,
107 N_("don't clone shallow repository")),
108 OPT_BOOL('n', "no-checkout", &option_no_checkout
,
109 N_("don't create a checkout")),
110 OPT_BOOL(0, "bare", &option_bare
, N_("create a bare repository")),
111 OPT_HIDDEN_BOOL(0, "naked", &option_bare
,
112 N_("create a bare repository")),
113 OPT_BOOL(0, "mirror", &option_mirror
,
114 N_("create a mirror repository (implies bare)")),
115 OPT_BOOL('l', "local", &option_local
,
116 N_("to clone from a local repository")),
117 OPT_BOOL(0, "no-hardlinks", &option_no_hardlinks
,
118 N_("don't use local hardlinks, always copy")),
119 OPT_BOOL('s', "shared", &option_shared
,
120 N_("setup as shared repository")),
121 { OPTION_CALLBACK
, 0, "recurse-submodules", &option_recurse_submodules
,
122 N_("pathspec"), N_("initialize submodules in the clone"),
123 PARSE_OPT_OPTARG
, recurse_submodules_cb
, (intptr_t)"." },
124 OPT_ALIAS(0, "recursive", "recurse-submodules"),
125 OPT_INTEGER('j', "jobs", &max_jobs
,
126 N_("number of submodules cloned in parallel")),
127 OPT_STRING(0, "template", &option_template
, N_("template-directory"),
128 N_("directory from which templates will be used")),
129 OPT_STRING_LIST(0, "reference", &option_required_reference
, N_("repo"),
130 N_("reference repository")),
131 OPT_STRING_LIST(0, "reference-if-able", &option_optional_reference
,
132 N_("repo"), N_("reference repository")),
133 OPT_BOOL(0, "dissociate", &option_dissociate
,
134 N_("use --reference only while cloning")),
135 OPT_STRING('o', "origin", &option_origin
, N_("name"),
136 N_("use <name> instead of 'origin' to track upstream")),
137 OPT_STRING('b', "branch", &option_branch
, N_("branch"),
138 N_("checkout <branch> instead of the remote's HEAD")),
139 OPT_STRING('u', "upload-pack", &option_upload_pack
, N_("path"),
140 N_("path to git-upload-pack on the remote")),
141 OPT_STRING(0, "depth", &option_depth
, N_("depth"),
142 N_("create a shallow clone of that depth")),
143 OPT_STRING(0, "shallow-since", &option_since
, N_("time"),
144 N_("create a shallow clone since a specific time")),
145 OPT_STRING_LIST(0, "shallow-exclude", &option_not
, N_("revision"),
146 N_("deepen history of shallow clone, excluding rev")),
147 OPT_BOOL(0, "single-branch", &option_single_branch
,
148 N_("clone only one branch, HEAD or --branch")),
149 OPT_BOOL(0, "no-tags", &option_no_tags
,
150 N_("don't clone any tags, and make later fetches not to follow them")),
151 OPT_BOOL(0, "shallow-submodules", &option_shallow_submodules
,
152 N_("any cloned submodules will be shallow")),
153 OPT_STRING(0, "separate-git-dir", &real_git_dir
, N_("gitdir"),
154 N_("separate git dir from working tree")),
155 OPT_STRING_LIST('c', "config", &option_config
, N_("key=value"),
156 N_("set config inside the new repository")),
157 OPT_STRING_LIST(0, "server-option", &server_options
,
158 N_("server-specific"), N_("option to transmit")),
159 OPT_SET_INT('4', "ipv4", &family
, N_("use IPv4 addresses only"),
160 TRANSPORT_FAMILY_IPV4
),
161 OPT_SET_INT('6', "ipv6", &family
, N_("use IPv6 addresses only"),
162 TRANSPORT_FAMILY_IPV6
),
163 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options
),
164 OPT_BOOL(0, "also-filter-submodules", &option_filter_submodules
,
165 N_("apply partial clone filters to submodules")),
166 OPT_BOOL(0, "remote-submodules", &option_remote_submodules
,
167 N_("any cloned submodules will use their remote-tracking branch")),
168 OPT_BOOL(0, "sparse", &option_sparse_checkout
,
169 N_("initialize sparse-checkout file to include only files at root")),
170 OPT_STRING(0, "bundle-uri", &bundle_uri
,
171 N_("uri"), N_("a URI for downloading bundles before fetching from origin remote")),
175 static const char *get_repo_path_1(struct strbuf
*path
, int *is_bundle
)
177 static char *suffix
[] = { "/.git", "", ".git/.git", ".git" };
178 static char *bundle_suffix
[] = { ".bundle", "" };
179 size_t baselen
= path
->len
;
183 for (i
= 0; i
< ARRAY_SIZE(suffix
); i
++) {
184 strbuf_setlen(path
, baselen
);
185 strbuf_addstr(path
, suffix
[i
]);
186 if (stat(path
->buf
, &st
))
188 if (S_ISDIR(st
.st_mode
) && is_git_directory(path
->buf
)) {
191 } else if (S_ISREG(st
.st_mode
) && st
.st_size
> 8) {
192 /* Is it a "gitfile"? */
195 int len
, fd
= open(path
->buf
, O_RDONLY
);
198 len
= read_in_full(fd
, signature
, 8);
200 if (len
!= 8 || strncmp(signature
, "gitdir: ", 8))
202 dst
= read_gitfile(path
->buf
);
210 for (i
= 0; i
< ARRAY_SIZE(bundle_suffix
); i
++) {
211 strbuf_setlen(path
, baselen
);
212 strbuf_addstr(path
, bundle_suffix
[i
]);
213 if (!stat(path
->buf
, &st
) && S_ISREG(st
.st_mode
)) {
222 static char *get_repo_path(const char *repo
, int *is_bundle
)
224 struct strbuf path
= STRBUF_INIT
;
228 strbuf_addstr(&path
, repo
);
229 raw
= get_repo_path_1(&path
, is_bundle
);
230 canon
= raw
? absolute_pathdup(raw
) : NULL
;
231 strbuf_release(&path
);
235 static int add_one_reference(struct string_list_item
*item
, void *cb_data
)
237 struct strbuf err
= STRBUF_INIT
;
238 int *required
= cb_data
;
239 char *ref_git
= compute_alternate_path(item
->string
, &err
);
246 _("info: Could not add alternate for '%s': %s\n"),
247 item
->string
, err
.buf
);
249 struct strbuf sb
= STRBUF_INIT
;
250 strbuf_addf(&sb
, "%s/objects", ref_git
);
251 add_to_alternates_file(sb
.buf
);
255 strbuf_release(&err
);
260 static void setup_reference(void)
263 for_each_string_list(&option_required_reference
,
264 add_one_reference
, &required
);
266 for_each_string_list(&option_optional_reference
,
267 add_one_reference
, &required
);
270 static void copy_alternates(struct strbuf
*src
, const char *src_repo
)
273 * Read from the source objects/info/alternates file
274 * and copy the entries to corresponding file in the
275 * destination repository with add_to_alternates_file().
276 * Both src and dst have "$path/objects/info/alternates".
278 * Instead of copying bit-for-bit from the original,
279 * we need to append to existing one so that the already
280 * created entry via "clone -s" is not lost, and also
281 * to turn entries with paths relative to the original
282 * absolute, so that they can be used in the new repository.
284 FILE *in
= xfopen(src
->buf
, "r");
285 struct strbuf line
= STRBUF_INIT
;
287 while (strbuf_getline(&line
, in
) != EOF
) {
289 if (!line
.len
|| line
.buf
[0] == '#')
291 if (is_absolute_path(line
.buf
)) {
292 add_to_alternates_file(line
.buf
);
295 abs_path
= mkpathdup("%s/objects/%s", src_repo
, line
.buf
);
296 if (!normalize_path_copy(abs_path
, abs_path
))
297 add_to_alternates_file(abs_path
);
299 warning("skipping invalid relative alternate: %s/%s",
303 strbuf_release(&line
);
307 static void mkdir_if_missing(const char *pathname
, mode_t mode
)
311 if (!mkdir(pathname
, mode
))
315 die_errno(_("failed to create directory '%s'"), pathname
);
316 else if (stat(pathname
, &st
))
317 die_errno(_("failed to stat '%s'"), pathname
);
318 else if (!S_ISDIR(st
.st_mode
))
319 die(_("%s exists and is not a directory"), pathname
);
322 static void copy_or_link_directory(struct strbuf
*src
, struct strbuf
*dest
,
323 const char *src_repo
)
325 int src_len
, dest_len
;
326 struct dir_iterator
*iter
;
328 struct strbuf realpath
= STRBUF_INIT
;
330 mkdir_if_missing(dest
->buf
, 0777);
332 iter
= dir_iterator_begin(src
->buf
, DIR_ITERATOR_PEDANTIC
);
335 die_errno(_("failed to start iterator over '%s'"), src
->buf
);
337 strbuf_addch(src
, '/');
339 strbuf_addch(dest
, '/');
340 dest_len
= dest
->len
;
342 while ((iter_status
= dir_iterator_advance(iter
)) == ITER_OK
) {
343 strbuf_setlen(src
, src_len
);
344 strbuf_addstr(src
, iter
->relative_path
);
345 strbuf_setlen(dest
, dest_len
);
346 strbuf_addstr(dest
, iter
->relative_path
);
348 if (S_ISLNK(iter
->st
.st_mode
))
349 die(_("symlink '%s' exists, refusing to clone with --local"),
350 iter
->relative_path
);
352 if (S_ISDIR(iter
->st
.st_mode
)) {
353 mkdir_if_missing(dest
->buf
, 0777);
357 /* Files that cannot be copied bit-for-bit... */
358 if (!fspathcmp(iter
->relative_path
, "info/alternates")) {
359 copy_alternates(src
, src_repo
);
363 if (unlink(dest
->buf
) && errno
!= ENOENT
)
364 die_errno(_("failed to unlink '%s'"), dest
->buf
);
365 if (!option_no_hardlinks
) {
366 strbuf_realpath(&realpath
, src
->buf
, 1);
367 if (!link(realpath
.buf
, dest
->buf
))
369 if (option_local
> 0)
370 die_errno(_("failed to create link '%s'"), dest
->buf
);
371 option_no_hardlinks
= 1;
373 if (copy_file_with_time(dest
->buf
, src
->buf
, 0666))
374 die_errno(_("failed to copy file to '%s'"), dest
->buf
);
377 if (iter_status
!= ITER_DONE
) {
378 strbuf_setlen(src
, src_len
);
379 die(_("failed to iterate over '%s'"), src
->buf
);
382 strbuf_release(&realpath
);
385 static void clone_local(const char *src_repo
, const char *dest_repo
)
388 struct strbuf alt
= STRBUF_INIT
;
389 get_common_dir(&alt
, src_repo
);
390 strbuf_addstr(&alt
, "/objects");
391 add_to_alternates_file(alt
.buf
);
392 strbuf_release(&alt
);
394 struct strbuf src
= STRBUF_INIT
;
395 struct strbuf dest
= STRBUF_INIT
;
396 get_common_dir(&src
, src_repo
);
397 get_common_dir(&dest
, dest_repo
);
398 strbuf_addstr(&src
, "/objects");
399 strbuf_addstr(&dest
, "/objects");
400 copy_or_link_directory(&src
, &dest
, src_repo
);
401 strbuf_release(&src
);
402 strbuf_release(&dest
);
405 if (0 <= option_verbosity
)
406 fprintf(stderr
, _("done.\n"));
409 static const char *junk_work_tree
;
410 static int junk_work_tree_flags
;
411 static const char *junk_git_dir
;
412 static int junk_git_dir_flags
;
417 } junk_mode
= JUNK_LEAVE_NONE
;
419 static const char junk_leave_repo_msg
[] =
420 N_("Clone succeeded, but checkout failed.\n"
421 "You can inspect what was checked out with 'git status'\n"
422 "and retry with 'git restore --source=HEAD :/'\n");
424 static void remove_junk(void)
426 struct strbuf sb
= STRBUF_INIT
;
429 case JUNK_LEAVE_REPO
:
430 warning("%s", _(junk_leave_repo_msg
));
435 /* proceed to removal */
440 strbuf_addstr(&sb
, junk_git_dir
);
441 remove_dir_recursively(&sb
, junk_git_dir_flags
);
444 if (junk_work_tree
) {
445 strbuf_addstr(&sb
, junk_work_tree
);
446 remove_dir_recursively(&sb
, junk_work_tree_flags
);
451 static void remove_junk_on_signal(int signo
)
458 static struct ref
*find_remote_branch(const struct ref
*refs
, const char *branch
)
461 struct strbuf head
= STRBUF_INIT
;
462 strbuf_addstr(&head
, "refs/heads/");
463 strbuf_addstr(&head
, branch
);
464 ref
= find_ref_by_name(refs
, head
.buf
);
465 strbuf_release(&head
);
470 strbuf_addstr(&head
, "refs/tags/");
471 strbuf_addstr(&head
, branch
);
472 ref
= find_ref_by_name(refs
, head
.buf
);
473 strbuf_release(&head
);
478 static struct ref
*wanted_peer_refs(const struct ref
*refs
,
479 struct refspec
*refspec
)
481 struct ref
*head
= copy_ref(find_ref_by_name(refs
, "HEAD"));
482 struct ref
*local_refs
= head
;
483 struct ref
**tail
= head
? &head
->next
: &local_refs
;
485 if (option_single_branch
) {
486 struct ref
*remote_head
= NULL
;
489 remote_head
= guess_remote_head(head
, refs
, 0);
493 remote_head
= copy_ref(find_remote_branch(refs
, option_branch
));
496 if (!remote_head
&& option_branch
)
497 warning(_("Could not find remote branch %s to clone."),
501 for (i
= 0; i
< refspec
->nr
; i
++)
502 get_fetch_map(remote_head
, &refspec
->items
[i
],
505 /* if --branch=tag, pull the requested tag explicitly */
506 get_fetch_map(remote_head
, tag_refspec
, &tail
, 0);
508 free_refs(remote_head
);
511 for (i
= 0; i
< refspec
->nr
; i
++)
512 get_fetch_map(refs
, &refspec
->items
[i
], &tail
, 0);
515 if (!option_mirror
&& !option_single_branch
&& !option_no_tags
)
516 get_fetch_map(refs
, tag_refspec
, &tail
, 0);
521 static void write_remote_refs(const struct ref
*local_refs
)
525 struct ref_transaction
*t
;
526 struct strbuf err
= STRBUF_INIT
;
528 t
= ref_transaction_begin(&err
);
532 for (r
= local_refs
; r
; r
= r
->next
) {
535 if (ref_transaction_create(t
, r
->peer_ref
->name
, &r
->old_oid
,
540 if (initial_ref_transaction_commit(t
, &err
))
543 strbuf_release(&err
);
544 ref_transaction_free(t
);
547 static void write_followtags(const struct ref
*refs
, const char *msg
)
549 const struct ref
*ref
;
550 for (ref
= refs
; ref
; ref
= ref
->next
) {
551 if (!starts_with(ref
->name
, "refs/tags/"))
553 if (ends_with(ref
->name
, "^{}"))
555 if (!has_object_file_with_flags(&ref
->old_oid
,
557 OBJECT_INFO_SKIP_FETCH_OBJECT
))
559 update_ref(msg
, ref
->name
, &ref
->old_oid
, NULL
, 0,
560 UPDATE_REFS_DIE_ON_ERR
);
564 static const struct object_id
*iterate_ref_map(void *cb_data
)
566 struct ref
**rm
= cb_data
;
567 struct ref
*ref
= *rm
;
570 * Skip anything missing a peer_ref, which we are not
571 * actually going to write a ref for.
573 while (ref
&& !ref
->peer_ref
)
579 return &ref
->old_oid
;
582 static void update_remote_refs(const struct ref
*refs
,
583 const struct ref
*mapped_refs
,
584 const struct ref
*remote_head_points_at
,
585 const char *branch_top
,
587 struct transport
*transport
,
588 int check_connectivity
)
590 const struct ref
*rm
= mapped_refs
;
592 if (check_connectivity
) {
593 struct check_connected_options opt
= CHECK_CONNECTED_INIT
;
595 opt
.transport
= transport
;
596 opt
.progress
= transport
->progress
;
598 if (check_connected(iterate_ref_map
, &rm
, &opt
))
599 die(_("remote did not send all necessary objects"));
603 write_remote_refs(mapped_refs
);
604 if (option_single_branch
&& !option_no_tags
)
605 write_followtags(refs
, msg
);
608 if (remote_head_points_at
&& !option_bare
) {
609 struct strbuf head_ref
= STRBUF_INIT
;
610 strbuf_addstr(&head_ref
, branch_top
);
611 strbuf_addstr(&head_ref
, "HEAD");
612 if (create_symref(head_ref
.buf
,
613 remote_head_points_at
->peer_ref
->name
,
615 die(_("unable to update %s"), head_ref
.buf
);
616 strbuf_release(&head_ref
);
620 static void update_head(const struct ref
*our
, const struct ref
*remote
,
621 const char *unborn
, const char *msg
)
624 if (our
&& skip_prefix(our
->name
, "refs/heads/", &head
)) {
625 /* Local default branch link */
626 if (create_symref("HEAD", our
->name
, NULL
) < 0)
627 die(_("unable to update HEAD"));
629 update_ref(msg
, "HEAD", &our
->old_oid
, NULL
, 0,
630 UPDATE_REFS_DIE_ON_ERR
);
631 install_branch_config(0, head
, remote_name
, our
->name
);
634 struct commit
*c
= lookup_commit_reference(the_repository
,
636 /* --branch specifies a non-branch (i.e. tags), detach HEAD */
637 update_ref(msg
, "HEAD", &c
->object
.oid
, NULL
, REF_NO_DEREF
,
638 UPDATE_REFS_DIE_ON_ERR
);
641 * We know remote HEAD points to a non-branch, or
642 * HEAD points to a branch but we don't know which one.
643 * Detach HEAD in all these cases.
645 update_ref(msg
, "HEAD", &remote
->old_oid
, NULL
, REF_NO_DEREF
,
646 UPDATE_REFS_DIE_ON_ERR
);
647 } else if (unborn
&& skip_prefix(unborn
, "refs/heads/", &head
)) {
649 * Unborn head from remote; same as "our" case above except
650 * that we have no ref to update.
652 if (create_symref("HEAD", unborn
, NULL
) < 0)
653 die(_("unable to update HEAD"));
655 install_branch_config(0, head
, remote_name
, unborn
);
659 static int git_sparse_checkout_init(const char *repo
)
661 struct child_process cmd
= CHILD_PROCESS_INIT
;
663 strvec_pushl(&cmd
.args
, "-C", repo
, "sparse-checkout", "set", NULL
);
666 * We must apply the setting in the current process
667 * for the later checkout to use the sparse-checkout file.
669 core_apply_sparse_checkout
= 1;
672 if (run_command(&cmd
)) {
673 error(_("failed to initialize sparse-checkout"));
680 static int checkout(int submodule_progress
, int filter_submodules
)
682 struct object_id oid
;
684 struct lock_file lock_file
= LOCK_INIT
;
685 struct unpack_trees_options opts
;
690 if (option_no_checkout
)
693 head
= resolve_refdup("HEAD", RESOLVE_REF_READING
, &oid
, NULL
);
695 warning(_("remote HEAD refers to nonexistent ref, "
696 "unable to checkout"));
699 if (!strcmp(head
, "HEAD")) {
700 if (advice_enabled(ADVICE_DETACHED_HEAD
))
701 detach_advice(oid_to_hex(&oid
));
704 if (!starts_with(head
, "refs/heads/"))
705 die(_("HEAD not found below refs/heads!"));
708 /* We need to be in the new work tree for the checkout */
711 repo_hold_locked_index(the_repository
, &lock_file
, LOCK_DIE_ON_ERROR
);
713 memset(&opts
, 0, sizeof opts
);
717 opts
.preserve_ignored
= 0;
718 opts
.fn
= oneway_merge
;
719 opts
.verbose_update
= (option_verbosity
>= 0);
720 opts
.src_index
= &the_index
;
721 opts
.dst_index
= &the_index
;
722 init_checkout_metadata(&opts
.meta
, head
, &oid
, NULL
);
724 tree
= parse_tree_indirect(&oid
);
726 die(_("unable to parse commit %s"), oid_to_hex(&oid
));
728 init_tree_desc(&t
, tree
->buffer
, tree
->size
);
729 if (unpack_trees(1, &t
, &opts
) < 0)
730 die(_("unable to checkout working tree"));
734 if (write_locked_index(&the_index
, &lock_file
, COMMIT_LOCK
))
735 die(_("unable to write new index file"));
737 err
|= run_hooks_l("post-checkout", oid_to_hex(null_oid()),
738 oid_to_hex(&oid
), "1", NULL
);
740 if (!err
&& (option_recurse_submodules
.nr
> 0)) {
741 struct child_process cmd
= CHILD_PROCESS_INIT
;
742 strvec_pushl(&cmd
.args
, "submodule", "update", "--require-init",
743 "--recursive", NULL
);
745 if (option_shallow_submodules
== 1)
746 strvec_push(&cmd
.args
, "--depth=1");
749 strvec_pushf(&cmd
.args
, "--jobs=%d", max_jobs
);
751 if (submodule_progress
)
752 strvec_push(&cmd
.args
, "--progress");
754 if (option_verbosity
< 0)
755 strvec_push(&cmd
.args
, "--quiet");
757 if (option_remote_submodules
) {
758 strvec_push(&cmd
.args
, "--remote");
759 strvec_push(&cmd
.args
, "--no-fetch");
762 if (filter_submodules
&& filter_options
.choice
)
763 strvec_pushf(&cmd
.args
, "--filter=%s",
764 expand_list_objects_filter_spec(&filter_options
));
766 if (option_single_branch
>= 0)
767 strvec_push(&cmd
.args
, option_single_branch
?
769 "--no-single-branch");
772 err
= run_command(&cmd
);
778 static int git_clone_config(const char *k
, const char *v
, void *cb
)
780 if (!strcmp(k
, "clone.defaultremotename")) {
782 remote_name
= xstrdup(v
);
784 if (!strcmp(k
, "clone.rejectshallow"))
785 config_reject_shallow
= git_config_bool(k
, v
);
786 if (!strcmp(k
, "clone.filtersubmodules"))
787 config_filter_submodules
= git_config_bool(k
, v
);
789 return git_default_config(k
, v
, cb
);
792 static int write_one_config(const char *key
, const char *value
, void *data
)
795 * give git_clone_config a chance to write config values back to the
796 * environment, since git_config_set_multivar_gently only deals with
799 int apply_failed
= git_clone_config(key
, value
, data
);
803 return git_config_set_multivar_gently(key
,
804 value
? value
: "true",
805 CONFIG_REGEX_NONE
, 0);
808 static void write_config(struct string_list
*config
)
812 for (i
= 0; i
< config
->nr
; i
++) {
813 if (git_config_parse_parameter(config
->items
[i
].string
,
814 write_one_config
, NULL
) < 0)
815 die(_("unable to write parameters to config file"));
819 static void write_refspec_config(const char *src_ref_prefix
,
820 const struct ref
*our_head_points_at
,
821 const struct ref
*remote_head_points_at
,
822 struct strbuf
*branch_top
)
824 struct strbuf key
= STRBUF_INIT
;
825 struct strbuf value
= STRBUF_INIT
;
827 if (option_mirror
|| !option_bare
) {
828 if (option_single_branch
&& !option_mirror
) {
830 if (starts_with(our_head_points_at
->name
, "refs/tags/"))
831 strbuf_addf(&value
, "+%s:%s", our_head_points_at
->name
,
832 our_head_points_at
->name
);
834 strbuf_addf(&value
, "+%s:%s%s", our_head_points_at
->name
,
835 branch_top
->buf
, option_branch
);
836 } else if (remote_head_points_at
) {
837 const char *head
= remote_head_points_at
->name
;
838 if (!skip_prefix(head
, "refs/heads/", &head
))
839 BUG("remote HEAD points at non-head?");
841 strbuf_addf(&value
, "+%s:%s%s", remote_head_points_at
->name
,
842 branch_top
->buf
, head
);
845 * otherwise, the next "git fetch" will
846 * simply fetch from HEAD without updating
847 * any remote-tracking branch, which is what
851 strbuf_addf(&value
, "+%s*:%s*", src_ref_prefix
, branch_top
->buf
);
853 /* Configure the remote */
855 strbuf_addf(&key
, "remote.%s.fetch", remote_name
);
856 git_config_set_multivar(key
.buf
, value
.buf
, "^$", 0);
860 strbuf_addf(&key
, "remote.%s.mirror", remote_name
);
861 git_config_set(key
.buf
, "true");
867 strbuf_release(&key
);
868 strbuf_release(&value
);
871 static void dissociate_from_references(void)
873 char *alternates
= git_pathdup("objects/info/alternates");
875 if (!access(alternates
, F_OK
)) {
876 struct child_process cmd
= CHILD_PROCESS_INIT
;
880 strvec_pushl(&cmd
.args
, "repack", "-a", "-d", NULL
);
881 if (run_command(&cmd
))
882 die(_("cannot repack to clean up"));
883 if (unlink(alternates
) && errno
!= ENOENT
)
884 die_errno(_("cannot unlink temporary alternates file"));
889 static int path_exists(const char *path
)
892 return !stat(path
, &sb
);
895 int cmd_clone(int argc
, const char **argv
, const char *prefix
)
897 int is_bundle
= 0, is_local
;
898 int reject_shallow
= 0;
899 const char *repo_name
, *repo
, *work_tree
, *git_dir
;
900 char *repo_to_free
= NULL
;
901 char *path
= NULL
, *dir
, *display_repo
= NULL
;
902 int dest_exists
, real_dest_exists
= 0;
903 const struct ref
*refs
, *remote_head
;
904 struct ref
*remote_head_points_at
= NULL
;
905 const struct ref
*our_head_points_at
;
906 char *unborn_head
= NULL
;
907 struct ref
*mapped_refs
= NULL
;
908 const struct ref
*ref
;
909 struct strbuf key
= STRBUF_INIT
;
910 struct strbuf branch_top
= STRBUF_INIT
, reflog_msg
= STRBUF_INIT
;
911 struct transport
*transport
= NULL
;
912 const char *src_ref_prefix
= "refs/heads/";
913 struct remote
*remote
;
914 int err
= 0, complete_refs_before_fetch
= 1;
915 int submodule_progress
;
916 int filter_submodules
= 0;
918 struct transport_ls_refs_options transport_ls_refs_options
=
919 TRANSPORT_LS_REFS_OPTIONS_INIT
;
921 packet_trace_identity("clone");
923 git_config(git_clone_config
, NULL
);
925 argc
= parse_options(argc
, argv
, prefix
, builtin_clone_options
,
926 builtin_clone_usage
, 0);
929 usage_msg_opt(_("Too many arguments."),
930 builtin_clone_usage
, builtin_clone_options
);
933 usage_msg_opt(_("You must specify a repository to clone."),
934 builtin_clone_usage
, builtin_clone_options
);
936 if (option_depth
|| option_since
|| option_not
.nr
)
938 if (option_single_branch
== -1)
939 option_single_branch
= deepen
? 1 : 0;
946 die(_("options '%s' and '%s' cannot be used together"), "--bare", "--separate-git-dir");
947 option_no_checkout
= 1;
950 if (bundle_uri
&& deepen
)
951 die(_("--bundle-uri is incompatible with --depth, --shallow-since, and --shallow-exclude"));
955 path
= get_repo_path(repo_name
, &is_bundle
);
958 repo
= repo_to_free
= absolute_pathdup(repo_name
);
959 } else if (strchr(repo_name
, ':')) {
961 display_repo
= transport_anonymize_url(repo
);
963 die(_("repository '%s' does not exist"), repo_name
);
965 /* no need to be strict, transport_set_option() will validate it again */
966 if (option_depth
&& atoi(option_depth
) < 1)
967 die(_("depth %s is not a positive number"), option_depth
);
970 dir
= xstrdup(argv
[1]);
972 dir
= git_url_basename(repo_name
, is_bundle
, option_bare
);
973 strip_dir_trailing_slashes(dir
);
975 dest_exists
= path_exists(dir
);
976 if (dest_exists
&& !is_empty_dir(dir
))
977 die(_("destination path '%s' already exists and is not "
978 "an empty directory."), dir
);
981 real_dest_exists
= path_exists(real_git_dir
);
982 if (real_dest_exists
&& !is_empty_dir(real_git_dir
))
983 die(_("repository path '%s' already exists and is not "
984 "an empty directory."), real_git_dir
);
988 strbuf_addf(&reflog_msg
, "clone: from %s",
989 display_repo
? display_repo
: repo
);
995 work_tree
= getenv("GIT_WORK_TREE");
996 if (work_tree
&& path_exists(work_tree
))
997 die(_("working tree '%s' already exists."), work_tree
);
1000 if (option_bare
|| work_tree
)
1001 git_dir
= xstrdup(dir
);
1004 git_dir
= mkpathdup("%s/.git", dir
);
1007 atexit(remove_junk
);
1008 sigchain_push_common(remove_junk_on_signal
);
1011 if (safe_create_leading_directories_const(work_tree
) < 0)
1012 die_errno(_("could not create leading directories of '%s'"),
1015 junk_work_tree_flags
|= REMOVE_DIR_KEEP_TOPLEVEL
;
1016 else if (mkdir(work_tree
, 0777))
1017 die_errno(_("could not create work tree dir '%s'"),
1019 junk_work_tree
= work_tree
;
1020 set_git_work_tree(work_tree
);
1024 if (real_dest_exists
)
1025 junk_git_dir_flags
|= REMOVE_DIR_KEEP_TOPLEVEL
;
1026 junk_git_dir
= real_git_dir
;
1029 junk_git_dir_flags
|= REMOVE_DIR_KEEP_TOPLEVEL
;
1030 junk_git_dir
= git_dir
;
1032 if (safe_create_leading_directories_const(git_dir
) < 0)
1033 die(_("could not create leading directories of '%s'"), git_dir
);
1035 if (0 <= option_verbosity
) {
1037 fprintf(stderr
, _("Cloning into bare repository '%s'...\n"), dir
);
1039 fprintf(stderr
, _("Cloning into '%s'...\n"), dir
);
1042 if (option_recurse_submodules
.nr
> 0) {
1043 struct string_list_item
*item
;
1044 struct strbuf sb
= STRBUF_INIT
;
1047 /* remove duplicates */
1048 string_list_sort(&option_recurse_submodules
);
1049 string_list_remove_duplicates(&option_recurse_submodules
, 0);
1052 * NEEDSWORK: In a multi-working-tree world, this needs to be
1053 * set in the per-worktree config.
1055 for_each_string_list_item(item
, &option_recurse_submodules
) {
1056 strbuf_addf(&sb
, "submodule.active=%s",
1058 string_list_append(&option_config
,
1059 strbuf_detach(&sb
, NULL
));
1062 if (!git_config_get_bool("submodule.stickyRecursiveClone", &val
) &&
1064 string_list_append(&option_config
, "submodule.recurse=true");
1066 if (option_required_reference
.nr
&&
1067 option_optional_reference
.nr
)
1068 die(_("clone --recursive is not compatible with "
1069 "both --reference and --reference-if-able"));
1070 else if (option_required_reference
.nr
) {
1071 string_list_append(&option_config
,
1072 "submodule.alternateLocation=superproject");
1073 string_list_append(&option_config
,
1074 "submodule.alternateErrorStrategy=die");
1075 } else if (option_optional_reference
.nr
) {
1076 string_list_append(&option_config
,
1077 "submodule.alternateLocation=superproject");
1078 string_list_append(&option_config
,
1079 "submodule.alternateErrorStrategy=info");
1083 init_db(git_dir
, real_git_dir
, option_template
, GIT_HASH_UNKNOWN
, NULL
,
1087 free((char *)git_dir
);
1088 git_dir
= real_git_dir
;
1092 * additional config can be injected with -c, make sure it's included
1093 * after init_db, which clears the entire config environment.
1095 write_config(&option_config
);
1098 * re-read config after init_db and write_config to pick up any config
1099 * injected by --template and --config, respectively.
1101 git_config(git_clone_config
, NULL
);
1104 * If option_reject_shallow is specified from CLI option,
1105 * ignore config_reject_shallow from git_clone_config.
1107 if (config_reject_shallow
!= -1)
1108 reject_shallow
= config_reject_shallow
;
1109 if (option_reject_shallow
!= -1)
1110 reject_shallow
= option_reject_shallow
;
1113 * If option_filter_submodules is specified from CLI option,
1114 * ignore config_filter_submodules from git_clone_config.
1116 if (config_filter_submodules
!= -1)
1117 filter_submodules
= config_filter_submodules
;
1118 if (option_filter_submodules
!= -1)
1119 filter_submodules
= option_filter_submodules
;
1122 * Exit if the user seems to be doing something silly with submodule
1123 * filter flags (but not with filter configs, as those should be
1126 if (option_filter_submodules
> 0 && !filter_options
.choice
)
1127 die(_("the option '%s' requires '%s'"),
1128 "--also-filter-submodules", "--filter");
1129 if (option_filter_submodules
> 0 && !option_recurse_submodules
.nr
)
1130 die(_("the option '%s' requires '%s'"),
1131 "--also-filter-submodules", "--recurse-submodules");
1134 * apply the remote name provided by --origin only after this second
1135 * call to git_config, to ensure it overrides all config-based values.
1137 if (option_origin
) {
1139 remote_name
= xstrdup(option_origin
);
1143 remote_name
= xstrdup("origin");
1145 if (!valid_remote_name(remote_name
))
1146 die(_("'%s' is not a valid remote name"), remote_name
);
1150 src_ref_prefix
= "refs/";
1151 strbuf_addstr(&branch_top
, src_ref_prefix
);
1153 git_config_set("core.bare", "true");
1155 strbuf_addf(&branch_top
, "refs/remotes/%s/", remote_name
);
1158 strbuf_addf(&key
, "remote.%s.url", remote_name
);
1159 git_config_set(key
.buf
, repo
);
1162 if (option_no_tags
) {
1163 strbuf_addf(&key
, "remote.%s.tagOpt", remote_name
);
1164 git_config_set(key
.buf
, "--no-tags");
1168 if (option_required_reference
.nr
|| option_optional_reference
.nr
)
1171 if (option_sparse_checkout
&& git_sparse_checkout_init(dir
))
1174 remote
= remote_get(remote_name
);
1176 refspec_appendf(&remote
->fetch
, "+%s*:%s*", src_ref_prefix
,
1179 path
= get_repo_path(remote
->url
[0], &is_bundle
);
1180 is_local
= option_local
!= 0 && path
&& !is_bundle
;
1183 warning(_("--depth is ignored in local clones; use file:// instead."));
1185 warning(_("--shallow-since is ignored in local clones; use file:// instead."));
1187 warning(_("--shallow-exclude is ignored in local clones; use file:// instead."));
1188 if (filter_options
.choice
)
1189 warning(_("--filter is ignored in local clones; use file:// instead."));
1190 if (!access(mkpath("%s/shallow", path
), F_OK
)) {
1192 die(_("source repository is shallow, reject to clone."));
1193 if (option_local
> 0)
1194 warning(_("source repository is shallow, ignoring --local"));
1198 if (option_local
> 0 && !is_local
)
1199 warning(_("--local is ignored"));
1201 transport
= transport_get(remote
, path
? path
: remote
->url
[0]);
1202 transport_set_verbosity(transport
, option_verbosity
, option_progress
);
1203 transport
->family
= family
;
1204 transport
->cloning
= 1;
1207 struct bundle_header header
= BUNDLE_HEADER_INIT
;
1208 int fd
= read_bundle_header(path
, &header
);
1209 int has_filter
= header
.filter
.choice
!= LOFC_DISABLED
;
1213 bundle_header_release(&header
);
1215 die(_("cannot clone from filtered bundle"));
1218 transport_set_option(transport
, TRANS_OPT_KEEP
, "yes");
1221 transport_set_option(transport
, TRANS_OPT_REJECT_SHALLOW
, "1");
1223 transport_set_option(transport
, TRANS_OPT_DEPTH
,
1226 transport_set_option(transport
, TRANS_OPT_DEEPEN_SINCE
,
1229 transport_set_option(transport
, TRANS_OPT_DEEPEN_NOT
,
1230 (const char *)&option_not
);
1231 if (option_single_branch
)
1232 transport_set_option(transport
, TRANS_OPT_FOLLOWTAGS
, "1");
1234 if (option_upload_pack
)
1235 transport_set_option(transport
, TRANS_OPT_UPLOADPACK
,
1236 option_upload_pack
);
1238 if (server_options
.nr
)
1239 transport
->server_options
= &server_options
;
1241 if (filter_options
.choice
) {
1243 expand_list_objects_filter_spec(&filter_options
);
1244 transport_set_option(transport
, TRANS_OPT_LIST_OBJECTS_FILTER
,
1246 transport_set_option(transport
, TRANS_OPT_FROM_PROMISOR
, "1");
1249 if (transport
->smart_options
&& !deepen
&& !filter_options
.choice
)
1250 transport
->smart_options
->check_self_contained_and_connected
= 1;
1253 * Before fetching from the remote, download and install bundle
1254 * data from the --bundle-uri option.
1257 int has_heuristic
= 0;
1259 /* At this point, we need the_repository to match the cloned repo. */
1260 if (repo_init(the_repository
, git_dir
, work_tree
))
1261 warning(_("failed to initialize the repo, skipping bundle URI"));
1262 else if (fetch_bundle_uri(the_repository
, bundle_uri
, &has_heuristic
))
1263 warning(_("failed to fetch objects from bundle URI '%s'"),
1265 else if (has_heuristic
)
1266 git_config_set_gently("fetch.bundleuri", bundle_uri
);
1269 strvec_push(&transport_ls_refs_options
.ref_prefixes
, "HEAD");
1270 refspec_ref_prefixes(&remote
->fetch
,
1271 &transport_ls_refs_options
.ref_prefixes
);
1273 expand_ref_prefix(&transport_ls_refs_options
.ref_prefixes
,
1275 if (!option_no_tags
)
1276 strvec_push(&transport_ls_refs_options
.ref_prefixes
,
1279 refs
= transport_get_remote_refs(transport
, &transport_ls_refs_options
);
1282 mapped_refs
= wanted_peer_refs(refs
, &remote
->fetch
);
1286 * Populate transport->got_remote_bundle_uri and
1287 * transport->bundle_uri. We might get nothing.
1289 transport_get_remote_bundle_uri(transport
);
1291 if (transport
->bundles
&&
1292 hashmap_get_size(&transport
->bundles
->bundles
)) {
1293 /* At this point, we need the_repository to match the cloned repo. */
1294 if (repo_init(the_repository
, git_dir
, work_tree
))
1295 warning(_("failed to initialize the repo, skipping bundle URI"));
1296 else if (fetch_bundle_list(the_repository
,
1297 transport
->bundles
))
1298 warning(_("failed to fetch advertised bundles"));
1300 clear_bundle_list(transport
->bundles
);
1301 FREE_AND_NULL(transport
->bundles
);
1306 int hash_algo
= hash_algo_by_ptr(transport_get_hash_algo(transport
));
1309 * Now that we know what algorithm the remote side is using,
1310 * let's set ours to the same thing.
1312 initialize_repository_version(hash_algo
, 1);
1313 repo_set_hash_algo(the_repository
, hash_algo
);
1315 * transport_get_remote_refs() may return refs with null sha-1
1316 * in mapped_refs (see struct transport->get_refs_list
1317 * comment). In that case we need fetch it early because
1318 * remote_head code below relies on it.
1320 * for normal clones, transport_get_remote_refs() should
1321 * return reliable ref set, we can delay cloning until after
1322 * remote HEAD check.
1324 for (ref
= refs
; ref
; ref
= ref
->next
)
1325 if (is_null_oid(&ref
->old_oid
)) {
1326 complete_refs_before_fetch
= 0;
1330 if (!is_local
&& !complete_refs_before_fetch
) {
1331 if (transport_fetch_refs(transport
, mapped_refs
))
1332 die(_("remote transport reported error"));
1336 remote_head
= find_ref_by_name(refs
, "HEAD");
1337 remote_head_points_at
= guess_remote_head(remote_head
, mapped_refs
, 0);
1339 if (option_branch
) {
1340 our_head_points_at
= find_remote_branch(mapped_refs
, option_branch
);
1341 if (!our_head_points_at
)
1342 die(_("Remote branch %s not found in upstream %s"),
1343 option_branch
, remote_name
);
1344 } else if (remote_head_points_at
) {
1345 our_head_points_at
= remote_head_points_at
;
1346 } else if (remote_head
) {
1347 our_head_points_at
= NULL
;
1352 warning(_("You appear to have cloned an empty repository."));
1353 option_no_checkout
= 1;
1356 if (transport_ls_refs_options
.unborn_head_target
&&
1357 skip_prefix(transport_ls_refs_options
.unborn_head_target
,
1358 "refs/heads/", &branch
)) {
1359 unborn_head
= xstrdup(transport_ls_refs_options
.unborn_head_target
);
1361 branch
= git_default_branch_name(0);
1362 unborn_head
= xstrfmt("refs/heads/%s", branch
);
1366 * We may have selected a local default branch name "foo",
1367 * and even though the remote's HEAD does not point there,
1368 * it may still have a "foo" branch. If so, set it up so
1369 * that we can follow the usual checkout code later.
1371 * Note that for an empty repo we'll already have set
1372 * option_no_checkout above, which would work against us here.
1373 * But for an empty repo, find_remote_branch() can never find
1376 our_head_points_at
= find_remote_branch(mapped_refs
, branch
);
1379 write_refspec_config(src_ref_prefix
, our_head_points_at
,
1380 remote_head_points_at
, &branch_top
);
1382 if (filter_options
.choice
)
1383 partial_clone_register(remote_name
, &filter_options
);
1386 clone_local(path
, git_dir
);
1387 else if (mapped_refs
&& complete_refs_before_fetch
) {
1388 if (transport_fetch_refs(transport
, mapped_refs
))
1389 die(_("remote transport reported error"));
1392 update_remote_refs(refs
, mapped_refs
, remote_head_points_at
,
1393 branch_top
.buf
, reflog_msg
.buf
, transport
,
1396 update_head(our_head_points_at
, remote_head
, unborn_head
, reflog_msg
.buf
);
1399 * We want to show progress for recursive submodule clones iff
1400 * we did so for the main clone. But only the transport knows
1401 * the final decision for this flag, so we need to rescue the value
1402 * before we free the transport.
1404 submodule_progress
= transport
->progress
;
1406 transport_unlock_pack(transport
, 0);
1407 transport_disconnect(transport
);
1409 if (option_dissociate
) {
1410 close_object_store(the_repository
->objects
);
1411 dissociate_from_references();
1414 junk_mode
= JUNK_LEAVE_REPO
;
1415 err
= checkout(submodule_progress
, filter_submodules
);
1418 strbuf_release(&reflog_msg
);
1419 strbuf_release(&branch_top
);
1420 strbuf_release(&key
);
1421 free_refs(mapped_refs
);
1422 free_refs(remote_head_points_at
);
1427 junk_mode
= JUNK_LEAVE_ALL
;
1429 transport_ls_refs_options_release(&transport_ls_refs_options
);