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