]> git.ipfire.org Git - thirdparty/git.git/blame - builtin/clone.c
clone: add `--shallow-submodules` flag
[thirdparty/git.git] / builtin / clone.c
CommitLineData
8434c2f1
DB
1/*
2 * Builtin "git clone"
3 *
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
7 *
8 * Clone a repository into a different directory that does not yet exist.
9 */
10
c2e86add 11#include "builtin.h"
697cc8ef 12#include "lockfile.h"
8434c2f1
DB
13#include "parse-options.h"
14#include "fetch-pack.h"
15#include "refs.h"
16#include "tree.h"
17#include "tree-walk.h"
18#include "unpack-trees.h"
19#include "transport.h"
20#include "strbuf.h"
21#include "dir.h"
4a16d072 22#include "sigchain.h"
a9f2c136 23#include "branch.h"
8ef51733 24#include "remote.h"
dfa7a6c5 25#include "run-command.h"
0433ad12 26#include "connected.h"
8434c2f1
DB
27
28/*
29 * Overall FIXMEs:
30 * - respect DB_ENVIRONMENT for .git/objects.
31 *
32 * Implementation notes:
33 * - dropping use-separate-remote and no-separate-remote compatibility
34 *
35 */
36static const char * const builtin_clone_usage[] = {
9c9b4f2f 37 N_("git clone [<options>] [--] <repo> [<dir>]"),
8434c2f1
DB
38 NULL
39};
40
3e6e0edd 41static int option_no_checkout, option_bare, option_mirror, option_single_branch = -1;
189260b1 42static int option_local = -1, option_no_hardlinks, option_shared, option_recursive;
d22eb044 43static int option_shallow_submodules = -1;
dbc92b07 44static char *option_template, *option_depth;
8434c2f1 45static char *option_origin = NULL;
7a4ee28f 46static char *option_branch = NULL;
b57fb80a 47static const char *real_git_dir;
8434c2f1 48static char *option_upload_pack = "git-upload-pack";
5bd631b3 49static int option_verbosity;
01fdc21f 50static int option_progress = -1;
84054f79 51static struct string_list option_config;
dbc92b07 52static struct string_list option_reference;
fb1d6dab 53static int option_dissociate;
72290d6a 54static int max_jobs = -1;
dbc92b07 55
8434c2f1 56static struct option builtin_clone_options[] = {
5bd631b3 57 OPT__VERBOSITY(&option_verbosity),
01fdc21f 58 OPT_BOOL(0, "progress", &option_progress,
32b77add 59 N_("force progress reporting")),
d5d09d47
SB
60 OPT_BOOL('n', "no-checkout", &option_no_checkout,
61 N_("don't create a checkout")),
4741edd5
SB
62 OPT_BOOL(0, "bare", &option_bare, N_("create a bare repository")),
63 OPT_HIDDEN_BOOL(0, "naked", &option_bare,
64 N_("create a bare repository")),
d5d09d47
SB
65 OPT_BOOL(0, "mirror", &option_mirror,
66 N_("create a mirror repository (implies bare)")),
189260b1 67 OPT_BOOL('l', "local", &option_local,
32b77add 68 N_("to clone from a local repository")),
d5d09d47 69 OPT_BOOL(0, "no-hardlinks", &option_no_hardlinks,
32b77add 70 N_("don't use local hardlinks, always copy")),
d5d09d47 71 OPT_BOOL('s', "shared", &option_shared,
32b77add 72 N_("setup as shared repository")),
d5d09d47 73 OPT_BOOL(0, "recursive", &option_recursive,
32b77add 74 N_("initialize submodules in the clone")),
d5d09d47 75 OPT_BOOL(0, "recurse-submodules", &option_recursive,
32b77add 76 N_("initialize submodules in the clone")),
72290d6a
SB
77 OPT_INTEGER('j', "jobs", &max_jobs,
78 N_("number of submodules cloned in parallel")),
32b77add
NTND
79 OPT_STRING(0, "template", &option_template, N_("template-directory"),
80 N_("directory from which templates will be used")),
8ade009c
JK
81 OPT_STRING_LIST(0, "reference", &option_reference, N_("repo"),
82 N_("reference repository")),
14f8b9b4
JK
83 OPT_BOOL(0, "dissociate", &option_dissociate,
84 N_("use --reference only while cloning")),
32b77add
NTND
85 OPT_STRING('o', "origin", &option_origin, N_("name"),
86 N_("use <name> instead of 'origin' to track upstream")),
87 OPT_STRING('b', "branch", &option_branch, N_("branch"),
88 N_("checkout <branch> instead of the remote's HEAD")),
89 OPT_STRING('u', "upload-pack", &option_upload_pack, N_("path"),
90 N_("path to git-upload-pack on the remote")),
91 OPT_STRING(0, "depth", &option_depth, N_("depth"),
92 N_("create a shallow clone of that depth")),
3e6e0edd 93 OPT_BOOL(0, "single-branch", &option_single_branch,
32b77add 94 N_("clone only one branch, HEAD or --branch")),
d22eb044
SB
95 OPT_BOOL(0, "shallow-submodules", &option_shallow_submodules,
96 N_("any cloned submodules will be shallow")),
32b77add
NTND
97 OPT_STRING(0, "separate-git-dir", &real_git_dir, N_("gitdir"),
98 N_("separate git dir from working tree")),
99 OPT_STRING_LIST('c', "config", &option_config, N_("key=value"),
100 N_("set config inside the new repository")),
8434c2f1
DB
101 OPT_END()
102};
103
0ea68e42 104static const char *get_repo_path_1(struct strbuf *path, int *is_bundle)
8434c2f1 105{
b3256eb8 106 static char *suffix[] = { "/.git", "", ".git/.git", ".git" };
8434c2f1 107 static char *bundle_suffix[] = { ".bundle", "" };
0ea68e42 108 size_t baselen = path->len;
8434c2f1
DB
109 struct stat st;
110 int i;
111
112 for (i = 0; i < ARRAY_SIZE(suffix); i++) {
0ea68e42
JK
113 strbuf_setlen(path, baselen);
114 strbuf_addstr(path, suffix[i]);
115 if (stat(path->buf, &st))
9b0ebc72 116 continue;
0ea68e42 117 if (S_ISDIR(st.st_mode) && is_git_directory(path->buf)) {
8434c2f1 118 *is_bundle = 0;
0ea68e42 119 return path->buf;
9b0ebc72
NTND
120 } else if (S_ISREG(st.st_mode) && st.st_size > 8) {
121 /* Is it a "gitfile"? */
122 char signature[8];
0ea68e42
JK
123 const char *dst;
124 int len, fd = open(path->buf, O_RDONLY);
9b0ebc72
NTND
125 if (fd < 0)
126 continue;
127 len = read_in_full(fd, signature, 8);
128 close(fd);
129 if (len != 8 || strncmp(signature, "gitdir: ", 8))
130 continue;
0ea68e42
JK
131 dst = read_gitfile(path->buf);
132 if (dst) {
9b0ebc72 133 *is_bundle = 0;
0ea68e42 134 return dst;
9b0ebc72 135 }
8434c2f1
DB
136 }
137 }
138
139 for (i = 0; i < ARRAY_SIZE(bundle_suffix); i++) {
0ea68e42
JK
140 strbuf_setlen(path, baselen);
141 strbuf_addstr(path, bundle_suffix[i]);
142 if (!stat(path->buf, &st) && S_ISREG(st.st_mode)) {
8434c2f1 143 *is_bundle = 1;
0ea68e42 144 return path->buf;
8434c2f1
DB
145 }
146 }
147
148 return NULL;
149}
150
0ea68e42
JK
151static char *get_repo_path(const char *repo, int *is_bundle)
152{
153 struct strbuf path = STRBUF_INIT;
154 const char *raw;
155 char *canon;
156
157 strbuf_addstr(&path, repo);
158 raw = get_repo_path_1(&path, is_bundle);
159 canon = raw ? xstrdup(absolute_path(raw)) : NULL;
160 strbuf_release(&path);
161 return canon;
162}
163
6612f877 164static char *guess_dir_name(const char *repo, int is_bundle, int is_bare)
8434c2f1 165{
e8959867 166 const char *end = repo + strlen(repo), *start, *ptr;
7e837c64 167 size_t len;
8a94bc7b 168 char *dir;
b8c5db35 169
e8959867
PS
170 /*
171 * Skip scheme.
172 */
173 start = strstr(repo, "://");
174 if (start == NULL)
175 start = repo;
176 else
177 start += 3;
178
179 /*
180 * Skip authentication data. The stripping does happen
181 * greedily, such that we strip up to the last '@' inside
182 * the host part.
183 */
184 for (ptr = start; ptr < end && !is_dir_sep(*ptr); ptr++) {
185 if (*ptr == '@')
186 start = ptr + 1;
187 }
188
b8c5db35 189 /*
8a94bc7b 190 * Strip trailing spaces, slashes and /.git
b8c5db35 191 */
e8959867 192 while (start < end && (is_dir_sep(end[-1]) || isspace(end[-1])))
b8c5db35 193 end--;
e8959867 194 if (end - start > 5 && is_dir_sep(end[-5]) &&
b8c5db35
JS
195 !strncmp(end - 4, ".git", 4)) {
196 end -= 5;
e8959867 197 while (start < end && is_dir_sep(end[-1]))
b8c5db35
JS
198 end--;
199 }
200
201 /*
92722efe
PS
202 * Strip trailing port number if we've got only a
203 * hostname (that is, there is no dir separator but a
204 * colon). This check is required such that we do not
205 * strip URI's like '/foo/bar:2222.git', which should
206 * result in a dir '2222' being guessed due to backwards
207 * compatibility.
208 */
209 if (memchr(start, '/', end - start) == NULL
210 && memchr(start, ':', end - start) != NULL) {
211 ptr = end;
212 while (start < ptr && isdigit(ptr[-1]) && ptr[-1] != ':')
213 ptr--;
214 if (start < ptr && ptr[-1] == ':')
215 end = ptr - 1;
216 }
217
b8c5db35 218 /*
e8959867
PS
219 * Find last component. To remain backwards compatible we
220 * also regard colons as path separators, such that
221 * cloning a repository 'foo:bar.git' would result in a
222 * directory 'bar' being guessed.
b8c5db35 223 */
e8959867
PS
224 ptr = end;
225 while (start < ptr && !is_dir_sep(ptr[-1]) && ptr[-1] != ':')
226 ptr--;
227 start = ptr;
b8c5db35
JS
228
229 /*
230 * Strip .{bundle,git}.
231 */
db2e2204
JK
232 len = end - start;
233 strip_suffix_mem(start, &len, is_bundle ? ".bundle" : ".git");
8434c2f1 234
adef9561
PS
235 if (!len || (len == 1 && *start == '/'))
236 die("No directory name could be guessed.\n"
237 "Please specify a directory on the command line");
238
7e837c64
SS
239 if (is_bare)
240 dir = xstrfmt("%.*s.git", (int)len, start);
241 else
242 dir = xstrndup(start, len);
8a94bc7b
AR
243 /*
244 * Replace sequences of 'control' characters and whitespace
245 * with one ascii space, remove leading and trailing spaces.
246 */
247 if (*dir) {
248 char *out = dir;
249 int prev_space = 1 /* strip leading whitespace */;
250 for (end = dir; *end; ++end) {
251 char ch = *end;
252 if ((unsigned char)ch < '\x20')
253 ch = '\x20';
254 if (isspace(ch)) {
255 if (prev_space)
256 continue;
257 prev_space = 1;
258 } else
259 prev_space = 0;
260 *out++ = ch;
261 }
262 *out = '\0';
263 if (out > dir && prev_space)
264 out[-1] = '\0';
6612f877 265 }
8a94bc7b 266 return dir;
8434c2f1
DB
267}
268
44a68fd5
CB
269static void strip_trailing_slashes(char *dir)
270{
271 char *end = dir + strlen(dir);
272
273 while (dir < end - 1 && is_dir_sep(end[-1]))
274 end--;
275 *end = '\0';
276}
277
dbc92b07 278static int add_one_reference(struct string_list_item *item, void *cb_data)
8434c2f1 279{
e6baf4a1 280 char *ref_git;
b552b56d 281 const char *repo;
e6baf4a1 282 struct strbuf alternate = STRBUF_INIT;
8434c2f1 283
b552b56d 284 /* Beware: read_gitfile(), real_path() and mkpath() return static buffer */
e6baf4a1 285 ref_git = xstrdup(real_path(item->string));
b552b56d
AS
286
287 repo = read_gitfile(ref_git);
288 if (!repo)
289 repo = read_gitfile(mkpath("%s/.git", ref_git));
290 if (repo) {
291 free(ref_git);
292 ref_git = xstrdup(repo);
293 }
294
295 if (!repo && is_directory(mkpath("%s/.git/objects", ref_git))) {
4e2d094d 296 char *ref_git_git = mkpathdup("%s/.git", ref_git);
e6baf4a1
JH
297 free(ref_git);
298 ref_git = ref_git_git;
d78db842
NTND
299 } else if (!is_directory(mkpath("%s/objects", ref_git))) {
300 struct strbuf sb = STRBUF_INIT;
301 if (get_common_dir(&sb, ref_git))
302 die(_("reference repository '%s' as a linked checkout is not supported yet."),
303 item->string);
0658569e 304 die(_("reference repository '%s' is not a local repository."),
dbc92b07 305 item->string);
d78db842 306 }
8434c2f1 307
606e435a
NTND
308 if (!access(mkpath("%s/shallow", ref_git), F_OK))
309 die(_("reference repository '%s' is shallow"), item->string);
310
311 if (!access(mkpath("%s/info/grafts", ref_git), F_OK))
312 die(_("reference repository '%s' is grafted"), item->string);
313
e6baf4a1
JH
314 strbuf_addf(&alternate, "%s/objects", ref_git);
315 add_to_alternates_file(alternate.buf);
316 strbuf_release(&alternate);
e6baf4a1 317 free(ref_git);
dbc92b07
JH
318 return 0;
319}
8434c2f1 320
dbc92b07
JH
321static void setup_reference(void)
322{
323 for_each_string_list(&option_reference, add_one_reference, NULL);
8434c2f1
DB
324}
325
e6baf4a1
JH
326static void copy_alternates(struct strbuf *src, struct strbuf *dst,
327 const char *src_repo)
328{
329 /*
330 * Read from the source objects/info/alternates file
331 * and copy the entries to corresponding file in the
332 * destination repository with add_to_alternates_file().
333 * Both src and dst have "$path/objects/info/alternates".
334 *
335 * Instead of copying bit-for-bit from the original,
336 * we need to append to existing one so that the already
337 * created entry via "clone -s" is not lost, and also
338 * to turn entries with paths relative to the original
339 * absolute, so that they can be used in the new repository.
340 */
341 FILE *in = fopen(src->buf, "r");
342 struct strbuf line = STRBUF_INIT;
343
344 while (strbuf_getline(&line, in, '\n') != EOF) {
dcf69262 345 char *abs_path;
e6baf4a1
JH
346 if (!line.len || line.buf[0] == '#')
347 continue;
348 if (is_absolute_path(line.buf)) {
349 add_to_alternates_file(line.buf);
350 continue;
351 }
dcf69262
NTND
352 abs_path = mkpathdup("%s/objects/%s", src_repo, line.buf);
353 normalize_path_copy(abs_path, abs_path);
354 add_to_alternates_file(abs_path);
355 free(abs_path);
e6baf4a1
JH
356 }
357 strbuf_release(&line);
358 fclose(in);
359}
360
361static void copy_or_link_directory(struct strbuf *src, struct strbuf *dest,
362 const char *src_repo, int src_baselen)
8434c2f1
DB
363{
364 struct dirent *de;
365 struct stat buf;
366 int src_len, dest_len;
367 DIR *dir;
368
b9e125e0 369 dir = opendir(src->buf);
8434c2f1 370 if (!dir)
e84d7b74 371 die_errno(_("failed to open '%s'"), src->buf);
8434c2f1 372
b9e125e0 373 if (mkdir(dest->buf, 0777)) {
8434c2f1 374 if (errno != EEXIST)
e84d7b74 375 die_errno(_("failed to create directory '%s'"), dest->buf);
b9e125e0 376 else if (stat(dest->buf, &buf))
e84d7b74 377 die_errno(_("failed to stat '%s'"), dest->buf);
8434c2f1 378 else if (!S_ISDIR(buf.st_mode))
e84d7b74 379 die(_("%s exists and is not a directory"), dest->buf);
8434c2f1
DB
380 }
381
b9e125e0
MV
382 strbuf_addch(src, '/');
383 src_len = src->len;
384 strbuf_addch(dest, '/');
385 dest_len = dest->len;
8434c2f1
DB
386
387 while ((de = readdir(dir)) != NULL) {
b9e125e0
MV
388 strbuf_setlen(src, src_len);
389 strbuf_addstr(src, de->d_name);
390 strbuf_setlen(dest, dest_len);
391 strbuf_addstr(dest, de->d_name);
392 if (stat(src->buf, &buf)) {
e84d7b74 393 warning (_("failed to stat %s\n"), src->buf);
8434c2f1
DB
394 continue;
395 }
396 if (S_ISDIR(buf.st_mode)) {
397 if (de->d_name[0] != '.')
e6baf4a1
JH
398 copy_or_link_directory(src, dest,
399 src_repo, src_baselen);
400 continue;
401 }
402
403 /* Files that cannot be copied bit-for-bit... */
404 if (!strcmp(src->buf + src_baselen, "/info/alternates")) {
405 copy_alternates(src, dest, src_repo);
8434c2f1
DB
406 continue;
407 }
408
b9e125e0 409 if (unlink(dest->buf) && errno != ENOENT)
e84d7b74 410 die_errno(_("failed to unlink '%s'"), dest->buf);
fdabc242 411 if (!option_no_hardlinks) {
b9e125e0 412 if (!link(src->buf, dest->buf))
fdabc242 413 continue;
189260b1 414 if (option_local > 0)
e84d7b74 415 die_errno(_("failed to create link '%s'"), dest->buf);
fdabc242 416 option_no_hardlinks = 1;
8434c2f1 417 }
f7835a25 418 if (copy_file_with_time(dest->buf, src->buf, 0666))
e84d7b74 419 die_errno(_("failed to copy file to '%s'"), dest->buf);
8434c2f1 420 }
689ef4d4 421 closedir(dir);
8434c2f1
DB
422}
423
6f48d39f 424static void clone_local(const char *src_repo, const char *dest_repo)
8434c2f1 425{
e6baf4a1
JH
426 if (option_shared) {
427 struct strbuf alt = STRBUF_INIT;
428 strbuf_addf(&alt, "%s/objects", src_repo);
429 add_to_alternates_file(alt.buf);
430 strbuf_release(&alt);
431 } else {
432 struct strbuf src = STRBUF_INIT;
433 struct strbuf dest = STRBUF_INIT;
744e4697
NTND
434 get_common_dir(&src, src_repo);
435 get_common_dir(&dest, dest_repo);
436 strbuf_addstr(&src, "/objects");
437 strbuf_addstr(&dest, "/objects");
e6baf4a1 438 copy_or_link_directory(&src, &dest, src_repo, src.len);
b9e125e0
MV
439 strbuf_release(&src);
440 strbuf_release(&dest);
8434c2f1
DB
441 }
442
28ba96ab 443 if (0 <= option_verbosity)
68b939b2 444 fprintf(stderr, _("done.\n"));
8434c2f1
DB
445}
446
447static const char *junk_work_tree;
448static const char *junk_git_dir;
85064630 449static enum {
d3b34622
JK
450 JUNK_LEAVE_NONE,
451 JUNK_LEAVE_REPO,
452 JUNK_LEAVE_ALL
453} junk_mode = JUNK_LEAVE_NONE;
454
455static const char junk_leave_repo_msg[] =
456N_("Clone succeeded, but checkout failed.\n"
457 "You can inspect what was checked out with 'git status'\n"
458 "and retry the checkout with 'git checkout -f HEAD'\n");
8434c2f1
DB
459
460static void remove_junk(void)
461{
f285a2d7 462 struct strbuf sb = STRBUF_INIT;
d3b34622
JK
463
464 switch (junk_mode) {
465 case JUNK_LEAVE_REPO:
466 warning("%s", _(junk_leave_repo_msg));
467 /* fall-through */
468 case JUNK_LEAVE_ALL:
469 return;
470 default:
471 /* proceed to removal */
472 break;
473 }
474
8434c2f1
DB
475 if (junk_git_dir) {
476 strbuf_addstr(&sb, junk_git_dir);
477 remove_dir_recursively(&sb, 0);
478 strbuf_reset(&sb);
479 }
480 if (junk_work_tree) {
481 strbuf_addstr(&sb, junk_work_tree);
482 remove_dir_recursively(&sb, 0);
483 strbuf_reset(&sb);
484 }
485}
486
487static void remove_junk_on_signal(int signo)
488{
489 remove_junk();
4a16d072 490 sigchain_pop(signo);
8434c2f1
DB
491 raise(signo);
492}
493
9e585046
NTND
494static struct ref *find_remote_branch(const struct ref *refs, const char *branch)
495{
496 struct ref *ref;
497 struct strbuf head = STRBUF_INIT;
498 strbuf_addstr(&head, "refs/heads/");
499 strbuf_addstr(&head, branch);
500 ref = find_ref_by_name(refs, head.buf);
501 strbuf_release(&head);
5a7d5b68
NTND
502
503 if (ref)
504 return ref;
505
506 strbuf_addstr(&head, "refs/tags/");
507 strbuf_addstr(&head, branch);
508 ref = find_ref_by_name(refs, head.buf);
509 strbuf_release(&head);
510
9e585046
NTND
511 return ref;
512}
513
5bdc32d3
NP
514static struct ref *wanted_peer_refs(const struct ref *refs,
515 struct refspec *refspec)
8434c2f1 516{
c1921c18
JK
517 struct ref *head = copy_ref(find_ref_by_name(refs, "HEAD"));
518 struct ref *local_refs = head;
519 struct ref **tail = head ? &head->next : &local_refs;
8434c2f1 520
3e6e0edd
NTND
521 if (option_single_branch) {
522 struct ref *remote_head = NULL;
523
524 if (!option_branch)
525 remote_head = guess_remote_head(head, refs, 0);
0ec4b165
NTND
526 else {
527 local_refs = NULL;
528 tail = &local_refs;
529 remote_head = copy_ref(find_remote_branch(refs, option_branch));
530 }
3e6e0edd
NTND
531
532 if (!remote_head && option_branch)
533 warning(_("Could not find remote branch %s to clone."),
534 option_branch);
5a7d5b68 535 else {
3e6e0edd 536 get_fetch_map(remote_head, refspec, &tail, 0);
5a7d5b68
NTND
537
538 /* if --branch=tag, pull the requested tag explicitly */
539 get_fetch_map(remote_head, tag_refspec, &tail, 0);
540 }
3e6e0edd
NTND
541 } else
542 get_fetch_map(refs, refspec, &tail, 0);
543
544 if (!option_mirror && !option_single_branch)
468386a9 545 get_fetch_map(refs, tag_refspec, &tail, 0);
8434c2f1 546
5bdc32d3
NP
547 return local_refs;
548}
549
550static void write_remote_refs(const struct ref *local_refs)
551{
552 const struct ref *r;
553
58f233ce
MH
554 struct ref_transaction *t;
555 struct strbuf err = STRBUF_INIT;
556
557 t = ref_transaction_begin(&err);
558 if (!t)
559 die("%s", err.buf);
9f69d297 560
c1921c18
JK
561 for (r = local_refs; r; r = r->next) {
562 if (!r->peer_ref)
563 continue;
f4e54d02 564 if (ref_transaction_create(t, r->peer_ref->name, r->old_oid.hash,
58f233ce
MH
565 0, NULL, &err))
566 die("%s", err.buf);
c1921c18 567 }
3e8aded2 568
58f233ce
MH
569 if (initial_ref_transaction_commit(t, &err))
570 die("%s", err.buf);
571
572 strbuf_release(&err);
573 ref_transaction_free(t);
8434c2f1
DB
574}
575
3e6e0edd
NTND
576static void write_followtags(const struct ref *refs, const char *msg)
577{
578 const struct ref *ref;
579 for (ref = refs; ref; ref = ref->next) {
59556548 580 if (!starts_with(ref->name, "refs/tags/"))
3e6e0edd 581 continue;
59556548 582 if (ends_with(ref->name, "^{}"))
3e6e0edd 583 continue;
f4e54d02 584 if (!has_object_file(&ref->old_oid))
3e6e0edd 585 continue;
f4e54d02 586 update_ref(msg, ref->name, ref->old_oid.hash,
f4124112 587 NULL, 0, UPDATE_REFS_DIE_ON_ERR);
3e6e0edd
NTND
588 }
589}
590
0433ad12
JK
591static int iterate_ref_map(void *cb_data, unsigned char sha1[20])
592{
593 struct ref **rm = cb_data;
594 struct ref *ref = *rm;
595
596 /*
597 * Skip anything missing a peer_ref, which we are not
598 * actually going to write a ref for.
599 */
600 while (ref && !ref->peer_ref)
601 ref = ref->next;
602 /* Returning -1 notes "end of list" to the caller. */
603 if (!ref)
604 return -1;
605
f4e54d02 606 hashcpy(sha1, ref->old_oid.hash);
0433ad12
JK
607 *rm = ref->next;
608 return 0;
609}
610
960b7d1c
NTND
611static void update_remote_refs(const struct ref *refs,
612 const struct ref *mapped_refs,
613 const struct ref *remote_head_points_at,
614 const char *branch_top,
c6807a40 615 const char *msg,
45ed4afa 616 struct transport *transport,
125a05fd 617 int check_connectivity)
960b7d1c 618{
0433ad12
JK
619 const struct ref *rm = mapped_refs;
620
125a05fd 621 if (check_connectivity) {
2856cbf0 622 if (transport->progress)
68b939b2 623 fprintf(stderr, _("Checking connectivity... "));
45ed4afa
JH
624 if (check_everything_connected_with_transport(iterate_ref_map,
625 0, &rm, transport))
125a05fd 626 die(_("remote did not send all necessary objects"));
2856cbf0 627 if (transport->progress)
f94a84c4 628 fprintf(stderr, _("done.\n"));
125a05fd 629 }
0433ad12 630
960b7d1c 631 if (refs) {
960b7d1c
NTND
632 write_remote_refs(mapped_refs);
633 if (option_single_branch)
634 write_followtags(refs, msg);
635 }
636
637 if (remote_head_points_at && !option_bare) {
638 struct strbuf head_ref = STRBUF_INIT;
639 strbuf_addstr(&head_ref, branch_top);
640 strbuf_addstr(&head_ref, "HEAD");
641 create_symref(head_ref.buf,
642 remote_head_points_at->peer_ref->name,
643 msg);
644 }
645}
646
f034d354
NTND
647static void update_head(const struct ref *our, const struct ref *remote,
648 const char *msg)
649{
cf4fff57
JK
650 const char *head;
651 if (our && skip_prefix(our->name, "refs/heads/", &head)) {
f034d354
NTND
652 /* Local default branch link */
653 create_symref("HEAD", our->name, NULL);
654 if (!option_bare) {
f4e54d02 655 update_ref(msg, "HEAD", our->old_oid.hash, NULL, 0,
f4124112 656 UPDATE_REFS_DIE_ON_ERR);
f034d354
NTND
657 install_branch_config(0, head, option_origin, our->name);
658 }
5a7d5b68 659 } else if (our) {
f4e54d02 660 struct commit *c = lookup_commit_reference(our->old_oid.hash);
5a7d5b68 661 /* --branch specifies a non-branch (i.e. tags), detach HEAD */
ed1c9977 662 update_ref(msg, "HEAD", c->object.oid.hash,
f4124112 663 NULL, REF_NODEREF, UPDATE_REFS_DIE_ON_ERR);
f034d354
NTND
664 } else if (remote) {
665 /*
666 * We know remote HEAD points to a non-branch, or
920b691f 667 * HEAD points to a branch but we don't know which one.
f034d354
NTND
668 * Detach HEAD in all these cases.
669 */
f4e54d02 670 update_ref(msg, "HEAD", remote->old_oid.hash,
f4124112 671 NULL, REF_NODEREF, UPDATE_REFS_DIE_ON_ERR);
f034d354
NTND
672 }
673}
674
c39852c1
NTND
675static int checkout(void)
676{
677 unsigned char sha1[20];
678 char *head;
679 struct lock_file *lock_file;
680 struct unpack_trees_options opts;
681 struct tree *tree;
682 struct tree_desc t;
03b86647 683 int err = 0;
c39852c1
NTND
684
685 if (option_no_checkout)
686 return 0;
687
7695d118 688 head = resolve_refdup("HEAD", RESOLVE_REF_READING, sha1, NULL);
c39852c1
NTND
689 if (!head) {
690 warning(_("remote HEAD refers to nonexistent ref, "
691 "unable to checkout.\n"));
692 return 0;
693 }
2857093b
NTND
694 if (!strcmp(head, "HEAD")) {
695 if (advice_detached_head)
696 detach_advice(sha1_to_hex(sha1));
697 } else {
59556548 698 if (!starts_with(head, "refs/heads/"))
c39852c1
NTND
699 die(_("HEAD not found below refs/heads!"));
700 }
701 free(head);
702
703 /* We need to be in the new work tree for the checkout */
704 setup_work_tree();
705
706 lock_file = xcalloc(1, sizeof(struct lock_file));
03b86647 707 hold_locked_index(lock_file, 1);
c39852c1
NTND
708
709 memset(&opts, 0, sizeof opts);
710 opts.update = 1;
711 opts.merge = 1;
712 opts.fn = oneway_merge;
8f63da13 713 opts.verbose_update = (option_verbosity >= 0);
c39852c1
NTND
714 opts.src_index = &the_index;
715 opts.dst_index = &the_index;
716
717 tree = parse_tree_indirect(sha1);
718 parse_tree(tree);
719 init_tree_desc(&t, tree->buffer, tree->size);
0aac7bb2
JK
720 if (unpack_trees(1, &t, &opts) < 0)
721 die(_("unable to checkout working tree"));
c39852c1 722
03b86647 723 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
c39852c1
NTND
724 die(_("unable to write new index file"));
725
15048f8a
BP
726 err |= run_hook_le(NULL, "post-checkout", sha1_to_hex(null_sha1),
727 sha1_to_hex(sha1), "1", NULL);
c39852c1 728
72290d6a
SB
729 if (!err && option_recursive) {
730 struct argv_array args = ARGV_ARRAY_INIT;
731 argv_array_pushl(&args, "submodule", "update", "--init", "--recursive", NULL);
732
d22eb044
SB
733 if (option_shallow_submodules == 1
734 || (option_shallow_submodules == -1 && option_depth))
735 argv_array_push(&args, "--depth=1");
736
72290d6a
SB
737 if (max_jobs != -1)
738 argv_array_pushf(&args, "--jobs=%d", max_jobs);
739
740 err = run_command_v_opt(args.argv, RUN_GIT_CMD);
741 argv_array_clear(&args);
742 }
c39852c1
NTND
743
744 return err;
745}
746
84054f79
JK
747static int write_one_config(const char *key, const char *value, void *data)
748{
749 return git_config_set_multivar(key, value ? value : "true", "^$", 0);
750}
751
752static void write_config(struct string_list *config)
753{
754 int i;
755
756 for (i = 0; i < config->nr; i++) {
757 if (git_config_parse_parameter(config->items[i].string,
758 write_one_config, NULL) < 0)
759 die("unable to write parameters to config file");
760 }
761}
762
24d36f14
DA
763static void write_refspec_config(const char *src_ref_prefix,
764 const struct ref *our_head_points_at,
765 const struct ref *remote_head_points_at,
766 struct strbuf *branch_top)
31b808a0
RT
767{
768 struct strbuf key = STRBUF_INIT;
769 struct strbuf value = STRBUF_INIT;
770
771 if (option_mirror || !option_bare) {
772 if (option_single_branch && !option_mirror) {
773 if (option_branch) {
60a5f5fc 774 if (starts_with(our_head_points_at->name, "refs/tags/"))
31b808a0
RT
775 strbuf_addf(&value, "+%s:%s", our_head_points_at->name,
776 our_head_points_at->name);
777 else
778 strbuf_addf(&value, "+%s:%s%s", our_head_points_at->name,
779 branch_top->buf, option_branch);
780 } else if (remote_head_points_at) {
cf4fff57
JK
781 const char *head = remote_head_points_at->name;
782 if (!skip_prefix(head, "refs/heads/", &head))
783 die("BUG: remote HEAD points at non-head?");
784
31b808a0 785 strbuf_addf(&value, "+%s:%s%s", remote_head_points_at->name,
cf4fff57 786 branch_top->buf, head);
31b808a0
RT
787 }
788 /*
789 * otherwise, the next "git fetch" will
790 * simply fetch from HEAD without updating
d6ac1d21 791 * any remote-tracking branch, which is what
31b808a0
RT
792 * we want.
793 */
794 } else {
795 strbuf_addf(&value, "+%s*:%s*", src_ref_prefix, branch_top->buf);
796 }
797 /* Configure the remote */
798 if (value.len) {
799 strbuf_addf(&key, "remote.%s.fetch", option_origin);
800 git_config_set_multivar(key.buf, value.buf, "^$", 0);
801 strbuf_reset(&key);
802
803 if (option_mirror) {
804 strbuf_addf(&key, "remote.%s.mirror", option_origin);
805 git_config_set(key.buf, "true");
806 strbuf_reset(&key);
807 }
808 }
809 }
810
811 strbuf_release(&key);
812 strbuf_release(&value);
813}
814
fb1d6dab
JH
815static void dissociate_from_references(void)
816{
817 static const char* argv[] = { "repack", "-a", "-d", NULL };
0181681e 818 char *alternates = git_pathdup("objects/info/alternates");
fb1d6dab 819
0181681e
AR
820 if (!access(alternates, F_OK)) {
821 if (run_command_v_opt(argv, RUN_GIT_CMD|RUN_COMMAND_NO_STDIN))
822 die(_("cannot repack to clean up"));
823 if (unlink(alternates) && errno != ENOENT)
824 die_errno(_("cannot unlink temporary alternates file"));
825 }
826 free(alternates);
fb1d6dab
JH
827}
828
8434c2f1
DB
829int cmd_clone(int argc, const char **argv, const char *prefix)
830{
24c61c44 831 int is_bundle = 0, is_local;
8434c2f1
DB
832 struct stat buf;
833 const char *repo_name, *repo, *work_tree, *git_dir;
834 char *path, *dir;
55892d23 835 int dest_exists;
37148311 836 const struct ref *refs, *remote_head;
7a4ee28f
JK
837 const struct ref *remote_head_points_at;
838 const struct ref *our_head_points_at;
37148311 839 struct ref *mapped_refs;
90498161 840 const struct ref *ref;
b5ff37ac
MV
841 struct strbuf key = STRBUF_INIT, value = STRBUF_INIT;
842 struct strbuf branch_top = STRBUF_INIT, reflog_msg = STRBUF_INIT;
1db4a75c 843 struct transport *transport = NULL;
9e585046 844 const char *src_ref_prefix = "refs/heads/";
6f48d39f 845 struct remote *remote;
90498161 846 int err = 0, complete_refs_before_fetch = 1;
8434c2f1 847
689f0396
DB
848 struct refspec *refspec;
849 const char *fetch_pattern;
8434c2f1 850
bbc30f99 851 packet_trace_identity("clone");
37782920 852 argc = parse_options(argc, argv, prefix, builtin_clone_options,
8434c2f1
DB
853 builtin_clone_usage, 0);
854
d52dc4b1 855 if (argc > 2)
e84d7b74 856 usage_msg_opt(_("Too many arguments."),
d52dc4b1
JN
857 builtin_clone_usage, builtin_clone_options);
858
8434c2f1 859 if (argc == 0)
e84d7b74 860 usage_msg_opt(_("You must specify a repository to clone."),
d52dc4b1 861 builtin_clone_usage, builtin_clone_options);
8434c2f1 862
3e6e0edd
NTND
863 if (option_single_branch == -1)
864 option_single_branch = option_depth ? 1 : 0;
865
bc699afc
JS
866 if (option_mirror)
867 option_bare = 1;
868
8434c2f1
DB
869 if (option_bare) {
870 if (option_origin)
e84d7b74 871 die(_("--bare and --origin %s options are incompatible."),
8434c2f1 872 option_origin);
95b63f1e
NTND
873 if (real_git_dir)
874 die(_("--bare and --separate-git-dir are incompatible."));
8434c2f1 875 option_no_checkout = 1;
8434c2f1
DB
876 }
877
878 if (!option_origin)
879 option_origin = "origin";
880
881 repo_name = argv[0];
882
883 path = get_repo_path(repo_name, &is_bundle);
884 if (path)
e2a57aac 885 repo = xstrdup(absolute_path(repo_name));
8434c2f1 886 else if (!strchr(repo_name, ':'))
d3e1ddfd 887 die(_("repository '%s' does not exist"), repo_name);
8434c2f1
DB
888 else
889 repo = repo_name;
890
5594bcad
NTND
891 /* no need to be strict, transport_set_option() will validate it again */
892 if (option_depth && atoi(option_depth) < 1)
893 die(_("depth %s is not a positive number"), option_depth);
894
8434c2f1
DB
895 if (argc == 2)
896 dir = xstrdup(argv[1]);
897 else
6612f877 898 dir = guess_dir_name(repo_name, is_bundle, option_bare);
44a68fd5 899 strip_trailing_slashes(dir);
8434c2f1 900
55892d23
AP
901 dest_exists = !stat(dir, &buf);
902 if (dest_exists && !is_empty_dir(dir))
e84d7b74
ÆAB
903 die(_("destination path '%s' already exists and is not "
904 "an empty directory."), dir);
8434c2f1 905
8434c2f1
DB
906 strbuf_addf(&reflog_msg, "clone: from %s", repo);
907
908 if (option_bare)
909 work_tree = NULL;
910 else {
911 work_tree = getenv("GIT_WORK_TREE");
912 if (work_tree && !stat(work_tree, &buf))
e84d7b74 913 die(_("working tree '%s' already exists."), work_tree);
8434c2f1
DB
914 }
915
916 if (option_bare || work_tree)
917 git_dir = xstrdup(dir);
918 else {
919 work_tree = dir;
4e2d094d 920 git_dir = mkpathdup("%s/.git", dir);
8434c2f1
DB
921 }
922
ee0e3872
JK
923 atexit(remove_junk);
924 sigchain_push_common(remove_junk_on_signal);
925
8434c2f1 926 if (!option_bare) {
8e21d63b 927 if (safe_create_leading_directories_const(work_tree) < 0)
e84d7b74 928 die_errno(_("could not create leading directories of '%s'"),
d824cbba 929 work_tree);
45d4fdc2 930 if (!dest_exists && mkdir(work_tree, 0777))
16eff6c0 931 die_errno(_("could not create work tree dir '%s'"),
d824cbba 932 work_tree);
ee0e3872 933 junk_work_tree = work_tree;
8434c2f1
DB
934 set_git_work_tree(work_tree);
935 }
8434c2f1 936
ee0e3872 937 junk_git_dir = git_dir;
8e21d63b 938 if (safe_create_leading_directories_const(git_dir) < 0)
e84d7b74 939 die(_("could not create leading directories of '%s'"), git_dir);
b57fb80a
NTND
940
941 set_git_dir_init(git_dir, real_git_dir, 0);
9be1980b 942 if (real_git_dir) {
b57fb80a 943 git_dir = real_git_dir;
9be1980b
JL
944 junk_git_dir = real_git_dir;
945 }
8434c2f1 946
3781fcce
ÆAB
947 if (0 <= option_verbosity) {
948 if (option_bare)
68b939b2 949 fprintf(stderr, _("Cloning into bare repository '%s'...\n"), dir);
3781fcce 950 else
68b939b2 951 fprintf(stderr, _("Cloning into '%s'...\n"), dir);
3781fcce 952 }
28ba96ab 953 init_db(option_template, INIT_DB_QUIET);
84054f79 954 write_config(&option_config);
8434c2f1 955
9bd81e42 956 git_config(git_default_config, NULL);
8434c2f1
DB
957
958 if (option_bare) {
bc699afc
JS
959 if (option_mirror)
960 src_ref_prefix = "refs/";
b5ff37ac 961 strbuf_addstr(&branch_top, src_ref_prefix);
8434c2f1
DB
962
963 git_config_set("core.bare", "true");
964 } else {
b5ff37ac 965 strbuf_addf(&branch_top, "refs/remotes/%s/", option_origin);
bc699afc 966 }
8434c2f1 967
689f0396 968 strbuf_addf(&value, "+%s*:%s*", src_ref_prefix, branch_top.buf);
df61c889
SR
969 strbuf_addf(&key, "remote.%s.url", option_origin);
970 git_config_set(key.buf, repo);
971 strbuf_reset(&key);
972
dbc92b07
JH
973 if (option_reference.nr)
974 setup_reference();
766ac6a6 975
689f0396
DB
976 fetch_pattern = value.buf;
977 refspec = parse_fetch_refspec(1, &fetch_pattern);
978
979 strbuf_reset(&value);
8434c2f1 980
6f48d39f
NTND
981 remote = remote_get(option_origin);
982 transport = transport_get(remote, remote->url[0]);
822f0c4f
MH
983 transport_set_verbosity(transport, option_verbosity, option_progress);
984
f38aa83f
MB
985 path = get_repo_path(remote->url[0], &is_bundle);
986 is_local = option_local != 0 && path && !is_bundle;
987 if (is_local) {
988 if (option_depth)
989 warning(_("--depth is ignored in local clones; use file:// instead."));
990 if (!access(mkpath("%s/shallow", path), F_OK)) {
991 if (option_local > 0)
992 warning(_("source repository is shallow, ignoring --local"));
993 is_local = 0;
994 }
995 }
996 if (option_local > 0 && !is_local)
997 warning(_("--local is ignored"));
beea4152 998 transport->cloning = 1;
8434c2f1 999
643f918d
JK
1000 if (!transport->get_refs_list || (!is_local && !transport->fetch))
1001 die(_("Don't know how to clone %s"), transport->url);
37b78c25 1002
643f918d 1003 transport_set_option(transport, TRANS_OPT_KEEP, "yes");
8434c2f1 1004
643f918d
JK
1005 if (option_depth)
1006 transport_set_option(transport, TRANS_OPT_DEPTH,
1007 option_depth);
1008 if (option_single_branch)
1009 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
8434c2f1 1010
643f918d
JK
1011 if (option_upload_pack)
1012 transport_set_option(transport, TRANS_OPT_UPLOADPACK,
1013 option_upload_pack);
c6807a40 1014
643f918d
JK
1015 if (transport->smart_options && !option_depth)
1016 transport->smart_options->check_self_contained_and_connected = 1;
8434c2f1 1017
6f48d39f 1018 refs = transport_get_remote_refs(transport);
8434c2f1 1019
5b05795c
MH
1020 if (refs) {
1021 mapped_refs = wanted_peer_refs(refs, refspec);
1022 /*
1023 * transport_get_remote_refs() may return refs with null sha-1
1024 * in mapped_refs (see struct transport->get_refs_list
1025 * comment). In that case we need fetch it early because
1026 * remote_head code below relies on it.
1027 *
1028 * for normal clones, transport_get_remote_refs() should
1029 * return reliable ref set, we can delay cloning until after
1030 * remote HEAD check.
1031 */
1032 for (ref = refs; ref; ref = ref->next)
f4e54d02 1033 if (is_null_oid(&ref->old_oid)) {
5b05795c
MH
1034 complete_refs_before_fetch = 0;
1035 break;
1036 }
90498161 1037
5b05795c
MH
1038 if (!is_local && !complete_refs_before_fetch)
1039 transport_fetch_refs(transport, mapped_refs);
8434c2f1 1040
6cb4e6cc 1041 remote_head = find_ref_by_name(refs, "HEAD");
7a4ee28f
JK
1042 remote_head_points_at =
1043 guess_remote_head(remote_head, mapped_refs, 0);
1044
1045 if (option_branch) {
7a4ee28f 1046 our_head_points_at =
9e585046 1047 find_remote_branch(mapped_refs, option_branch);
7a4ee28f 1048
920b691f
NTND
1049 if (!our_head_points_at)
1050 die(_("Remote branch %s not found in upstream %s"),
1051 option_branch, option_origin);
7a4ee28f
JK
1052 }
1053 else
1054 our_head_points_at = remote_head_points_at;
86ac7518
SR
1055 }
1056 else {
a3552aba
RT
1057 if (option_branch)
1058 die(_("Remote branch %s not found in upstream %s"),
1059 option_branch, option_origin);
1060
e84d7b74 1061 warning(_("You appear to have cloned an empty repository."));
5b05795c 1062 mapped_refs = NULL;
7a4ee28f
JK
1063 our_head_points_at = NULL;
1064 remote_head_points_at = NULL;
86ac7518
SR
1065 remote_head = NULL;
1066 option_no_checkout = 1;
5cd12b85 1067 if (!option_bare)
a9f2c136 1068 install_branch_config(0, "master", option_origin,
5cd12b85 1069 "refs/heads/master");
86ac7518 1070 }
8434c2f1 1071
31b808a0
RT
1072 write_refspec_config(src_ref_prefix, our_head_points_at,
1073 remote_head_points_at, &branch_top);
1074
6f48d39f
NTND
1075 if (is_local)
1076 clone_local(path, git_dir);
90498161 1077 else if (refs && complete_refs_before_fetch)
6f48d39f 1078 transport_fetch_refs(transport, mapped_refs);
8434c2f1 1079
960b7d1c 1080 update_remote_refs(refs, mapped_refs, remote_head_points_at,
45ed4afa 1081 branch_top.buf, reflog_msg.buf, transport, !is_local);
8434c2f1 1082
f034d354 1083 update_head(our_head_points_at, remote_head, reflog_msg.buf);
1db4a75c 1084
6f48d39f
NTND
1085 transport_unlock_pack(transport);
1086 transport_disconnect(transport);
1db4a75c 1087
786b150c
JS
1088 if (option_dissociate) {
1089 close_all_packs();
fb1d6dab 1090 dissociate_from_references();
786b150c 1091 }
fb1d6dab 1092
d3b34622 1093 junk_mode = JUNK_LEAVE_REPO;
c39852c1 1094 err = checkout();
8434c2f1
DB
1095
1096 strbuf_release(&reflog_msg);
b5ff37ac
MV
1097 strbuf_release(&branch_top);
1098 strbuf_release(&key);
1099 strbuf_release(&value);
d3b34622 1100 junk_mode = JUNK_LEAVE_ALL;
50b67732
SB
1101
1102 free(refspec);
dfa7a6c5 1103 return err;
8434c2f1 1104}