]> git.ipfire.org Git - thirdparty/git.git/blame - builtin/clone.c
l10n: correct indentation of show-branch usage
[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[] = {
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 51static struct string_list option_reference;
fb1d6dab 52static int option_dissociate;
dbc92b07
JH
53
54static int opt_parse_reference(const struct option *opt, const char *arg, int unset)
55{
56 struct string_list *option_reference = opt->value;
57 if (!arg)
58 return -1;
59 string_list_append(option_reference, arg);
60 return 0;
61}
8434c2f1
DB
62
63static struct option builtin_clone_options[] = {
5bd631b3 64 OPT__VERBOSITY(&option_verbosity),
01fdc21f 65 OPT_BOOL(0, "progress", &option_progress,
32b77add 66 N_("force progress reporting")),
d5d09d47
SB
67 OPT_BOOL('n', "no-checkout", &option_no_checkout,
68 N_("don't create a checkout")),
4741edd5
SB
69 OPT_BOOL(0, "bare", &option_bare, N_("create a bare repository")),
70 OPT_HIDDEN_BOOL(0, "naked", &option_bare,
71 N_("create a bare repository")),
d5d09d47
SB
72 OPT_BOOL(0, "mirror", &option_mirror,
73 N_("create a mirror repository (implies bare)")),
189260b1 74 OPT_BOOL('l', "local", &option_local,
32b77add 75 N_("to clone from a local repository")),
d5d09d47 76 OPT_BOOL(0, "no-hardlinks", &option_no_hardlinks,
32b77add 77 N_("don't use local hardlinks, always copy")),
d5d09d47 78 OPT_BOOL('s', "shared", &option_shared,
32b77add 79 N_("setup as shared repository")),
d5d09d47 80 OPT_BOOL(0, "recursive", &option_recursive,
32b77add 81 N_("initialize submodules in the clone")),
d5d09d47 82 OPT_BOOL(0, "recurse-submodules", &option_recursive,
32b77add
NTND
83 N_("initialize submodules in the clone")),
84 OPT_STRING(0, "template", &option_template, N_("template-directory"),
85 N_("directory from which templates will be used")),
86 OPT_CALLBACK(0 , "reference", &option_reference, N_("repo"),
87 N_("reference repository"), &opt_parse_reference),
88 OPT_STRING('o', "origin", &option_origin, N_("name"),
89 N_("use <name> instead of 'origin' to track upstream")),
90 OPT_STRING('b', "branch", &option_branch, N_("branch"),
91 N_("checkout <branch> instead of the remote's HEAD")),
92 OPT_STRING('u', "upload-pack", &option_upload_pack, N_("path"),
93 N_("path to git-upload-pack on the remote")),
94 OPT_STRING(0, "depth", &option_depth, N_("depth"),
95 N_("create a shallow clone of that depth")),
3e6e0edd 96 OPT_BOOL(0, "single-branch", &option_single_branch,
32b77add 97 N_("clone only one branch, HEAD or --branch")),
fb1d6dab
JH
98 OPT_BOOL(0, "dissociate", &option_dissociate,
99 N_("use --reference only while cloning")),
32b77add
NTND
100 OPT_STRING(0, "separate-git-dir", &real_git_dir, N_("gitdir"),
101 N_("separate git dir from working tree")),
102 OPT_STRING_LIST('c', "config", &option_config, N_("key=value"),
103 N_("set config inside the new repository")),
8434c2f1
DB
104 OPT_END()
105};
106
e7fed18a
JH
107static const char *argv_submodule[] = {
108 "submodule", "update", "--init", "--recursive", NULL
109};
110
8434c2f1
DB
111static char *get_repo_path(const char *repo, int *is_bundle)
112{
b3256eb8 113 static char *suffix[] = { "/.git", "", ".git/.git", ".git" };
8434c2f1
DB
114 static char *bundle_suffix[] = { ".bundle", "" };
115 struct stat st;
116 int i;
117
118 for (i = 0; i < ARRAY_SIZE(suffix); i++) {
119 const char *path;
120 path = mkpath("%s%s", repo, suffix[i]);
9b0ebc72
NTND
121 if (stat(path, &st))
122 continue;
b3256eb8 123 if (S_ISDIR(st.st_mode) && is_git_directory(path)) {
8434c2f1 124 *is_bundle = 0;
e2a57aac 125 return xstrdup(absolute_path(path));
9b0ebc72
NTND
126 } else if (S_ISREG(st.st_mode) && st.st_size > 8) {
127 /* Is it a "gitfile"? */
128 char signature[8];
129 int len, fd = open(path, O_RDONLY);
130 if (fd < 0)
131 continue;
132 len = read_in_full(fd, signature, 8);
133 close(fd);
134 if (len != 8 || strncmp(signature, "gitdir: ", 8))
135 continue;
136 path = read_gitfile(path);
137 if (path) {
138 *is_bundle = 0;
139 return xstrdup(absolute_path(path));
140 }
8434c2f1
DB
141 }
142 }
143
144 for (i = 0; i < ARRAY_SIZE(bundle_suffix); i++) {
145 const char *path;
146 path = mkpath("%s%s", repo, bundle_suffix[i]);
147 if (!stat(path, &st) && S_ISREG(st.st_mode)) {
148 *is_bundle = 1;
e2a57aac 149 return xstrdup(absolute_path(path));
8434c2f1
DB
150 }
151 }
152
153 return NULL;
154}
155
6612f877 156static char *guess_dir_name(const char *repo, int is_bundle, int is_bare)
8434c2f1 157{
b8c5db35 158 const char *end = repo + strlen(repo), *start;
8a94bc7b 159 char *dir;
b8c5db35
JS
160
161 /*
8a94bc7b 162 * Strip trailing spaces, slashes and /.git
b8c5db35 163 */
8a94bc7b 164 while (repo < end && (is_dir_sep(end[-1]) || isspace(end[-1])))
b8c5db35
JS
165 end--;
166 if (end - repo > 5 && is_dir_sep(end[-5]) &&
167 !strncmp(end - 4, ".git", 4)) {
168 end -= 5;
169 while (repo < end && is_dir_sep(end[-1]))
170 end--;
171 }
172
173 /*
174 * Find last component, but be prepared that repo could have
175 * the form "remote.example.com:foo.git", i.e. no slash
176 * in the directory part.
177 */
178 start = end;
179 while (repo < start && !is_dir_sep(start[-1]) && start[-1] != ':')
180 start--;
181
182 /*
183 * Strip .{bundle,git}.
184 */
185 if (is_bundle) {
186 if (end - start > 7 && !strncmp(end - 7, ".bundle", 7))
187 end -= 7;
188 } else {
189 if (end - start > 4 && !strncmp(end - 4, ".git", 4))
190 end -= 4;
8434c2f1
DB
191 }
192
6612f877 193 if (is_bare) {
32716a2c
MV
194 struct strbuf result = STRBUF_INIT;
195 strbuf_addf(&result, "%.*s.git", (int)(end - start), start);
2af202be 196 dir = strbuf_detach(&result, NULL);
8a94bc7b
AR
197 } else
198 dir = xstrndup(start, end - start);
199 /*
200 * Replace sequences of 'control' characters and whitespace
201 * with one ascii space, remove leading and trailing spaces.
202 */
203 if (*dir) {
204 char *out = dir;
205 int prev_space = 1 /* strip leading whitespace */;
206 for (end = dir; *end; ++end) {
207 char ch = *end;
208 if ((unsigned char)ch < '\x20')
209 ch = '\x20';
210 if (isspace(ch)) {
211 if (prev_space)
212 continue;
213 prev_space = 1;
214 } else
215 prev_space = 0;
216 *out++ = ch;
217 }
218 *out = '\0';
219 if (out > dir && prev_space)
220 out[-1] = '\0';
6612f877 221 }
8a94bc7b 222 return dir;
8434c2f1
DB
223}
224
44a68fd5
CB
225static void strip_trailing_slashes(char *dir)
226{
227 char *end = dir + strlen(dir);
228
229 while (dir < end - 1 && is_dir_sep(end[-1]))
230 end--;
231 *end = '\0';
232}
233
dbc92b07 234static int add_one_reference(struct string_list_item *item, void *cb_data)
8434c2f1 235{
e6baf4a1 236 char *ref_git;
b552b56d 237 const char *repo;
e6baf4a1 238 struct strbuf alternate = STRBUF_INIT;
8434c2f1 239
b552b56d 240 /* Beware: read_gitfile(), real_path() and mkpath() return static buffer */
e6baf4a1 241 ref_git = xstrdup(real_path(item->string));
b552b56d
AS
242
243 repo = read_gitfile(ref_git);
244 if (!repo)
245 repo = read_gitfile(mkpath("%s/.git", ref_git));
246 if (repo) {
247 free(ref_git);
248 ref_git = xstrdup(repo);
249 }
250
251 if (!repo && is_directory(mkpath("%s/.git/objects", ref_git))) {
4e2d094d 252 char *ref_git_git = mkpathdup("%s/.git", ref_git);
e6baf4a1
JH
253 free(ref_git);
254 ref_git = ref_git_git;
255 } else if (!is_directory(mkpath("%s/objects", ref_git)))
0658569e 256 die(_("reference repository '%s' is not a local repository."),
dbc92b07 257 item->string);
8434c2f1 258
606e435a
NTND
259 if (!access(mkpath("%s/shallow", ref_git), F_OK))
260 die(_("reference repository '%s' is shallow"), item->string);
261
262 if (!access(mkpath("%s/info/grafts", ref_git), F_OK))
263 die(_("reference repository '%s' is grafted"), item->string);
264
e6baf4a1
JH
265 strbuf_addf(&alternate, "%s/objects", ref_git);
266 add_to_alternates_file(alternate.buf);
267 strbuf_release(&alternate);
e6baf4a1 268 free(ref_git);
dbc92b07
JH
269 return 0;
270}
8434c2f1 271
dbc92b07
JH
272static void setup_reference(void)
273{
274 for_each_string_list(&option_reference, add_one_reference, NULL);
8434c2f1
DB
275}
276
e6baf4a1
JH
277static void copy_alternates(struct strbuf *src, struct strbuf *dst,
278 const char *src_repo)
279{
280 /*
281 * Read from the source objects/info/alternates file
282 * and copy the entries to corresponding file in the
283 * destination repository with add_to_alternates_file().
284 * Both src and dst have "$path/objects/info/alternates".
285 *
286 * Instead of copying bit-for-bit from the original,
287 * we need to append to existing one so that the already
288 * created entry via "clone -s" is not lost, and also
289 * to turn entries with paths relative to the original
290 * absolute, so that they can be used in the new repository.
291 */
292 FILE *in = fopen(src->buf, "r");
293 struct strbuf line = STRBUF_INIT;
294
295 while (strbuf_getline(&line, in, '\n') != EOF) {
296 char *abs_path, abs_buf[PATH_MAX];
297 if (!line.len || line.buf[0] == '#')
298 continue;
299 if (is_absolute_path(line.buf)) {
300 add_to_alternates_file(line.buf);
301 continue;
302 }
303 abs_path = mkpath("%s/objects/%s", src_repo, line.buf);
304 normalize_path_copy(abs_buf, abs_path);
305 add_to_alternates_file(abs_buf);
306 }
307 strbuf_release(&line);
308 fclose(in);
309}
310
311static void copy_or_link_directory(struct strbuf *src, struct strbuf *dest,
312 const char *src_repo, int src_baselen)
8434c2f1
DB
313{
314 struct dirent *de;
315 struct stat buf;
316 int src_len, dest_len;
317 DIR *dir;
318
b9e125e0 319 dir = opendir(src->buf);
8434c2f1 320 if (!dir)
e84d7b74 321 die_errno(_("failed to open '%s'"), src->buf);
8434c2f1 322
b9e125e0 323 if (mkdir(dest->buf, 0777)) {
8434c2f1 324 if (errno != EEXIST)
e84d7b74 325 die_errno(_("failed to create directory '%s'"), dest->buf);
b9e125e0 326 else if (stat(dest->buf, &buf))
e84d7b74 327 die_errno(_("failed to stat '%s'"), dest->buf);
8434c2f1 328 else if (!S_ISDIR(buf.st_mode))
e84d7b74 329 die(_("%s exists and is not a directory"), dest->buf);
8434c2f1
DB
330 }
331
b9e125e0
MV
332 strbuf_addch(src, '/');
333 src_len = src->len;
334 strbuf_addch(dest, '/');
335 dest_len = dest->len;
8434c2f1
DB
336
337 while ((de = readdir(dir)) != NULL) {
b9e125e0
MV
338 strbuf_setlen(src, src_len);
339 strbuf_addstr(src, de->d_name);
340 strbuf_setlen(dest, dest_len);
341 strbuf_addstr(dest, de->d_name);
342 if (stat(src->buf, &buf)) {
e84d7b74 343 warning (_("failed to stat %s\n"), src->buf);
8434c2f1
DB
344 continue;
345 }
346 if (S_ISDIR(buf.st_mode)) {
347 if (de->d_name[0] != '.')
e6baf4a1
JH
348 copy_or_link_directory(src, dest,
349 src_repo, src_baselen);
350 continue;
351 }
352
353 /* Files that cannot be copied bit-for-bit... */
354 if (!strcmp(src->buf + src_baselen, "/info/alternates")) {
355 copy_alternates(src, dest, src_repo);
8434c2f1
DB
356 continue;
357 }
358
b9e125e0 359 if (unlink(dest->buf) && errno != ENOENT)
e84d7b74 360 die_errno(_("failed to unlink '%s'"), dest->buf);
fdabc242 361 if (!option_no_hardlinks) {
b9e125e0 362 if (!link(src->buf, dest->buf))
fdabc242 363 continue;
189260b1 364 if (option_local > 0)
e84d7b74 365 die_errno(_("failed to create link '%s'"), dest->buf);
fdabc242 366 option_no_hardlinks = 1;
8434c2f1 367 }
f7835a25 368 if (copy_file_with_time(dest->buf, src->buf, 0666))
e84d7b74 369 die_errno(_("failed to copy file to '%s'"), dest->buf);
8434c2f1 370 }
689ef4d4 371 closedir(dir);
8434c2f1
DB
372}
373
6f48d39f 374static void clone_local(const char *src_repo, const char *dest_repo)
8434c2f1 375{
e6baf4a1
JH
376 if (option_shared) {
377 struct strbuf alt = STRBUF_INIT;
378 strbuf_addf(&alt, "%s/objects", src_repo);
379 add_to_alternates_file(alt.buf);
380 strbuf_release(&alt);
381 } else {
382 struct strbuf src = STRBUF_INIT;
383 struct strbuf dest = STRBUF_INIT;
b9e125e0
MV
384 strbuf_addf(&src, "%s/objects", src_repo);
385 strbuf_addf(&dest, "%s/objects", dest_repo);
e6baf4a1 386 copy_or_link_directory(&src, &dest, src_repo, src.len);
b9e125e0
MV
387 strbuf_release(&src);
388 strbuf_release(&dest);
8434c2f1
DB
389 }
390
28ba96ab 391 if (0 <= option_verbosity)
68b939b2 392 fprintf(stderr, _("done.\n"));
8434c2f1
DB
393}
394
395static const char *junk_work_tree;
396static const char *junk_git_dir;
85064630 397static enum {
d3b34622
JK
398 JUNK_LEAVE_NONE,
399 JUNK_LEAVE_REPO,
400 JUNK_LEAVE_ALL
401} junk_mode = JUNK_LEAVE_NONE;
402
403static const char junk_leave_repo_msg[] =
404N_("Clone succeeded, but checkout failed.\n"
405 "You can inspect what was checked out with 'git status'\n"
406 "and retry the checkout with 'git checkout -f HEAD'\n");
8434c2f1
DB
407
408static void remove_junk(void)
409{
f285a2d7 410 struct strbuf sb = STRBUF_INIT;
d3b34622
JK
411
412 switch (junk_mode) {
413 case JUNK_LEAVE_REPO:
414 warning("%s", _(junk_leave_repo_msg));
415 /* fall-through */
416 case JUNK_LEAVE_ALL:
417 return;
418 default:
419 /* proceed to removal */
420 break;
421 }
422
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
7695d118 626 head = resolve_refdup("HEAD", RESOLVE_REF_READING, sha1, NULL);
c39852c1
NTND
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
fb1d6dab
JH
741static void dissociate_from_references(void)
742{
743 static const char* argv[] = { "repack", "-a", "-d", NULL };
744
745 if (run_command_v_opt(argv, RUN_GIT_CMD|RUN_COMMAND_NO_STDIN))
746 die(_("cannot repack to clean up"));
747 if (unlink(git_path("objects/info/alternates")) && errno != ENOENT)
748 die_errno(_("cannot unlink temporary alternates file"));
749}
750
8434c2f1
DB
751int cmd_clone(int argc, const char **argv, const char *prefix)
752{
24c61c44 753 int is_bundle = 0, is_local;
8434c2f1
DB
754 struct stat buf;
755 const char *repo_name, *repo, *work_tree, *git_dir;
756 char *path, *dir;
55892d23 757 int dest_exists;
37148311 758 const struct ref *refs, *remote_head;
7a4ee28f
JK
759 const struct ref *remote_head_points_at;
760 const struct ref *our_head_points_at;
37148311 761 struct ref *mapped_refs;
90498161 762 const struct ref *ref;
b5ff37ac
MV
763 struct strbuf key = STRBUF_INIT, value = STRBUF_INIT;
764 struct strbuf branch_top = STRBUF_INIT, reflog_msg = STRBUF_INIT;
1db4a75c 765 struct transport *transport = NULL;
9e585046 766 const char *src_ref_prefix = "refs/heads/";
6f48d39f 767 struct remote *remote;
90498161 768 int err = 0, complete_refs_before_fetch = 1;
8434c2f1 769
689f0396
DB
770 struct refspec *refspec;
771 const char *fetch_pattern;
8434c2f1 772
bbc30f99 773 packet_trace_identity("clone");
37782920 774 argc = parse_options(argc, argv, prefix, builtin_clone_options,
8434c2f1
DB
775 builtin_clone_usage, 0);
776
d52dc4b1 777 if (argc > 2)
e84d7b74 778 usage_msg_opt(_("Too many arguments."),
d52dc4b1
JN
779 builtin_clone_usage, builtin_clone_options);
780
8434c2f1 781 if (argc == 0)
e84d7b74 782 usage_msg_opt(_("You must specify a repository to clone."),
d52dc4b1 783 builtin_clone_usage, builtin_clone_options);
8434c2f1 784
3e6e0edd
NTND
785 if (option_single_branch == -1)
786 option_single_branch = option_depth ? 1 : 0;
787
bc699afc
JS
788 if (option_mirror)
789 option_bare = 1;
790
8434c2f1
DB
791 if (option_bare) {
792 if (option_origin)
e84d7b74 793 die(_("--bare and --origin %s options are incompatible."),
8434c2f1 794 option_origin);
95b63f1e
NTND
795 if (real_git_dir)
796 die(_("--bare and --separate-git-dir are incompatible."));
8434c2f1 797 option_no_checkout = 1;
8434c2f1
DB
798 }
799
800 if (!option_origin)
801 option_origin = "origin";
802
803 repo_name = argv[0];
804
805 path = get_repo_path(repo_name, &is_bundle);
806 if (path)
e2a57aac 807 repo = xstrdup(absolute_path(repo_name));
8434c2f1 808 else if (!strchr(repo_name, ':'))
d3e1ddfd 809 die(_("repository '%s' does not exist"), repo_name);
8434c2f1
DB
810 else
811 repo = repo_name;
812
5594bcad
NTND
813 /* no need to be strict, transport_set_option() will validate it again */
814 if (option_depth && atoi(option_depth) < 1)
815 die(_("depth %s is not a positive number"), option_depth);
816
8434c2f1
DB
817 if (argc == 2)
818 dir = xstrdup(argv[1]);
819 else
6612f877 820 dir = guess_dir_name(repo_name, is_bundle, option_bare);
44a68fd5 821 strip_trailing_slashes(dir);
8434c2f1 822
55892d23
AP
823 dest_exists = !stat(dir, &buf);
824 if (dest_exists && !is_empty_dir(dir))
e84d7b74
ÆAB
825 die(_("destination path '%s' already exists and is not "
826 "an empty directory."), dir);
8434c2f1 827
8434c2f1
DB
828 strbuf_addf(&reflog_msg, "clone: from %s", repo);
829
830 if (option_bare)
831 work_tree = NULL;
832 else {
833 work_tree = getenv("GIT_WORK_TREE");
834 if (work_tree && !stat(work_tree, &buf))
e84d7b74 835 die(_("working tree '%s' already exists."), work_tree);
8434c2f1
DB
836 }
837
838 if (option_bare || work_tree)
839 git_dir = xstrdup(dir);
840 else {
841 work_tree = dir;
4e2d094d 842 git_dir = mkpathdup("%s/.git", dir);
8434c2f1
DB
843 }
844
845 if (!option_bare) {
846 junk_work_tree = work_tree;
8e21d63b 847 if (safe_create_leading_directories_const(work_tree) < 0)
e84d7b74 848 die_errno(_("could not create leading directories of '%s'"),
d824cbba 849 work_tree);
45d4fdc2 850 if (!dest_exists && mkdir(work_tree, 0777))
e84d7b74 851 die_errno(_("could not create work tree dir '%s'."),
d824cbba 852 work_tree);
8434c2f1
DB
853 set_git_work_tree(work_tree);
854 }
855 junk_git_dir = git_dir;
856 atexit(remove_junk);
57b235a4 857 sigchain_push_common(remove_junk_on_signal);
8434c2f1 858
8e21d63b 859 if (safe_create_leading_directories_const(git_dir) < 0)
e84d7b74 860 die(_("could not create leading directories of '%s'"), git_dir);
b57fb80a
NTND
861
862 set_git_dir_init(git_dir, real_git_dir, 0);
9be1980b 863 if (real_git_dir) {
b57fb80a 864 git_dir = real_git_dir;
9be1980b
JL
865 junk_git_dir = real_git_dir;
866 }
8434c2f1 867
3781fcce
ÆAB
868 if (0 <= option_verbosity) {
869 if (option_bare)
68b939b2 870 fprintf(stderr, _("Cloning into bare repository '%s'...\n"), dir);
3781fcce 871 else
68b939b2 872 fprintf(stderr, _("Cloning into '%s'...\n"), dir);
3781fcce 873 }
28ba96ab 874 init_db(option_template, INIT_DB_QUIET);
84054f79 875 write_config(&option_config);
8434c2f1 876
9bd81e42 877 git_config(git_default_config, NULL);
8434c2f1
DB
878
879 if (option_bare) {
bc699afc
JS
880 if (option_mirror)
881 src_ref_prefix = "refs/";
b5ff37ac 882 strbuf_addstr(&branch_top, src_ref_prefix);
8434c2f1
DB
883
884 git_config_set("core.bare", "true");
885 } else {
b5ff37ac 886 strbuf_addf(&branch_top, "refs/remotes/%s/", option_origin);
bc699afc 887 }
8434c2f1 888
689f0396 889 strbuf_addf(&value, "+%s*:%s*", src_ref_prefix, branch_top.buf);
df61c889
SR
890 strbuf_addf(&key, "remote.%s.url", option_origin);
891 git_config_set(key.buf, repo);
892 strbuf_reset(&key);
893
dbc92b07
JH
894 if (option_reference.nr)
895 setup_reference();
fb1d6dab
JH
896 else if (option_dissociate) {
897 warning(_("--dissociate given, but there is no --reference"));
898 option_dissociate = 0;
899 }
766ac6a6 900
689f0396
DB
901 fetch_pattern = value.buf;
902 refspec = parse_fetch_refspec(1, &fetch_pattern);
903
904 strbuf_reset(&value);
8434c2f1 905
6f48d39f
NTND
906 remote = remote_get(option_origin);
907 transport = transport_get(remote, remote->url[0]);
f38aa83f
MB
908 path = get_repo_path(remote->url[0], &is_bundle);
909 is_local = option_local != 0 && path && !is_bundle;
910 if (is_local) {
911 if (option_depth)
912 warning(_("--depth is ignored in local clones; use file:// instead."));
913 if (!access(mkpath("%s/shallow", path), F_OK)) {
914 if (option_local > 0)
915 warning(_("source repository is shallow, ignoring --local"));
916 is_local = 0;
917 }
918 }
919 if (option_local > 0 && !is_local)
920 warning(_("--local is ignored"));
beea4152 921 transport->cloning = 1;
8434c2f1 922
643f918d
JK
923 if (!transport->get_refs_list || (!is_local && !transport->fetch))
924 die(_("Don't know how to clone %s"), transport->url);
37b78c25 925
643f918d 926 transport_set_option(transport, TRANS_OPT_KEEP, "yes");
8434c2f1 927
643f918d
JK
928 if (option_depth)
929 transport_set_option(transport, TRANS_OPT_DEPTH,
930 option_depth);
931 if (option_single_branch)
932 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
8434c2f1 933
643f918d 934 transport_set_verbosity(transport, option_verbosity, option_progress);
8434c2f1 935
643f918d
JK
936 if (option_upload_pack)
937 transport_set_option(transport, TRANS_OPT_UPLOADPACK,
938 option_upload_pack);
c6807a40 939
643f918d
JK
940 if (transport->smart_options && !option_depth)
941 transport->smart_options->check_self_contained_and_connected = 1;
8434c2f1 942
6f48d39f 943 refs = transport_get_remote_refs(transport);
8434c2f1 944
5b05795c
MH
945 if (refs) {
946 mapped_refs = wanted_peer_refs(refs, refspec);
947 /*
948 * transport_get_remote_refs() may return refs with null sha-1
949 * in mapped_refs (see struct transport->get_refs_list
950 * comment). In that case we need fetch it early because
951 * remote_head code below relies on it.
952 *
953 * for normal clones, transport_get_remote_refs() should
954 * return reliable ref set, we can delay cloning until after
955 * remote HEAD check.
956 */
957 for (ref = refs; ref; ref = ref->next)
958 if (is_null_sha1(ref->old_sha1)) {
959 complete_refs_before_fetch = 0;
960 break;
961 }
90498161 962
5b05795c
MH
963 if (!is_local && !complete_refs_before_fetch)
964 transport_fetch_refs(transport, mapped_refs);
8434c2f1 965
6cb4e6cc 966 remote_head = find_ref_by_name(refs, "HEAD");
7a4ee28f
JK
967 remote_head_points_at =
968 guess_remote_head(remote_head, mapped_refs, 0);
969
970 if (option_branch) {
7a4ee28f 971 our_head_points_at =
9e585046 972 find_remote_branch(mapped_refs, option_branch);
7a4ee28f 973
920b691f
NTND
974 if (!our_head_points_at)
975 die(_("Remote branch %s not found in upstream %s"),
976 option_branch, option_origin);
7a4ee28f
JK
977 }
978 else
979 our_head_points_at = remote_head_points_at;
86ac7518
SR
980 }
981 else {
a3552aba
RT
982 if (option_branch)
983 die(_("Remote branch %s not found in upstream %s"),
984 option_branch, option_origin);
985
e84d7b74 986 warning(_("You appear to have cloned an empty repository."));
5b05795c 987 mapped_refs = NULL;
7a4ee28f
JK
988 our_head_points_at = NULL;
989 remote_head_points_at = NULL;
86ac7518
SR
990 remote_head = NULL;
991 option_no_checkout = 1;
5cd12b85 992 if (!option_bare)
a9f2c136 993 install_branch_config(0, "master", option_origin,
5cd12b85 994 "refs/heads/master");
86ac7518 995 }
8434c2f1 996
31b808a0
RT
997 write_refspec_config(src_ref_prefix, our_head_points_at,
998 remote_head_points_at, &branch_top);
999
6f48d39f
NTND
1000 if (is_local)
1001 clone_local(path, git_dir);
90498161 1002 else if (refs && complete_refs_before_fetch)
6f48d39f 1003 transport_fetch_refs(transport, mapped_refs);
8434c2f1 1004
960b7d1c 1005 update_remote_refs(refs, mapped_refs, remote_head_points_at,
45ed4afa 1006 branch_top.buf, reflog_msg.buf, transport, !is_local);
8434c2f1 1007
f034d354 1008 update_head(our_head_points_at, remote_head, reflog_msg.buf);
1db4a75c 1009
6f48d39f
NTND
1010 transport_unlock_pack(transport);
1011 transport_disconnect(transport);
1db4a75c 1012
fb1d6dab
JH
1013 if (option_dissociate)
1014 dissociate_from_references();
1015
d3b34622 1016 junk_mode = JUNK_LEAVE_REPO;
c39852c1 1017 err = checkout();
8434c2f1
DB
1018
1019 strbuf_release(&reflog_msg);
b5ff37ac
MV
1020 strbuf_release(&branch_top);
1021 strbuf_release(&key);
1022 strbuf_release(&value);
d3b34622 1023 junk_mode = JUNK_LEAVE_ALL;
50b67732
SB
1024
1025 free(refspec);
dfa7a6c5 1026 return err;
8434c2f1 1027}