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