parse-options-cb: stop clamping "--abbrev=" to hash length
[git/gitster.git] / setup.c
blobf00f6cf2b69f09b7c46a596e3b7a9ac6c923947f
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"
20 #include "exec-cmd.h"
22 static int inside_git_dir = -1;
23 static int inside_work_tree = -1;
24 static int work_tree_config_is_bogus;
25 enum allowed_bare_repo {
26 ALLOWED_BARE_REPO_EXPLICIT = 0,
27 ALLOWED_BARE_REPO_ALL,
30 static struct startup_info the_startup_info;
31 struct startup_info *startup_info = &the_startup_info;
32 const char *tmp_original_cwd;
35 * The input parameter must contain an absolute path, and it must already be
36 * normalized.
38 * Find the part of an absolute path that lies inside the work tree by
39 * dereferencing symlinks outside the work tree, for example:
40 * /dir1/repo/dir2/file (work tree is /dir1/repo) -> dir2/file
41 * /dir/file (work tree is /) -> dir/file
42 * /dir/symlink1/symlink2 (symlink1 points to work tree) -> symlink2
43 * /dir/repolink/file (repolink points to /dir/repo) -> file
44 * /dir/repo (exactly equal to work tree) -> (empty string)
46 static int abspath_part_inside_repo(char *path)
48 size_t len;
49 size_t wtlen;
50 char *path0;
51 int off;
52 const char *work_tree = get_git_work_tree();
53 struct strbuf realpath = STRBUF_INIT;
55 if (!work_tree)
56 return -1;
57 wtlen = strlen(work_tree);
58 len = strlen(path);
59 off = offset_1st_component(path);
61 /* check if work tree is already the prefix */
62 if (wtlen <= len && !fspathncmp(path, work_tree, wtlen)) {
63 if (path[wtlen] == '/') {
64 memmove(path, path + wtlen + 1, len - wtlen);
65 return 0;
66 } else if (path[wtlen - 1] == '/' || path[wtlen] == '\0') {
67 /* work tree is the root, or the whole path */
68 memmove(path, path + wtlen, len - wtlen + 1);
69 return 0;
71 /* work tree might match beginning of a symlink to work tree */
72 off = wtlen;
74 path0 = path;
75 path += off;
77 /* check each '/'-terminated level */
78 while (*path) {
79 path++;
80 if (*path == '/') {
81 *path = '\0';
82 strbuf_realpath(&realpath, path0, 1);
83 if (fspathcmp(realpath.buf, work_tree) == 0) {
84 memmove(path0, path + 1, len - (path - path0));
85 strbuf_release(&realpath);
86 return 0;
88 *path = '/';
92 /* check whole path */
93 strbuf_realpath(&realpath, path0, 1);
94 if (fspathcmp(realpath.buf, work_tree) == 0) {
95 *path0 = '\0';
96 strbuf_release(&realpath);
97 return 0;
100 strbuf_release(&realpath);
101 return -1;
105 * Normalize "path", prepending the "prefix" for relative paths. If
106 * remaining_prefix is not NULL, return the actual prefix still
107 * remains in the path. For example, prefix = sub1/sub2/ and path is
109 * foo -> sub1/sub2/foo (full prefix)
110 * ../foo -> sub1/foo (remaining prefix is sub1/)
111 * ../../bar -> bar (no remaining prefix)
112 * ../../sub1/sub2/foo -> sub1/sub2/foo (but no remaining prefix)
113 * `pwd`/../bar -> sub1/bar (no remaining prefix)
115 char *prefix_path_gently(const char *prefix, int len,
116 int *remaining_prefix, const char *path)
118 const char *orig = path;
119 char *sanitized;
120 if (is_absolute_path(orig)) {
121 sanitized = xmallocz(strlen(path));
122 if (remaining_prefix)
123 *remaining_prefix = 0;
124 if (normalize_path_copy_len(sanitized, path, remaining_prefix)) {
125 free(sanitized);
126 return NULL;
128 if (abspath_part_inside_repo(sanitized)) {
129 free(sanitized);
130 return NULL;
132 } else {
133 sanitized = xstrfmt("%.*s%s", len, len ? prefix : "", path);
134 if (remaining_prefix)
135 *remaining_prefix = len;
136 if (normalize_path_copy_len(sanitized, sanitized, remaining_prefix)) {
137 free(sanitized);
138 return NULL;
141 return sanitized;
144 char *prefix_path(const char *prefix, int len, const char *path)
146 char *r = prefix_path_gently(prefix, len, NULL, path);
147 if (!r) {
148 const char *hint_path = get_git_work_tree();
149 if (!hint_path)
150 hint_path = get_git_dir();
151 die(_("'%s' is outside repository at '%s'"), path,
152 absolute_path(hint_path));
154 return r;
157 int path_inside_repo(const char *prefix, const char *path)
159 int len = prefix ? strlen(prefix) : 0;
160 char *r = prefix_path_gently(prefix, len, NULL, path);
161 if (r) {
162 free(r);
163 return 1;
165 return 0;
168 int check_filename(const char *prefix, const char *arg)
170 char *to_free = NULL;
171 struct stat st;
173 if (skip_prefix(arg, ":/", &arg)) {
174 if (!*arg) /* ":/" is root dir, always exists */
175 return 1;
176 prefix = NULL;
177 } else if (skip_prefix(arg, ":!", &arg) ||
178 skip_prefix(arg, ":^", &arg)) {
179 if (!*arg) /* excluding everything is silly, but allowed */
180 return 1;
183 if (prefix)
184 arg = to_free = prefix_filename(prefix, arg);
186 if (!lstat(arg, &st)) {
187 free(to_free);
188 return 1; /* file exists */
190 if (is_missing_file_error(errno)) {
191 free(to_free);
192 return 0; /* file does not exist */
194 die_errno(_("failed to stat '%s'"), arg);
197 static void NORETURN die_verify_filename(struct repository *r,
198 const char *prefix,
199 const char *arg,
200 int diagnose_misspelt_rev)
202 if (!diagnose_misspelt_rev)
203 die(_("%s: no such path in the working tree.\n"
204 "Use 'git <command> -- <path>...' to specify paths that do not exist locally."),
205 arg);
207 * Saying "'(icase)foo' does not exist in the index" when the
208 * user gave us ":(icase)foo" is just stupid. A magic pathspec
209 * begins with a colon and is followed by a non-alnum; do not
210 * let maybe_die_on_misspelt_object_name() even trigger.
212 if (!(arg[0] == ':' && !isalnum(arg[1])))
213 maybe_die_on_misspelt_object_name(r, arg, prefix);
215 /* ... or fall back the most general message. */
216 die(_("ambiguous argument '%s': unknown revision or path not in the working tree.\n"
217 "Use '--' to separate paths from revisions, like this:\n"
218 "'git <command> [<revision>...] -- [<file>...]'"), arg);
223 * Check for arguments that don't resolve as actual files,
224 * but which look sufficiently like pathspecs that we'll consider
225 * them such for the purposes of rev/pathspec DWIM parsing.
227 static int looks_like_pathspec(const char *arg)
229 const char *p;
230 int escaped = 0;
233 * Wildcard characters imply the user is looking to match pathspecs
234 * that aren't in the filesystem. Note that this doesn't include
235 * backslash even though it's a glob special; by itself it doesn't
236 * cause any increase in the match. Likewise ignore backslash-escaped
237 * wildcard characters.
239 for (p = arg; *p; p++) {
240 if (escaped) {
241 escaped = 0;
242 } else if (is_glob_special(*p)) {
243 if (*p == '\\')
244 escaped = 1;
245 else
246 return 1;
250 /* long-form pathspec magic */
251 if (starts_with(arg, ":("))
252 return 1;
254 return 0;
258 * Verify a filename that we got as an argument for a pathspec
259 * entry. Note that a filename that begins with "-" never verifies
260 * as true, because even if such a filename were to exist, we want
261 * it to be preceded by the "--" marker (or we want the user to
262 * use a format like "./-filename")
264 * The "diagnose_misspelt_rev" is used to provide a user-friendly
265 * diagnosis when dying upon finding that "name" is not a pathname.
266 * If set to 1, the diagnosis will try to diagnose "name" as an
267 * invalid object name (e.g. HEAD:foo). If set to 0, the diagnosis
268 * will only complain about an inexisting file.
270 * This function is typically called to check that a "file or rev"
271 * argument is unambiguous. In this case, the caller will want
272 * diagnose_misspelt_rev == 1 when verifying the first non-rev
273 * argument (which could have been a revision), and
274 * diagnose_misspelt_rev == 0 for the next ones (because we already
275 * saw a filename, there's not ambiguity anymore).
277 void verify_filename(const char *prefix,
278 const char *arg,
279 int diagnose_misspelt_rev)
281 if (*arg == '-')
282 die(_("option '%s' must come before non-option arguments"), arg);
283 if (looks_like_pathspec(arg) || check_filename(prefix, arg))
284 return;
285 die_verify_filename(the_repository, prefix, arg, diagnose_misspelt_rev);
289 * Opposite of the above: the command line did not have -- marker
290 * and we parsed the arg as a refname. It should not be interpretable
291 * as a filename.
293 void verify_non_filename(const char *prefix, const char *arg)
295 if (!is_inside_work_tree() || is_inside_git_dir())
296 return;
297 if (*arg == '-')
298 return; /* flag */
299 if (!check_filename(prefix, arg))
300 return;
301 die(_("ambiguous argument '%s': both revision and filename\n"
302 "Use '--' to separate paths from revisions, like this:\n"
303 "'git <command> [<revision>...] -- [<file>...]'"), arg);
306 int get_common_dir(struct strbuf *sb, const char *gitdir)
308 const char *git_env_common_dir = getenv(GIT_COMMON_DIR_ENVIRONMENT);
309 if (git_env_common_dir) {
310 strbuf_addstr(sb, git_env_common_dir);
311 return 1;
312 } else {
313 return get_common_dir_noenv(sb, gitdir);
317 int get_common_dir_noenv(struct strbuf *sb, const char *gitdir)
319 struct strbuf data = STRBUF_INIT;
320 struct strbuf path = STRBUF_INIT;
321 int ret = 0;
323 strbuf_addf(&path, "%s/commondir", gitdir);
324 if (file_exists(path.buf)) {
325 if (strbuf_read_file(&data, path.buf, 0) <= 0)
326 die_errno(_("failed to read %s"), path.buf);
327 while (data.len && (data.buf[data.len - 1] == '\n' ||
328 data.buf[data.len - 1] == '\r'))
329 data.len--;
330 data.buf[data.len] = '\0';
331 strbuf_reset(&path);
332 if (!is_absolute_path(data.buf))
333 strbuf_addf(&path, "%s/", gitdir);
334 strbuf_addbuf(&path, &data);
335 strbuf_add_real_path(sb, path.buf);
336 ret = 1;
337 } else {
338 strbuf_addstr(sb, gitdir);
341 strbuf_release(&data);
342 strbuf_release(&path);
343 return ret;
346 static int validate_headref(const char *path)
348 struct stat st;
349 char buffer[256];
350 const char *refname;
351 struct object_id oid;
352 int fd;
353 ssize_t len;
355 if (lstat(path, &st) < 0)
356 return -1;
358 /* Make sure it is a "refs/.." symlink */
359 if (S_ISLNK(st.st_mode)) {
360 len = readlink(path, buffer, sizeof(buffer)-1);
361 if (len >= 5 && !memcmp("refs/", buffer, 5))
362 return 0;
363 return -1;
367 * Anything else, just open it and try to see if it is a symbolic ref.
369 fd = open(path, O_RDONLY);
370 if (fd < 0)
371 return -1;
372 len = read_in_full(fd, buffer, sizeof(buffer)-1);
373 close(fd);
375 if (len < 0)
376 return -1;
377 buffer[len] = '\0';
380 * Is it a symbolic ref?
382 if (skip_prefix(buffer, "ref:", &refname)) {
383 while (isspace(*refname))
384 refname++;
385 if (starts_with(refname, "refs/"))
386 return 0;
390 * Is this a detached HEAD?
392 if (get_oid_hex_any(buffer, &oid) != GIT_HASH_UNKNOWN)
393 return 0;
395 return -1;
399 * Test if it looks like we're at a git directory.
400 * We want to see:
402 * - either an objects/ directory _or_ the proper
403 * GIT_OBJECT_DIRECTORY environment variable
404 * - a refs/ directory
405 * - either a HEAD symlink or a HEAD file that is formatted as
406 * a proper "ref:", or a regular file HEAD that has a properly
407 * formatted sha1 object name.
409 int is_git_directory(const char *suspect)
411 struct strbuf path = STRBUF_INIT;
412 int ret = 0;
413 size_t len;
415 /* Check worktree-related signatures */
416 strbuf_addstr(&path, suspect);
417 strbuf_complete(&path, '/');
418 strbuf_addstr(&path, "HEAD");
419 if (validate_headref(path.buf))
420 goto done;
422 strbuf_reset(&path);
423 get_common_dir(&path, suspect);
424 len = path.len;
426 /* Check non-worktree-related signatures */
427 if (getenv(DB_ENVIRONMENT)) {
428 if (access(getenv(DB_ENVIRONMENT), X_OK))
429 goto done;
431 else {
432 strbuf_setlen(&path, len);
433 strbuf_addstr(&path, "/objects");
434 if (access(path.buf, X_OK))
435 goto done;
438 strbuf_setlen(&path, len);
439 strbuf_addstr(&path, "/refs");
440 if (access(path.buf, X_OK))
441 goto done;
443 ret = 1;
444 done:
445 strbuf_release(&path);
446 return ret;
449 int is_nonbare_repository_dir(struct strbuf *path)
451 int ret = 0;
452 int gitfile_error;
453 size_t orig_path_len = path->len;
454 assert(orig_path_len != 0);
455 strbuf_complete(path, '/');
456 strbuf_addstr(path, ".git");
457 if (read_gitfile_gently(path->buf, &gitfile_error) || is_git_directory(path->buf))
458 ret = 1;
459 if (gitfile_error == READ_GITFILE_ERR_OPEN_FAILED ||
460 gitfile_error == READ_GITFILE_ERR_READ_FAILED)
461 ret = 1;
462 strbuf_setlen(path, orig_path_len);
463 return ret;
466 int is_inside_git_dir(void)
468 if (inside_git_dir < 0)
469 inside_git_dir = is_inside_dir(get_git_dir());
470 return inside_git_dir;
473 int is_inside_work_tree(void)
475 if (inside_work_tree < 0)
476 inside_work_tree = is_inside_dir(get_git_work_tree());
477 return inside_work_tree;
480 void setup_work_tree(void)
482 const char *work_tree;
483 static int initialized = 0;
485 if (initialized)
486 return;
488 if (work_tree_config_is_bogus)
489 die(_("unable to set up work tree using invalid config"));
491 work_tree = get_git_work_tree();
492 if (!work_tree || chdir_notify(work_tree))
493 die(_("this operation must be run in a work tree"));
496 * Make sure subsequent git processes find correct worktree
497 * if $GIT_WORK_TREE is set relative
499 if (getenv(GIT_WORK_TREE_ENVIRONMENT))
500 setenv(GIT_WORK_TREE_ENVIRONMENT, ".", 1);
502 initialized = 1;
505 static void setup_original_cwd(void)
507 struct strbuf tmp = STRBUF_INIT;
508 const char *worktree = NULL;
509 int offset = -1;
511 if (!tmp_original_cwd)
512 return;
515 * startup_info->original_cwd points to the current working
516 * directory we inherited from our parent process, which is a
517 * directory we want to avoid removing.
519 * For convience, we would like to have the path relative to the
520 * worktree instead of an absolute path.
522 * Yes, startup_info->original_cwd is usually the same as 'prefix',
523 * but differs in two ways:
524 * - prefix has a trailing '/'
525 * - if the user passes '-C' to git, that modifies the prefix but
526 * not startup_info->original_cwd.
529 /* Normalize the directory */
530 if (!strbuf_realpath(&tmp, tmp_original_cwd, 0)) {
531 trace2_data_string("setup", the_repository,
532 "realpath-path", tmp_original_cwd);
533 trace2_data_string("setup", the_repository,
534 "realpath-failure", strerror(errno));
535 free((char*)tmp_original_cwd);
536 tmp_original_cwd = NULL;
537 return;
540 free((char*)tmp_original_cwd);
541 tmp_original_cwd = NULL;
542 startup_info->original_cwd = strbuf_detach(&tmp, NULL);
545 * Get our worktree; we only protect the current working directory
546 * if it's in the worktree.
548 worktree = get_git_work_tree();
549 if (!worktree)
550 goto no_prevention_needed;
552 offset = dir_inside_of(startup_info->original_cwd, worktree);
553 if (offset >= 0) {
555 * If startup_info->original_cwd == worktree, that is already
556 * protected and we don't need original_cwd as a secondary
557 * protection measure.
559 if (!*(startup_info->original_cwd + offset))
560 goto no_prevention_needed;
563 * original_cwd was inside worktree; precompose it just as
564 * we do prefix so that built up paths will match
566 startup_info->original_cwd = \
567 precompose_string_if_needed(startup_info->original_cwd
568 + offset);
569 return;
572 no_prevention_needed:
573 free((char*)startup_info->original_cwd);
574 startup_info->original_cwd = NULL;
577 static int read_worktree_config(const char *var, const char *value,
578 const struct config_context *ctx UNUSED,
579 void *vdata)
581 struct repository_format *data = vdata;
583 if (strcmp(var, "core.bare") == 0) {
584 data->is_bare = git_config_bool(var, value);
585 } else if (strcmp(var, "core.worktree") == 0) {
586 if (!value)
587 return config_error_nonbool(var);
588 free(data->work_tree);
589 data->work_tree = xstrdup(value);
591 return 0;
594 enum extension_result {
595 EXTENSION_ERROR = -1, /* compatible with error(), etc */
596 EXTENSION_UNKNOWN = 0,
597 EXTENSION_OK = 1
601 * Do not add new extensions to this function. It handles extensions which are
602 * respected even in v0-format repositories for historical compatibility.
604 static enum extension_result handle_extension_v0(const char *var,
605 const char *value,
606 const char *ext,
607 struct repository_format *data)
609 if (!strcmp(ext, "noop")) {
610 return EXTENSION_OK;
611 } else if (!strcmp(ext, "preciousobjects")) {
612 data->precious_objects = git_config_bool(var, value);
613 return EXTENSION_OK;
614 } else if (!strcmp(ext, "partialclone")) {
615 if (!value)
616 return config_error_nonbool(var);
617 data->partial_clone = xstrdup(value);
618 return EXTENSION_OK;
619 } else if (!strcmp(ext, "worktreeconfig")) {
620 data->worktree_config = git_config_bool(var, value);
621 return EXTENSION_OK;
624 return EXTENSION_UNKNOWN;
628 * Record any new extensions in this function.
630 static enum extension_result handle_extension(const char *var,
631 const char *value,
632 const char *ext,
633 struct repository_format *data)
635 if (!strcmp(ext, "noop-v1")) {
636 return EXTENSION_OK;
637 } else if (!strcmp(ext, "objectformat")) {
638 int format;
640 if (!value)
641 return config_error_nonbool(var);
642 format = hash_algo_by_name(value);
643 if (format == GIT_HASH_UNKNOWN)
644 return error(_("invalid value for '%s': '%s'"),
645 "extensions.objectformat", value);
646 data->hash_algo = format;
647 return EXTENSION_OK;
648 } else if (!strcmp(ext, "compatobjectformat")) {
649 struct string_list_item *item;
650 int format;
652 if (!value)
653 return config_error_nonbool(var);
654 format = hash_algo_by_name(value);
655 if (format == GIT_HASH_UNKNOWN)
656 return error(_("invalid value for '%s': '%s'"),
657 "extensions.compatobjectformat", value);
658 /* For now only support compatObjectFormat being specified once. */
659 for_each_string_list_item(item, &data->v1_only_extensions) {
660 if (!strcmp(item->string, "compatobjectformat"))
661 return error(_("'%s' already specified as '%s'"),
662 "extensions.compatobjectformat",
663 hash_algos[data->compat_hash_algo].name);
665 data->compat_hash_algo = format;
666 return EXTENSION_OK;
667 } else if (!strcmp(ext, "refstorage")) {
668 unsigned int format;
670 if (!value)
671 return config_error_nonbool(var);
672 format = ref_storage_format_by_name(value);
673 if (format == REF_STORAGE_FORMAT_UNKNOWN)
674 return error(_("invalid value for '%s': '%s'"),
675 "extensions.refstorage", value);
676 data->ref_storage_format = format;
677 return EXTENSION_OK;
679 return EXTENSION_UNKNOWN;
682 static int check_repo_format(const char *var, const char *value,
683 const struct config_context *ctx, void *vdata)
685 struct repository_format *data = vdata;
686 const char *ext;
688 if (strcmp(var, "core.repositoryformatversion") == 0)
689 data->version = git_config_int(var, value, ctx->kvi);
690 else if (skip_prefix(var, "extensions.", &ext)) {
691 switch (handle_extension_v0(var, value, ext, data)) {
692 case EXTENSION_ERROR:
693 return -1;
694 case EXTENSION_OK:
695 return 0;
696 case EXTENSION_UNKNOWN:
697 break;
700 switch (handle_extension(var, value, ext, data)) {
701 case EXTENSION_ERROR:
702 return -1;
703 case EXTENSION_OK:
704 string_list_append(&data->v1_only_extensions, ext);
705 return 0;
706 case EXTENSION_UNKNOWN:
707 string_list_append(&data->unknown_extensions, ext);
708 return 0;
712 return read_worktree_config(var, value, ctx, vdata);
715 static int check_repository_format_gently(const char *gitdir, struct repository_format *candidate, int *nongit_ok)
717 struct strbuf sb = STRBUF_INIT;
718 struct strbuf err = STRBUF_INIT;
719 int has_common;
721 has_common = get_common_dir(&sb, gitdir);
722 strbuf_addstr(&sb, "/config");
723 read_repository_format(candidate, sb.buf);
724 strbuf_release(&sb);
727 * For historical use of check_repository_format() in git-init,
728 * we treat a missing config as a silent "ok", even when nongit_ok
729 * is unset.
731 if (candidate->version < 0)
732 return 0;
734 if (verify_repository_format(candidate, &err) < 0) {
735 if (nongit_ok) {
736 warning("%s", err.buf);
737 strbuf_release(&err);
738 *nongit_ok = -1;
739 return -1;
741 die("%s", err.buf);
744 repository_format_precious_objects = candidate->precious_objects;
745 string_list_clear(&candidate->unknown_extensions, 0);
746 string_list_clear(&candidate->v1_only_extensions, 0);
748 if (candidate->worktree_config) {
750 * pick up core.bare and core.worktree from per-worktree
751 * config if present
753 strbuf_addf(&sb, "%s/config.worktree", gitdir);
754 git_config_from_file(read_worktree_config, sb.buf, candidate);
755 strbuf_release(&sb);
756 has_common = 0;
759 if (!has_common) {
760 if (candidate->is_bare != -1) {
761 is_bare_repository_cfg = candidate->is_bare;
762 if (is_bare_repository_cfg == 1)
763 inside_work_tree = -1;
765 if (candidate->work_tree) {
766 free(git_work_tree_cfg);
767 git_work_tree_cfg = xstrdup(candidate->work_tree);
768 inside_work_tree = -1;
772 return 0;
775 int upgrade_repository_format(int target_version)
777 struct strbuf sb = STRBUF_INIT;
778 struct strbuf err = STRBUF_INIT;
779 struct strbuf repo_version = STRBUF_INIT;
780 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
781 int ret;
783 strbuf_git_common_path(&sb, the_repository, "config");
784 read_repository_format(&repo_fmt, sb.buf);
785 strbuf_release(&sb);
787 if (repo_fmt.version >= target_version) {
788 ret = 0;
789 goto out;
792 if (verify_repository_format(&repo_fmt, &err) < 0) {
793 ret = error("cannot upgrade repository format from %d to %d: %s",
794 repo_fmt.version, target_version, err.buf);
795 goto out;
797 if (!repo_fmt.version && repo_fmt.unknown_extensions.nr) {
798 ret = error("cannot upgrade repository format: "
799 "unknown extension %s",
800 repo_fmt.unknown_extensions.items[0].string);
801 goto out;
804 strbuf_addf(&repo_version, "%d", target_version);
805 git_config_set("core.repositoryformatversion", repo_version.buf);
807 ret = 1;
809 out:
810 clear_repository_format(&repo_fmt);
811 strbuf_release(&repo_version);
812 strbuf_release(&err);
813 return ret;
816 static void init_repository_format(struct repository_format *format)
818 const struct repository_format fresh = REPOSITORY_FORMAT_INIT;
820 memcpy(format, &fresh, sizeof(fresh));
823 int read_repository_format(struct repository_format *format, const char *path)
825 clear_repository_format(format);
826 git_config_from_file(check_repo_format, path, format);
827 if (format->version == -1)
828 clear_repository_format(format);
829 return format->version;
832 void clear_repository_format(struct repository_format *format)
834 string_list_clear(&format->unknown_extensions, 0);
835 string_list_clear(&format->v1_only_extensions, 0);
836 free(format->work_tree);
837 free(format->partial_clone);
838 init_repository_format(format);
841 int verify_repository_format(const struct repository_format *format,
842 struct strbuf *err)
844 if (GIT_REPO_VERSION_READ < format->version) {
845 strbuf_addf(err, _("Expected git repo version <= %d, found %d"),
846 GIT_REPO_VERSION_READ, format->version);
847 return -1;
850 if (format->version >= 1 && format->unknown_extensions.nr) {
851 int i;
853 strbuf_addstr(err, Q_("unknown repository extension found:",
854 "unknown repository extensions found:",
855 format->unknown_extensions.nr));
857 for (i = 0; i < format->unknown_extensions.nr; i++)
858 strbuf_addf(err, "\n\t%s",
859 format->unknown_extensions.items[i].string);
860 return -1;
863 if (format->version == 0 && format->v1_only_extensions.nr) {
864 int i;
866 strbuf_addstr(err,
867 Q_("repo version is 0, but v1-only extension found:",
868 "repo version is 0, but v1-only extensions found:",
869 format->v1_only_extensions.nr));
871 for (i = 0; i < format->v1_only_extensions.nr; i++)
872 strbuf_addf(err, "\n\t%s",
873 format->v1_only_extensions.items[i].string);
874 return -1;
877 return 0;
880 void read_gitfile_error_die(int error_code, const char *path, const char *dir)
882 switch (error_code) {
883 case READ_GITFILE_ERR_STAT_FAILED:
884 case READ_GITFILE_ERR_NOT_A_FILE:
885 /* non-fatal; follow return path */
886 break;
887 case READ_GITFILE_ERR_OPEN_FAILED:
888 die_errno(_("error opening '%s'"), path);
889 case READ_GITFILE_ERR_TOO_LARGE:
890 die(_("too large to be a .git file: '%s'"), path);
891 case READ_GITFILE_ERR_READ_FAILED:
892 die(_("error reading %s"), path);
893 case READ_GITFILE_ERR_INVALID_FORMAT:
894 die(_("invalid gitfile format: %s"), path);
895 case READ_GITFILE_ERR_NO_PATH:
896 die(_("no path in gitfile: %s"), path);
897 case READ_GITFILE_ERR_NOT_A_REPO:
898 die(_("not a git repository: %s"), dir);
899 default:
900 BUG("unknown error code");
905 * Try to read the location of the git directory from the .git file,
906 * return path to git directory if found. The return value comes from
907 * a shared buffer.
909 * On failure, if return_error_code is not NULL, return_error_code
910 * will be set to an error code and NULL will be returned. If
911 * return_error_code is NULL the function will die instead (for most
912 * cases).
914 const char *read_gitfile_gently(const char *path, int *return_error_code)
916 const int max_file_size = 1 << 20; /* 1MB */
917 int error_code = 0;
918 char *buf = NULL;
919 char *dir = NULL;
920 const char *slash;
921 struct stat st;
922 int fd;
923 ssize_t len;
924 static struct strbuf realpath = STRBUF_INIT;
926 if (stat(path, &st)) {
927 /* NEEDSWORK: discern between ENOENT vs other errors */
928 error_code = READ_GITFILE_ERR_STAT_FAILED;
929 goto cleanup_return;
931 if (!S_ISREG(st.st_mode)) {
932 error_code = READ_GITFILE_ERR_NOT_A_FILE;
933 goto cleanup_return;
935 if (st.st_size > max_file_size) {
936 error_code = READ_GITFILE_ERR_TOO_LARGE;
937 goto cleanup_return;
939 fd = open(path, O_RDONLY);
940 if (fd < 0) {
941 error_code = READ_GITFILE_ERR_OPEN_FAILED;
942 goto cleanup_return;
944 buf = xmallocz(st.st_size);
945 len = read_in_full(fd, buf, st.st_size);
946 close(fd);
947 if (len != st.st_size) {
948 error_code = READ_GITFILE_ERR_READ_FAILED;
949 goto cleanup_return;
951 if (!starts_with(buf, "gitdir: ")) {
952 error_code = READ_GITFILE_ERR_INVALID_FORMAT;
953 goto cleanup_return;
955 while (buf[len - 1] == '\n' || buf[len - 1] == '\r')
956 len--;
957 if (len < 9) {
958 error_code = READ_GITFILE_ERR_NO_PATH;
959 goto cleanup_return;
961 buf[len] = '\0';
962 dir = buf + 8;
964 if (!is_absolute_path(dir) && (slash = strrchr(path, '/'))) {
965 size_t pathlen = slash+1 - path;
966 dir = xstrfmt("%.*s%.*s", (int)pathlen, path,
967 (int)(len - 8), buf + 8);
968 free(buf);
969 buf = dir;
971 if (!is_git_directory(dir)) {
972 error_code = READ_GITFILE_ERR_NOT_A_REPO;
973 goto cleanup_return;
976 strbuf_realpath(&realpath, dir, 1);
977 path = realpath.buf;
979 cleanup_return:
980 if (return_error_code)
981 *return_error_code = error_code;
982 else if (error_code)
983 read_gitfile_error_die(error_code, path, dir);
985 free(buf);
986 return error_code ? NULL : path;
989 static const char *setup_explicit_git_dir(const char *gitdirenv,
990 struct strbuf *cwd,
991 struct repository_format *repo_fmt,
992 int *nongit_ok)
994 const char *work_tree_env = getenv(GIT_WORK_TREE_ENVIRONMENT);
995 const char *worktree;
996 char *gitfile;
997 int offset;
999 if (PATH_MAX - 40 < strlen(gitdirenv))
1000 die(_("'$%s' too big"), GIT_DIR_ENVIRONMENT);
1002 gitfile = (char*)read_gitfile(gitdirenv);
1003 if (gitfile) {
1004 gitfile = xstrdup(gitfile);
1005 gitdirenv = gitfile;
1008 if (!is_git_directory(gitdirenv)) {
1009 if (nongit_ok) {
1010 *nongit_ok = 1;
1011 free(gitfile);
1012 return NULL;
1014 die(_("not a git repository: '%s'"), gitdirenv);
1017 if (check_repository_format_gently(gitdirenv, repo_fmt, nongit_ok)) {
1018 free(gitfile);
1019 return NULL;
1022 /* #3, #7, #11, #15, #19, #23, #27, #31 (see t1510) */
1023 if (work_tree_env)
1024 set_git_work_tree(work_tree_env);
1025 else if (is_bare_repository_cfg > 0) {
1026 if (git_work_tree_cfg) {
1027 /* #22.2, #30 */
1028 warning("core.bare and core.worktree do not make sense");
1029 work_tree_config_is_bogus = 1;
1032 /* #18, #26 */
1033 set_git_dir(gitdirenv, 0);
1034 free(gitfile);
1035 return NULL;
1037 else if (git_work_tree_cfg) { /* #6, #14 */
1038 if (is_absolute_path(git_work_tree_cfg))
1039 set_git_work_tree(git_work_tree_cfg);
1040 else {
1041 char *core_worktree;
1042 if (chdir(gitdirenv))
1043 die_errno(_("cannot chdir to '%s'"), gitdirenv);
1044 if (chdir(git_work_tree_cfg))
1045 die_errno(_("cannot chdir to '%s'"), git_work_tree_cfg);
1046 core_worktree = xgetcwd();
1047 if (chdir(cwd->buf))
1048 die_errno(_("cannot come back to cwd"));
1049 set_git_work_tree(core_worktree);
1050 free(core_worktree);
1053 else if (!git_env_bool(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, 1)) {
1054 /* #16d */
1055 set_git_dir(gitdirenv, 0);
1056 free(gitfile);
1057 return NULL;
1059 else /* #2, #10 */
1060 set_git_work_tree(".");
1062 /* set_git_work_tree() must have been called by now */
1063 worktree = get_git_work_tree();
1065 /* both get_git_work_tree() and cwd are already normalized */
1066 if (!strcmp(cwd->buf, worktree)) { /* cwd == worktree */
1067 set_git_dir(gitdirenv, 0);
1068 free(gitfile);
1069 return NULL;
1072 offset = dir_inside_of(cwd->buf, worktree);
1073 if (offset >= 0) { /* cwd inside worktree? */
1074 set_git_dir(gitdirenv, 1);
1075 if (chdir(worktree))
1076 die_errno(_("cannot chdir to '%s'"), worktree);
1077 strbuf_addch(cwd, '/');
1078 free(gitfile);
1079 return cwd->buf + offset;
1082 /* cwd outside worktree */
1083 set_git_dir(gitdirenv, 0);
1084 free(gitfile);
1085 return NULL;
1088 static const char *setup_discovered_git_dir(const char *gitdir,
1089 struct strbuf *cwd, int offset,
1090 struct repository_format *repo_fmt,
1091 int *nongit_ok)
1093 if (check_repository_format_gently(gitdir, repo_fmt, nongit_ok))
1094 return NULL;
1096 /* --work-tree is set without --git-dir; use discovered one */
1097 if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
1098 char *to_free = NULL;
1099 const char *ret;
1101 if (offset != cwd->len && !is_absolute_path(gitdir))
1102 gitdir = to_free = real_pathdup(gitdir, 1);
1103 if (chdir(cwd->buf))
1104 die_errno(_("cannot come back to cwd"));
1105 ret = setup_explicit_git_dir(gitdir, cwd, repo_fmt, nongit_ok);
1106 free(to_free);
1107 return ret;
1110 /* #16.2, #17.2, #20.2, #21.2, #24, #25, #28, #29 (see t1510) */
1111 if (is_bare_repository_cfg > 0) {
1112 set_git_dir(gitdir, (offset != cwd->len));
1113 if (chdir(cwd->buf))
1114 die_errno(_("cannot come back to cwd"));
1115 return NULL;
1118 /* #0, #1, #5, #8, #9, #12, #13 */
1119 set_git_work_tree(".");
1120 if (strcmp(gitdir, DEFAULT_GIT_DIR_ENVIRONMENT))
1121 set_git_dir(gitdir, 0);
1122 inside_git_dir = 0;
1123 inside_work_tree = 1;
1124 if (offset >= cwd->len)
1125 return NULL;
1127 /* Make "offset" point past the '/' (already the case for root dirs) */
1128 if (offset != offset_1st_component(cwd->buf))
1129 offset++;
1130 /* Add a '/' at the end */
1131 strbuf_addch(cwd, '/');
1132 return cwd->buf + offset;
1135 /* #16.1, #17.1, #20.1, #21.1, #22.1 (see t1510) */
1136 static const char *setup_bare_git_dir(struct strbuf *cwd, int offset,
1137 struct repository_format *repo_fmt,
1138 int *nongit_ok)
1140 int root_len;
1142 if (check_repository_format_gently(".", repo_fmt, nongit_ok))
1143 return NULL;
1145 setenv(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, "0", 1);
1147 /* --work-tree is set without --git-dir; use discovered one */
1148 if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
1149 static const char *gitdir;
1151 gitdir = offset == cwd->len ? "." : xmemdupz(cwd->buf, offset);
1152 if (chdir(cwd->buf))
1153 die_errno(_("cannot come back to cwd"));
1154 return setup_explicit_git_dir(gitdir, cwd, repo_fmt, nongit_ok);
1157 inside_git_dir = 1;
1158 inside_work_tree = 0;
1159 if (offset != cwd->len) {
1160 if (chdir(cwd->buf))
1161 die_errno(_("cannot come back to cwd"));
1162 root_len = offset_1st_component(cwd->buf);
1163 strbuf_setlen(cwd, offset > root_len ? offset : root_len);
1164 set_git_dir(cwd->buf, 0);
1166 else
1167 set_git_dir(".", 0);
1168 return NULL;
1171 static dev_t get_device_or_die(const char *path, const char *prefix, int prefix_len)
1173 struct stat buf;
1174 if (stat(path, &buf)) {
1175 die_errno(_("failed to stat '%*s%s%s'"),
1176 prefix_len,
1177 prefix ? prefix : "",
1178 prefix ? "/" : "", path);
1180 return buf.st_dev;
1184 * A "string_list_each_func_t" function that canonicalizes an entry
1185 * from GIT_CEILING_DIRECTORIES using real_pathdup(), or
1186 * discards it if unusable. The presence of an empty entry in
1187 * GIT_CEILING_DIRECTORIES turns off canonicalization for all
1188 * subsequent entries.
1190 static int canonicalize_ceiling_entry(struct string_list_item *item,
1191 void *cb_data)
1193 int *empty_entry_found = cb_data;
1194 char *ceil = item->string;
1196 if (!*ceil) {
1197 *empty_entry_found = 1;
1198 return 0;
1199 } else if (!is_absolute_path(ceil)) {
1200 return 0;
1201 } else if (*empty_entry_found) {
1202 /* Keep entry but do not canonicalize it */
1203 return 1;
1204 } else {
1205 char *real_path = real_pathdup(ceil, 0);
1206 if (!real_path) {
1207 return 0;
1209 free(item->string);
1210 item->string = real_path;
1211 return 1;
1215 struct safe_directory_data {
1216 const char *path;
1217 int is_safe;
1220 static int safe_directory_cb(const char *key, const char *value,
1221 const struct config_context *ctx UNUSED, void *d)
1223 struct safe_directory_data *data = d;
1225 if (strcmp(key, "safe.directory"))
1226 return 0;
1228 if (!value || !*value) {
1229 data->is_safe = 0;
1230 } else if (!strcmp(value, "*")) {
1231 data->is_safe = 1;
1232 } else {
1233 const char *interpolated = NULL;
1235 if (!git_config_pathname(&interpolated, key, value) &&
1236 !fspathcmp(data->path, interpolated ? interpolated : value))
1237 data->is_safe = 1;
1239 free((char *)interpolated);
1242 return 0;
1246 * Check if a repository is safe, by verifying the ownership of the
1247 * worktree (if any), the git directory, and the gitfile (if any).
1249 * Exemptions for known-safe repositories can be added via `safe.directory`
1250 * config settings; for non-bare repositories, their worktree needs to be
1251 * added, for bare ones their git directory.
1253 static int ensure_valid_ownership(const char *gitfile,
1254 const char *worktree, const char *gitdir,
1255 struct strbuf *report)
1257 struct safe_directory_data data = {
1258 .path = worktree ? worktree : gitdir
1261 if (!git_env_bool("GIT_TEST_ASSUME_DIFFERENT_OWNER", 0) &&
1262 (!gitfile || is_path_owned_by_current_user(gitfile, report)) &&
1263 (!worktree || is_path_owned_by_current_user(worktree, report)) &&
1264 (!gitdir || is_path_owned_by_current_user(gitdir, report)))
1265 return 1;
1268 * data.path is the "path" that identifies the repository and it is
1269 * constant regardless of what failed above. data.is_safe should be
1270 * initialized to false, and might be changed by the callback.
1272 git_protected_config(safe_directory_cb, &data);
1274 return data.is_safe;
1277 void die_upon_dubious_ownership(const char *gitfile, const char *worktree,
1278 const char *gitdir)
1280 struct strbuf report = STRBUF_INIT, quoted = STRBUF_INIT;
1281 const char *path;
1283 if (ensure_valid_ownership(gitfile, worktree, gitdir, &report))
1284 return;
1286 strbuf_complete(&report, '\n');
1287 path = gitfile ? gitfile : gitdir;
1288 sq_quote_buf_pretty(&quoted, path);
1290 die(_("detected dubious ownership in repository at '%s'\n"
1291 "%s"
1292 "To add an exception for this directory, call:\n"
1293 "\n"
1294 "\tgit config --global --add safe.directory %s"),
1295 path, report.buf, quoted.buf);
1298 static int allowed_bare_repo_cb(const char *key, const char *value,
1299 const struct config_context *ctx UNUSED,
1300 void *d)
1302 enum allowed_bare_repo *allowed_bare_repo = d;
1304 if (strcasecmp(key, "safe.bareRepository"))
1305 return 0;
1307 if (!strcmp(value, "explicit")) {
1308 *allowed_bare_repo = ALLOWED_BARE_REPO_EXPLICIT;
1309 return 0;
1311 if (!strcmp(value, "all")) {
1312 *allowed_bare_repo = ALLOWED_BARE_REPO_ALL;
1313 return 0;
1315 return -1;
1318 static enum allowed_bare_repo get_allowed_bare_repo(void)
1320 enum allowed_bare_repo result = ALLOWED_BARE_REPO_ALL;
1321 git_protected_config(allowed_bare_repo_cb, &result);
1322 return result;
1325 static const char *allowed_bare_repo_to_string(
1326 enum allowed_bare_repo allowed_bare_repo)
1328 switch (allowed_bare_repo) {
1329 case ALLOWED_BARE_REPO_EXPLICIT:
1330 return "explicit";
1331 case ALLOWED_BARE_REPO_ALL:
1332 return "all";
1333 default:
1334 BUG("invalid allowed_bare_repo %d",
1335 allowed_bare_repo);
1337 return NULL;
1340 static int is_implicit_bare_repo(const char *path)
1343 * what we found is a ".git" directory at the root of
1344 * the working tree.
1346 if (ends_with_path_components(path, ".git"))
1347 return 1;
1350 * we are inside $GIT_DIR of a secondary worktree of a
1351 * non-bare repository.
1353 if (strstr(path, "/.git/worktrees/"))
1354 return 1;
1357 * we are inside $GIT_DIR of a worktree of a non-embedded
1358 * submodule, whose superproject is not a bare repository.
1360 if (strstr(path, "/.git/modules/"))
1361 return 1;
1363 return 0;
1367 * We cannot decide in this function whether we are in the work tree or
1368 * not, since the config can only be read _after_ this function was called.
1370 * Also, we avoid changing any global state (such as the current working
1371 * directory) to allow early callers.
1373 * The directory where the search should start needs to be passed in via the
1374 * `dir` parameter; upon return, the `dir` buffer will contain the path of
1375 * the directory where the search ended, and `gitdir` will contain the path of
1376 * the discovered .git/ directory, if any. If `gitdir` is not absolute, it
1377 * is relative to `dir` (i.e. *not* necessarily the cwd).
1379 static enum discovery_result setup_git_directory_gently_1(struct strbuf *dir,
1380 struct strbuf *gitdir,
1381 struct strbuf *report,
1382 int die_on_error)
1384 const char *env_ceiling_dirs = getenv(CEILING_DIRECTORIES_ENVIRONMENT);
1385 struct string_list ceiling_dirs = STRING_LIST_INIT_DUP;
1386 const char *gitdirenv;
1387 int ceil_offset = -1, min_offset = offset_1st_component(dir->buf);
1388 dev_t current_device = 0;
1389 int one_filesystem = 1;
1392 * If GIT_DIR is set explicitly, we're not going
1393 * to do any discovery, but we still do repository
1394 * validation.
1396 gitdirenv = getenv(GIT_DIR_ENVIRONMENT);
1397 if (gitdirenv) {
1398 strbuf_addstr(gitdir, gitdirenv);
1399 return GIT_DIR_EXPLICIT;
1402 if (env_ceiling_dirs) {
1403 int empty_entry_found = 0;
1405 string_list_split(&ceiling_dirs, env_ceiling_dirs, PATH_SEP, -1);
1406 filter_string_list(&ceiling_dirs, 0,
1407 canonicalize_ceiling_entry, &empty_entry_found);
1408 ceil_offset = longest_ancestor_length(dir->buf, &ceiling_dirs);
1409 string_list_clear(&ceiling_dirs, 0);
1412 if (ceil_offset < 0)
1413 ceil_offset = min_offset - 2;
1415 if (min_offset && min_offset == dir->len &&
1416 !is_dir_sep(dir->buf[min_offset - 1])) {
1417 strbuf_addch(dir, '/');
1418 min_offset++;
1422 * Test in the following order (relative to the dir):
1423 * - .git (file containing "gitdir: <path>")
1424 * - .git/
1425 * - ./ (bare)
1426 * - ../.git
1427 * - ../.git/
1428 * - ../ (bare)
1429 * - ../../.git
1430 * etc.
1432 one_filesystem = !git_env_bool("GIT_DISCOVERY_ACROSS_FILESYSTEM", 0);
1433 if (one_filesystem)
1434 current_device = get_device_or_die(dir->buf, NULL, 0);
1435 for (;;) {
1436 int offset = dir->len, error_code = 0;
1437 char *gitdir_path = NULL;
1438 char *gitfile = NULL;
1440 if (offset > min_offset)
1441 strbuf_addch(dir, '/');
1442 strbuf_addstr(dir, DEFAULT_GIT_DIR_ENVIRONMENT);
1443 gitdirenv = read_gitfile_gently(dir->buf, die_on_error ?
1444 NULL : &error_code);
1445 if (!gitdirenv) {
1446 if (die_on_error ||
1447 error_code == READ_GITFILE_ERR_NOT_A_FILE) {
1448 /* NEEDSWORK: fail if .git is not file nor dir */
1449 if (is_git_directory(dir->buf)) {
1450 gitdirenv = DEFAULT_GIT_DIR_ENVIRONMENT;
1451 gitdir_path = xstrdup(dir->buf);
1453 } else if (error_code != READ_GITFILE_ERR_STAT_FAILED)
1454 return GIT_DIR_INVALID_GITFILE;
1455 } else
1456 gitfile = xstrdup(dir->buf);
1458 * Earlier, we tentatively added DEFAULT_GIT_DIR_ENVIRONMENT
1459 * to check that directory for a repository.
1460 * Now trim that tentative addition away, because we want to
1461 * focus on the real directory we are in.
1463 strbuf_setlen(dir, offset);
1464 if (gitdirenv) {
1465 enum discovery_result ret;
1466 const char *gitdir_candidate =
1467 gitdir_path ? gitdir_path : gitdirenv;
1469 if (ensure_valid_ownership(gitfile, dir->buf,
1470 gitdir_candidate, report)) {
1471 strbuf_addstr(gitdir, gitdirenv);
1472 ret = GIT_DIR_DISCOVERED;
1473 } else
1474 ret = GIT_DIR_INVALID_OWNERSHIP;
1477 * Earlier, during discovery, we might have allocated
1478 * string copies for gitdir_path or gitfile so make
1479 * sure we don't leak by freeing them now, before
1480 * leaving the loop and function.
1482 * Note: gitdirenv will be non-NULL whenever these are
1483 * allocated, therefore we need not take care of releasing
1484 * them outside of this conditional block.
1486 free(gitdir_path);
1487 free(gitfile);
1489 return ret;
1492 if (is_git_directory(dir->buf)) {
1493 trace2_data_string("setup", NULL, "implicit-bare-repository", dir->buf);
1494 if (get_allowed_bare_repo() == ALLOWED_BARE_REPO_EXPLICIT &&
1495 !is_implicit_bare_repo(dir->buf))
1496 return GIT_DIR_DISALLOWED_BARE;
1497 if (!ensure_valid_ownership(NULL, NULL, dir->buf, report))
1498 return GIT_DIR_INVALID_OWNERSHIP;
1499 strbuf_addstr(gitdir, ".");
1500 return GIT_DIR_BARE;
1503 if (offset <= min_offset)
1504 return GIT_DIR_HIT_CEILING;
1506 while (--offset > ceil_offset && !is_dir_sep(dir->buf[offset]))
1507 ; /* continue */
1508 if (offset <= ceil_offset)
1509 return GIT_DIR_HIT_CEILING;
1511 strbuf_setlen(dir, offset > min_offset ? offset : min_offset);
1512 if (one_filesystem &&
1513 current_device != get_device_or_die(dir->buf, NULL, offset))
1514 return GIT_DIR_HIT_MOUNT_POINT;
1518 enum discovery_result discover_git_directory_reason(struct strbuf *commondir,
1519 struct strbuf *gitdir)
1521 struct strbuf dir = STRBUF_INIT, err = STRBUF_INIT;
1522 size_t gitdir_offset = gitdir->len, cwd_len;
1523 size_t commondir_offset = commondir->len;
1524 struct repository_format candidate = REPOSITORY_FORMAT_INIT;
1525 enum discovery_result result;
1527 if (strbuf_getcwd(&dir))
1528 return GIT_DIR_CWD_FAILURE;
1530 cwd_len = dir.len;
1531 result = setup_git_directory_gently_1(&dir, gitdir, NULL, 0);
1532 if (result <= 0) {
1533 strbuf_release(&dir);
1534 return result;
1538 * The returned gitdir is relative to dir, and if dir does not reflect
1539 * the current working directory, we simply make the gitdir absolute.
1541 if (dir.len < cwd_len && !is_absolute_path(gitdir->buf + gitdir_offset)) {
1542 /* Avoid a trailing "/." */
1543 if (!strcmp(".", gitdir->buf + gitdir_offset))
1544 strbuf_setlen(gitdir, gitdir_offset);
1545 else
1546 strbuf_addch(&dir, '/');
1547 strbuf_insert(gitdir, gitdir_offset, dir.buf, dir.len);
1550 get_common_dir(commondir, gitdir->buf + gitdir_offset);
1552 strbuf_reset(&dir);
1553 strbuf_addf(&dir, "%s/config", commondir->buf + commondir_offset);
1554 read_repository_format(&candidate, dir.buf);
1555 strbuf_release(&dir);
1557 if (verify_repository_format(&candidate, &err) < 0) {
1558 warning("ignoring git dir '%s': %s",
1559 gitdir->buf + gitdir_offset, err.buf);
1560 strbuf_release(&err);
1561 strbuf_setlen(commondir, commondir_offset);
1562 strbuf_setlen(gitdir, gitdir_offset);
1563 clear_repository_format(&candidate);
1564 return GIT_DIR_INVALID_FORMAT;
1567 clear_repository_format(&candidate);
1568 return result;
1571 const char *setup_git_directory_gently(int *nongit_ok)
1573 static struct strbuf cwd = STRBUF_INIT;
1574 struct strbuf dir = STRBUF_INIT, gitdir = STRBUF_INIT, report = STRBUF_INIT;
1575 const char *prefix = NULL;
1576 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
1579 * We may have read an incomplete configuration before
1580 * setting-up the git directory. If so, clear the cache so
1581 * that the next queries to the configuration reload complete
1582 * configuration (including the per-repo config file that we
1583 * ignored previously).
1585 git_config_clear();
1588 * Let's assume that we are in a git repository.
1589 * If it turns out later that we are somewhere else, the value will be
1590 * updated accordingly.
1592 if (nongit_ok)
1593 *nongit_ok = 0;
1595 if (strbuf_getcwd(&cwd))
1596 die_errno(_("Unable to read current working directory"));
1597 strbuf_addbuf(&dir, &cwd);
1599 switch (setup_git_directory_gently_1(&dir, &gitdir, &report, 1)) {
1600 case GIT_DIR_EXPLICIT:
1601 prefix = setup_explicit_git_dir(gitdir.buf, &cwd, &repo_fmt, nongit_ok);
1602 break;
1603 case GIT_DIR_DISCOVERED:
1604 if (dir.len < cwd.len && chdir(dir.buf))
1605 die(_("cannot change to '%s'"), dir.buf);
1606 prefix = setup_discovered_git_dir(gitdir.buf, &cwd, dir.len,
1607 &repo_fmt, nongit_ok);
1608 break;
1609 case GIT_DIR_BARE:
1610 if (dir.len < cwd.len && chdir(dir.buf))
1611 die(_("cannot change to '%s'"), dir.buf);
1612 prefix = setup_bare_git_dir(&cwd, dir.len, &repo_fmt, nongit_ok);
1613 break;
1614 case GIT_DIR_HIT_CEILING:
1615 if (!nongit_ok)
1616 die(_("not a git repository (or any of the parent directories): %s"),
1617 DEFAULT_GIT_DIR_ENVIRONMENT);
1618 *nongit_ok = 1;
1619 break;
1620 case GIT_DIR_HIT_MOUNT_POINT:
1621 if (!nongit_ok)
1622 die(_("not a git repository (or any parent up to mount point %s)\n"
1623 "Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set)."),
1624 dir.buf);
1625 *nongit_ok = 1;
1626 break;
1627 case GIT_DIR_INVALID_OWNERSHIP:
1628 if (!nongit_ok) {
1629 struct strbuf quoted = STRBUF_INIT;
1631 strbuf_complete(&report, '\n');
1632 sq_quote_buf_pretty(&quoted, dir.buf);
1633 die(_("detected dubious ownership in repository at '%s'\n"
1634 "%s"
1635 "To add an exception for this directory, call:\n"
1636 "\n"
1637 "\tgit config --global --add safe.directory %s"),
1638 dir.buf, report.buf, quoted.buf);
1640 *nongit_ok = 1;
1641 break;
1642 case GIT_DIR_DISALLOWED_BARE:
1643 if (!nongit_ok) {
1644 die(_("cannot use bare repository '%s' (safe.bareRepository is '%s')"),
1645 dir.buf,
1646 allowed_bare_repo_to_string(get_allowed_bare_repo()));
1648 *nongit_ok = 1;
1649 break;
1650 case GIT_DIR_CWD_FAILURE:
1651 case GIT_DIR_INVALID_FORMAT:
1653 * As a safeguard against setup_git_directory_gently_1 returning
1654 * these values, fallthrough to BUG. Otherwise it is possible to
1655 * set startup_info->have_repository to 1 when we did nothing to
1656 * find a repository.
1658 default:
1659 BUG("unhandled setup_git_directory_gently_1() result");
1663 * At this point, nongit_ok is stable. If it is non-NULL and points
1664 * to a non-zero value, then this means that we haven't found a
1665 * repository and that the caller expects startup_info to reflect
1666 * this.
1668 * Regardless of the state of nongit_ok, startup_info->prefix and
1669 * the GIT_PREFIX environment variable must always match. For details
1670 * see Documentation/config/alias.txt.
1672 if (nongit_ok && *nongit_ok)
1673 startup_info->have_repository = 0;
1674 else
1675 startup_info->have_repository = 1;
1678 * Not all paths through the setup code will call 'set_git_dir()' (which
1679 * directly sets up the environment) so in order to guarantee that the
1680 * environment is in a consistent state after setup, explicitly setup
1681 * the environment if we have a repository.
1683 * NEEDSWORK: currently we allow bogus GIT_DIR values to be set in some
1684 * code paths so we also need to explicitly setup the environment if
1685 * the user has set GIT_DIR. It may be beneficial to disallow bogus
1686 * GIT_DIR values at some point in the future.
1688 if (/* GIT_DIR_EXPLICIT, GIT_DIR_DISCOVERED, GIT_DIR_BARE */
1689 startup_info->have_repository ||
1690 /* GIT_DIR_EXPLICIT */
1691 getenv(GIT_DIR_ENVIRONMENT)) {
1692 if (!the_repository->gitdir) {
1693 const char *gitdir = getenv(GIT_DIR_ENVIRONMENT);
1694 if (!gitdir)
1695 gitdir = DEFAULT_GIT_DIR_ENVIRONMENT;
1696 setup_git_env(gitdir);
1698 if (startup_info->have_repository) {
1699 repo_set_hash_algo(the_repository, repo_fmt.hash_algo);
1700 repo_set_compat_hash_algo(the_repository,
1701 repo_fmt.compat_hash_algo);
1702 repo_set_ref_storage_format(the_repository,
1703 repo_fmt.ref_storage_format);
1704 the_repository->repository_format_worktree_config =
1705 repo_fmt.worktree_config;
1706 /* take ownership of repo_fmt.partial_clone */
1707 the_repository->repository_format_partial_clone =
1708 repo_fmt.partial_clone;
1709 repo_fmt.partial_clone = NULL;
1713 * Since precompose_string_if_needed() needs to look at
1714 * the core.precomposeunicode configuration, this
1715 * has to happen after the above block that finds
1716 * out where the repository is, i.e. a preparation
1717 * for calling git_config_get_bool().
1719 if (prefix) {
1720 prefix = precompose_string_if_needed(prefix);
1721 startup_info->prefix = prefix;
1722 setenv(GIT_PREFIX_ENVIRONMENT, prefix, 1);
1723 } else {
1724 startup_info->prefix = NULL;
1725 setenv(GIT_PREFIX_ENVIRONMENT, "", 1);
1728 setup_original_cwd();
1730 strbuf_release(&dir);
1731 strbuf_release(&gitdir);
1732 strbuf_release(&report);
1733 clear_repository_format(&repo_fmt);
1735 return prefix;
1738 int git_config_perm(const char *var, const char *value)
1740 int i;
1741 char *endptr;
1743 if (!value)
1744 return PERM_GROUP;
1746 if (!strcmp(value, "umask"))
1747 return PERM_UMASK;
1748 if (!strcmp(value, "group"))
1749 return PERM_GROUP;
1750 if (!strcmp(value, "all") ||
1751 !strcmp(value, "world") ||
1752 !strcmp(value, "everybody"))
1753 return PERM_EVERYBODY;
1755 /* Parse octal numbers */
1756 i = strtol(value, &endptr, 8);
1758 /* If not an octal number, maybe true/false? */
1759 if (*endptr != 0)
1760 return git_config_bool(var, value) ? PERM_GROUP : PERM_UMASK;
1763 * Treat values 0, 1 and 2 as compatibility cases, otherwise it is
1764 * a chmod value to restrict to.
1766 switch (i) {
1767 case PERM_UMASK: /* 0 */
1768 return PERM_UMASK;
1769 case OLD_PERM_GROUP: /* 1 */
1770 return PERM_GROUP;
1771 case OLD_PERM_EVERYBODY: /* 2 */
1772 return PERM_EVERYBODY;
1775 /* A filemode value was given: 0xxx */
1777 if ((i & 0600) != 0600)
1778 die(_("problem with core.sharedRepository filemode value "
1779 "(0%.3o).\nThe owner of files must always have "
1780 "read and write permissions."), i);
1783 * Mask filemode value. Others can not get write permission.
1784 * x flags for directories are handled separately.
1786 return -(i & 0666);
1789 void check_repository_format(struct repository_format *fmt)
1791 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
1792 if (!fmt)
1793 fmt = &repo_fmt;
1794 check_repository_format_gently(get_git_dir(), fmt, NULL);
1795 startup_info->have_repository = 1;
1796 repo_set_hash_algo(the_repository, fmt->hash_algo);
1797 repo_set_compat_hash_algo(the_repository, fmt->compat_hash_algo);
1798 repo_set_ref_storage_format(the_repository,
1799 fmt->ref_storage_format);
1800 the_repository->repository_format_worktree_config =
1801 fmt->worktree_config;
1802 the_repository->repository_format_partial_clone =
1803 xstrdup_or_null(fmt->partial_clone);
1804 clear_repository_format(&repo_fmt);
1808 * Returns the "prefix", a path to the current working directory
1809 * relative to the work tree root, or NULL, if the current working
1810 * directory is not a strict subdirectory of the work tree root. The
1811 * prefix always ends with a '/' character.
1813 const char *setup_git_directory(void)
1815 return setup_git_directory_gently(NULL);
1818 const char *resolve_gitdir_gently(const char *suspect, int *return_error_code)
1820 if (is_git_directory(suspect))
1821 return suspect;
1822 return read_gitfile_gently(suspect, return_error_code);
1825 /* if any standard file descriptor is missing open it to /dev/null */
1826 void sanitize_stdfds(void)
1828 int fd = xopen("/dev/null", O_RDWR);
1829 while (fd < 2)
1830 fd = xdup(fd);
1831 if (fd > 2)
1832 close(fd);
1835 int daemonize(void)
1837 #ifdef NO_POSIX_GOODIES
1838 errno = ENOSYS;
1839 return -1;
1840 #else
1841 switch (fork()) {
1842 case 0:
1843 break;
1844 case -1:
1845 die_errno(_("fork failed"));
1846 default:
1847 exit(0);
1849 if (setsid() == -1)
1850 die_errno(_("setsid failed"));
1851 close(0);
1852 close(1);
1853 close(2);
1854 sanitize_stdfds();
1855 return 0;
1856 #endif
1859 struct template_dir_cb_data {
1860 char *path;
1861 int initialized;
1864 static int template_dir_cb(const char *key, const char *value,
1865 const struct config_context *ctx, void *d)
1867 struct template_dir_cb_data *data = d;
1869 if (strcmp(key, "init.templatedir"))
1870 return 0;
1872 if (!value) {
1873 data->path = NULL;
1874 } else {
1875 char *path = NULL;
1877 FREE_AND_NULL(data->path);
1878 if (!git_config_pathname((const char **)&path, key, value))
1879 data->path = path ? path : xstrdup(value);
1882 return 0;
1885 const char *get_template_dir(const char *option_template)
1887 const char *template_dir = option_template;
1889 if (!template_dir)
1890 template_dir = getenv(TEMPLATE_DIR_ENVIRONMENT);
1891 if (!template_dir) {
1892 static struct template_dir_cb_data data;
1894 if (!data.initialized) {
1895 git_protected_config(template_dir_cb, &data);
1896 data.initialized = 1;
1898 template_dir = data.path;
1900 if (!template_dir) {
1901 static char *dir;
1903 if (!dir)
1904 dir = system_path(DEFAULT_GIT_TEMPLATE_DIR);
1905 template_dir = dir;
1907 return template_dir;
1910 #ifdef NO_TRUSTABLE_FILEMODE
1911 #define TEST_FILEMODE 0
1912 #else
1913 #define TEST_FILEMODE 1
1914 #endif
1916 #define GIT_DEFAULT_HASH_ENVIRONMENT "GIT_DEFAULT_HASH"
1918 static void copy_templates_1(struct strbuf *path, struct strbuf *template_path,
1919 DIR *dir)
1921 size_t path_baselen = path->len;
1922 size_t template_baselen = template_path->len;
1923 struct dirent *de;
1925 /* Note: if ".git/hooks" file exists in the repository being
1926 * re-initialized, /etc/core-git/templates/hooks/update would
1927 * cause "git init" to fail here. I think this is sane but
1928 * it means that the set of templates we ship by default, along
1929 * with the way the namespace under .git/ is organized, should
1930 * be really carefully chosen.
1932 safe_create_dir(path->buf, 1);
1933 while ((de = readdir(dir)) != NULL) {
1934 struct stat st_git, st_template;
1935 int exists = 0;
1937 strbuf_setlen(path, path_baselen);
1938 strbuf_setlen(template_path, template_baselen);
1940 if (de->d_name[0] == '.')
1941 continue;
1942 strbuf_addstr(path, de->d_name);
1943 strbuf_addstr(template_path, de->d_name);
1944 if (lstat(path->buf, &st_git)) {
1945 if (errno != ENOENT)
1946 die_errno(_("cannot stat '%s'"), path->buf);
1948 else
1949 exists = 1;
1951 if (lstat(template_path->buf, &st_template))
1952 die_errno(_("cannot stat template '%s'"), template_path->buf);
1954 if (S_ISDIR(st_template.st_mode)) {
1955 DIR *subdir = opendir(template_path->buf);
1956 if (!subdir)
1957 die_errno(_("cannot opendir '%s'"), template_path->buf);
1958 strbuf_addch(path, '/');
1959 strbuf_addch(template_path, '/');
1960 copy_templates_1(path, template_path, subdir);
1961 closedir(subdir);
1963 else if (exists)
1964 continue;
1965 else if (S_ISLNK(st_template.st_mode)) {
1966 struct strbuf lnk = STRBUF_INIT;
1967 if (strbuf_readlink(&lnk, template_path->buf,
1968 st_template.st_size) < 0)
1969 die_errno(_("cannot readlink '%s'"), template_path->buf);
1970 if (symlink(lnk.buf, path->buf))
1971 die_errno(_("cannot symlink '%s' '%s'"),
1972 lnk.buf, path->buf);
1973 strbuf_release(&lnk);
1975 else if (S_ISREG(st_template.st_mode)) {
1976 if (copy_file(path->buf, template_path->buf, st_template.st_mode))
1977 die_errno(_("cannot copy '%s' to '%s'"),
1978 template_path->buf, path->buf);
1980 else
1981 error(_("ignoring template %s"), template_path->buf);
1985 static void copy_templates(const char *option_template)
1987 const char *template_dir = get_template_dir(option_template);
1988 struct strbuf path = STRBUF_INIT;
1989 struct strbuf template_path = STRBUF_INIT;
1990 size_t template_len;
1991 struct repository_format template_format = REPOSITORY_FORMAT_INIT;
1992 struct strbuf err = STRBUF_INIT;
1993 DIR *dir;
1994 char *to_free = NULL;
1996 if (!template_dir || !*template_dir)
1997 return;
1999 strbuf_addstr(&template_path, template_dir);
2000 strbuf_complete(&template_path, '/');
2001 template_len = template_path.len;
2003 dir = opendir(template_path.buf);
2004 if (!dir) {
2005 warning(_("templates not found in %s"), template_dir);
2006 goto free_return;
2009 /* Make sure that template is from the correct vintage */
2010 strbuf_addstr(&template_path, "config");
2011 read_repository_format(&template_format, template_path.buf);
2012 strbuf_setlen(&template_path, template_len);
2015 * No mention of version at all is OK, but anything else should be
2016 * verified.
2018 if (template_format.version >= 0 &&
2019 verify_repository_format(&template_format, &err) < 0) {
2020 warning(_("not copying templates from '%s': %s"),
2021 template_dir, err.buf);
2022 strbuf_release(&err);
2023 goto close_free_return;
2026 strbuf_addstr(&path, get_git_common_dir());
2027 strbuf_complete(&path, '/');
2028 copy_templates_1(&path, &template_path, dir);
2029 close_free_return:
2030 closedir(dir);
2031 free_return:
2032 free(to_free);
2033 strbuf_release(&path);
2034 strbuf_release(&template_path);
2035 clear_repository_format(&template_format);
2039 * If the git_dir is not directly inside the working tree, then git will not
2040 * find it by default, and we need to set the worktree explicitly.
2042 static int needs_work_tree_config(const char *git_dir, const char *work_tree)
2044 if (!strcmp(work_tree, "/") && !strcmp(git_dir, "/.git"))
2045 return 0;
2046 if (skip_prefix(git_dir, work_tree, &git_dir) &&
2047 !strcmp(git_dir, "/.git"))
2048 return 0;
2049 return 1;
2052 void initialize_repository_version(int hash_algo,
2053 unsigned int ref_storage_format,
2054 int reinit)
2056 char repo_version_string[10];
2057 int repo_version = GIT_REPO_VERSION;
2060 * Note that we initialize the repository version to 1 when the ref
2061 * storage format is unknown. This is on purpose so that we can add the
2062 * correct object format to the config during git-clone(1). The format
2063 * version will get adjusted by git-clone(1) once it has learned about
2064 * the remote repository's format.
2066 if (hash_algo != GIT_HASH_SHA1 ||
2067 ref_storage_format != REF_STORAGE_FORMAT_FILES)
2068 repo_version = GIT_REPO_VERSION_READ;
2070 /* This forces creation of new config file */
2071 xsnprintf(repo_version_string, sizeof(repo_version_string),
2072 "%d", repo_version);
2073 git_config_set("core.repositoryformatversion", repo_version_string);
2075 if (hash_algo != GIT_HASH_SHA1 && hash_algo != GIT_HASH_UNKNOWN)
2076 git_config_set("extensions.objectformat",
2077 hash_algos[hash_algo].name);
2078 else if (reinit)
2079 git_config_set_gently("extensions.objectformat", NULL);
2081 if (ref_storage_format != REF_STORAGE_FORMAT_FILES)
2082 git_config_set("extensions.refstorage",
2083 ref_storage_format_to_name(ref_storage_format));
2086 static int is_reinit(void)
2088 struct strbuf buf = STRBUF_INIT;
2089 char junk[2];
2090 int ret;
2092 git_path_buf(&buf, "HEAD");
2093 ret = !access(buf.buf, R_OK) || readlink(buf.buf, junk, sizeof(junk) - 1) != -1;
2094 strbuf_release(&buf);
2095 return ret;
2098 void create_reference_database(unsigned int ref_storage_format,
2099 const char *initial_branch, int quiet)
2101 struct strbuf err = STRBUF_INIT;
2102 char *to_free = NULL;
2103 int reinit = is_reinit();
2105 repo_set_ref_storage_format(the_repository, ref_storage_format);
2106 if (ref_store_create_on_disk(get_main_ref_store(the_repository), 0, &err))
2107 die("failed to set up refs db: %s", err.buf);
2110 * Point the HEAD symref to the initial branch with if HEAD does
2111 * not yet exist.
2113 if (!reinit) {
2114 char *ref;
2116 if (!initial_branch)
2117 initial_branch = to_free =
2118 repo_default_branch_name(the_repository, quiet);
2120 ref = xstrfmt("refs/heads/%s", initial_branch);
2121 if (check_refname_format(ref, 0) < 0)
2122 die(_("invalid initial branch name: '%s'"),
2123 initial_branch);
2125 if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", ref, NULL) < 0)
2126 exit(1);
2127 free(ref);
2130 if (reinit && initial_branch)
2131 warning(_("re-init: ignored --initial-branch=%s"),
2132 initial_branch);
2134 strbuf_release(&err);
2135 free(to_free);
2138 static int create_default_files(const char *template_path,
2139 const char *original_git_dir,
2140 const struct repository_format *fmt,
2141 int init_shared_repository)
2143 struct stat st1;
2144 struct strbuf buf = STRBUF_INIT;
2145 char *path;
2146 int reinit;
2147 int filemode;
2148 const char *work_tree = get_git_work_tree();
2151 * First copy the templates -- we might have the default
2152 * config file there, in which case we would want to read
2153 * from it after installing.
2155 * Before reading that config, we also need to clear out any cached
2156 * values (since we've just potentially changed what's available on
2157 * disk).
2159 copy_templates(template_path);
2160 git_config_clear();
2161 reset_shared_repository();
2162 git_config(git_default_config, NULL);
2164 reinit = is_reinit();
2167 * We must make sure command-line options continue to override any
2168 * values we might have just re-read from the config.
2170 if (init_shared_repository != -1)
2171 set_shared_repository(init_shared_repository);
2173 is_bare_repository_cfg = !work_tree;
2176 * We would have created the above under user's umask -- under
2177 * shared-repository settings, we would need to fix them up.
2179 if (get_shared_repository()) {
2180 adjust_shared_perm(get_git_dir());
2183 initialize_repository_version(fmt->hash_algo, fmt->ref_storage_format, 0);
2185 /* Check filemode trustability */
2186 path = git_path_buf(&buf, "config");
2187 filemode = TEST_FILEMODE;
2188 if (TEST_FILEMODE && !lstat(path, &st1)) {
2189 struct stat st2;
2190 filemode = (!chmod(path, st1.st_mode ^ S_IXUSR) &&
2191 !lstat(path, &st2) &&
2192 st1.st_mode != st2.st_mode &&
2193 !chmod(path, st1.st_mode));
2194 if (filemode && !reinit && (st1.st_mode & S_IXUSR))
2195 filemode = 0;
2197 git_config_set("core.filemode", filemode ? "true" : "false");
2199 if (is_bare_repository())
2200 git_config_set("core.bare", "true");
2201 else {
2202 git_config_set("core.bare", "false");
2203 /* allow template config file to override the default */
2204 if (log_all_ref_updates == LOG_REFS_UNSET)
2205 git_config_set("core.logallrefupdates", "true");
2206 if (needs_work_tree_config(original_git_dir, work_tree))
2207 git_config_set("core.worktree", work_tree);
2210 if (!reinit) {
2211 /* Check if symlink is supported in the work tree */
2212 path = git_path_buf(&buf, "tXXXXXX");
2213 if (!close(xmkstemp(path)) &&
2214 !unlink(path) &&
2215 !symlink("testing", path) &&
2216 !lstat(path, &st1) &&
2217 S_ISLNK(st1.st_mode))
2218 unlink(path); /* good */
2219 else
2220 git_config_set("core.symlinks", "false");
2222 /* Check if the filesystem is case-insensitive */
2223 path = git_path_buf(&buf, "CoNfIg");
2224 if (!access(path, F_OK))
2225 git_config_set("core.ignorecase", "true");
2226 probe_utf8_pathname_composition();
2229 strbuf_release(&buf);
2230 return reinit;
2233 static void create_object_directory(void)
2235 struct strbuf path = STRBUF_INIT;
2236 size_t baselen;
2238 strbuf_addstr(&path, get_object_directory());
2239 baselen = path.len;
2241 safe_create_dir(path.buf, 1);
2243 strbuf_setlen(&path, baselen);
2244 strbuf_addstr(&path, "/pack");
2245 safe_create_dir(path.buf, 1);
2247 strbuf_setlen(&path, baselen);
2248 strbuf_addstr(&path, "/info");
2249 safe_create_dir(path.buf, 1);
2251 strbuf_release(&path);
2254 static void separate_git_dir(const char *git_dir, const char *git_link)
2256 struct stat st;
2258 if (!stat(git_link, &st)) {
2259 const char *src;
2261 if (S_ISREG(st.st_mode))
2262 src = read_gitfile(git_link);
2263 else if (S_ISDIR(st.st_mode))
2264 src = git_link;
2265 else
2266 die(_("unable to handle file type %d"), (int)st.st_mode);
2268 if (rename(src, git_dir))
2269 die_errno(_("unable to move %s to %s"), src, git_dir);
2270 repair_worktrees(NULL, NULL);
2273 write_file(git_link, "gitdir: %s", git_dir);
2276 static void validate_hash_algorithm(struct repository_format *repo_fmt, int hash)
2278 const char *env = getenv(GIT_DEFAULT_HASH_ENVIRONMENT);
2280 * If we already have an initialized repo, don't allow the user to
2281 * specify a different algorithm, as that could cause corruption.
2282 * Otherwise, if the user has specified one on the command line, use it.
2284 if (repo_fmt->version >= 0 && hash != GIT_HASH_UNKNOWN && hash != repo_fmt->hash_algo)
2285 die(_("attempt to reinitialize repository with different hash"));
2286 else if (hash != GIT_HASH_UNKNOWN)
2287 repo_fmt->hash_algo = hash;
2288 else if (env) {
2289 int env_algo = hash_algo_by_name(env);
2290 if (env_algo == GIT_HASH_UNKNOWN)
2291 die(_("unknown hash algorithm '%s'"), env);
2292 repo_fmt->hash_algo = env_algo;
2296 static void validate_ref_storage_format(struct repository_format *repo_fmt,
2297 unsigned int format)
2299 const char *name = getenv("GIT_DEFAULT_REF_FORMAT");
2301 if (repo_fmt->version >= 0 &&
2302 format != REF_STORAGE_FORMAT_UNKNOWN &&
2303 format != repo_fmt->ref_storage_format) {
2304 die(_("attempt to reinitialize repository with different reference storage format"));
2305 } else if (format != REF_STORAGE_FORMAT_UNKNOWN) {
2306 repo_fmt->ref_storage_format = format;
2307 } else if (name) {
2308 format = ref_storage_format_by_name(name);
2309 if (format == REF_STORAGE_FORMAT_UNKNOWN)
2310 die(_("unknown ref storage format '%s'"), name);
2311 repo_fmt->ref_storage_format = format;
2315 int init_db(const char *git_dir, const char *real_git_dir,
2316 const char *template_dir, int hash,
2317 unsigned int ref_storage_format,
2318 const char *initial_branch,
2319 int init_shared_repository, unsigned int flags)
2321 int reinit;
2322 int exist_ok = flags & INIT_DB_EXIST_OK;
2323 char *original_git_dir = real_pathdup(git_dir, 1);
2324 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
2326 if (real_git_dir) {
2327 struct stat st;
2329 if (!exist_ok && !stat(git_dir, &st))
2330 die(_("%s already exists"), git_dir);
2332 if (!exist_ok && !stat(real_git_dir, &st))
2333 die(_("%s already exists"), real_git_dir);
2335 set_git_dir(real_git_dir, 1);
2336 git_dir = get_git_dir();
2337 separate_git_dir(git_dir, original_git_dir);
2339 else {
2340 set_git_dir(git_dir, 1);
2341 git_dir = get_git_dir();
2343 startup_info->have_repository = 1;
2345 /* Ensure `core.hidedotfiles` is processed */
2346 git_config(platform_core_config, NULL);
2348 safe_create_dir(git_dir, 0);
2351 /* Check to see if the repository version is right.
2352 * Note that a newly created repository does not have
2353 * config file, so this will not fail. What we are catching
2354 * is an attempt to reinitialize new repository with an old tool.
2356 check_repository_format(&repo_fmt);
2358 validate_hash_algorithm(&repo_fmt, hash);
2359 validate_ref_storage_format(&repo_fmt, ref_storage_format);
2361 reinit = create_default_files(template_dir, original_git_dir,
2362 &repo_fmt, init_shared_repository);
2365 * Now that we have set up both the hash algorithm and the ref storage
2366 * format we can update the repository's settings accordingly.
2368 repo_set_hash_algo(the_repository, repo_fmt.hash_algo);
2369 repo_set_ref_storage_format(the_repository, repo_fmt.ref_storage_format);
2371 if (!(flags & INIT_DB_SKIP_REFDB))
2372 create_reference_database(repo_fmt.ref_storage_format,
2373 initial_branch, flags & INIT_DB_QUIET);
2374 create_object_directory();
2376 if (get_shared_repository()) {
2377 char buf[10];
2378 /* We do not spell "group" and such, so that
2379 * the configuration can be read by older version
2380 * of git. Note, we use octal numbers for new share modes,
2381 * and compatibility values for PERM_GROUP and
2382 * PERM_EVERYBODY.
2384 if (get_shared_repository() < 0)
2385 /* force to the mode value */
2386 xsnprintf(buf, sizeof(buf), "0%o", -get_shared_repository());
2387 else if (get_shared_repository() == PERM_GROUP)
2388 xsnprintf(buf, sizeof(buf), "%d", OLD_PERM_GROUP);
2389 else if (get_shared_repository() == PERM_EVERYBODY)
2390 xsnprintf(buf, sizeof(buf), "%d", OLD_PERM_EVERYBODY);
2391 else
2392 BUG("invalid value for shared_repository");
2393 git_config_set("core.sharedrepository", buf);
2394 git_config_set("receive.denyNonFastforwards", "true");
2397 if (!(flags & INIT_DB_QUIET)) {
2398 int len = strlen(git_dir);
2400 if (reinit)
2401 printf(get_shared_repository()
2402 ? _("Reinitialized existing shared Git repository in %s%s\n")
2403 : _("Reinitialized existing Git repository in %s%s\n"),
2404 git_dir, len && git_dir[len-1] != '/' ? "/" : "");
2405 else
2406 printf(get_shared_repository()
2407 ? _("Initialized empty shared Git repository in %s%s\n")
2408 : _("Initialized empty Git repository in %s%s\n"),
2409 git_dir, len && git_dir[len-1] != '/' ? "/" : "");
2412 clear_repository_format(&repo_fmt);
2413 free(original_git_dir);
2414 return 0;