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