interplane.Get Omega
Read in your language

git

[Ported from github.com/git/git] Sync with Git 2.56.1

Brought by drakestapleton

branch master Branches Tags History

git / builtin / clone.c

1738 lines · 53209 bytes Raw Blame History
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_REPOSITORY_VARIABLE
12#define DISABLE_SIGN_COMPARE_WARNINGS
13
14#include "builtin.h"
15
16#include "abspath.h"
17#include "advice.h"
18#include "config.h"
19#include "copy.h"
20#include "environment.h"
21#include "gettext.h"
22#include "hex.h"
23#include "lockfile.h"
24#include "parse-options.h"
25#include "refs.h"
26#include "refspec.h"
27#include "object-file.h"
28#include "odb.h"
29#include "tree.h"
30#include "tree-walk.h"
31#include "unpack-trees.h"
32#include "transport.h"
33#include "strbuf.h"
34#include "dir.h"
35#include "dir-iterator.h"
36#include "iterator.h"
37#include "sigchain.h"
38#include "branch.h"
39#include "remote.h"
40#include "run-command.h"
41#include "setup.h"
42#include "connected.h"
43#include "packfile.h"
44#include "path.h"
45#include "pkt-line.h"
46#include "list-objects-filter-options.h"
47#include "hook.h"
48#include "bundle.h"
49#include "bundle-uri.h"
50
51/*
52 * Overall FIXMEs:
53 * - respect DB_ENVIRONMENT for .git/objects.
54 *
55 * Implementation notes:
56 * - dropping use-separate-remote and no-separate-remote compatibility
57 *
58 */
59
60struct clone_opts {
61 int wants_head;
62 int detach;
63};
64#define CLONE_OPTS_INIT { \
65 .wants_head = 1 /* default enabled */ \
66}
67
68static int option_no_checkout, option_bare, option_mirror, option_single_branch = -1;
69static int option_local = -1, option_no_hardlinks, option_shared;
70static int option_tags = 1; /* default enabled */
71static int option_shallow_submodules;
72static int config_reject_shallow = -1; /* unspecified */
73static char *remote_name = NULL;
74static char *option_branch = NULL;
75static int option_verbosity;
76static struct string_list option_required_reference = STRING_LIST_INIT_NODUP;
77static struct string_list option_optional_reference = STRING_LIST_INIT_NODUP;
78static int max_jobs = -1;
79static struct string_list option_recurse_submodules = STRING_LIST_INIT_NODUP;
80static int config_filter_submodules = -1; /* unspecified */
81static int option_remote_submodules;
82
83static int recurse_submodules_cb(const struct option *opt,
84 const char *arg, int unset)
85{
86 if (unset)
87 string_list_clear((struct string_list *)opt->value, 0);
88 else if (arg)
89 string_list_append((struct string_list *)opt->value, arg);
90 else
91 string_list_append((struct string_list *)opt->value,
92 (const char *)opt->defval);
93
94 return 0;
95}
96
97static const char *get_repo_path_1(struct strbuf *path, int *is_bundle)
98{
99 static const char *suffix[] = { "/.git", "", ".git/.git", ".git" };
100 static const char *bundle_suffix[] = { ".bundle", "" };
101 size_t baselen = path->len;
102 struct stat st;
103 int i;
104
105 for (i = 0; i < ARRAY_SIZE(suffix); i++) {
106 strbuf_setlen(path, baselen);
107 strbuf_addstr(path, suffix[i]);
108 if (stat(path->buf, &st))
109 continue;
110 if (S_ISDIR(st.st_mode) && is_git_directory(path->buf)) {
111 *is_bundle = 0;
112 return path->buf;
113 } else if (S_ISREG(st.st_mode) && st.st_size > 8) {
114 /* Is it a "gitfile"? */
115 char signature[8];
116 const char *dst;
117 int len, fd = open(path->buf, O_RDONLY);
118 if (fd < 0)
119 continue;
120 len = read_in_full(fd, signature, 8);
121 close(fd);
122 if (len != 8 || strncmp(signature, "gitdir: ", 8))
123 continue;
124 dst = read_gitfile(path->buf);
125 if (dst) {
126 *is_bundle = 0;
127 return dst;
128 }
129 }
130 }
131
132 for (i = 0; i < ARRAY_SIZE(bundle_suffix); i++) {
133 strbuf_setlen(path, baselen);
134 strbuf_addstr(path, bundle_suffix[i]);
135 if (!stat(path->buf, &st) && S_ISREG(st.st_mode)) {
136 *is_bundle = 1;
137 return path->buf;
138 }
139 }
140
141 return NULL;
142}
143
144static char *get_repo_path(const char *repo, int *is_bundle)
145{
146 struct strbuf path = STRBUF_INIT;
147 const char *raw;
148 char *canon;
149
150 strbuf_addstr(&path, repo);
151 raw = get_repo_path_1(&path, is_bundle);
152 canon = raw ? absolute_pathdup(raw) : NULL;
153 strbuf_release(&path);
154 return canon;
155}
156
157struct collect_alternates_data {
158 struct strvec *alternates;
159 bool required;
160};
161
162static int collect_one_alternate(struct string_list_item *item, void *cb_data)
163{
164 struct collect_alternates_data *data = cb_data;
165 struct strbuf err = STRBUF_INIT;
166 char *ref_git = compute_alternate_path(item->string, &err);
167
168 if (!ref_git) {
169 if (data->required)
170 die("%s", err.buf);
171 else
172 fprintf(stderr,
173 _("info: Could not add alternate for '%s': %s\n"),
174 item->string, err.buf);
175 } else {
176 strvec_pushf(data->alternates, "%s/objects", ref_git);
177 }
178
179 strbuf_release(&err);
180 free(ref_git);
181 return 0;
182}
183
184static void read_alternates(struct strvec *alternates, const char *src_repo)
185{
186 /*
187 * Read from the source objects/info/alternates file
188 * and copy the entries to corresponding file in the
189 * destination repository with add_to_alternates_file().
190 * Both src and dst have "$path/objects/info/alternates".
191 *
192 * Instead of copying bit-for-bit from the original,
193 * we need to append to existing one so that the already
194 * created entry via "clone -s" is not lost, and also
195 * to turn entries with paths relative to the original
196 * absolute, so that they can be used in the new repository.
197 */
198 FILE *in;
199 struct strbuf path = STRBUF_INIT;
200 struct strbuf line = STRBUF_INIT;
201
202 strbuf_addf(&path, "%s/objects/info/alternates", src_repo);
203
204 in = fopen(path.buf, "r");
205 if (!in) {
206 if (errno == ENOENT)
207 goto out;
208 die_errno("could not read alternates file '%s'", path.buf);
209 }
210
211 while (strbuf_getline(&line, in) != EOF) {
212 char *abs_path;
213 if (!line.len || line.buf[0] == '#')
214 continue;
215 if (is_absolute_path(line.buf)) {
216 strvec_push(alternates, line.buf);
217 continue;
218 }
219 abs_path = mkpathdup("%s/objects/%s", src_repo, line.buf);
220 if (!normalize_path_copy(abs_path, abs_path))
221 strvec_push(alternates, abs_path);
222 else
223 warning("skipping invalid relative alternate: %s/%s",
224 src_repo, line.buf);
225 free(abs_path);
226 }
227
228out:
229 strbuf_release(&path);
230 strbuf_release(&line);
231 if (in)
232 fclose(in);
233}
234
235static void collect_alternates(struct strvec *alternates,
236 const char *local_source_repo)
237{
238 if (option_required_reference.nr || option_optional_reference.nr) {
239 struct collect_alternates_data data = {
240 .alternates = alternates,
241 .required = true,
242 };
243
244 for_each_string_list(&option_required_reference,
245 collect_one_alternate, &data);
246 data.required = false;
247 for_each_string_list(&option_optional_reference,
248 collect_one_alternate, &data);
249 }
250
251 if (local_source_repo) {
252 struct strbuf commondir = STRBUF_INIT;
253
254 get_common_dir(&commondir, local_source_repo);
255 if (option_shared)
256 strvec_pushf(alternates, "%s/objects", commondir.buf);
257 else
258 read_alternates(alternates, commondir.buf);
259
260 strbuf_release(&commondir);
261 }
262}
263
264static void mkdir_if_missing(const char *pathname, mode_t mode)
265{
266 struct stat st;
267
268 if (!mkdir(pathname, mode))
269 return;
270
271 if (errno != EEXIST)
272 die_errno(_("failed to create directory '%s'"), pathname);
273 else if (stat(pathname, &st))
274 die_errno(_("failed to stat '%s'"), pathname);
275 else if (!S_ISDIR(st.st_mode))
276 die(_("%s exists and is not a directory"), pathname);
277}
278
279static void copy_or_link_directory(struct strbuf *src, struct strbuf *dest,
280 const char *src_repo)
281{
282 int src_len, dest_len;
283 struct dir_iterator *iter;
284 int iter_status;
285
286 /*
287 * Refuse copying directories by default which aren't owned by us. The
288 * code that performs either the copying or hardlinking is not prepared
289 * to handle various edge cases where an adversary may for example
290 * racily swap out files for symlinks. This can cause us to
291 * inadvertently use the wrong source file.
292 *
293 * Furthermore, even if we were prepared to handle such races safely,
294 * creating hardlinks across user boundaries is an inherently unsafe
295 * operation as the hardlinked files can be rewritten at will by the
296 * potentially-untrusted user. We thus refuse to do so by default.
297 */
298 die_upon_dubious_ownership(NULL, NULL, src_repo);
299
300 mkdir_if_missing(dest->buf, 0777);
301
302 iter = dir_iterator_begin(src->buf, DIR_ITERATOR_PEDANTIC);
303
304 if (!iter) {
305 if (errno == ENOTDIR) {
306 int saved_errno = errno;
307 struct stat st;
308
309 if (!lstat(src->buf, &st) && S_ISLNK(st.st_mode))
310 die(_("'%s' is a symlink, refusing to clone with --local"),
311 src->buf);
312 errno = saved_errno;
313 }
314 die_errno(_("failed to start iterator over '%s'"), src->buf);
315 }
316
317 strbuf_addch(src, '/');
318 src_len = src->len;
319 strbuf_addch(dest, '/');
320 dest_len = dest->len;
321
322 while ((iter_status = dir_iterator_advance(iter)) == ITER_OK) {
323 strbuf_setlen(src, src_len);
324 strbuf_addstr(src, iter->relative_path);
325 strbuf_setlen(dest, dest_len);
326 strbuf_addstr(dest, iter->relative_path);
327
328 if (S_ISLNK(iter->st.st_mode))
329 die(_("symlink '%s' exists, refusing to clone with --local"),
330 iter->relative_path);
331
332 if (S_ISDIR(iter->st.st_mode)) {
333 mkdir_if_missing(dest->buf, 0777);
334 continue;
335 }
336
337 /* Alternates were already handled earlier. */
338 if (!fspathcmp(iter->relative_path, "info/alternates"))
339 continue;
340
341 if (unlink(dest->buf) && errno != ENOENT)
342 die_errno(_("failed to unlink '%s'"), dest->buf);
343 if (!option_no_hardlinks) {
344 if (!link(src->buf, dest->buf)) {
345 struct stat st;
346
347 /*
348 * Sanity-check whether the created hardlink
349 * actually links to the expected file now. This
350 * catches time-of-check-time-of-use bugs in
351 * case the source file was meanwhile swapped.
352 */
353 if (lstat(dest->buf, &st))
354 die(_("hardlink cannot be checked at '%s'"), dest->buf);
355 if (st.st_mode != iter->st.st_mode ||
356 st.st_ino != iter->st.st_ino ||
357 st.st_dev != iter->st.st_dev ||
358 st.st_size != iter->st.st_size ||
359 st.st_uid != iter->st.st_uid ||
360 st.st_gid != iter->st.st_gid)
361 die(_("hardlink different from source at '%s'"), dest->buf);
362
363 continue;
364 }
365 if (option_local > 0)
366 die_errno(_("failed to create link '%s'"), dest->buf);
367 option_no_hardlinks = 1;
368 }
369 if (copy_file_with_time(the_repository, dest->buf, src->buf, 0666))
370 die_errno(_("failed to copy file to '%s'"), dest->buf);
371 }
372
373 if (iter_status != ITER_DONE) {
374 strbuf_setlen(src, src_len);
375 die(_("failed to iterate over '%s'"), src->buf);
376 }
377
378 dir_iterator_free(iter);
379}
380
381static bool is_using_default_object_storage_format(const char *repo_path)
382{
383 struct repository_format format = REPOSITORY_FORMAT_INIT;
384 struct strbuf config = STRBUF_INIT;
385 bool is_default;
386
387 get_common_dir(&config, repo_path);
388 strbuf_addstr(&config, "/config");
389 read_repository_format(&format, config.buf);
390
391 is_default = format.object_storage_format == OBJECT_STORAGE_FORMAT_FILES &&
392 !format.object_storage_payload;
393
394 clear_repository_format(&format);
395 strbuf_release(&config);
396 return is_default;
397}
398
399static void clone_local(const char *src_repo, const char *dest_repo)
400{
401 if (!option_shared) {
402 struct strbuf src = STRBUF_INIT;
403 struct strbuf dest = STRBUF_INIT;
404 get_common_dir(&src, src_repo);
405 get_common_dir(&dest, dest_repo);
406 strbuf_addstr(&src, "/objects");
407 strbuf_addstr(&dest, "/objects");
408 copy_or_link_directory(&src, &dest, src_repo);
409 strbuf_release(&src);
410 strbuf_release(&dest);
411 }
412
413 if (0 <= option_verbosity)
414 fprintf(stderr, _("done.\n"));
415}
416
417static const char *junk_work_tree;
418static int junk_work_tree_flags;
419static const char *junk_git_dir;
420static int junk_git_dir_flags;
421static enum {
422 JUNK_LEAVE_NONE,
423 JUNK_LEAVE_REPO,
424 JUNK_LEAVE_ALL
425} junk_mode = JUNK_LEAVE_NONE;
426
427static const char junk_leave_repo_msg[] =
428N_("Clone succeeded, but checkout failed.\n"
429 "You can inspect what was checked out with 'git status'\n"
430 "and retry with 'git restore --source=HEAD :/'\n");
431
432static void remove_junk(void)
433{
434 struct strbuf sb = STRBUF_INIT;
435
436 switch (junk_mode) {
437 case JUNK_LEAVE_REPO:
438 warning("%s", _(junk_leave_repo_msg));
439 /* fall-through */
440 case JUNK_LEAVE_ALL:
441 return;
442 default:
443 /* proceed to removal */
444 break;
445 }
446
447 if (junk_git_dir) {
448 strbuf_addstr(&sb, junk_git_dir);
449 remove_dir_recursively(&sb, junk_git_dir_flags);
450 strbuf_reset(&sb);
451 }
452 if (junk_work_tree) {
453 strbuf_addstr(&sb, junk_work_tree);
454 remove_dir_recursively(&sb, junk_work_tree_flags);
455 }
456 strbuf_release(&sb);
457}
458
459static void remove_junk_on_signal(int signo)
460{
461 remove_junk();
462 sigchain_pop(signo);
463 raise(signo);
464}
465
466static struct ref *find_remote_branch(const struct ref *refs, const char *branch)
467{
468 struct ref *ref;
469 struct strbuf head = STRBUF_INIT;
470 strbuf_addstr(&head, "refs/heads/");
471 strbuf_addstr(&head, branch);
472 ref = find_ref_by_name(refs, head.buf);
473 strbuf_release(&head);
474
475 if (ref)
476 return ref;
477
478 strbuf_addstr(&head, "refs/tags/");
479 strbuf_addstr(&head, branch);
480 ref = find_ref_by_name(refs, head.buf);
481 strbuf_release(&head);
482
483 return ref;
484}
485
486static struct ref *wanted_peer_refs(struct clone_opts *opts,
487 const struct ref *refs,
488 struct refspec *refspec)
489{
490 struct ref *local_refs = NULL;
491 struct ref **tail = &local_refs;
492 struct ref *to_free = NULL;
493
494 if (opts->wants_head) {
495 struct ref *head = copy_ref(find_ref_by_name(refs, "HEAD"));
496 if (head)
497 tail_link_ref(head, &tail);
498 if (option_single_branch)
499 refs = to_free =
500 guess_remote_head(head, refs,
501 REMOTE_GUESS_HEAD_QUIET);
502 } else if (option_single_branch) {
503 local_refs = NULL;
504 tail = &local_refs;
505 refs = to_free = copy_ref(find_remote_branch(refs, option_branch));
506 }
507
508 for (size_t i = 0; i < refspec->nr; i++)
509 get_fetch_map(refs, &refspec->items[i], &tail, 0);
510
511 free_one_ref(to_free);
512
513 return local_refs;
514}
515
516static void write_remote_refs(const struct ref *local_refs)
517{
518 const struct ref *r;
519
520 struct ref_transaction *t;
521 struct strbuf err = STRBUF_INIT;
522
523 t = ref_store_transaction_begin(get_main_ref_store(the_repository),
524 REF_TRANSACTION_FLAG_INITIAL, &err);
525 if (!t)
526 die("%s", err.buf);
527
528 for (r = local_refs; r; r = r->next) {
529 if (!r->peer_ref)
530 continue;
531 if (ref_transaction_create(t, r->peer_ref->name, &r->old_oid,
532 NULL, 0, NULL, &err))
533 die("%s", err.buf);
534 }
535
536 if (ref_transaction_commit(t, &err))
537 die("%s", err.buf);
538
539 strbuf_release(&err);
540 ref_transaction_free(t);
541}
542
543static void write_followtags(const struct ref *refs, const char *msg)
544{
545 const struct ref *ref;
546 for (ref = refs; ref; ref = ref->next) {
547 if (!starts_with(ref->name, "refs/tags/"))
548 continue;
549 if (ends_with(ref->name, "^{}"))
550 continue;
551 if (!odb_has_object(the_repository->objects, &ref->old_oid, 0))
552 continue;
553 refs_update_ref(get_main_ref_store(the_repository), msg,
554 ref->name, &ref->old_oid, NULL, 0,
555 UPDATE_REFS_DIE_ON_ERR);
556 }
557}
558
559static const struct object_id *iterate_ref_map(void *cb_data)
560{
561 struct ref **rm = cb_data;
562 struct ref *ref = *rm;
563
564 /*
565 * Skip anything missing a peer_ref, which we are not
566 * actually going to write a ref for.
567 */
568 while (ref && !ref->peer_ref)
569 ref = ref->next;
570 if (!ref)
571 return NULL;
572
573 *rm = ref->next;
574 return &ref->old_oid;
575}
576
577static void update_remote_refs(const struct ref *refs,
578 const struct ref *mapped_refs,
579 const struct ref *remote_head_points_at,
580 const char *branch_top,
581 const char *msg,
582 struct transport *transport,
583 int check_connectivity)
584{
585 const struct ref *rm = mapped_refs;
586
587 if (check_connectivity) {
588 struct check_connected_options opt = CHECK_CONNECTED_INIT;
589
590 opt.transport = transport;
591 opt.progress = transport->progress;
592
593 if (check_connected(the_repository, iterate_ref_map, &rm, &opt))
594 die(_("remote did not send all necessary objects"));
595 }
596
597 if (refs) {
598 write_remote_refs(mapped_refs);
599 if (option_single_branch && option_tags)
600 write_followtags(refs, msg);
601 }
602
603 if (remote_head_points_at && remote_head_points_at->peer_ref && !option_bare) {
604 struct strbuf head_ref = STRBUF_INIT;
605 strbuf_addstr(&head_ref, branch_top);
606 strbuf_addstr(&head_ref, "HEAD");
607 if (refs_update_symref(get_main_ref_store(the_repository), head_ref.buf,
608 remote_head_points_at->peer_ref->name,
609 msg) < 0)
610 die(_("unable to update %s"), head_ref.buf);
611 strbuf_release(&head_ref);
612 }
613}
614
615static void update_head(struct clone_opts *opts, const struct ref *our, const struct ref *remote,
616 const char *unborn, const char *msg)
617{
618 const char *head;
619 if (our && !opts->detach && skip_prefix(our->name, "refs/heads/", &head)) {
620 /* Local default branch link */
621 if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", our->name, NULL) < 0)
622 die(_("unable to update HEAD"));
623 if (!option_bare) {
624 refs_update_ref(get_main_ref_store(the_repository),
625 msg, "HEAD", &our->old_oid, NULL, 0,
626 UPDATE_REFS_DIE_ON_ERR);
627 install_branch_config(0, head, remote_name, our->name);
628 }
629 } else if (our) {
630 struct commit *c = lookup_commit_or_die(&our->old_oid,
631 our->name);
632
633 /* --branch specifies a non-branch (i.e. tags), detach HEAD */
634 refs_update_ref(get_main_ref_store(the_repository), msg,
635 "HEAD", &c->object.oid, NULL, REF_NO_DEREF,
636 UPDATE_REFS_DIE_ON_ERR);
637 } else if (remote) {
638 /*
639 * We know remote HEAD points to a non-branch, or
640 * HEAD points to a branch but we don't know which one.
641 * Detach HEAD in all these cases.
642 */
643 refs_update_ref(get_main_ref_store(the_repository), msg,
644 "HEAD", &remote->old_oid, NULL, REF_NO_DEREF,
645 UPDATE_REFS_DIE_ON_ERR);
646 } else if (unborn && skip_prefix(unborn, "refs/heads/", &head)) {
647 /*
648 * Unborn head from remote; same as "our" case above except
649 * that we have no ref to update.
650 */
651 if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", unborn, NULL) < 0)
652 die(_("unable to update HEAD"));
653 if (!option_bare)
654 install_branch_config(0, head, remote_name, unborn);
655 }
656}
657
658static int git_sparse_checkout_init(const char *repo)
659{
660 struct child_process cmd = CHILD_PROCESS_INIT;
661 int result = 0;
662 struct repo_config_values *cfg = repo_config_values(the_repository);
663
664 strvec_pushl(&cmd.args, "-C", repo, "sparse-checkout", "set", NULL);
665
666 /*
667 * We must apply the setting in the current process
668 * for the later checkout to use the sparse-checkout file.
669 */
670 cfg->apply_sparse_checkout = 1;
671
672 cmd.git_cmd = 1;
673 if (run_command(&cmd)) {
674 error(_("failed to initialize sparse-checkout"));
675 result = 1;
676 }
677
678 return result;
679}
680
681static int checkout(int submodule_progress,
682 struct list_objects_filter_options *filter_options,
683 int filter_submodules,
684 enum ref_storage_format ref_storage_format,
685 enum object_storage_format object_storage_format)
686{
687 struct object_id oid;
688 char *head;
689 struct lock_file lock_file = LOCK_INIT;
690 struct unpack_trees_options opts;
691 struct tree *tree;
692 struct tree_desc t;
693 int err = 0;
694 struct run_hooks_opt hook_opt = RUN_HOOKS_OPT_INIT_FORCE_SERIAL;
695
696 if (option_no_checkout)
697 return 0;
698
699 head = refs_resolve_refdup(get_main_ref_store(the_repository), "HEAD",
700 RESOLVE_REF_READING, &oid, NULL);
701 if (!head) {
702 warning(_("remote HEAD refers to nonexistent ref, "
703 "unable to checkout"));
704 return 0;
705 }
706 if (!strcmp(head, "HEAD")) {
707 if (advice_enabled(ADVICE_DETACHED_HEAD))
708 detach_advice(oid_to_hex(&oid));
709 FREE_AND_NULL(head);
710 } else {
711 if (!starts_with(head, "refs/heads/"))
712 die(_("HEAD not found below refs/heads!"));
713 }
714
715 /* We need to be in the new work tree for the checkout */
716 setup_work_tree(the_repository);
717
718 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
719
720 memset(&opts, 0, sizeof opts);
721 opts.update = 1;
722 opts.merge = 1;
723 opts.clone = 1;
724 opts.preserve_ignored = 0;
725 opts.fn = oneway_merge;
726 opts.verbose_update = (option_verbosity >= 0);
727 opts.src_index = the_repository->index;
728 opts.dst_index = the_repository->index;
729 init_checkout_metadata(&opts.meta, head, &oid, NULL);
730
731 tree = repo_parse_tree_indirect(the_repository, &oid);
732 if (!tree)
733 die(_("unable to parse commit %s"), oid_to_hex(&oid));
734 if (repo_parse_tree(the_repository, tree) < 0)
735 exit(128);
736 init_tree_desc(&t, &tree->object.oid, tree->buffer, tree->size);
737 if (unpack_trees(1, &t, &opts) < 0)
738 die(_("unable to checkout working tree"));
739
740 free(head);
741
742 if (write_locked_index(the_repository->index, &lock_file, COMMIT_LOCK))
743 die(_("unable to write new index file"));
744
745 strvec_pushl(&hook_opt.args, oid_to_hex(null_oid(the_hash_algo)),
746 oid_to_hex(&oid), "1", NULL);
747 err |= run_hooks_opt(the_repository, "post-checkout", &hook_opt);
748
749 if (!err && (option_recurse_submodules.nr > 0)) {
750 struct child_process cmd = CHILD_PROCESS_INIT;
751 strvec_pushl(&cmd.args, "submodule", "update", "--require-init",
752 "--recursive", NULL);
753
754 if (option_shallow_submodules == 1)
755 strvec_push(&cmd.args, "--depth=1");
756
757 if (max_jobs != -1)
758 strvec_pushf(&cmd.args, "--jobs=%d", max_jobs);
759
760 if (submodule_progress)
761 strvec_push(&cmd.args, "--progress");
762
763 if (option_verbosity < 0)
764 strvec_push(&cmd.args, "--quiet");
765
766 if (option_remote_submodules) {
767 strvec_push(&cmd.args, "--remote");
768 strvec_push(&cmd.args, "--no-fetch");
769 }
770
771 if (ref_storage_format != REF_STORAGE_FORMAT_UNKNOWN)
772 strvec_pushf(&cmd.args, "--ref-storage-format=%s",
773 ref_storage_format_to_name(ref_storage_format));
774
775 if (object_storage_format != OBJECT_STORAGE_FORMAT_UNKNOWN)
776 strvec_pushf(&cmd.args, "--object-storage-format=%s",
777 object_storage_format_to_name(object_storage_format));
778
779 if (filter_submodules && filter_options->choice)
780 strvec_pushf(&cmd.args, "--filter=%s",
781 expand_list_objects_filter_spec(filter_options));
782
783 if (option_single_branch >= 0)
784 strvec_push(&cmd.args, option_single_branch ?
785 "--single-branch" :
786 "--no-single-branch");
787
788 cmd.git_cmd = 1;
789 err = run_command(&cmd);
790 }
791
792 return err;
793}
794
795static int git_clone_config(const char *k, const char *v,
796 const struct config_context *ctx, void *cb)
797{
798 if (!strcmp(k, "clone.defaultremotename")) {
799 if (!v)
800 return config_error_nonbool(k);
801 free(remote_name);
802 remote_name = xstrdup(v);
803 }
804 if (!strcmp(k, "clone.rejectshallow"))
805 config_reject_shallow = git_config_bool(k, v);
806 if (!strcmp(k, "clone.filtersubmodules"))
807 config_filter_submodules = git_config_bool(k, v);
808
809 return git_default_config(k, v, ctx, cb);
810}
811
812static int write_one_config(const char *key, const char *value,
813 const struct config_context *ctx,
814 void *data)
815{
816 /*
817 * give git_clone_config a chance to write config values back to the
818 * environment, since repo_config_set_multivar_gently only deals with
819 * config-file writes
820 */
821 int apply_failed = git_clone_config(key, value, ctx, data);
822 if (apply_failed)
823 return apply_failed;
824
825 return repo_config_set_multivar_gently(the_repository, key,
826 value ? value : "true",
827 CONFIG_REGEX_NONE, 0);
828}
829
830static void write_config(struct string_list *config)
831{
832 int i;
833
834 for (i = 0; i < config->nr; i++) {
835 if (git_config_parse_parameter(config->items[i].string,
836 write_one_config, NULL) < 0)
837 die(_("unable to write parameters to config file"));
838 }
839}
840
841static void write_refspec_config(const char *src_ref_prefix,
842 const struct ref *our_head_points_at,
843 const struct ref *remote_head_points_at,
844 struct strbuf *branch_top)
845{
846 struct strbuf key = STRBUF_INIT;
847 struct strbuf value = STRBUF_INIT;
848
849 if (option_mirror || !option_bare) {
850 if (option_single_branch && !option_mirror) {
851 if (option_branch) {
852 if (starts_with(our_head_points_at->name, "refs/tags/"))
853 strbuf_addf(&value, "+%s:%s", our_head_points_at->name,
854 our_head_points_at->name);
855 else
856 strbuf_addf(&value, "+%s:%s%s", our_head_points_at->name,
857 branch_top->buf, option_branch);
858 } else if (remote_head_points_at) {
859 const char *head = remote_head_points_at->name;
860 if (!skip_prefix(head, "refs/heads/", &head))
861 BUG("remote HEAD points at non-head?");
862
863 strbuf_addf(&value, "+%s:%s%s", remote_head_points_at->name,
864 branch_top->buf, head);
865 }
866 /*
867 * otherwise, the next "git fetch" will
868 * simply fetch from HEAD without updating
869 * any remote-tracking branch, which is what
870 * we want.
871 */
872 } else {
873 strbuf_addf(&value, "+%s*:%s*", src_ref_prefix, branch_top->buf);
874 }
875 /* Configure the remote */
876 if (value.len) {
877 strbuf_addf(&key, "remote.%s.fetch", remote_name);
878 repo_config_set_multivar(the_repository, key.buf, value.buf, "^$", 0);
879 strbuf_reset(&key);
880
881 if (option_mirror) {
882 strbuf_addf(&key, "remote.%s.mirror", remote_name);
883 repo_config_set(the_repository, key.buf, "true");
884 strbuf_reset(&key);
885 }
886 }
887 }
888
889 strbuf_release(&key);
890 strbuf_release(&value);
891}
892
893static void dissociate_from_references(void)
894{
895 char *alternates = repo_git_path(the_repository, "objects/info/alternates");
896
897 if (!access(alternates, F_OK)) {
898 struct child_process cmd = CHILD_PROCESS_INIT;
899
900 cmd.git_cmd = 1;
901 cmd.no_stdin = 1;
902 strvec_pushl(&cmd.args, "repack", "-a", "-d", NULL);
903 if (run_command(&cmd))
904 die(_("cannot repack to clean up"));
905 if (unlink(alternates) && errno != ENOENT)
906 die_errno(_("cannot unlink temporary alternates file"));
907 }
908 free(alternates);
909}
910
911static int path_exists(const char *path)
912{
913 struct stat sb;
914 return !stat(path, &sb);
915}
916
917int cmd_clone(int argc,
918 const char **argv,
919 const char *prefix,
920 struct repository *repository UNUSED)
921{
922 int is_bundle = 0, is_local;
923 int reject_shallow = 0;
924 const char *repo_name, *repo, *work_tree, *git_dir;
925 char *repo_to_free = NULL;
926 char *path = NULL, *dir, *display_repo = NULL;
927 int dest_exists, real_dest_exists = 0;
928 const struct ref *refs, *remote_head;
929 struct ref *remote_head_points_at = NULL;
930 const struct ref *our_head_points_at;
931 char *unborn_head = NULL;
932 struct ref *mapped_refs = NULL;
933 const struct ref *ref;
934 struct strbuf key = STRBUF_INIT;
935 struct strbuf buf = STRBUF_INIT;
936 struct strbuf branch_top = STRBUF_INIT, reflog_msg = STRBUF_INIT;
937 struct transport *transport = NULL;
938 const char *src_ref_prefix = "refs/heads/";
939 struct remote *remote;
940 int err = 0, complete_refs_before_fetch = 1;
941 int submodule_progress;
942 int filter_submodules = 0;
943 int hash_algo;
944 enum object_storage_format object_storage_format = OBJECT_STORAGE_FORMAT_UNKNOWN;
945 enum ref_storage_format ref_storage_format = REF_STORAGE_FORMAT_UNKNOWN;
946 const int do_not_override_repo_unix_permissions = -1;
947 int option_reject_shallow = -1; /* unspecified */
948 int deepen = 0;
949 char *option_template = NULL, *option_depth = NULL, *option_since = NULL;
950 char *option_origin = NULL;
951 struct string_list option_not = STRING_LIST_INIT_NODUP;
952 const char *real_git_dir = NULL;
953 const char *ref_storage_format_uri = NULL;
954 const char *object_storage_format_uri = NULL;
955 const char *option_upload_pack = "git-upload-pack";
956 int option_progress = -1;
957 int option_sparse_checkout = 0;
958 enum transport_family family = TRANSPORT_FAMILY_ALL;
959 struct string_list option_config = STRING_LIST_INIT_DUP;
960 int option_dissociate = 0;
961 struct list_objects_filter_options filter_options = LIST_OBJECTS_FILTER_INIT;
962 int option_filter_submodules = -1; /* unspecified */
963 struct string_list server_options = STRING_LIST_INIT_NODUP;
964 const char *bundle_uri = NULL;
965 char *option_rev = NULL;
966
967 struct clone_opts opts = CLONE_OPTS_INIT;
968
969 struct transport_ls_refs_options transport_ls_refs_options =
970 TRANSPORT_LS_REFS_OPTIONS_INIT;
971
972 struct option builtin_clone_options[] = {
973 OPT__VERBOSITY(&option_verbosity),
974 OPT_BOOL(0, "progress", &option_progress,
975 N_("force progress reporting")),
976 OPT_BOOL(0, "reject-shallow", &option_reject_shallow,
977 N_("don't clone shallow repository")),
978 OPT_BOOL('n', "no-checkout", &option_no_checkout,
979 N_("don't create a checkout")),
980 OPT_BOOL(0, "bare", &option_bare, N_("create a bare repository")),
981 OPT_HIDDEN_BOOL(0, "naked", &option_bare,
982 N_("create a bare repository")),
983 OPT_BOOL(0, "mirror", &option_mirror,
984 N_("create a mirror repository (implies --bare)")),
985 OPT_BOOL('l', "local", &option_local,
986 N_("to clone from a local repository")),
987 OPT_BOOL(0, "no-hardlinks", &option_no_hardlinks,
988 N_("don't use local hardlinks, always copy")),
989 OPT_BOOL('s', "shared", &option_shared,
990 N_("setup as shared repository")),
991 {
992 .type = OPTION_CALLBACK,
993 .long_name = "recurse-submodules",
994 .value = &option_recurse_submodules,
995 .argh = N_("pathspec"),
996 .help = N_("initialize submodules in the clone"),
997 .flags = PARSE_OPT_OPTARG,
998 .callback = recurse_submodules_cb,
999 .defval = (intptr_t)".",
1000 },
1001 OPT_ALIAS(0, "recursive", "recurse-submodules"),
1002 OPT_INTEGER('j', "jobs", &max_jobs,
1003 N_("number of submodules cloned in parallel")),
1004 OPT_STRING(0, "template", &option_template, N_("template-directory"),
1005 N_("directory from which templates will be used")),
1006 OPT_STRING_LIST(0, "reference", &option_required_reference, N_("repo"),
1007 N_("reference repository")),
1008 OPT_STRING_LIST(0, "reference-if-able", &option_optional_reference,
1009 N_("repo"), N_("reference repository")),
1010 OPT_BOOL(0, "dissociate", &option_dissociate,
1011 N_("use --reference only while cloning")),
1012 OPT_STRING('o', "origin", &option_origin, N_("name"),
1013 N_("use <name> instead of 'origin' to track upstream")),
1014 OPT_STRING('b', "branch", &option_branch, N_("branch"),
1015 N_("checkout <branch> instead of the remote's HEAD")),
1016 OPT_STRING(0, "revision", &option_rev, N_("rev"),
1017 N_("clone single revision <rev> and check out")),
1018 OPT_STRING('u', "upload-pack", &option_upload_pack, N_("path"),
1019 N_("path to git-upload-pack on the remote")),
1020 OPT_STRING(0, "depth", &option_depth, N_("depth"),
1021 N_("create a shallow clone of that depth")),
1022 OPT_STRING(0, "shallow-since", &option_since, N_("time"),
1023 N_("create a shallow clone since a specific time")),
1024 OPT_STRING_LIST(0, "shallow-exclude", &option_not, N_("ref"),
1025 N_("deepen history of shallow clone, excluding ref")),
1026 OPT_BOOL(0, "single-branch", &option_single_branch,
1027 N_("clone only one branch, HEAD or --branch")),
1028 OPT_BOOL(0, "tags", &option_tags,
1029 N_("clone tags, and make later fetches not to follow them")),
1030 OPT_BOOL(0, "shallow-submodules", &option_shallow_submodules,
1031 N_("any cloned submodules will be shallow")),
1032 OPT_STRING(0, "separate-git-dir", &real_git_dir, N_("gitdir"),
1033 N_("separate git dir from working tree")),
1034 OPT_STRING(0, "ref-storage-format", &ref_storage_format_uri, N_("format"),
1035 N_("specify the reference storage format to use")),
1036 OPT_STRING(0, "object-storage-format", &object_storage_format_uri, N_("format"),
1037 N_("specify the object storage format to use")),
1038 OPT_ALIAS_F(0, "ref-format", "ref-storage-format", PARSE_OPT_HIDDEN),
1039 OPT_STRING_LIST('c', "config", &option_config, N_("key=value"),
1040 N_("set config inside the new repository")),
1041 OPT_STRING_LIST(0, "server-option", &server_options,
1042 N_("server-specific"), N_("option to transmit")),
1043 OPT_IPVERSION(&family),
1044 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
1045 OPT_BOOL(0, "also-filter-submodules", &option_filter_submodules,
1046 N_("apply partial clone filters to submodules")),
1047 OPT_BOOL(0, "remote-submodules", &option_remote_submodules,
1048 N_("any cloned submodules will use their remote-tracking branch")),
1049 OPT_BOOL(0, "sparse", &option_sparse_checkout,
1050 N_("initialize sparse-checkout file to include only files at root")),
1051 OPT_STRING(0, "bundle-uri", &bundle_uri,
1052 N_("uri"), N_("a URI for downloading bundles before fetching from origin remote")),
1053 OPT_END()
1054 };
1055 struct strvec alternates = STRVEC_INIT;
1056
1057 const char * const builtin_clone_usage[] = {
1058 N_("git clone [<options>] [--] <repo> [<dir>]"),
1059 NULL
1060 };
1061
1062 filter_options.allow_auto_filter = 1;
1063
1064 packet_trace_identity("clone");
1065
1066 repo_config(the_repository, git_clone_config, NULL);
1067
1068 argc = parse_options(argc, argv, prefix, builtin_clone_options,
1069 builtin_clone_usage, 0);
1070
1071 if (argc > 2)
1072 usage_msg_opt(_("Too many arguments."),
1073 builtin_clone_usage, builtin_clone_options);
1074
1075 if (argc == 0)
1076 usage_msg_opt(_("You must specify a repository to clone."),
1077 builtin_clone_usage, builtin_clone_options);
1078
1079 if (option_depth || option_since || option_not.nr)
1080 deepen = 1;
1081 if (option_single_branch == -1)
1082 option_single_branch = deepen ? 1 : 0;
1083
1084 if (ref_storage_format_uri) {
1085 ref_storage_format = ref_storage_format_by_uri(ref_storage_format_uri, NULL);
1086 if (ref_storage_format == REF_STORAGE_FORMAT_UNKNOWN)
1087 die(_("unknown ref storage format '%s'"), ref_storage_format_uri);
1088 }
1089
1090 if (object_storage_format_uri) {
1091 object_storage_format = object_storage_format_by_uri(object_storage_format_uri, NULL);
1092 if (object_storage_format == OBJECT_STORAGE_FORMAT_UNKNOWN)
1093 die(_("unknown object storage format '%s'"), object_storage_format_uri);
1094 }
1095
1096 if (option_mirror) {
1097 option_bare = 1;
1098 option_tags = 0;
1099 }
1100
1101 if (option_bare) {
1102 if (real_git_dir)
1103 die(_("options '%s' and '%s' cannot be used together"), "--bare", "--separate-git-dir");
1104 option_no_checkout = 1;
1105 }
1106
1107 if (bundle_uri && deepen)
1108 die(_("options '%s' and '%s' cannot be used together"),
1109 "--bundle-uri",
1110 "--depth/--shallow-since/--shallow-exclude");
1111
1112 repo_name = argv[0];
1113
1114 path = get_repo_path(repo_name, &is_bundle);
1115 if (path) {
1116 FREE_AND_NULL(path);
1117 repo = repo_to_free = absolute_pathdup(repo_name);
1118 } else if (strchr(repo_name, ':')) {
1119 repo = repo_name;
1120 display_repo = transport_anonymize_url(repo);
1121 } else
1122 die(_("repository '%s' does not exist"), repo_name);
1123
1124 /* no need to be strict, transport_set_option() will validate it again */
1125 if (option_depth && atoi(option_depth) < 1)
1126 die(_("depth %s is not a positive number"), option_depth);
1127
1128 if (argc == 2)
1129 dir = xstrdup(argv[1]);
1130 else
1131 dir = git_url_basename(repo_name, is_bundle, option_bare);
1132 strip_dir_trailing_slashes(dir);
1133
1134 dest_exists = path_exists(dir);
1135 if (dest_exists && !is_empty_dir(dir))
1136 die(_("destination path '%s' already exists and is not "
1137 "an empty directory."), dir);
1138
1139 if (real_git_dir) {
1140 real_dest_exists = path_exists(real_git_dir);
1141 if (real_dest_exists && !is_empty_dir(real_git_dir))
1142 die(_("repository path '%s' already exists and is not "
1143 "an empty directory."), real_git_dir);
1144 }
1145
1146
1147 strbuf_addf(&reflog_msg, "clone: from %s",
1148 display_repo ? display_repo : repo);
1149 free(display_repo);
1150
1151 if (option_bare)
1152 work_tree = NULL;
1153 else {
1154 work_tree = getenv("GIT_WORK_TREE");
1155 if (work_tree && path_exists(work_tree))
1156 die(_("working tree '%s' already exists."), work_tree);
1157 }
1158
1159 if (option_bare || work_tree)
1160 git_dir = xstrdup(dir);
1161 else {
1162 work_tree = dir;
1163 git_dir = mkpathdup("%s/.git", dir);
1164 }
1165
1166 atexit(remove_junk);
1167 sigchain_push_common(remove_junk_on_signal);
1168
1169 if (!option_bare) {
1170 if (safe_create_leading_directories_no_share_const(work_tree) < 0)
1171 die_errno(_("could not create leading directories of '%s'"),
1172 work_tree);
1173 if (dest_exists)
1174 junk_work_tree_flags |= REMOVE_DIR_KEEP_TOPLEVEL;
1175 else if (mkdir(work_tree, 0777))
1176 die_errno(_("could not create work tree dir '%s'"),
1177 work_tree);
1178 junk_work_tree = work_tree;
1179 }
1180
1181 if (real_git_dir) {
1182 if (real_dest_exists)
1183 junk_git_dir_flags |= REMOVE_DIR_KEEP_TOPLEVEL;
1184 junk_git_dir = real_git_dir;
1185 } else {
1186 if (dest_exists)
1187 junk_git_dir_flags |= REMOVE_DIR_KEEP_TOPLEVEL;
1188 junk_git_dir = git_dir;
1189 }
1190 if (safe_create_leading_directories_no_share_const(git_dir) < 0)
1191 die(_("could not create leading directories of '%s'"), git_dir);
1192
1193 if (0 <= option_verbosity) {
1194 if (option_bare)
1195 fprintf(stderr, _("Cloning into bare repository '%s'...\n"), dir);
1196 else
1197 fprintf(stderr, _("Cloning into '%s'...\n"), dir);
1198 }
1199
1200 if (option_recurse_submodules.nr > 0) {
1201 struct string_list_item *item;
1202 struct strbuf sb = STRBUF_INIT;
1203 int val;
1204
1205 /* remove duplicates */
1206 string_list_sort_u(&option_recurse_submodules, 0);
1207
1208 /*
1209 * NEEDSWORK: In a multi-working-tree world, this needs to be
1210 * set in the per-worktree config.
1211 */
1212 for_each_string_list_item(item, &option_recurse_submodules) {
1213 strbuf_addf(&sb, "submodule.active=%s",
1214 item->string);
1215 string_list_append(&option_config, sb.buf);
1216 strbuf_reset(&sb);
1217 }
1218
1219 if (!repo_config_get_bool(the_repository, "submodule.stickyRecursiveClone", &val) &&
1220 val)
1221 string_list_append(&option_config, "submodule.recurse=true");
1222
1223 if (option_required_reference.nr &&
1224 option_optional_reference.nr)
1225 die(_("clone --recursive is not compatible with "
1226 "both --reference and --reference-if-able"));
1227 else if (option_required_reference.nr) {
1228 string_list_append(&option_config,
1229 "submodule.alternateLocation=superproject");
1230 string_list_append(&option_config,
1231 "submodule.alternateErrorStrategy=die");
1232 } else if (option_optional_reference.nr) {
1233 string_list_append(&option_config,
1234 "submodule.alternateLocation=superproject");
1235 string_list_append(&option_config,
1236 "submodule.alternateErrorStrategy=info");
1237 }
1238
1239 strbuf_release(&sb);
1240 }
1241
1242 /*
1243 * Initialize the repository, but skip initializing the reference
1244 * database. We do not yet know about the object format of the
1245 * repository, and reference backends may persist that information into
1246 * their on-disk data structures.
1247 */
1248 create_repository(the_repository, git_dir, real_git_dir, work_tree,
1249 option_template, GIT_HASH_UNKNOWN,
1250 ref_storage_format_uri, object_storage_format_uri,
1251 do_not_override_repo_unix_permissions, NULL);
1252
1253 if (real_git_dir) {
1254 free((char *)git_dir);
1255 git_dir = real_git_dir;
1256 }
1257
1258 /*
1259 * We have a chicken-and-egg situation between initializing the refdb
1260 * and spawning transport helpers:
1261 *
1262 * - Initializing the refdb requires us to know about the object
1263 * format. We thus have to spawn the transport helper to learn
1264 * about it.
1265 *
1266 * - The transport helper may want to access the Git repository. But
1267 * because the refdb has not been initialized, we don't have "HEAD"
1268 * or "refs/". Thus, the helper cannot find the Git repository.
1269 *
1270 * Ideally, we would have structured the helper protocol such that it's
1271 * mandatory for the helper to first announce its capabilities without
1272 * yet assuming a fully initialized repository. Like that, we could
1273 * have added a "lazy-refdb-init" capability that announces whether the
1274 * helper is ready to handle not-yet-initialized refdbs. If any helper
1275 * didn't support them, we would have fully initialized the refdb with
1276 * the SHA1 object format, but later on bailed out if we found out that
1277 * the remote repository used a different object format.
1278 *
1279 * But we didn't, and thus we use the following workaround to partially
1280 * initialize the repository's refdb such that it can be discovered by
1281 * Git commands. To do so, we:
1282 *
1283 * - Create an invalid HEAD ref pointing at "refs/heads/.invalid".
1284 *
1285 * - Create the "refs/" directory.
1286 *
1287 * - Set up the ref storage format and repository version as
1288 * required.
1289 *
1290 * This is sufficient for Git commands to discover the Git directory.
1291 */
1292 initialize_repository_version(the_repository, GIT_HASH_UNKNOWN,
1293 the_repository->ref_storage_format,
1294 the_repository->object_storage_format, 1);
1295
1296 refs_create_refdir_stubs(the_repository, git_dir, NULL);
1297
1298 /*
1299 * additional config can be injected with -c, make sure it's included
1300 * after init_db, which clears the entire config environment.
1301 */
1302 write_config(&option_config);
1303
1304 /*
1305 * re-read config after init_db and write_config to pick up any config
1306 * injected by --template and --config, respectively.
1307 */
1308 repo_config(the_repository, git_clone_config, NULL);
1309
1310 /*
1311 * If option_reject_shallow is specified from CLI option,
1312 * ignore config_reject_shallow from git_clone_config.
1313 */
1314 if (config_reject_shallow != -1)
1315 reject_shallow = config_reject_shallow;
1316 if (option_reject_shallow != -1)
1317 reject_shallow = option_reject_shallow;
1318
1319 /*
1320 * If option_filter_submodules is specified from CLI option,
1321 * ignore config_filter_submodules from git_clone_config.
1322 */
1323 if (config_filter_submodules != -1)
1324 filter_submodules = config_filter_submodules;
1325 if (option_filter_submodules != -1)
1326 filter_submodules = option_filter_submodules;
1327
1328 /*
1329 * Exit if the user seems to be doing something silly with submodule
1330 * filter flags (but not with filter configs, as those should be
1331 * set-and-forget).
1332 */
1333 if (option_filter_submodules > 0 && !filter_options.choice)
1334 die(_("the option '%s' requires '%s'"),
1335 "--also-filter-submodules", "--filter");
1336 if (option_filter_submodules > 0 && !option_recurse_submodules.nr)
1337 die(_("the option '%s' requires '%s'"),
1338 "--also-filter-submodules", "--recurse-submodules");
1339
1340 /*
1341 * apply the remote name provided by --origin only after this second
1342 * call to git_config, to ensure it overrides all config-based values.
1343 */
1344 if (option_origin) {
1345 free(remote_name);
1346 remote_name = xstrdup(option_origin);
1347 }
1348
1349 if (!remote_name)
1350 remote_name = xstrdup("origin");
1351
1352 if (!valid_remote_name(remote_name))
1353 die(_("'%s' is not a valid remote name"), remote_name);
1354
1355 if (option_bare) {
1356 if (option_mirror)
1357 src_ref_prefix = "refs/";
1358 strbuf_addstr(&branch_top, src_ref_prefix);
1359
1360 repo_config_set(the_repository, "core.bare", "true");
1361 } else if (!option_rev) {
1362 strbuf_addf(&branch_top, "refs/remotes/%s/", remote_name);
1363 }
1364
1365 strbuf_addf(&key, "remote.%s.url", remote_name);
1366 repo_config_set(the_repository, key.buf, repo);
1367 strbuf_reset(&key);
1368
1369 if (!option_tags) {
1370 strbuf_addf(&key, "remote.%s.tagOpt", remote_name);
1371 repo_config_set(the_repository, key.buf, "--no-tags");
1372 strbuf_reset(&key);
1373 }
1374
1375 remote = remote_get_early(remote_name);
1376
1377 if (!option_rev)
1378 refspec_appendf(&remote->fetch, "+%s*:%s*", src_ref_prefix,
1379 branch_top.buf);
1380
1381 path = get_repo_path(remote->url.v[0], &is_bundle);
1382 is_local = option_local != 0 && path && !is_bundle;
1383 if (is_local) {
1384 if (option_depth)
1385 warning(_("--depth is ignored in local clones; use file:// instead."));
1386 if (option_since)
1387 warning(_("--shallow-since is ignored in local clones; use file:// instead."));
1388 if (option_not.nr)
1389 warning(_("--shallow-exclude is ignored in local clones; use file:// instead."));
1390 if (filter_options.choice)
1391 warning(_("--filter is ignored in local clones; use file:// instead."));
1392 if (!access(mkpath("%s/shallow", path), F_OK)) {
1393 if (reject_shallow)
1394 die(_("source repository is shallow, reject to clone."));
1395 if (option_local > 0)
1396 warning(_("source repository is shallow, ignoring --local"));
1397 is_local = 0;
1398 }
1399 }
1400
1401 /*
1402 * Local clones copy or hardlink the object directory of the source repository
1403 * into the destination. This only works when both repositories use the "files"
1404 * object storage format.
1405 */
1406 if (is_local &&
1407 (!is_using_default_object_storage_format(path) || !is_using_default_object_storage_format(git_dir))) {
1408 if (option_local > 0)
1409 die(_("cannot perform local clone with non-default object storage format"));
1410 else
1411 warning(_("falling back to non-local clone because of non-default object storage format"));
1412 is_local = 0;
1413 }
1414
1415 if (option_local > 0 && !is_local)
1416 warning(_("--local is ignored"));
1417
1418 collect_alternates(&alternates, is_local ? path : NULL);
1419 create_object_database(the_repository, &alternates);
1420
1421 transport = transport_get(remote, path ? path : remote->url.v[0]);
1422 transport_set_verbosity(transport, option_verbosity, option_progress);
1423 transport->family = family;
1424 transport->cloning = 1;
1425
1426 if (is_bundle) {
1427 struct bundle_header header = BUNDLE_HEADER_INIT;
1428 int fd = read_bundle_header(path, &header);
1429 int has_filter = header.filter.choice != LOFC_DISABLED;
1430
1431 if (fd > 0)
1432 close(fd);
1433 bundle_header_release(&header);
1434 if (has_filter)
1435 die(_("cannot clone from filtered bundle"));
1436 }
1437
1438 transport_set_option(transport, TRANS_OPT_KEEP, "yes");
1439
1440 die_for_incompatible_opt2(!!option_rev, "--revision",
1441 !!option_branch, "--branch");
1442 die_for_incompatible_opt2(!!option_rev, "--revision",
1443 option_mirror, "--mirror");
1444
1445 if (reject_shallow)
1446 transport_set_option(transport, TRANS_OPT_REJECT_SHALLOW, "1");
1447 if (option_depth)
1448 transport_set_option(transport, TRANS_OPT_DEPTH,
1449 option_depth);
1450 if (option_since)
1451 transport_set_option(transport, TRANS_OPT_DEEPEN_SINCE,
1452 option_since);
1453 if (option_not.nr)
1454 transport_set_option(transport, TRANS_OPT_DEEPEN_NOT,
1455 (const char *)&option_not);
1456 if (option_single_branch) {
1457 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
1458
1459 if (option_branch)
1460 opts.wants_head = 0;
1461 }
1462
1463 if (option_upload_pack)
1464 transport_set_option(transport, TRANS_OPT_UPLOADPACK,
1465 option_upload_pack);
1466
1467 if (server_options.nr)
1468 transport->server_options = &server_options;
1469
1470 if (filter_options.choice) {
1471 const char *spec =
1472 expand_list_objects_filter_spec(&filter_options);
1473 transport_set_option(transport, TRANS_OPT_LIST_OBJECTS_FILTER,
1474 spec);
1475 transport_set_option(transport, TRANS_OPT_FROM_PROMISOR, "1");
1476 }
1477
1478 if (transport->smart_options && !deepen && !filter_options.choice)
1479 transport->smart_options->check_self_contained_and_connected = 1;
1480
1481 if (option_rev) {
1482 option_tags = 0;
1483 option_single_branch = 0;
1484 opts.wants_head = 0;
1485 opts.detach = 1;
1486
1487 refspec_append(&remote->fetch, option_rev);
1488 }
1489
1490 if (option_tags || option_branch)
1491 /*
1492 * Add tags refspec when user asked for tags (implicitly) or
1493 * specified --branch, whose argument might be a tag.
1494 */
1495 refspec_append(&remote->fetch, TAG_REFSPEC);
1496
1497 refspec_ref_prefixes(&remote->fetch,
1498 &transport_ls_refs_options.ref_prefixes);
1499 if (option_branch)
1500 expand_ref_prefix(&transport_ls_refs_options.ref_prefixes,
1501 option_branch);
1502
1503 /*
1504 * As part of transport_get_remote_refs() the server tells us the hash
1505 * algorithm, which we require to initialize the repo. But calling that
1506 * function without any ref prefix, will cause the server to announce
1507 * all known refs. If the argument passed to --revision was a hex oid,
1508 * ref_prefixes will be empty so we fall back to asking about HEAD to
1509 * reduce traffic from the server.
1510 */
1511 if (opts.wants_head || transport_ls_refs_options.ref_prefixes.nr == 0)
1512 strvec_push(&transport_ls_refs_options.ref_prefixes, "HEAD");
1513
1514 refs = transport_get_remote_refs(transport, &transport_ls_refs_options);
1515
1516 /*
1517 * Now that we know what algorithm the remote side is using, let's set
1518 * ours to the same thing.
1519 */
1520 hash_algo = hash_algo_by_ptr(transport_get_hash_algo(transport));
1521 initialize_repository_version(the_repository, hash_algo,
1522 the_repository->ref_storage_format,
1523 the_repository->object_storage_format, 1);
1524 repo_set_hash_algo(the_repository, hash_algo);
1525 create_reference_database(the_repository, NULL, 1);
1526 startup_info->have_repository = 1;
1527
1528 /*
1529 * Before fetching from the remote, download and install bundle
1530 * data from the --bundle-uri option.
1531 */
1532 if (bundle_uri) {
1533 struct remote_state *state;
1534 int has_heuristic = 0;
1535
1536 /*
1537 * We need to save the remote state as our remote's lifetime is
1538 * tied to it.
1539 */
1540 state = the_repository->remote_state;
1541 the_repository->remote_state = NULL;
1542 repo_clear(the_repository);
1543
1544 /* At this point, we need the_repository to match the cloned repo. */
1545 if (repo_init(the_repository, git_dir, work_tree))
1546 warning(_("failed to initialize the repo, skipping bundle URI"));
1547 else if (fetch_bundle_uri(the_repository, bundle_uri, &has_heuristic))
1548 warning(_("failed to fetch objects from bundle URI '%s'"),
1549 bundle_uri);
1550 else if (has_heuristic)
1551 repo_config_set_gently(the_repository, "fetch.bundleuri", bundle_uri);
1552
1553 remote_state_clear(the_repository->remote_state);
1554 free(the_repository->remote_state);
1555 the_repository->remote_state = state;
1556 } else {
1557 /*
1558 * Populate transport->got_remote_bundle_uri and
1559 * transport->bundle_uri. We might get nothing.
1560 */
1561 transport_get_remote_bundle_uri(transport);
1562
1563 if (transport->bundles &&
1564 hashmap_get_size(&transport->bundles->bundles)) {
1565 struct remote_state *state;
1566
1567 /*
1568 * We need to save the remote state as our remote's
1569 * lifetime is tied to it.
1570 */
1571 state = the_repository->remote_state;
1572 the_repository->remote_state = NULL;
1573 repo_clear(the_repository);
1574
1575 /* At this point, we need the_repository to match the cloned repo. */
1576 if (repo_init(the_repository, git_dir, work_tree))
1577 warning(_("failed to initialize the repo, skipping bundle URI"));
1578 else if (fetch_bundle_list(the_repository,
1579 transport->bundles))
1580 warning(_("failed to fetch advertised bundles"));
1581
1582 remote_state_clear(the_repository->remote_state);
1583 free(the_repository->remote_state);
1584 the_repository->remote_state = state;
1585 } else {
1586 clear_bundle_list(transport->bundles);
1587 FREE_AND_NULL(transport->bundles);
1588 }
1589 }
1590
1591 if (refs)
1592 mapped_refs = wanted_peer_refs(&opts, refs, &remote->fetch);
1593
1594 if (mapped_refs) {
1595 /*
1596 * transport_get_remote_refs() may return refs with null sha-1
1597 * in mapped_refs (see struct transport->get_refs_list
1598 * comment). In that case we need fetch it early because
1599 * remote_head code below relies on it.
1600 *
1601 * for normal clones, transport_get_remote_refs() should
1602 * return reliable ref set, we can delay cloning until after
1603 * remote HEAD check.
1604 */
1605 for (ref = refs; ref; ref = ref->next)
1606 if (is_null_oid(&ref->old_oid)) {
1607 complete_refs_before_fetch = 0;
1608 break;
1609 }
1610
1611 if (!is_local && !complete_refs_before_fetch) {
1612 if (transport_fetch_refs(transport, mapped_refs))
1613 die(_("remote transport reported error"));
1614 }
1615 }
1616
1617 remote_head = find_ref_by_name(refs, "HEAD");
1618 remote_head_points_at = guess_remote_head(remote_head, mapped_refs,
1619 REMOTE_GUESS_HEAD_QUIET);
1620
1621 if (option_branch) {
1622 our_head_points_at = find_remote_branch(mapped_refs, option_branch);
1623 if (!our_head_points_at)
1624 die(_("Remote branch %s not found in upstream %s"),
1625 option_branch, remote_name);
1626 } else if (option_rev) {
1627 our_head_points_at = mapped_refs;
1628 if (!our_head_points_at)
1629 die(_("Remote revision %s not found in upstream %s"),
1630 option_rev, remote_name);
1631 } else if (remote_head_points_at) {
1632 our_head_points_at = remote_head_points_at;
1633 } else if (remote_head) {
1634 our_head_points_at = NULL;
1635 } else {
1636 char *to_free = NULL;
1637 const char *branch;
1638
1639 if (!mapped_refs) {
1640 warning(_("You appear to have cloned an empty repository."));
1641 option_no_checkout = 1;
1642 }
1643
1644 if (transport_ls_refs_options.unborn_head_target &&
1645 !check_refname_format(transport_ls_refs_options.unborn_head_target, 0) &&
1646 skip_prefix(transport_ls_refs_options.unborn_head_target,
1647 "refs/heads/", &branch)) {
1648 unborn_head = xstrdup(transport_ls_refs_options.unborn_head_target);
1649 } else {
1650 branch = to_free = repo_default_branch_name(the_repository, 0);
1651 unborn_head = xstrfmt("refs/heads/%s", branch);
1652 }
1653
1654 /*
1655 * We may have selected a local default branch name "foo",
1656 * and even though the remote's HEAD does not point there,
1657 * it may still have a "foo" branch. If so, set it up so
1658 * that we can follow the usual checkout code later.
1659 *
1660 * Note that for an empty repo we'll already have set
1661 * option_no_checkout above, which would work against us here.
1662 * But for an empty repo, find_remote_branch() can never find
1663 * a match.
1664 */
1665 our_head_points_at = find_remote_branch(mapped_refs, branch);
1666
1667 free(to_free);
1668 }
1669
1670 if (!option_rev)
1671 write_refspec_config(src_ref_prefix, our_head_points_at,
1672 remote_head_points_at, &branch_top);
1673
1674 if (filter_options.choice)
1675 partial_clone_register(remote_name, &filter_options);
1676
1677 if (is_local)
1678 clone_local(path, git_dir);
1679 else if (mapped_refs && complete_refs_before_fetch) {
1680 if (transport_fetch_refs(transport, mapped_refs))
1681 die(_("remote transport reported error"));
1682 }
1683
1684 update_remote_refs(refs, mapped_refs, remote_head_points_at,
1685 branch_top.buf, reflog_msg.buf, transport,
1686 !is_local);
1687
1688 update_head(&opts, our_head_points_at, remote_head, unborn_head, reflog_msg.buf);
1689
1690 /*
1691 * We want to show progress for recursive submodule clones iff
1692 * we did so for the main clone. But only the transport knows
1693 * the final decision for this flag, so we need to rescue the value
1694 * before we free the transport.
1695 */
1696 submodule_progress = transport->progress;
1697
1698 transport_unlock_pack(transport, 0);
1699 transport_disconnect(transport);
1700
1701 if (option_dissociate) {
1702 odb_close(the_repository->objects);
1703 dissociate_from_references();
1704 }
1705
1706 if (option_sparse_checkout && git_sparse_checkout_init(dir))
1707 return 1;
1708
1709 junk_mode = JUNK_LEAVE_REPO;
1710 err = checkout(submodule_progress,
1711 &filter_options,
1712 filter_submodules,
1713 ref_storage_format,
1714 object_storage_format);
1715
1716 list_objects_filter_release(&filter_options);
1717
1718 string_list_clear(&option_not, 0);
1719 string_list_clear(&option_config, 0);
1720 string_list_clear(&server_options, 0);
1721 strvec_clear(&alternates);
1722
1723 free(remote_name);
1724 strbuf_release(&reflog_msg);
1725 strbuf_release(&branch_top);
1726 strbuf_release(&buf);
1727 strbuf_release(&key);
1728 free_refs(mapped_refs);
1729 free_refs(remote_head_points_at);
1730 free(unborn_head);
1731 free(dir);
1732 free(path);
1733 free(repo_to_free);
1734 junk_mode = JUNK_LEAVE_ALL;
1735
1736 transport_ls_refs_options_release(&transport_ls_refs_options);
1737 return err;
1738}