]> git.ipfire.org Git - thirdparty/git.git/blame - builtin/clone.c
Sync with 2.31.5
[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
f8adbec9 11#define USE_THE_INDEX_COMPATIBILITY_MACROS
c2e86add 12#include "builtin.h"
b2141fc1 13#include "config.h"
697cc8ef 14#include "lockfile.h"
8434c2f1
DB
15#include "parse-options.h"
16#include "fetch-pack.h"
17#include "refs.h"
ec0cb496 18#include "refspec.h"
cbd53a21 19#include "object-store.h"
8434c2f1
DB
20#include "tree.h"
21#include "tree-walk.h"
22#include "unpack-trees.h"
23#include "transport.h"
24#include "strbuf.h"
25#include "dir.h"
ff7ccc8c
MT
26#include "dir-iterator.h"
27#include "iterator.h"
4a16d072 28#include "sigchain.h"
a9f2c136 29#include "branch.h"
8ef51733 30#include "remote.h"
dfa7a6c5 31#include "run-command.h"
0433ad12 32#include "connected.h"
3836d88a 33#include "packfile.h"
548719fb 34#include "list-objects-filter-options.h"
8434c2f1
DB
35
36/*
37 * Overall FIXMEs:
38 * - respect DB_ENVIRONMENT for .git/objects.
39 *
40 * Implementation notes:
41 * - dropping use-separate-remote and no-separate-remote compatibility
42 *
43 */
44static const char * const builtin_clone_usage[] = {
9c9b4f2f 45 N_("git clone [<options>] [--] <repo> [<dir>]"),
8434c2f1
DB
46 NULL
47};
48
3e6e0edd 49static int option_no_checkout, option_bare, option_mirror, option_single_branch = -1;
bb62e0a9 50static int option_local = -1, option_no_hardlinks, option_shared;
0dab2468 51static int option_no_tags;
18a74a09 52static int option_shallow_submodules;
4fe788b1
LL
53static int option_reject_shallow = -1; /* unspecified */
54static int config_reject_shallow = -1; /* unspecified */
994c2aaf
NTND
55static int deepen;
56static char *option_template, *option_depth, *option_since;
8434c2f1 57static char *option_origin = NULL;
de9ed3ef 58static char *remote_name = NULL;
7a4ee28f 59static char *option_branch = NULL;
859e5df9 60static struct string_list option_not = STRING_LIST_INIT_NODUP;
b57fb80a 61static const char *real_git_dir;
8434c2f1 62static char *option_upload_pack = "git-upload-pack";
5bd631b3 63static int option_verbosity;
01fdc21f 64static int option_progress = -1;
d89f09c8 65static int option_sparse_checkout;
c915f11e 66static enum transport_family family;
2721ce21 67static struct string_list option_config = STRING_LIST_INIT_NODUP;
5e40800d 68static struct string_list option_required_reference = STRING_LIST_INIT_NODUP;
f7415b4d 69static struct string_list option_optional_reference = STRING_LIST_INIT_NODUP;
fb1d6dab 70static int option_dissociate;
72290d6a 71static int max_jobs = -1;
bb62e0a9 72static struct string_list option_recurse_submodules = STRING_LIST_INIT_NODUP;
548719fb 73static struct list_objects_filter_options filter_options;
6e983059 74static struct string_list server_options = STRING_LIST_INIT_NODUP;
4c691016 75static int option_remote_submodules;
bb62e0a9
BW
76
77static int recurse_submodules_cb(const struct option *opt,
78 const char *arg, int unset)
79{
80 if (unset)
81 string_list_clear((struct string_list *)opt->value, 0);
82 else if (arg)
83 string_list_append((struct string_list *)opt->value, arg);
84 else
85 string_list_append((struct string_list *)opt->value,
86 (const char *)opt->defval);
87
88 return 0;
89}
dbc92b07 90
8434c2f1 91static struct option builtin_clone_options[] = {
5bd631b3 92 OPT__VERBOSITY(&option_verbosity),
01fdc21f 93 OPT_BOOL(0, "progress", &option_progress,
32b77add 94 N_("force progress reporting")),
4fe788b1
LL
95 OPT_BOOL(0, "reject-shallow", &option_reject_shallow,
96 N_("don't clone shallow repository")),
d5d09d47
SB
97 OPT_BOOL('n', "no-checkout", &option_no_checkout,
98 N_("don't create a checkout")),
4741edd5
SB
99 OPT_BOOL(0, "bare", &option_bare, N_("create a bare repository")),
100 OPT_HIDDEN_BOOL(0, "naked", &option_bare,
101 N_("create a bare repository")),
d5d09d47
SB
102 OPT_BOOL(0, "mirror", &option_mirror,
103 N_("create a mirror repository (implies bare)")),
189260b1 104 OPT_BOOL('l', "local", &option_local,
32b77add 105 N_("to clone from a local repository")),
d5d09d47 106 OPT_BOOL(0, "no-hardlinks", &option_no_hardlinks,
32b77add 107 N_("don't use local hardlinks, always copy")),
d5d09d47 108 OPT_BOOL('s', "shared", &option_shared,
32b77add 109 N_("setup as shared repository")),
bb62e0a9
BW
110 { OPTION_CALLBACK, 0, "recurse-submodules", &option_recurse_submodules,
111 N_("pathspec"), N_("initialize submodules in the clone"),
112 PARSE_OPT_OPTARG, recurse_submodules_cb, (intptr_t)"." },
c28b036f 113 OPT_ALIAS(0, "recursive", "recurse-submodules"),
72290d6a
SB
114 OPT_INTEGER('j', "jobs", &max_jobs,
115 N_("number of submodules cloned in parallel")),
32b77add
NTND
116 OPT_STRING(0, "template", &option_template, N_("template-directory"),
117 N_("directory from which templates will be used")),
5e40800d 118 OPT_STRING_LIST(0, "reference", &option_required_reference, N_("repo"),
8ade009c 119 N_("reference repository")),
f7415b4d
SB
120 OPT_STRING_LIST(0, "reference-if-able", &option_optional_reference,
121 N_("repo"), N_("reference repository")),
14f8b9b4
JK
122 OPT_BOOL(0, "dissociate", &option_dissociate,
123 N_("use --reference only while cloning")),
32b77add
NTND
124 OPT_STRING('o', "origin", &option_origin, N_("name"),
125 N_("use <name> instead of 'origin' to track upstream")),
126 OPT_STRING('b', "branch", &option_branch, N_("branch"),
127 N_("checkout <branch> instead of the remote's HEAD")),
128 OPT_STRING('u', "upload-pack", &option_upload_pack, N_("path"),
129 N_("path to git-upload-pack on the remote")),
130 OPT_STRING(0, "depth", &option_depth, N_("depth"),
131 N_("create a shallow clone of that depth")),
994c2aaf
NTND
132 OPT_STRING(0, "shallow-since", &option_since, N_("time"),
133 N_("create a shallow clone since a specific time")),
859e5df9 134 OPT_STRING_LIST(0, "shallow-exclude", &option_not, N_("revision"),
6d873865 135 N_("deepen history of shallow clone, excluding rev")),
3e6e0edd 136 OPT_BOOL(0, "single-branch", &option_single_branch,
32b77add 137 N_("clone only one branch, HEAD or --branch")),
0dab2468
ÆAB
138 OPT_BOOL(0, "no-tags", &option_no_tags,
139 N_("don't clone any tags, and make later fetches not to follow them")),
d22eb044
SB
140 OPT_BOOL(0, "shallow-submodules", &option_shallow_submodules,
141 N_("any cloned submodules will be shallow")),
32b77add
NTND
142 OPT_STRING(0, "separate-git-dir", &real_git_dir, N_("gitdir"),
143 N_("separate git dir from working tree")),
144 OPT_STRING_LIST('c', "config", &option_config, N_("key=value"),
145 N_("set config inside the new repository")),
6e983059
JT
146 OPT_STRING_LIST(0, "server-option", &server_options,
147 N_("server-specific"), N_("option to transmit")),
c915f11e
EW
148 OPT_SET_INT('4', "ipv4", &family, N_("use IPv4 addresses only"),
149 TRANSPORT_FAMILY_IPV4),
150 OPT_SET_INT('6', "ipv6", &family, N_("use IPv6 addresses only"),
151 TRANSPORT_FAMILY_IPV6),
548719fb 152 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
4c691016
BA
153 OPT_BOOL(0, "remote-submodules", &option_remote_submodules,
154 N_("any cloned submodules will use their remote-tracking branch")),
d89f09c8
DS
155 OPT_BOOL(0, "sparse", &option_sparse_checkout,
156 N_("initialize sparse-checkout file to include only files at root")),
8434c2f1
DB
157 OPT_END()
158};
159
0ea68e42 160static const char *get_repo_path_1(struct strbuf *path, int *is_bundle)
8434c2f1 161{
b3256eb8 162 static char *suffix[] = { "/.git", "", ".git/.git", ".git" };
8434c2f1 163 static char *bundle_suffix[] = { ".bundle", "" };
0ea68e42 164 size_t baselen = path->len;
8434c2f1
DB
165 struct stat st;
166 int i;
167
168 for (i = 0; i < ARRAY_SIZE(suffix); i++) {
0ea68e42
JK
169 strbuf_setlen(path, baselen);
170 strbuf_addstr(path, suffix[i]);
171 if (stat(path->buf, &st))
9b0ebc72 172 continue;
0ea68e42 173 if (S_ISDIR(st.st_mode) && is_git_directory(path->buf)) {
8434c2f1 174 *is_bundle = 0;
0ea68e42 175 return path->buf;
9b0ebc72
NTND
176 } else if (S_ISREG(st.st_mode) && st.st_size > 8) {
177 /* Is it a "gitfile"? */
178 char signature[8];
0ea68e42
JK
179 const char *dst;
180 int len, fd = open(path->buf, O_RDONLY);
9b0ebc72
NTND
181 if (fd < 0)
182 continue;
183 len = read_in_full(fd, signature, 8);
184 close(fd);
185 if (len != 8 || strncmp(signature, "gitdir: ", 8))
186 continue;
0ea68e42
JK
187 dst = read_gitfile(path->buf);
188 if (dst) {
9b0ebc72 189 *is_bundle = 0;
0ea68e42 190 return dst;
9b0ebc72 191 }
8434c2f1
DB
192 }
193 }
194
195 for (i = 0; i < ARRAY_SIZE(bundle_suffix); i++) {
0ea68e42
JK
196 strbuf_setlen(path, baselen);
197 strbuf_addstr(path, bundle_suffix[i]);
198 if (!stat(path->buf, &st) && S_ISREG(st.st_mode)) {
8434c2f1 199 *is_bundle = 1;
0ea68e42 200 return path->buf;
8434c2f1
DB
201 }
202 }
203
204 return NULL;
205}
206
0ea68e42
JK
207static char *get_repo_path(const char *repo, int *is_bundle)
208{
209 struct strbuf path = STRBUF_INIT;
210 const char *raw;
211 char *canon;
212
213 strbuf_addstr(&path, repo);
214 raw = get_repo_path_1(&path, is_bundle);
0aaad415 215 canon = raw ? absolute_pathdup(raw) : NULL;
0ea68e42
JK
216 strbuf_release(&path);
217 return canon;
218}
219
6612f877 220static char *guess_dir_name(const char *repo, int is_bundle, int is_bare)
8434c2f1 221{
e8959867 222 const char *end = repo + strlen(repo), *start, *ptr;
7e837c64 223 size_t len;
8a94bc7b 224 char *dir;
b8c5db35 225
e8959867
PS
226 /*
227 * Skip scheme.
228 */
229 start = strstr(repo, "://");
230 if (start == NULL)
231 start = repo;
232 else
233 start += 3;
234
235 /*
236 * Skip authentication data. The stripping does happen
237 * greedily, such that we strip up to the last '@' inside
238 * the host part.
239 */
240 for (ptr = start; ptr < end && !is_dir_sep(*ptr); ptr++) {
241 if (*ptr == '@')
242 start = ptr + 1;
243 }
244
b8c5db35 245 /*
8a94bc7b 246 * Strip trailing spaces, slashes and /.git
b8c5db35 247 */
e8959867 248 while (start < end && (is_dir_sep(end[-1]) || isspace(end[-1])))
b8c5db35 249 end--;
e8959867 250 if (end - start > 5 && is_dir_sep(end[-5]) &&
b8c5db35
JS
251 !strncmp(end - 4, ".git", 4)) {
252 end -= 5;
e8959867 253 while (start < end && is_dir_sep(end[-1]))
b8c5db35
JS
254 end--;
255 }
256
257 /*
92722efe
PS
258 * Strip trailing port number if we've got only a
259 * hostname (that is, there is no dir separator but a
260 * colon). This check is required such that we do not
261 * strip URI's like '/foo/bar:2222.git', which should
262 * result in a dir '2222' being guessed due to backwards
263 * compatibility.
264 */
265 if (memchr(start, '/', end - start) == NULL
266 && memchr(start, ':', end - start) != NULL) {
267 ptr = end;
268 while (start < ptr && isdigit(ptr[-1]) && ptr[-1] != ':')
269 ptr--;
270 if (start < ptr && ptr[-1] == ':')
271 end = ptr - 1;
272 }
273
b8c5db35 274 /*
e8959867
PS
275 * Find last component. To remain backwards compatible we
276 * also regard colons as path separators, such that
277 * cloning a repository 'foo:bar.git' would result in a
278 * directory 'bar' being guessed.
b8c5db35 279 */
e8959867
PS
280 ptr = end;
281 while (start < ptr && !is_dir_sep(ptr[-1]) && ptr[-1] != ':')
282 ptr--;
283 start = ptr;
b8c5db35
JS
284
285 /*
286 * Strip .{bundle,git}.
287 */
db2e2204
JK
288 len = end - start;
289 strip_suffix_mem(start, &len, is_bundle ? ".bundle" : ".git");
8434c2f1 290
adef9561 291 if (!len || (len == 1 && *start == '/'))
39ad4f39
NTND
292 die(_("No directory name could be guessed.\n"
293 "Please specify a directory on the command line"));
adef9561 294
7e837c64
SS
295 if (is_bare)
296 dir = xstrfmt("%.*s.git", (int)len, start);
297 else
298 dir = xstrndup(start, len);
8a94bc7b
AR
299 /*
300 * Replace sequences of 'control' characters and whitespace
301 * with one ascii space, remove leading and trailing spaces.
302 */
303 if (*dir) {
304 char *out = dir;
305 int prev_space = 1 /* strip leading whitespace */;
306 for (end = dir; *end; ++end) {
307 char ch = *end;
308 if ((unsigned char)ch < '\x20')
309 ch = '\x20';
310 if (isspace(ch)) {
311 if (prev_space)
312 continue;
313 prev_space = 1;
314 } else
315 prev_space = 0;
316 *out++ = ch;
317 }
318 *out = '\0';
319 if (out > dir && prev_space)
320 out[-1] = '\0';
6612f877 321 }
8a94bc7b 322 return dir;
8434c2f1
DB
323}
324
44a68fd5
CB
325static void strip_trailing_slashes(char *dir)
326{
327 char *end = dir + strlen(dir);
328
329 while (dir < end - 1 && is_dir_sep(end[-1]))
330 end--;
331 *end = '\0';
332}
333
dbc92b07 334static int add_one_reference(struct string_list_item *item, void *cb_data)
8434c2f1 335{
9eeea7d2 336 struct strbuf err = STRBUF_INIT;
f7415b4d 337 int *required = cb_data;
9eeea7d2 338 char *ref_git = compute_alternate_path(item->string, &err);
8434c2f1 339
f7415b4d
SB
340 if (!ref_git) {
341 if (*required)
342 die("%s", err.buf);
343 else
344 fprintf(stderr,
345 _("info: Could not add alternate for '%s': %s\n"),
346 item->string, err.buf);
347 } else {
348 struct strbuf sb = STRBUF_INIT;
349 strbuf_addf(&sb, "%s/objects", ref_git);
350 add_to_alternates_file(sb.buf);
351 strbuf_release(&sb);
352 }
606e435a 353
9eeea7d2 354 strbuf_release(&err);
f7415b4d 355 free(ref_git);
dbc92b07
JH
356 return 0;
357}
8434c2f1 358
dbc92b07
JH
359static void setup_reference(void)
360{
f7415b4d
SB
361 int required = 1;
362 for_each_string_list(&option_required_reference,
363 add_one_reference, &required);
364 required = 0;
365 for_each_string_list(&option_optional_reference,
366 add_one_reference, &required);
8434c2f1
DB
367}
368
3c1dce88 369static void copy_alternates(struct strbuf *src, const char *src_repo)
e6baf4a1
JH
370{
371 /*
372 * Read from the source objects/info/alternates file
373 * and copy the entries to corresponding file in the
374 * destination repository with add_to_alternates_file().
375 * Both src and dst have "$path/objects/info/alternates".
376 *
377 * Instead of copying bit-for-bit from the original,
378 * we need to append to existing one so that the already
379 * created entry via "clone -s" is not lost, and also
380 * to turn entries with paths relative to the original
381 * absolute, so that they can be used in the new repository.
382 */
02912f47 383 FILE *in = xfopen(src->buf, "r");
e6baf4a1
JH
384 struct strbuf line = STRBUF_INIT;
385
3f163962 386 while (strbuf_getline(&line, in) != EOF) {
dcf69262 387 char *abs_path;
e6baf4a1
JH
388 if (!line.len || line.buf[0] == '#')
389 continue;
390 if (is_absolute_path(line.buf)) {
391 add_to_alternates_file(line.buf);
392 continue;
393 }
dcf69262 394 abs_path = mkpathdup("%s/objects/%s", src_repo, line.buf);
22d3b8de
JK
395 if (!normalize_path_copy(abs_path, abs_path))
396 add_to_alternates_file(abs_path);
397 else
398 warning("skipping invalid relative alternate: %s/%s",
399 src_repo, line.buf);
dcf69262 400 free(abs_path);
e6baf4a1
JH
401 }
402 strbuf_release(&line);
403 fclose(in);
404}
405
14954b79
MT
406static void mkdir_if_missing(const char *pathname, mode_t mode)
407{
408 struct stat st;
409
410 if (!mkdir(pathname, mode))
411 return;
412
413 if (errno != EEXIST)
414 die_errno(_("failed to create directory '%s'"), pathname);
415 else if (stat(pathname, &st))
416 die_errno(_("failed to stat '%s'"), pathname);
417 else if (!S_ISDIR(st.st_mode))
418 die(_("%s exists and is not a directory"), pathname);
419}
420
e6baf4a1 421static void copy_or_link_directory(struct strbuf *src, struct strbuf *dest,
ff7ccc8c 422 const char *src_repo)
8434c2f1 423{
8434c2f1 424 int src_len, dest_len;
ff7ccc8c
MT
425 struct dir_iterator *iter;
426 int iter_status;
3d7747e3 427 struct strbuf realpath = STRBUF_INIT;
8434c2f1 428
14954b79 429 mkdir_if_missing(dest->buf, 0777);
8434c2f1 430
6f054f9f 431 iter = dir_iterator_begin(src->buf, DIR_ITERATOR_PEDANTIC);
ff7ccc8c
MT
432
433 if (!iter)
434 die_errno(_("failed to start iterator over '%s'"), src->buf);
8434c2f1 435
b9e125e0
MV
436 strbuf_addch(src, '/');
437 src_len = src->len;
438 strbuf_addch(dest, '/');
439 dest_len = dest->len;
8434c2f1 440
ff7ccc8c 441 while ((iter_status = dir_iterator_advance(iter)) == ITER_OK) {
b9e125e0 442 strbuf_setlen(src, src_len);
ff7ccc8c 443 strbuf_addstr(src, iter->relative_path);
b9e125e0 444 strbuf_setlen(dest, dest_len);
ff7ccc8c
MT
445 strbuf_addstr(dest, iter->relative_path);
446
6f054f9f
TB
447 if (S_ISLNK(iter->st.st_mode))
448 die(_("symlink '%s' exists, refusing to clone with --local"),
449 iter->relative_path);
450
ff7ccc8c
MT
451 if (S_ISDIR(iter->st.st_mode)) {
452 mkdir_if_missing(dest->buf, 0777);
e6baf4a1
JH
453 continue;
454 }
455
456 /* Files that cannot be copied bit-for-bit... */
c4d9c506 457 if (!fspathcmp(iter->relative_path, "info/alternates")) {
3c1dce88 458 copy_alternates(src, src_repo);
8434c2f1
DB
459 continue;
460 }
461
b9e125e0 462 if (unlink(dest->buf) && errno != ENOENT)
e84d7b74 463 die_errno(_("failed to unlink '%s'"), dest->buf);
fdabc242 464 if (!option_no_hardlinks) {
3d7747e3
AM
465 strbuf_realpath(&realpath, src->buf, 1);
466 if (!link(realpath.buf, dest->buf))
fdabc242 467 continue;
189260b1 468 if (option_local > 0)
e84d7b74 469 die_errno(_("failed to create link '%s'"), dest->buf);
fdabc242 470 option_no_hardlinks = 1;
8434c2f1 471 }
f7835a25 472 if (copy_file_with_time(dest->buf, src->buf, 0666))
e84d7b74 473 die_errno(_("failed to copy file to '%s'"), dest->buf);
8434c2f1 474 }
ff7ccc8c
MT
475
476 if (iter_status != ITER_DONE) {
477 strbuf_setlen(src, src_len);
478 die(_("failed to iterate over '%s'"), src->buf);
479 }
3d7747e3
AM
480
481 strbuf_release(&realpath);
8434c2f1
DB
482}
483
6f48d39f 484static void clone_local(const char *src_repo, const char *dest_repo)
8434c2f1 485{
e6baf4a1
JH
486 if (option_shared) {
487 struct strbuf alt = STRBUF_INIT;
b3b05971
ES
488 get_common_dir(&alt, src_repo);
489 strbuf_addstr(&alt, "/objects");
e6baf4a1
JH
490 add_to_alternates_file(alt.buf);
491 strbuf_release(&alt);
492 } else {
493 struct strbuf src = STRBUF_INIT;
494 struct strbuf dest = STRBUF_INIT;
744e4697
NTND
495 get_common_dir(&src, src_repo);
496 get_common_dir(&dest, dest_repo);
497 strbuf_addstr(&src, "/objects");
498 strbuf_addstr(&dest, "/objects");
ff7ccc8c 499 copy_or_link_directory(&src, &dest, src_repo);
b9e125e0
MV
500 strbuf_release(&src);
501 strbuf_release(&dest);
8434c2f1
DB
502 }
503
28ba96ab 504 if (0 <= option_verbosity)
68b939b2 505 fprintf(stderr, _("done.\n"));
8434c2f1
DB
506}
507
508static const char *junk_work_tree;
d45420c1 509static int junk_work_tree_flags;
8434c2f1 510static const char *junk_git_dir;
d45420c1 511static int junk_git_dir_flags;
85064630 512static enum {
d3b34622
JK
513 JUNK_LEAVE_NONE,
514 JUNK_LEAVE_REPO,
515 JUNK_LEAVE_ALL
516} junk_mode = JUNK_LEAVE_NONE;
517
518static const char junk_leave_repo_msg[] =
519N_("Clone succeeded, but checkout failed.\n"
520 "You can inspect what was checked out with 'git status'\n"
80f537f7 521 "and retry with 'git restore --source=HEAD :/'\n");
8434c2f1
DB
522
523static void remove_junk(void)
524{
f285a2d7 525 struct strbuf sb = STRBUF_INIT;
d3b34622
JK
526
527 switch (junk_mode) {
528 case JUNK_LEAVE_REPO:
529 warning("%s", _(junk_leave_repo_msg));
530 /* fall-through */
531 case JUNK_LEAVE_ALL:
532 return;
533 default:
534 /* proceed to removal */
535 break;
536 }
537
8434c2f1
DB
538 if (junk_git_dir) {
539 strbuf_addstr(&sb, junk_git_dir);
d45420c1 540 remove_dir_recursively(&sb, junk_git_dir_flags);
8434c2f1
DB
541 strbuf_reset(&sb);
542 }
543 if (junk_work_tree) {
544 strbuf_addstr(&sb, junk_work_tree);
d45420c1 545 remove_dir_recursively(&sb, junk_work_tree_flags);
8434c2f1 546 }
9c18b548 547 strbuf_release(&sb);
8434c2f1
DB
548}
549
550static void remove_junk_on_signal(int signo)
551{
552 remove_junk();
4a16d072 553 sigchain_pop(signo);
8434c2f1
DB
554 raise(signo);
555}
556
9e585046
NTND
557static struct ref *find_remote_branch(const struct ref *refs, const char *branch)
558{
559 struct ref *ref;
560 struct strbuf head = STRBUF_INIT;
561 strbuf_addstr(&head, "refs/heads/");
562 strbuf_addstr(&head, branch);
563 ref = find_ref_by_name(refs, head.buf);
564 strbuf_release(&head);
5a7d5b68
NTND
565
566 if (ref)
567 return ref;
568
569 strbuf_addstr(&head, "refs/tags/");
570 strbuf_addstr(&head, branch);
571 ref = find_ref_by_name(refs, head.buf);
572 strbuf_release(&head);
573
9e585046
NTND
574 return ref;
575}
576
5bdc32d3 577static struct ref *wanted_peer_refs(const struct ref *refs,
515be833 578 struct refspec *refspec)
8434c2f1 579{
c1921c18
JK
580 struct ref *head = copy_ref(find_ref_by_name(refs, "HEAD"));
581 struct ref *local_refs = head;
582 struct ref **tail = head ? &head->next : &local_refs;
8434c2f1 583
3e6e0edd
NTND
584 if (option_single_branch) {
585 struct ref *remote_head = NULL;
586
587 if (!option_branch)
588 remote_head = guess_remote_head(head, refs, 0);
0ec4b165
NTND
589 else {
590 local_refs = NULL;
591 tail = &local_refs;
592 remote_head = copy_ref(find_remote_branch(refs, option_branch));
593 }
3e6e0edd
NTND
594
595 if (!remote_head && option_branch)
596 warning(_("Could not find remote branch %s to clone."),
597 option_branch);
5a7d5b68 598 else {
515be833
SG
599 int i;
600 for (i = 0; i < refspec->nr; i++)
601 get_fetch_map(remote_head, &refspec->items[i],
602 &tail, 0);
5a7d5b68
NTND
603
604 /* if --branch=tag, pull the requested tag explicitly */
605 get_fetch_map(remote_head, tag_refspec, &tail, 0);
606 }
515be833
SG
607 } else {
608 int i;
609 for (i = 0; i < refspec->nr; i++)
610 get_fetch_map(refs, &refspec->items[i], &tail, 0);
611 }
3e6e0edd 612
0dab2468 613 if (!option_mirror && !option_single_branch && !option_no_tags)
468386a9 614 get_fetch_map(refs, tag_refspec, &tail, 0);
8434c2f1 615
5bdc32d3
NP
616 return local_refs;
617}
618
619static void write_remote_refs(const struct ref *local_refs)
620{
621 const struct ref *r;
622
58f233ce
MH
623 struct ref_transaction *t;
624 struct strbuf err = STRBUF_INIT;
625
626 t = ref_transaction_begin(&err);
627 if (!t)
628 die("%s", err.buf);
9f69d297 629
c1921c18
JK
630 for (r = local_refs; r; r = r->next) {
631 if (!r->peer_ref)
632 continue;
89f3bbdd 633 if (ref_transaction_create(t, r->peer_ref->name, &r->old_oid,
58f233ce
MH
634 0, NULL, &err))
635 die("%s", err.buf);
c1921c18 636 }
3e8aded2 637
58f233ce
MH
638 if (initial_ref_transaction_commit(t, &err))
639 die("%s", err.buf);
640
641 strbuf_release(&err);
642 ref_transaction_free(t);
8434c2f1
DB
643}
644
3e6e0edd
NTND
645static void write_followtags(const struct ref *refs, const char *msg)
646{
647 const struct ref *ref;
648 for (ref = refs; ref; ref = ref->next) {
59556548 649 if (!starts_with(ref->name, "refs/tags/"))
3e6e0edd 650 continue;
59556548 651 if (ends_with(ref->name, "^{}"))
3e6e0edd 652 continue;
167a575e
JK
653 if (!has_object_file_with_flags(&ref->old_oid,
654 OBJECT_INFO_QUICK |
655 OBJECT_INFO_SKIP_FETCH_OBJECT))
3e6e0edd 656 continue;
ae077771 657 update_ref(msg, ref->name, &ref->old_oid, NULL, 0,
658 UPDATE_REFS_DIE_ON_ERR);
3e6e0edd
NTND
659 }
660}
661
6ccac9ee 662static int iterate_ref_map(void *cb_data, struct object_id *oid)
0433ad12
JK
663{
664 struct ref **rm = cb_data;
665 struct ref *ref = *rm;
666
667 /*
668 * Skip anything missing a peer_ref, which we are not
669 * actually going to write a ref for.
670 */
671 while (ref && !ref->peer_ref)
672 ref = ref->next;
673 /* Returning -1 notes "end of list" to the caller. */
674 if (!ref)
675 return -1;
676
6ccac9ee 677 oidcpy(oid, &ref->old_oid);
0433ad12
JK
678 *rm = ref->next;
679 return 0;
680}
681
960b7d1c
NTND
682static void update_remote_refs(const struct ref *refs,
683 const struct ref *mapped_refs,
684 const struct ref *remote_head_points_at,
685 const char *branch_top,
c6807a40 686 const char *msg,
45ed4afa 687 struct transport *transport,
2b98478c 688 int check_connectivity)
960b7d1c 689{
0433ad12
JK
690 const struct ref *rm = mapped_refs;
691
125a05fd 692 if (check_connectivity) {
7043c707
JK
693 struct check_connected_options opt = CHECK_CONNECTED_INIT;
694
695 opt.transport = transport;
38e590ea 696 opt.progress = transport->progress;
7043c707 697
7043c707 698 if (check_connected(iterate_ref_map, &rm, &opt))
125a05fd
JK
699 die(_("remote did not send all necessary objects"));
700 }
0433ad12 701
960b7d1c 702 if (refs) {
960b7d1c 703 write_remote_refs(mapped_refs);
0dab2468 704 if (option_single_branch && !option_no_tags)
960b7d1c
NTND
705 write_followtags(refs, msg);
706 }
707
708 if (remote_head_points_at && !option_bare) {
709 struct strbuf head_ref = STRBUF_INIT;
710 strbuf_addstr(&head_ref, branch_top);
711 strbuf_addstr(&head_ref, "HEAD");
4be49d75
JK
712 if (create_symref(head_ref.buf,
713 remote_head_points_at->peer_ref->name,
714 msg) < 0)
39ad4f39 715 die(_("unable to update %s"), head_ref.buf);
4be49d75 716 strbuf_release(&head_ref);
960b7d1c
NTND
717 }
718}
719
f034d354
NTND
720static void update_head(const struct ref *our, const struct ref *remote,
721 const char *msg)
722{
cf4fff57
JK
723 const char *head;
724 if (our && skip_prefix(our->name, "refs/heads/", &head)) {
f034d354 725 /* Local default branch link */
4be49d75 726 if (create_symref("HEAD", our->name, NULL) < 0)
39ad4f39 727 die(_("unable to update HEAD"));
f034d354 728 if (!option_bare) {
ae077771 729 update_ref(msg, "HEAD", &our->old_oid, NULL, 0,
f4124112 730 UPDATE_REFS_DIE_ON_ERR);
75ca3906 731 install_branch_config(0, head, remote_name, our->name);
f034d354 732 }
5a7d5b68 733 } else if (our) {
2122f675
SB
734 struct commit *c = lookup_commit_reference(the_repository,
735 &our->old_oid);
5a7d5b68 736 /* --branch specifies a non-branch (i.e. tags), detach HEAD */
91774afc 737 update_ref(msg, "HEAD", &c->object.oid, NULL, REF_NO_DEREF,
ae077771 738 UPDATE_REFS_DIE_ON_ERR);
f034d354
NTND
739 } else if (remote) {
740 /*
741 * We know remote HEAD points to a non-branch, or
920b691f 742 * HEAD points to a branch but we don't know which one.
f034d354
NTND
743 * Detach HEAD in all these cases.
744 */
91774afc 745 update_ref(msg, "HEAD", &remote->old_oid, NULL, REF_NO_DEREF,
ae077771 746 UPDATE_REFS_DIE_ON_ERR);
f034d354
NTND
747 }
748}
749
d89f09c8
DS
750static int git_sparse_checkout_init(const char *repo)
751{
22f9b7f3 752 struct strvec argv = STRVEC_INIT;
d89f09c8 753 int result = 0;
22f9b7f3 754 strvec_pushl(&argv, "-C", repo, "sparse-checkout", "init", NULL);
d89f09c8
DS
755
756 /*
757 * We must apply the setting in the current process
758 * for the later checkout to use the sparse-checkout file.
759 */
760 core_apply_sparse_checkout = 1;
761
d70a9eb6 762 if (run_command_v_opt(argv.v, RUN_GIT_CMD)) {
d89f09c8
DS
763 error(_("failed to initialize sparse-checkout"));
764 result = 1;
765 }
766
22f9b7f3 767 strvec_clear(&argv);
d89f09c8
DS
768 return result;
769}
770
72c5f883 771static int checkout(int submodule_progress)
c39852c1 772{
ddc2cc64 773 struct object_id oid;
c39852c1 774 char *head;
837e34eb 775 struct lock_file lock_file = LOCK_INIT;
c39852c1
NTND
776 struct unpack_trees_options opts;
777 struct tree *tree;
778 struct tree_desc t;
03b86647 779 int err = 0;
c39852c1
NTND
780
781 if (option_no_checkout)
782 return 0;
783
0f2dc722 784 head = resolve_refdup("HEAD", RESOLVE_REF_READING, &oid, NULL);
c39852c1
NTND
785 if (!head) {
786 warning(_("remote HEAD refers to nonexistent ref, "
787 "unable to checkout.\n"));
788 return 0;
789 }
2857093b
NTND
790 if (!strcmp(head, "HEAD")) {
791 if (advice_detached_head)
ddc2cc64 792 detach_advice(oid_to_hex(&oid));
dfc8cdc6 793 FREE_AND_NULL(head);
2857093b 794 } else {
59556548 795 if (!starts_with(head, "refs/heads/"))
c39852c1
NTND
796 die(_("HEAD not found below refs/heads!"));
797 }
c39852c1
NTND
798
799 /* We need to be in the new work tree for the checkout */
800 setup_work_tree();
801
837e34eb 802 hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
c39852c1
NTND
803
804 memset(&opts, 0, sizeof opts);
805 opts.update = 1;
806 opts.merge = 1;
b878579a 807 opts.clone = 1;
c39852c1 808 opts.fn = oneway_merge;
8f63da13 809 opts.verbose_update = (option_verbosity >= 0);
c39852c1
NTND
810 opts.src_index = &the_index;
811 opts.dst_index = &the_index;
dfc8cdc6 812 init_checkout_metadata(&opts.meta, head, &oid, NULL);
c39852c1 813
a9dbc179 814 tree = parse_tree_indirect(&oid);
c39852c1
NTND
815 parse_tree(tree);
816 init_tree_desc(&t, tree->buffer, tree->size);
0aac7bb2
JK
817 if (unpack_trees(1, &t, &opts) < 0)
818 die(_("unable to checkout working tree"));
c39852c1 819
dfc8cdc6 820 free(head);
821
837e34eb 822 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
c39852c1
NTND
823 die(_("unable to write new index file"));
824
14228447 825 err |= run_hook_le(NULL, "post-checkout", oid_to_hex(null_oid()),
ddc2cc64 826 oid_to_hex(&oid), "1", NULL);
c39852c1 827
bb62e0a9 828 if (!err && (option_recurse_submodules.nr > 0)) {
22f9b7f3
JK
829 struct strvec args = STRVEC_INIT;
830 strvec_pushl(&args, "submodule", "update", "--require-init", "--recursive", NULL);
72290d6a 831
18a74a09 832 if (option_shallow_submodules == 1)
22f9b7f3 833 strvec_push(&args, "--depth=1");
d22eb044 834
72290d6a 835 if (max_jobs != -1)
22f9b7f3 836 strvec_pushf(&args, "--jobs=%d", max_jobs);
72290d6a 837
72c5f883 838 if (submodule_progress)
22f9b7f3 839 strvec_push(&args, "--progress");
72c5f883 840
03c004c5 841 if (option_verbosity < 0)
22f9b7f3 842 strvec_push(&args, "--quiet");
03c004c5 843
4c691016 844 if (option_remote_submodules) {
22f9b7f3
JK
845 strvec_push(&args, "--remote");
846 strvec_push(&args, "--no-fetch");
4c691016
BA
847 }
848
132f600b 849 if (option_single_branch >= 0)
22f9b7f3 850 strvec_push(&args, option_single_branch ?
132f600b
ES
851 "--single-branch" :
852 "--no-single-branch");
853
d70a9eb6 854 err = run_command_v_opt(args.v, RUN_GIT_CMD);
22f9b7f3 855 strvec_clear(&args);
72290d6a 856 }
c39852c1
NTND
857
858 return err;
859}
860
552955ed
SB
861static int git_clone_config(const char *k, const char *v, void *cb)
862{
de9ed3ef
SB
863 if (!strcmp(k, "clone.defaultremotename")) {
864 free(remote_name);
865 remote_name = xstrdup(v);
866 }
4fe788b1
LL
867 if (!strcmp(k, "clone.rejectshallow"))
868 config_reject_shallow = git_config_bool(k, v);
869
552955ed
SB
870 return git_default_config(k, v, cb);
871}
872
84054f79
JK
873static int write_one_config(const char *key, const char *value, void *data)
874{
552955ed
SB
875 /*
876 * give git_clone_config a chance to write config values back to the
877 * environment, since git_config_set_multivar_gently only deals with
878 * config-file writes
879 */
880 int apply_failed = git_clone_config(key, value, data);
881 if (apply_failed)
882 return apply_failed;
883
db4eca1f
JN
884 return git_config_set_multivar_gently(key,
885 value ? value : "true",
886 CONFIG_REGEX_NONE, 0);
84054f79
JK
887}
888
889static void write_config(struct string_list *config)
890{
891 int i;
892
893 for (i = 0; i < config->nr; i++) {
894 if (git_config_parse_parameter(config->items[i].string,
895 write_one_config, NULL) < 0)
39ad4f39 896 die(_("unable to write parameters to config file"));
84054f79
JK
897 }
898}
899
24d36f14
DA
900static void write_refspec_config(const char *src_ref_prefix,
901 const struct ref *our_head_points_at,
902 const struct ref *remote_head_points_at,
903 struct strbuf *branch_top)
31b808a0
RT
904{
905 struct strbuf key = STRBUF_INIT;
906 struct strbuf value = STRBUF_INIT;
907
908 if (option_mirror || !option_bare) {
909 if (option_single_branch && !option_mirror) {
910 if (option_branch) {
60a5f5fc 911 if (starts_with(our_head_points_at->name, "refs/tags/"))
31b808a0
RT
912 strbuf_addf(&value, "+%s:%s", our_head_points_at->name,
913 our_head_points_at->name);
914 else
915 strbuf_addf(&value, "+%s:%s%s", our_head_points_at->name,
916 branch_top->buf, option_branch);
917 } else if (remote_head_points_at) {
cf4fff57
JK
918 const char *head = remote_head_points_at->name;
919 if (!skip_prefix(head, "refs/heads/", &head))
033abf97 920 BUG("remote HEAD points at non-head?");
cf4fff57 921
31b808a0 922 strbuf_addf(&value, "+%s:%s%s", remote_head_points_at->name,
cf4fff57 923 branch_top->buf, head);
31b808a0
RT
924 }
925 /*
926 * otherwise, the next "git fetch" will
927 * simply fetch from HEAD without updating
d6ac1d21 928 * any remote-tracking branch, which is what
31b808a0
RT
929 * we want.
930 */
931 } else {
932 strbuf_addf(&value, "+%s*:%s*", src_ref_prefix, branch_top->buf);
933 }
934 /* Configure the remote */
935 if (value.len) {
75ca3906 936 strbuf_addf(&key, "remote.%s.fetch", remote_name);
31b808a0
RT
937 git_config_set_multivar(key.buf, value.buf, "^$", 0);
938 strbuf_reset(&key);
939
940 if (option_mirror) {
75ca3906 941 strbuf_addf(&key, "remote.%s.mirror", remote_name);
31b808a0
RT
942 git_config_set(key.buf, "true");
943 strbuf_reset(&key);
944 }
945 }
946 }
947
948 strbuf_release(&key);
949 strbuf_release(&value);
950}
951
fb1d6dab
JH
952static void dissociate_from_references(void)
953{
954 static const char* argv[] = { "repack", "-a", "-d", NULL };
0181681e 955 char *alternates = git_pathdup("objects/info/alternates");
fb1d6dab 956
0181681e
AR
957 if (!access(alternates, F_OK)) {
958 if (run_command_v_opt(argv, RUN_GIT_CMD|RUN_COMMAND_NO_STDIN))
959 die(_("cannot repack to clean up"));
960 if (unlink(alternates) && errno != ENOENT)
961 die_errno(_("cannot unlink temporary alternates file"));
962 }
963 free(alternates);
fb1d6dab
JH
964}
965
6c020421 966static int path_exists(const char *path)
f9e377ad
JK
967{
968 struct stat sb;
969 return !stat(path, &sb);
970}
971
8434c2f1
DB
972int cmd_clone(int argc, const char **argv, const char *prefix)
973{
24c61c44 974 int is_bundle = 0, is_local;
4fe788b1 975 int reject_shallow = 0;
8434c2f1 976 const char *repo_name, *repo, *work_tree, *git_dir;
0c454273 977 char *path = NULL, *dir, *display_repo = NULL;
dfaa209a 978 int dest_exists, real_dest_exists = 0;
37148311 979 const struct ref *refs, *remote_head;
0c454273 980 struct ref *remote_head_points_at = NULL;
7a4ee28f 981 const struct ref *our_head_points_at;
37148311 982 struct ref *mapped_refs;
90498161 983 const struct ref *ref;
3e42cb3b 984 struct strbuf key = STRBUF_INIT;
b5ff37ac 985 struct strbuf branch_top = STRBUF_INIT, reflog_msg = STRBUF_INIT;
1db4a75c 986 struct transport *transport = NULL;
9e585046 987 const char *src_ref_prefix = "refs/heads/";
6f48d39f 988 struct remote *remote;
90498161 989 int err = 0, complete_refs_before_fetch = 1;
72c5f883 990 int submodule_progress;
8434c2f1 991
39835409
JT
992 struct transport_ls_refs_options transport_ls_refs_options =
993 TRANSPORT_LS_REFS_OPTIONS_INIT;
8434c2f1 994
bbc30f99 995 packet_trace_identity("clone");
552955ed
SB
996
997 git_config(git_clone_config, NULL);
998
37782920 999 argc = parse_options(argc, argv, prefix, builtin_clone_options,
8434c2f1
DB
1000 builtin_clone_usage, 0);
1001
d52dc4b1 1002 if (argc > 2)
e84d7b74 1003 usage_msg_opt(_("Too many arguments."),
d52dc4b1
JN
1004 builtin_clone_usage, builtin_clone_options);
1005
8434c2f1 1006 if (argc == 0)
e84d7b74 1007 usage_msg_opt(_("You must specify a repository to clone."),
d52dc4b1 1008 builtin_clone_usage, builtin_clone_options);
8434c2f1 1009
859e5df9 1010 if (option_depth || option_since || option_not.nr)
994c2aaf 1011 deepen = 1;
3e6e0edd 1012 if (option_single_branch == -1)
994c2aaf 1013 option_single_branch = deepen ? 1 : 0;
3e6e0edd 1014
bc699afc
JS
1015 if (option_mirror)
1016 option_bare = 1;
1017
8434c2f1
DB
1018 if (option_bare) {
1019 if (option_origin)
e84d7b74 1020 die(_("--bare and --origin %s options are incompatible."),
8434c2f1 1021 option_origin);
95b63f1e
NTND
1022 if (real_git_dir)
1023 die(_("--bare and --separate-git-dir are incompatible."));
8434c2f1 1024 option_no_checkout = 1;
8434c2f1
DB
1025 }
1026
8434c2f1
DB
1027 repo_name = argv[0];
1028
1029 path = get_repo_path(repo_name, &is_bundle);
0c454273
AH
1030 if (path) {
1031 FREE_AND_NULL(path);
0aaad415 1032 repo = absolute_pathdup(repo_name);
0c454273 1033 } else if (strchr(repo_name, ':')) {
8434c2f1 1034 repo = repo_name;
46da295a
JS
1035 display_repo = transport_anonymize_url(repo);
1036 } else
1037 die(_("repository '%s' does not exist"), repo_name);
8434c2f1 1038
5594bcad
NTND
1039 /* no need to be strict, transport_set_option() will validate it again */
1040 if (option_depth && atoi(option_depth) < 1)
1041 die(_("depth %s is not a positive number"), option_depth);
1042
8434c2f1
DB
1043 if (argc == 2)
1044 dir = xstrdup(argv[1]);
1045 else
6612f877 1046 dir = guess_dir_name(repo_name, is_bundle, option_bare);
44a68fd5 1047 strip_trailing_slashes(dir);
8434c2f1 1048
6c020421 1049 dest_exists = path_exists(dir);
55892d23 1050 if (dest_exists && !is_empty_dir(dir))
e84d7b74
ÆAB
1051 die(_("destination path '%s' already exists and is not "
1052 "an empty directory."), dir);
8434c2f1 1053
dfaa209a
BW
1054 if (real_git_dir) {
1055 real_dest_exists = path_exists(real_git_dir);
1056 if (real_dest_exists && !is_empty_dir(real_git_dir))
1057 die(_("repository path '%s' already exists and is not "
1058 "an empty directory."), real_git_dir);
1059 }
1060
1061
46da295a
JS
1062 strbuf_addf(&reflog_msg, "clone: from %s",
1063 display_repo ? display_repo : repo);
1064 free(display_repo);
8434c2f1
DB
1065
1066 if (option_bare)
1067 work_tree = NULL;
1068 else {
1069 work_tree = getenv("GIT_WORK_TREE");
6c020421 1070 if (work_tree && path_exists(work_tree))
e84d7b74 1071 die(_("working tree '%s' already exists."), work_tree);
8434c2f1
DB
1072 }
1073
1074 if (option_bare || work_tree)
1075 git_dir = xstrdup(dir);
1076 else {
1077 work_tree = dir;
4e2d094d 1078 git_dir = mkpathdup("%s/.git", dir);
8434c2f1
DB
1079 }
1080
ee0e3872
JK
1081 atexit(remove_junk);
1082 sigchain_push_common(remove_junk_on_signal);
1083
8434c2f1 1084 if (!option_bare) {
8e21d63b 1085 if (safe_create_leading_directories_const(work_tree) < 0)
e84d7b74 1086 die_errno(_("could not create leading directories of '%s'"),
d824cbba 1087 work_tree);
d45420c1
JK
1088 if (dest_exists)
1089 junk_work_tree_flags |= REMOVE_DIR_KEEP_TOPLEVEL;
1090 else if (mkdir(work_tree, 0777))
16eff6c0 1091 die_errno(_("could not create work tree dir '%s'"),
d824cbba 1092 work_tree);
ee0e3872 1093 junk_work_tree = work_tree;
8434c2f1
DB
1094 set_git_work_tree(work_tree);
1095 }
8434c2f1 1096
d45420c1 1097 if (real_git_dir) {
dfaa209a 1098 if (real_dest_exists)
d45420c1
JK
1099 junk_git_dir_flags |= REMOVE_DIR_KEEP_TOPLEVEL;
1100 junk_git_dir = real_git_dir;
1101 } else {
1102 if (dest_exists)
1103 junk_git_dir_flags |= REMOVE_DIR_KEEP_TOPLEVEL;
1104 junk_git_dir = git_dir;
1105 }
8e21d63b 1106 if (safe_create_leading_directories_const(git_dir) < 0)
e84d7b74 1107 die(_("could not create leading directories of '%s'"), git_dir);
b57fb80a 1108
3781fcce
ÆAB
1109 if (0 <= option_verbosity) {
1110 if (option_bare)
68b939b2 1111 fprintf(stderr, _("Cloning into bare repository '%s'...\n"), dir);
3781fcce 1112 else
68b939b2 1113 fprintf(stderr, _("Cloning into '%s'...\n"), dir);
3781fcce 1114 }
31224cbd 1115
bb62e0a9
BW
1116 if (option_recurse_submodules.nr > 0) {
1117 struct string_list_item *item;
1118 struct strbuf sb = STRBUF_INIT;
1119
1120 /* remove duplicates */
1121 string_list_sort(&option_recurse_submodules);
1122 string_list_remove_duplicates(&option_recurse_submodules, 0);
1123
1124 /*
1125 * NEEDSWORK: In a multi-working-tree world, this needs to be
1126 * set in the per-worktree config.
1127 */
1128 for_each_string_list_item(item, &option_recurse_submodules) {
1129 strbuf_addf(&sb, "submodule.active=%s",
1130 item->string);
1131 string_list_append(&option_config,
1132 strbuf_detach(&sb, NULL));
1133 }
1134
31224cbd
SB
1135 if (option_required_reference.nr &&
1136 option_optional_reference.nr)
1137 die(_("clone --recursive is not compatible with "
1138 "both --reference and --reference-if-able"));
1139 else if (option_required_reference.nr) {
1140 string_list_append(&option_config,
1141 "submodule.alternateLocation=superproject");
1142 string_list_append(&option_config,
1143 "submodule.alternateErrorStrategy=die");
1144 } else if (option_optional_reference.nr) {
1145 string_list_append(&option_config,
1146 "submodule.alternateLocation=superproject");
1147 string_list_append(&option_config,
1148 "submodule.alternateErrorStrategy=info");
1149 }
1150 }
1151
32ba12da
JS
1152 init_db(git_dir, real_git_dir, option_template, GIT_HASH_UNKNOWN, NULL,
1153 INIT_DB_QUIET);
33158701
NTND
1154
1155 if (real_git_dir)
1156 git_dir = real_git_dir;
1157
552955ed
SB
1158 /*
1159 * additional config can be injected with -c, make sure it's included
1160 * after init_db, which clears the entire config environment.
1161 */
84054f79 1162 write_config(&option_config);
8434c2f1 1163
552955ed
SB
1164 /*
1165 * re-read config after init_db and write_config to pick up any config
1166 * injected by --template and --config, respectively.
1167 */
1168 git_config(git_clone_config, NULL);
8434c2f1 1169
4fe788b1
LL
1170 /*
1171 * If option_reject_shallow is specified from CLI option,
1172 * ignore config_reject_shallow from git_clone_config.
1173 */
1174 if (config_reject_shallow != -1)
1175 reject_shallow = config_reject_shallow;
1176 if (option_reject_shallow != -1)
1177 reject_shallow = option_reject_shallow;
1178
de9ed3ef
SB
1179 /*
1180 * apply the remote name provided by --origin only after this second
1181 * call to git_config, to ensure it overrides all config-based values.
1182 */
1183 if (option_origin != NULL)
1184 remote_name = xstrdup(option_origin);
1185
1186 if (remote_name == NULL)
1187 remote_name = xstrdup("origin");
1188
1189 if (!valid_remote_name(remote_name))
1190 die(_("'%s' is not a valid remote name"), remote_name);
8434c2f1
DB
1191
1192 if (option_bare) {
bc699afc
JS
1193 if (option_mirror)
1194 src_ref_prefix = "refs/";
b5ff37ac 1195 strbuf_addstr(&branch_top, src_ref_prefix);
8434c2f1
DB
1196
1197 git_config_set("core.bare", "true");
1198 } else {
75ca3906 1199 strbuf_addf(&branch_top, "refs/remotes/%s/", remote_name);
bc699afc 1200 }
8434c2f1 1201
75ca3906 1202 strbuf_addf(&key, "remote.%s.url", remote_name);
df61c889
SR
1203 git_config_set(key.buf, repo);
1204 strbuf_reset(&key);
1205
0dab2468 1206 if (option_no_tags) {
75ca3906 1207 strbuf_addf(&key, "remote.%s.tagOpt", remote_name);
0dab2468
ÆAB
1208 git_config_set(key.buf, "--no-tags");
1209 strbuf_reset(&key);
1210 }
1211
f7415b4d 1212 if (option_required_reference.nr || option_optional_reference.nr)
dbc92b07 1213 setup_reference();
766ac6a6 1214
47dbf10d 1215 if (option_sparse_checkout && git_sparse_checkout_init(dir))
d89f09c8
DS
1216 return 1;
1217
75ca3906 1218 remote = remote_get(remote_name);
689f0396 1219
1af8b8c0
RS
1220 refspec_appendf(&remote->fetch, "+%s*:%s*", src_ref_prefix,
1221 branch_top.buf);
8434c2f1 1222
6f48d39f 1223 transport = transport_get(remote, remote->url[0]);
822f0c4f 1224 transport_set_verbosity(transport, option_verbosity, option_progress);
c915f11e 1225 transport->family = family;
822f0c4f 1226
f38aa83f
MB
1227 path = get_repo_path(remote->url[0], &is_bundle);
1228 is_local = option_local != 0 && path && !is_bundle;
1229 if (is_local) {
1230 if (option_depth)
1231 warning(_("--depth is ignored in local clones; use file:// instead."));
994c2aaf
NTND
1232 if (option_since)
1233 warning(_("--shallow-since is ignored in local clones; use file:// instead."));
859e5df9
NTND
1234 if (option_not.nr)
1235 warning(_("--shallow-exclude is ignored in local clones; use file:// instead."));
548719fb
JT
1236 if (filter_options.choice)
1237 warning(_("--filter is ignored in local clones; use file:// instead."));
f38aa83f 1238 if (!access(mkpath("%s/shallow", path), F_OK)) {
4fe788b1
LL
1239 if (reject_shallow)
1240 die(_("source repository is shallow, reject to clone."));
f38aa83f
MB
1241 if (option_local > 0)
1242 warning(_("source repository is shallow, ignoring --local"));
1243 is_local = 0;
1244 }
1245 }
1246 if (option_local > 0 && !is_local)
1247 warning(_("--local is ignored"));
beea4152 1248 transport->cloning = 1;
8434c2f1 1249
643f918d 1250 transport_set_option(transport, TRANS_OPT_KEEP, "yes");
8434c2f1 1251
4fe788b1
LL
1252 if (reject_shallow)
1253 transport_set_option(transport, TRANS_OPT_REJECT_SHALLOW, "1");
643f918d
JK
1254 if (option_depth)
1255 transport_set_option(transport, TRANS_OPT_DEPTH,
1256 option_depth);
994c2aaf
NTND
1257 if (option_since)
1258 transport_set_option(transport, TRANS_OPT_DEEPEN_SINCE,
1259 option_since);
859e5df9
NTND
1260 if (option_not.nr)
1261 transport_set_option(transport, TRANS_OPT_DEEPEN_NOT,
1262 (const char *)&option_not);
643f918d
JK
1263 if (option_single_branch)
1264 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
8434c2f1 1265
643f918d
JK
1266 if (option_upload_pack)
1267 transport_set_option(transport, TRANS_OPT_UPLOADPACK,
1268 option_upload_pack);
c6807a40 1269
6e983059
JT
1270 if (server_options.nr)
1271 transport->server_options = &server_options;
1272
548719fb 1273 if (filter_options.choice) {
cf9ceb5a
MD
1274 const char *spec =
1275 expand_list_objects_filter_spec(&filter_options);
548719fb 1276 transport_set_option(transport, TRANS_OPT_LIST_OBJECTS_FILTER,
cf9ceb5a 1277 spec);
548719fb
JT
1278 transport_set_option(transport, TRANS_OPT_FROM_PROMISOR, "1");
1279 }
1280
1281 if (transport->smart_options && !deepen && !filter_options.choice)
643f918d 1282 transport->smart_options->check_self_contained_and_connected = 1;
8434c2f1 1283
402c47d9 1284
39835409
JT
1285 strvec_push(&transport_ls_refs_options.ref_prefixes, "HEAD");
1286 refspec_ref_prefixes(&remote->fetch,
1287 &transport_ls_refs_options.ref_prefixes);
402c47d9 1288 if (option_branch)
39835409
JT
1289 expand_ref_prefix(&transport_ls_refs_options.ref_prefixes,
1290 option_branch);
402c47d9 1291 if (!option_no_tags)
39835409
JT
1292 strvec_push(&transport_ls_refs_options.ref_prefixes,
1293 "refs/tags/");
402c47d9 1294
39835409 1295 refs = transport_get_remote_refs(transport, &transport_ls_refs_options);
8434c2f1 1296
5b05795c 1297 if (refs) {
b65dc2ce 1298 int hash_algo = hash_algo_by_ptr(transport_get_hash_algo(transport));
1299
1300 /*
1301 * Now that we know what algorithm the remote side is using,
1302 * let's set ours to the same thing.
1303 */
47ac9703 1304 initialize_repository_version(hash_algo, 1);
b65dc2ce 1305 repo_set_hash_algo(the_repository, hash_algo);
1306
515be833 1307 mapped_refs = wanted_peer_refs(refs, &remote->fetch);
5b05795c
MH
1308 /*
1309 * transport_get_remote_refs() may return refs with null sha-1
1310 * in mapped_refs (see struct transport->get_refs_list
1311 * comment). In that case we need fetch it early because
1312 * remote_head code below relies on it.
1313 *
1314 * for normal clones, transport_get_remote_refs() should
1315 * return reliable ref set, we can delay cloning until after
1316 * remote HEAD check.
1317 */
1318 for (ref = refs; ref; ref = ref->next)
f4e54d02 1319 if (is_null_oid(&ref->old_oid)) {
5b05795c
MH
1320 complete_refs_before_fetch = 0;
1321 break;
1322 }
90498161 1323
aab179d9
TB
1324 if (!is_local && !complete_refs_before_fetch) {
1325 err = transport_fetch_refs(transport, mapped_refs);
1326 if (err)
1327 goto cleanup;
1328 }
8434c2f1 1329
6cb4e6cc 1330 remote_head = find_ref_by_name(refs, "HEAD");
7a4ee28f
JK
1331 remote_head_points_at =
1332 guess_remote_head(remote_head, mapped_refs, 0);
1333
1334 if (option_branch) {
7a4ee28f 1335 our_head_points_at =
9e585046 1336 find_remote_branch(mapped_refs, option_branch);
7a4ee28f 1337
920b691f
NTND
1338 if (!our_head_points_at)
1339 die(_("Remote branch %s not found in upstream %s"),
75ca3906 1340 option_branch, remote_name);
7a4ee28f
JK
1341 }
1342 else
1343 our_head_points_at = remote_head_points_at;
86ac7518
SR
1344 }
1345 else {
a3552aba
RT
1346 if (option_branch)
1347 die(_("Remote branch %s not found in upstream %s"),
75ca3906 1348 option_branch, remote_name);
a3552aba 1349
e84d7b74 1350 warning(_("You appear to have cloned an empty repository."));
5b05795c 1351 mapped_refs = NULL;
7a4ee28f
JK
1352 our_head_points_at = NULL;
1353 remote_head_points_at = NULL;
86ac7518
SR
1354 remote_head = NULL;
1355 option_no_checkout = 1;
0cc1b475 1356 if (!option_bare) {
4f37d457
JT
1357 const char *branch;
1358 char *ref;
1359
1360 if (transport_ls_refs_options.unborn_head_target &&
1361 skip_prefix(transport_ls_refs_options.unborn_head_target,
1362 "refs/heads/", &branch)) {
1363 ref = transport_ls_refs_options.unborn_head_target;
1364 transport_ls_refs_options.unborn_head_target = NULL;
1365 create_symref("HEAD", ref, reflog_msg.buf);
1366 } else {
69571dfe 1367 branch = git_default_branch_name(0);
4f37d457
JT
1368 ref = xstrfmt("refs/heads/%s", branch);
1369 }
0cc1b475 1370
75ca3906 1371 install_branch_config(0, branch, remote_name, ref);
0cc1b475
JS
1372 free(ref);
1373 }
86ac7518 1374 }
8434c2f1 1375
31b808a0
RT
1376 write_refspec_config(src_ref_prefix, our_head_points_at,
1377 remote_head_points_at, &branch_top);
1378
548719fb 1379 if (filter_options.choice)
75ca3906 1380 partial_clone_register(remote_name, &filter_options);
548719fb 1381
6f48d39f
NTND
1382 if (is_local)
1383 clone_local(path, git_dir);
aab179d9
TB
1384 else if (refs && complete_refs_before_fetch) {
1385 err = transport_fetch_refs(transport, mapped_refs);
1386 if (err)
1387 goto cleanup;
1388 }
8434c2f1 1389
960b7d1c 1390 update_remote_refs(refs, mapped_refs, remote_head_points_at,
548719fb 1391 branch_top.buf, reflog_msg.buf, transport,
2b98478c 1392 !is_local);
8434c2f1 1393
f034d354 1394 update_head(our_head_points_at, remote_head, reflog_msg.buf);
1db4a75c 1395
72c5f883
JK
1396 /*
1397 * We want to show progress for recursive submodule clones iff
1398 * we did so for the main clone. But only the transport knows
1399 * the final decision for this flag, so we need to rescue the value
1400 * before we free the transport.
1401 */
1402 submodule_progress = transport->progress;
1403
6f48d39f
NTND
1404 transport_unlock_pack(transport);
1405 transport_disconnect(transport);
1db4a75c 1406
786b150c 1407 if (option_dissociate) {
2d511cfc 1408 close_object_store(the_repository->objects);
fb1d6dab 1409 dissociate_from_references();
786b150c 1410 }
fb1d6dab 1411
d3b34622 1412 junk_mode = JUNK_LEAVE_REPO;
72c5f883 1413 err = checkout(submodule_progress);
8434c2f1 1414
aab179d9 1415cleanup:
de9ed3ef 1416 free(remote_name);
8434c2f1 1417 strbuf_release(&reflog_msg);
b5ff37ac
MV
1418 strbuf_release(&branch_top);
1419 strbuf_release(&key);
0c454273
AH
1420 free_refs(mapped_refs);
1421 free_refs(remote_head_points_at);
1422 free(dir);
1423 free(path);
1424 UNLEAK(repo);
d3b34622 1425 junk_mode = JUNK_LEAVE_ALL;
50b67732 1426
39835409 1427 strvec_clear(&transport_ls_refs_options.ref_prefixes);
4f37d457 1428 free(transport_ls_refs_options.unborn_head_target);
dfa7a6c5 1429 return err;
8434c2f1 1430}