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