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_COMPATIBILITY_MACROS
15 #include "parse-options.h"
16 #include "fetch-pack.h"
19 #include "object-store.h"
21 #include "tree-walk.h"
22 #include "unpack-trees.h"
23 #include "transport.h"
26 #include "dir-iterator.h"
31 #include "run-command.h"
32 #include "connected.h"
34 #include "list-objects-filter-options.h"
38 * - respect DB_ENVIRONMENT for .git/objects.
40 * Implementation notes:
41 * - dropping use-separate-remote and no-separate-remote compatibility
44 static const char * const builtin_clone_usage
[] = {
45 N_("git clone [<options>] [--] <repo> [<dir>]"),
49 static int option_no_checkout
, option_bare
, option_mirror
, option_single_branch
= -1;
50 static int option_local
= -1, option_no_hardlinks
, option_shared
;
51 static int option_no_tags
;
52 static int option_shallow_submodules
;
53 static int option_reject_shallow
= -1; /* unspecified */
54 static int config_reject_shallow
= -1; /* unspecified */
56 static char *option_template
, *option_depth
, *option_since
;
57 static char *option_origin
= NULL
;
58 static char *remote_name
= NULL
;
59 static char *option_branch
= NULL
;
60 static struct string_list option_not
= STRING_LIST_INIT_NODUP
;
61 static const char *real_git_dir
;
62 static char *option_upload_pack
= "git-upload-pack";
63 static int option_verbosity
;
64 static int option_progress
= -1;
65 static int option_sparse_checkout
;
66 static enum transport_family family
;
67 static struct string_list option_config
= STRING_LIST_INIT_NODUP
;
68 static struct string_list option_required_reference
= STRING_LIST_INIT_NODUP
;
69 static struct string_list option_optional_reference
= STRING_LIST_INIT_NODUP
;
70 static int option_dissociate
;
71 static int max_jobs
= -1;
72 static struct string_list option_recurse_submodules
= STRING_LIST_INIT_NODUP
;
73 static struct list_objects_filter_options filter_options
;
74 static struct string_list server_options
= STRING_LIST_INIT_NODUP
;
75 static int option_remote_submodules
;
77 static int recurse_submodules_cb(const struct option
*opt
,
78 const char *arg
, int unset
)
81 string_list_clear((struct string_list
*)opt
->value
, 0);
83 string_list_append((struct string_list
*)opt
->value
, arg
);
85 string_list_append((struct string_list
*)opt
->value
,
86 (const char *)opt
->defval
);
91 static struct option builtin_clone_options
[] = {
92 OPT__VERBOSITY(&option_verbosity
),
93 OPT_BOOL(0, "progress", &option_progress
,
94 N_("force progress reporting")),
95 OPT_BOOL(0, "reject-shallow", &option_reject_shallow
,
96 N_("don't clone shallow repository")),
97 OPT_BOOL('n', "no-checkout", &option_no_checkout
,
98 N_("don't create a checkout")),
99 OPT_BOOL(0, "bare", &option_bare
, N_("create a bare repository")),
100 OPT_HIDDEN_BOOL(0, "naked", &option_bare
,
101 N_("create a bare repository")),
102 OPT_BOOL(0, "mirror", &option_mirror
,
103 N_("create a mirror repository (implies bare)")),
104 OPT_BOOL('l', "local", &option_local
,
105 N_("to clone from a local repository")),
106 OPT_BOOL(0, "no-hardlinks", &option_no_hardlinks
,
107 N_("don't use local hardlinks, always copy")),
108 OPT_BOOL('s', "shared", &option_shared
,
109 N_("setup as shared repository")),
110 { OPTION_CALLBACK
, 0, "recurse-submodules", &option_recurse_submodules
,
111 N_("pathspec"), N_("initialize submodules in the clone"),
112 PARSE_OPT_OPTARG
, recurse_submodules_cb
, (intptr_t)"." },
113 OPT_ALIAS(0, "recursive", "recurse-submodules"),
114 OPT_INTEGER('j', "jobs", &max_jobs
,
115 N_("number of submodules cloned in parallel")),
116 OPT_STRING(0, "template", &option_template
, N_("template-directory"),
117 N_("directory from which templates will be used")),
118 OPT_STRING_LIST(0, "reference", &option_required_reference
, N_("repo"),
119 N_("reference repository")),
120 OPT_STRING_LIST(0, "reference-if-able", &option_optional_reference
,
121 N_("repo"), N_("reference repository")),
122 OPT_BOOL(0, "dissociate", &option_dissociate
,
123 N_("use --reference only while cloning")),
124 OPT_STRING('o', "origin", &option_origin
, N_("name"),
125 N_("use <name> instead of 'origin' to track upstream")),
126 OPT_STRING('b', "branch", &option_branch
, N_("branch"),
127 N_("checkout <branch> instead of the remote's HEAD")),
128 OPT_STRING('u', "upload-pack", &option_upload_pack
, N_("path"),
129 N_("path to git-upload-pack on the remote")),
130 OPT_STRING(0, "depth", &option_depth
, N_("depth"),
131 N_("create a shallow clone of that depth")),
132 OPT_STRING(0, "shallow-since", &option_since
, N_("time"),
133 N_("create a shallow clone since a specific time")),
134 OPT_STRING_LIST(0, "shallow-exclude", &option_not
, N_("revision"),
135 N_("deepen history of shallow clone, excluding rev")),
136 OPT_BOOL(0, "single-branch", &option_single_branch
,
137 N_("clone only one branch, HEAD or --branch")),
138 OPT_BOOL(0, "no-tags", &option_no_tags
,
139 N_("don't clone any tags, and make later fetches not to follow them")),
140 OPT_BOOL(0, "shallow-submodules", &option_shallow_submodules
,
141 N_("any cloned submodules will be shallow")),
142 OPT_STRING(0, "separate-git-dir", &real_git_dir
, N_("gitdir"),
143 N_("separate git dir from working tree")),
144 OPT_STRING_LIST('c', "config", &option_config
, N_("key=value"),
145 N_("set config inside the new repository")),
146 OPT_STRING_LIST(0, "server-option", &server_options
,
147 N_("server-specific"), N_("option to transmit")),
148 OPT_SET_INT('4', "ipv4", &family
, N_("use IPv4 addresses only"),
149 TRANSPORT_FAMILY_IPV4
),
150 OPT_SET_INT('6', "ipv6", &family
, N_("use IPv6 addresses only"),
151 TRANSPORT_FAMILY_IPV6
),
152 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options
),
153 OPT_BOOL(0, "remote-submodules", &option_remote_submodules
,
154 N_("any cloned submodules will use their remote-tracking branch")),
155 OPT_BOOL(0, "sparse", &option_sparse_checkout
,
156 N_("initialize sparse-checkout file to include only files at root")),
160 static const char *get_repo_path_1(struct strbuf
*path
, int *is_bundle
)
162 static char *suffix
[] = { "/.git", "", ".git/.git", ".git" };
163 static char *bundle_suffix
[] = { ".bundle", "" };
164 size_t baselen
= path
->len
;
168 for (i
= 0; i
< ARRAY_SIZE(suffix
); i
++) {
169 strbuf_setlen(path
, baselen
);
170 strbuf_addstr(path
, suffix
[i
]);
171 if (stat(path
->buf
, &st
))
173 if (S_ISDIR(st
.st_mode
) && is_git_directory(path
->buf
)) {
176 } else if (S_ISREG(st
.st_mode
) && st
.st_size
> 8) {
177 /* Is it a "gitfile"? */
180 int len
, fd
= open(path
->buf
, O_RDONLY
);
183 len
= read_in_full(fd
, signature
, 8);
185 if (len
!= 8 || strncmp(signature
, "gitdir: ", 8))
187 dst
= read_gitfile(path
->buf
);
195 for (i
= 0; i
< ARRAY_SIZE(bundle_suffix
); i
++) {
196 strbuf_setlen(path
, baselen
);
197 strbuf_addstr(path
, bundle_suffix
[i
]);
198 if (!stat(path
->buf
, &st
) && S_ISREG(st
.st_mode
)) {
207 static char *get_repo_path(const char *repo
, int *is_bundle
)
209 struct strbuf path
= STRBUF_INIT
;
213 strbuf_addstr(&path
, repo
);
214 raw
= get_repo_path_1(&path
, is_bundle
);
215 canon
= raw
? absolute_pathdup(raw
) : NULL
;
216 strbuf_release(&path
);
220 static char *guess_dir_name(const char *repo
, int is_bundle
, int is_bare
)
222 const char *end
= repo
+ strlen(repo
), *start
, *ptr
;
229 start
= strstr(repo
, "://");
236 * Skip authentication data. The stripping does happen
237 * greedily, such that we strip up to the last '@' inside
240 for (ptr
= start
; ptr
< end
&& !is_dir_sep(*ptr
); ptr
++) {
246 * Strip trailing spaces, slashes and /.git
248 while (start
< end
&& (is_dir_sep(end
[-1]) || isspace(end
[-1])))
250 if (end
- start
> 5 && is_dir_sep(end
[-5]) &&
251 !strncmp(end
- 4, ".git", 4)) {
253 while (start
< end
&& is_dir_sep(end
[-1]))
258 * It should not be possible to overflow `ptrdiff_t` by passing in an
259 * insanely long URL, but GCC does not know that and will complain
260 * without this check.
263 die(_("No directory name could be guessed.\n"
264 "Please specify a directory on the command line"));
267 * Strip trailing port number if we've got only a
268 * hostname (that is, there is no dir separator but a
269 * colon). This check is required such that we do not
270 * strip URI's like '/foo/bar:2222.git', which should
271 * result in a dir '2222' being guessed due to backwards
274 if (memchr(start
, '/', end
- start
) == NULL
275 && memchr(start
, ':', end
- start
) != NULL
) {
277 while (start
< ptr
&& isdigit(ptr
[-1]) && ptr
[-1] != ':')
279 if (start
< ptr
&& ptr
[-1] == ':')
284 * Find last component. To remain backwards compatible we
285 * also regard colons as path separators, such that
286 * cloning a repository 'foo:bar.git' would result in a
287 * directory 'bar' being guessed.
290 while (start
< ptr
&& !is_dir_sep(ptr
[-1]) && ptr
[-1] != ':')
295 * Strip .{bundle,git}.
298 strip_suffix_mem(start
, &len
, is_bundle
? ".bundle" : ".git");
300 if (!len
|| (len
== 1 && *start
== '/'))
301 die(_("No directory name could be guessed.\n"
302 "Please specify a directory on the command line"));
305 dir
= xstrfmt("%.*s.git", (int)len
, start
);
307 dir
= xstrndup(start
, len
);
309 * Replace sequences of 'control' characters and whitespace
310 * with one ascii space, remove leading and trailing spaces.
314 int prev_space
= 1 /* strip leading whitespace */;
315 for (end
= dir
; *end
; ++end
) {
317 if ((unsigned char)ch
< '\x20')
328 if (out
> dir
&& prev_space
)
334 static void strip_trailing_slashes(char *dir
)
336 char *end
= dir
+ strlen(dir
);
338 while (dir
< end
- 1 && is_dir_sep(end
[-1]))
343 static int add_one_reference(struct string_list_item
*item
, void *cb_data
)
345 struct strbuf err
= STRBUF_INIT
;
346 int *required
= cb_data
;
347 char *ref_git
= compute_alternate_path(item
->string
, &err
);
354 _("info: Could not add alternate for '%s': %s\n"),
355 item
->string
, err
.buf
);
357 struct strbuf sb
= STRBUF_INIT
;
358 strbuf_addf(&sb
, "%s/objects", ref_git
);
359 add_to_alternates_file(sb
.buf
);
363 strbuf_release(&err
);
368 static void setup_reference(void)
371 for_each_string_list(&option_required_reference
,
372 add_one_reference
, &required
);
374 for_each_string_list(&option_optional_reference
,
375 add_one_reference
, &required
);
378 static void copy_alternates(struct strbuf
*src
, const char *src_repo
)
381 * Read from the source objects/info/alternates file
382 * and copy the entries to corresponding file in the
383 * destination repository with add_to_alternates_file().
384 * Both src and dst have "$path/objects/info/alternates".
386 * Instead of copying bit-for-bit from the original,
387 * we need to append to existing one so that the already
388 * created entry via "clone -s" is not lost, and also
389 * to turn entries with paths relative to the original
390 * absolute, so that they can be used in the new repository.
392 FILE *in
= xfopen(src
->buf
, "r");
393 struct strbuf line
= STRBUF_INIT
;
395 while (strbuf_getline(&line
, in
) != EOF
) {
397 if (!line
.len
|| line
.buf
[0] == '#')
399 if (is_absolute_path(line
.buf
)) {
400 add_to_alternates_file(line
.buf
);
403 abs_path
= mkpathdup("%s/objects/%s", src_repo
, line
.buf
);
404 if (!normalize_path_copy(abs_path
, abs_path
))
405 add_to_alternates_file(abs_path
);
407 warning("skipping invalid relative alternate: %s/%s",
411 strbuf_release(&line
);
415 static void mkdir_if_missing(const char *pathname
, mode_t mode
)
419 if (!mkdir(pathname
, mode
))
423 die_errno(_("failed to create directory '%s'"), pathname
);
424 else if (stat(pathname
, &st
))
425 die_errno(_("failed to stat '%s'"), pathname
);
426 else if (!S_ISDIR(st
.st_mode
))
427 die(_("%s exists and is not a directory"), pathname
);
430 static void copy_or_link_directory(struct strbuf
*src
, struct strbuf
*dest
,
431 const char *src_repo
)
433 int src_len
, dest_len
;
434 struct dir_iterator
*iter
;
436 struct strbuf realpath
= STRBUF_INIT
;
438 mkdir_if_missing(dest
->buf
, 0777);
440 iter
= dir_iterator_begin(src
->buf
, DIR_ITERATOR_PEDANTIC
);
443 die_errno(_("failed to start iterator over '%s'"), src
->buf
);
445 strbuf_addch(src
, '/');
447 strbuf_addch(dest
, '/');
448 dest_len
= dest
->len
;
450 while ((iter_status
= dir_iterator_advance(iter
)) == ITER_OK
) {
451 strbuf_setlen(src
, src_len
);
452 strbuf_addstr(src
, iter
->relative_path
);
453 strbuf_setlen(dest
, dest_len
);
454 strbuf_addstr(dest
, iter
->relative_path
);
456 if (S_ISLNK(iter
->st
.st_mode
))
457 die(_("symlink '%s' exists, refusing to clone with --local"),
458 iter
->relative_path
);
460 if (S_ISDIR(iter
->st
.st_mode
)) {
461 mkdir_if_missing(dest
->buf
, 0777);
465 /* Files that cannot be copied bit-for-bit... */
466 if (!fspathcmp(iter
->relative_path
, "info/alternates")) {
467 copy_alternates(src
, src_repo
);
471 if (unlink(dest
->buf
) && errno
!= ENOENT
)
472 die_errno(_("failed to unlink '%s'"), dest
->buf
);
473 if (!option_no_hardlinks
) {
474 strbuf_realpath(&realpath
, src
->buf
, 1);
475 if (!link(realpath
.buf
, dest
->buf
))
477 if (option_local
> 0)
478 die_errno(_("failed to create link '%s'"), dest
->buf
);
479 option_no_hardlinks
= 1;
481 if (copy_file_with_time(dest
->buf
, src
->buf
, 0666))
482 die_errno(_("failed to copy file to '%s'"), dest
->buf
);
485 if (iter_status
!= ITER_DONE
) {
486 strbuf_setlen(src
, src_len
);
487 die(_("failed to iterate over '%s'"), src
->buf
);
490 strbuf_release(&realpath
);
493 static void clone_local(const char *src_repo
, const char *dest_repo
)
496 struct strbuf alt
= STRBUF_INIT
;
497 get_common_dir(&alt
, src_repo
);
498 strbuf_addstr(&alt
, "/objects");
499 add_to_alternates_file(alt
.buf
);
500 strbuf_release(&alt
);
502 struct strbuf src
= STRBUF_INIT
;
503 struct strbuf dest
= STRBUF_INIT
;
504 get_common_dir(&src
, src_repo
);
505 get_common_dir(&dest
, dest_repo
);
506 strbuf_addstr(&src
, "/objects");
507 strbuf_addstr(&dest
, "/objects");
508 copy_or_link_directory(&src
, &dest
, src_repo
);
509 strbuf_release(&src
);
510 strbuf_release(&dest
);
513 if (0 <= option_verbosity
)
514 fprintf(stderr
, _("done.\n"));
517 static const char *junk_work_tree
;
518 static int junk_work_tree_flags
;
519 static const char *junk_git_dir
;
520 static int junk_git_dir_flags
;
525 } junk_mode
= JUNK_LEAVE_NONE
;
527 static const char junk_leave_repo_msg
[] =
528 N_("Clone succeeded, but checkout failed.\n"
529 "You can inspect what was checked out with 'git status'\n"
530 "and retry with 'git restore --source=HEAD :/'\n");
532 static void remove_junk(void)
534 struct strbuf sb
= STRBUF_INIT
;
537 case JUNK_LEAVE_REPO
:
538 warning("%s", _(junk_leave_repo_msg
));
543 /* proceed to removal */
548 strbuf_addstr(&sb
, junk_git_dir
);
549 remove_dir_recursively(&sb
, junk_git_dir_flags
);
552 if (junk_work_tree
) {
553 strbuf_addstr(&sb
, junk_work_tree
);
554 remove_dir_recursively(&sb
, junk_work_tree_flags
);
559 static void remove_junk_on_signal(int signo
)
566 static struct ref
*find_remote_branch(const struct ref
*refs
, const char *branch
)
569 struct strbuf head
= STRBUF_INIT
;
570 strbuf_addstr(&head
, "refs/heads/");
571 strbuf_addstr(&head
, branch
);
572 ref
= find_ref_by_name(refs
, head
.buf
);
573 strbuf_release(&head
);
578 strbuf_addstr(&head
, "refs/tags/");
579 strbuf_addstr(&head
, branch
);
580 ref
= find_ref_by_name(refs
, head
.buf
);
581 strbuf_release(&head
);
586 static struct ref
*wanted_peer_refs(const struct ref
*refs
,
587 struct refspec
*refspec
)
589 struct ref
*head
= copy_ref(find_ref_by_name(refs
, "HEAD"));
590 struct ref
*local_refs
= head
;
591 struct ref
**tail
= head
? &head
->next
: &local_refs
;
593 if (option_single_branch
) {
594 struct ref
*remote_head
= NULL
;
597 remote_head
= guess_remote_head(head
, refs
, 0);
601 remote_head
= copy_ref(find_remote_branch(refs
, option_branch
));
604 if (!remote_head
&& option_branch
)
605 warning(_("Could not find remote branch %s to clone."),
609 for (i
= 0; i
< refspec
->nr
; i
++)
610 get_fetch_map(remote_head
, &refspec
->items
[i
],
613 /* if --branch=tag, pull the requested tag explicitly */
614 get_fetch_map(remote_head
, tag_refspec
, &tail
, 0);
618 for (i
= 0; i
< refspec
->nr
; i
++)
619 get_fetch_map(refs
, &refspec
->items
[i
], &tail
, 0);
622 if (!option_mirror
&& !option_single_branch
&& !option_no_tags
)
623 get_fetch_map(refs
, tag_refspec
, &tail
, 0);
628 static void write_remote_refs(const struct ref
*local_refs
)
632 struct ref_transaction
*t
;
633 struct strbuf err
= STRBUF_INIT
;
635 t
= ref_transaction_begin(&err
);
639 for (r
= local_refs
; r
; r
= r
->next
) {
642 if (ref_transaction_create(t
, r
->peer_ref
->name
, &r
->old_oid
,
647 if (initial_ref_transaction_commit(t
, &err
))
650 strbuf_release(&err
);
651 ref_transaction_free(t
);
654 static void write_followtags(const struct ref
*refs
, const char *msg
)
656 const struct ref
*ref
;
657 for (ref
= refs
; ref
; ref
= ref
->next
) {
658 if (!starts_with(ref
->name
, "refs/tags/"))
660 if (ends_with(ref
->name
, "^{}"))
662 if (!has_object_file_with_flags(&ref
->old_oid
,
664 OBJECT_INFO_SKIP_FETCH_OBJECT
))
666 update_ref(msg
, ref
->name
, &ref
->old_oid
, NULL
, 0,
667 UPDATE_REFS_DIE_ON_ERR
);
671 static int iterate_ref_map(void *cb_data
, struct object_id
*oid
)
673 struct ref
**rm
= cb_data
;
674 struct ref
*ref
= *rm
;
677 * Skip anything missing a peer_ref, which we are not
678 * actually going to write a ref for.
680 while (ref
&& !ref
->peer_ref
)
682 /* Returning -1 notes "end of list" to the caller. */
686 oidcpy(oid
, &ref
->old_oid
);
691 static void update_remote_refs(const struct ref
*refs
,
692 const struct ref
*mapped_refs
,
693 const struct ref
*remote_head_points_at
,
694 const char *branch_top
,
696 struct transport
*transport
,
697 int check_connectivity
)
699 const struct ref
*rm
= mapped_refs
;
701 if (check_connectivity
) {
702 struct check_connected_options opt
= CHECK_CONNECTED_INIT
;
704 opt
.transport
= transport
;
705 opt
.progress
= transport
->progress
;
707 if (check_connected(iterate_ref_map
, &rm
, &opt
))
708 die(_("remote did not send all necessary objects"));
712 write_remote_refs(mapped_refs
);
713 if (option_single_branch
&& !option_no_tags
)
714 write_followtags(refs
, msg
);
717 if (remote_head_points_at
&& !option_bare
) {
718 struct strbuf head_ref
= STRBUF_INIT
;
719 strbuf_addstr(&head_ref
, branch_top
);
720 strbuf_addstr(&head_ref
, "HEAD");
721 if (create_symref(head_ref
.buf
,
722 remote_head_points_at
->peer_ref
->name
,
724 die(_("unable to update %s"), head_ref
.buf
);
725 strbuf_release(&head_ref
);
729 static void update_head(const struct ref
*our
, const struct ref
*remote
,
733 if (our
&& skip_prefix(our
->name
, "refs/heads/", &head
)) {
734 /* Local default branch link */
735 if (create_symref("HEAD", our
->name
, NULL
) < 0)
736 die(_("unable to update HEAD"));
738 update_ref(msg
, "HEAD", &our
->old_oid
, NULL
, 0,
739 UPDATE_REFS_DIE_ON_ERR
);
740 install_branch_config(0, head
, remote_name
, our
->name
);
743 struct commit
*c
= lookup_commit_reference(the_repository
,
745 /* --branch specifies a non-branch (i.e. tags), detach HEAD */
746 update_ref(msg
, "HEAD", &c
->object
.oid
, NULL
, REF_NO_DEREF
,
747 UPDATE_REFS_DIE_ON_ERR
);
750 * We know remote HEAD points to a non-branch, or
751 * HEAD points to a branch but we don't know which one.
752 * Detach HEAD in all these cases.
754 update_ref(msg
, "HEAD", &remote
->old_oid
, NULL
, REF_NO_DEREF
,
755 UPDATE_REFS_DIE_ON_ERR
);
759 static int git_sparse_checkout_init(const char *repo
)
761 struct strvec argv
= STRVEC_INIT
;
763 strvec_pushl(&argv
, "-C", repo
, "sparse-checkout", "init", NULL
);
766 * We must apply the setting in the current process
767 * for the later checkout to use the sparse-checkout file.
769 core_apply_sparse_checkout
= 1;
771 if (run_command_v_opt(argv
.v
, RUN_GIT_CMD
)) {
772 error(_("failed to initialize sparse-checkout"));
780 static int checkout(int submodule_progress
)
782 struct object_id oid
;
784 struct lock_file lock_file
= LOCK_INIT
;
785 struct unpack_trees_options opts
;
790 if (option_no_checkout
)
793 head
= resolve_refdup("HEAD", RESOLVE_REF_READING
, &oid
, NULL
);
795 warning(_("remote HEAD refers to nonexistent ref, "
796 "unable to checkout.\n"));
799 if (!strcmp(head
, "HEAD")) {
800 if (advice_detached_head
)
801 detach_advice(oid_to_hex(&oid
));
804 if (!starts_with(head
, "refs/heads/"))
805 die(_("HEAD not found below refs/heads!"));
808 /* We need to be in the new work tree for the checkout */
811 hold_locked_index(&lock_file
, LOCK_DIE_ON_ERROR
);
813 memset(&opts
, 0, sizeof opts
);
817 opts
.fn
= oneway_merge
;
818 opts
.verbose_update
= (option_verbosity
>= 0);
819 opts
.src_index
= &the_index
;
820 opts
.dst_index
= &the_index
;
821 init_checkout_metadata(&opts
.meta
, head
, &oid
, NULL
);
823 tree
= parse_tree_indirect(&oid
);
825 init_tree_desc(&t
, tree
->buffer
, tree
->size
);
826 if (unpack_trees(1, &t
, &opts
) < 0)
827 die(_("unable to checkout working tree"));
831 if (write_locked_index(&the_index
, &lock_file
, COMMIT_LOCK
))
832 die(_("unable to write new index file"));
834 err
|= run_hook_le(NULL
, "post-checkout", oid_to_hex(null_oid()),
835 oid_to_hex(&oid
), "1", NULL
);
837 if (!err
&& (option_recurse_submodules
.nr
> 0)) {
838 struct strvec args
= STRVEC_INIT
;
839 strvec_pushl(&args
, "submodule", "update", "--require-init", "--recursive", NULL
);
841 if (option_shallow_submodules
== 1)
842 strvec_push(&args
, "--depth=1");
845 strvec_pushf(&args
, "--jobs=%d", max_jobs
);
847 if (submodule_progress
)
848 strvec_push(&args
, "--progress");
850 if (option_verbosity
< 0)
851 strvec_push(&args
, "--quiet");
853 if (option_remote_submodules
) {
854 strvec_push(&args
, "--remote");
855 strvec_push(&args
, "--no-fetch");
858 if (option_single_branch
>= 0)
859 strvec_push(&args
, option_single_branch
?
861 "--no-single-branch");
863 err
= run_command_v_opt(args
.v
, RUN_GIT_CMD
);
870 static int git_clone_config(const char *k
, const char *v
, void *cb
)
872 if (!strcmp(k
, "clone.defaultremotename")) {
874 remote_name
= xstrdup(v
);
876 if (!strcmp(k
, "clone.rejectshallow"))
877 config_reject_shallow
= git_config_bool(k
, v
);
879 return git_default_config(k
, v
, cb
);
882 static int write_one_config(const char *key
, const char *value
, void *data
)
885 * give git_clone_config a chance to write config values back to the
886 * environment, since git_config_set_multivar_gently only deals with
889 int apply_failed
= git_clone_config(key
, value
, data
);
893 return git_config_set_multivar_gently(key
,
894 value
? value
: "true",
895 CONFIG_REGEX_NONE
, 0);
898 static void write_config(struct string_list
*config
)
902 for (i
= 0; i
< config
->nr
; i
++) {
903 if (git_config_parse_parameter(config
->items
[i
].string
,
904 write_one_config
, NULL
) < 0)
905 die(_("unable to write parameters to config file"));
909 static void write_refspec_config(const char *src_ref_prefix
,
910 const struct ref
*our_head_points_at
,
911 const struct ref
*remote_head_points_at
,
912 struct strbuf
*branch_top
)
914 struct strbuf key
= STRBUF_INIT
;
915 struct strbuf value
= STRBUF_INIT
;
917 if (option_mirror
|| !option_bare
) {
918 if (option_single_branch
&& !option_mirror
) {
920 if (starts_with(our_head_points_at
->name
, "refs/tags/"))
921 strbuf_addf(&value
, "+%s:%s", our_head_points_at
->name
,
922 our_head_points_at
->name
);
924 strbuf_addf(&value
, "+%s:%s%s", our_head_points_at
->name
,
925 branch_top
->buf
, option_branch
);
926 } else if (remote_head_points_at
) {
927 const char *head
= remote_head_points_at
->name
;
928 if (!skip_prefix(head
, "refs/heads/", &head
))
929 BUG("remote HEAD points at non-head?");
931 strbuf_addf(&value
, "+%s:%s%s", remote_head_points_at
->name
,
932 branch_top
->buf
, head
);
935 * otherwise, the next "git fetch" will
936 * simply fetch from HEAD without updating
937 * any remote-tracking branch, which is what
941 strbuf_addf(&value
, "+%s*:%s*", src_ref_prefix
, branch_top
->buf
);
943 /* Configure the remote */
945 strbuf_addf(&key
, "remote.%s.fetch", remote_name
);
946 git_config_set_multivar(key
.buf
, value
.buf
, "^$", 0);
950 strbuf_addf(&key
, "remote.%s.mirror", remote_name
);
951 git_config_set(key
.buf
, "true");
957 strbuf_release(&key
);
958 strbuf_release(&value
);
961 static void dissociate_from_references(void)
963 static const char* argv
[] = { "repack", "-a", "-d", NULL
};
964 char *alternates
= git_pathdup("objects/info/alternates");
966 if (!access(alternates
, F_OK
)) {
967 if (run_command_v_opt(argv
, RUN_GIT_CMD
|RUN_COMMAND_NO_STDIN
))
968 die(_("cannot repack to clean up"));
969 if (unlink(alternates
) && errno
!= ENOENT
)
970 die_errno(_("cannot unlink temporary alternates file"));
975 static int path_exists(const char *path
)
978 return !stat(path
, &sb
);
981 int cmd_clone(int argc
, const char **argv
, const char *prefix
)
983 int is_bundle
= 0, is_local
;
984 int reject_shallow
= 0;
985 const char *repo_name
, *repo
, *work_tree
, *git_dir
;
986 char *path
= NULL
, *dir
, *display_repo
= NULL
;
987 int dest_exists
, real_dest_exists
= 0;
988 const struct ref
*refs
, *remote_head
;
989 struct ref
*remote_head_points_at
= NULL
;
990 const struct ref
*our_head_points_at
;
991 struct ref
*mapped_refs
;
992 const struct ref
*ref
;
993 struct strbuf key
= STRBUF_INIT
;
994 struct strbuf branch_top
= STRBUF_INIT
, reflog_msg
= STRBUF_INIT
;
995 struct transport
*transport
= NULL
;
996 const char *src_ref_prefix
= "refs/heads/";
997 struct remote
*remote
;
998 int err
= 0, complete_refs_before_fetch
= 1;
999 int submodule_progress
;
1001 struct transport_ls_refs_options transport_ls_refs_options
=
1002 TRANSPORT_LS_REFS_OPTIONS_INIT
;
1004 packet_trace_identity("clone");
1006 git_config(git_clone_config
, NULL
);
1008 argc
= parse_options(argc
, argv
, prefix
, builtin_clone_options
,
1009 builtin_clone_usage
, 0);
1012 usage_msg_opt(_("Too many arguments."),
1013 builtin_clone_usage
, builtin_clone_options
);
1016 usage_msg_opt(_("You must specify a repository to clone."),
1017 builtin_clone_usage
, builtin_clone_options
);
1019 if (option_depth
|| option_since
|| option_not
.nr
)
1021 if (option_single_branch
== -1)
1022 option_single_branch
= deepen
? 1 : 0;
1029 die(_("--bare and --origin %s options are incompatible."),
1032 die(_("--bare and --separate-git-dir are incompatible."));
1033 option_no_checkout
= 1;
1036 repo_name
= argv
[0];
1038 path
= get_repo_path(repo_name
, &is_bundle
);
1040 FREE_AND_NULL(path
);
1041 repo
= absolute_pathdup(repo_name
);
1042 } else if (strchr(repo_name
, ':')) {
1044 display_repo
= transport_anonymize_url(repo
);
1046 die(_("repository '%s' does not exist"), repo_name
);
1048 /* no need to be strict, transport_set_option() will validate it again */
1049 if (option_depth
&& atoi(option_depth
) < 1)
1050 die(_("depth %s is not a positive number"), option_depth
);
1053 dir
= xstrdup(argv
[1]);
1055 dir
= guess_dir_name(repo_name
, is_bundle
, option_bare
);
1056 strip_trailing_slashes(dir
);
1058 dest_exists
= path_exists(dir
);
1059 if (dest_exists
&& !is_empty_dir(dir
))
1060 die(_("destination path '%s' already exists and is not "
1061 "an empty directory."), dir
);
1064 real_dest_exists
= path_exists(real_git_dir
);
1065 if (real_dest_exists
&& !is_empty_dir(real_git_dir
))
1066 die(_("repository path '%s' already exists and is not "
1067 "an empty directory."), real_git_dir
);
1071 strbuf_addf(&reflog_msg
, "clone: from %s",
1072 display_repo
? display_repo
: repo
);
1078 work_tree
= getenv("GIT_WORK_TREE");
1079 if (work_tree
&& path_exists(work_tree
))
1080 die(_("working tree '%s' already exists."), work_tree
);
1083 if (option_bare
|| work_tree
)
1084 git_dir
= xstrdup(dir
);
1087 git_dir
= mkpathdup("%s/.git", dir
);
1090 atexit(remove_junk
);
1091 sigchain_push_common(remove_junk_on_signal
);
1094 if (safe_create_leading_directories_const(work_tree
) < 0)
1095 die_errno(_("could not create leading directories of '%s'"),
1098 junk_work_tree_flags
|= REMOVE_DIR_KEEP_TOPLEVEL
;
1099 else if (mkdir(work_tree
, 0777))
1100 die_errno(_("could not create work tree dir '%s'"),
1102 junk_work_tree
= work_tree
;
1103 set_git_work_tree(work_tree
);
1107 if (real_dest_exists
)
1108 junk_git_dir_flags
|= REMOVE_DIR_KEEP_TOPLEVEL
;
1109 junk_git_dir
= real_git_dir
;
1112 junk_git_dir_flags
|= REMOVE_DIR_KEEP_TOPLEVEL
;
1113 junk_git_dir
= git_dir
;
1115 if (safe_create_leading_directories_const(git_dir
) < 0)
1116 die(_("could not create leading directories of '%s'"), git_dir
);
1118 if (0 <= option_verbosity
) {
1120 fprintf(stderr
, _("Cloning into bare repository '%s'...\n"), dir
);
1122 fprintf(stderr
, _("Cloning into '%s'...\n"), dir
);
1125 if (option_recurse_submodules
.nr
> 0) {
1126 struct string_list_item
*item
;
1127 struct strbuf sb
= STRBUF_INIT
;
1129 /* remove duplicates */
1130 string_list_sort(&option_recurse_submodules
);
1131 string_list_remove_duplicates(&option_recurse_submodules
, 0);
1134 * NEEDSWORK: In a multi-working-tree world, this needs to be
1135 * set in the per-worktree config.
1137 for_each_string_list_item(item
, &option_recurse_submodules
) {
1138 strbuf_addf(&sb
, "submodule.active=%s",
1140 string_list_append(&option_config
,
1141 strbuf_detach(&sb
, NULL
));
1144 if (option_required_reference
.nr
&&
1145 option_optional_reference
.nr
)
1146 die(_("clone --recursive is not compatible with "
1147 "both --reference and --reference-if-able"));
1148 else if (option_required_reference
.nr
) {
1149 string_list_append(&option_config
,
1150 "submodule.alternateLocation=superproject");
1151 string_list_append(&option_config
,
1152 "submodule.alternateErrorStrategy=die");
1153 } else if (option_optional_reference
.nr
) {
1154 string_list_append(&option_config
,
1155 "submodule.alternateLocation=superproject");
1156 string_list_append(&option_config
,
1157 "submodule.alternateErrorStrategy=info");
1161 init_db(git_dir
, real_git_dir
, option_template
, GIT_HASH_UNKNOWN
, NULL
,
1165 git_dir
= real_git_dir
;
1168 * additional config can be injected with -c, make sure it's included
1169 * after init_db, which clears the entire config environment.
1171 write_config(&option_config
);
1174 * re-read config after init_db and write_config to pick up any config
1175 * injected by --template and --config, respectively.
1177 git_config(git_clone_config
, NULL
);
1180 * If option_reject_shallow is specified from CLI option,
1181 * ignore config_reject_shallow from git_clone_config.
1183 if (config_reject_shallow
!= -1)
1184 reject_shallow
= config_reject_shallow
;
1185 if (option_reject_shallow
!= -1)
1186 reject_shallow
= option_reject_shallow
;
1189 * apply the remote name provided by --origin only after this second
1190 * call to git_config, to ensure it overrides all config-based values.
1192 if (option_origin
!= NULL
)
1193 remote_name
= xstrdup(option_origin
);
1195 if (remote_name
== NULL
)
1196 remote_name
= xstrdup("origin");
1198 if (!valid_remote_name(remote_name
))
1199 die(_("'%s' is not a valid remote name"), remote_name
);
1203 src_ref_prefix
= "refs/";
1204 strbuf_addstr(&branch_top
, src_ref_prefix
);
1206 git_config_set("core.bare", "true");
1208 strbuf_addf(&branch_top
, "refs/remotes/%s/", remote_name
);
1211 strbuf_addf(&key
, "remote.%s.url", remote_name
);
1212 git_config_set(key
.buf
, repo
);
1215 if (option_no_tags
) {
1216 strbuf_addf(&key
, "remote.%s.tagOpt", remote_name
);
1217 git_config_set(key
.buf
, "--no-tags");
1221 if (option_required_reference
.nr
|| option_optional_reference
.nr
)
1224 if (option_sparse_checkout
&& git_sparse_checkout_init(dir
))
1227 remote
= remote_get(remote_name
);
1229 refspec_appendf(&remote
->fetch
, "+%s*:%s*", src_ref_prefix
,
1232 path
= get_repo_path(remote
->url
[0], &is_bundle
);
1233 is_local
= option_local
!= 0 && path
&& !is_bundle
;
1236 warning(_("--depth is ignored in local clones; use file:// instead."));
1238 warning(_("--shallow-since is ignored in local clones; use file:// instead."));
1240 warning(_("--shallow-exclude is ignored in local clones; use file:// instead."));
1241 if (filter_options
.choice
)
1242 warning(_("--filter is ignored in local clones; use file:// instead."));
1243 if (!access(mkpath("%s/shallow", path
), F_OK
)) {
1245 die(_("source repository is shallow, reject to clone."));
1246 if (option_local
> 0)
1247 warning(_("source repository is shallow, ignoring --local"));
1251 if (option_local
> 0 && !is_local
)
1252 warning(_("--local is ignored"));
1254 transport
= transport_get(remote
, path
? path
: remote
->url
[0]);
1255 transport_set_verbosity(transport
, option_verbosity
, option_progress
);
1256 transport
->family
= family
;
1257 transport
->cloning
= 1;
1259 transport_set_option(transport
, TRANS_OPT_KEEP
, "yes");
1262 transport_set_option(transport
, TRANS_OPT_REJECT_SHALLOW
, "1");
1264 transport_set_option(transport
, TRANS_OPT_DEPTH
,
1267 transport_set_option(transport
, TRANS_OPT_DEEPEN_SINCE
,
1270 transport_set_option(transport
, TRANS_OPT_DEEPEN_NOT
,
1271 (const char *)&option_not
);
1272 if (option_single_branch
)
1273 transport_set_option(transport
, TRANS_OPT_FOLLOWTAGS
, "1");
1275 if (option_upload_pack
)
1276 transport_set_option(transport
, TRANS_OPT_UPLOADPACK
,
1277 option_upload_pack
);
1279 if (server_options
.nr
)
1280 transport
->server_options
= &server_options
;
1282 if (filter_options
.choice
) {
1284 expand_list_objects_filter_spec(&filter_options
);
1285 transport_set_option(transport
, TRANS_OPT_LIST_OBJECTS_FILTER
,
1287 transport_set_option(transport
, TRANS_OPT_FROM_PROMISOR
, "1");
1290 if (transport
->smart_options
&& !deepen
&& !filter_options
.choice
)
1291 transport
->smart_options
->check_self_contained_and_connected
= 1;
1294 strvec_push(&transport_ls_refs_options
.ref_prefixes
, "HEAD");
1295 refspec_ref_prefixes(&remote
->fetch
,
1296 &transport_ls_refs_options
.ref_prefixes
);
1298 expand_ref_prefix(&transport_ls_refs_options
.ref_prefixes
,
1300 if (!option_no_tags
)
1301 strvec_push(&transport_ls_refs_options
.ref_prefixes
,
1304 refs
= transport_get_remote_refs(transport
, &transport_ls_refs_options
);
1307 int hash_algo
= hash_algo_by_ptr(transport_get_hash_algo(transport
));
1310 * Now that we know what algorithm the remote side is using,
1311 * let's set ours to the same thing.
1313 initialize_repository_version(hash_algo
, 1);
1314 repo_set_hash_algo(the_repository
, hash_algo
);
1316 mapped_refs
= wanted_peer_refs(refs
, &remote
->fetch
);
1318 * transport_get_remote_refs() may return refs with null sha-1
1319 * in mapped_refs (see struct transport->get_refs_list
1320 * comment). In that case we need fetch it early because
1321 * remote_head code below relies on it.
1323 * for normal clones, transport_get_remote_refs() should
1324 * return reliable ref set, we can delay cloning until after
1325 * remote HEAD check.
1327 for (ref
= refs
; ref
; ref
= ref
->next
)
1328 if (is_null_oid(&ref
->old_oid
)) {
1329 complete_refs_before_fetch
= 0;
1333 if (!is_local
&& !complete_refs_before_fetch
) {
1334 err
= transport_fetch_refs(transport
, mapped_refs
);
1339 remote_head
= find_ref_by_name(refs
, "HEAD");
1340 remote_head_points_at
=
1341 guess_remote_head(remote_head
, mapped_refs
, 0);
1343 if (option_branch
) {
1344 our_head_points_at
=
1345 find_remote_branch(mapped_refs
, option_branch
);
1347 if (!our_head_points_at
)
1348 die(_("Remote branch %s not found in upstream %s"),
1349 option_branch
, remote_name
);
1352 our_head_points_at
= remote_head_points_at
;
1356 die(_("Remote branch %s not found in upstream %s"),
1357 option_branch
, remote_name
);
1359 warning(_("You appear to have cloned an empty repository."));
1361 our_head_points_at
= NULL
;
1362 remote_head_points_at
= NULL
;
1364 option_no_checkout
= 1;
1369 if (transport_ls_refs_options
.unborn_head_target
&&
1370 skip_prefix(transport_ls_refs_options
.unborn_head_target
,
1371 "refs/heads/", &branch
)) {
1372 ref
= transport_ls_refs_options
.unborn_head_target
;
1373 transport_ls_refs_options
.unborn_head_target
= NULL
;
1374 create_symref("HEAD", ref
, reflog_msg
.buf
);
1376 branch
= git_default_branch_name(0);
1377 ref
= xstrfmt("refs/heads/%s", branch
);
1380 install_branch_config(0, branch
, remote_name
, ref
);
1385 write_refspec_config(src_ref_prefix
, our_head_points_at
,
1386 remote_head_points_at
, &branch_top
);
1388 if (filter_options
.choice
)
1389 partial_clone_register(remote_name
, &filter_options
);
1392 clone_local(path
, git_dir
);
1393 else if (refs
&& complete_refs_before_fetch
) {
1394 err
= transport_fetch_refs(transport
, mapped_refs
);
1399 update_remote_refs(refs
, mapped_refs
, remote_head_points_at
,
1400 branch_top
.buf
, reflog_msg
.buf
, transport
,
1403 update_head(our_head_points_at
, remote_head
, reflog_msg
.buf
);
1406 * We want to show progress for recursive submodule clones iff
1407 * we did so for the main clone. But only the transport knows
1408 * the final decision for this flag, so we need to rescue the value
1409 * before we free the transport.
1411 submodule_progress
= transport
->progress
;
1413 transport_unlock_pack(transport
);
1414 transport_disconnect(transport
);
1416 if (option_dissociate
) {
1417 close_object_store(the_repository
->objects
);
1418 dissociate_from_references();
1421 junk_mode
= JUNK_LEAVE_REPO
;
1422 err
= checkout(submodule_progress
);
1426 strbuf_release(&reflog_msg
);
1427 strbuf_release(&branch_top
);
1428 strbuf_release(&key
);
1429 free_refs(mapped_refs
);
1430 free_refs(remote_head_points_at
);
1434 junk_mode
= JUNK_LEAVE_ALL
;
1436 strvec_clear(&transport_ls_refs_options
.ref_prefixes
);
1437 free(transport_ls_refs_options
.unborn_head_target
);