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