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