Sync with 'master'
[git.git] / setup.c
blob6049553c8665fbcbf7724778503690ee04417ded
1 #include "git-compat-util.h"
2 #include "abspath.h"
3 #include "copy.h"
4 #include "environment.h"
5 #include "exec-cmd.h"
6 #include "gettext.h"
7 #include "hex.h"
8 #include "object-name.h"
9 #include "refs.h"
10 #include "repository.h"
11 #include "config.h"
12 #include "dir.h"
13 #include "setup.h"
14 #include "string-list.h"
15 #include "chdir-notify.h"
16 #include "path.h"
17 #include "quote.h"
18 #include "trace2.h"
19 #include "worktree.h"
21 static int inside_git_dir = -1;
22 static int inside_work_tree = -1;
23 static int work_tree_config_is_bogus;
24 enum allowed_bare_repo {
25 ALLOWED_BARE_REPO_EXPLICIT = 0,
26 ALLOWED_BARE_REPO_ALL,
29 static struct startup_info the_startup_info;
30 struct startup_info *startup_info = &the_startup_info;
31 const char *tmp_original_cwd;
34 * The input parameter must contain an absolute path, and it must already be
35 * normalized.
37 * Find the part of an absolute path that lies inside the work tree by
38 * dereferencing symlinks outside the work tree, for example:
39 * /dir1/repo/dir2/file (work tree is /dir1/repo) -> dir2/file
40 * /dir/file (work tree is /) -> dir/file
41 * /dir/symlink1/symlink2 (symlink1 points to work tree) -> symlink2
42 * /dir/repolink/file (repolink points to /dir/repo) -> file
43 * /dir/repo (exactly equal to work tree) -> (empty string)
45 static int abspath_part_inside_repo(char *path)
47 size_t len;
48 size_t wtlen;
49 char *path0;
50 int off;
51 const char *work_tree = get_git_work_tree();
52 struct strbuf realpath = STRBUF_INIT;
54 if (!work_tree)
55 return -1;
56 wtlen = strlen(work_tree);
57 len = strlen(path);
58 off = offset_1st_component(path);
60 /* check if work tree is already the prefix */
61 if (wtlen <= len && !fspathncmp(path, work_tree, wtlen)) {
62 if (path[wtlen] == '/') {
63 memmove(path, path + wtlen + 1, len - wtlen);
64 return 0;
65 } else if (path[wtlen - 1] == '/' || path[wtlen] == '\0') {
66 /* work tree is the root, or the whole path */
67 memmove(path, path + wtlen, len - wtlen + 1);
68 return 0;
70 /* work tree might match beginning of a symlink to work tree */
71 off = wtlen;
73 path0 = path;
74 path += off;
76 /* check each '/'-terminated level */
77 while (*path) {
78 path++;
79 if (*path == '/') {
80 *path = '\0';
81 strbuf_realpath(&realpath, path0, 1);
82 if (fspathcmp(realpath.buf, work_tree) == 0) {
83 memmove(path0, path + 1, len - (path - path0));
84 strbuf_release(&realpath);
85 return 0;
87 *path = '/';
91 /* check whole path */
92 strbuf_realpath(&realpath, path0, 1);
93 if (fspathcmp(realpath.buf, work_tree) == 0) {
94 *path0 = '\0';
95 strbuf_release(&realpath);
96 return 0;
99 strbuf_release(&realpath);
100 return -1;
104 * Normalize "path", prepending the "prefix" for relative paths. If
105 * remaining_prefix is not NULL, return the actual prefix still
106 * remains in the path. For example, prefix = sub1/sub2/ and path is
108 * foo -> sub1/sub2/foo (full prefix)
109 * ../foo -> sub1/foo (remaining prefix is sub1/)
110 * ../../bar -> bar (no remaining prefix)
111 * ../../sub1/sub2/foo -> sub1/sub2/foo (but no remaining prefix)
112 * `pwd`/../bar -> sub1/bar (no remaining prefix)
114 char *prefix_path_gently(const char *prefix, int len,
115 int *remaining_prefix, const char *path)
117 const char *orig = path;
118 char *sanitized;
119 if (is_absolute_path(orig)) {
120 sanitized = xmallocz(strlen(path));
121 if (remaining_prefix)
122 *remaining_prefix = 0;
123 if (normalize_path_copy_len(sanitized, path, remaining_prefix)) {
124 free(sanitized);
125 return NULL;
127 if (abspath_part_inside_repo(sanitized)) {
128 free(sanitized);
129 return NULL;
131 } else {
132 sanitized = xstrfmt("%.*s%s", len, len ? prefix : "", path);
133 if (remaining_prefix)
134 *remaining_prefix = len;
135 if (normalize_path_copy_len(sanitized, sanitized, remaining_prefix)) {
136 free(sanitized);
137 return NULL;
140 return sanitized;
143 char *prefix_path(const char *prefix, int len, const char *path)
145 char *r = prefix_path_gently(prefix, len, NULL, path);
146 if (!r) {
147 const char *hint_path = get_git_work_tree();
148 if (!hint_path)
149 hint_path = get_git_dir();
150 die(_("'%s' is outside repository at '%s'"), path,
151 absolute_path(hint_path));
153 return r;
156 int path_inside_repo(const char *prefix, const char *path)
158 int len = prefix ? strlen(prefix) : 0;
159 char *r = prefix_path_gently(prefix, len, NULL, path);
160 if (r) {
161 free(r);
162 return 1;
164 return 0;
167 int check_filename(const char *prefix, const char *arg)
169 char *to_free = NULL;
170 struct stat st;
172 if (skip_prefix(arg, ":/", &arg)) {
173 if (!*arg) /* ":/" is root dir, always exists */
174 return 1;
175 prefix = NULL;
176 } else if (skip_prefix(arg, ":!", &arg) ||
177 skip_prefix(arg, ":^", &arg)) {
178 if (!*arg) /* excluding everything is silly, but allowed */
179 return 1;
182 if (prefix)
183 arg = to_free = prefix_filename(prefix, arg);
185 if (!lstat(arg, &st)) {
186 free(to_free);
187 return 1; /* file exists */
189 if (is_missing_file_error(errno)) {
190 free(to_free);
191 return 0; /* file does not exist */
193 die_errno(_("failed to stat '%s'"), arg);
196 static void NORETURN die_verify_filename(struct repository *r,
197 const char *prefix,
198 const char *arg,
199 int diagnose_misspelt_rev)
201 if (!diagnose_misspelt_rev)
202 die(_("%s: no such path in the working tree.\n"
203 "Use 'git <command> -- <path>...' to specify paths that do not exist locally."),
204 arg);
206 * Saying "'(icase)foo' does not exist in the index" when the
207 * user gave us ":(icase)foo" is just stupid. A magic pathspec
208 * begins with a colon and is followed by a non-alnum; do not
209 * let maybe_die_on_misspelt_object_name() even trigger.
211 if (!(arg[0] == ':' && !isalnum(arg[1])))
212 maybe_die_on_misspelt_object_name(r, arg, prefix);
214 /* ... or fall back the most general message. */
215 die(_("ambiguous argument '%s': unknown revision or path not in the working tree.\n"
216 "Use '--' to separate paths from revisions, like this:\n"
217 "'git <command> [<revision>...] -- [<file>...]'"), arg);
222 * Check for arguments that don't resolve as actual files,
223 * but which look sufficiently like pathspecs that we'll consider
224 * them such for the purposes of rev/pathspec DWIM parsing.
226 static int looks_like_pathspec(const char *arg)
228 const char *p;
229 int escaped = 0;
232 * Wildcard characters imply the user is looking to match pathspecs
233 * that aren't in the filesystem. Note that this doesn't include
234 * backslash even though it's a glob special; by itself it doesn't
235 * cause any increase in the match. Likewise ignore backslash-escaped
236 * wildcard characters.
238 for (p = arg; *p; p++) {
239 if (escaped) {
240 escaped = 0;
241 } else if (is_glob_special(*p)) {
242 if (*p == '\\')
243 escaped = 1;
244 else
245 return 1;
249 /* long-form pathspec magic */
250 if (starts_with(arg, ":("))
251 return 1;
253 return 0;
257 * Verify a filename that we got as an argument for a pathspec
258 * entry. Note that a filename that begins with "-" never verifies
259 * as true, because even if such a filename were to exist, we want
260 * it to be preceded by the "--" marker (or we want the user to
261 * use a format like "./-filename")
263 * The "diagnose_misspelt_rev" is used to provide a user-friendly
264 * diagnosis when dying upon finding that "name" is not a pathname.
265 * If set to 1, the diagnosis will try to diagnose "name" as an
266 * invalid object name (e.g. HEAD:foo). If set to 0, the diagnosis
267 * will only complain about an inexisting file.
269 * This function is typically called to check that a "file or rev"
270 * argument is unambiguous. In this case, the caller will want
271 * diagnose_misspelt_rev == 1 when verifying the first non-rev
272 * argument (which could have been a revision), and
273 * diagnose_misspelt_rev == 0 for the next ones (because we already
274 * saw a filename, there's not ambiguity anymore).
276 void verify_filename(const char *prefix,
277 const char *arg,
278 int diagnose_misspelt_rev)
280 if (*arg == '-')
281 die(_("option '%s' must come before non-option arguments"), arg);
282 if (looks_like_pathspec(arg) || check_filename(prefix, arg))
283 return;
284 die_verify_filename(the_repository, prefix, arg, diagnose_misspelt_rev);
288 * Opposite of the above: the command line did not have -- marker
289 * and we parsed the arg as a refname. It should not be interpretable
290 * as a filename.
292 void verify_non_filename(const char *prefix, const char *arg)
294 if (!is_inside_work_tree() || is_inside_git_dir())
295 return;
296 if (*arg == '-')
297 return; /* flag */
298 if (!check_filename(prefix, arg))
299 return;
300 die(_("ambiguous argument '%s': both revision and filename\n"
301 "Use '--' to separate paths from revisions, like this:\n"
302 "'git <command> [<revision>...] -- [<file>...]'"), arg);
305 int get_common_dir(struct strbuf *sb, const char *gitdir)
307 const char *git_env_common_dir = getenv(GIT_COMMON_DIR_ENVIRONMENT);
308 if (git_env_common_dir) {
309 strbuf_addstr(sb, git_env_common_dir);
310 return 1;
311 } else {
312 return get_common_dir_noenv(sb, gitdir);
316 int get_common_dir_noenv(struct strbuf *sb, const char *gitdir)
318 struct strbuf data = STRBUF_INIT;
319 struct strbuf path = STRBUF_INIT;
320 int ret = 0;
322 strbuf_addf(&path, "%s/commondir", gitdir);
323 if (file_exists(path.buf)) {
324 if (strbuf_read_file(&data, path.buf, 0) <= 0)
325 die_errno(_("failed to read %s"), path.buf);
326 while (data.len && (data.buf[data.len - 1] == '\n' ||
327 data.buf[data.len - 1] == '\r'))
328 data.len--;
329 data.buf[data.len] = '\0';
330 strbuf_reset(&path);
331 if (!is_absolute_path(data.buf))
332 strbuf_addf(&path, "%s/", gitdir);
333 strbuf_addbuf(&path, &data);
334 strbuf_add_real_path(sb, path.buf);
335 ret = 1;
336 } else {
337 strbuf_addstr(sb, gitdir);
340 strbuf_release(&data);
341 strbuf_release(&path);
342 return ret;
345 static int validate_headref(const char *path)
347 struct stat st;
348 char buffer[256];
349 const char *refname;
350 struct object_id oid;
351 int fd;
352 ssize_t len;
354 if (lstat(path, &st) < 0)
355 return -1;
357 /* Make sure it is a "refs/.." symlink */
358 if (S_ISLNK(st.st_mode)) {
359 len = readlink(path, buffer, sizeof(buffer)-1);
360 if (len >= 5 && !memcmp("refs/", buffer, 5))
361 return 0;
362 return -1;
366 * Anything else, just open it and try to see if it is a symbolic ref.
368 fd = open(path, O_RDONLY);
369 if (fd < 0)
370 return -1;
371 len = read_in_full(fd, buffer, sizeof(buffer)-1);
372 close(fd);
374 if (len < 0)
375 return -1;
376 buffer[len] = '\0';
379 * Is it a symbolic ref?
381 if (skip_prefix(buffer, "ref:", &refname)) {
382 while (isspace(*refname))
383 refname++;
384 if (starts_with(refname, "refs/"))
385 return 0;
389 * Is this a detached HEAD?
391 if (get_oid_hex_any(buffer, &oid) != GIT_HASH_UNKNOWN)
392 return 0;
394 return -1;
398 * Test if it looks like we're at a git directory.
399 * We want to see:
401 * - either an objects/ directory _or_ the proper
402 * GIT_OBJECT_DIRECTORY environment variable
403 * - a refs/ directory
404 * - either a HEAD symlink or a HEAD file that is formatted as
405 * a proper "ref:", or a regular file HEAD that has a properly
406 * formatted sha1 object name.
408 int is_git_directory(const char *suspect)
410 struct strbuf path = STRBUF_INIT;
411 int ret = 0;
412 size_t len;
414 /* Check worktree-related signatures */
415 strbuf_addstr(&path, suspect);
416 strbuf_complete(&path, '/');
417 strbuf_addstr(&path, "HEAD");
418 if (validate_headref(path.buf))
419 goto done;
421 strbuf_reset(&path);
422 get_common_dir(&path, suspect);
423 len = path.len;
425 /* Check non-worktree-related signatures */
426 if (getenv(DB_ENVIRONMENT)) {
427 if (access(getenv(DB_ENVIRONMENT), X_OK))
428 goto done;
430 else {
431 strbuf_setlen(&path, len);
432 strbuf_addstr(&path, "/objects");
433 if (access(path.buf, X_OK))
434 goto done;
437 strbuf_setlen(&path, len);
438 strbuf_addstr(&path, "/refs");
439 if (access(path.buf, X_OK))
440 goto done;
442 ret = 1;
443 done:
444 strbuf_release(&path);
445 return ret;
448 int is_nonbare_repository_dir(struct strbuf *path)
450 int ret = 0;
451 int gitfile_error;
452 size_t orig_path_len = path->len;
453 assert(orig_path_len != 0);
454 strbuf_complete(path, '/');
455 strbuf_addstr(path, ".git");
456 if (read_gitfile_gently(path->buf, &gitfile_error) || is_git_directory(path->buf))
457 ret = 1;
458 if (gitfile_error == READ_GITFILE_ERR_OPEN_FAILED ||
459 gitfile_error == READ_GITFILE_ERR_READ_FAILED)
460 ret = 1;
461 strbuf_setlen(path, orig_path_len);
462 return ret;
465 int is_inside_git_dir(void)
467 if (inside_git_dir < 0)
468 inside_git_dir = is_inside_dir(get_git_dir());
469 return inside_git_dir;
472 int is_inside_work_tree(void)
474 if (inside_work_tree < 0)
475 inside_work_tree = is_inside_dir(get_git_work_tree());
476 return inside_work_tree;
479 void setup_work_tree(void)
481 const char *work_tree;
482 static int initialized = 0;
484 if (initialized)
485 return;
487 if (work_tree_config_is_bogus)
488 die(_("unable to set up work tree using invalid config"));
490 work_tree = get_git_work_tree();
491 if (!work_tree || chdir_notify(work_tree))
492 die(_("this operation must be run in a work tree"));
495 * Make sure subsequent git processes find correct worktree
496 * if $GIT_WORK_TREE is set relative
498 if (getenv(GIT_WORK_TREE_ENVIRONMENT))
499 setenv(GIT_WORK_TREE_ENVIRONMENT, ".", 1);
501 initialized = 1;
504 static void setup_original_cwd(void)
506 struct strbuf tmp = STRBUF_INIT;
507 const char *worktree = NULL;
508 int offset = -1;
510 if (!tmp_original_cwd)
511 return;
514 * startup_info->original_cwd points to the current working
515 * directory we inherited from our parent process, which is a
516 * directory we want to avoid removing.
518 * For convience, we would like to have the path relative to the
519 * worktree instead of an absolute path.
521 * Yes, startup_info->original_cwd is usually the same as 'prefix',
522 * but differs in two ways:
523 * - prefix has a trailing '/'
524 * - if the user passes '-C' to git, that modifies the prefix but
525 * not startup_info->original_cwd.
528 /* Normalize the directory */
529 if (!strbuf_realpath(&tmp, tmp_original_cwd, 0)) {
530 trace2_data_string("setup", the_repository,
531 "realpath-path", tmp_original_cwd);
532 trace2_data_string("setup", the_repository,
533 "realpath-failure", strerror(errno));
534 free((char*)tmp_original_cwd);
535 tmp_original_cwd = NULL;
536 return;
539 free((char*)tmp_original_cwd);
540 tmp_original_cwd = NULL;
541 startup_info->original_cwd = strbuf_detach(&tmp, NULL);
544 * Get our worktree; we only protect the current working directory
545 * if it's in the worktree.
547 worktree = get_git_work_tree();
548 if (!worktree)
549 goto no_prevention_needed;
551 offset = dir_inside_of(startup_info->original_cwd, worktree);
552 if (offset >= 0) {
554 * If startup_info->original_cwd == worktree, that is already
555 * protected and we don't need original_cwd as a secondary
556 * protection measure.
558 if (!*(startup_info->original_cwd + offset))
559 goto no_prevention_needed;
562 * original_cwd was inside worktree; precompose it just as
563 * we do prefix so that built up paths will match
565 startup_info->original_cwd = \
566 precompose_string_if_needed(startup_info->original_cwd
567 + offset);
568 return;
571 no_prevention_needed:
572 free((char*)startup_info->original_cwd);
573 startup_info->original_cwd = NULL;
576 static int read_worktree_config(const char *var, const char *value,
577 const struct config_context *ctx UNUSED,
578 void *vdata)
580 struct repository_format *data = vdata;
582 if (strcmp(var, "core.bare") == 0) {
583 data->is_bare = git_config_bool(var, value);
584 } else if (strcmp(var, "core.worktree") == 0) {
585 if (!value)
586 return config_error_nonbool(var);
587 free(data->work_tree);
588 data->work_tree = xstrdup(value);
590 return 0;
593 enum extension_result {
594 EXTENSION_ERROR = -1, /* compatible with error(), etc */
595 EXTENSION_UNKNOWN = 0,
596 EXTENSION_OK = 1
600 * Do not add new extensions to this function. It handles extensions which are
601 * respected even in v0-format repositories for historical compatibility.
603 static enum extension_result handle_extension_v0(const char *var,
604 const char *value,
605 const char *ext,
606 struct repository_format *data)
608 if (!strcmp(ext, "noop")) {
609 return EXTENSION_OK;
610 } else if (!strcmp(ext, "preciousobjects")) {
611 data->precious_objects = git_config_bool(var, value);
612 return EXTENSION_OK;
613 } else if (!strcmp(ext, "partialclone")) {
614 if (!value)
615 return config_error_nonbool(var);
616 data->partial_clone = xstrdup(value);
617 return EXTENSION_OK;
618 } else if (!strcmp(ext, "worktreeconfig")) {
619 data->worktree_config = git_config_bool(var, value);
620 return EXTENSION_OK;
623 return EXTENSION_UNKNOWN;
627 * Record any new extensions in this function.
629 static enum extension_result handle_extension(const char *var,
630 const char *value,
631 const char *ext,
632 struct repository_format *data)
634 if (!strcmp(ext, "noop-v1")) {
635 return EXTENSION_OK;
636 } else if (!strcmp(ext, "objectformat")) {
637 int format;
639 if (!value)
640 return config_error_nonbool(var);
641 format = hash_algo_by_name(value);
642 if (format == GIT_HASH_UNKNOWN)
643 return error(_("invalid value for '%s': '%s'"),
644 "extensions.objectformat", value);
645 data->hash_algo = format;
646 return EXTENSION_OK;
647 } else if (!strcmp(ext, "compatobjectformat")) {
648 struct string_list_item *item;
649 int format;
651 if (!value)
652 return config_error_nonbool(var);
653 format = hash_algo_by_name(value);
654 if (format == GIT_HASH_UNKNOWN)
655 return error(_("invalid value for '%s': '%s'"),
656 "extensions.compatobjectformat", value);
657 /* For now only support compatObjectFormat being specified once. */
658 for_each_string_list_item(item, &data->v1_only_extensions) {
659 if (!strcmp(item->string, "compatobjectformat"))
660 return error(_("'%s' already specified as '%s'"),
661 "extensions.compatobjectformat",
662 hash_algos[data->compat_hash_algo].name);
664 data->compat_hash_algo = format;
665 return EXTENSION_OK;
666 } else if (!strcmp(ext, "refstorage")) {
667 unsigned int format;
669 if (!value)
670 return config_error_nonbool(var);
671 format = ref_storage_format_by_name(value);
672 if (format == REF_STORAGE_FORMAT_UNKNOWN)
673 return error(_("invalid value for '%s': '%s'"),
674 "extensions.refstorage", value);
675 data->ref_storage_format = format;
676 return EXTENSION_OK;
678 return EXTENSION_UNKNOWN;
681 static int check_repo_format(const char *var, const char *value,
682 const struct config_context *ctx, void *vdata)
684 struct repository_format *data = vdata;
685 const char *ext;
687 if (strcmp(var, "core.repositoryformatversion") == 0)
688 data->version = git_config_int(var, value, ctx->kvi);
689 else if (skip_prefix(var, "extensions.", &ext)) {
690 switch (handle_extension_v0(var, value, ext, data)) {
691 case EXTENSION_ERROR:
692 return -1;
693 case EXTENSION_OK:
694 return 0;
695 case EXTENSION_UNKNOWN:
696 break;
699 switch (handle_extension(var, value, ext, data)) {
700 case EXTENSION_ERROR:
701 return -1;
702 case EXTENSION_OK:
703 string_list_append(&data->v1_only_extensions, ext);
704 return 0;
705 case EXTENSION_UNKNOWN:
706 string_list_append(&data->unknown_extensions, ext);
707 return 0;
711 return read_worktree_config(var, value, ctx, vdata);
714 static int check_repository_format_gently(const char *gitdir, struct repository_format *candidate, int *nongit_ok)
716 struct strbuf sb = STRBUF_INIT;
717 struct strbuf err = STRBUF_INIT;
718 int has_common;
720 has_common = get_common_dir(&sb, gitdir);
721 strbuf_addstr(&sb, "/config");
722 read_repository_format(candidate, sb.buf);
723 strbuf_release(&sb);
726 * For historical use of check_repository_format() in git-init,
727 * we treat a missing config as a silent "ok", even when nongit_ok
728 * is unset.
730 if (candidate->version < 0)
731 return 0;
733 if (verify_repository_format(candidate, &err) < 0) {
734 if (nongit_ok) {
735 warning("%s", err.buf);
736 strbuf_release(&err);
737 *nongit_ok = -1;
738 return -1;
740 die("%s", err.buf);
743 repository_format_precious_objects = candidate->precious_objects;
744 string_list_clear(&candidate->unknown_extensions, 0);
745 string_list_clear(&candidate->v1_only_extensions, 0);
747 if (candidate->worktree_config) {
749 * pick up core.bare and core.worktree from per-worktree
750 * config if present
752 strbuf_addf(&sb, "%s/config.worktree", gitdir);
753 git_config_from_file(read_worktree_config, sb.buf, candidate);
754 strbuf_release(&sb);
755 has_common = 0;
758 if (!has_common) {
759 if (candidate->is_bare != -1) {
760 is_bare_repository_cfg = candidate->is_bare;
761 if (is_bare_repository_cfg == 1)
762 inside_work_tree = -1;
764 if (candidate->work_tree) {
765 free(git_work_tree_cfg);
766 git_work_tree_cfg = xstrdup(candidate->work_tree);
767 inside_work_tree = -1;
771 return 0;
774 int upgrade_repository_format(int target_version)
776 struct strbuf sb = STRBUF_INIT;
777 struct strbuf err = STRBUF_INIT;
778 struct strbuf repo_version = STRBUF_INIT;
779 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
780 int ret;
782 strbuf_git_common_path(&sb, the_repository, "config");
783 read_repository_format(&repo_fmt, sb.buf);
784 strbuf_release(&sb);
786 if (repo_fmt.version >= target_version) {
787 ret = 0;
788 goto out;
791 if (verify_repository_format(&repo_fmt, &err) < 0) {
792 ret = error("cannot upgrade repository format from %d to %d: %s",
793 repo_fmt.version, target_version, err.buf);
794 goto out;
796 if (!repo_fmt.version && repo_fmt.unknown_extensions.nr) {
797 ret = error("cannot upgrade repository format: "
798 "unknown extension %s",
799 repo_fmt.unknown_extensions.items[0].string);
800 goto out;
803 strbuf_addf(&repo_version, "%d", target_version);
804 git_config_set("core.repositoryformatversion", repo_version.buf);
806 ret = 1;
808 out:
809 clear_repository_format(&repo_fmt);
810 strbuf_release(&repo_version);
811 strbuf_release(&err);
812 return ret;
815 static void init_repository_format(struct repository_format *format)
817 const struct repository_format fresh = REPOSITORY_FORMAT_INIT;
819 memcpy(format, &fresh, sizeof(fresh));
822 int read_repository_format(struct repository_format *format, const char *path)
824 clear_repository_format(format);
825 git_config_from_file(check_repo_format, path, format);
826 if (format->version == -1)
827 clear_repository_format(format);
828 return format->version;
831 void clear_repository_format(struct repository_format *format)
833 string_list_clear(&format->unknown_extensions, 0);
834 string_list_clear(&format->v1_only_extensions, 0);
835 free(format->work_tree);
836 free(format->partial_clone);
837 init_repository_format(format);
840 int verify_repository_format(const struct repository_format *format,
841 struct strbuf *err)
843 if (GIT_REPO_VERSION_READ < format->version) {
844 strbuf_addf(err, _("Expected git repo version <= %d, found %d"),
845 GIT_REPO_VERSION_READ, format->version);
846 return -1;
849 if (format->version >= 1 && format->unknown_extensions.nr) {
850 int i;
852 strbuf_addstr(err, Q_("unknown repository extension found:",
853 "unknown repository extensions found:",
854 format->unknown_extensions.nr));
856 for (i = 0; i < format->unknown_extensions.nr; i++)
857 strbuf_addf(err, "\n\t%s",
858 format->unknown_extensions.items[i].string);
859 return -1;
862 if (format->version == 0 && format->v1_only_extensions.nr) {
863 int i;
865 strbuf_addstr(err,
866 Q_("repo version is 0, but v1-only extension found:",
867 "repo version is 0, but v1-only extensions found:",
868 format->v1_only_extensions.nr));
870 for (i = 0; i < format->v1_only_extensions.nr; i++)
871 strbuf_addf(err, "\n\t%s",
872 format->v1_only_extensions.items[i].string);
873 return -1;
876 return 0;
879 void read_gitfile_error_die(int error_code, const char *path, const char *dir)
881 switch (error_code) {
882 case READ_GITFILE_ERR_STAT_FAILED:
883 case READ_GITFILE_ERR_NOT_A_FILE:
884 /* non-fatal; follow return path */
885 break;
886 case READ_GITFILE_ERR_OPEN_FAILED:
887 die_errno(_("error opening '%s'"), path);
888 case READ_GITFILE_ERR_TOO_LARGE:
889 die(_("too large to be a .git file: '%s'"), path);
890 case READ_GITFILE_ERR_READ_FAILED:
891 die(_("error reading %s"), path);
892 case READ_GITFILE_ERR_INVALID_FORMAT:
893 die(_("invalid gitfile format: %s"), path);
894 case READ_GITFILE_ERR_NO_PATH:
895 die(_("no path in gitfile: %s"), path);
896 case READ_GITFILE_ERR_NOT_A_REPO:
897 die(_("not a git repository: %s"), dir);
898 default:
899 BUG("unknown error code");
904 * Try to read the location of the git directory from the .git file,
905 * return path to git directory if found. The return value comes from
906 * a shared buffer.
908 * On failure, if return_error_code is not NULL, return_error_code
909 * will be set to an error code and NULL will be returned. If
910 * return_error_code is NULL the function will die instead (for most
911 * cases).
913 const char *read_gitfile_gently(const char *path, int *return_error_code)
915 const int max_file_size = 1 << 20; /* 1MB */
916 int error_code = 0;
917 char *buf = NULL;
918 char *dir = NULL;
919 const char *slash;
920 struct stat st;
921 int fd;
922 ssize_t len;
923 static struct strbuf realpath = STRBUF_INIT;
925 if (stat(path, &st)) {
926 /* NEEDSWORK: discern between ENOENT vs other errors */
927 error_code = READ_GITFILE_ERR_STAT_FAILED;
928 goto cleanup_return;
930 if (!S_ISREG(st.st_mode)) {
931 error_code = READ_GITFILE_ERR_NOT_A_FILE;
932 goto cleanup_return;
934 if (st.st_size > max_file_size) {
935 error_code = READ_GITFILE_ERR_TOO_LARGE;
936 goto cleanup_return;
938 fd = open(path, O_RDONLY);
939 if (fd < 0) {
940 error_code = READ_GITFILE_ERR_OPEN_FAILED;
941 goto cleanup_return;
943 buf = xmallocz(st.st_size);
944 len = read_in_full(fd, buf, st.st_size);
945 close(fd);
946 if (len != st.st_size) {
947 error_code = READ_GITFILE_ERR_READ_FAILED;
948 goto cleanup_return;
950 if (!starts_with(buf, "gitdir: ")) {
951 error_code = READ_GITFILE_ERR_INVALID_FORMAT;
952 goto cleanup_return;
954 while (buf[len - 1] == '\n' || buf[len - 1] == '\r')
955 len--;
956 if (len < 9) {
957 error_code = READ_GITFILE_ERR_NO_PATH;
958 goto cleanup_return;
960 buf[len] = '\0';
961 dir = buf + 8;
963 if (!is_absolute_path(dir) && (slash = strrchr(path, '/'))) {
964 size_t pathlen = slash+1 - path;
965 dir = xstrfmt("%.*s%.*s", (int)pathlen, path,
966 (int)(len - 8), buf + 8);
967 free(buf);
968 buf = dir;
970 if (!is_git_directory(dir)) {
971 error_code = READ_GITFILE_ERR_NOT_A_REPO;
972 goto cleanup_return;
975 strbuf_realpath(&realpath, dir, 1);
976 path = realpath.buf;
978 cleanup_return:
979 if (return_error_code)
980 *return_error_code = error_code;
981 else if (error_code)
982 read_gitfile_error_die(error_code, path, dir);
984 free(buf);
985 return error_code ? NULL : path;
988 static const char *setup_explicit_git_dir(const char *gitdirenv,
989 struct strbuf *cwd,
990 struct repository_format *repo_fmt,
991 int *nongit_ok)
993 const char *work_tree_env = getenv(GIT_WORK_TREE_ENVIRONMENT);
994 const char *worktree;
995 char *gitfile;
996 int offset;
998 if (PATH_MAX - 40 < strlen(gitdirenv))
999 die(_("'$%s' too big"), GIT_DIR_ENVIRONMENT);
1001 gitfile = (char*)read_gitfile(gitdirenv);
1002 if (gitfile) {
1003 gitfile = xstrdup(gitfile);
1004 gitdirenv = gitfile;
1007 if (!is_git_directory(gitdirenv)) {
1008 if (nongit_ok) {
1009 *nongit_ok = 1;
1010 free(gitfile);
1011 return NULL;
1013 die(_("not a git repository: '%s'"), gitdirenv);
1016 if (check_repository_format_gently(gitdirenv, repo_fmt, nongit_ok)) {
1017 free(gitfile);
1018 return NULL;
1021 /* #3, #7, #11, #15, #19, #23, #27, #31 (see t1510) */
1022 if (work_tree_env)
1023 set_git_work_tree(work_tree_env);
1024 else if (is_bare_repository_cfg > 0) {
1025 if (git_work_tree_cfg) {
1026 /* #22.2, #30 */
1027 warning("core.bare and core.worktree do not make sense");
1028 work_tree_config_is_bogus = 1;
1031 /* #18, #26 */
1032 set_git_dir(gitdirenv, 0);
1033 free(gitfile);
1034 return NULL;
1036 else if (git_work_tree_cfg) { /* #6, #14 */
1037 if (is_absolute_path(git_work_tree_cfg))
1038 set_git_work_tree(git_work_tree_cfg);
1039 else {
1040 char *core_worktree;
1041 if (chdir(gitdirenv))
1042 die_errno(_("cannot chdir to '%s'"), gitdirenv);
1043 if (chdir(git_work_tree_cfg))
1044 die_errno(_("cannot chdir to '%s'"), git_work_tree_cfg);
1045 core_worktree = xgetcwd();
1046 if (chdir(cwd->buf))
1047 die_errno(_("cannot come back to cwd"));
1048 set_git_work_tree(core_worktree);
1049 free(core_worktree);
1052 else if (!git_env_bool(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, 1)) {
1053 /* #16d */
1054 set_git_dir(gitdirenv, 0);
1055 free(gitfile);
1056 return NULL;
1058 else /* #2, #10 */
1059 set_git_work_tree(".");
1061 /* set_git_work_tree() must have been called by now */
1062 worktree = get_git_work_tree();
1064 /* both get_git_work_tree() and cwd are already normalized */
1065 if (!strcmp(cwd->buf, worktree)) { /* cwd == worktree */
1066 set_git_dir(gitdirenv, 0);
1067 free(gitfile);
1068 return NULL;
1071 offset = dir_inside_of(cwd->buf, worktree);
1072 if (offset >= 0) { /* cwd inside worktree? */
1073 set_git_dir(gitdirenv, 1);
1074 if (chdir(worktree))
1075 die_errno(_("cannot chdir to '%s'"), worktree);
1076 strbuf_addch(cwd, '/');
1077 free(gitfile);
1078 return cwd->buf + offset;
1081 /* cwd outside worktree */
1082 set_git_dir(gitdirenv, 0);
1083 free(gitfile);
1084 return NULL;
1087 static const char *setup_discovered_git_dir(const char *gitdir,
1088 struct strbuf *cwd, int offset,
1089 struct repository_format *repo_fmt,
1090 int *nongit_ok)
1092 if (check_repository_format_gently(gitdir, repo_fmt, nongit_ok))
1093 return NULL;
1095 /* --work-tree is set without --git-dir; use discovered one */
1096 if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
1097 char *to_free = NULL;
1098 const char *ret;
1100 if (offset != cwd->len && !is_absolute_path(gitdir))
1101 gitdir = to_free = real_pathdup(gitdir, 1);
1102 if (chdir(cwd->buf))
1103 die_errno(_("cannot come back to cwd"));
1104 ret = setup_explicit_git_dir(gitdir, cwd, repo_fmt, nongit_ok);
1105 free(to_free);
1106 return ret;
1109 /* #16.2, #17.2, #20.2, #21.2, #24, #25, #28, #29 (see t1510) */
1110 if (is_bare_repository_cfg > 0) {
1111 set_git_dir(gitdir, (offset != cwd->len));
1112 if (chdir(cwd->buf))
1113 die_errno(_("cannot come back to cwd"));
1114 return NULL;
1117 /* #0, #1, #5, #8, #9, #12, #13 */
1118 set_git_work_tree(".");
1119 if (strcmp(gitdir, DEFAULT_GIT_DIR_ENVIRONMENT))
1120 set_git_dir(gitdir, 0);
1121 inside_git_dir = 0;
1122 inside_work_tree = 1;
1123 if (offset >= cwd->len)
1124 return NULL;
1126 /* Make "offset" point past the '/' (already the case for root dirs) */
1127 if (offset != offset_1st_component(cwd->buf))
1128 offset++;
1129 /* Add a '/' at the end */
1130 strbuf_addch(cwd, '/');
1131 return cwd->buf + offset;
1134 /* #16.1, #17.1, #20.1, #21.1, #22.1 (see t1510) */
1135 static const char *setup_bare_git_dir(struct strbuf *cwd, int offset,
1136 struct repository_format *repo_fmt,
1137 int *nongit_ok)
1139 int root_len;
1141 if (check_repository_format_gently(".", repo_fmt, nongit_ok))
1142 return NULL;
1144 setenv(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, "0", 1);
1146 /* --work-tree is set without --git-dir; use discovered one */
1147 if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
1148 static const char *gitdir;
1150 gitdir = offset == cwd->len ? "." : xmemdupz(cwd->buf, offset);
1151 if (chdir(cwd->buf))
1152 die_errno(_("cannot come back to cwd"));
1153 return setup_explicit_git_dir(gitdir, cwd, repo_fmt, nongit_ok);
1156 inside_git_dir = 1;
1157 inside_work_tree = 0;
1158 if (offset != cwd->len) {
1159 if (chdir(cwd->buf))
1160 die_errno(_("cannot come back to cwd"));
1161 root_len = offset_1st_component(cwd->buf);
1162 strbuf_setlen(cwd, offset > root_len ? offset : root_len);
1163 set_git_dir(cwd->buf, 0);
1165 else
1166 set_git_dir(".", 0);
1167 return NULL;
1170 static dev_t get_device_or_die(const char *path, const char *prefix, int prefix_len)
1172 struct stat buf;
1173 if (stat(path, &buf)) {
1174 die_errno(_("failed to stat '%*s%s%s'"),
1175 prefix_len,
1176 prefix ? prefix : "",
1177 prefix ? "/" : "", path);
1179 return buf.st_dev;
1183 * A "string_list_each_func_t" function that canonicalizes an entry
1184 * from GIT_CEILING_DIRECTORIES using real_pathdup(), or
1185 * discards it if unusable. The presence of an empty entry in
1186 * GIT_CEILING_DIRECTORIES turns off canonicalization for all
1187 * subsequent entries.
1189 static int canonicalize_ceiling_entry(struct string_list_item *item,
1190 void *cb_data)
1192 int *empty_entry_found = cb_data;
1193 char *ceil = item->string;
1195 if (!*ceil) {
1196 *empty_entry_found = 1;
1197 return 0;
1198 } else if (!is_absolute_path(ceil)) {
1199 return 0;
1200 } else if (*empty_entry_found) {
1201 /* Keep entry but do not canonicalize it */
1202 return 1;
1203 } else {
1204 char *real_path = real_pathdup(ceil, 0);
1205 if (!real_path) {
1206 return 0;
1208 free(item->string);
1209 item->string = real_path;
1210 return 1;
1214 struct safe_directory_data {
1215 const char *path;
1216 int is_safe;
1219 static int safe_directory_cb(const char *key, const char *value,
1220 const struct config_context *ctx UNUSED, void *d)
1222 struct safe_directory_data *data = d;
1224 if (strcmp(key, "safe.directory"))
1225 return 0;
1227 if (!value || !*value) {
1228 data->is_safe = 0;
1229 } else if (!strcmp(value, "*")) {
1230 data->is_safe = 1;
1231 } else {
1232 const char *interpolated = NULL;
1234 if (!git_config_pathname(&interpolated, key, value) &&
1235 !fspathcmp(data->path, interpolated ? interpolated : value))
1236 data->is_safe = 1;
1238 free((char *)interpolated);
1241 return 0;
1245 * Check if a repository is safe, by verifying the ownership of the
1246 * worktree (if any), the git directory, and the gitfile (if any).
1248 * Exemptions for known-safe repositories can be added via `safe.directory`
1249 * config settings; for non-bare repositories, their worktree needs to be
1250 * added, for bare ones their git directory.
1252 static int ensure_valid_ownership(const char *gitfile,
1253 const char *worktree, const char *gitdir,
1254 struct strbuf *report)
1256 struct safe_directory_data data = {
1257 .path = worktree ? worktree : gitdir
1260 if (!git_env_bool("GIT_TEST_ASSUME_DIFFERENT_OWNER", 0) &&
1261 (!gitfile || is_path_owned_by_current_user(gitfile, report)) &&
1262 (!worktree || is_path_owned_by_current_user(worktree, report)) &&
1263 (!gitdir || is_path_owned_by_current_user(gitdir, report)))
1264 return 1;
1267 * data.path is the "path" that identifies the repository and it is
1268 * constant regardless of what failed above. data.is_safe should be
1269 * initialized to false, and might be changed by the callback.
1271 git_protected_config(safe_directory_cb, &data);
1273 return data.is_safe;
1276 static int allowed_bare_repo_cb(const char *key, const char *value,
1277 const struct config_context *ctx UNUSED,
1278 void *d)
1280 enum allowed_bare_repo *allowed_bare_repo = d;
1282 if (strcasecmp(key, "safe.bareRepository"))
1283 return 0;
1285 if (!strcmp(value, "explicit")) {
1286 *allowed_bare_repo = ALLOWED_BARE_REPO_EXPLICIT;
1287 return 0;
1289 if (!strcmp(value, "all")) {
1290 *allowed_bare_repo = ALLOWED_BARE_REPO_ALL;
1291 return 0;
1293 return -1;
1296 static enum allowed_bare_repo get_allowed_bare_repo(void)
1298 enum allowed_bare_repo result = ALLOWED_BARE_REPO_ALL;
1299 git_protected_config(allowed_bare_repo_cb, &result);
1300 return result;
1303 static const char *allowed_bare_repo_to_string(
1304 enum allowed_bare_repo allowed_bare_repo)
1306 switch (allowed_bare_repo) {
1307 case ALLOWED_BARE_REPO_EXPLICIT:
1308 return "explicit";
1309 case ALLOWED_BARE_REPO_ALL:
1310 return "all";
1311 default:
1312 BUG("invalid allowed_bare_repo %d",
1313 allowed_bare_repo);
1315 return NULL;
1318 static int is_implicit_bare_repo(const char *path)
1321 * what we found is a ".git" directory at the root of
1322 * the working tree.
1324 if (ends_with_path_components(path, ".git"))
1325 return 1;
1328 * we are inside $GIT_DIR of a secondary worktree of a
1329 * non-bare repository.
1331 if (strstr(path, "/.git/worktrees/"))
1332 return 1;
1335 * we are inside $GIT_DIR of a worktree of a non-embedded
1336 * submodule, whose superproject is not a bare repository.
1338 if (strstr(path, "/.git/modules/"))
1339 return 1;
1341 return 0;
1345 * We cannot decide in this function whether we are in the work tree or
1346 * not, since the config can only be read _after_ this function was called.
1348 * Also, we avoid changing any global state (such as the current working
1349 * directory) to allow early callers.
1351 * The directory where the search should start needs to be passed in via the
1352 * `dir` parameter; upon return, the `dir` buffer will contain the path of
1353 * the directory where the search ended, and `gitdir` will contain the path of
1354 * the discovered .git/ directory, if any. If `gitdir` is not absolute, it
1355 * is relative to `dir` (i.e. *not* necessarily the cwd).
1357 static enum discovery_result setup_git_directory_gently_1(struct strbuf *dir,
1358 struct strbuf *gitdir,
1359 struct strbuf *report,
1360 int die_on_error)
1362 const char *env_ceiling_dirs = getenv(CEILING_DIRECTORIES_ENVIRONMENT);
1363 struct string_list ceiling_dirs = STRING_LIST_INIT_DUP;
1364 const char *gitdirenv;
1365 int ceil_offset = -1, min_offset = offset_1st_component(dir->buf);
1366 dev_t current_device = 0;
1367 int one_filesystem = 1;
1370 * If GIT_DIR is set explicitly, we're not going
1371 * to do any discovery, but we still do repository
1372 * validation.
1374 gitdirenv = getenv(GIT_DIR_ENVIRONMENT);
1375 if (gitdirenv) {
1376 strbuf_addstr(gitdir, gitdirenv);
1377 return GIT_DIR_EXPLICIT;
1380 if (env_ceiling_dirs) {
1381 int empty_entry_found = 0;
1383 string_list_split(&ceiling_dirs, env_ceiling_dirs, PATH_SEP, -1);
1384 filter_string_list(&ceiling_dirs, 0,
1385 canonicalize_ceiling_entry, &empty_entry_found);
1386 ceil_offset = longest_ancestor_length(dir->buf, &ceiling_dirs);
1387 string_list_clear(&ceiling_dirs, 0);
1390 if (ceil_offset < 0)
1391 ceil_offset = min_offset - 2;
1393 if (min_offset && min_offset == dir->len &&
1394 !is_dir_sep(dir->buf[min_offset - 1])) {
1395 strbuf_addch(dir, '/');
1396 min_offset++;
1400 * Test in the following order (relative to the dir):
1401 * - .git (file containing "gitdir: <path>")
1402 * - .git/
1403 * - ./ (bare)
1404 * - ../.git
1405 * - ../.git/
1406 * - ../ (bare)
1407 * - ../../.git
1408 * etc.
1410 one_filesystem = !git_env_bool("GIT_DISCOVERY_ACROSS_FILESYSTEM", 0);
1411 if (one_filesystem)
1412 current_device = get_device_or_die(dir->buf, NULL, 0);
1413 for (;;) {
1414 int offset = dir->len, error_code = 0;
1415 char *gitdir_path = NULL;
1416 char *gitfile = NULL;
1418 if (offset > min_offset)
1419 strbuf_addch(dir, '/');
1420 strbuf_addstr(dir, DEFAULT_GIT_DIR_ENVIRONMENT);
1421 gitdirenv = read_gitfile_gently(dir->buf, die_on_error ?
1422 NULL : &error_code);
1423 if (!gitdirenv) {
1424 if (die_on_error ||
1425 error_code == READ_GITFILE_ERR_NOT_A_FILE) {
1426 /* NEEDSWORK: fail if .git is not file nor dir */
1427 if (is_git_directory(dir->buf)) {
1428 gitdirenv = DEFAULT_GIT_DIR_ENVIRONMENT;
1429 gitdir_path = xstrdup(dir->buf);
1431 } else if (error_code != READ_GITFILE_ERR_STAT_FAILED)
1432 return GIT_DIR_INVALID_GITFILE;
1433 } else
1434 gitfile = xstrdup(dir->buf);
1436 * Earlier, we tentatively added DEFAULT_GIT_DIR_ENVIRONMENT
1437 * to check that directory for a repository.
1438 * Now trim that tentative addition away, because we want to
1439 * focus on the real directory we are in.
1441 strbuf_setlen(dir, offset);
1442 if (gitdirenv) {
1443 enum discovery_result ret;
1444 const char *gitdir_candidate =
1445 gitdir_path ? gitdir_path : gitdirenv;
1447 if (ensure_valid_ownership(gitfile, dir->buf,
1448 gitdir_candidate, report)) {
1449 strbuf_addstr(gitdir, gitdirenv);
1450 ret = GIT_DIR_DISCOVERED;
1451 } else
1452 ret = GIT_DIR_INVALID_OWNERSHIP;
1455 * Earlier, during discovery, we might have allocated
1456 * string copies for gitdir_path or gitfile so make
1457 * sure we don't leak by freeing them now, before
1458 * leaving the loop and function.
1460 * Note: gitdirenv will be non-NULL whenever these are
1461 * allocated, therefore we need not take care of releasing
1462 * them outside of this conditional block.
1464 free(gitdir_path);
1465 free(gitfile);
1467 return ret;
1470 if (is_git_directory(dir->buf)) {
1471 trace2_data_string("setup", NULL, "implicit-bare-repository", dir->buf);
1472 if (get_allowed_bare_repo() == ALLOWED_BARE_REPO_EXPLICIT &&
1473 !is_implicit_bare_repo(dir->buf))
1474 return GIT_DIR_DISALLOWED_BARE;
1475 if (!ensure_valid_ownership(NULL, NULL, dir->buf, report))
1476 return GIT_DIR_INVALID_OWNERSHIP;
1477 strbuf_addstr(gitdir, ".");
1478 return GIT_DIR_BARE;
1481 if (offset <= min_offset)
1482 return GIT_DIR_HIT_CEILING;
1484 while (--offset > ceil_offset && !is_dir_sep(dir->buf[offset]))
1485 ; /* continue */
1486 if (offset <= ceil_offset)
1487 return GIT_DIR_HIT_CEILING;
1489 strbuf_setlen(dir, offset > min_offset ? offset : min_offset);
1490 if (one_filesystem &&
1491 current_device != get_device_or_die(dir->buf, NULL, offset))
1492 return GIT_DIR_HIT_MOUNT_POINT;
1496 enum discovery_result discover_git_directory_reason(struct strbuf *commondir,
1497 struct strbuf *gitdir)
1499 struct strbuf dir = STRBUF_INIT, err = STRBUF_INIT;
1500 size_t gitdir_offset = gitdir->len, cwd_len;
1501 size_t commondir_offset = commondir->len;
1502 struct repository_format candidate = REPOSITORY_FORMAT_INIT;
1503 enum discovery_result result;
1505 if (strbuf_getcwd(&dir))
1506 return GIT_DIR_CWD_FAILURE;
1508 cwd_len = dir.len;
1509 result = setup_git_directory_gently_1(&dir, gitdir, NULL, 0);
1510 if (result <= 0) {
1511 strbuf_release(&dir);
1512 return result;
1516 * The returned gitdir is relative to dir, and if dir does not reflect
1517 * the current working directory, we simply make the gitdir absolute.
1519 if (dir.len < cwd_len && !is_absolute_path(gitdir->buf + gitdir_offset)) {
1520 /* Avoid a trailing "/." */
1521 if (!strcmp(".", gitdir->buf + gitdir_offset))
1522 strbuf_setlen(gitdir, gitdir_offset);
1523 else
1524 strbuf_addch(&dir, '/');
1525 strbuf_insert(gitdir, gitdir_offset, dir.buf, dir.len);
1528 get_common_dir(commondir, gitdir->buf + gitdir_offset);
1530 strbuf_reset(&dir);
1531 strbuf_addf(&dir, "%s/config", commondir->buf + commondir_offset);
1532 read_repository_format(&candidate, dir.buf);
1533 strbuf_release(&dir);
1535 if (verify_repository_format(&candidate, &err) < 0) {
1536 warning("ignoring git dir '%s': %s",
1537 gitdir->buf + gitdir_offset, err.buf);
1538 strbuf_release(&err);
1539 strbuf_setlen(commondir, commondir_offset);
1540 strbuf_setlen(gitdir, gitdir_offset);
1541 clear_repository_format(&candidate);
1542 return GIT_DIR_INVALID_FORMAT;
1545 clear_repository_format(&candidate);
1546 return result;
1549 const char *setup_git_directory_gently(int *nongit_ok)
1551 static struct strbuf cwd = STRBUF_INIT;
1552 struct strbuf dir = STRBUF_INIT, gitdir = STRBUF_INIT, report = STRBUF_INIT;
1553 const char *prefix = NULL;
1554 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
1557 * We may have read an incomplete configuration before
1558 * setting-up the git directory. If so, clear the cache so
1559 * that the next queries to the configuration reload complete
1560 * configuration (including the per-repo config file that we
1561 * ignored previously).
1563 git_config_clear();
1566 * Let's assume that we are in a git repository.
1567 * If it turns out later that we are somewhere else, the value will be
1568 * updated accordingly.
1570 if (nongit_ok)
1571 *nongit_ok = 0;
1573 if (strbuf_getcwd(&cwd))
1574 die_errno(_("Unable to read current working directory"));
1575 strbuf_addbuf(&dir, &cwd);
1577 switch (setup_git_directory_gently_1(&dir, &gitdir, &report, 1)) {
1578 case GIT_DIR_EXPLICIT:
1579 prefix = setup_explicit_git_dir(gitdir.buf, &cwd, &repo_fmt, nongit_ok);
1580 break;
1581 case GIT_DIR_DISCOVERED:
1582 if (dir.len < cwd.len && chdir(dir.buf))
1583 die(_("cannot change to '%s'"), dir.buf);
1584 prefix = setup_discovered_git_dir(gitdir.buf, &cwd, dir.len,
1585 &repo_fmt, nongit_ok);
1586 break;
1587 case GIT_DIR_BARE:
1588 if (dir.len < cwd.len && chdir(dir.buf))
1589 die(_("cannot change to '%s'"), dir.buf);
1590 prefix = setup_bare_git_dir(&cwd, dir.len, &repo_fmt, nongit_ok);
1591 break;
1592 case GIT_DIR_HIT_CEILING:
1593 if (!nongit_ok)
1594 die(_("not a git repository (or any of the parent directories): %s"),
1595 DEFAULT_GIT_DIR_ENVIRONMENT);
1596 *nongit_ok = 1;
1597 break;
1598 case GIT_DIR_HIT_MOUNT_POINT:
1599 if (!nongit_ok)
1600 die(_("not a git repository (or any parent up to mount point %s)\n"
1601 "Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set)."),
1602 dir.buf);
1603 *nongit_ok = 1;
1604 break;
1605 case GIT_DIR_INVALID_OWNERSHIP:
1606 if (!nongit_ok) {
1607 struct strbuf quoted = STRBUF_INIT;
1609 strbuf_complete(&report, '\n');
1610 sq_quote_buf_pretty(&quoted, dir.buf);
1611 die(_("detected dubious ownership in repository at '%s'\n"
1612 "%s"
1613 "To add an exception for this directory, call:\n"
1614 "\n"
1615 "\tgit config --global --add safe.directory %s"),
1616 dir.buf, report.buf, quoted.buf);
1618 *nongit_ok = 1;
1619 break;
1620 case GIT_DIR_DISALLOWED_BARE:
1621 if (!nongit_ok) {
1622 die(_("cannot use bare repository '%s' (safe.bareRepository is '%s')"),
1623 dir.buf,
1624 allowed_bare_repo_to_string(get_allowed_bare_repo()));
1626 *nongit_ok = 1;
1627 break;
1628 case GIT_DIR_CWD_FAILURE:
1629 case GIT_DIR_INVALID_FORMAT:
1631 * As a safeguard against setup_git_directory_gently_1 returning
1632 * these values, fallthrough to BUG. Otherwise it is possible to
1633 * set startup_info->have_repository to 1 when we did nothing to
1634 * find a repository.
1636 default:
1637 BUG("unhandled setup_git_directory_gently_1() result");
1641 * At this point, nongit_ok is stable. If it is non-NULL and points
1642 * to a non-zero value, then this means that we haven't found a
1643 * repository and that the caller expects startup_info to reflect
1644 * this.
1646 * Regardless of the state of nongit_ok, startup_info->prefix and
1647 * the GIT_PREFIX environment variable must always match. For details
1648 * see Documentation/config/alias.txt.
1650 if (nongit_ok && *nongit_ok)
1651 startup_info->have_repository = 0;
1652 else
1653 startup_info->have_repository = 1;
1656 * Not all paths through the setup code will call 'set_git_dir()' (which
1657 * directly sets up the environment) so in order to guarantee that the
1658 * environment is in a consistent state after setup, explicitly setup
1659 * the environment if we have a repository.
1661 * NEEDSWORK: currently we allow bogus GIT_DIR values to be set in some
1662 * code paths so we also need to explicitly setup the environment if
1663 * the user has set GIT_DIR. It may be beneficial to disallow bogus
1664 * GIT_DIR values at some point in the future.
1666 if (/* GIT_DIR_EXPLICIT, GIT_DIR_DISCOVERED, GIT_DIR_BARE */
1667 startup_info->have_repository ||
1668 /* GIT_DIR_EXPLICIT */
1669 getenv(GIT_DIR_ENVIRONMENT)) {
1670 if (!the_repository->gitdir) {
1671 const char *gitdir = getenv(GIT_DIR_ENVIRONMENT);
1672 if (!gitdir)
1673 gitdir = DEFAULT_GIT_DIR_ENVIRONMENT;
1674 setup_git_env(gitdir);
1676 if (startup_info->have_repository) {
1677 repo_set_hash_algo(the_repository, repo_fmt.hash_algo);
1678 repo_set_compat_hash_algo(the_repository,
1679 repo_fmt.compat_hash_algo);
1680 repo_set_ref_storage_format(the_repository,
1681 repo_fmt.ref_storage_format);
1682 the_repository->repository_format_worktree_config =
1683 repo_fmt.worktree_config;
1684 /* take ownership of repo_fmt.partial_clone */
1685 the_repository->repository_format_partial_clone =
1686 repo_fmt.partial_clone;
1687 repo_fmt.partial_clone = NULL;
1691 * Since precompose_string_if_needed() needs to look at
1692 * the core.precomposeunicode configuration, this
1693 * has to happen after the above block that finds
1694 * out where the repository is, i.e. a preparation
1695 * for calling git_config_get_bool().
1697 if (prefix) {
1698 prefix = precompose_string_if_needed(prefix);
1699 startup_info->prefix = prefix;
1700 setenv(GIT_PREFIX_ENVIRONMENT, prefix, 1);
1701 } else {
1702 startup_info->prefix = NULL;
1703 setenv(GIT_PREFIX_ENVIRONMENT, "", 1);
1706 setup_original_cwd();
1708 strbuf_release(&dir);
1709 strbuf_release(&gitdir);
1710 strbuf_release(&report);
1711 clear_repository_format(&repo_fmt);
1713 return prefix;
1716 int git_config_perm(const char *var, const char *value)
1718 int i;
1719 char *endptr;
1721 if (!value)
1722 return PERM_GROUP;
1724 if (!strcmp(value, "umask"))
1725 return PERM_UMASK;
1726 if (!strcmp(value, "group"))
1727 return PERM_GROUP;
1728 if (!strcmp(value, "all") ||
1729 !strcmp(value, "world") ||
1730 !strcmp(value, "everybody"))
1731 return PERM_EVERYBODY;
1733 /* Parse octal numbers */
1734 i = strtol(value, &endptr, 8);
1736 /* If not an octal number, maybe true/false? */
1737 if (*endptr != 0)
1738 return git_config_bool(var, value) ? PERM_GROUP : PERM_UMASK;
1741 * Treat values 0, 1 and 2 as compatibility cases, otherwise it is
1742 * a chmod value to restrict to.
1744 switch (i) {
1745 case PERM_UMASK: /* 0 */
1746 return PERM_UMASK;
1747 case OLD_PERM_GROUP: /* 1 */
1748 return PERM_GROUP;
1749 case OLD_PERM_EVERYBODY: /* 2 */
1750 return PERM_EVERYBODY;
1753 /* A filemode value was given: 0xxx */
1755 if ((i & 0600) != 0600)
1756 die(_("problem with core.sharedRepository filemode value "
1757 "(0%.3o).\nThe owner of files must always have "
1758 "read and write permissions."), i);
1761 * Mask filemode value. Others can not get write permission.
1762 * x flags for directories are handled separately.
1764 return -(i & 0666);
1767 void check_repository_format(struct repository_format *fmt)
1769 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
1770 if (!fmt)
1771 fmt = &repo_fmt;
1772 check_repository_format_gently(get_git_dir(), fmt, NULL);
1773 startup_info->have_repository = 1;
1774 repo_set_hash_algo(the_repository, fmt->hash_algo);
1775 repo_set_compat_hash_algo(the_repository, fmt->compat_hash_algo);
1776 repo_set_ref_storage_format(the_repository,
1777 fmt->ref_storage_format);
1778 the_repository->repository_format_worktree_config =
1779 fmt->worktree_config;
1780 the_repository->repository_format_partial_clone =
1781 xstrdup_or_null(fmt->partial_clone);
1782 clear_repository_format(&repo_fmt);
1786 * Returns the "prefix", a path to the current working directory
1787 * relative to the work tree root, or NULL, if the current working
1788 * directory is not a strict subdirectory of the work tree root. The
1789 * prefix always ends with a '/' character.
1791 const char *setup_git_directory(void)
1793 return setup_git_directory_gently(NULL);
1796 const char *resolve_gitdir_gently(const char *suspect, int *return_error_code)
1798 if (is_git_directory(suspect))
1799 return suspect;
1800 return read_gitfile_gently(suspect, return_error_code);
1803 /* if any standard file descriptor is missing open it to /dev/null */
1804 void sanitize_stdfds(void)
1806 int fd = xopen("/dev/null", O_RDWR);
1807 while (fd < 2)
1808 fd = xdup(fd);
1809 if (fd > 2)
1810 close(fd);
1813 int daemonize(void)
1815 #ifdef NO_POSIX_GOODIES
1816 errno = ENOSYS;
1817 return -1;
1818 #else
1819 switch (fork()) {
1820 case 0:
1821 break;
1822 case -1:
1823 die_errno(_("fork failed"));
1824 default:
1825 exit(0);
1827 if (setsid() == -1)
1828 die_errno(_("setsid failed"));
1829 close(0);
1830 close(1);
1831 close(2);
1832 sanitize_stdfds();
1833 return 0;
1834 #endif
1837 #ifdef NO_TRUSTABLE_FILEMODE
1838 #define TEST_FILEMODE 0
1839 #else
1840 #define TEST_FILEMODE 1
1841 #endif
1843 #define GIT_DEFAULT_HASH_ENVIRONMENT "GIT_DEFAULT_HASH"
1845 static void copy_templates_1(struct strbuf *path, struct strbuf *template_path,
1846 DIR *dir)
1848 size_t path_baselen = path->len;
1849 size_t template_baselen = template_path->len;
1850 struct dirent *de;
1852 /* Note: if ".git/hooks" file exists in the repository being
1853 * re-initialized, /etc/core-git/templates/hooks/update would
1854 * cause "git init" to fail here. I think this is sane but
1855 * it means that the set of templates we ship by default, along
1856 * with the way the namespace under .git/ is organized, should
1857 * be really carefully chosen.
1859 safe_create_dir(path->buf, 1);
1860 while ((de = readdir(dir)) != NULL) {
1861 struct stat st_git, st_template;
1862 int exists = 0;
1864 strbuf_setlen(path, path_baselen);
1865 strbuf_setlen(template_path, template_baselen);
1867 if (de->d_name[0] == '.')
1868 continue;
1869 strbuf_addstr(path, de->d_name);
1870 strbuf_addstr(template_path, de->d_name);
1871 if (lstat(path->buf, &st_git)) {
1872 if (errno != ENOENT)
1873 die_errno(_("cannot stat '%s'"), path->buf);
1875 else
1876 exists = 1;
1878 if (lstat(template_path->buf, &st_template))
1879 die_errno(_("cannot stat template '%s'"), template_path->buf);
1881 if (S_ISDIR(st_template.st_mode)) {
1882 DIR *subdir = opendir(template_path->buf);
1883 if (!subdir)
1884 die_errno(_("cannot opendir '%s'"), template_path->buf);
1885 strbuf_addch(path, '/');
1886 strbuf_addch(template_path, '/');
1887 copy_templates_1(path, template_path, subdir);
1888 closedir(subdir);
1890 else if (exists)
1891 continue;
1892 else if (S_ISLNK(st_template.st_mode)) {
1893 struct strbuf lnk = STRBUF_INIT;
1894 if (strbuf_readlink(&lnk, template_path->buf,
1895 st_template.st_size) < 0)
1896 die_errno(_("cannot readlink '%s'"), template_path->buf);
1897 if (symlink(lnk.buf, path->buf))
1898 die_errno(_("cannot symlink '%s' '%s'"),
1899 lnk.buf, path->buf);
1900 strbuf_release(&lnk);
1902 else if (S_ISREG(st_template.st_mode)) {
1903 if (copy_file(path->buf, template_path->buf, st_template.st_mode))
1904 die_errno(_("cannot copy '%s' to '%s'"),
1905 template_path->buf, path->buf);
1907 else
1908 error(_("ignoring template %s"), template_path->buf);
1912 static void copy_templates(const char *template_dir, const char *init_template_dir)
1914 struct strbuf path = STRBUF_INIT;
1915 struct strbuf template_path = STRBUF_INIT;
1916 size_t template_len;
1917 struct repository_format template_format = REPOSITORY_FORMAT_INIT;
1918 struct strbuf err = STRBUF_INIT;
1919 DIR *dir;
1920 char *to_free = NULL;
1922 if (!template_dir)
1923 template_dir = getenv(TEMPLATE_DIR_ENVIRONMENT);
1924 if (!template_dir)
1925 template_dir = init_template_dir;
1926 if (!template_dir)
1927 template_dir = to_free = system_path(DEFAULT_GIT_TEMPLATE_DIR);
1928 if (!template_dir[0]) {
1929 free(to_free);
1930 return;
1933 strbuf_addstr(&template_path, template_dir);
1934 strbuf_complete(&template_path, '/');
1935 template_len = template_path.len;
1937 dir = opendir(template_path.buf);
1938 if (!dir) {
1939 warning(_("templates not found in %s"), template_dir);
1940 goto free_return;
1943 /* Make sure that template is from the correct vintage */
1944 strbuf_addstr(&template_path, "config");
1945 read_repository_format(&template_format, template_path.buf);
1946 strbuf_setlen(&template_path, template_len);
1949 * No mention of version at all is OK, but anything else should be
1950 * verified.
1952 if (template_format.version >= 0 &&
1953 verify_repository_format(&template_format, &err) < 0) {
1954 warning(_("not copying templates from '%s': %s"),
1955 template_dir, err.buf);
1956 strbuf_release(&err);
1957 goto close_free_return;
1960 strbuf_addstr(&path, get_git_common_dir());
1961 strbuf_complete(&path, '/');
1962 copy_templates_1(&path, &template_path, dir);
1963 close_free_return:
1964 closedir(dir);
1965 free_return:
1966 free(to_free);
1967 strbuf_release(&path);
1968 strbuf_release(&template_path);
1969 clear_repository_format(&template_format);
1973 * If the git_dir is not directly inside the working tree, then git will not
1974 * find it by default, and we need to set the worktree explicitly.
1976 static int needs_work_tree_config(const char *git_dir, const char *work_tree)
1978 if (!strcmp(work_tree, "/") && !strcmp(git_dir, "/.git"))
1979 return 0;
1980 if (skip_prefix(git_dir, work_tree, &git_dir) &&
1981 !strcmp(git_dir, "/.git"))
1982 return 0;
1983 return 1;
1986 void initialize_repository_version(int hash_algo,
1987 unsigned int ref_storage_format,
1988 int reinit)
1990 char repo_version_string[10];
1991 int repo_version = GIT_REPO_VERSION;
1994 * Note that we initialize the repository version to 1 when the ref
1995 * storage format is unknown. This is on purpose so that we can add the
1996 * correct object format to the config during git-clone(1). The format
1997 * version will get adjusted by git-clone(1) once it has learned about
1998 * the remote repository's format.
2000 if (hash_algo != GIT_HASH_SHA1 ||
2001 ref_storage_format != REF_STORAGE_FORMAT_FILES)
2002 repo_version = GIT_REPO_VERSION_READ;
2004 /* This forces creation of new config file */
2005 xsnprintf(repo_version_string, sizeof(repo_version_string),
2006 "%d", repo_version);
2007 git_config_set("core.repositoryformatversion", repo_version_string);
2009 if (hash_algo != GIT_HASH_SHA1 && hash_algo != GIT_HASH_UNKNOWN)
2010 git_config_set("extensions.objectformat",
2011 hash_algos[hash_algo].name);
2012 else if (reinit)
2013 git_config_set_gently("extensions.objectformat", NULL);
2015 if (ref_storage_format != REF_STORAGE_FORMAT_FILES)
2016 git_config_set("extensions.refstorage",
2017 ref_storage_format_to_name(ref_storage_format));
2020 static int is_reinit(void)
2022 struct strbuf buf = STRBUF_INIT;
2023 char junk[2];
2024 int ret;
2026 git_path_buf(&buf, "HEAD");
2027 ret = !access(buf.buf, R_OK) || readlink(buf.buf, junk, sizeof(junk) - 1) != -1;
2028 strbuf_release(&buf);
2029 return ret;
2032 void create_reference_database(unsigned int ref_storage_format,
2033 const char *initial_branch, int quiet)
2035 struct strbuf err = STRBUF_INIT;
2036 int reinit = is_reinit();
2038 repo_set_ref_storage_format(the_repository, ref_storage_format);
2039 if (refs_init_db(get_main_ref_store(the_repository), 0, &err))
2040 die("failed to set up refs db: %s", err.buf);
2043 * Point the HEAD symref to the initial branch with if HEAD does
2044 * not yet exist.
2046 if (!reinit) {
2047 char *ref;
2049 if (!initial_branch)
2050 initial_branch = git_default_branch_name(quiet);
2052 ref = xstrfmt("refs/heads/%s", initial_branch);
2053 if (check_refname_format(ref, 0) < 0)
2054 die(_("invalid initial branch name: '%s'"),
2055 initial_branch);
2057 if (refs_create_symref(get_main_ref_store(the_repository), "HEAD", ref, NULL) < 0)
2058 exit(1);
2059 free(ref);
2062 if (reinit && initial_branch)
2063 warning(_("re-init: ignored --initial-branch=%s"),
2064 initial_branch);
2066 strbuf_release(&err);
2069 static int create_default_files(const char *template_path,
2070 const char *original_git_dir,
2071 const struct repository_format *fmt,
2072 int init_shared_repository)
2074 struct stat st1;
2075 struct strbuf buf = STRBUF_INIT;
2076 char *path;
2077 int reinit;
2078 int filemode;
2079 const char *init_template_dir = NULL;
2080 const char *work_tree = get_git_work_tree();
2083 * First copy the templates -- we might have the default
2084 * config file there, in which case we would want to read
2085 * from it after installing.
2087 * Before reading that config, we also need to clear out any cached
2088 * values (since we've just potentially changed what's available on
2089 * disk).
2091 git_config_get_pathname("init.templatedir", &init_template_dir);
2092 copy_templates(template_path, init_template_dir);
2093 free((char *)init_template_dir);
2094 git_config_clear();
2095 reset_shared_repository();
2096 git_config(git_default_config, NULL);
2098 reinit = is_reinit();
2101 * We must make sure command-line options continue to override any
2102 * values we might have just re-read from the config.
2104 if (init_shared_repository != -1)
2105 set_shared_repository(init_shared_repository);
2107 is_bare_repository_cfg = !work_tree;
2110 * We would have created the above under user's umask -- under
2111 * shared-repository settings, we would need to fix them up.
2113 if (get_shared_repository()) {
2114 adjust_shared_perm(get_git_dir());
2117 initialize_repository_version(fmt->hash_algo, fmt->ref_storage_format, 0);
2119 /* Check filemode trustability */
2120 path = git_path_buf(&buf, "config");
2121 filemode = TEST_FILEMODE;
2122 if (TEST_FILEMODE && !lstat(path, &st1)) {
2123 struct stat st2;
2124 filemode = (!chmod(path, st1.st_mode ^ S_IXUSR) &&
2125 !lstat(path, &st2) &&
2126 st1.st_mode != st2.st_mode &&
2127 !chmod(path, st1.st_mode));
2128 if (filemode && !reinit && (st1.st_mode & S_IXUSR))
2129 filemode = 0;
2131 git_config_set("core.filemode", filemode ? "true" : "false");
2133 if (is_bare_repository())
2134 git_config_set("core.bare", "true");
2135 else {
2136 git_config_set("core.bare", "false");
2137 /* allow template config file to override the default */
2138 if (log_all_ref_updates == LOG_REFS_UNSET)
2139 git_config_set("core.logallrefupdates", "true");
2140 if (needs_work_tree_config(original_git_dir, work_tree))
2141 git_config_set("core.worktree", work_tree);
2144 if (!reinit) {
2145 /* Check if symlink is supported in the work tree */
2146 path = git_path_buf(&buf, "tXXXXXX");
2147 if (!close(xmkstemp(path)) &&
2148 !unlink(path) &&
2149 !symlink("testing", path) &&
2150 !lstat(path, &st1) &&
2151 S_ISLNK(st1.st_mode))
2152 unlink(path); /* good */
2153 else
2154 git_config_set("core.symlinks", "false");
2156 /* Check if the filesystem is case-insensitive */
2157 path = git_path_buf(&buf, "CoNfIg");
2158 if (!access(path, F_OK))
2159 git_config_set("core.ignorecase", "true");
2160 probe_utf8_pathname_composition();
2163 strbuf_release(&buf);
2164 return reinit;
2167 static void create_object_directory(void)
2169 struct strbuf path = STRBUF_INIT;
2170 size_t baselen;
2172 strbuf_addstr(&path, get_object_directory());
2173 baselen = path.len;
2175 safe_create_dir(path.buf, 1);
2177 strbuf_setlen(&path, baselen);
2178 strbuf_addstr(&path, "/pack");
2179 safe_create_dir(path.buf, 1);
2181 strbuf_setlen(&path, baselen);
2182 strbuf_addstr(&path, "/info");
2183 safe_create_dir(path.buf, 1);
2185 strbuf_release(&path);
2188 static void separate_git_dir(const char *git_dir, const char *git_link)
2190 struct stat st;
2192 if (!stat(git_link, &st)) {
2193 const char *src;
2195 if (S_ISREG(st.st_mode))
2196 src = read_gitfile(git_link);
2197 else if (S_ISDIR(st.st_mode))
2198 src = git_link;
2199 else
2200 die(_("unable to handle file type %d"), (int)st.st_mode);
2202 if (rename(src, git_dir))
2203 die_errno(_("unable to move %s to %s"), src, git_dir);
2204 repair_worktrees(NULL, NULL);
2207 write_file(git_link, "gitdir: %s", git_dir);
2210 static void validate_hash_algorithm(struct repository_format *repo_fmt, int hash)
2212 const char *env = getenv(GIT_DEFAULT_HASH_ENVIRONMENT);
2214 * If we already have an initialized repo, don't allow the user to
2215 * specify a different algorithm, as that could cause corruption.
2216 * Otherwise, if the user has specified one on the command line, use it.
2218 if (repo_fmt->version >= 0 && hash != GIT_HASH_UNKNOWN && hash != repo_fmt->hash_algo)
2219 die(_("attempt to reinitialize repository with different hash"));
2220 else if (hash != GIT_HASH_UNKNOWN)
2221 repo_fmt->hash_algo = hash;
2222 else if (env) {
2223 int env_algo = hash_algo_by_name(env);
2224 if (env_algo == GIT_HASH_UNKNOWN)
2225 die(_("unknown hash algorithm '%s'"), env);
2226 repo_fmt->hash_algo = env_algo;
2230 static void validate_ref_storage_format(struct repository_format *repo_fmt,
2231 unsigned int format)
2233 const char *name = getenv("GIT_DEFAULT_REF_FORMAT");
2235 if (repo_fmt->version >= 0 &&
2236 format != REF_STORAGE_FORMAT_UNKNOWN &&
2237 format != repo_fmt->ref_storage_format) {
2238 die(_("attempt to reinitialize repository with different reference storage format"));
2239 } else if (format != REF_STORAGE_FORMAT_UNKNOWN) {
2240 repo_fmt->ref_storage_format = format;
2241 } else if (name) {
2242 format = ref_storage_format_by_name(name);
2243 if (format == REF_STORAGE_FORMAT_UNKNOWN)
2244 die(_("unknown ref storage format '%s'"), name);
2245 repo_fmt->ref_storage_format = format;
2249 int init_db(const char *git_dir, const char *real_git_dir,
2250 const char *template_dir, int hash,
2251 unsigned int ref_storage_format,
2252 const char *initial_branch,
2253 int init_shared_repository, unsigned int flags)
2255 int reinit;
2256 int exist_ok = flags & INIT_DB_EXIST_OK;
2257 char *original_git_dir = real_pathdup(git_dir, 1);
2258 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
2260 if (real_git_dir) {
2261 struct stat st;
2263 if (!exist_ok && !stat(git_dir, &st))
2264 die(_("%s already exists"), git_dir);
2266 if (!exist_ok && !stat(real_git_dir, &st))
2267 die(_("%s already exists"), real_git_dir);
2269 set_git_dir(real_git_dir, 1);
2270 git_dir = get_git_dir();
2271 separate_git_dir(git_dir, original_git_dir);
2273 else {
2274 set_git_dir(git_dir, 1);
2275 git_dir = get_git_dir();
2277 startup_info->have_repository = 1;
2279 /* Ensure `core.hidedotfiles` is processed */
2280 git_config(platform_core_config, NULL);
2282 safe_create_dir(git_dir, 0);
2285 /* Check to see if the repository version is right.
2286 * Note that a newly created repository does not have
2287 * config file, so this will not fail. What we are catching
2288 * is an attempt to reinitialize new repository with an old tool.
2290 check_repository_format(&repo_fmt);
2292 validate_hash_algorithm(&repo_fmt, hash);
2293 validate_ref_storage_format(&repo_fmt, ref_storage_format);
2295 reinit = create_default_files(template_dir, original_git_dir,
2296 &repo_fmt, init_shared_repository);
2299 * Now that we have set up both the hash algorithm and the ref storage
2300 * format we can update the repository's settings accordingly.
2302 repo_set_hash_algo(the_repository, repo_fmt.hash_algo);
2303 repo_set_ref_storage_format(the_repository, repo_fmt.ref_storage_format);
2305 if (!(flags & INIT_DB_SKIP_REFDB))
2306 create_reference_database(repo_fmt.ref_storage_format,
2307 initial_branch, flags & INIT_DB_QUIET);
2308 create_object_directory();
2310 if (get_shared_repository()) {
2311 char buf[10];
2312 /* We do not spell "group" and such, so that
2313 * the configuration can be read by older version
2314 * of git. Note, we use octal numbers for new share modes,
2315 * and compatibility values for PERM_GROUP and
2316 * PERM_EVERYBODY.
2318 if (get_shared_repository() < 0)
2319 /* force to the mode value */
2320 xsnprintf(buf, sizeof(buf), "0%o", -get_shared_repository());
2321 else if (get_shared_repository() == PERM_GROUP)
2322 xsnprintf(buf, sizeof(buf), "%d", OLD_PERM_GROUP);
2323 else if (get_shared_repository() == PERM_EVERYBODY)
2324 xsnprintf(buf, sizeof(buf), "%d", OLD_PERM_EVERYBODY);
2325 else
2326 BUG("invalid value for shared_repository");
2327 git_config_set("core.sharedrepository", buf);
2328 git_config_set("receive.denyNonFastforwards", "true");
2331 if (!(flags & INIT_DB_QUIET)) {
2332 int len = strlen(git_dir);
2334 if (reinit)
2335 printf(get_shared_repository()
2336 ? _("Reinitialized existing shared Git repository in %s%s\n")
2337 : _("Reinitialized existing Git repository in %s%s\n"),
2338 git_dir, len && git_dir[len-1] != '/' ? "/" : "");
2339 else
2340 printf(get_shared_repository()
2341 ? _("Initialized empty shared Git repository in %s%s\n")
2342 : _("Initialized empty Git repository in %s%s\n"),
2343 git_dir, len && git_dir[len-1] != '/' ? "/" : "");
2346 clear_repository_format(&repo_fmt);
2347 free(original_git_dir);
2348 return 0;