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.
16
#include "environment.h"
20
#include "parse-options.h"
23
#include "object-file.h"
24
#include "object-store-ll.h"
27
#include "unpack-trees.h"
31
#include "dir-iterator.h"
36
#include "run-command.h"
42
#include "list-objects-filter-options.h"
45
#include "bundle-uri.h"
49
* - respect DB_ENVIRONMENT for .git/objects.
51
* Implementation notes:
52
* - dropping use-separate-remote and no-separate-remote compatibility
55
static const char * const builtin_clone_usage[] = {
56
N_("git clone [<options>] [--] <repo> [<dir>]"),
60
static int option_no_checkout, option_bare, option_mirror, option_single_branch = -1;
61
static int option_local = -1, option_no_hardlinks, option_shared;
62
static int option_no_tags;
63
static int option_shallow_submodules;
64
static int option_reject_shallow = -1; /* unspecified */
65
static int config_reject_shallow = -1; /* unspecified */
67
static char *option_template, *option_depth, *option_since;
68
static char *option_origin = NULL;
69
static char *remote_name = NULL;
70
static char *option_branch = NULL;
71
static struct string_list option_not = STRING_LIST_INIT_NODUP;
72
static const char *real_git_dir;
73
static const char *ref_format;
74
static const char *option_upload_pack = "git-upload-pack";
75
static int option_verbosity;
76
static int option_progress = -1;
77
static int option_sparse_checkout;
78
static enum transport_family family;
79
static struct string_list option_config = STRING_LIST_INIT_NODUP;
80
static struct string_list option_required_reference = STRING_LIST_INIT_NODUP;
81
static struct string_list option_optional_reference = STRING_LIST_INIT_NODUP;
82
static int option_dissociate;
83
static int max_jobs = -1;
84
static struct string_list option_recurse_submodules = STRING_LIST_INIT_NODUP;
85
static struct list_objects_filter_options filter_options = LIST_OBJECTS_FILTER_INIT;
86
static int option_filter_submodules = -1; /* unspecified */
87
static int config_filter_submodules = -1; /* unspecified */
88
static struct string_list server_options = STRING_LIST_INIT_NODUP;
89
static int option_remote_submodules;
90
static const char *bundle_uri;
92
static int recurse_submodules_cb(const struct option *opt,
93
const char *arg, int unset)
96
string_list_clear((struct string_list *)opt->value, 0);
98
string_list_append((struct string_list *)opt->value, arg);
100
string_list_append((struct string_list *)opt->value,
101
(const char *)opt->defval);
106
static struct option builtin_clone_options[] = {
107
OPT__VERBOSITY(&option_verbosity),
108
OPT_BOOL(0, "progress", &option_progress,
109
N_("force progress reporting")),
110
OPT_BOOL(0, "reject-shallow", &option_reject_shallow,
111
N_("don't clone shallow repository")),
112
OPT_BOOL('n', "no-checkout", &option_no_checkout,
113
N_("don't create a checkout")),
114
OPT_BOOL(0, "bare", &option_bare, N_("create a bare repository")),
115
OPT_HIDDEN_BOOL(0, "naked", &option_bare,
116
N_("create a bare repository")),
117
OPT_BOOL(0, "mirror", &option_mirror,
118
N_("create a mirror repository (implies --bare)")),
119
OPT_BOOL('l', "local", &option_local,
120
N_("to clone from a local repository")),
121
OPT_BOOL(0, "no-hardlinks", &option_no_hardlinks,
122
N_("don't use local hardlinks, always copy")),
123
OPT_BOOL('s', "shared", &option_shared,
124
N_("setup as shared repository")),
125
{ OPTION_CALLBACK, 0, "recurse-submodules", &option_recurse_submodules,
126
N_("pathspec"), N_("initialize submodules in the clone"),
127
PARSE_OPT_OPTARG, recurse_submodules_cb, (intptr_t)"." },
128
OPT_ALIAS(0, "recursive", "recurse-submodules"),
129
OPT_INTEGER('j', "jobs", &max_jobs,
130
N_("number of submodules cloned in parallel")),
131
OPT_STRING(0, "template", &option_template, N_("template-directory"),
132
N_("directory from which templates will be used")),
133
OPT_STRING_LIST(0, "reference", &option_required_reference, N_("repo"),
134
N_("reference repository")),
135
OPT_STRING_LIST(0, "reference-if-able", &option_optional_reference,
136
N_("repo"), N_("reference repository")),
137
OPT_BOOL(0, "dissociate", &option_dissociate,
138
N_("use --reference only while cloning")),
139
OPT_STRING('o', "origin", &option_origin, N_("name"),
140
N_("use <name> instead of 'origin' to track upstream")),
141
OPT_STRING('b', "branch", &option_branch, N_("branch"),
142
N_("checkout <branch> instead of the remote's HEAD")),
143
OPT_STRING('u', "upload-pack", &option_upload_pack, N_("path"),
144
N_("path to git-upload-pack on the remote")),
145
OPT_STRING(0, "depth", &option_depth, N_("depth"),
146
N_("create a shallow clone of that depth")),
147
OPT_STRING(0, "shallow-since", &option_since, N_("time"),
148
N_("create a shallow clone since a specific time")),
149
OPT_STRING_LIST(0, "shallow-exclude", &option_not, N_("revision"),
150
N_("deepen history of shallow clone, excluding rev")),
151
OPT_BOOL(0, "single-branch", &option_single_branch,
152
N_("clone only one branch, HEAD or --branch")),
153
OPT_BOOL(0, "no-tags", &option_no_tags,
154
N_("don't clone any tags, and make later fetches not to follow them")),
155
OPT_BOOL(0, "shallow-submodules", &option_shallow_submodules,
156
N_("any cloned submodules will be shallow")),
157
OPT_STRING(0, "separate-git-dir", &real_git_dir, N_("gitdir"),
158
N_("separate git dir from working tree")),
159
OPT_STRING(0, "ref-format", &ref_format, N_("format"),
160
N_("specify the reference format to use")),
161
OPT_STRING_LIST('c', "config", &option_config, N_("key=value"),
162
N_("set config inside the new repository")),
163
OPT_STRING_LIST(0, "server-option", &server_options,
164
N_("server-specific"), N_("option to transmit")),
165
OPT_IPVERSION(&family),
166
OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
167
OPT_BOOL(0, "also-filter-submodules", &option_filter_submodules,
168
N_("apply partial clone filters to submodules")),
169
OPT_BOOL(0, "remote-submodules", &option_remote_submodules,
170
N_("any cloned submodules will use their remote-tracking branch")),
171
OPT_BOOL(0, "sparse", &option_sparse_checkout,
172
N_("initialize sparse-checkout file to include only files at root")),
173
OPT_STRING(0, "bundle-uri", &bundle_uri,
174
N_("uri"), N_("a URI for downloading bundles before fetching from origin remote")),
178
static const char *get_repo_path_1(struct strbuf *path, int *is_bundle)
180
static const char *suffix[] = { "/.git", "", ".git/.git", ".git" };
181
static const char *bundle_suffix[] = { ".bundle", "" };
182
size_t baselen = path->len;
186
for (i = 0; i < ARRAY_SIZE(suffix); i++) {
187
strbuf_setlen(path, baselen);
188
strbuf_addstr(path, suffix[i]);
189
if (stat(path->buf, &st))
191
if (S_ISDIR(st.st_mode) && is_git_directory(path->buf)) {
194
} else if (S_ISREG(st.st_mode) && st.st_size > 8) {
195
/* Is it a "gitfile"? */
198
int len, fd = open(path->buf, O_RDONLY);
201
len = read_in_full(fd, signature, 8);
203
if (len != 8 || strncmp(signature, "gitdir: ", 8))
205
dst = read_gitfile(path->buf);
213
for (i = 0; i < ARRAY_SIZE(bundle_suffix); i++) {
214
strbuf_setlen(path, baselen);
215
strbuf_addstr(path, bundle_suffix[i]);
216
if (!stat(path->buf, &st) && S_ISREG(st.st_mode)) {
225
static char *get_repo_path(const char *repo, int *is_bundle)
227
struct strbuf path = STRBUF_INIT;
231
strbuf_addstr(&path, repo);
232
raw = get_repo_path_1(&path, is_bundle);
233
canon = raw ? absolute_pathdup(raw) : NULL;
234
strbuf_release(&path);
238
static int add_one_reference(struct string_list_item *item, void *cb_data)
240
struct strbuf err = STRBUF_INIT;
241
int *required = cb_data;
242
char *ref_git = compute_alternate_path(item->string, &err);
249
_("info: Could not add alternate for '%s': %s\n"),
250
item->string, err.buf);
252
struct strbuf sb = STRBUF_INIT;
253
strbuf_addf(&sb, "%s/objects", ref_git);
254
add_to_alternates_file(sb.buf);
258
strbuf_release(&err);
263
static void setup_reference(void)
266
for_each_string_list(&option_required_reference,
267
add_one_reference, &required);
269
for_each_string_list(&option_optional_reference,
270
add_one_reference, &required);
273
static void copy_alternates(struct strbuf *src, const char *src_repo)
276
* Read from the source objects/info/alternates file
277
* and copy the entries to corresponding file in the
278
* destination repository with add_to_alternates_file().
279
* Both src and dst have "$path/objects/info/alternates".
281
* Instead of copying bit-for-bit from the original,
282
* we need to append to existing one so that the already
283
* created entry via "clone -s" is not lost, and also
284
* to turn entries with paths relative to the original
285
* absolute, so that they can be used in the new repository.
287
FILE *in = xfopen(src->buf, "r");
288
struct strbuf line = STRBUF_INIT;
290
while (strbuf_getline(&line, in) != EOF) {
292
if (!line.len || line.buf[0] == '#')
294
if (is_absolute_path(line.buf)) {
295
add_to_alternates_file(line.buf);
298
abs_path = mkpathdup("%s/objects/%s", src_repo, line.buf);
299
if (!normalize_path_copy(abs_path, abs_path))
300
add_to_alternates_file(abs_path);
302
warning("skipping invalid relative alternate: %s/%s",
306
strbuf_release(&line);
310
static void mkdir_if_missing(const char *pathname, mode_t mode)
314
if (!mkdir(pathname, mode))
318
die_errno(_("failed to create directory '%s'"), pathname);
319
else if (stat(pathname, &st))
320
die_errno(_("failed to stat '%s'"), pathname);
321
else if (!S_ISDIR(st.st_mode))
322
die(_("%s exists and is not a directory"), pathname);
325
static void copy_or_link_directory(struct strbuf *src, struct strbuf *dest,
326
const char *src_repo)
328
int src_len, dest_len;
329
struct dir_iterator *iter;
333
* Refuse copying directories by default which aren't owned by us. The
334
* code that performs either the copying or hardlinking is not prepared
335
* to handle various edge cases where an adversary may for example
336
* racily swap out files for symlinks. This can cause us to
337
* inadvertently use the wrong source file.
339
* Furthermore, even if we were prepared to handle such races safely,
340
* creating hardlinks across user boundaries is an inherently unsafe
341
* operation as the hardlinked files can be rewritten at will by the
342
* potentially-untrusted user. We thus refuse to do so by default.
344
die_upon_dubious_ownership(NULL, NULL, src_repo);
346
mkdir_if_missing(dest->buf, 0777);
348
iter = dir_iterator_begin(src->buf, DIR_ITERATOR_PEDANTIC);
351
if (errno == ENOTDIR) {
352
int saved_errno = errno;
355
if (!lstat(src->buf, &st) && S_ISLNK(st.st_mode))
356
die(_("'%s' is a symlink, refusing to clone with --local"),
360
die_errno(_("failed to start iterator over '%s'"), src->buf);
363
strbuf_addch(src, '/');
365
strbuf_addch(dest, '/');
366
dest_len = dest->len;
368
while ((iter_status = dir_iterator_advance(iter)) == ITER_OK) {
369
strbuf_setlen(src, src_len);
370
strbuf_addstr(src, iter->relative_path);
371
strbuf_setlen(dest, dest_len);
372
strbuf_addstr(dest, iter->relative_path);
374
if (S_ISLNK(iter->st.st_mode))
375
die(_("symlink '%s' exists, refusing to clone with --local"),
376
iter->relative_path);
378
if (S_ISDIR(iter->st.st_mode)) {
379
mkdir_if_missing(dest->buf, 0777);
383
/* Files that cannot be copied bit-for-bit... */
384
if (!fspathcmp(iter->relative_path, "info/alternates")) {
385
copy_alternates(src, src_repo);
389
if (unlink(dest->buf) && errno != ENOENT)
390
die_errno(_("failed to unlink '%s'"), dest->buf);
391
if (!option_no_hardlinks) {
392
if (!link(src->buf, dest->buf)) {
396
* Sanity-check whether the created hardlink
397
* actually links to the expected file now. This
398
* catches time-of-check-time-of-use bugs in
399
* case the source file was meanwhile swapped.
401
if (lstat(dest->buf, &st))
402
die(_("hardlink cannot be checked at '%s'"), dest->buf);
403
if (st.st_mode != iter->st.st_mode ||
404
st.st_ino != iter->st.st_ino ||
405
st.st_dev != iter->st.st_dev ||
406
st.st_size != iter->st.st_size ||
407
st.st_uid != iter->st.st_uid ||
408
st.st_gid != iter->st.st_gid)
409
die(_("hardlink different from source at '%s'"), dest->buf);
413
if (option_local > 0)
414
die_errno(_("failed to create link '%s'"), dest->buf);
415
option_no_hardlinks = 1;
417
if (copy_file_with_time(dest->buf, src->buf, 0666))
418
die_errno(_("failed to copy file to '%s'"), dest->buf);
421
if (iter_status != ITER_DONE) {
422
strbuf_setlen(src, src_len);
423
die(_("failed to iterate over '%s'"), src->buf);
427
static void clone_local(const char *src_repo, const char *dest_repo)
430
struct strbuf alt = STRBUF_INIT;
431
get_common_dir(&alt, src_repo);
432
strbuf_addstr(&alt, "/objects");
433
add_to_alternates_file(alt.buf);
434
strbuf_release(&alt);
436
struct strbuf src = STRBUF_INIT;
437
struct strbuf dest = STRBUF_INIT;
438
get_common_dir(&src, src_repo);
439
get_common_dir(&dest, dest_repo);
440
strbuf_addstr(&src, "/objects");
441
strbuf_addstr(&dest, "/objects");
442
copy_or_link_directory(&src, &dest, src_repo);
443
strbuf_release(&src);
444
strbuf_release(&dest);
447
if (0 <= option_verbosity)
448
fprintf(stderr, _("done.\n"));
451
static const char *junk_work_tree;
452
static int junk_work_tree_flags;
453
static const char *junk_git_dir;
454
static int junk_git_dir_flags;
459
} junk_mode = JUNK_LEAVE_NONE;
461
static const char junk_leave_repo_msg[] =
462
N_("Clone succeeded, but checkout failed.\n"
463
"You can inspect what was checked out with 'git status'\n"
464
"and retry with 'git restore --source=HEAD :/'\n");
466
static void remove_junk(void)
468
struct strbuf sb = STRBUF_INIT;
471
case JUNK_LEAVE_REPO:
472
warning("%s", _(junk_leave_repo_msg));
477
/* proceed to removal */
482
strbuf_addstr(&sb, junk_git_dir);
483
remove_dir_recursively(&sb, junk_git_dir_flags);
486
if (junk_work_tree) {
487
strbuf_addstr(&sb, junk_work_tree);
488
remove_dir_recursively(&sb, junk_work_tree_flags);
493
static void remove_junk_on_signal(int signo)
500
static struct ref *find_remote_branch(const struct ref *refs, const char *branch)
503
struct strbuf head = STRBUF_INIT;
504
strbuf_addstr(&head, "refs/heads/");
505
strbuf_addstr(&head, branch);
506
ref = find_ref_by_name(refs, head.buf);
507
strbuf_release(&head);
512
strbuf_addstr(&head, "refs/tags/");
513
strbuf_addstr(&head, branch);
514
ref = find_ref_by_name(refs, head.buf);
515
strbuf_release(&head);
520
static struct ref *wanted_peer_refs(const struct ref *refs,
521
struct refspec *refspec)
523
struct ref *head = copy_ref(find_ref_by_name(refs, "HEAD"));
524
struct ref *local_refs = head;
525
struct ref **tail = head ? &head->next : &local_refs;
526
struct refspec_item tag_refspec;
528
refspec_item_init(&tag_refspec, TAG_REFSPEC, 0);
530
if (option_single_branch) {
531
struct ref *remote_head = NULL;
534
remote_head = guess_remote_head(head, refs, 0);
537
local_refs = head = NULL;
539
remote_head = copy_ref(find_remote_branch(refs, option_branch));
542
if (!remote_head && option_branch)
543
warning(_("Could not find remote branch %s to clone."),
547
for (i = 0; i < refspec->nr; i++)
548
get_fetch_map(remote_head, &refspec->items[i],
551
/* if --branch=tag, pull the requested tag explicitly */
552
get_fetch_map(remote_head, &tag_refspec, &tail, 0);
554
free_refs(remote_head);
557
for (i = 0; i < refspec->nr; i++)
558
get_fetch_map(refs, &refspec->items[i], &tail, 0);
561
if (!option_mirror && !option_single_branch && !option_no_tags)
562
get_fetch_map(refs, &tag_refspec, &tail, 0);
564
refspec_item_clear(&tag_refspec);
568
static void write_remote_refs(const struct ref *local_refs)
572
struct ref_transaction *t;
573
struct strbuf err = STRBUF_INIT;
575
t = ref_store_transaction_begin(get_main_ref_store(the_repository),
580
for (r = local_refs; r; r = r->next) {
583
if (ref_transaction_create(t, r->peer_ref->name, &r->old_oid,
584
NULL, 0, NULL, &err))
588
if (initial_ref_transaction_commit(t, &err))
591
strbuf_release(&err);
592
ref_transaction_free(t);
595
static void write_followtags(const struct ref *refs, const char *msg)
597
const struct ref *ref;
598
for (ref = refs; ref; ref = ref->next) {
599
if (!starts_with(ref->name, "refs/tags/"))
601
if (ends_with(ref->name, "^{}"))
603
if (!repo_has_object_file_with_flags(the_repository, &ref->old_oid,
605
OBJECT_INFO_SKIP_FETCH_OBJECT))
607
refs_update_ref(get_main_ref_store(the_repository), msg,
608
ref->name, &ref->old_oid, NULL, 0,
609
UPDATE_REFS_DIE_ON_ERR);
613
static const struct object_id *iterate_ref_map(void *cb_data)
615
struct ref **rm = cb_data;
616
struct ref *ref = *rm;
619
* Skip anything missing a peer_ref, which we are not
620
* actually going to write a ref for.
622
while (ref && !ref->peer_ref)
628
return &ref->old_oid;
631
static void update_remote_refs(const struct ref *refs,
632
const struct ref *mapped_refs,
633
const struct ref *remote_head_points_at,
634
const char *branch_top,
636
struct transport *transport,
637
int check_connectivity)
639
const struct ref *rm = mapped_refs;
641
if (check_connectivity) {
642
struct check_connected_options opt = CHECK_CONNECTED_INIT;
644
opt.transport = transport;
645
opt.progress = transport->progress;
647
if (check_connected(iterate_ref_map, &rm, &opt))
648
die(_("remote did not send all necessary objects"));
652
write_remote_refs(mapped_refs);
653
if (option_single_branch && !option_no_tags)
654
write_followtags(refs, msg);
657
if (remote_head_points_at && !option_bare) {
658
struct strbuf head_ref = STRBUF_INIT;
659
strbuf_addstr(&head_ref, branch_top);
660
strbuf_addstr(&head_ref, "HEAD");
661
if (refs_update_symref(get_main_ref_store(the_repository), head_ref.buf,
662
remote_head_points_at->peer_ref->name,
664
die(_("unable to update %s"), head_ref.buf);
665
strbuf_release(&head_ref);
669
static void update_head(const struct ref *our, const struct ref *remote,
670
const char *unborn, const char *msg)
673
if (our && skip_prefix(our->name, "refs/heads/", &head)) {
674
/* Local default branch link */
675
if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", our->name, NULL) < 0)
676
die(_("unable to update HEAD"));
678
refs_update_ref(get_main_ref_store(the_repository),
679
msg, "HEAD", &our->old_oid, NULL, 0,
680
UPDATE_REFS_DIE_ON_ERR);
681
install_branch_config(0, head, remote_name, our->name);
684
struct commit *c = lookup_commit_reference(the_repository,
686
/* --branch specifies a non-branch (i.e. tags), detach HEAD */
687
refs_update_ref(get_main_ref_store(the_repository), msg,
688
"HEAD", &c->object.oid, NULL, REF_NO_DEREF,
689
UPDATE_REFS_DIE_ON_ERR);
692
* We know remote HEAD points to a non-branch, or
693
* HEAD points to a branch but we don't know which one.
694
* Detach HEAD in all these cases.
696
refs_update_ref(get_main_ref_store(the_repository), msg,
697
"HEAD", &remote->old_oid, NULL, REF_NO_DEREF,
698
UPDATE_REFS_DIE_ON_ERR);
699
} else if (unborn && skip_prefix(unborn, "refs/heads/", &head)) {
701
* Unborn head from remote; same as "our" case above except
702
* that we have no ref to update.
704
if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", unborn, NULL) < 0)
705
die(_("unable to update HEAD"));
707
install_branch_config(0, head, remote_name, unborn);
711
static int git_sparse_checkout_init(const char *repo)
713
struct child_process cmd = CHILD_PROCESS_INIT;
715
strvec_pushl(&cmd.args, "-C", repo, "sparse-checkout", "set", NULL);
718
* We must apply the setting in the current process
719
* for the later checkout to use the sparse-checkout file.
721
core_apply_sparse_checkout = 1;
724
if (run_command(&cmd)) {
725
error(_("failed to initialize sparse-checkout"));
732
static int checkout(int submodule_progress, int filter_submodules,
733
enum ref_storage_format ref_storage_format)
735
struct object_id oid;
737
struct lock_file lock_file = LOCK_INIT;
738
struct unpack_trees_options opts;
743
if (option_no_checkout)
746
head = refs_resolve_refdup(get_main_ref_store(the_repository), "HEAD",
747
RESOLVE_REF_READING, &oid, NULL);
749
warning(_("remote HEAD refers to nonexistent ref, "
750
"unable to checkout"));
753
if (!strcmp(head, "HEAD")) {
754
if (advice_enabled(ADVICE_DETACHED_HEAD))
755
detach_advice(oid_to_hex(&oid));
758
if (!starts_with(head, "refs/heads/"))
759
die(_("HEAD not found below refs/heads!"));
762
/* We need to be in the new work tree for the checkout */
765
repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
767
memset(&opts, 0, sizeof opts);
771
opts.preserve_ignored = 0;
772
opts.fn = oneway_merge;
773
opts.verbose_update = (option_verbosity >= 0);
774
opts.src_index = the_repository->index;
775
opts.dst_index = the_repository->index;
776
init_checkout_metadata(&opts.meta, head, &oid, NULL);
778
tree = parse_tree_indirect(&oid);
780
die(_("unable to parse commit %s"), oid_to_hex(&oid));
781
if (parse_tree(tree) < 0)
783
init_tree_desc(&t, &tree->object.oid, tree->buffer, tree->size);
784
if (unpack_trees(1, &t, &opts) < 0)
785
die(_("unable to checkout working tree"));
789
if (write_locked_index(the_repository->index, &lock_file, COMMIT_LOCK))
790
die(_("unable to write new index file"));
792
err |= run_hooks_l(the_repository, "post-checkout", oid_to_hex(null_oid()),
793
oid_to_hex(&oid), "1", NULL);
795
if (!err && (option_recurse_submodules.nr > 0)) {
796
struct child_process cmd = CHILD_PROCESS_INIT;
797
strvec_pushl(&cmd.args, "submodule", "update", "--require-init",
798
"--recursive", NULL);
800
if (option_shallow_submodules == 1)
801
strvec_push(&cmd.args, "--depth=1");
804
strvec_pushf(&cmd.args, "--jobs=%d", max_jobs);
806
if (submodule_progress)
807
strvec_push(&cmd.args, "--progress");
809
if (option_verbosity < 0)
810
strvec_push(&cmd.args, "--quiet");
812
if (option_remote_submodules) {
813
strvec_push(&cmd.args, "--remote");
814
strvec_push(&cmd.args, "--no-fetch");
817
if (ref_storage_format != REF_STORAGE_FORMAT_UNKNOWN)
818
strvec_pushf(&cmd.args, "--ref-format=%s",
819
ref_storage_format_to_name(ref_storage_format));
821
if (filter_submodules && filter_options.choice)
822
strvec_pushf(&cmd.args, "--filter=%s",
823
expand_list_objects_filter_spec(&filter_options));
825
if (option_single_branch >= 0)
826
strvec_push(&cmd.args, option_single_branch ?
828
"--no-single-branch");
831
err = run_command(&cmd);
837
static int git_clone_config(const char *k, const char *v,
838
const struct config_context *ctx, void *cb)
840
if (!strcmp(k, "clone.defaultremotename")) {
842
return config_error_nonbool(k);
844
remote_name = xstrdup(v);
846
if (!strcmp(k, "clone.rejectshallow"))
847
config_reject_shallow = git_config_bool(k, v);
848
if (!strcmp(k, "clone.filtersubmodules"))
849
config_filter_submodules = git_config_bool(k, v);
851
return git_default_config(k, v, ctx, cb);
854
static int write_one_config(const char *key, const char *value,
855
const struct config_context *ctx,
859
* give git_clone_config a chance to write config values back to the
860
* environment, since git_config_set_multivar_gently only deals with
863
int apply_failed = git_clone_config(key, value, ctx, data);
867
return git_config_set_multivar_gently(key,
868
value ? value : "true",
869
CONFIG_REGEX_NONE, 0);
872
static void write_config(struct string_list *config)
876
for (i = 0; i < config->nr; i++) {
877
if (git_config_parse_parameter(config->items[i].string,
878
write_one_config, NULL) < 0)
879
die(_("unable to write parameters to config file"));
883
static void write_refspec_config(const char *src_ref_prefix,
884
const struct ref *our_head_points_at,
885
const struct ref *remote_head_points_at,
886
struct strbuf *branch_top)
888
struct strbuf key = STRBUF_INIT;
889
struct strbuf value = STRBUF_INIT;
891
if (option_mirror || !option_bare) {
892
if (option_single_branch && !option_mirror) {
894
if (starts_with(our_head_points_at->name, "refs/tags/"))
895
strbuf_addf(&value, "+%s:%s", our_head_points_at->name,
896
our_head_points_at->name);
898
strbuf_addf(&value, "+%s:%s%s", our_head_points_at->name,
899
branch_top->buf, option_branch);
900
} else if (remote_head_points_at) {
901
const char *head = remote_head_points_at->name;
902
if (!skip_prefix(head, "refs/heads/", &head))
903
BUG("remote HEAD points at non-head?");
905
strbuf_addf(&value, "+%s:%s%s", remote_head_points_at->name,
906
branch_top->buf, head);
909
* otherwise, the next "git fetch" will
910
* simply fetch from HEAD without updating
911
* any remote-tracking branch, which is what
915
strbuf_addf(&value, "+%s*:%s*", src_ref_prefix, branch_top->buf);
917
/* Configure the remote */
919
strbuf_addf(&key, "remote.%s.fetch", remote_name);
920
git_config_set_multivar(key.buf, value.buf, "^$", 0);
924
strbuf_addf(&key, "remote.%s.mirror", remote_name);
925
git_config_set(key.buf, "true");
931
strbuf_release(&key);
932
strbuf_release(&value);
935
static void dissociate_from_references(void)
937
char *alternates = git_pathdup("objects/info/alternates");
939
if (!access(alternates, F_OK)) {
940
struct child_process cmd = CHILD_PROCESS_INIT;
944
strvec_pushl(&cmd.args, "repack", "-a", "-d", NULL);
945
if (run_command(&cmd))
946
die(_("cannot repack to clean up"));
947
if (unlink(alternates) && errno != ENOENT)
948
die_errno(_("cannot unlink temporary alternates file"));
953
static int path_exists(const char *path)
956
return !stat(path, &sb);
959
int cmd_clone(int argc, const char **argv, const char *prefix)
961
int is_bundle = 0, is_local;
962
int reject_shallow = 0;
963
const char *repo_name, *repo, *work_tree, *git_dir;
964
char *repo_to_free = NULL;
965
char *path = NULL, *dir, *display_repo = NULL;
966
int dest_exists, real_dest_exists = 0;
967
const struct ref *refs, *remote_head;
968
struct ref *remote_head_points_at = NULL;
969
const struct ref *our_head_points_at;
970
char *unborn_head = NULL;
971
struct ref *mapped_refs = NULL;
972
const struct ref *ref;
973
struct strbuf key = STRBUF_INIT;
974
struct strbuf buf = STRBUF_INIT;
975
struct strbuf branch_top = STRBUF_INIT, reflog_msg = STRBUF_INIT;
976
struct transport *transport = NULL;
977
const char *src_ref_prefix = "refs/heads/";
978
struct remote *remote;
979
int err = 0, complete_refs_before_fetch = 1;
980
int submodule_progress;
981
int filter_submodules = 0;
983
enum ref_storage_format ref_storage_format = REF_STORAGE_FORMAT_UNKNOWN;
984
const int do_not_override_repo_unix_permissions = -1;
986
struct transport_ls_refs_options transport_ls_refs_options =
987
TRANSPORT_LS_REFS_OPTIONS_INIT;
989
packet_trace_identity("clone");
991
git_config(git_clone_config, NULL);
993
argc = parse_options(argc, argv, prefix, builtin_clone_options,
994
builtin_clone_usage, 0);
997
usage_msg_opt(_("Too many arguments."),
998
builtin_clone_usage, builtin_clone_options);
1001
usage_msg_opt(_("You must specify a repository to clone."),
1002
builtin_clone_usage, builtin_clone_options);
1004
if (option_depth || option_since || option_not.nr)
1006
if (option_single_branch == -1)
1007
option_single_branch = deepen ? 1 : 0;
1010
ref_storage_format = ref_storage_format_by_name(ref_format);
1011
if (ref_storage_format == REF_STORAGE_FORMAT_UNKNOWN)
1012
die(_("unknown ref storage format '%s'"), ref_format);
1020
die(_("options '%s' and '%s' cannot be used together"), "--bare", "--separate-git-dir");
1021
option_no_checkout = 1;
1024
if (bundle_uri && deepen)
1025
die(_("options '%s' and '%s' cannot be used together"),
1027
"--depth/--shallow-since/--shallow-exclude");
1029
repo_name = argv[0];
1031
path = get_repo_path(repo_name, &is_bundle);
1033
FREE_AND_NULL(path);
1034
repo = repo_to_free = absolute_pathdup(repo_name);
1035
} else if (strchr(repo_name, ':')) {
1037
display_repo = transport_anonymize_url(repo);
1039
die(_("repository '%s' does not exist"), repo_name);
1041
/* no need to be strict, transport_set_option() will validate it again */
1042
if (option_depth && atoi(option_depth) < 1)
1043
die(_("depth %s is not a positive number"), option_depth);
1046
dir = xstrdup(argv[1]);
1048
dir = git_url_basename(repo_name, is_bundle, option_bare);
1049
strip_dir_trailing_slashes(dir);
1051
dest_exists = path_exists(dir);
1052
if (dest_exists && !is_empty_dir(dir))
1053
die(_("destination path '%s' already exists and is not "
1054
"an empty directory."), dir);
1057
real_dest_exists = path_exists(real_git_dir);
1058
if (real_dest_exists && !is_empty_dir(real_git_dir))
1059
die(_("repository path '%s' already exists and is not "
1060
"an empty directory."), real_git_dir);
1064
strbuf_addf(&reflog_msg, "clone: from %s",
1065
display_repo ? display_repo : repo);
1071
work_tree = getenv("GIT_WORK_TREE");
1072
if (work_tree && path_exists(work_tree))
1073
die(_("working tree '%s' already exists."), work_tree);
1076
if (option_bare || work_tree)
1077
git_dir = xstrdup(dir);
1080
git_dir = mkpathdup("%s/.git", dir);
1083
atexit(remove_junk);
1084
sigchain_push_common(remove_junk_on_signal);
1087
if (safe_create_leading_directories_const(work_tree) < 0)
1088
die_errno(_("could not create leading directories of '%s'"),
1091
junk_work_tree_flags |= REMOVE_DIR_KEEP_TOPLEVEL;
1092
else if (mkdir(work_tree, 0777))
1093
die_errno(_("could not create work tree dir '%s'"),
1095
junk_work_tree = work_tree;
1096
set_git_work_tree(work_tree);
1100
if (real_dest_exists)
1101
junk_git_dir_flags |= REMOVE_DIR_KEEP_TOPLEVEL;
1102
junk_git_dir = real_git_dir;
1105
junk_git_dir_flags |= REMOVE_DIR_KEEP_TOPLEVEL;
1106
junk_git_dir = git_dir;
1108
if (safe_create_leading_directories_const(git_dir) < 0)
1109
die(_("could not create leading directories of '%s'"), git_dir);
1111
if (0 <= option_verbosity) {
1113
fprintf(stderr, _("Cloning into bare repository '%s'...\n"), dir);
1115
fprintf(stderr, _("Cloning into '%s'...\n"), dir);
1118
if (option_recurse_submodules.nr > 0) {
1119
struct string_list_item *item;
1120
struct strbuf sb = STRBUF_INIT;
1123
/* remove duplicates */
1124
string_list_sort(&option_recurse_submodules);
1125
string_list_remove_duplicates(&option_recurse_submodules, 0);
1128
* NEEDSWORK: In a multi-working-tree world, this needs to be
1129
* set in the per-worktree config.
1131
for_each_string_list_item(item, &option_recurse_submodules) {
1132
strbuf_addf(&sb, "submodule.active=%s",
1134
string_list_append(&option_config,
1135
strbuf_detach(&sb, NULL));
1138
if (!git_config_get_bool("submodule.stickyRecursiveClone", &val) &&
1140
string_list_append(&option_config, "submodule.recurse=true");
1142
if (option_required_reference.nr &&
1143
option_optional_reference.nr)
1144
die(_("clone --recursive is not compatible with "
1145
"both --reference and --reference-if-able"));
1146
else if (option_required_reference.nr) {
1147
string_list_append(&option_config,
1148
"submodule.alternateLocation=superproject");
1149
string_list_append(&option_config,
1150
"submodule.alternateErrorStrategy=die");
1151
} else if (option_optional_reference.nr) {
1152
string_list_append(&option_config,
1153
"submodule.alternateLocation=superproject");
1154
string_list_append(&option_config,
1155
"submodule.alternateErrorStrategy=info");
1160
* Initialize the repository, but skip initializing the reference
1161
* database. We do not yet know about the object format of the
1162
* repository, and reference backends may persist that information into
1163
* their on-disk data structures.
1165
init_db(git_dir, real_git_dir, option_template, GIT_HASH_UNKNOWN,
1166
ref_storage_format, NULL,
1167
do_not_override_repo_unix_permissions, INIT_DB_QUIET | INIT_DB_SKIP_REFDB);
1170
free((char *)git_dir);
1171
git_dir = real_git_dir;
1175
* We have a chicken-and-egg situation between initializing the refdb
1176
* and spawning transport helpers:
1178
* - Initializing the refdb requires us to know about the object
1179
* format. We thus have to spawn the transport helper to learn
1182
* - The transport helper may want to access the Git repository. But
1183
* because the refdb has not been initialized, we don't have "HEAD"
1184
* or "refs/". Thus, the helper cannot find the Git repository.
1186
* Ideally, we would have structured the helper protocol such that it's
1187
* mandatory for the helper to first announce its capabilities without
1188
* yet assuming a fully initialized repository. Like that, we could
1189
* have added a "lazy-refdb-init" capability that announces whether the
1190
* helper is ready to handle not-yet-initialized refdbs. If any helper
1191
* didn't support them, we would have fully initialized the refdb with
1192
* the SHA1 object format, but later on bailed out if we found out that
1193
* the remote repository used a different object format.
1195
* But we didn't, and thus we use the following workaround to partially
1196
* initialize the repository's refdb such that it can be discovered by
1197
* Git commands. To do so, we:
1199
* - Create an invalid HEAD ref pointing at "refs/heads/.invalid".
1201
* - Create the "refs/" directory.
1203
* - Set up the ref storage format and repository version as
1206
* This is sufficient for Git commands to discover the Git directory.
1208
initialize_repository_version(GIT_HASH_UNKNOWN,
1209
the_repository->ref_storage_format, 1);
1211
strbuf_addf(&buf, "%s/HEAD", git_dir);
1212
write_file(buf.buf, "ref: refs/heads/.invalid");
1215
strbuf_addf(&buf, "%s/refs", git_dir);
1216
safe_create_dir(buf.buf, 1);
1219
* additional config can be injected with -c, make sure it's included
1220
* after init_db, which clears the entire config environment.
1222
write_config(&option_config);
1225
* re-read config after init_db and write_config to pick up any config
1226
* injected by --template and --config, respectively.
1228
git_config(git_clone_config, NULL);
1231
* If option_reject_shallow is specified from CLI option,
1232
* ignore config_reject_shallow from git_clone_config.
1234
if (config_reject_shallow != -1)
1235
reject_shallow = config_reject_shallow;
1236
if (option_reject_shallow != -1)
1237
reject_shallow = option_reject_shallow;
1240
* If option_filter_submodules is specified from CLI option,
1241
* ignore config_filter_submodules from git_clone_config.
1243
if (config_filter_submodules != -1)
1244
filter_submodules = config_filter_submodules;
1245
if (option_filter_submodules != -1)
1246
filter_submodules = option_filter_submodules;
1249
* Exit if the user seems to be doing something silly with submodule
1250
* filter flags (but not with filter configs, as those should be
1253
if (option_filter_submodules > 0 && !filter_options.choice)
1254
die(_("the option '%s' requires '%s'"),
1255
"--also-filter-submodules", "--filter");
1256
if (option_filter_submodules > 0 && !option_recurse_submodules.nr)
1257
die(_("the option '%s' requires '%s'"),
1258
"--also-filter-submodules", "--recurse-submodules");
1261
* apply the remote name provided by --origin only after this second
1262
* call to git_config, to ensure it overrides all config-based values.
1264
if (option_origin) {
1266
remote_name = xstrdup(option_origin);
1270
remote_name = xstrdup("origin");
1272
if (!valid_remote_name(remote_name))
1273
die(_("'%s' is not a valid remote name"), remote_name);
1277
src_ref_prefix = "refs/";
1278
strbuf_addstr(&branch_top, src_ref_prefix);
1280
git_config_set("core.bare", "true");
1282
strbuf_addf(&branch_top, "refs/remotes/%s/", remote_name);
1285
strbuf_addf(&key, "remote.%s.url", remote_name);
1286
git_config_set(key.buf, repo);
1289
if (option_no_tags) {
1290
strbuf_addf(&key, "remote.%s.tagOpt", remote_name);
1291
git_config_set(key.buf, "--no-tags");
1295
if (option_required_reference.nr || option_optional_reference.nr)
1298
remote = remote_get_early(remote_name);
1300
refspec_appendf(&remote->fetch, "+%s*:%s*", src_ref_prefix,
1303
path = get_repo_path(remote->url.v[0], &is_bundle);
1304
is_local = option_local != 0 && path && !is_bundle;
1307
warning(_("--depth is ignored in local clones; use file:// instead."));
1309
warning(_("--shallow-since is ignored in local clones; use file:// instead."));
1311
warning(_("--shallow-exclude is ignored in local clones; use file:// instead."));
1312
if (filter_options.choice)
1313
warning(_("--filter is ignored in local clones; use file:// instead."));
1314
if (!access(mkpath("%s/shallow", path), F_OK)) {
1316
die(_("source repository is shallow, reject to clone."));
1317
if (option_local > 0)
1318
warning(_("source repository is shallow, ignoring --local"));
1322
if (option_local > 0 && !is_local)
1323
warning(_("--local is ignored"));
1325
transport = transport_get(remote, path ? path : remote->url.v[0]);
1326
transport_set_verbosity(transport, option_verbosity, option_progress);
1327
transport->family = family;
1328
transport->cloning = 1;
1331
struct bundle_header header = BUNDLE_HEADER_INIT;
1332
int fd = read_bundle_header(path, &header);
1333
int has_filter = header.filter.choice != LOFC_DISABLED;
1337
bundle_header_release(&header);
1339
die(_("cannot clone from filtered bundle"));
1342
transport_set_option(transport, TRANS_OPT_KEEP, "yes");
1345
transport_set_option(transport, TRANS_OPT_REJECT_SHALLOW, "1");
1347
transport_set_option(transport, TRANS_OPT_DEPTH,
1350
transport_set_option(transport, TRANS_OPT_DEEPEN_SINCE,
1353
transport_set_option(transport, TRANS_OPT_DEEPEN_NOT,
1354
(const char *)&option_not);
1355
if (option_single_branch)
1356
transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
1358
if (option_upload_pack)
1359
transport_set_option(transport, TRANS_OPT_UPLOADPACK,
1360
option_upload_pack);
1362
if (server_options.nr)
1363
transport->server_options = &server_options;
1365
if (filter_options.choice) {
1367
expand_list_objects_filter_spec(&filter_options);
1368
transport_set_option(transport, TRANS_OPT_LIST_OBJECTS_FILTER,
1370
transport_set_option(transport, TRANS_OPT_FROM_PROMISOR, "1");
1373
if (transport->smart_options && !deepen && !filter_options.choice)
1374
transport->smart_options->check_self_contained_and_connected = 1;
1376
strvec_push(&transport_ls_refs_options.ref_prefixes, "HEAD");
1377
refspec_ref_prefixes(&remote->fetch,
1378
&transport_ls_refs_options.ref_prefixes);
1380
expand_ref_prefix(&transport_ls_refs_options.ref_prefixes,
1382
if (!option_no_tags)
1383
strvec_push(&transport_ls_refs_options.ref_prefixes,
1386
refs = transport_get_remote_refs(transport, &transport_ls_refs_options);
1389
* Now that we know what algorithm the remote side is using, let's set
1390
* ours to the same thing.
1392
hash_algo = hash_algo_by_ptr(transport_get_hash_algo(transport));
1393
initialize_repository_version(hash_algo, the_repository->ref_storage_format, 1);
1394
repo_set_hash_algo(the_repository, hash_algo);
1395
create_reference_database(the_repository->ref_storage_format, NULL, 1);
1398
* Before fetching from the remote, download and install bundle
1399
* data from the --bundle-uri option.
1402
int has_heuristic = 0;
1404
/* At this point, we need the_repository to match the cloned repo. */
1405
if (repo_init(the_repository, git_dir, work_tree))
1406
warning(_("failed to initialize the repo, skipping bundle URI"));
1407
else if (fetch_bundle_uri(the_repository, bundle_uri, &has_heuristic))
1408
warning(_("failed to fetch objects from bundle URI '%s'"),
1410
else if (has_heuristic)
1411
git_config_set_gently("fetch.bundleuri", bundle_uri);
1414
* Populate transport->got_remote_bundle_uri and
1415
* transport->bundle_uri. We might get nothing.
1417
transport_get_remote_bundle_uri(transport);
1419
if (transport->bundles &&
1420
hashmap_get_size(&transport->bundles->bundles)) {
1421
/* At this point, we need the_repository to match the cloned repo. */
1422
if (repo_init(the_repository, git_dir, work_tree))
1423
warning(_("failed to initialize the repo, skipping bundle URI"));
1424
else if (fetch_bundle_list(the_repository,
1425
transport->bundles))
1426
warning(_("failed to fetch advertised bundles"));
1428
clear_bundle_list(transport->bundles);
1429
FREE_AND_NULL(transport->bundles);
1434
mapped_refs = wanted_peer_refs(refs, &remote->fetch);
1438
* transport_get_remote_refs() may return refs with null sha-1
1439
* in mapped_refs (see struct transport->get_refs_list
1440
* comment). In that case we need fetch it early because
1441
* remote_head code below relies on it.
1443
* for normal clones, transport_get_remote_refs() should
1444
* return reliable ref set, we can delay cloning until after
1445
* remote HEAD check.
1447
for (ref = refs; ref; ref = ref->next)
1448
if (is_null_oid(&ref->old_oid)) {
1449
complete_refs_before_fetch = 0;
1453
if (!is_local && !complete_refs_before_fetch) {
1454
if (transport_fetch_refs(transport, mapped_refs))
1455
die(_("remote transport reported error"));
1459
remote_head = find_ref_by_name(refs, "HEAD");
1460
remote_head_points_at = guess_remote_head(remote_head, mapped_refs, 0);
1462
if (option_branch) {
1463
our_head_points_at = find_remote_branch(mapped_refs, option_branch);
1464
if (!our_head_points_at)
1465
die(_("Remote branch %s not found in upstream %s"),
1466
option_branch, remote_name);
1467
} else if (remote_head_points_at) {
1468
our_head_points_at = remote_head_points_at;
1469
} else if (remote_head) {
1470
our_head_points_at = NULL;
1472
char *to_free = NULL;
1476
warning(_("You appear to have cloned an empty repository."));
1477
option_no_checkout = 1;
1480
if (transport_ls_refs_options.unborn_head_target &&
1481
skip_prefix(transport_ls_refs_options.unborn_head_target,
1482
"refs/heads/", &branch)) {
1483
unborn_head = xstrdup(transport_ls_refs_options.unborn_head_target);
1485
branch = to_free = repo_default_branch_name(the_repository, 0);
1486
unborn_head = xstrfmt("refs/heads/%s", branch);
1490
* We may have selected a local default branch name "foo",
1491
* and even though the remote's HEAD does not point there,
1492
* it may still have a "foo" branch. If so, set it up so
1493
* that we can follow the usual checkout code later.
1495
* Note that for an empty repo we'll already have set
1496
* option_no_checkout above, which would work against us here.
1497
* But for an empty repo, find_remote_branch() can never find
1500
our_head_points_at = find_remote_branch(mapped_refs, branch);
1505
write_refspec_config(src_ref_prefix, our_head_points_at,
1506
remote_head_points_at, &branch_top);
1508
if (filter_options.choice)
1509
partial_clone_register(remote_name, &filter_options);
1512
clone_local(path, git_dir);
1513
else if (mapped_refs && complete_refs_before_fetch) {
1514
if (transport_fetch_refs(transport, mapped_refs))
1515
die(_("remote transport reported error"));
1518
update_remote_refs(refs, mapped_refs, remote_head_points_at,
1519
branch_top.buf, reflog_msg.buf, transport,
1522
update_head(our_head_points_at, remote_head, unborn_head, reflog_msg.buf);
1525
* We want to show progress for recursive submodule clones iff
1526
* we did so for the main clone. But only the transport knows
1527
* the final decision for this flag, so we need to rescue the value
1528
* before we free the transport.
1530
submodule_progress = transport->progress;
1532
transport_unlock_pack(transport, 0);
1533
transport_disconnect(transport);
1535
if (option_dissociate) {
1536
close_object_store(the_repository->objects);
1537
dissociate_from_references();
1540
if (option_sparse_checkout && git_sparse_checkout_init(dir))
1543
junk_mode = JUNK_LEAVE_REPO;
1544
err = checkout(submodule_progress, filter_submodules,
1545
ref_storage_format);
1548
strbuf_release(&reflog_msg);
1549
strbuf_release(&branch_top);
1550
strbuf_release(&buf);
1551
strbuf_release(&key);
1552
free_refs(mapped_refs);
1553
free_refs(remote_head_points_at);
1559
junk_mode = JUNK_LEAVE_ALL;
1561
transport_ls_refs_options_release(&transport_ls_refs_options);