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