The eighth batch
[alt-git.git] / setup.c
blob8a488f3e7c74b1ffeef8d25ffb656b990a4c06a6
1 #define USE_THE_REPOSITORY_VARIABLE
2 #define DISABLE_SIGN_COMPARE_WARNINGS
4 #include "git-compat-util.h"
5 #include "abspath.h"
6 #include "copy.h"
7 #include "environment.h"
8 #include "exec-cmd.h"
9 #include "gettext.h"
10 #include "hex.h"
11 #include "object-file.h"
12 #include "object-name.h"
13 #include "refs.h"
14 #include "replace-object.h"
15 #include "repository.h"
16 #include "config.h"
17 #include "dir.h"
18 #include "setup.h"
19 #include "shallow.h"
20 #include "string-list.h"
21 #include "strvec.h"
22 #include "chdir-notify.h"
23 #include "path.h"
24 #include "quote.h"
25 #include "tmp-objdir.h"
26 #include "trace.h"
27 #include "trace2.h"
28 #include "worktree.h"
29 #include "exec-cmd.h"
31 static int inside_git_dir = -1;
32 static int inside_work_tree = -1;
33 static int work_tree_config_is_bogus;
34 enum allowed_bare_repo {
35 ALLOWED_BARE_REPO_EXPLICIT = 0,
36 ALLOWED_BARE_REPO_ALL,
39 static struct startup_info the_startup_info;
40 struct startup_info *startup_info = &the_startup_info;
41 const char *tmp_original_cwd;
44 * The input parameter must contain an absolute path, and it must already be
45 * normalized.
47 * Find the part of an absolute path that lies inside the work tree by
48 * dereferencing symlinks outside the work tree, for example:
49 * /dir1/repo/dir2/file (work tree is /dir1/repo) -> dir2/file
50 * /dir/file (work tree is /) -> dir/file
51 * /dir/symlink1/symlink2 (symlink1 points to work tree) -> symlink2
52 * /dir/repolink/file (repolink points to /dir/repo) -> file
53 * /dir/repo (exactly equal to work tree) -> (empty string)
55 static int abspath_part_inside_repo(char *path)
57 size_t len;
58 size_t wtlen;
59 char *path0;
60 int off;
61 const char *work_tree = precompose_string_if_needed(repo_get_work_tree(the_repository));
62 struct strbuf realpath = STRBUF_INIT;
64 if (!work_tree)
65 return -1;
66 wtlen = strlen(work_tree);
67 len = strlen(path);
68 off = offset_1st_component(path);
70 /* check if work tree is already the prefix */
71 if (wtlen <= len && !fspathncmp(path, work_tree, wtlen)) {
72 if (path[wtlen] == '/') {
73 memmove(path, path + wtlen + 1, len - wtlen);
74 return 0;
75 } else if (path[wtlen - 1] == '/' || path[wtlen] == '\0') {
76 /* work tree is the root, or the whole path */
77 memmove(path, path + wtlen, len - wtlen + 1);
78 return 0;
80 /* work tree might match beginning of a symlink to work tree */
81 off = wtlen;
83 path0 = path;
84 path += off;
86 /* check each '/'-terminated level */
87 while (*path) {
88 path++;
89 if (*path == '/') {
90 *path = '\0';
91 strbuf_realpath(&realpath, path0, 1);
92 if (fspathcmp(realpath.buf, work_tree) == 0) {
93 memmove(path0, path + 1, len - (path - path0));
94 strbuf_release(&realpath);
95 return 0;
97 *path = '/';
101 /* check whole path */
102 strbuf_realpath(&realpath, path0, 1);
103 if (fspathcmp(realpath.buf, work_tree) == 0) {
104 *path0 = '\0';
105 strbuf_release(&realpath);
106 return 0;
109 strbuf_release(&realpath);
110 return -1;
114 * Normalize "path", prepending the "prefix" for relative paths. If
115 * remaining_prefix is not NULL, return the actual prefix still
116 * remains in the path. For example, prefix = sub1/sub2/ and path is
118 * foo -> sub1/sub2/foo (full prefix)
119 * ../foo -> sub1/foo (remaining prefix is sub1/)
120 * ../../bar -> bar (no remaining prefix)
121 * ../../sub1/sub2/foo -> sub1/sub2/foo (but no remaining prefix)
122 * `pwd`/../bar -> sub1/bar (no remaining prefix)
124 char *prefix_path_gently(const char *prefix, int len,
125 int *remaining_prefix, const char *path)
127 const char *orig = path;
128 char *sanitized;
129 if (is_absolute_path(orig)) {
130 sanitized = xmallocz(strlen(path));
131 if (remaining_prefix)
132 *remaining_prefix = 0;
133 if (normalize_path_copy_len(sanitized, path, remaining_prefix)) {
134 free(sanitized);
135 return NULL;
137 if (abspath_part_inside_repo(sanitized)) {
138 free(sanitized);
139 return NULL;
141 } else {
142 sanitized = xstrfmt("%.*s%s", len, len ? prefix : "", path);
143 if (remaining_prefix)
144 *remaining_prefix = len;
145 if (normalize_path_copy_len(sanitized, sanitized, remaining_prefix)) {
146 free(sanitized);
147 return NULL;
150 return sanitized;
153 char *prefix_path(const char *prefix, int len, const char *path)
155 char *r = prefix_path_gently(prefix, len, NULL, path);
156 if (!r) {
157 const char *hint_path = repo_get_work_tree(the_repository);
158 if (!hint_path)
159 hint_path = repo_get_git_dir(the_repository);
160 die(_("'%s' is outside repository at '%s'"), path,
161 absolute_path(hint_path));
163 return r;
166 int path_inside_repo(const char *prefix, const char *path)
168 int len = prefix ? strlen(prefix) : 0;
169 char *r = prefix_path_gently(prefix, len, NULL, path);
170 if (r) {
171 free(r);
172 return 1;
174 return 0;
177 int check_filename(const char *prefix, const char *arg)
179 char *to_free = NULL;
180 struct stat st;
182 if (skip_prefix(arg, ":/", &arg)) {
183 if (!*arg) /* ":/" is root dir, always exists */
184 return 1;
185 prefix = NULL;
186 } else if (skip_prefix(arg, ":!", &arg) ||
187 skip_prefix(arg, ":^", &arg)) {
188 if (!*arg) /* excluding everything is silly, but allowed */
189 return 1;
192 if (prefix)
193 arg = to_free = prefix_filename(prefix, arg);
195 if (!lstat(arg, &st)) {
196 free(to_free);
197 return 1; /* file exists */
199 if (is_missing_file_error(errno)) {
200 free(to_free);
201 return 0; /* file does not exist */
203 die_errno(_("failed to stat '%s'"), arg);
206 static void NORETURN die_verify_filename(struct repository *r,
207 const char *prefix,
208 const char *arg,
209 int diagnose_misspelt_rev)
211 if (!diagnose_misspelt_rev)
212 die(_("%s: no such path in the working tree.\n"
213 "Use 'git <command> -- <path>...' to specify paths that do not exist locally."),
214 arg);
216 * Saying "'(icase)foo' does not exist in the index" when the
217 * user gave us ":(icase)foo" is just stupid. A magic pathspec
218 * begins with a colon and is followed by a non-alnum; do not
219 * let maybe_die_on_misspelt_object_name() even trigger.
221 if (!(arg[0] == ':' && !isalnum(arg[1])))
222 maybe_die_on_misspelt_object_name(r, arg, prefix);
224 /* ... or fall back the most general message. */
225 die(_("ambiguous argument '%s': unknown revision or path not in the working tree.\n"
226 "Use '--' to separate paths from revisions, like this:\n"
227 "'git <command> [<revision>...] -- [<file>...]'"), arg);
232 * Check for arguments that don't resolve as actual files,
233 * but which look sufficiently like pathspecs that we'll consider
234 * them such for the purposes of rev/pathspec DWIM parsing.
236 static int looks_like_pathspec(const char *arg)
238 const char *p;
239 int escaped = 0;
242 * Wildcard characters imply the user is looking to match pathspecs
243 * that aren't in the filesystem. Note that this doesn't include
244 * backslash even though it's a glob special; by itself it doesn't
245 * cause any increase in the match. Likewise ignore backslash-escaped
246 * wildcard characters.
248 for (p = arg; *p; p++) {
249 if (escaped) {
250 escaped = 0;
251 } else if (is_glob_special(*p)) {
252 if (*p == '\\')
253 escaped = 1;
254 else
255 return 1;
259 /* long-form pathspec magic */
260 if (starts_with(arg, ":("))
261 return 1;
263 return 0;
267 * Verify a filename that we got as an argument for a pathspec
268 * entry. Note that a filename that begins with "-" never verifies
269 * as true, because even if such a filename were to exist, we want
270 * it to be preceded by the "--" marker (or we want the user to
271 * use a format like "./-filename")
273 * The "diagnose_misspelt_rev" is used to provide a user-friendly
274 * diagnosis when dying upon finding that "name" is not a pathname.
275 * If set to 1, the diagnosis will try to diagnose "name" as an
276 * invalid object name (e.g. HEAD:foo). If set to 0, the diagnosis
277 * will only complain about an inexisting file.
279 * This function is typically called to check that a "file or rev"
280 * argument is unambiguous. In this case, the caller will want
281 * diagnose_misspelt_rev == 1 when verifying the first non-rev
282 * argument (which could have been a revision), and
283 * diagnose_misspelt_rev == 0 for the next ones (because we already
284 * saw a filename, there's not ambiguity anymore).
286 void verify_filename(const char *prefix,
287 const char *arg,
288 int diagnose_misspelt_rev)
290 if (*arg == '-')
291 die(_("option '%s' must come before non-option arguments"), arg);
292 if (looks_like_pathspec(arg) || check_filename(prefix, arg))
293 return;
294 die_verify_filename(the_repository, prefix, arg, diagnose_misspelt_rev);
298 * Opposite of the above: the command line did not have -- marker
299 * and we parsed the arg as a refname. It should not be interpretable
300 * as a filename.
302 void verify_non_filename(const char *prefix, const char *arg)
304 if (!is_inside_work_tree() || is_inside_git_dir())
305 return;
306 if (*arg == '-')
307 return; /* flag */
308 if (!check_filename(prefix, arg))
309 return;
310 die(_("ambiguous argument '%s': both revision and filename\n"
311 "Use '--' to separate paths from revisions, like this:\n"
312 "'git <command> [<revision>...] -- [<file>...]'"), arg);
315 int get_common_dir(struct strbuf *sb, const char *gitdir)
317 const char *git_env_common_dir = getenv(GIT_COMMON_DIR_ENVIRONMENT);
318 if (git_env_common_dir) {
319 strbuf_addstr(sb, git_env_common_dir);
320 return 1;
321 } else {
322 return get_common_dir_noenv(sb, gitdir);
326 int get_common_dir_noenv(struct strbuf *sb, const char *gitdir)
328 struct strbuf data = STRBUF_INIT;
329 struct strbuf path = STRBUF_INIT;
330 int ret = 0;
332 strbuf_addf(&path, "%s/commondir", gitdir);
333 if (file_exists(path.buf)) {
334 if (strbuf_read_file(&data, path.buf, 0) <= 0)
335 die_errno(_("failed to read %s"), path.buf);
336 while (data.len && (data.buf[data.len - 1] == '\n' ||
337 data.buf[data.len - 1] == '\r'))
338 data.len--;
339 data.buf[data.len] = '\0';
340 strbuf_reset(&path);
341 if (!is_absolute_path(data.buf))
342 strbuf_addf(&path, "%s/", gitdir);
343 strbuf_addbuf(&path, &data);
344 strbuf_add_real_path(sb, path.buf);
345 ret = 1;
346 } else {
347 strbuf_addstr(sb, gitdir);
350 strbuf_release(&data);
351 strbuf_release(&path);
352 return ret;
355 static int validate_headref(const char *path)
357 struct stat st;
358 char buffer[256];
359 const char *refname;
360 struct object_id oid;
361 int fd;
362 ssize_t len;
364 if (lstat(path, &st) < 0)
365 return -1;
367 /* Make sure it is a "refs/.." symlink */
368 if (S_ISLNK(st.st_mode)) {
369 len = readlink(path, buffer, sizeof(buffer)-1);
370 if (len >= 5 && !memcmp("refs/", buffer, 5))
371 return 0;
372 return -1;
376 * Anything else, just open it and try to see if it is a symbolic ref.
378 fd = open(path, O_RDONLY);
379 if (fd < 0)
380 return -1;
381 len = read_in_full(fd, buffer, sizeof(buffer)-1);
382 close(fd);
384 if (len < 0)
385 return -1;
386 buffer[len] = '\0';
389 * Is it a symbolic ref?
391 if (skip_prefix(buffer, "ref:", &refname)) {
392 while (isspace(*refname))
393 refname++;
394 if (starts_with(refname, "refs/"))
395 return 0;
399 * Is this a detached HEAD?
401 if (get_oid_hex_any(buffer, &oid) != GIT_HASH_UNKNOWN)
402 return 0;
404 return -1;
408 * Test if it looks like we're at a git directory.
409 * We want to see:
411 * - either an objects/ directory _or_ the proper
412 * GIT_OBJECT_DIRECTORY environment variable
413 * - a refs/ directory
414 * - either a HEAD symlink or a HEAD file that is formatted as
415 * a proper "ref:", or a regular file HEAD that has a properly
416 * formatted sha1 object name.
418 int is_git_directory(const char *suspect)
420 struct strbuf path = STRBUF_INIT;
421 int ret = 0;
422 size_t len;
424 /* Check worktree-related signatures */
425 strbuf_addstr(&path, suspect);
426 strbuf_complete(&path, '/');
427 strbuf_addstr(&path, "HEAD");
428 if (validate_headref(path.buf))
429 goto done;
431 strbuf_reset(&path);
432 get_common_dir(&path, suspect);
433 len = path.len;
435 /* Check non-worktree-related signatures */
436 if (getenv(DB_ENVIRONMENT)) {
437 if (access(getenv(DB_ENVIRONMENT), X_OK))
438 goto done;
440 else {
441 strbuf_setlen(&path, len);
442 strbuf_addstr(&path, "/objects");
443 if (access(path.buf, X_OK))
444 goto done;
447 strbuf_setlen(&path, len);
448 strbuf_addstr(&path, "/refs");
449 if (access(path.buf, X_OK))
450 goto done;
452 ret = 1;
453 done:
454 strbuf_release(&path);
455 return ret;
458 int is_nonbare_repository_dir(struct strbuf *path)
460 int ret = 0;
461 int gitfile_error;
462 size_t orig_path_len = path->len;
463 assert(orig_path_len != 0);
464 strbuf_complete(path, '/');
465 strbuf_addstr(path, ".git");
466 if (read_gitfile_gently(path->buf, &gitfile_error) || is_git_directory(path->buf))
467 ret = 1;
468 if (gitfile_error == READ_GITFILE_ERR_OPEN_FAILED ||
469 gitfile_error == READ_GITFILE_ERR_READ_FAILED)
470 ret = 1;
471 strbuf_setlen(path, orig_path_len);
472 return ret;
475 int is_inside_git_dir(void)
477 if (inside_git_dir < 0)
478 inside_git_dir = is_inside_dir(repo_get_git_dir(the_repository));
479 return inside_git_dir;
482 int is_inside_work_tree(void)
484 if (inside_work_tree < 0)
485 inside_work_tree = is_inside_dir(repo_get_work_tree(the_repository));
486 return inside_work_tree;
489 void setup_work_tree(void)
491 const char *work_tree;
492 static int initialized = 0;
494 if (initialized)
495 return;
497 if (work_tree_config_is_bogus)
498 die(_("unable to set up work tree using invalid config"));
500 work_tree = repo_get_work_tree(the_repository);
501 if (!work_tree || chdir_notify(work_tree))
502 die(_("this operation must be run in a work tree"));
505 * Make sure subsequent git processes find correct worktree
506 * if $GIT_WORK_TREE is set relative
508 if (getenv(GIT_WORK_TREE_ENVIRONMENT))
509 setenv(GIT_WORK_TREE_ENVIRONMENT, ".", 1);
511 initialized = 1;
514 static void setup_original_cwd(void)
516 struct strbuf tmp = STRBUF_INIT;
517 const char *worktree = NULL;
518 int offset = -1;
520 if (!tmp_original_cwd)
521 return;
524 * startup_info->original_cwd points to the current working
525 * directory we inherited from our parent process, which is a
526 * directory we want to avoid removing.
528 * For convenience, we would like to have the path relative to the
529 * worktree instead of an absolute path.
531 * Yes, startup_info->original_cwd is usually the same as 'prefix',
532 * but differs in two ways:
533 * - prefix has a trailing '/'
534 * - if the user passes '-C' to git, that modifies the prefix but
535 * not startup_info->original_cwd.
538 /* Normalize the directory */
539 if (!strbuf_realpath(&tmp, tmp_original_cwd, 0)) {
540 trace2_data_string("setup", the_repository,
541 "realpath-path", tmp_original_cwd);
542 trace2_data_string("setup", the_repository,
543 "realpath-failure", strerror(errno));
544 free((char*)tmp_original_cwd);
545 tmp_original_cwd = NULL;
546 return;
549 free((char*)tmp_original_cwd);
550 tmp_original_cwd = NULL;
551 startup_info->original_cwd = strbuf_detach(&tmp, NULL);
554 * Get our worktree; we only protect the current working directory
555 * if it's in the worktree.
557 worktree = repo_get_work_tree(the_repository);
558 if (!worktree)
559 goto no_prevention_needed;
561 offset = dir_inside_of(startup_info->original_cwd, worktree);
562 if (offset >= 0) {
564 * If startup_info->original_cwd == worktree, that is already
565 * protected and we don't need original_cwd as a secondary
566 * protection measure.
568 if (!*(startup_info->original_cwd + offset))
569 goto no_prevention_needed;
572 * original_cwd was inside worktree; precompose it just as
573 * we do prefix so that built up paths will match
575 startup_info->original_cwd = \
576 precompose_string_if_needed(startup_info->original_cwd
577 + offset);
578 return;
581 no_prevention_needed:
582 free((char*)startup_info->original_cwd);
583 startup_info->original_cwd = NULL;
586 static int read_worktree_config(const char *var, const char *value,
587 const struct config_context *ctx UNUSED,
588 void *vdata)
590 struct repository_format *data = vdata;
592 if (strcmp(var, "core.bare") == 0) {
593 data->is_bare = git_config_bool(var, value);
594 } else if (strcmp(var, "core.worktree") == 0) {
595 if (!value)
596 return config_error_nonbool(var);
597 free(data->work_tree);
598 data->work_tree = xstrdup(value);
600 return 0;
603 enum extension_result {
604 EXTENSION_ERROR = -1, /* compatible with error(), etc */
605 EXTENSION_UNKNOWN = 0,
606 EXTENSION_OK = 1
610 * Do not add new extensions to this function. It handles extensions which are
611 * respected even in v0-format repositories for historical compatibility.
613 static enum extension_result handle_extension_v0(const char *var,
614 const char *value,
615 const char *ext,
616 struct repository_format *data)
618 if (!strcmp(ext, "noop")) {
619 return EXTENSION_OK;
620 } else if (!strcmp(ext, "preciousobjects")) {
621 data->precious_objects = git_config_bool(var, value);
622 return EXTENSION_OK;
623 } else if (!strcmp(ext, "partialclone")) {
624 if (!value)
625 return config_error_nonbool(var);
626 data->partial_clone = xstrdup(value);
627 return EXTENSION_OK;
628 } else if (!strcmp(ext, "worktreeconfig")) {
629 data->worktree_config = git_config_bool(var, value);
630 return EXTENSION_OK;
633 return EXTENSION_UNKNOWN;
637 * Record any new extensions in this function.
639 static enum extension_result handle_extension(const char *var,
640 const char *value,
641 const char *ext,
642 struct repository_format *data)
644 if (!strcmp(ext, "noop-v1")) {
645 return EXTENSION_OK;
646 } else if (!strcmp(ext, "objectformat")) {
647 int format;
649 if (!value)
650 return config_error_nonbool(var);
651 format = hash_algo_by_name(value);
652 if (format == GIT_HASH_UNKNOWN)
653 return error(_("invalid value for '%s': '%s'"),
654 "extensions.objectformat", value);
655 data->hash_algo = format;
656 return EXTENSION_OK;
657 } else if (!strcmp(ext, "compatobjectformat")) {
658 struct string_list_item *item;
659 int format;
661 if (!value)
662 return config_error_nonbool(var);
663 format = hash_algo_by_name(value);
664 if (format == GIT_HASH_UNKNOWN)
665 return error(_("invalid value for '%s': '%s'"),
666 "extensions.compatobjectformat", value);
667 /* For now only support compatObjectFormat being specified once. */
668 for_each_string_list_item(item, &data->v1_only_extensions) {
669 if (!strcmp(item->string, "compatobjectformat"))
670 return error(_("'%s' already specified as '%s'"),
671 "extensions.compatobjectformat",
672 hash_algos[data->compat_hash_algo].name);
674 data->compat_hash_algo = format;
675 return EXTENSION_OK;
676 } else if (!strcmp(ext, "refstorage")) {
677 unsigned int format;
679 if (!value)
680 return config_error_nonbool(var);
681 format = ref_storage_format_by_name(value);
682 if (format == REF_STORAGE_FORMAT_UNKNOWN)
683 return error(_("invalid value for '%s': '%s'"),
684 "extensions.refstorage", value);
685 data->ref_storage_format = format;
686 return EXTENSION_OK;
687 } else if (!strcmp(ext, "relativeworktrees")) {
688 data->relative_worktrees = git_config_bool(var, value);
689 return EXTENSION_OK;
691 return EXTENSION_UNKNOWN;
694 static int check_repo_format(const char *var, const char *value,
695 const struct config_context *ctx, void *vdata)
697 struct repository_format *data = vdata;
698 const char *ext;
700 if (strcmp(var, "core.repositoryformatversion") == 0)
701 data->version = git_config_int(var, value, ctx->kvi);
702 else if (skip_prefix(var, "extensions.", &ext)) {
703 switch (handle_extension_v0(var, value, ext, data)) {
704 case EXTENSION_ERROR:
705 return -1;
706 case EXTENSION_OK:
707 return 0;
708 case EXTENSION_UNKNOWN:
709 break;
712 switch (handle_extension(var, value, ext, data)) {
713 case EXTENSION_ERROR:
714 return -1;
715 case EXTENSION_OK:
716 string_list_append(&data->v1_only_extensions, ext);
717 return 0;
718 case EXTENSION_UNKNOWN:
719 string_list_append(&data->unknown_extensions, ext);
720 return 0;
724 return read_worktree_config(var, value, ctx, vdata);
727 static int check_repository_format_gently(const char *gitdir, struct repository_format *candidate, int *nongit_ok)
729 struct strbuf sb = STRBUF_INIT;
730 struct strbuf err = STRBUF_INIT;
731 int has_common;
733 has_common = get_common_dir(&sb, gitdir);
734 strbuf_addstr(&sb, "/config");
735 read_repository_format(candidate, sb.buf);
736 strbuf_release(&sb);
739 * For historical use of check_repository_format() in git-init,
740 * we treat a missing config as a silent "ok", even when nongit_ok
741 * is unset.
743 if (candidate->version < 0)
744 return 0;
746 if (verify_repository_format(candidate, &err) < 0) {
747 if (nongit_ok) {
748 warning("%s", err.buf);
749 strbuf_release(&err);
750 *nongit_ok = -1;
751 return -1;
753 die("%s", err.buf);
756 repository_format_precious_objects = candidate->precious_objects;
757 string_list_clear(&candidate->unknown_extensions, 0);
758 string_list_clear(&candidate->v1_only_extensions, 0);
760 if (candidate->worktree_config) {
762 * pick up core.bare and core.worktree from per-worktree
763 * config if present
765 strbuf_addf(&sb, "%s/config.worktree", gitdir);
766 git_config_from_file(read_worktree_config, sb.buf, candidate);
767 strbuf_release(&sb);
768 has_common = 0;
771 if (!has_common) {
772 if (candidate->is_bare != -1) {
773 is_bare_repository_cfg = candidate->is_bare;
774 if (is_bare_repository_cfg == 1)
775 inside_work_tree = -1;
777 if (candidate->work_tree) {
778 free(git_work_tree_cfg);
779 git_work_tree_cfg = xstrdup(candidate->work_tree);
780 inside_work_tree = -1;
784 return 0;
787 int upgrade_repository_format(int target_version)
789 struct strbuf sb = STRBUF_INIT;
790 struct strbuf err = STRBUF_INIT;
791 struct strbuf repo_version = STRBUF_INIT;
792 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
793 int ret;
795 strbuf_git_common_path(&sb, the_repository, "config");
796 read_repository_format(&repo_fmt, sb.buf);
797 strbuf_release(&sb);
799 if (repo_fmt.version >= target_version) {
800 ret = 0;
801 goto out;
804 if (verify_repository_format(&repo_fmt, &err) < 0) {
805 ret = error("cannot upgrade repository format from %d to %d: %s",
806 repo_fmt.version, target_version, err.buf);
807 goto out;
809 if (!repo_fmt.version && repo_fmt.unknown_extensions.nr) {
810 ret = error("cannot upgrade repository format: "
811 "unknown extension %s",
812 repo_fmt.unknown_extensions.items[0].string);
813 goto out;
816 strbuf_addf(&repo_version, "%d", target_version);
817 git_config_set("core.repositoryformatversion", repo_version.buf);
819 ret = 1;
821 out:
822 clear_repository_format(&repo_fmt);
823 strbuf_release(&repo_version);
824 strbuf_release(&err);
825 return ret;
828 static void init_repository_format(struct repository_format *format)
830 const struct repository_format fresh = REPOSITORY_FORMAT_INIT;
832 memcpy(format, &fresh, sizeof(fresh));
835 int read_repository_format(struct repository_format *format, const char *path)
837 clear_repository_format(format);
838 git_config_from_file(check_repo_format, path, format);
839 if (format->version == -1)
840 clear_repository_format(format);
841 return format->version;
844 void clear_repository_format(struct repository_format *format)
846 string_list_clear(&format->unknown_extensions, 0);
847 string_list_clear(&format->v1_only_extensions, 0);
848 free(format->work_tree);
849 free(format->partial_clone);
850 init_repository_format(format);
853 int verify_repository_format(const struct repository_format *format,
854 struct strbuf *err)
856 if (GIT_REPO_VERSION_READ < format->version) {
857 strbuf_addf(err, _("Expected git repo version <= %d, found %d"),
858 GIT_REPO_VERSION_READ, format->version);
859 return -1;
862 if (format->version >= 1 && format->unknown_extensions.nr) {
863 int i;
865 strbuf_addstr(err, Q_("unknown repository extension found:",
866 "unknown repository extensions found:",
867 format->unknown_extensions.nr));
869 for (i = 0; i < format->unknown_extensions.nr; i++)
870 strbuf_addf(err, "\n\t%s",
871 format->unknown_extensions.items[i].string);
872 return -1;
875 if (format->version == 0 && format->v1_only_extensions.nr) {
876 int i;
878 strbuf_addstr(err,
879 Q_("repo version is 0, but v1-only extension found:",
880 "repo version is 0, but v1-only extensions found:",
881 format->v1_only_extensions.nr));
883 for (i = 0; i < format->v1_only_extensions.nr; i++)
884 strbuf_addf(err, "\n\t%s",
885 format->v1_only_extensions.items[i].string);
886 return -1;
889 return 0;
892 void read_gitfile_error_die(int error_code, const char *path, const char *dir)
894 switch (error_code) {
895 case READ_GITFILE_ERR_STAT_FAILED:
896 case READ_GITFILE_ERR_NOT_A_FILE:
897 /* non-fatal; follow return path */
898 break;
899 case READ_GITFILE_ERR_OPEN_FAILED:
900 die_errno(_("error opening '%s'"), path);
901 case READ_GITFILE_ERR_TOO_LARGE:
902 die(_("too large to be a .git file: '%s'"), path);
903 case READ_GITFILE_ERR_READ_FAILED:
904 die(_("error reading %s"), path);
905 case READ_GITFILE_ERR_INVALID_FORMAT:
906 die(_("invalid gitfile format: %s"), path);
907 case READ_GITFILE_ERR_NO_PATH:
908 die(_("no path in gitfile: %s"), path);
909 case READ_GITFILE_ERR_NOT_A_REPO:
910 die(_("not a git repository: %s"), dir);
911 default:
912 BUG("unknown error code");
917 * Try to read the location of the git directory from the .git file,
918 * return path to git directory if found. The return value comes from
919 * a shared buffer.
921 * On failure, if return_error_code is not NULL, return_error_code
922 * will be set to an error code and NULL will be returned. If
923 * return_error_code is NULL the function will die instead (for most
924 * cases).
926 const char *read_gitfile_gently(const char *path, int *return_error_code)
928 const int max_file_size = 1 << 20; /* 1MB */
929 int error_code = 0;
930 char *buf = NULL;
931 char *dir = NULL;
932 const char *slash;
933 struct stat st;
934 int fd;
935 ssize_t len;
936 static struct strbuf realpath = STRBUF_INIT;
938 if (stat(path, &st)) {
939 /* NEEDSWORK: discern between ENOENT vs other errors */
940 error_code = READ_GITFILE_ERR_STAT_FAILED;
941 goto cleanup_return;
943 if (!S_ISREG(st.st_mode)) {
944 error_code = READ_GITFILE_ERR_NOT_A_FILE;
945 goto cleanup_return;
947 if (st.st_size > max_file_size) {
948 error_code = READ_GITFILE_ERR_TOO_LARGE;
949 goto cleanup_return;
951 fd = open(path, O_RDONLY);
952 if (fd < 0) {
953 error_code = READ_GITFILE_ERR_OPEN_FAILED;
954 goto cleanup_return;
956 buf = xmallocz(st.st_size);
957 len = read_in_full(fd, buf, st.st_size);
958 close(fd);
959 if (len != st.st_size) {
960 error_code = READ_GITFILE_ERR_READ_FAILED;
961 goto cleanup_return;
963 if (!starts_with(buf, "gitdir: ")) {
964 error_code = READ_GITFILE_ERR_INVALID_FORMAT;
965 goto cleanup_return;
967 while (buf[len - 1] == '\n' || buf[len - 1] == '\r')
968 len--;
969 if (len < 9) {
970 error_code = READ_GITFILE_ERR_NO_PATH;
971 goto cleanup_return;
973 buf[len] = '\0';
974 dir = buf + 8;
976 if (!is_absolute_path(dir) && (slash = strrchr(path, '/'))) {
977 size_t pathlen = slash+1 - path;
978 dir = xstrfmt("%.*s%.*s", (int)pathlen, path,
979 (int)(len - 8), buf + 8);
980 free(buf);
981 buf = dir;
983 if (!is_git_directory(dir)) {
984 error_code = READ_GITFILE_ERR_NOT_A_REPO;
985 goto cleanup_return;
988 strbuf_realpath(&realpath, dir, 1);
989 path = realpath.buf;
991 cleanup_return:
992 if (return_error_code)
993 *return_error_code = error_code;
994 else if (error_code)
995 read_gitfile_error_die(error_code, path, dir);
997 free(buf);
998 return error_code ? NULL : path;
1001 static const char *setup_explicit_git_dir(const char *gitdirenv,
1002 struct strbuf *cwd,
1003 struct repository_format *repo_fmt,
1004 int *nongit_ok)
1006 const char *work_tree_env = getenv(GIT_WORK_TREE_ENVIRONMENT);
1007 const char *worktree;
1008 char *gitfile;
1009 int offset;
1011 if (PATH_MAX - 40 < strlen(gitdirenv))
1012 die(_("'$%s' too big"), GIT_DIR_ENVIRONMENT);
1014 gitfile = (char*)read_gitfile(gitdirenv);
1015 if (gitfile) {
1016 gitfile = xstrdup(gitfile);
1017 gitdirenv = gitfile;
1020 if (!is_git_directory(gitdirenv)) {
1021 if (nongit_ok) {
1022 *nongit_ok = 1;
1023 free(gitfile);
1024 return NULL;
1026 die(_("not a git repository: '%s'"), gitdirenv);
1029 if (check_repository_format_gently(gitdirenv, repo_fmt, nongit_ok)) {
1030 free(gitfile);
1031 return NULL;
1034 /* #3, #7, #11, #15, #19, #23, #27, #31 (see t1510) */
1035 if (work_tree_env)
1036 set_git_work_tree(work_tree_env);
1037 else if (is_bare_repository_cfg > 0) {
1038 if (git_work_tree_cfg) {
1039 /* #22.2, #30 */
1040 warning("core.bare and core.worktree do not make sense");
1041 work_tree_config_is_bogus = 1;
1044 /* #18, #26 */
1045 set_git_dir(gitdirenv, 0);
1046 free(gitfile);
1047 return NULL;
1049 else if (git_work_tree_cfg) { /* #6, #14 */
1050 if (is_absolute_path(git_work_tree_cfg))
1051 set_git_work_tree(git_work_tree_cfg);
1052 else {
1053 char *core_worktree;
1054 if (chdir(gitdirenv))
1055 die_errno(_("cannot chdir to '%s'"), gitdirenv);
1056 if (chdir(git_work_tree_cfg))
1057 die_errno(_("cannot chdir to '%s'"), git_work_tree_cfg);
1058 core_worktree = xgetcwd();
1059 if (chdir(cwd->buf))
1060 die_errno(_("cannot come back to cwd"));
1061 set_git_work_tree(core_worktree);
1062 free(core_worktree);
1065 else if (!git_env_bool(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, 1)) {
1066 /* #16d */
1067 set_git_dir(gitdirenv, 0);
1068 free(gitfile);
1069 return NULL;
1071 else /* #2, #10 */
1072 set_git_work_tree(".");
1074 /* set_git_work_tree() must have been called by now */
1075 worktree = repo_get_work_tree(the_repository);
1077 /* both repo_get_work_tree() and cwd are already normalized */
1078 if (!strcmp(cwd->buf, worktree)) { /* cwd == worktree */
1079 set_git_dir(gitdirenv, 0);
1080 free(gitfile);
1081 return NULL;
1084 offset = dir_inside_of(cwd->buf, worktree);
1085 if (offset >= 0) { /* cwd inside worktree? */
1086 set_git_dir(gitdirenv, 1);
1087 if (chdir(worktree))
1088 die_errno(_("cannot chdir to '%s'"), worktree);
1089 strbuf_addch(cwd, '/');
1090 free(gitfile);
1091 return cwd->buf + offset;
1094 /* cwd outside worktree */
1095 set_git_dir(gitdirenv, 0);
1096 free(gitfile);
1097 return NULL;
1100 static const char *setup_discovered_git_dir(const char *gitdir,
1101 struct strbuf *cwd, int offset,
1102 struct repository_format *repo_fmt,
1103 int *nongit_ok)
1105 if (check_repository_format_gently(gitdir, repo_fmt, nongit_ok))
1106 return NULL;
1108 /* --work-tree is set without --git-dir; use discovered one */
1109 if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
1110 char *to_free = NULL;
1111 const char *ret;
1113 if (offset != cwd->len && !is_absolute_path(gitdir))
1114 gitdir = to_free = real_pathdup(gitdir, 1);
1115 if (chdir(cwd->buf))
1116 die_errno(_("cannot come back to cwd"));
1117 ret = setup_explicit_git_dir(gitdir, cwd, repo_fmt, nongit_ok);
1118 free(to_free);
1119 return ret;
1122 /* #16.2, #17.2, #20.2, #21.2, #24, #25, #28, #29 (see t1510) */
1123 if (is_bare_repository_cfg > 0) {
1124 set_git_dir(gitdir, (offset != cwd->len));
1125 if (chdir(cwd->buf))
1126 die_errno(_("cannot come back to cwd"));
1127 return NULL;
1130 /* #0, #1, #5, #8, #9, #12, #13 */
1131 set_git_work_tree(".");
1132 if (strcmp(gitdir, DEFAULT_GIT_DIR_ENVIRONMENT))
1133 set_git_dir(gitdir, 0);
1134 inside_git_dir = 0;
1135 inside_work_tree = 1;
1136 if (offset >= cwd->len)
1137 return NULL;
1139 /* Make "offset" point past the '/' (already the case for root dirs) */
1140 if (offset != offset_1st_component(cwd->buf))
1141 offset++;
1142 /* Add a '/' at the end */
1143 strbuf_addch(cwd, '/');
1144 return cwd->buf + offset;
1147 /* #16.1, #17.1, #20.1, #21.1, #22.1 (see t1510) */
1148 static const char *setup_bare_git_dir(struct strbuf *cwd, int offset,
1149 struct repository_format *repo_fmt,
1150 int *nongit_ok)
1152 int root_len;
1154 if (check_repository_format_gently(".", repo_fmt, nongit_ok))
1155 return NULL;
1157 setenv(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, "0", 1);
1159 /* --work-tree is set without --git-dir; use discovered one */
1160 if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
1161 static const char *gitdir;
1163 gitdir = offset == cwd->len ? "." : xmemdupz(cwd->buf, offset);
1164 if (chdir(cwd->buf))
1165 die_errno(_("cannot come back to cwd"));
1166 return setup_explicit_git_dir(gitdir, cwd, repo_fmt, nongit_ok);
1169 inside_git_dir = 1;
1170 inside_work_tree = 0;
1171 if (offset != cwd->len) {
1172 if (chdir(cwd->buf))
1173 die_errno(_("cannot come back to cwd"));
1174 root_len = offset_1st_component(cwd->buf);
1175 strbuf_setlen(cwd, offset > root_len ? offset : root_len);
1176 set_git_dir(cwd->buf, 0);
1178 else
1179 set_git_dir(".", 0);
1180 return NULL;
1183 static dev_t get_device_or_die(const char *path, const char *prefix, int prefix_len)
1185 struct stat buf;
1186 if (stat(path, &buf)) {
1187 die_errno(_("failed to stat '%*s%s%s'"),
1188 prefix_len,
1189 prefix ? prefix : "",
1190 prefix ? "/" : "", path);
1192 return buf.st_dev;
1196 * A "string_list_each_func_t" function that canonicalizes an entry
1197 * from GIT_CEILING_DIRECTORIES using real_pathdup(), or
1198 * discards it if unusable. The presence of an empty entry in
1199 * GIT_CEILING_DIRECTORIES turns off canonicalization for all
1200 * subsequent entries.
1202 static int canonicalize_ceiling_entry(struct string_list_item *item,
1203 void *cb_data)
1205 int *empty_entry_found = cb_data;
1206 char *ceil = item->string;
1208 if (!*ceil) {
1209 *empty_entry_found = 1;
1210 return 0;
1211 } else if (!is_absolute_path(ceil)) {
1212 return 0;
1213 } else if (*empty_entry_found) {
1214 /* Keep entry but do not canonicalize it */
1215 return 1;
1216 } else {
1217 char *real_path = real_pathdup(ceil, 0);
1218 if (!real_path) {
1219 return 0;
1221 free(item->string);
1222 item->string = real_path;
1223 return 1;
1227 struct safe_directory_data {
1228 char *path;
1229 int is_safe;
1232 static int safe_directory_cb(const char *key, const char *value,
1233 const struct config_context *ctx UNUSED, void *d)
1235 struct safe_directory_data *data = d;
1237 if (strcmp(key, "safe.directory"))
1238 return 0;
1240 if (!value || !*value) {
1241 data->is_safe = 0;
1242 } else if (!strcmp(value, "*")) {
1243 data->is_safe = 1;
1244 } else {
1245 char *allowed = NULL;
1247 if (!git_config_pathname(&allowed, key, value)) {
1248 char *normalized = NULL;
1251 * Setting safe.directory to a non-absolute path
1252 * makes little sense---it won't be relative to
1253 * the configuration file the item is defined in.
1254 * Except for ".", which means "if we are at the top
1255 * level of a repository, then it is OK", which is
1256 * slightly tighter than "*" that allows discovery.
1258 if (!is_absolute_path(allowed) && strcmp(allowed, ".")) {
1259 warning(_("safe.directory '%s' not absolute"),
1260 allowed);
1261 goto next;
1265 * A .gitconfig in $HOME may be shared across
1266 * different machines and safe.directory entries
1267 * may or may not exist as paths on all of these
1268 * machines. In other words, it is not a warning
1269 * worthy event when there is no such path on this
1270 * machine---the entry may be useful elsewhere.
1272 normalized = real_pathdup(allowed, 0);
1273 if (!normalized)
1274 goto next;
1276 if (ends_with(normalized, "/*")) {
1277 size_t len = strlen(normalized);
1278 if (!fspathncmp(normalized, data->path, len - 1))
1279 data->is_safe = 1;
1280 } else if (!fspathcmp(data->path, normalized)) {
1281 data->is_safe = 1;
1283 next:
1284 free(normalized);
1285 free(allowed);
1289 return 0;
1293 * Check if a repository is safe, by verifying the ownership of the
1294 * worktree (if any), the git directory, and the gitfile (if any).
1296 * Exemptions for known-safe repositories can be added via `safe.directory`
1297 * config settings; for non-bare repositories, their worktree needs to be
1298 * added, for bare ones their git directory.
1300 static int ensure_valid_ownership(const char *gitfile,
1301 const char *worktree, const char *gitdir,
1302 struct strbuf *report)
1304 struct safe_directory_data data = { 0 };
1306 if (!git_env_bool("GIT_TEST_ASSUME_DIFFERENT_OWNER", 0) &&
1307 (!gitfile || is_path_owned_by_current_user(gitfile, report)) &&
1308 (!worktree || is_path_owned_by_current_user(worktree, report)) &&
1309 (!gitdir || is_path_owned_by_current_user(gitdir, report)))
1310 return 1;
1313 * normalize the data.path for comparison with normalized paths
1314 * that come from the configuration file. The path is unsafe
1315 * if it cannot be normalized.
1317 data.path = real_pathdup(worktree ? worktree : gitdir, 0);
1318 if (!data.path)
1319 return 0;
1322 * data.path is the "path" that identifies the repository and it is
1323 * constant regardless of what failed above. data.is_safe should be
1324 * initialized to false, and might be changed by the callback.
1326 git_protected_config(safe_directory_cb, &data);
1328 free(data.path);
1329 return data.is_safe;
1332 void die_upon_dubious_ownership(const char *gitfile, const char *worktree,
1333 const char *gitdir)
1335 struct strbuf report = STRBUF_INIT, quoted = STRBUF_INIT;
1336 const char *path;
1338 if (ensure_valid_ownership(gitfile, worktree, gitdir, &report))
1339 return;
1341 strbuf_complete(&report, '\n');
1342 path = gitfile ? gitfile : gitdir;
1343 sq_quote_buf_pretty(&quoted, path);
1345 die(_("detected dubious ownership in repository at '%s'\n"
1346 "%s"
1347 "To add an exception for this directory, call:\n"
1348 "\n"
1349 "\tgit config --global --add safe.directory %s"),
1350 path, report.buf, quoted.buf);
1353 static int allowed_bare_repo_cb(const char *key, const char *value,
1354 const struct config_context *ctx UNUSED,
1355 void *d)
1357 enum allowed_bare_repo *allowed_bare_repo = d;
1359 if (strcasecmp(key, "safe.bareRepository"))
1360 return 0;
1362 if (!strcmp(value, "explicit")) {
1363 *allowed_bare_repo = ALLOWED_BARE_REPO_EXPLICIT;
1364 return 0;
1366 if (!strcmp(value, "all")) {
1367 *allowed_bare_repo = ALLOWED_BARE_REPO_ALL;
1368 return 0;
1370 return -1;
1373 static enum allowed_bare_repo get_allowed_bare_repo(void)
1375 enum allowed_bare_repo result = ALLOWED_BARE_REPO_ALL;
1376 git_protected_config(allowed_bare_repo_cb, &result);
1377 return result;
1380 static const char *allowed_bare_repo_to_string(
1381 enum allowed_bare_repo allowed_bare_repo)
1383 switch (allowed_bare_repo) {
1384 case ALLOWED_BARE_REPO_EXPLICIT:
1385 return "explicit";
1386 case ALLOWED_BARE_REPO_ALL:
1387 return "all";
1388 default:
1389 BUG("invalid allowed_bare_repo %d",
1390 allowed_bare_repo);
1392 return NULL;
1395 static int is_implicit_bare_repo(const char *path)
1398 * what we found is a ".git" directory at the root of
1399 * the working tree.
1401 if (ends_with_path_components(path, ".git"))
1402 return 1;
1405 * we are inside $GIT_DIR of a secondary worktree of a
1406 * non-bare repository.
1408 if (strstr(path, "/.git/worktrees/"))
1409 return 1;
1412 * we are inside $GIT_DIR of a worktree of a non-embedded
1413 * submodule, whose superproject is not a bare repository.
1415 if (strstr(path, "/.git/modules/"))
1416 return 1;
1418 return 0;
1422 * We cannot decide in this function whether we are in the work tree or
1423 * not, since the config can only be read _after_ this function was called.
1425 * Also, we avoid changing any global state (such as the current working
1426 * directory) to allow early callers.
1428 * The directory where the search should start needs to be passed in via the
1429 * `dir` parameter; upon return, the `dir` buffer will contain the path of
1430 * the directory where the search ended, and `gitdir` will contain the path of
1431 * the discovered .git/ directory, if any. If `gitdir` is not absolute, it
1432 * is relative to `dir` (i.e. *not* necessarily the cwd).
1434 static enum discovery_result setup_git_directory_gently_1(struct strbuf *dir,
1435 struct strbuf *gitdir,
1436 struct strbuf *report,
1437 int die_on_error)
1439 const char *env_ceiling_dirs = getenv(CEILING_DIRECTORIES_ENVIRONMENT);
1440 struct string_list ceiling_dirs = STRING_LIST_INIT_DUP;
1441 const char *gitdirenv;
1442 int ceil_offset = -1, min_offset = offset_1st_component(dir->buf);
1443 dev_t current_device = 0;
1444 int one_filesystem = 1;
1447 * If GIT_DIR is set explicitly, we're not going
1448 * to do any discovery, but we still do repository
1449 * validation.
1451 gitdirenv = getenv(GIT_DIR_ENVIRONMENT);
1452 if (gitdirenv) {
1453 strbuf_addstr(gitdir, gitdirenv);
1454 return GIT_DIR_EXPLICIT;
1457 if (env_ceiling_dirs) {
1458 int empty_entry_found = 0;
1460 string_list_split(&ceiling_dirs, env_ceiling_dirs, PATH_SEP, -1);
1461 filter_string_list(&ceiling_dirs, 0,
1462 canonicalize_ceiling_entry, &empty_entry_found);
1463 ceil_offset = longest_ancestor_length(dir->buf, &ceiling_dirs);
1464 string_list_clear(&ceiling_dirs, 0);
1467 if (ceil_offset < 0)
1468 ceil_offset = min_offset - 2;
1470 if (min_offset && min_offset == dir->len &&
1471 !is_dir_sep(dir->buf[min_offset - 1])) {
1472 strbuf_addch(dir, '/');
1473 min_offset++;
1477 * Test in the following order (relative to the dir):
1478 * - .git (file containing "gitdir: <path>")
1479 * - .git/
1480 * - ./ (bare)
1481 * - ../.git
1482 * - ../.git/
1483 * - ../ (bare)
1484 * - ../../.git
1485 * etc.
1487 one_filesystem = !git_env_bool("GIT_DISCOVERY_ACROSS_FILESYSTEM", 0);
1488 if (one_filesystem)
1489 current_device = get_device_or_die(dir->buf, NULL, 0);
1490 for (;;) {
1491 int offset = dir->len, error_code = 0;
1492 char *gitdir_path = NULL;
1493 char *gitfile = NULL;
1495 if (offset > min_offset)
1496 strbuf_addch(dir, '/');
1497 strbuf_addstr(dir, DEFAULT_GIT_DIR_ENVIRONMENT);
1498 gitdirenv = read_gitfile_gently(dir->buf, die_on_error ?
1499 NULL : &error_code);
1500 if (!gitdirenv) {
1501 if (die_on_error ||
1502 error_code == READ_GITFILE_ERR_NOT_A_FILE) {
1503 /* NEEDSWORK: fail if .git is not file nor dir */
1504 if (is_git_directory(dir->buf)) {
1505 gitdirenv = DEFAULT_GIT_DIR_ENVIRONMENT;
1506 gitdir_path = xstrdup(dir->buf);
1508 } else if (error_code != READ_GITFILE_ERR_STAT_FAILED)
1509 return GIT_DIR_INVALID_GITFILE;
1510 } else
1511 gitfile = xstrdup(dir->buf);
1513 * Earlier, we tentatively added DEFAULT_GIT_DIR_ENVIRONMENT
1514 * to check that directory for a repository.
1515 * Now trim that tentative addition away, because we want to
1516 * focus on the real directory we are in.
1518 strbuf_setlen(dir, offset);
1519 if (gitdirenv) {
1520 enum discovery_result ret;
1521 const char *gitdir_candidate =
1522 gitdir_path ? gitdir_path : gitdirenv;
1524 if (ensure_valid_ownership(gitfile, dir->buf,
1525 gitdir_candidate, report)) {
1526 strbuf_addstr(gitdir, gitdirenv);
1527 ret = GIT_DIR_DISCOVERED;
1528 } else
1529 ret = GIT_DIR_INVALID_OWNERSHIP;
1532 * Earlier, during discovery, we might have allocated
1533 * string copies for gitdir_path or gitfile so make
1534 * sure we don't leak by freeing them now, before
1535 * leaving the loop and function.
1537 * Note: gitdirenv will be non-NULL whenever these are
1538 * allocated, therefore we need not take care of releasing
1539 * them outside of this conditional block.
1541 free(gitdir_path);
1542 free(gitfile);
1544 return ret;
1547 if (is_git_directory(dir->buf)) {
1548 trace2_data_string("setup", NULL, "implicit-bare-repository", dir->buf);
1549 if (get_allowed_bare_repo() == ALLOWED_BARE_REPO_EXPLICIT &&
1550 !is_implicit_bare_repo(dir->buf))
1551 return GIT_DIR_DISALLOWED_BARE;
1552 if (!ensure_valid_ownership(NULL, NULL, dir->buf, report))
1553 return GIT_DIR_INVALID_OWNERSHIP;
1554 strbuf_addstr(gitdir, ".");
1555 return GIT_DIR_BARE;
1558 if (offset <= min_offset)
1559 return GIT_DIR_HIT_CEILING;
1561 while (--offset > ceil_offset && !is_dir_sep(dir->buf[offset]))
1562 ; /* continue */
1563 if (offset <= ceil_offset)
1564 return GIT_DIR_HIT_CEILING;
1566 strbuf_setlen(dir, offset > min_offset ? offset : min_offset);
1567 if (one_filesystem &&
1568 current_device != get_device_or_die(dir->buf, NULL, offset))
1569 return GIT_DIR_HIT_MOUNT_POINT;
1573 enum discovery_result discover_git_directory_reason(struct strbuf *commondir,
1574 struct strbuf *gitdir)
1576 struct strbuf dir = STRBUF_INIT, err = STRBUF_INIT;
1577 size_t gitdir_offset = gitdir->len, cwd_len;
1578 size_t commondir_offset = commondir->len;
1579 struct repository_format candidate = REPOSITORY_FORMAT_INIT;
1580 enum discovery_result result;
1582 if (strbuf_getcwd(&dir))
1583 return GIT_DIR_CWD_FAILURE;
1585 cwd_len = dir.len;
1586 result = setup_git_directory_gently_1(&dir, gitdir, NULL, 0);
1587 if (result <= 0) {
1588 strbuf_release(&dir);
1589 return result;
1593 * The returned gitdir is relative to dir, and if dir does not reflect
1594 * the current working directory, we simply make the gitdir absolute.
1596 if (dir.len < cwd_len && !is_absolute_path(gitdir->buf + gitdir_offset)) {
1597 /* Avoid a trailing "/." */
1598 if (!strcmp(".", gitdir->buf + gitdir_offset))
1599 strbuf_setlen(gitdir, gitdir_offset);
1600 else
1601 strbuf_addch(&dir, '/');
1602 strbuf_insert(gitdir, gitdir_offset, dir.buf, dir.len);
1605 get_common_dir(commondir, gitdir->buf + gitdir_offset);
1607 strbuf_reset(&dir);
1608 strbuf_addf(&dir, "%s/config", commondir->buf + commondir_offset);
1609 read_repository_format(&candidate, dir.buf);
1610 strbuf_release(&dir);
1612 if (verify_repository_format(&candidate, &err) < 0) {
1613 warning("ignoring git dir '%s': %s",
1614 gitdir->buf + gitdir_offset, err.buf);
1615 strbuf_release(&err);
1616 strbuf_setlen(commondir, commondir_offset);
1617 strbuf_setlen(gitdir, gitdir_offset);
1618 clear_repository_format(&candidate);
1619 return GIT_DIR_INVALID_FORMAT;
1622 clear_repository_format(&candidate);
1623 return result;
1626 void setup_git_env(const char *git_dir)
1628 char *git_replace_ref_base;
1629 const char *shallow_file;
1630 const char *replace_ref_base;
1631 struct set_gitdir_args args = { NULL };
1632 struct strvec to_free = STRVEC_INIT;
1634 args.commondir = getenv_safe(&to_free, GIT_COMMON_DIR_ENVIRONMENT);
1635 args.object_dir = getenv_safe(&to_free, DB_ENVIRONMENT);
1636 args.graft_file = getenv_safe(&to_free, GRAFT_ENVIRONMENT);
1637 args.index_file = getenv_safe(&to_free, INDEX_ENVIRONMENT);
1638 args.alternate_db = getenv_safe(&to_free, ALTERNATE_DB_ENVIRONMENT);
1639 if (getenv(GIT_QUARANTINE_ENVIRONMENT)) {
1640 args.disable_ref_updates = 1;
1643 repo_set_gitdir(the_repository, git_dir, &args);
1644 strvec_clear(&to_free);
1646 if (getenv(NO_REPLACE_OBJECTS_ENVIRONMENT))
1647 disable_replace_refs();
1648 replace_ref_base = getenv(GIT_REPLACE_REF_BASE_ENVIRONMENT);
1649 git_replace_ref_base = xstrdup(replace_ref_base ? replace_ref_base
1650 : "refs/replace/");
1651 update_ref_namespace(NAMESPACE_REPLACE, git_replace_ref_base);
1653 shallow_file = getenv(GIT_SHALLOW_FILE_ENVIRONMENT);
1654 if (shallow_file)
1655 set_alternate_shallow_file(the_repository, shallow_file, 0);
1657 if (git_env_bool(NO_LAZY_FETCH_ENVIRONMENT, 0))
1658 fetch_if_missing = 0;
1661 static void set_git_dir_1(const char *path)
1663 xsetenv(GIT_DIR_ENVIRONMENT, path, 1);
1664 setup_git_env(path);
1667 static void update_relative_gitdir(const char *name UNUSED,
1668 const char *old_cwd,
1669 const char *new_cwd,
1670 void *data UNUSED)
1672 char *path = reparent_relative_path(old_cwd, new_cwd,
1673 repo_get_git_dir(the_repository));
1674 struct tmp_objdir *tmp_objdir = tmp_objdir_unapply_primary_odb();
1676 trace_printf_key(&trace_setup_key,
1677 "setup: move $GIT_DIR to '%s'",
1678 path);
1679 set_git_dir_1(path);
1680 if (tmp_objdir)
1681 tmp_objdir_reapply_primary_odb(tmp_objdir, old_cwd, new_cwd);
1682 free(path);
1685 void set_git_dir(const char *path, int make_realpath)
1687 struct strbuf realpath = STRBUF_INIT;
1689 if (make_realpath) {
1690 strbuf_realpath(&realpath, path, 1);
1691 path = realpath.buf;
1694 set_git_dir_1(path);
1695 if (!is_absolute_path(path))
1696 chdir_notify_register(NULL, update_relative_gitdir, NULL);
1698 strbuf_release(&realpath);
1701 static int git_work_tree_initialized;
1704 * Note. This works only before you used a work tree. This was added
1705 * primarily to support git-clone to work in a new repository it just
1706 * created, and is not meant to flip between different work trees.
1708 void set_git_work_tree(const char *new_work_tree)
1710 if (git_work_tree_initialized) {
1711 struct strbuf realpath = STRBUF_INIT;
1713 strbuf_realpath(&realpath, new_work_tree, 1);
1714 new_work_tree = realpath.buf;
1715 if (strcmp(new_work_tree, the_repository->worktree))
1716 die("internal error: work tree has already been set\n"
1717 "Current worktree: %s\nNew worktree: %s",
1718 the_repository->worktree, new_work_tree);
1719 strbuf_release(&realpath);
1720 return;
1722 git_work_tree_initialized = 1;
1723 repo_set_worktree(the_repository, new_work_tree);
1726 const char *setup_git_directory_gently(int *nongit_ok)
1728 static struct strbuf cwd = STRBUF_INIT;
1729 struct strbuf dir = STRBUF_INIT, gitdir = STRBUF_INIT, report = STRBUF_INIT;
1730 const char *prefix = NULL;
1731 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
1734 * We may have read an incomplete configuration before
1735 * setting-up the git directory. If so, clear the cache so
1736 * that the next queries to the configuration reload complete
1737 * configuration (including the per-repo config file that we
1738 * ignored previously).
1740 git_config_clear();
1743 * Let's assume that we are in a git repository.
1744 * If it turns out later that we are somewhere else, the value will be
1745 * updated accordingly.
1747 if (nongit_ok)
1748 *nongit_ok = 0;
1750 if (strbuf_getcwd(&cwd))
1751 die_errno(_("Unable to read current working directory"));
1752 strbuf_addbuf(&dir, &cwd);
1754 switch (setup_git_directory_gently_1(&dir, &gitdir, &report, 1)) {
1755 case GIT_DIR_EXPLICIT:
1756 prefix = setup_explicit_git_dir(gitdir.buf, &cwd, &repo_fmt, nongit_ok);
1757 break;
1758 case GIT_DIR_DISCOVERED:
1759 if (dir.len < cwd.len && chdir(dir.buf))
1760 die(_("cannot change to '%s'"), dir.buf);
1761 prefix = setup_discovered_git_dir(gitdir.buf, &cwd, dir.len,
1762 &repo_fmt, nongit_ok);
1763 break;
1764 case GIT_DIR_BARE:
1765 if (dir.len < cwd.len && chdir(dir.buf))
1766 die(_("cannot change to '%s'"), dir.buf);
1767 prefix = setup_bare_git_dir(&cwd, dir.len, &repo_fmt, nongit_ok);
1768 break;
1769 case GIT_DIR_HIT_CEILING:
1770 if (!nongit_ok)
1771 die(_("not a git repository (or any of the parent directories): %s"),
1772 DEFAULT_GIT_DIR_ENVIRONMENT);
1773 *nongit_ok = 1;
1774 break;
1775 case GIT_DIR_HIT_MOUNT_POINT:
1776 if (!nongit_ok)
1777 die(_("not a git repository (or any parent up to mount point %s)\n"
1778 "Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set)."),
1779 dir.buf);
1780 *nongit_ok = 1;
1781 break;
1782 case GIT_DIR_INVALID_OWNERSHIP:
1783 if (!nongit_ok) {
1784 struct strbuf quoted = STRBUF_INIT;
1786 strbuf_complete(&report, '\n');
1787 sq_quote_buf_pretty(&quoted, dir.buf);
1788 die(_("detected dubious ownership in repository at '%s'\n"
1789 "%s"
1790 "To add an exception for this directory, call:\n"
1791 "\n"
1792 "\tgit config --global --add safe.directory %s"),
1793 dir.buf, report.buf, quoted.buf);
1795 *nongit_ok = 1;
1796 break;
1797 case GIT_DIR_DISALLOWED_BARE:
1798 if (!nongit_ok) {
1799 die(_("cannot use bare repository '%s' (safe.bareRepository is '%s')"),
1800 dir.buf,
1801 allowed_bare_repo_to_string(get_allowed_bare_repo()));
1803 *nongit_ok = 1;
1804 break;
1805 case GIT_DIR_CWD_FAILURE:
1806 case GIT_DIR_INVALID_FORMAT:
1808 * As a safeguard against setup_git_directory_gently_1 returning
1809 * these values, fallthrough to BUG. Otherwise it is possible to
1810 * set startup_info->have_repository to 1 when we did nothing to
1811 * find a repository.
1813 default:
1814 BUG("unhandled setup_git_directory_gently_1() result");
1818 * At this point, nongit_ok is stable. If it is non-NULL and points
1819 * to a non-zero value, then this means that we haven't found a
1820 * repository and that the caller expects startup_info to reflect
1821 * this.
1823 * Regardless of the state of nongit_ok, startup_info->prefix and
1824 * the GIT_PREFIX environment variable must always match. For details
1825 * see Documentation/config/alias.txt.
1827 if (nongit_ok && *nongit_ok)
1828 startup_info->have_repository = 0;
1829 else
1830 startup_info->have_repository = 1;
1833 * Not all paths through the setup code will call 'set_git_dir()' (which
1834 * directly sets up the environment) so in order to guarantee that the
1835 * environment is in a consistent state after setup, explicitly setup
1836 * the environment if we have a repository.
1838 * NEEDSWORK: currently we allow bogus GIT_DIR values to be set in some
1839 * code paths so we also need to explicitly setup the environment if
1840 * the user has set GIT_DIR. It may be beneficial to disallow bogus
1841 * GIT_DIR values at some point in the future.
1843 if (/* GIT_DIR_EXPLICIT, GIT_DIR_DISCOVERED, GIT_DIR_BARE */
1844 startup_info->have_repository ||
1845 /* GIT_DIR_EXPLICIT */
1846 getenv(GIT_DIR_ENVIRONMENT)) {
1847 if (!the_repository->gitdir) {
1848 const char *gitdir = getenv(GIT_DIR_ENVIRONMENT);
1849 if (!gitdir)
1850 gitdir = DEFAULT_GIT_DIR_ENVIRONMENT;
1851 setup_git_env(gitdir);
1853 if (startup_info->have_repository) {
1854 repo_set_hash_algo(the_repository, repo_fmt.hash_algo);
1855 repo_set_compat_hash_algo(the_repository,
1856 repo_fmt.compat_hash_algo);
1857 repo_set_ref_storage_format(the_repository,
1858 repo_fmt.ref_storage_format);
1859 the_repository->repository_format_worktree_config =
1860 repo_fmt.worktree_config;
1861 the_repository->repository_format_relative_worktrees =
1862 repo_fmt.relative_worktrees;
1863 /* take ownership of repo_fmt.partial_clone */
1864 the_repository->repository_format_partial_clone =
1865 repo_fmt.partial_clone;
1866 repo_fmt.partial_clone = NULL;
1870 * Since precompose_string_if_needed() needs to look at
1871 * the core.precomposeunicode configuration, this
1872 * has to happen after the above block that finds
1873 * out where the repository is, i.e. a preparation
1874 * for calling git_config_get_bool().
1876 if (prefix) {
1877 prefix = precompose_string_if_needed(prefix);
1878 startup_info->prefix = prefix;
1879 setenv(GIT_PREFIX_ENVIRONMENT, prefix, 1);
1880 } else {
1881 startup_info->prefix = NULL;
1882 setenv(GIT_PREFIX_ENVIRONMENT, "", 1);
1885 setup_original_cwd();
1887 strbuf_release(&dir);
1888 strbuf_release(&gitdir);
1889 strbuf_release(&report);
1890 clear_repository_format(&repo_fmt);
1892 return prefix;
1895 int git_config_perm(const char *var, const char *value)
1897 int i;
1898 char *endptr;
1900 if (!value)
1901 return PERM_GROUP;
1903 if (!strcmp(value, "umask"))
1904 return PERM_UMASK;
1905 if (!strcmp(value, "group"))
1906 return PERM_GROUP;
1907 if (!strcmp(value, "all") ||
1908 !strcmp(value, "world") ||
1909 !strcmp(value, "everybody"))
1910 return PERM_EVERYBODY;
1912 /* Parse octal numbers */
1913 i = strtol(value, &endptr, 8);
1915 /* If not an octal number, maybe true/false? */
1916 if (*endptr != 0)
1917 return git_config_bool(var, value) ? PERM_GROUP : PERM_UMASK;
1920 * Treat values 0, 1 and 2 as compatibility cases, otherwise it is
1921 * a chmod value to restrict to.
1923 switch (i) {
1924 case PERM_UMASK: /* 0 */
1925 return PERM_UMASK;
1926 case OLD_PERM_GROUP: /* 1 */
1927 return PERM_GROUP;
1928 case OLD_PERM_EVERYBODY: /* 2 */
1929 return PERM_EVERYBODY;
1932 /* A filemode value was given: 0xxx */
1934 if ((i & 0600) != 0600)
1935 die(_("problem with core.sharedRepository filemode value "
1936 "(0%.3o).\nThe owner of files must always have "
1937 "read and write permissions."), i);
1940 * Mask filemode value. Others can not get write permission.
1941 * x flags for directories are handled separately.
1943 return -(i & 0666);
1946 void check_repository_format(struct repository_format *fmt)
1948 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
1949 if (!fmt)
1950 fmt = &repo_fmt;
1951 check_repository_format_gently(repo_get_git_dir(the_repository), fmt, NULL);
1952 startup_info->have_repository = 1;
1953 repo_set_hash_algo(the_repository, fmt->hash_algo);
1954 repo_set_compat_hash_algo(the_repository, fmt->compat_hash_algo);
1955 repo_set_ref_storage_format(the_repository,
1956 fmt->ref_storage_format);
1957 the_repository->repository_format_worktree_config =
1958 fmt->worktree_config;
1959 the_repository->repository_format_relative_worktrees =
1960 fmt->relative_worktrees;
1961 the_repository->repository_format_partial_clone =
1962 xstrdup_or_null(fmt->partial_clone);
1963 clear_repository_format(&repo_fmt);
1967 * Returns the "prefix", a path to the current working directory
1968 * relative to the work tree root, or NULL, if the current working
1969 * directory is not a strict subdirectory of the work tree root. The
1970 * prefix always ends with a '/' character.
1972 const char *setup_git_directory(void)
1974 return setup_git_directory_gently(NULL);
1977 const char *resolve_gitdir_gently(const char *suspect, int *return_error_code)
1979 if (is_git_directory(suspect))
1980 return suspect;
1981 return read_gitfile_gently(suspect, return_error_code);
1984 /* if any standard file descriptor is missing open it to /dev/null */
1985 void sanitize_stdfds(void)
1987 int fd = xopen("/dev/null", O_RDWR);
1988 while (fd < 2)
1989 fd = xdup(fd);
1990 if (fd > 2)
1991 close(fd);
1994 int daemonize(void)
1996 #ifdef NO_POSIX_GOODIES
1997 errno = ENOSYS;
1998 return -1;
1999 #else
2000 switch (fork()) {
2001 case 0:
2002 break;
2003 case -1:
2004 die_errno(_("fork failed"));
2005 default:
2006 exit(0);
2008 if (setsid() == -1)
2009 die_errno(_("setsid failed"));
2010 close(0);
2011 close(1);
2012 close(2);
2013 sanitize_stdfds();
2014 return 0;
2015 #endif
2018 struct template_dir_cb_data {
2019 char *path;
2020 int initialized;
2023 static int template_dir_cb(const char *key, const char *value,
2024 const struct config_context *ctx UNUSED, void *d)
2026 struct template_dir_cb_data *data = d;
2028 if (strcmp(key, "init.templatedir"))
2029 return 0;
2031 if (!value) {
2032 data->path = NULL;
2033 } else {
2034 char *path = NULL;
2036 FREE_AND_NULL(data->path);
2037 if (!git_config_pathname(&path, key, value))
2038 data->path = path ? path : xstrdup(value);
2041 return 0;
2044 const char *get_template_dir(const char *option_template)
2046 const char *template_dir = option_template;
2048 if (!template_dir)
2049 template_dir = getenv(TEMPLATE_DIR_ENVIRONMENT);
2050 if (!template_dir) {
2051 static struct template_dir_cb_data data;
2053 if (!data.initialized) {
2054 git_protected_config(template_dir_cb, &data);
2055 data.initialized = 1;
2057 template_dir = data.path;
2059 if (!template_dir) {
2060 static char *dir;
2062 if (!dir)
2063 dir = system_path(DEFAULT_GIT_TEMPLATE_DIR);
2064 template_dir = dir;
2066 return template_dir;
2069 #ifdef NO_TRUSTABLE_FILEMODE
2070 #define TEST_FILEMODE 0
2071 #else
2072 #define TEST_FILEMODE 1
2073 #endif
2075 #define GIT_DEFAULT_HASH_ENVIRONMENT "GIT_DEFAULT_HASH"
2077 static void copy_templates_1(struct strbuf *path, struct strbuf *template_path,
2078 DIR *dir)
2080 size_t path_baselen = path->len;
2081 size_t template_baselen = template_path->len;
2082 struct dirent *de;
2084 /* Note: if ".git/hooks" file exists in the repository being
2085 * re-initialized, /etc/core-git/templates/hooks/update would
2086 * cause "git init" to fail here. I think this is sane but
2087 * it means that the set of templates we ship by default, along
2088 * with the way the namespace under .git/ is organized, should
2089 * be really carefully chosen.
2091 safe_create_dir(path->buf, 1);
2092 while ((de = readdir(dir)) != NULL) {
2093 struct stat st_git, st_template;
2094 int exists = 0;
2096 strbuf_setlen(path, path_baselen);
2097 strbuf_setlen(template_path, template_baselen);
2099 if (de->d_name[0] == '.')
2100 continue;
2101 strbuf_addstr(path, de->d_name);
2102 strbuf_addstr(template_path, de->d_name);
2103 if (lstat(path->buf, &st_git)) {
2104 if (errno != ENOENT)
2105 die_errno(_("cannot stat '%s'"), path->buf);
2107 else
2108 exists = 1;
2110 if (lstat(template_path->buf, &st_template))
2111 die_errno(_("cannot stat template '%s'"), template_path->buf);
2113 if (S_ISDIR(st_template.st_mode)) {
2114 DIR *subdir = opendir(template_path->buf);
2115 if (!subdir)
2116 die_errno(_("cannot opendir '%s'"), template_path->buf);
2117 strbuf_addch(path, '/');
2118 strbuf_addch(template_path, '/');
2119 copy_templates_1(path, template_path, subdir);
2120 closedir(subdir);
2122 else if (exists)
2123 continue;
2124 else if (S_ISLNK(st_template.st_mode)) {
2125 struct strbuf lnk = STRBUF_INIT;
2126 if (strbuf_readlink(&lnk, template_path->buf,
2127 st_template.st_size) < 0)
2128 die_errno(_("cannot readlink '%s'"), template_path->buf);
2129 if (symlink(lnk.buf, path->buf))
2130 die_errno(_("cannot symlink '%s' '%s'"),
2131 lnk.buf, path->buf);
2132 strbuf_release(&lnk);
2134 else if (S_ISREG(st_template.st_mode)) {
2135 if (copy_file(path->buf, template_path->buf, st_template.st_mode))
2136 die_errno(_("cannot copy '%s' to '%s'"),
2137 template_path->buf, path->buf);
2139 else
2140 error(_("ignoring template %s"), template_path->buf);
2144 static void copy_templates(const char *option_template)
2146 const char *template_dir = get_template_dir(option_template);
2147 struct strbuf path = STRBUF_INIT;
2148 struct strbuf template_path = STRBUF_INIT;
2149 size_t template_len;
2150 struct repository_format template_format = REPOSITORY_FORMAT_INIT;
2151 struct strbuf err = STRBUF_INIT;
2152 DIR *dir;
2153 char *to_free = NULL;
2155 if (!template_dir || !*template_dir)
2156 return;
2158 strbuf_addstr(&template_path, template_dir);
2159 strbuf_complete(&template_path, '/');
2160 template_len = template_path.len;
2162 dir = opendir(template_path.buf);
2163 if (!dir) {
2164 warning(_("templates not found in %s"), template_dir);
2165 goto free_return;
2168 /* Make sure that template is from the correct vintage */
2169 strbuf_addstr(&template_path, "config");
2170 read_repository_format(&template_format, template_path.buf);
2171 strbuf_setlen(&template_path, template_len);
2174 * No mention of version at all is OK, but anything else should be
2175 * verified.
2177 if (template_format.version >= 0 &&
2178 verify_repository_format(&template_format, &err) < 0) {
2179 warning(_("not copying templates from '%s': %s"),
2180 template_dir, err.buf);
2181 strbuf_release(&err);
2182 goto close_free_return;
2185 strbuf_addstr(&path, repo_get_common_dir(the_repository));
2186 strbuf_complete(&path, '/');
2187 copy_templates_1(&path, &template_path, dir);
2188 close_free_return:
2189 closedir(dir);
2190 free_return:
2191 free(to_free);
2192 strbuf_release(&path);
2193 strbuf_release(&template_path);
2194 clear_repository_format(&template_format);
2198 * If the git_dir is not directly inside the working tree, then git will not
2199 * find it by default, and we need to set the worktree explicitly.
2201 static int needs_work_tree_config(const char *git_dir, const char *work_tree)
2203 if (!strcmp(work_tree, "/") && !strcmp(git_dir, "/.git"))
2204 return 0;
2205 if (skip_prefix(git_dir, work_tree, &git_dir) &&
2206 !strcmp(git_dir, "/.git"))
2207 return 0;
2208 return 1;
2211 void initialize_repository_version(int hash_algo,
2212 enum ref_storage_format ref_storage_format,
2213 int reinit)
2215 struct strbuf repo_version = STRBUF_INIT;
2216 int target_version = GIT_REPO_VERSION;
2219 * Note that we initialize the repository version to 1 when the ref
2220 * storage format is unknown. This is on purpose so that we can add the
2221 * correct object format to the config during git-clone(1). The format
2222 * version will get adjusted by git-clone(1) once it has learned about
2223 * the remote repository's format.
2225 if (hash_algo != GIT_HASH_SHA1 ||
2226 ref_storage_format != REF_STORAGE_FORMAT_FILES)
2227 target_version = GIT_REPO_VERSION_READ;
2229 if (hash_algo != GIT_HASH_SHA1 && hash_algo != GIT_HASH_UNKNOWN)
2230 git_config_set("extensions.objectformat",
2231 hash_algos[hash_algo].name);
2232 else if (reinit)
2233 git_config_set_gently("extensions.objectformat", NULL);
2235 if (ref_storage_format != REF_STORAGE_FORMAT_FILES)
2236 git_config_set("extensions.refstorage",
2237 ref_storage_format_to_name(ref_storage_format));
2238 else if (reinit)
2239 git_config_set_gently("extensions.refstorage", NULL);
2241 if (reinit) {
2242 struct strbuf config = STRBUF_INIT;
2243 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
2245 strbuf_git_common_path(&config, the_repository, "config");
2246 read_repository_format(&repo_fmt, config.buf);
2248 if (repo_fmt.v1_only_extensions.nr)
2249 target_version = GIT_REPO_VERSION_READ;
2251 strbuf_release(&config);
2252 clear_repository_format(&repo_fmt);
2255 strbuf_addf(&repo_version, "%d", target_version);
2256 git_config_set("core.repositoryformatversion", repo_version.buf);
2258 strbuf_release(&repo_version);
2261 static int is_reinit(void)
2263 struct strbuf buf = STRBUF_INIT;
2264 char junk[2];
2265 int ret;
2267 git_path_buf(&buf, "HEAD");
2268 ret = !access(buf.buf, R_OK) || readlink(buf.buf, junk, sizeof(junk) - 1) != -1;
2269 strbuf_release(&buf);
2270 return ret;
2273 void create_reference_database(enum ref_storage_format ref_storage_format,
2274 const char *initial_branch, int quiet)
2276 struct strbuf err = STRBUF_INIT;
2277 char *to_free = NULL;
2278 int reinit = is_reinit();
2280 repo_set_ref_storage_format(the_repository, ref_storage_format);
2281 if (ref_store_create_on_disk(get_main_ref_store(the_repository), 0, &err))
2282 die("failed to set up refs db: %s", err.buf);
2285 * Point the HEAD symref to the initial branch with if HEAD does
2286 * not yet exist.
2288 if (!reinit) {
2289 char *ref;
2291 if (!initial_branch)
2292 initial_branch = to_free =
2293 repo_default_branch_name(the_repository, quiet);
2295 ref = xstrfmt("refs/heads/%s", initial_branch);
2296 if (check_refname_format(ref, 0) < 0)
2297 die(_("invalid initial branch name: '%s'"),
2298 initial_branch);
2300 if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", ref, NULL) < 0)
2301 exit(1);
2302 free(ref);
2305 if (reinit && initial_branch)
2306 warning(_("re-init: ignored --initial-branch=%s"),
2307 initial_branch);
2309 strbuf_release(&err);
2310 free(to_free);
2313 static int create_default_files(const char *template_path,
2314 const char *original_git_dir,
2315 const struct repository_format *fmt,
2316 int init_shared_repository)
2318 struct stat st1;
2319 struct strbuf buf = STRBUF_INIT;
2320 char *path;
2321 int reinit;
2322 int filemode;
2323 const char *work_tree = repo_get_work_tree(the_repository);
2326 * First copy the templates -- we might have the default
2327 * config file there, in which case we would want to read
2328 * from it after installing.
2330 * Before reading that config, we also need to clear out any cached
2331 * values (since we've just potentially changed what's available on
2332 * disk).
2334 copy_templates(template_path);
2335 git_config_clear();
2336 reset_shared_repository();
2337 git_config(git_default_config, NULL);
2339 reinit = is_reinit();
2342 * We must make sure command-line options continue to override any
2343 * values we might have just re-read from the config.
2345 if (init_shared_repository != -1)
2346 set_shared_repository(init_shared_repository);
2348 is_bare_repository_cfg = !work_tree;
2351 * We would have created the above under user's umask -- under
2352 * shared-repository settings, we would need to fix them up.
2354 if (get_shared_repository()) {
2355 adjust_shared_perm(repo_get_git_dir(the_repository));
2358 initialize_repository_version(fmt->hash_algo, fmt->ref_storage_format, reinit);
2360 /* Check filemode trustability */
2361 path = git_path_buf(&buf, "config");
2362 filemode = TEST_FILEMODE;
2363 if (TEST_FILEMODE && !lstat(path, &st1)) {
2364 struct stat st2;
2365 filemode = (!chmod(path, st1.st_mode ^ S_IXUSR) &&
2366 !lstat(path, &st2) &&
2367 st1.st_mode != st2.st_mode &&
2368 !chmod(path, st1.st_mode));
2369 if (filemode && !reinit && (st1.st_mode & S_IXUSR))
2370 filemode = 0;
2372 git_config_set("core.filemode", filemode ? "true" : "false");
2374 if (is_bare_repository())
2375 git_config_set("core.bare", "true");
2376 else {
2377 git_config_set("core.bare", "false");
2378 /* allow template config file to override the default */
2379 if (repo_settings_get_log_all_ref_updates(the_repository) == LOG_REFS_UNSET)
2380 git_config_set("core.logallrefupdates", "true");
2381 if (needs_work_tree_config(original_git_dir, work_tree))
2382 git_config_set("core.worktree", work_tree);
2385 if (!reinit) {
2386 /* Check if symlink is supported in the work tree */
2387 path = git_path_buf(&buf, "tXXXXXX");
2388 if (!close(xmkstemp(path)) &&
2389 !unlink(path) &&
2390 !symlink("testing", path) &&
2391 !lstat(path, &st1) &&
2392 S_ISLNK(st1.st_mode))
2393 unlink(path); /* good */
2394 else
2395 git_config_set("core.symlinks", "false");
2397 /* Check if the filesystem is case-insensitive */
2398 path = git_path_buf(&buf, "CoNfIg");
2399 if (!access(path, F_OK))
2400 git_config_set("core.ignorecase", "true");
2401 probe_utf8_pathname_composition();
2404 strbuf_release(&buf);
2405 return reinit;
2408 static void create_object_directory(void)
2410 struct strbuf path = STRBUF_INIT;
2411 size_t baselen;
2413 strbuf_addstr(&path, repo_get_object_directory(the_repository));
2414 baselen = path.len;
2416 safe_create_dir(path.buf, 1);
2418 strbuf_setlen(&path, baselen);
2419 strbuf_addstr(&path, "/pack");
2420 safe_create_dir(path.buf, 1);
2422 strbuf_setlen(&path, baselen);
2423 strbuf_addstr(&path, "/info");
2424 safe_create_dir(path.buf, 1);
2426 strbuf_release(&path);
2429 static void separate_git_dir(const char *git_dir, const char *git_link)
2431 struct stat st;
2433 if (!stat(git_link, &st)) {
2434 const char *src;
2436 if (S_ISREG(st.st_mode))
2437 src = read_gitfile(git_link);
2438 else if (S_ISDIR(st.st_mode))
2439 src = git_link;
2440 else
2441 die(_("unable to handle file type %d"), (int)st.st_mode);
2443 if (rename(src, git_dir))
2444 die_errno(_("unable to move %s to %s"), src, git_dir);
2445 repair_worktrees_after_gitdir_move(src);
2448 write_file(git_link, "gitdir: %s", git_dir);
2451 struct default_format_config {
2452 int hash;
2453 enum ref_storage_format ref_format;
2456 static int read_default_format_config(const char *key, const char *value,
2457 const struct config_context *ctx UNUSED,
2458 void *payload)
2460 struct default_format_config *cfg = payload;
2461 char *str = NULL;
2462 int ret;
2464 if (!strcmp(key, "init.defaultobjectformat")) {
2465 ret = git_config_string(&str, key, value);
2466 if (ret)
2467 goto out;
2468 cfg->hash = hash_algo_by_name(str);
2469 if (cfg->hash == GIT_HASH_UNKNOWN)
2470 warning(_("unknown hash algorithm '%s'"), str);
2471 goto out;
2474 if (!strcmp(key, "init.defaultrefformat")) {
2475 ret = git_config_string(&str, key, value);
2476 if (ret)
2477 goto out;
2478 cfg->ref_format = ref_storage_format_by_name(str);
2479 if (cfg->ref_format == REF_STORAGE_FORMAT_UNKNOWN)
2480 warning(_("unknown ref storage format '%s'"), str);
2481 goto out;
2484 ret = 0;
2485 out:
2486 free(str);
2487 return ret;
2490 static void repository_format_configure(struct repository_format *repo_fmt,
2491 int hash, enum ref_storage_format ref_format)
2493 struct default_format_config cfg = {
2494 .hash = GIT_HASH_UNKNOWN,
2495 .ref_format = REF_STORAGE_FORMAT_UNKNOWN,
2497 struct config_options opts = {
2498 .respect_includes = 1,
2499 .ignore_repo = 1,
2500 .ignore_worktree = 1,
2502 const char *env;
2504 config_with_options(read_default_format_config, &cfg, NULL, NULL, &opts);
2507 * If we already have an initialized repo, don't allow the user to
2508 * specify a different algorithm, as that could cause corruption.
2509 * Otherwise, if the user has specified one on the command line, use it.
2511 env = getenv(GIT_DEFAULT_HASH_ENVIRONMENT);
2512 if (repo_fmt->version >= 0 && hash != GIT_HASH_UNKNOWN && hash != repo_fmt->hash_algo)
2513 die(_("attempt to reinitialize repository with different hash"));
2514 else if (hash != GIT_HASH_UNKNOWN)
2515 repo_fmt->hash_algo = hash;
2516 else if (env) {
2517 int env_algo = hash_algo_by_name(env);
2518 if (env_algo == GIT_HASH_UNKNOWN)
2519 die(_("unknown hash algorithm '%s'"), env);
2520 repo_fmt->hash_algo = env_algo;
2521 } else if (cfg.hash != GIT_HASH_UNKNOWN) {
2522 repo_fmt->hash_algo = cfg.hash;
2524 repo_set_hash_algo(the_repository, repo_fmt->hash_algo);
2526 env = getenv("GIT_DEFAULT_REF_FORMAT");
2527 if (repo_fmt->version >= 0 &&
2528 ref_format != REF_STORAGE_FORMAT_UNKNOWN &&
2529 ref_format != repo_fmt->ref_storage_format) {
2530 die(_("attempt to reinitialize repository with different reference storage format"));
2531 } else if (ref_format != REF_STORAGE_FORMAT_UNKNOWN) {
2532 repo_fmt->ref_storage_format = ref_format;
2533 } else if (env) {
2534 ref_format = ref_storage_format_by_name(env);
2535 if (ref_format == REF_STORAGE_FORMAT_UNKNOWN)
2536 die(_("unknown ref storage format '%s'"), env);
2537 repo_fmt->ref_storage_format = ref_format;
2538 } else if (cfg.ref_format != REF_STORAGE_FORMAT_UNKNOWN) {
2539 repo_fmt->ref_storage_format = cfg.ref_format;
2541 repo_set_ref_storage_format(the_repository, repo_fmt->ref_storage_format);
2544 int init_db(const char *git_dir, const char *real_git_dir,
2545 const char *template_dir, int hash,
2546 enum ref_storage_format ref_storage_format,
2547 const char *initial_branch,
2548 int init_shared_repository, unsigned int flags)
2550 int reinit;
2551 int exist_ok = flags & INIT_DB_EXIST_OK;
2552 char *original_git_dir = real_pathdup(git_dir, 1);
2553 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
2555 if (real_git_dir) {
2556 struct stat st;
2558 if (!exist_ok && !stat(git_dir, &st))
2559 die(_("%s already exists"), git_dir);
2561 if (!exist_ok && !stat(real_git_dir, &st))
2562 die(_("%s already exists"), real_git_dir);
2564 set_git_dir(real_git_dir, 1);
2565 git_dir = repo_get_git_dir(the_repository);
2566 separate_git_dir(git_dir, original_git_dir);
2568 else {
2569 set_git_dir(git_dir, 1);
2570 git_dir = repo_get_git_dir(the_repository);
2572 startup_info->have_repository = 1;
2575 * Check to see if the repository version is right.
2576 * Note that a newly created repository does not have
2577 * config file, so this will not fail. What we are catching
2578 * is an attempt to reinitialize new repository with an old tool.
2580 check_repository_format(&repo_fmt);
2582 repository_format_configure(&repo_fmt, hash, ref_storage_format);
2585 * Ensure `core.hidedotfiles` is processed. This must happen after we
2586 * have set up the repository format such that we can evaluate
2587 * includeIf conditions correctly in the case of re-initialization.
2589 git_config(platform_core_config, NULL);
2591 safe_create_dir(git_dir, 0);
2593 reinit = create_default_files(template_dir, original_git_dir,
2594 &repo_fmt, init_shared_repository);
2596 if (!(flags & INIT_DB_SKIP_REFDB))
2597 create_reference_database(repo_fmt.ref_storage_format,
2598 initial_branch, flags & INIT_DB_QUIET);
2599 create_object_directory();
2601 if (get_shared_repository()) {
2602 char buf[10];
2603 /* We do not spell "group" and such, so that
2604 * the configuration can be read by older version
2605 * of git. Note, we use octal numbers for new share modes,
2606 * and compatibility values for PERM_GROUP and
2607 * PERM_EVERYBODY.
2609 if (get_shared_repository() < 0)
2610 /* force to the mode value */
2611 xsnprintf(buf, sizeof(buf), "0%o", -get_shared_repository());
2612 else if (get_shared_repository() == PERM_GROUP)
2613 xsnprintf(buf, sizeof(buf), "%d", OLD_PERM_GROUP);
2614 else if (get_shared_repository() == PERM_EVERYBODY)
2615 xsnprintf(buf, sizeof(buf), "%d", OLD_PERM_EVERYBODY);
2616 else
2617 BUG("invalid value for shared_repository");
2618 git_config_set("core.sharedrepository", buf);
2619 git_config_set("receive.denyNonFastforwards", "true");
2622 if (!(flags & INIT_DB_QUIET)) {
2623 int len = strlen(git_dir);
2625 if (reinit)
2626 printf(get_shared_repository()
2627 ? _("Reinitialized existing shared Git repository in %s%s\n")
2628 : _("Reinitialized existing Git repository in %s%s\n"),
2629 git_dir, len && git_dir[len-1] != '/' ? "/" : "");
2630 else
2631 printf(get_shared_repository()
2632 ? _("Initialized empty shared Git repository in %s%s\n")
2633 : _("Initialized empty Git repository in %s%s\n"),
2634 git_dir, len && git_dir[len-1] != '/' ? "/" : "");
2637 clear_repository_format(&repo_fmt);
2638 free(original_git_dir);
2639 return 0;