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