path: expose `do_git_common_path()` as `repo_common_pathv()`
[git/gitster.git] / setup.c
blobd458edcc028ef17d5917470bdbc71ecbbd66045c
1 #define USE_THE_REPOSITORY_VARIABLE
3 #include "git-compat-util.h"
4 #include "abspath.h"
5 #include "copy.h"
6 #include "environment.h"
7 #include "exec-cmd.h"
8 #include "gettext.h"
9 #include "hex.h"
10 #include "object-name.h"
11 #include "refs.h"
12 #include "repository.h"
13 #include "config.h"
14 #include "dir.h"
15 #include "setup.h"
16 #include "string-list.h"
17 #include "chdir-notify.h"
18 #include "path.h"
19 #include "quote.h"
20 #include "trace2.h"
21 #include "worktree.h"
22 #include "exec-cmd.h"
24 static int inside_git_dir = -1;
25 static int inside_work_tree = -1;
26 static int work_tree_config_is_bogus;
27 enum allowed_bare_repo {
28 ALLOWED_BARE_REPO_EXPLICIT = 0,
29 ALLOWED_BARE_REPO_ALL,
32 static struct startup_info the_startup_info;
33 struct startup_info *startup_info = &the_startup_info;
34 const char *tmp_original_cwd;
37 * The input parameter must contain an absolute path, and it must already be
38 * normalized.
40 * Find the part of an absolute path that lies inside the work tree by
41 * dereferencing symlinks outside the work tree, for example:
42 * /dir1/repo/dir2/file (work tree is /dir1/repo) -> dir2/file
43 * /dir/file (work tree is /) -> dir/file
44 * /dir/symlink1/symlink2 (symlink1 points to work tree) -> symlink2
45 * /dir/repolink/file (repolink points to /dir/repo) -> file
46 * /dir/repo (exactly equal to work tree) -> (empty string)
48 static int abspath_part_inside_repo(char *path)
50 size_t len;
51 size_t wtlen;
52 char *path0;
53 int off;
54 const char *work_tree = precompose_string_if_needed(get_git_work_tree());
55 struct strbuf realpath = STRBUF_INIT;
57 if (!work_tree)
58 return -1;
59 wtlen = strlen(work_tree);
60 len = strlen(path);
61 off = offset_1st_component(path);
63 /* check if work tree is already the prefix */
64 if (wtlen <= len && !fspathncmp(path, work_tree, wtlen)) {
65 if (path[wtlen] == '/') {
66 memmove(path, path + wtlen + 1, len - wtlen);
67 return 0;
68 } else if (path[wtlen - 1] == '/' || path[wtlen] == '\0') {
69 /* work tree is the root, or the whole path */
70 memmove(path, path + wtlen, len - wtlen + 1);
71 return 0;
73 /* work tree might match beginning of a symlink to work tree */
74 off = wtlen;
76 path0 = path;
77 path += off;
79 /* check each '/'-terminated level */
80 while (*path) {
81 path++;
82 if (*path == '/') {
83 *path = '\0';
84 strbuf_realpath(&realpath, path0, 1);
85 if (fspathcmp(realpath.buf, work_tree) == 0) {
86 memmove(path0, path + 1, len - (path - path0));
87 strbuf_release(&realpath);
88 return 0;
90 *path = '/';
94 /* check whole path */
95 strbuf_realpath(&realpath, path0, 1);
96 if (fspathcmp(realpath.buf, work_tree) == 0) {
97 *path0 = '\0';
98 strbuf_release(&realpath);
99 return 0;
102 strbuf_release(&realpath);
103 return -1;
107 * Normalize "path", prepending the "prefix" for relative paths. If
108 * remaining_prefix is not NULL, return the actual prefix still
109 * remains in the path. For example, prefix = sub1/sub2/ and path is
111 * foo -> sub1/sub2/foo (full prefix)
112 * ../foo -> sub1/foo (remaining prefix is sub1/)
113 * ../../bar -> bar (no remaining prefix)
114 * ../../sub1/sub2/foo -> sub1/sub2/foo (but no remaining prefix)
115 * `pwd`/../bar -> sub1/bar (no remaining prefix)
117 char *prefix_path_gently(const char *prefix, int len,
118 int *remaining_prefix, const char *path)
120 const char *orig = path;
121 char *sanitized;
122 if (is_absolute_path(orig)) {
123 sanitized = xmallocz(strlen(path));
124 if (remaining_prefix)
125 *remaining_prefix = 0;
126 if (normalize_path_copy_len(sanitized, path, remaining_prefix)) {
127 free(sanitized);
128 return NULL;
130 if (abspath_part_inside_repo(sanitized)) {
131 free(sanitized);
132 return NULL;
134 } else {
135 sanitized = xstrfmt("%.*s%s", len, len ? prefix : "", path);
136 if (remaining_prefix)
137 *remaining_prefix = len;
138 if (normalize_path_copy_len(sanitized, sanitized, remaining_prefix)) {
139 free(sanitized);
140 return NULL;
143 return sanitized;
146 char *prefix_path(const char *prefix, int len, const char *path)
148 char *r = prefix_path_gently(prefix, len, NULL, path);
149 if (!r) {
150 const char *hint_path = get_git_work_tree();
151 if (!hint_path)
152 hint_path = get_git_dir();
153 die(_("'%s' is outside repository at '%s'"), path,
154 absolute_path(hint_path));
156 return r;
159 int path_inside_repo(const char *prefix, const char *path)
161 int len = prefix ? strlen(prefix) : 0;
162 char *r = prefix_path_gently(prefix, len, NULL, path);
163 if (r) {
164 free(r);
165 return 1;
167 return 0;
170 int check_filename(const char *prefix, const char *arg)
172 char *to_free = NULL;
173 struct stat st;
175 if (skip_prefix(arg, ":/", &arg)) {
176 if (!*arg) /* ":/" is root dir, always exists */
177 return 1;
178 prefix = NULL;
179 } else if (skip_prefix(arg, ":!", &arg) ||
180 skip_prefix(arg, ":^", &arg)) {
181 if (!*arg) /* excluding everything is silly, but allowed */
182 return 1;
185 if (prefix)
186 arg = to_free = prefix_filename(prefix, arg);
188 if (!lstat(arg, &st)) {
189 free(to_free);
190 return 1; /* file exists */
192 if (is_missing_file_error(errno)) {
193 free(to_free);
194 return 0; /* file does not exist */
196 die_errno(_("failed to stat '%s'"), arg);
199 static void NORETURN die_verify_filename(struct repository *r,
200 const char *prefix,
201 const char *arg,
202 int diagnose_misspelt_rev)
204 if (!diagnose_misspelt_rev)
205 die(_("%s: no such path in the working tree.\n"
206 "Use 'git <command> -- <path>...' to specify paths that do not exist locally."),
207 arg);
209 * Saying "'(icase)foo' does not exist in the index" when the
210 * user gave us ":(icase)foo" is just stupid. A magic pathspec
211 * begins with a colon and is followed by a non-alnum; do not
212 * let maybe_die_on_misspelt_object_name() even trigger.
214 if (!(arg[0] == ':' && !isalnum(arg[1])))
215 maybe_die_on_misspelt_object_name(r, arg, prefix);
217 /* ... or fall back the most general message. */
218 die(_("ambiguous argument '%s': unknown revision or path not in the working tree.\n"
219 "Use '--' to separate paths from revisions, like this:\n"
220 "'git <command> [<revision>...] -- [<file>...]'"), arg);
225 * Check for arguments that don't resolve as actual files,
226 * but which look sufficiently like pathspecs that we'll consider
227 * them such for the purposes of rev/pathspec DWIM parsing.
229 static int looks_like_pathspec(const char *arg)
231 const char *p;
232 int escaped = 0;
235 * Wildcard characters imply the user is looking to match pathspecs
236 * that aren't in the filesystem. Note that this doesn't include
237 * backslash even though it's a glob special; by itself it doesn't
238 * cause any increase in the match. Likewise ignore backslash-escaped
239 * wildcard characters.
241 for (p = arg; *p; p++) {
242 if (escaped) {
243 escaped = 0;
244 } else if (is_glob_special(*p)) {
245 if (*p == '\\')
246 escaped = 1;
247 else
248 return 1;
252 /* long-form pathspec magic */
253 if (starts_with(arg, ":("))
254 return 1;
256 return 0;
260 * Verify a filename that we got as an argument for a pathspec
261 * entry. Note that a filename that begins with "-" never verifies
262 * as true, because even if such a filename were to exist, we want
263 * it to be preceded by the "--" marker (or we want the user to
264 * use a format like "./-filename")
266 * The "diagnose_misspelt_rev" is used to provide a user-friendly
267 * diagnosis when dying upon finding that "name" is not a pathname.
268 * If set to 1, the diagnosis will try to diagnose "name" as an
269 * invalid object name (e.g. HEAD:foo). If set to 0, the diagnosis
270 * will only complain about an inexisting file.
272 * This function is typically called to check that a "file or rev"
273 * argument is unambiguous. In this case, the caller will want
274 * diagnose_misspelt_rev == 1 when verifying the first non-rev
275 * argument (which could have been a revision), and
276 * diagnose_misspelt_rev == 0 for the next ones (because we already
277 * saw a filename, there's not ambiguity anymore).
279 void verify_filename(const char *prefix,
280 const char *arg,
281 int diagnose_misspelt_rev)
283 if (*arg == '-')
284 die(_("option '%s' must come before non-option arguments"), arg);
285 if (looks_like_pathspec(arg) || check_filename(prefix, arg))
286 return;
287 die_verify_filename(the_repository, prefix, arg, diagnose_misspelt_rev);
291 * Opposite of the above: the command line did not have -- marker
292 * and we parsed the arg as a refname. It should not be interpretable
293 * as a filename.
295 void verify_non_filename(const char *prefix, const char *arg)
297 if (!is_inside_work_tree() || is_inside_git_dir())
298 return;
299 if (*arg == '-')
300 return; /* flag */
301 if (!check_filename(prefix, arg))
302 return;
303 die(_("ambiguous argument '%s': both revision and filename\n"
304 "Use '--' to separate paths from revisions, like this:\n"
305 "'git <command> [<revision>...] -- [<file>...]'"), arg);
308 int get_common_dir(struct strbuf *sb, const char *gitdir)
310 const char *git_env_common_dir = getenv(GIT_COMMON_DIR_ENVIRONMENT);
311 if (git_env_common_dir) {
312 strbuf_addstr(sb, git_env_common_dir);
313 return 1;
314 } else {
315 return get_common_dir_noenv(sb, gitdir);
319 int get_common_dir_noenv(struct strbuf *sb, const char *gitdir)
321 struct strbuf data = STRBUF_INIT;
322 struct strbuf path = STRBUF_INIT;
323 int ret = 0;
325 strbuf_addf(&path, "%s/commondir", gitdir);
326 if (file_exists(path.buf)) {
327 if (strbuf_read_file(&data, path.buf, 0) <= 0)
328 die_errno(_("failed to read %s"), path.buf);
329 while (data.len && (data.buf[data.len - 1] == '\n' ||
330 data.buf[data.len - 1] == '\r'))
331 data.len--;
332 data.buf[data.len] = '\0';
333 strbuf_reset(&path);
334 if (!is_absolute_path(data.buf))
335 strbuf_addf(&path, "%s/", gitdir);
336 strbuf_addbuf(&path, &data);
337 strbuf_add_real_path(sb, path.buf);
338 ret = 1;
339 } else {
340 strbuf_addstr(sb, gitdir);
343 strbuf_release(&data);
344 strbuf_release(&path);
345 return ret;
348 static int validate_headref(const char *path)
350 struct stat st;
351 char buffer[256];
352 const char *refname;
353 struct object_id oid;
354 int fd;
355 ssize_t len;
357 if (lstat(path, &st) < 0)
358 return -1;
360 /* Make sure it is a "refs/.." symlink */
361 if (S_ISLNK(st.st_mode)) {
362 len = readlink(path, buffer, sizeof(buffer)-1);
363 if (len >= 5 && !memcmp("refs/", buffer, 5))
364 return 0;
365 return -1;
369 * Anything else, just open it and try to see if it is a symbolic ref.
371 fd = open(path, O_RDONLY);
372 if (fd < 0)
373 return -1;
374 len = read_in_full(fd, buffer, sizeof(buffer)-1);
375 close(fd);
377 if (len < 0)
378 return -1;
379 buffer[len] = '\0';
382 * Is it a symbolic ref?
384 if (skip_prefix(buffer, "ref:", &refname)) {
385 while (isspace(*refname))
386 refname++;
387 if (starts_with(refname, "refs/"))
388 return 0;
392 * Is this a detached HEAD?
394 if (get_oid_hex_any(buffer, &oid) != GIT_HASH_UNKNOWN)
395 return 0;
397 return -1;
401 * Test if it looks like we're at a git directory.
402 * We want to see:
404 * - either an objects/ directory _or_ the proper
405 * GIT_OBJECT_DIRECTORY environment variable
406 * - a refs/ directory
407 * - either a HEAD symlink or a HEAD file that is formatted as
408 * a proper "ref:", or a regular file HEAD that has a properly
409 * formatted sha1 object name.
411 int is_git_directory(const char *suspect)
413 struct strbuf path = STRBUF_INIT;
414 int ret = 0;
415 size_t len;
417 /* Check worktree-related signatures */
418 strbuf_addstr(&path, suspect);
419 strbuf_complete(&path, '/');
420 strbuf_addstr(&path, "HEAD");
421 if (validate_headref(path.buf))
422 goto done;
424 strbuf_reset(&path);
425 get_common_dir(&path, suspect);
426 len = path.len;
428 /* Check non-worktree-related signatures */
429 if (getenv(DB_ENVIRONMENT)) {
430 if (access(getenv(DB_ENVIRONMENT), X_OK))
431 goto done;
433 else {
434 strbuf_setlen(&path, len);
435 strbuf_addstr(&path, "/objects");
436 if (access(path.buf, X_OK))
437 goto done;
440 strbuf_setlen(&path, len);
441 strbuf_addstr(&path, "/refs");
442 if (access(path.buf, X_OK))
443 goto done;
445 ret = 1;
446 done:
447 strbuf_release(&path);
448 return ret;
451 int is_nonbare_repository_dir(struct strbuf *path)
453 int ret = 0;
454 int gitfile_error;
455 size_t orig_path_len = path->len;
456 assert(orig_path_len != 0);
457 strbuf_complete(path, '/');
458 strbuf_addstr(path, ".git");
459 if (read_gitfile_gently(path->buf, &gitfile_error) || is_git_directory(path->buf))
460 ret = 1;
461 if (gitfile_error == READ_GITFILE_ERR_OPEN_FAILED ||
462 gitfile_error == READ_GITFILE_ERR_READ_FAILED)
463 ret = 1;
464 strbuf_setlen(path, orig_path_len);
465 return ret;
468 int is_inside_git_dir(void)
470 if (inside_git_dir < 0)
471 inside_git_dir = is_inside_dir(get_git_dir());
472 return inside_git_dir;
475 int is_inside_work_tree(void)
477 if (inside_work_tree < 0)
478 inside_work_tree = is_inside_dir(get_git_work_tree());
479 return inside_work_tree;
482 void setup_work_tree(void)
484 const char *work_tree;
485 static int initialized = 0;
487 if (initialized)
488 return;
490 if (work_tree_config_is_bogus)
491 die(_("unable to set up work tree using invalid config"));
493 work_tree = get_git_work_tree();
494 if (!work_tree || chdir_notify(work_tree))
495 die(_("this operation must be run in a work tree"));
498 * Make sure subsequent git processes find correct worktree
499 * if $GIT_WORK_TREE is set relative
501 if (getenv(GIT_WORK_TREE_ENVIRONMENT))
502 setenv(GIT_WORK_TREE_ENVIRONMENT, ".", 1);
504 initialized = 1;
507 static void setup_original_cwd(void)
509 struct strbuf tmp = STRBUF_INIT;
510 const char *worktree = NULL;
511 int offset = -1;
513 if (!tmp_original_cwd)
514 return;
517 * startup_info->original_cwd points to the current working
518 * directory we inherited from our parent process, which is a
519 * directory we want to avoid removing.
521 * For convience, we would like to have the path relative to the
522 * worktree instead of an absolute path.
524 * Yes, startup_info->original_cwd is usually the same as 'prefix',
525 * but differs in two ways:
526 * - prefix has a trailing '/'
527 * - if the user passes '-C' to git, that modifies the prefix but
528 * not startup_info->original_cwd.
531 /* Normalize the directory */
532 if (!strbuf_realpath(&tmp, tmp_original_cwd, 0)) {
533 trace2_data_string("setup", the_repository,
534 "realpath-path", tmp_original_cwd);
535 trace2_data_string("setup", the_repository,
536 "realpath-failure", strerror(errno));
537 free((char*)tmp_original_cwd);
538 tmp_original_cwd = NULL;
539 return;
542 free((char*)tmp_original_cwd);
543 tmp_original_cwd = NULL;
544 startup_info->original_cwd = strbuf_detach(&tmp, NULL);
547 * Get our worktree; we only protect the current working directory
548 * if it's in the worktree.
550 worktree = get_git_work_tree();
551 if (!worktree)
552 goto no_prevention_needed;
554 offset = dir_inside_of(startup_info->original_cwd, worktree);
555 if (offset >= 0) {
557 * If startup_info->original_cwd == worktree, that is already
558 * protected and we don't need original_cwd as a secondary
559 * protection measure.
561 if (!*(startup_info->original_cwd + offset))
562 goto no_prevention_needed;
565 * original_cwd was inside worktree; precompose it just as
566 * we do prefix so that built up paths will match
568 startup_info->original_cwd = \
569 precompose_string_if_needed(startup_info->original_cwd
570 + offset);
571 return;
574 no_prevention_needed:
575 free((char*)startup_info->original_cwd);
576 startup_info->original_cwd = NULL;
579 static int read_worktree_config(const char *var, const char *value,
580 const struct config_context *ctx UNUSED,
581 void *vdata)
583 struct repository_format *data = vdata;
585 if (strcmp(var, "core.bare") == 0) {
586 data->is_bare = git_config_bool(var, value);
587 } else if (strcmp(var, "core.worktree") == 0) {
588 if (!value)
589 return config_error_nonbool(var);
590 free(data->work_tree);
591 data->work_tree = xstrdup(value);
593 return 0;
596 enum extension_result {
597 EXTENSION_ERROR = -1, /* compatible with error(), etc */
598 EXTENSION_UNKNOWN = 0,
599 EXTENSION_OK = 1
603 * Do not add new extensions to this function. It handles extensions which are
604 * respected even in v0-format repositories for historical compatibility.
606 static enum extension_result handle_extension_v0(const char *var,
607 const char *value,
608 const char *ext,
609 struct repository_format *data)
611 if (!strcmp(ext, "noop")) {
612 return EXTENSION_OK;
613 } else if (!strcmp(ext, "preciousobjects")) {
614 data->precious_objects = git_config_bool(var, value);
615 return EXTENSION_OK;
616 } else if (!strcmp(ext, "partialclone")) {
617 if (!value)
618 return config_error_nonbool(var);
619 data->partial_clone = xstrdup(value);
620 return EXTENSION_OK;
621 } else if (!strcmp(ext, "worktreeconfig")) {
622 data->worktree_config = git_config_bool(var, value);
623 return EXTENSION_OK;
626 return EXTENSION_UNKNOWN;
630 * Record any new extensions in this function.
632 static enum extension_result handle_extension(const char *var,
633 const char *value,
634 const char *ext,
635 struct repository_format *data)
637 if (!strcmp(ext, "noop-v1")) {
638 return EXTENSION_OK;
639 } else if (!strcmp(ext, "objectformat")) {
640 int format;
642 if (!value)
643 return config_error_nonbool(var);
644 format = hash_algo_by_name(value);
645 if (format == GIT_HASH_UNKNOWN)
646 return error(_("invalid value for '%s': '%s'"),
647 "extensions.objectformat", value);
648 data->hash_algo = format;
649 return EXTENSION_OK;
650 } else if (!strcmp(ext, "compatobjectformat")) {
651 struct string_list_item *item;
652 int format;
654 if (!value)
655 return config_error_nonbool(var);
656 format = hash_algo_by_name(value);
657 if (format == GIT_HASH_UNKNOWN)
658 return error(_("invalid value for '%s': '%s'"),
659 "extensions.compatobjectformat", value);
660 /* For now only support compatObjectFormat being specified once. */
661 for_each_string_list_item(item, &data->v1_only_extensions) {
662 if (!strcmp(item->string, "compatobjectformat"))
663 return error(_("'%s' already specified as '%s'"),
664 "extensions.compatobjectformat",
665 hash_algos[data->compat_hash_algo].name);
667 data->compat_hash_algo = format;
668 return EXTENSION_OK;
669 } else if (!strcmp(ext, "refstorage")) {
670 unsigned int format;
672 if (!value)
673 return config_error_nonbool(var);
674 format = ref_storage_format_by_name(value);
675 if (format == REF_STORAGE_FORMAT_UNKNOWN)
676 return error(_("invalid value for '%s': '%s'"),
677 "extensions.refstorage", value);
678 data->ref_storage_format = format;
679 return EXTENSION_OK;
681 return EXTENSION_UNKNOWN;
684 static int check_repo_format(const char *var, const char *value,
685 const struct config_context *ctx, void *vdata)
687 struct repository_format *data = vdata;
688 const char *ext;
690 if (strcmp(var, "core.repositoryformatversion") == 0)
691 data->version = git_config_int(var, value, ctx->kvi);
692 else if (skip_prefix(var, "extensions.", &ext)) {
693 switch (handle_extension_v0(var, value, ext, data)) {
694 case EXTENSION_ERROR:
695 return -1;
696 case EXTENSION_OK:
697 return 0;
698 case EXTENSION_UNKNOWN:
699 break;
702 switch (handle_extension(var, value, ext, data)) {
703 case EXTENSION_ERROR:
704 return -1;
705 case EXTENSION_OK:
706 string_list_append(&data->v1_only_extensions, ext);
707 return 0;
708 case EXTENSION_UNKNOWN:
709 string_list_append(&data->unknown_extensions, ext);
710 return 0;
714 return read_worktree_config(var, value, ctx, vdata);
717 static int check_repository_format_gently(const char *gitdir, struct repository_format *candidate, int *nongit_ok)
719 struct strbuf sb = STRBUF_INIT;
720 struct strbuf err = STRBUF_INIT;
721 int has_common;
723 has_common = get_common_dir(&sb, gitdir);
724 strbuf_addstr(&sb, "/config");
725 read_repository_format(candidate, sb.buf);
726 strbuf_release(&sb);
729 * For historical use of check_repository_format() in git-init,
730 * we treat a missing config as a silent "ok", even when nongit_ok
731 * is unset.
733 if (candidate->version < 0)
734 return 0;
736 if (verify_repository_format(candidate, &err) < 0) {
737 if (nongit_ok) {
738 warning("%s", err.buf);
739 strbuf_release(&err);
740 *nongit_ok = -1;
741 return -1;
743 die("%s", err.buf);
746 repository_format_precious_objects = candidate->precious_objects;
747 string_list_clear(&candidate->unknown_extensions, 0);
748 string_list_clear(&candidate->v1_only_extensions, 0);
750 if (candidate->worktree_config) {
752 * pick up core.bare and core.worktree from per-worktree
753 * config if present
755 strbuf_addf(&sb, "%s/config.worktree", gitdir);
756 git_config_from_file(read_worktree_config, sb.buf, candidate);
757 strbuf_release(&sb);
758 has_common = 0;
761 if (!has_common) {
762 if (candidate->is_bare != -1) {
763 is_bare_repository_cfg = candidate->is_bare;
764 if (is_bare_repository_cfg == 1)
765 inside_work_tree = -1;
767 if (candidate->work_tree) {
768 free(git_work_tree_cfg);
769 git_work_tree_cfg = xstrdup(candidate->work_tree);
770 inside_work_tree = -1;
774 return 0;
777 int upgrade_repository_format(int target_version)
779 struct strbuf sb = STRBUF_INIT;
780 struct strbuf err = STRBUF_INIT;
781 struct strbuf repo_version = STRBUF_INIT;
782 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
783 int ret;
785 strbuf_git_common_path(&sb, the_repository, "config");
786 read_repository_format(&repo_fmt, sb.buf);
787 strbuf_release(&sb);
789 if (repo_fmt.version >= target_version) {
790 ret = 0;
791 goto out;
794 if (verify_repository_format(&repo_fmt, &err) < 0) {
795 ret = error("cannot upgrade repository format from %d to %d: %s",
796 repo_fmt.version, target_version, err.buf);
797 goto out;
799 if (!repo_fmt.version && repo_fmt.unknown_extensions.nr) {
800 ret = error("cannot upgrade repository format: "
801 "unknown extension %s",
802 repo_fmt.unknown_extensions.items[0].string);
803 goto out;
806 strbuf_addf(&repo_version, "%d", target_version);
807 git_config_set("core.repositoryformatversion", repo_version.buf);
809 ret = 1;
811 out:
812 clear_repository_format(&repo_fmt);
813 strbuf_release(&repo_version);
814 strbuf_release(&err);
815 return ret;
818 static void init_repository_format(struct repository_format *format)
820 const struct repository_format fresh = REPOSITORY_FORMAT_INIT;
822 memcpy(format, &fresh, sizeof(fresh));
825 int read_repository_format(struct repository_format *format, const char *path)
827 clear_repository_format(format);
828 git_config_from_file(check_repo_format, path, format);
829 if (format->version == -1)
830 clear_repository_format(format);
831 return format->version;
834 void clear_repository_format(struct repository_format *format)
836 string_list_clear(&format->unknown_extensions, 0);
837 string_list_clear(&format->v1_only_extensions, 0);
838 free(format->work_tree);
839 free(format->partial_clone);
840 init_repository_format(format);
843 int verify_repository_format(const struct repository_format *format,
844 struct strbuf *err)
846 if (GIT_REPO_VERSION_READ < format->version) {
847 strbuf_addf(err, _("Expected git repo version <= %d, found %d"),
848 GIT_REPO_VERSION_READ, format->version);
849 return -1;
852 if (format->version >= 1 && format->unknown_extensions.nr) {
853 int i;
855 strbuf_addstr(err, Q_("unknown repository extension found:",
856 "unknown repository extensions found:",
857 format->unknown_extensions.nr));
859 for (i = 0; i < format->unknown_extensions.nr; i++)
860 strbuf_addf(err, "\n\t%s",
861 format->unknown_extensions.items[i].string);
862 return -1;
865 if (format->version == 0 && format->v1_only_extensions.nr) {
866 int i;
868 strbuf_addstr(err,
869 Q_("repo version is 0, but v1-only extension found:",
870 "repo version is 0, but v1-only extensions found:",
871 format->v1_only_extensions.nr));
873 for (i = 0; i < format->v1_only_extensions.nr; i++)
874 strbuf_addf(err, "\n\t%s",
875 format->v1_only_extensions.items[i].string);
876 return -1;
879 return 0;
882 void read_gitfile_error_die(int error_code, const char *path, const char *dir)
884 switch (error_code) {
885 case READ_GITFILE_ERR_STAT_FAILED:
886 case READ_GITFILE_ERR_NOT_A_FILE:
887 /* non-fatal; follow return path */
888 break;
889 case READ_GITFILE_ERR_OPEN_FAILED:
890 die_errno(_("error opening '%s'"), path);
891 case READ_GITFILE_ERR_TOO_LARGE:
892 die(_("too large to be a .git file: '%s'"), path);
893 case READ_GITFILE_ERR_READ_FAILED:
894 die(_("error reading %s"), path);
895 case READ_GITFILE_ERR_INVALID_FORMAT:
896 die(_("invalid gitfile format: %s"), path);
897 case READ_GITFILE_ERR_NO_PATH:
898 die(_("no path in gitfile: %s"), path);
899 case READ_GITFILE_ERR_NOT_A_REPO:
900 die(_("not a git repository: %s"), dir);
901 default:
902 BUG("unknown error code");
907 * Try to read the location of the git directory from the .git file,
908 * return path to git directory if found. The return value comes from
909 * a shared buffer.
911 * On failure, if return_error_code is not NULL, return_error_code
912 * will be set to an error code and NULL will be returned. If
913 * return_error_code is NULL the function will die instead (for most
914 * cases).
916 const char *read_gitfile_gently(const char *path, int *return_error_code)
918 const int max_file_size = 1 << 20; /* 1MB */
919 int error_code = 0;
920 char *buf = NULL;
921 char *dir = NULL;
922 const char *slash;
923 struct stat st;
924 int fd;
925 ssize_t len;
926 static struct strbuf realpath = STRBUF_INIT;
928 if (stat(path, &st)) {
929 /* NEEDSWORK: discern between ENOENT vs other errors */
930 error_code = READ_GITFILE_ERR_STAT_FAILED;
931 goto cleanup_return;
933 if (!S_ISREG(st.st_mode)) {
934 error_code = READ_GITFILE_ERR_NOT_A_FILE;
935 goto cleanup_return;
937 if (st.st_size > max_file_size) {
938 error_code = READ_GITFILE_ERR_TOO_LARGE;
939 goto cleanup_return;
941 fd = open(path, O_RDONLY);
942 if (fd < 0) {
943 error_code = READ_GITFILE_ERR_OPEN_FAILED;
944 goto cleanup_return;
946 buf = xmallocz(st.st_size);
947 len = read_in_full(fd, buf, st.st_size);
948 close(fd);
949 if (len != st.st_size) {
950 error_code = READ_GITFILE_ERR_READ_FAILED;
951 goto cleanup_return;
953 if (!starts_with(buf, "gitdir: ")) {
954 error_code = READ_GITFILE_ERR_INVALID_FORMAT;
955 goto cleanup_return;
957 while (buf[len - 1] == '\n' || buf[len - 1] == '\r')
958 len--;
959 if (len < 9) {
960 error_code = READ_GITFILE_ERR_NO_PATH;
961 goto cleanup_return;
963 buf[len] = '\0';
964 dir = buf + 8;
966 if (!is_absolute_path(dir) && (slash = strrchr(path, '/'))) {
967 size_t pathlen = slash+1 - path;
968 dir = xstrfmt("%.*s%.*s", (int)pathlen, path,
969 (int)(len - 8), buf + 8);
970 free(buf);
971 buf = dir;
973 if (!is_git_directory(dir)) {
974 error_code = READ_GITFILE_ERR_NOT_A_REPO;
975 goto cleanup_return;
978 strbuf_realpath(&realpath, dir, 1);
979 path = realpath.buf;
981 cleanup_return:
982 if (return_error_code)
983 *return_error_code = error_code;
984 else if (error_code)
985 read_gitfile_error_die(error_code, path, dir);
987 free(buf);
988 return error_code ? NULL : path;
991 static const char *setup_explicit_git_dir(const char *gitdirenv,
992 struct strbuf *cwd,
993 struct repository_format *repo_fmt,
994 int *nongit_ok)
996 const char *work_tree_env = getenv(GIT_WORK_TREE_ENVIRONMENT);
997 const char *worktree;
998 char *gitfile;
999 int offset;
1001 if (PATH_MAX - 40 < strlen(gitdirenv))
1002 die(_("'$%s' too big"), GIT_DIR_ENVIRONMENT);
1004 gitfile = (char*)read_gitfile(gitdirenv);
1005 if (gitfile) {
1006 gitfile = xstrdup(gitfile);
1007 gitdirenv = gitfile;
1010 if (!is_git_directory(gitdirenv)) {
1011 if (nongit_ok) {
1012 *nongit_ok = 1;
1013 free(gitfile);
1014 return NULL;
1016 die(_("not a git repository: '%s'"), gitdirenv);
1019 if (check_repository_format_gently(gitdirenv, repo_fmt, nongit_ok)) {
1020 free(gitfile);
1021 return NULL;
1024 /* #3, #7, #11, #15, #19, #23, #27, #31 (see t1510) */
1025 if (work_tree_env)
1026 set_git_work_tree(work_tree_env);
1027 else if (is_bare_repository_cfg > 0) {
1028 if (git_work_tree_cfg) {
1029 /* #22.2, #30 */
1030 warning("core.bare and core.worktree do not make sense");
1031 work_tree_config_is_bogus = 1;
1034 /* #18, #26 */
1035 set_git_dir(gitdirenv, 0);
1036 free(gitfile);
1037 return NULL;
1039 else if (git_work_tree_cfg) { /* #6, #14 */
1040 if (is_absolute_path(git_work_tree_cfg))
1041 set_git_work_tree(git_work_tree_cfg);
1042 else {
1043 char *core_worktree;
1044 if (chdir(gitdirenv))
1045 die_errno(_("cannot chdir to '%s'"), gitdirenv);
1046 if (chdir(git_work_tree_cfg))
1047 die_errno(_("cannot chdir to '%s'"), git_work_tree_cfg);
1048 core_worktree = xgetcwd();
1049 if (chdir(cwd->buf))
1050 die_errno(_("cannot come back to cwd"));
1051 set_git_work_tree(core_worktree);
1052 free(core_worktree);
1055 else if (!git_env_bool(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, 1)) {
1056 /* #16d */
1057 set_git_dir(gitdirenv, 0);
1058 free(gitfile);
1059 return NULL;
1061 else /* #2, #10 */
1062 set_git_work_tree(".");
1064 /* set_git_work_tree() must have been called by now */
1065 worktree = get_git_work_tree();
1067 /* both get_git_work_tree() and cwd are already normalized */
1068 if (!strcmp(cwd->buf, worktree)) { /* cwd == worktree */
1069 set_git_dir(gitdirenv, 0);
1070 free(gitfile);
1071 return NULL;
1074 offset = dir_inside_of(cwd->buf, worktree);
1075 if (offset >= 0) { /* cwd inside worktree? */
1076 set_git_dir(gitdirenv, 1);
1077 if (chdir(worktree))
1078 die_errno(_("cannot chdir to '%s'"), worktree);
1079 strbuf_addch(cwd, '/');
1080 free(gitfile);
1081 return cwd->buf + offset;
1084 /* cwd outside worktree */
1085 set_git_dir(gitdirenv, 0);
1086 free(gitfile);
1087 return NULL;
1090 static const char *setup_discovered_git_dir(const char *gitdir,
1091 struct strbuf *cwd, int offset,
1092 struct repository_format *repo_fmt,
1093 int *nongit_ok)
1095 if (check_repository_format_gently(gitdir, repo_fmt, nongit_ok))
1096 return NULL;
1098 /* --work-tree is set without --git-dir; use discovered one */
1099 if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
1100 char *to_free = NULL;
1101 const char *ret;
1103 if (offset != cwd->len && !is_absolute_path(gitdir))
1104 gitdir = to_free = real_pathdup(gitdir, 1);
1105 if (chdir(cwd->buf))
1106 die_errno(_("cannot come back to cwd"));
1107 ret = setup_explicit_git_dir(gitdir, cwd, repo_fmt, nongit_ok);
1108 free(to_free);
1109 return ret;
1112 /* #16.2, #17.2, #20.2, #21.2, #24, #25, #28, #29 (see t1510) */
1113 if (is_bare_repository_cfg > 0) {
1114 set_git_dir(gitdir, (offset != cwd->len));
1115 if (chdir(cwd->buf))
1116 die_errno(_("cannot come back to cwd"));
1117 return NULL;
1120 /* #0, #1, #5, #8, #9, #12, #13 */
1121 set_git_work_tree(".");
1122 if (strcmp(gitdir, DEFAULT_GIT_DIR_ENVIRONMENT))
1123 set_git_dir(gitdir, 0);
1124 inside_git_dir = 0;
1125 inside_work_tree = 1;
1126 if (offset >= cwd->len)
1127 return NULL;
1129 /* Make "offset" point past the '/' (already the case for root dirs) */
1130 if (offset != offset_1st_component(cwd->buf))
1131 offset++;
1132 /* Add a '/' at the end */
1133 strbuf_addch(cwd, '/');
1134 return cwd->buf + offset;
1137 /* #16.1, #17.1, #20.1, #21.1, #22.1 (see t1510) */
1138 static const char *setup_bare_git_dir(struct strbuf *cwd, int offset,
1139 struct repository_format *repo_fmt,
1140 int *nongit_ok)
1142 int root_len;
1144 if (check_repository_format_gently(".", repo_fmt, nongit_ok))
1145 return NULL;
1147 setenv(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, "0", 1);
1149 /* --work-tree is set without --git-dir; use discovered one */
1150 if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
1151 static const char *gitdir;
1153 gitdir = offset == cwd->len ? "." : xmemdupz(cwd->buf, offset);
1154 if (chdir(cwd->buf))
1155 die_errno(_("cannot come back to cwd"));
1156 return setup_explicit_git_dir(gitdir, cwd, repo_fmt, nongit_ok);
1159 inside_git_dir = 1;
1160 inside_work_tree = 0;
1161 if (offset != cwd->len) {
1162 if (chdir(cwd->buf))
1163 die_errno(_("cannot come back to cwd"));
1164 root_len = offset_1st_component(cwd->buf);
1165 strbuf_setlen(cwd, offset > root_len ? offset : root_len);
1166 set_git_dir(cwd->buf, 0);
1168 else
1169 set_git_dir(".", 0);
1170 return NULL;
1173 static dev_t get_device_or_die(const char *path, const char *prefix, int prefix_len)
1175 struct stat buf;
1176 if (stat(path, &buf)) {
1177 die_errno(_("failed to stat '%*s%s%s'"),
1178 prefix_len,
1179 prefix ? prefix : "",
1180 prefix ? "/" : "", path);
1182 return buf.st_dev;
1186 * A "string_list_each_func_t" function that canonicalizes an entry
1187 * from GIT_CEILING_DIRECTORIES using real_pathdup(), or
1188 * discards it if unusable. The presence of an empty entry in
1189 * GIT_CEILING_DIRECTORIES turns off canonicalization for all
1190 * subsequent entries.
1192 static int canonicalize_ceiling_entry(struct string_list_item *item,
1193 void *cb_data)
1195 int *empty_entry_found = cb_data;
1196 char *ceil = item->string;
1198 if (!*ceil) {
1199 *empty_entry_found = 1;
1200 return 0;
1201 } else if (!is_absolute_path(ceil)) {
1202 return 0;
1203 } else if (*empty_entry_found) {
1204 /* Keep entry but do not canonicalize it */
1205 return 1;
1206 } else {
1207 char *real_path = real_pathdup(ceil, 0);
1208 if (!real_path) {
1209 return 0;
1211 free(item->string);
1212 item->string = real_path;
1213 return 1;
1217 struct safe_directory_data {
1218 const char *path;
1219 int is_safe;
1222 static int safe_directory_cb(const char *key, const char *value,
1223 const struct config_context *ctx UNUSED, void *d)
1225 struct safe_directory_data *data = d;
1227 if (strcmp(key, "safe.directory"))
1228 return 0;
1230 if (!value || !*value) {
1231 data->is_safe = 0;
1232 } else if (!strcmp(value, "*")) {
1233 data->is_safe = 1;
1234 } else {
1235 char *allowed = NULL;
1237 if (!git_config_pathname(&allowed, key, value)) {
1238 const char *check = allowed ? allowed : value;
1239 if (ends_with(check, "/*")) {
1240 size_t len = strlen(check);
1241 if (!fspathncmp(check, data->path, len - 1))
1242 data->is_safe = 1;
1243 } else if (!fspathcmp(data->path, check)) {
1244 data->is_safe = 1;
1247 if (allowed != value)
1248 free(allowed);
1251 return 0;
1255 * Check if a repository is safe, by verifying the ownership of the
1256 * worktree (if any), the git directory, and the gitfile (if any).
1258 * Exemptions for known-safe repositories can be added via `safe.directory`
1259 * config settings; for non-bare repositories, their worktree needs to be
1260 * added, for bare ones their git directory.
1262 static int ensure_valid_ownership(const char *gitfile,
1263 const char *worktree, const char *gitdir,
1264 struct strbuf *report)
1266 struct safe_directory_data data = {
1267 .path = worktree ? worktree : gitdir
1270 if (!git_env_bool("GIT_TEST_ASSUME_DIFFERENT_OWNER", 0) &&
1271 (!gitfile || is_path_owned_by_current_user(gitfile, report)) &&
1272 (!worktree || is_path_owned_by_current_user(worktree, report)) &&
1273 (!gitdir || is_path_owned_by_current_user(gitdir, report)))
1274 return 1;
1277 * data.path is the "path" that identifies the repository and it is
1278 * constant regardless of what failed above. data.is_safe should be
1279 * initialized to false, and might be changed by the callback.
1281 git_protected_config(safe_directory_cb, &data);
1283 return data.is_safe;
1286 void die_upon_dubious_ownership(const char *gitfile, const char *worktree,
1287 const char *gitdir)
1289 struct strbuf report = STRBUF_INIT, quoted = STRBUF_INIT;
1290 const char *path;
1292 if (ensure_valid_ownership(gitfile, worktree, gitdir, &report))
1293 return;
1295 strbuf_complete(&report, '\n');
1296 path = gitfile ? gitfile : gitdir;
1297 sq_quote_buf_pretty(&quoted, path);
1299 die(_("detected dubious ownership in repository at '%s'\n"
1300 "%s"
1301 "To add an exception for this directory, call:\n"
1302 "\n"
1303 "\tgit config --global --add safe.directory %s"),
1304 path, report.buf, quoted.buf);
1307 static int allowed_bare_repo_cb(const char *key, const char *value,
1308 const struct config_context *ctx UNUSED,
1309 void *d)
1311 enum allowed_bare_repo *allowed_bare_repo = d;
1313 if (strcasecmp(key, "safe.bareRepository"))
1314 return 0;
1316 if (!strcmp(value, "explicit")) {
1317 *allowed_bare_repo = ALLOWED_BARE_REPO_EXPLICIT;
1318 return 0;
1320 if (!strcmp(value, "all")) {
1321 *allowed_bare_repo = ALLOWED_BARE_REPO_ALL;
1322 return 0;
1324 return -1;
1327 static enum allowed_bare_repo get_allowed_bare_repo(void)
1329 enum allowed_bare_repo result = ALLOWED_BARE_REPO_ALL;
1330 git_protected_config(allowed_bare_repo_cb, &result);
1331 return result;
1334 static const char *allowed_bare_repo_to_string(
1335 enum allowed_bare_repo allowed_bare_repo)
1337 switch (allowed_bare_repo) {
1338 case ALLOWED_BARE_REPO_EXPLICIT:
1339 return "explicit";
1340 case ALLOWED_BARE_REPO_ALL:
1341 return "all";
1342 default:
1343 BUG("invalid allowed_bare_repo %d",
1344 allowed_bare_repo);
1346 return NULL;
1349 static int is_implicit_bare_repo(const char *path)
1352 * what we found is a ".git" directory at the root of
1353 * the working tree.
1355 if (ends_with_path_components(path, ".git"))
1356 return 1;
1359 * we are inside $GIT_DIR of a secondary worktree of a
1360 * non-bare repository.
1362 if (strstr(path, "/.git/worktrees/"))
1363 return 1;
1366 * we are inside $GIT_DIR of a worktree of a non-embedded
1367 * submodule, whose superproject is not a bare repository.
1369 if (strstr(path, "/.git/modules/"))
1370 return 1;
1372 return 0;
1376 * We cannot decide in this function whether we are in the work tree or
1377 * not, since the config can only be read _after_ this function was called.
1379 * Also, we avoid changing any global state (such as the current working
1380 * directory) to allow early callers.
1382 * The directory where the search should start needs to be passed in via the
1383 * `dir` parameter; upon return, the `dir` buffer will contain the path of
1384 * the directory where the search ended, and `gitdir` will contain the path of
1385 * the discovered .git/ directory, if any. If `gitdir` is not absolute, it
1386 * is relative to `dir` (i.e. *not* necessarily the cwd).
1388 static enum discovery_result setup_git_directory_gently_1(struct strbuf *dir,
1389 struct strbuf *gitdir,
1390 struct strbuf *report,
1391 int die_on_error)
1393 const char *env_ceiling_dirs = getenv(CEILING_DIRECTORIES_ENVIRONMENT);
1394 struct string_list ceiling_dirs = STRING_LIST_INIT_DUP;
1395 const char *gitdirenv;
1396 int ceil_offset = -1, min_offset = offset_1st_component(dir->buf);
1397 dev_t current_device = 0;
1398 int one_filesystem = 1;
1401 * If GIT_DIR is set explicitly, we're not going
1402 * to do any discovery, but we still do repository
1403 * validation.
1405 gitdirenv = getenv(GIT_DIR_ENVIRONMENT);
1406 if (gitdirenv) {
1407 strbuf_addstr(gitdir, gitdirenv);
1408 return GIT_DIR_EXPLICIT;
1411 if (env_ceiling_dirs) {
1412 int empty_entry_found = 0;
1414 string_list_split(&ceiling_dirs, env_ceiling_dirs, PATH_SEP, -1);
1415 filter_string_list(&ceiling_dirs, 0,
1416 canonicalize_ceiling_entry, &empty_entry_found);
1417 ceil_offset = longest_ancestor_length(dir->buf, &ceiling_dirs);
1418 string_list_clear(&ceiling_dirs, 0);
1421 if (ceil_offset < 0)
1422 ceil_offset = min_offset - 2;
1424 if (min_offset && min_offset == dir->len &&
1425 !is_dir_sep(dir->buf[min_offset - 1])) {
1426 strbuf_addch(dir, '/');
1427 min_offset++;
1431 * Test in the following order (relative to the dir):
1432 * - .git (file containing "gitdir: <path>")
1433 * - .git/
1434 * - ./ (bare)
1435 * - ../.git
1436 * - ../.git/
1437 * - ../ (bare)
1438 * - ../../.git
1439 * etc.
1441 one_filesystem = !git_env_bool("GIT_DISCOVERY_ACROSS_FILESYSTEM", 0);
1442 if (one_filesystem)
1443 current_device = get_device_or_die(dir->buf, NULL, 0);
1444 for (;;) {
1445 int offset = dir->len, error_code = 0;
1446 char *gitdir_path = NULL;
1447 char *gitfile = NULL;
1449 if (offset > min_offset)
1450 strbuf_addch(dir, '/');
1451 strbuf_addstr(dir, DEFAULT_GIT_DIR_ENVIRONMENT);
1452 gitdirenv = read_gitfile_gently(dir->buf, die_on_error ?
1453 NULL : &error_code);
1454 if (!gitdirenv) {
1455 if (die_on_error ||
1456 error_code == READ_GITFILE_ERR_NOT_A_FILE) {
1457 /* NEEDSWORK: fail if .git is not file nor dir */
1458 if (is_git_directory(dir->buf)) {
1459 gitdirenv = DEFAULT_GIT_DIR_ENVIRONMENT;
1460 gitdir_path = xstrdup(dir->buf);
1462 } else if (error_code != READ_GITFILE_ERR_STAT_FAILED)
1463 return GIT_DIR_INVALID_GITFILE;
1464 } else
1465 gitfile = xstrdup(dir->buf);
1467 * Earlier, we tentatively added DEFAULT_GIT_DIR_ENVIRONMENT
1468 * to check that directory for a repository.
1469 * Now trim that tentative addition away, because we want to
1470 * focus on the real directory we are in.
1472 strbuf_setlen(dir, offset);
1473 if (gitdirenv) {
1474 enum discovery_result ret;
1475 const char *gitdir_candidate =
1476 gitdir_path ? gitdir_path : gitdirenv;
1478 if (ensure_valid_ownership(gitfile, dir->buf,
1479 gitdir_candidate, report)) {
1480 strbuf_addstr(gitdir, gitdirenv);
1481 ret = GIT_DIR_DISCOVERED;
1482 } else
1483 ret = GIT_DIR_INVALID_OWNERSHIP;
1486 * Earlier, during discovery, we might have allocated
1487 * string copies for gitdir_path or gitfile so make
1488 * sure we don't leak by freeing them now, before
1489 * leaving the loop and function.
1491 * Note: gitdirenv will be non-NULL whenever these are
1492 * allocated, therefore we need not take care of releasing
1493 * them outside of this conditional block.
1495 free(gitdir_path);
1496 free(gitfile);
1498 return ret;
1501 if (is_git_directory(dir->buf)) {
1502 trace2_data_string("setup", NULL, "implicit-bare-repository", dir->buf);
1503 if (get_allowed_bare_repo() == ALLOWED_BARE_REPO_EXPLICIT &&
1504 !is_implicit_bare_repo(dir->buf))
1505 return GIT_DIR_DISALLOWED_BARE;
1506 if (!ensure_valid_ownership(NULL, NULL, dir->buf, report))
1507 return GIT_DIR_INVALID_OWNERSHIP;
1508 strbuf_addstr(gitdir, ".");
1509 return GIT_DIR_BARE;
1512 if (offset <= min_offset)
1513 return GIT_DIR_HIT_CEILING;
1515 while (--offset > ceil_offset && !is_dir_sep(dir->buf[offset]))
1516 ; /* continue */
1517 if (offset <= ceil_offset)
1518 return GIT_DIR_HIT_CEILING;
1520 strbuf_setlen(dir, offset > min_offset ? offset : min_offset);
1521 if (one_filesystem &&
1522 current_device != get_device_or_die(dir->buf, NULL, offset))
1523 return GIT_DIR_HIT_MOUNT_POINT;
1527 enum discovery_result discover_git_directory_reason(struct strbuf *commondir,
1528 struct strbuf *gitdir)
1530 struct strbuf dir = STRBUF_INIT, err = STRBUF_INIT;
1531 size_t gitdir_offset = gitdir->len, cwd_len;
1532 size_t commondir_offset = commondir->len;
1533 struct repository_format candidate = REPOSITORY_FORMAT_INIT;
1534 enum discovery_result result;
1536 if (strbuf_getcwd(&dir))
1537 return GIT_DIR_CWD_FAILURE;
1539 cwd_len = dir.len;
1540 result = setup_git_directory_gently_1(&dir, gitdir, NULL, 0);
1541 if (result <= 0) {
1542 strbuf_release(&dir);
1543 return result;
1547 * The returned gitdir is relative to dir, and if dir does not reflect
1548 * the current working directory, we simply make the gitdir absolute.
1550 if (dir.len < cwd_len && !is_absolute_path(gitdir->buf + gitdir_offset)) {
1551 /* Avoid a trailing "/." */
1552 if (!strcmp(".", gitdir->buf + gitdir_offset))
1553 strbuf_setlen(gitdir, gitdir_offset);
1554 else
1555 strbuf_addch(&dir, '/');
1556 strbuf_insert(gitdir, gitdir_offset, dir.buf, dir.len);
1559 get_common_dir(commondir, gitdir->buf + gitdir_offset);
1561 strbuf_reset(&dir);
1562 strbuf_addf(&dir, "%s/config", commondir->buf + commondir_offset);
1563 read_repository_format(&candidate, dir.buf);
1564 strbuf_release(&dir);
1566 if (verify_repository_format(&candidate, &err) < 0) {
1567 warning("ignoring git dir '%s': %s",
1568 gitdir->buf + gitdir_offset, err.buf);
1569 strbuf_release(&err);
1570 strbuf_setlen(commondir, commondir_offset);
1571 strbuf_setlen(gitdir, gitdir_offset);
1572 clear_repository_format(&candidate);
1573 return GIT_DIR_INVALID_FORMAT;
1576 clear_repository_format(&candidate);
1577 return result;
1580 const char *setup_git_directory_gently(int *nongit_ok)
1582 static struct strbuf cwd = STRBUF_INIT;
1583 struct strbuf dir = STRBUF_INIT, gitdir = STRBUF_INIT, report = STRBUF_INIT;
1584 const char *prefix = NULL;
1585 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
1588 * We may have read an incomplete configuration before
1589 * setting-up the git directory. If so, clear the cache so
1590 * that the next queries to the configuration reload complete
1591 * configuration (including the per-repo config file that we
1592 * ignored previously).
1594 git_config_clear();
1597 * Let's assume that we are in a git repository.
1598 * If it turns out later that we are somewhere else, the value will be
1599 * updated accordingly.
1601 if (nongit_ok)
1602 *nongit_ok = 0;
1604 if (strbuf_getcwd(&cwd))
1605 die_errno(_("Unable to read current working directory"));
1606 strbuf_addbuf(&dir, &cwd);
1608 switch (setup_git_directory_gently_1(&dir, &gitdir, &report, 1)) {
1609 case GIT_DIR_EXPLICIT:
1610 prefix = setup_explicit_git_dir(gitdir.buf, &cwd, &repo_fmt, nongit_ok);
1611 break;
1612 case GIT_DIR_DISCOVERED:
1613 if (dir.len < cwd.len && chdir(dir.buf))
1614 die(_("cannot change to '%s'"), dir.buf);
1615 prefix = setup_discovered_git_dir(gitdir.buf, &cwd, dir.len,
1616 &repo_fmt, nongit_ok);
1617 break;
1618 case GIT_DIR_BARE:
1619 if (dir.len < cwd.len && chdir(dir.buf))
1620 die(_("cannot change to '%s'"), dir.buf);
1621 prefix = setup_bare_git_dir(&cwd, dir.len, &repo_fmt, nongit_ok);
1622 break;
1623 case GIT_DIR_HIT_CEILING:
1624 if (!nongit_ok)
1625 die(_("not a git repository (or any of the parent directories): %s"),
1626 DEFAULT_GIT_DIR_ENVIRONMENT);
1627 *nongit_ok = 1;
1628 break;
1629 case GIT_DIR_HIT_MOUNT_POINT:
1630 if (!nongit_ok)
1631 die(_("not a git repository (or any parent up to mount point %s)\n"
1632 "Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set)."),
1633 dir.buf);
1634 *nongit_ok = 1;
1635 break;
1636 case GIT_DIR_INVALID_OWNERSHIP:
1637 if (!nongit_ok) {
1638 struct strbuf quoted = STRBUF_INIT;
1640 strbuf_complete(&report, '\n');
1641 sq_quote_buf_pretty(&quoted, dir.buf);
1642 die(_("detected dubious ownership in repository at '%s'\n"
1643 "%s"
1644 "To add an exception for this directory, call:\n"
1645 "\n"
1646 "\tgit config --global --add safe.directory %s"),
1647 dir.buf, report.buf, quoted.buf);
1649 *nongit_ok = 1;
1650 break;
1651 case GIT_DIR_DISALLOWED_BARE:
1652 if (!nongit_ok) {
1653 die(_("cannot use bare repository '%s' (safe.bareRepository is '%s')"),
1654 dir.buf,
1655 allowed_bare_repo_to_string(get_allowed_bare_repo()));
1657 *nongit_ok = 1;
1658 break;
1659 case GIT_DIR_CWD_FAILURE:
1660 case GIT_DIR_INVALID_FORMAT:
1662 * As a safeguard against setup_git_directory_gently_1 returning
1663 * these values, fallthrough to BUG. Otherwise it is possible to
1664 * set startup_info->have_repository to 1 when we did nothing to
1665 * find a repository.
1667 default:
1668 BUG("unhandled setup_git_directory_gently_1() result");
1672 * At this point, nongit_ok is stable. If it is non-NULL and points
1673 * to a non-zero value, then this means that we haven't found a
1674 * repository and that the caller expects startup_info to reflect
1675 * this.
1677 * Regardless of the state of nongit_ok, startup_info->prefix and
1678 * the GIT_PREFIX environment variable must always match. For details
1679 * see Documentation/config/alias.txt.
1681 if (nongit_ok && *nongit_ok)
1682 startup_info->have_repository = 0;
1683 else
1684 startup_info->have_repository = 1;
1687 * Not all paths through the setup code will call 'set_git_dir()' (which
1688 * directly sets up the environment) so in order to guarantee that the
1689 * environment is in a consistent state after setup, explicitly setup
1690 * the environment if we have a repository.
1692 * NEEDSWORK: currently we allow bogus GIT_DIR values to be set in some
1693 * code paths so we also need to explicitly setup the environment if
1694 * the user has set GIT_DIR. It may be beneficial to disallow bogus
1695 * GIT_DIR values at some point in the future.
1697 if (/* GIT_DIR_EXPLICIT, GIT_DIR_DISCOVERED, GIT_DIR_BARE */
1698 startup_info->have_repository ||
1699 /* GIT_DIR_EXPLICIT */
1700 getenv(GIT_DIR_ENVIRONMENT)) {
1701 if (!the_repository->gitdir) {
1702 const char *gitdir = getenv(GIT_DIR_ENVIRONMENT);
1703 if (!gitdir)
1704 gitdir = DEFAULT_GIT_DIR_ENVIRONMENT;
1705 setup_git_env(gitdir);
1707 if (startup_info->have_repository) {
1708 repo_set_hash_algo(the_repository, repo_fmt.hash_algo);
1709 repo_set_compat_hash_algo(the_repository,
1710 repo_fmt.compat_hash_algo);
1711 repo_set_ref_storage_format(the_repository,
1712 repo_fmt.ref_storage_format);
1713 the_repository->repository_format_worktree_config =
1714 repo_fmt.worktree_config;
1715 /* take ownership of repo_fmt.partial_clone */
1716 the_repository->repository_format_partial_clone =
1717 repo_fmt.partial_clone;
1718 repo_fmt.partial_clone = NULL;
1722 * Since precompose_string_if_needed() needs to look at
1723 * the core.precomposeunicode configuration, this
1724 * has to happen after the above block that finds
1725 * out where the repository is, i.e. a preparation
1726 * for calling git_config_get_bool().
1728 if (prefix) {
1729 prefix = precompose_string_if_needed(prefix);
1730 startup_info->prefix = prefix;
1731 setenv(GIT_PREFIX_ENVIRONMENT, prefix, 1);
1732 } else {
1733 startup_info->prefix = NULL;
1734 setenv(GIT_PREFIX_ENVIRONMENT, "", 1);
1737 setup_original_cwd();
1739 strbuf_release(&dir);
1740 strbuf_release(&gitdir);
1741 strbuf_release(&report);
1742 clear_repository_format(&repo_fmt);
1744 return prefix;
1747 int git_config_perm(const char *var, const char *value)
1749 int i;
1750 char *endptr;
1752 if (!value)
1753 return PERM_GROUP;
1755 if (!strcmp(value, "umask"))
1756 return PERM_UMASK;
1757 if (!strcmp(value, "group"))
1758 return PERM_GROUP;
1759 if (!strcmp(value, "all") ||
1760 !strcmp(value, "world") ||
1761 !strcmp(value, "everybody"))
1762 return PERM_EVERYBODY;
1764 /* Parse octal numbers */
1765 i = strtol(value, &endptr, 8);
1767 /* If not an octal number, maybe true/false? */
1768 if (*endptr != 0)
1769 return git_config_bool(var, value) ? PERM_GROUP : PERM_UMASK;
1772 * Treat values 0, 1 and 2 as compatibility cases, otherwise it is
1773 * a chmod value to restrict to.
1775 switch (i) {
1776 case PERM_UMASK: /* 0 */
1777 return PERM_UMASK;
1778 case OLD_PERM_GROUP: /* 1 */
1779 return PERM_GROUP;
1780 case OLD_PERM_EVERYBODY: /* 2 */
1781 return PERM_EVERYBODY;
1784 /* A filemode value was given: 0xxx */
1786 if ((i & 0600) != 0600)
1787 die(_("problem with core.sharedRepository filemode value "
1788 "(0%.3o).\nThe owner of files must always have "
1789 "read and write permissions."), i);
1792 * Mask filemode value. Others can not get write permission.
1793 * x flags for directories are handled separately.
1795 return -(i & 0666);
1798 void check_repository_format(struct repository_format *fmt)
1800 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
1801 if (!fmt)
1802 fmt = &repo_fmt;
1803 check_repository_format_gently(get_git_dir(), fmt, NULL);
1804 startup_info->have_repository = 1;
1805 repo_set_hash_algo(the_repository, fmt->hash_algo);
1806 repo_set_compat_hash_algo(the_repository, fmt->compat_hash_algo);
1807 repo_set_ref_storage_format(the_repository,
1808 fmt->ref_storage_format);
1809 the_repository->repository_format_worktree_config =
1810 fmt->worktree_config;
1811 the_repository->repository_format_partial_clone =
1812 xstrdup_or_null(fmt->partial_clone);
1813 clear_repository_format(&repo_fmt);
1817 * Returns the "prefix", a path to the current working directory
1818 * relative to the work tree root, or NULL, if the current working
1819 * directory is not a strict subdirectory of the work tree root. The
1820 * prefix always ends with a '/' character.
1822 const char *setup_git_directory(void)
1824 return setup_git_directory_gently(NULL);
1827 const char *resolve_gitdir_gently(const char *suspect, int *return_error_code)
1829 if (is_git_directory(suspect))
1830 return suspect;
1831 return read_gitfile_gently(suspect, return_error_code);
1834 /* if any standard file descriptor is missing open it to /dev/null */
1835 void sanitize_stdfds(void)
1837 int fd = xopen("/dev/null", O_RDWR);
1838 while (fd < 2)
1839 fd = xdup(fd);
1840 if (fd > 2)
1841 close(fd);
1844 int daemonize(void)
1846 #ifdef NO_POSIX_GOODIES
1847 errno = ENOSYS;
1848 return -1;
1849 #else
1850 switch (fork()) {
1851 case 0:
1852 break;
1853 case -1:
1854 die_errno(_("fork failed"));
1855 default:
1856 exit(0);
1858 if (setsid() == -1)
1859 die_errno(_("setsid failed"));
1860 close(0);
1861 close(1);
1862 close(2);
1863 sanitize_stdfds();
1864 return 0;
1865 #endif
1868 struct template_dir_cb_data {
1869 char *path;
1870 int initialized;
1873 static int template_dir_cb(const char *key, const char *value,
1874 const struct config_context *ctx, void *d)
1876 struct template_dir_cb_data *data = d;
1878 if (strcmp(key, "init.templatedir"))
1879 return 0;
1881 if (!value) {
1882 data->path = NULL;
1883 } else {
1884 char *path = NULL;
1886 FREE_AND_NULL(data->path);
1887 if (!git_config_pathname(&path, key, value))
1888 data->path = path ? path : xstrdup(value);
1891 return 0;
1894 const char *get_template_dir(const char *option_template)
1896 const char *template_dir = option_template;
1898 if (!template_dir)
1899 template_dir = getenv(TEMPLATE_DIR_ENVIRONMENT);
1900 if (!template_dir) {
1901 static struct template_dir_cb_data data;
1903 if (!data.initialized) {
1904 git_protected_config(template_dir_cb, &data);
1905 data.initialized = 1;
1907 template_dir = data.path;
1909 if (!template_dir) {
1910 static char *dir;
1912 if (!dir)
1913 dir = system_path(DEFAULT_GIT_TEMPLATE_DIR);
1914 template_dir = dir;
1916 return template_dir;
1919 #ifdef NO_TRUSTABLE_FILEMODE
1920 #define TEST_FILEMODE 0
1921 #else
1922 #define TEST_FILEMODE 1
1923 #endif
1925 #define GIT_DEFAULT_HASH_ENVIRONMENT "GIT_DEFAULT_HASH"
1927 static void copy_templates_1(struct strbuf *path, struct strbuf *template_path,
1928 DIR *dir)
1930 size_t path_baselen = path->len;
1931 size_t template_baselen = template_path->len;
1932 struct dirent *de;
1934 /* Note: if ".git/hooks" file exists in the repository being
1935 * re-initialized, /etc/core-git/templates/hooks/update would
1936 * cause "git init" to fail here. I think this is sane but
1937 * it means that the set of templates we ship by default, along
1938 * with the way the namespace under .git/ is organized, should
1939 * be really carefully chosen.
1941 safe_create_dir(path->buf, 1);
1942 while ((de = readdir(dir)) != NULL) {
1943 struct stat st_git, st_template;
1944 int exists = 0;
1946 strbuf_setlen(path, path_baselen);
1947 strbuf_setlen(template_path, template_baselen);
1949 if (de->d_name[0] == '.')
1950 continue;
1951 strbuf_addstr(path, de->d_name);
1952 strbuf_addstr(template_path, de->d_name);
1953 if (lstat(path->buf, &st_git)) {
1954 if (errno != ENOENT)
1955 die_errno(_("cannot stat '%s'"), path->buf);
1957 else
1958 exists = 1;
1960 if (lstat(template_path->buf, &st_template))
1961 die_errno(_("cannot stat template '%s'"), template_path->buf);
1963 if (S_ISDIR(st_template.st_mode)) {
1964 DIR *subdir = opendir(template_path->buf);
1965 if (!subdir)
1966 die_errno(_("cannot opendir '%s'"), template_path->buf);
1967 strbuf_addch(path, '/');
1968 strbuf_addch(template_path, '/');
1969 copy_templates_1(path, template_path, subdir);
1970 closedir(subdir);
1972 else if (exists)
1973 continue;
1974 else if (S_ISLNK(st_template.st_mode)) {
1975 struct strbuf lnk = STRBUF_INIT;
1976 if (strbuf_readlink(&lnk, template_path->buf,
1977 st_template.st_size) < 0)
1978 die_errno(_("cannot readlink '%s'"), template_path->buf);
1979 if (symlink(lnk.buf, path->buf))
1980 die_errno(_("cannot symlink '%s' '%s'"),
1981 lnk.buf, path->buf);
1982 strbuf_release(&lnk);
1984 else if (S_ISREG(st_template.st_mode)) {
1985 if (copy_file(path->buf, template_path->buf, st_template.st_mode))
1986 die_errno(_("cannot copy '%s' to '%s'"),
1987 template_path->buf, path->buf);
1989 else
1990 error(_("ignoring template %s"), template_path->buf);
1994 static void copy_templates(const char *option_template)
1996 const char *template_dir = get_template_dir(option_template);
1997 struct strbuf path = STRBUF_INIT;
1998 struct strbuf template_path = STRBUF_INIT;
1999 size_t template_len;
2000 struct repository_format template_format = REPOSITORY_FORMAT_INIT;
2001 struct strbuf err = STRBUF_INIT;
2002 DIR *dir;
2003 char *to_free = NULL;
2005 if (!template_dir || !*template_dir)
2006 return;
2008 strbuf_addstr(&template_path, template_dir);
2009 strbuf_complete(&template_path, '/');
2010 template_len = template_path.len;
2012 dir = opendir(template_path.buf);
2013 if (!dir) {
2014 warning(_("templates not found in %s"), template_dir);
2015 goto free_return;
2018 /* Make sure that template is from the correct vintage */
2019 strbuf_addstr(&template_path, "config");
2020 read_repository_format(&template_format, template_path.buf);
2021 strbuf_setlen(&template_path, template_len);
2024 * No mention of version at all is OK, but anything else should be
2025 * verified.
2027 if (template_format.version >= 0 &&
2028 verify_repository_format(&template_format, &err) < 0) {
2029 warning(_("not copying templates from '%s': %s"),
2030 template_dir, err.buf);
2031 strbuf_release(&err);
2032 goto close_free_return;
2035 strbuf_addstr(&path, get_git_common_dir());
2036 strbuf_complete(&path, '/');
2037 copy_templates_1(&path, &template_path, dir);
2038 close_free_return:
2039 closedir(dir);
2040 free_return:
2041 free(to_free);
2042 strbuf_release(&path);
2043 strbuf_release(&template_path);
2044 clear_repository_format(&template_format);
2048 * If the git_dir is not directly inside the working tree, then git will not
2049 * find it by default, and we need to set the worktree explicitly.
2051 static int needs_work_tree_config(const char *git_dir, const char *work_tree)
2053 if (!strcmp(work_tree, "/") && !strcmp(git_dir, "/.git"))
2054 return 0;
2055 if (skip_prefix(git_dir, work_tree, &git_dir) &&
2056 !strcmp(git_dir, "/.git"))
2057 return 0;
2058 return 1;
2061 void initialize_repository_version(int hash_algo,
2062 enum ref_storage_format ref_storage_format,
2063 int reinit)
2065 char repo_version_string[10];
2066 int repo_version = GIT_REPO_VERSION;
2069 * Note that we initialize the repository version to 1 when the ref
2070 * storage format is unknown. This is on purpose so that we can add the
2071 * correct object format to the config during git-clone(1). The format
2072 * version will get adjusted by git-clone(1) once it has learned about
2073 * the remote repository's format.
2075 if (hash_algo != GIT_HASH_SHA1 ||
2076 ref_storage_format != REF_STORAGE_FORMAT_FILES)
2077 repo_version = GIT_REPO_VERSION_READ;
2079 /* This forces creation of new config file */
2080 xsnprintf(repo_version_string, sizeof(repo_version_string),
2081 "%d", repo_version);
2082 git_config_set("core.repositoryformatversion", repo_version_string);
2084 if (hash_algo != GIT_HASH_SHA1 && hash_algo != GIT_HASH_UNKNOWN)
2085 git_config_set("extensions.objectformat",
2086 hash_algos[hash_algo].name);
2087 else if (reinit)
2088 git_config_set_gently("extensions.objectformat", NULL);
2090 if (ref_storage_format != REF_STORAGE_FORMAT_FILES)
2091 git_config_set("extensions.refstorage",
2092 ref_storage_format_to_name(ref_storage_format));
2093 else if (reinit)
2094 git_config_set_gently("extensions.refstorage", NULL);
2097 static int is_reinit(void)
2099 struct strbuf buf = STRBUF_INIT;
2100 char junk[2];
2101 int ret;
2103 git_path_buf(&buf, "HEAD");
2104 ret = !access(buf.buf, R_OK) || readlink(buf.buf, junk, sizeof(junk) - 1) != -1;
2105 strbuf_release(&buf);
2106 return ret;
2109 void create_reference_database(enum ref_storage_format ref_storage_format,
2110 const char *initial_branch, int quiet)
2112 struct strbuf err = STRBUF_INIT;
2113 char *to_free = NULL;
2114 int reinit = is_reinit();
2116 repo_set_ref_storage_format(the_repository, ref_storage_format);
2117 if (ref_store_create_on_disk(get_main_ref_store(the_repository), 0, &err))
2118 die("failed to set up refs db: %s", err.buf);
2121 * Point the HEAD symref to the initial branch with if HEAD does
2122 * not yet exist.
2124 if (!reinit) {
2125 char *ref;
2127 if (!initial_branch)
2128 initial_branch = to_free =
2129 repo_default_branch_name(the_repository, quiet);
2131 ref = xstrfmt("refs/heads/%s", initial_branch);
2132 if (check_refname_format(ref, 0) < 0)
2133 die(_("invalid initial branch name: '%s'"),
2134 initial_branch);
2136 if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", ref, NULL) < 0)
2137 exit(1);
2138 free(ref);
2141 if (reinit && initial_branch)
2142 warning(_("re-init: ignored --initial-branch=%s"),
2143 initial_branch);
2145 strbuf_release(&err);
2146 free(to_free);
2149 static int create_default_files(const char *template_path,
2150 const char *original_git_dir,
2151 const struct repository_format *fmt,
2152 int init_shared_repository)
2154 struct stat st1;
2155 struct strbuf buf = STRBUF_INIT;
2156 char *path;
2157 int reinit;
2158 int filemode;
2159 const char *work_tree = get_git_work_tree();
2162 * First copy the templates -- we might have the default
2163 * config file there, in which case we would want to read
2164 * from it after installing.
2166 * Before reading that config, we also need to clear out any cached
2167 * values (since we've just potentially changed what's available on
2168 * disk).
2170 copy_templates(template_path);
2171 git_config_clear();
2172 reset_shared_repository();
2173 git_config(git_default_config, NULL);
2175 reinit = is_reinit();
2178 * We must make sure command-line options continue to override any
2179 * values we might have just re-read from the config.
2181 if (init_shared_repository != -1)
2182 set_shared_repository(init_shared_repository);
2184 is_bare_repository_cfg = !work_tree;
2187 * We would have created the above under user's umask -- under
2188 * shared-repository settings, we would need to fix them up.
2190 if (get_shared_repository()) {
2191 adjust_shared_perm(get_git_dir());
2194 initialize_repository_version(fmt->hash_algo, fmt->ref_storage_format, 0);
2196 /* Check filemode trustability */
2197 path = git_path_buf(&buf, "config");
2198 filemode = TEST_FILEMODE;
2199 if (TEST_FILEMODE && !lstat(path, &st1)) {
2200 struct stat st2;
2201 filemode = (!chmod(path, st1.st_mode ^ S_IXUSR) &&
2202 !lstat(path, &st2) &&
2203 st1.st_mode != st2.st_mode &&
2204 !chmod(path, st1.st_mode));
2205 if (filemode && !reinit && (st1.st_mode & S_IXUSR))
2206 filemode = 0;
2208 git_config_set("core.filemode", filemode ? "true" : "false");
2210 if (is_bare_repository())
2211 git_config_set("core.bare", "true");
2212 else {
2213 git_config_set("core.bare", "false");
2214 /* allow template config file to override the default */
2215 if (log_all_ref_updates == LOG_REFS_UNSET)
2216 git_config_set("core.logallrefupdates", "true");
2217 if (needs_work_tree_config(original_git_dir, work_tree))
2218 git_config_set("core.worktree", work_tree);
2221 if (!reinit) {
2222 /* Check if symlink is supported in the work tree */
2223 path = git_path_buf(&buf, "tXXXXXX");
2224 if (!close(xmkstemp(path)) &&
2225 !unlink(path) &&
2226 !symlink("testing", path) &&
2227 !lstat(path, &st1) &&
2228 S_ISLNK(st1.st_mode))
2229 unlink(path); /* good */
2230 else
2231 git_config_set("core.symlinks", "false");
2233 /* Check if the filesystem is case-insensitive */
2234 path = git_path_buf(&buf, "CoNfIg");
2235 if (!access(path, F_OK))
2236 git_config_set("core.ignorecase", "true");
2237 probe_utf8_pathname_composition();
2240 strbuf_release(&buf);
2241 return reinit;
2244 static void create_object_directory(void)
2246 struct strbuf path = STRBUF_INIT;
2247 size_t baselen;
2249 strbuf_addstr(&path, get_object_directory());
2250 baselen = path.len;
2252 safe_create_dir(path.buf, 1);
2254 strbuf_setlen(&path, baselen);
2255 strbuf_addstr(&path, "/pack");
2256 safe_create_dir(path.buf, 1);
2258 strbuf_setlen(&path, baselen);
2259 strbuf_addstr(&path, "/info");
2260 safe_create_dir(path.buf, 1);
2262 strbuf_release(&path);
2265 static void separate_git_dir(const char *git_dir, const char *git_link)
2267 struct stat st;
2269 if (!stat(git_link, &st)) {
2270 const char *src;
2272 if (S_ISREG(st.st_mode))
2273 src = read_gitfile(git_link);
2274 else if (S_ISDIR(st.st_mode))
2275 src = git_link;
2276 else
2277 die(_("unable to handle file type %d"), (int)st.st_mode);
2279 if (rename(src, git_dir))
2280 die_errno(_("unable to move %s to %s"), src, git_dir);
2281 repair_worktrees(NULL, NULL);
2284 write_file(git_link, "gitdir: %s", git_dir);
2287 static void validate_hash_algorithm(struct repository_format *repo_fmt, int hash)
2289 const char *env = getenv(GIT_DEFAULT_HASH_ENVIRONMENT);
2291 * If we already have an initialized repo, don't allow the user to
2292 * specify a different algorithm, as that could cause corruption.
2293 * Otherwise, if the user has specified one on the command line, use it.
2295 if (repo_fmt->version >= 0 && hash != GIT_HASH_UNKNOWN && hash != repo_fmt->hash_algo)
2296 die(_("attempt to reinitialize repository with different hash"));
2297 else if (hash != GIT_HASH_UNKNOWN)
2298 repo_fmt->hash_algo = hash;
2299 else if (env) {
2300 int env_algo = hash_algo_by_name(env);
2301 if (env_algo == GIT_HASH_UNKNOWN)
2302 die(_("unknown hash algorithm '%s'"), env);
2303 repo_fmt->hash_algo = env_algo;
2307 static void validate_ref_storage_format(struct repository_format *repo_fmt,
2308 enum ref_storage_format format)
2310 const char *name = getenv("GIT_DEFAULT_REF_FORMAT");
2312 if (repo_fmt->version >= 0 &&
2313 format != REF_STORAGE_FORMAT_UNKNOWN &&
2314 format != repo_fmt->ref_storage_format) {
2315 die(_("attempt to reinitialize repository with different reference storage format"));
2316 } else if (format != REF_STORAGE_FORMAT_UNKNOWN) {
2317 repo_fmt->ref_storage_format = format;
2318 } else if (name) {
2319 format = ref_storage_format_by_name(name);
2320 if (format == REF_STORAGE_FORMAT_UNKNOWN)
2321 die(_("unknown ref storage format '%s'"), name);
2322 repo_fmt->ref_storage_format = format;
2326 int init_db(const char *git_dir, const char *real_git_dir,
2327 const char *template_dir, int hash,
2328 enum ref_storage_format ref_storage_format,
2329 const char *initial_branch,
2330 int init_shared_repository, unsigned int flags)
2332 int reinit;
2333 int exist_ok = flags & INIT_DB_EXIST_OK;
2334 char *original_git_dir = real_pathdup(git_dir, 1);
2335 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
2337 if (real_git_dir) {
2338 struct stat st;
2340 if (!exist_ok && !stat(git_dir, &st))
2341 die(_("%s already exists"), git_dir);
2343 if (!exist_ok && !stat(real_git_dir, &st))
2344 die(_("%s already exists"), real_git_dir);
2346 set_git_dir(real_git_dir, 1);
2347 git_dir = get_git_dir();
2348 separate_git_dir(git_dir, original_git_dir);
2350 else {
2351 set_git_dir(git_dir, 1);
2352 git_dir = get_git_dir();
2354 startup_info->have_repository = 1;
2356 /* Check to see if the repository version is right.
2357 * Note that a newly created repository does not have
2358 * config file, so this will not fail. What we are catching
2359 * is an attempt to reinitialize new repository with an old tool.
2361 check_repository_format(&repo_fmt);
2363 validate_hash_algorithm(&repo_fmt, hash);
2364 validate_ref_storage_format(&repo_fmt, ref_storage_format);
2367 * Now that we have set up both the hash algorithm and the ref storage
2368 * format we can update the repository's settings accordingly.
2370 repo_set_hash_algo(the_repository, repo_fmt.hash_algo);
2371 repo_set_ref_storage_format(the_repository, repo_fmt.ref_storage_format);
2374 * Ensure `core.hidedotfiles` is processed. This must happen after we
2375 * have set up the repository format such that we can evaluate
2376 * includeIf conditions correctly in the case of re-initialization.
2378 git_config(platform_core_config, NULL);
2380 safe_create_dir(git_dir, 0);
2382 reinit = create_default_files(template_dir, original_git_dir,
2383 &repo_fmt, init_shared_repository);
2385 if (!(flags & INIT_DB_SKIP_REFDB))
2386 create_reference_database(repo_fmt.ref_storage_format,
2387 initial_branch, flags & INIT_DB_QUIET);
2388 create_object_directory();
2390 if (get_shared_repository()) {
2391 char buf[10];
2392 /* We do not spell "group" and such, so that
2393 * the configuration can be read by older version
2394 * of git. Note, we use octal numbers for new share modes,
2395 * and compatibility values for PERM_GROUP and
2396 * PERM_EVERYBODY.
2398 if (get_shared_repository() < 0)
2399 /* force to the mode value */
2400 xsnprintf(buf, sizeof(buf), "0%o", -get_shared_repository());
2401 else if (get_shared_repository() == PERM_GROUP)
2402 xsnprintf(buf, sizeof(buf), "%d", OLD_PERM_GROUP);
2403 else if (get_shared_repository() == PERM_EVERYBODY)
2404 xsnprintf(buf, sizeof(buf), "%d", OLD_PERM_EVERYBODY);
2405 else
2406 BUG("invalid value for shared_repository");
2407 git_config_set("core.sharedrepository", buf);
2408 git_config_set("receive.denyNonFastforwards", "true");
2411 if (!(flags & INIT_DB_QUIET)) {
2412 int len = strlen(git_dir);
2414 if (reinit)
2415 printf(get_shared_repository()
2416 ? _("Reinitialized existing shared Git repository in %s%s\n")
2417 : _("Reinitialized existing Git repository in %s%s\n"),
2418 git_dir, len && git_dir[len-1] != '/' ? "/" : "");
2419 else
2420 printf(get_shared_repository()
2421 ? _("Initialized empty shared Git repository in %s%s\n")
2422 : _("Initialized empty Git repository in %s%s\n"),
2423 git_dir, len && git_dir[len-1] != '/' ? "/" : "");
2426 clear_repository_format(&repo_fmt);
2427 free(original_git_dir);
2428 return 0;