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