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