The eleventh batch
[git/gitster.git] / setup.c
blob7b648de0279116b381eea46800ad130606926103
1 #define USE_THE_REPOSITORY_VARIABLE
3 #include "git-compat-util.h"
4 #include "abspath.h"
5 #include "copy.h"
6 #include "environment.h"
7 #include "exec-cmd.h"
8 #include "gettext.h"
9 #include "hex.h"
10 #include "object-file.h"
11 #include "object-name.h"
12 #include "refs.h"
13 #include "replace-object.h"
14 #include "repository.h"
15 #include "config.h"
16 #include "dir.h"
17 #include "setup.h"
18 #include "shallow.h"
19 #include "string-list.h"
20 #include "strvec.h"
21 #include "chdir-notify.h"
22 #include "path.h"
23 #include "quote.h"
24 #include "tmp-objdir.h"
25 #include "trace.h"
26 #include "trace2.h"
27 #include "worktree.h"
28 #include "exec-cmd.h"
30 static int inside_git_dir = -1;
31 static int inside_work_tree = -1;
32 static int work_tree_config_is_bogus;
33 enum allowed_bare_repo {
34 ALLOWED_BARE_REPO_EXPLICIT = 0,
35 ALLOWED_BARE_REPO_ALL,
38 static struct startup_info the_startup_info;
39 struct startup_info *startup_info = &the_startup_info;
40 const char *tmp_original_cwd;
43 * The input parameter must contain an absolute path, and it must already be
44 * normalized.
46 * Find the part of an absolute path that lies inside the work tree by
47 * dereferencing symlinks outside the work tree, for example:
48 * /dir1/repo/dir2/file (work tree is /dir1/repo) -> dir2/file
49 * /dir/file (work tree is /) -> dir/file
50 * /dir/symlink1/symlink2 (symlink1 points to work tree) -> symlink2
51 * /dir/repolink/file (repolink points to /dir/repo) -> file
52 * /dir/repo (exactly equal to work tree) -> (empty string)
54 static int abspath_part_inside_repo(char *path)
56 size_t len;
57 size_t wtlen;
58 char *path0;
59 int off;
60 const char *work_tree = precompose_string_if_needed(repo_get_work_tree(the_repository));
61 struct strbuf realpath = STRBUF_INIT;
63 if (!work_tree)
64 return -1;
65 wtlen = strlen(work_tree);
66 len = strlen(path);
67 off = offset_1st_component(path);
69 /* check if work tree is already the prefix */
70 if (wtlen <= len && !fspathncmp(path, work_tree, wtlen)) {
71 if (path[wtlen] == '/') {
72 memmove(path, path + wtlen + 1, len - wtlen);
73 return 0;
74 } else if (path[wtlen - 1] == '/' || path[wtlen] == '\0') {
75 /* work tree is the root, or the whole path */
76 memmove(path, path + wtlen, len - wtlen + 1);
77 return 0;
79 /* work tree might match beginning of a symlink to work tree */
80 off = wtlen;
82 path0 = path;
83 path += off;
85 /* check each '/'-terminated level */
86 while (*path) {
87 path++;
88 if (*path == '/') {
89 *path = '\0';
90 strbuf_realpath(&realpath, path0, 1);
91 if (fspathcmp(realpath.buf, work_tree) == 0) {
92 memmove(path0, path + 1, len - (path - path0));
93 strbuf_release(&realpath);
94 return 0;
96 *path = '/';
100 /* check whole path */
101 strbuf_realpath(&realpath, path0, 1);
102 if (fspathcmp(realpath.buf, work_tree) == 0) {
103 *path0 = '\0';
104 strbuf_release(&realpath);
105 return 0;
108 strbuf_release(&realpath);
109 return -1;
113 * Normalize "path", prepending the "prefix" for relative paths. If
114 * remaining_prefix is not NULL, return the actual prefix still
115 * remains in the path. For example, prefix = sub1/sub2/ and path is
117 * foo -> sub1/sub2/foo (full prefix)
118 * ../foo -> sub1/foo (remaining prefix is sub1/)
119 * ../../bar -> bar (no remaining prefix)
120 * ../../sub1/sub2/foo -> sub1/sub2/foo (but no remaining prefix)
121 * `pwd`/../bar -> sub1/bar (no remaining prefix)
123 char *prefix_path_gently(const char *prefix, int len,
124 int *remaining_prefix, const char *path)
126 const char *orig = path;
127 char *sanitized;
128 if (is_absolute_path(orig)) {
129 sanitized = xmallocz(strlen(path));
130 if (remaining_prefix)
131 *remaining_prefix = 0;
132 if (normalize_path_copy_len(sanitized, path, remaining_prefix)) {
133 free(sanitized);
134 return NULL;
136 if (abspath_part_inside_repo(sanitized)) {
137 free(sanitized);
138 return NULL;
140 } else {
141 sanitized = xstrfmt("%.*s%s", len, len ? prefix : "", path);
142 if (remaining_prefix)
143 *remaining_prefix = len;
144 if (normalize_path_copy_len(sanitized, sanitized, remaining_prefix)) {
145 free(sanitized);
146 return NULL;
149 return sanitized;
152 char *prefix_path(const char *prefix, int len, const char *path)
154 char *r = prefix_path_gently(prefix, len, NULL, path);
155 if (!r) {
156 const char *hint_path = repo_get_work_tree(the_repository);
157 if (!hint_path)
158 hint_path = repo_get_git_dir(the_repository);
159 die(_("'%s' is outside repository at '%s'"), path,
160 absolute_path(hint_path));
162 return r;
165 int path_inside_repo(const char *prefix, const char *path)
167 int len = prefix ? strlen(prefix) : 0;
168 char *r = prefix_path_gently(prefix, len, NULL, path);
169 if (r) {
170 free(r);
171 return 1;
173 return 0;
176 int check_filename(const char *prefix, const char *arg)
178 char *to_free = NULL;
179 struct stat st;
181 if (skip_prefix(arg, ":/", &arg)) {
182 if (!*arg) /* ":/" is root dir, always exists */
183 return 1;
184 prefix = NULL;
185 } else if (skip_prefix(arg, ":!", &arg) ||
186 skip_prefix(arg, ":^", &arg)) {
187 if (!*arg) /* excluding everything is silly, but allowed */
188 return 1;
191 if (prefix)
192 arg = to_free = prefix_filename(prefix, arg);
194 if (!lstat(arg, &st)) {
195 free(to_free);
196 return 1; /* file exists */
198 if (is_missing_file_error(errno)) {
199 free(to_free);
200 return 0; /* file does not exist */
202 die_errno(_("failed to stat '%s'"), arg);
205 static void NORETURN die_verify_filename(struct repository *r,
206 const char *prefix,
207 const char *arg,
208 int diagnose_misspelt_rev)
210 if (!diagnose_misspelt_rev)
211 die(_("%s: no such path in the working tree.\n"
212 "Use 'git <command> -- <path>...' to specify paths that do not exist locally."),
213 arg);
215 * Saying "'(icase)foo' does not exist in the index" when the
216 * user gave us ":(icase)foo" is just stupid. A magic pathspec
217 * begins with a colon and is followed by a non-alnum; do not
218 * let maybe_die_on_misspelt_object_name() even trigger.
220 if (!(arg[0] == ':' && !isalnum(arg[1])))
221 maybe_die_on_misspelt_object_name(r, arg, prefix);
223 /* ... or fall back the most general message. */
224 die(_("ambiguous argument '%s': unknown revision or path not in the working tree.\n"
225 "Use '--' to separate paths from revisions, like this:\n"
226 "'git <command> [<revision>...] -- [<file>...]'"), arg);
231 * Check for arguments that don't resolve as actual files,
232 * but which look sufficiently like pathspecs that we'll consider
233 * them such for the purposes of rev/pathspec DWIM parsing.
235 static int looks_like_pathspec(const char *arg)
237 const char *p;
238 int escaped = 0;
241 * Wildcard characters imply the user is looking to match pathspecs
242 * that aren't in the filesystem. Note that this doesn't include
243 * backslash even though it's a glob special; by itself it doesn't
244 * cause any increase in the match. Likewise ignore backslash-escaped
245 * wildcard characters.
247 for (p = arg; *p; p++) {
248 if (escaped) {
249 escaped = 0;
250 } else if (is_glob_special(*p)) {
251 if (*p == '\\')
252 escaped = 1;
253 else
254 return 1;
258 /* long-form pathspec magic */
259 if (starts_with(arg, ":("))
260 return 1;
262 return 0;
266 * Verify a filename that we got as an argument for a pathspec
267 * entry. Note that a filename that begins with "-" never verifies
268 * as true, because even if such a filename were to exist, we want
269 * it to be preceded by the "--" marker (or we want the user to
270 * use a format like "./-filename")
272 * The "diagnose_misspelt_rev" is used to provide a user-friendly
273 * diagnosis when dying upon finding that "name" is not a pathname.
274 * If set to 1, the diagnosis will try to diagnose "name" as an
275 * invalid object name (e.g. HEAD:foo). If set to 0, the diagnosis
276 * will only complain about an inexisting file.
278 * This function is typically called to check that a "file or rev"
279 * argument is unambiguous. In this case, the caller will want
280 * diagnose_misspelt_rev == 1 when verifying the first non-rev
281 * argument (which could have been a revision), and
282 * diagnose_misspelt_rev == 0 for the next ones (because we already
283 * saw a filename, there's not ambiguity anymore).
285 void verify_filename(const char *prefix,
286 const char *arg,
287 int diagnose_misspelt_rev)
289 if (*arg == '-')
290 die(_("option '%s' must come before non-option arguments"), arg);
291 if (looks_like_pathspec(arg) || check_filename(prefix, arg))
292 return;
293 die_verify_filename(the_repository, prefix, arg, diagnose_misspelt_rev);
297 * Opposite of the above: the command line did not have -- marker
298 * and we parsed the arg as a refname. It should not be interpretable
299 * as a filename.
301 void verify_non_filename(const char *prefix, const char *arg)
303 if (!is_inside_work_tree() || is_inside_git_dir())
304 return;
305 if (*arg == '-')
306 return; /* flag */
307 if (!check_filename(prefix, arg))
308 return;
309 die(_("ambiguous argument '%s': both revision and filename\n"
310 "Use '--' to separate paths from revisions, like this:\n"
311 "'git <command> [<revision>...] -- [<file>...]'"), arg);
314 int get_common_dir(struct strbuf *sb, const char *gitdir)
316 const char *git_env_common_dir = getenv(GIT_COMMON_DIR_ENVIRONMENT);
317 if (git_env_common_dir) {
318 strbuf_addstr(sb, git_env_common_dir);
319 return 1;
320 } else {
321 return get_common_dir_noenv(sb, gitdir);
325 int get_common_dir_noenv(struct strbuf *sb, const char *gitdir)
327 struct strbuf data = STRBUF_INIT;
328 struct strbuf path = STRBUF_INIT;
329 int ret = 0;
331 strbuf_addf(&path, "%s/commondir", gitdir);
332 if (file_exists(path.buf)) {
333 if (strbuf_read_file(&data, path.buf, 0) <= 0)
334 die_errno(_("failed to read %s"), path.buf);
335 while (data.len && (data.buf[data.len - 1] == '\n' ||
336 data.buf[data.len - 1] == '\r'))
337 data.len--;
338 data.buf[data.len] = '\0';
339 strbuf_reset(&path);
340 if (!is_absolute_path(data.buf))
341 strbuf_addf(&path, "%s/", gitdir);
342 strbuf_addbuf(&path, &data);
343 strbuf_add_real_path(sb, path.buf);
344 ret = 1;
345 } else {
346 strbuf_addstr(sb, gitdir);
349 strbuf_release(&data);
350 strbuf_release(&path);
351 return ret;
354 static int validate_headref(const char *path)
356 struct stat st;
357 char buffer[256];
358 const char *refname;
359 struct object_id oid;
360 int fd;
361 ssize_t len;
363 if (lstat(path, &st) < 0)
364 return -1;
366 /* Make sure it is a "refs/.." symlink */
367 if (S_ISLNK(st.st_mode)) {
368 len = readlink(path, buffer, sizeof(buffer)-1);
369 if (len >= 5 && !memcmp("refs/", buffer, 5))
370 return 0;
371 return -1;
375 * Anything else, just open it and try to see if it is a symbolic ref.
377 fd = open(path, O_RDONLY);
378 if (fd < 0)
379 return -1;
380 len = read_in_full(fd, buffer, sizeof(buffer)-1);
381 close(fd);
383 if (len < 0)
384 return -1;
385 buffer[len] = '\0';
388 * Is it a symbolic ref?
390 if (skip_prefix(buffer, "ref:", &refname)) {
391 while (isspace(*refname))
392 refname++;
393 if (starts_with(refname, "refs/"))
394 return 0;
398 * Is this a detached HEAD?
400 if (get_oid_hex_any(buffer, &oid) != GIT_HASH_UNKNOWN)
401 return 0;
403 return -1;
407 * Test if it looks like we're at a git directory.
408 * We want to see:
410 * - either an objects/ directory _or_ the proper
411 * GIT_OBJECT_DIRECTORY environment variable
412 * - a refs/ directory
413 * - either a HEAD symlink or a HEAD file that is formatted as
414 * a proper "ref:", or a regular file HEAD that has a properly
415 * formatted sha1 object name.
417 int is_git_directory(const char *suspect)
419 struct strbuf path = STRBUF_INIT;
420 int ret = 0;
421 size_t len;
423 /* Check worktree-related signatures */
424 strbuf_addstr(&path, suspect);
425 strbuf_complete(&path, '/');
426 strbuf_addstr(&path, "HEAD");
427 if (validate_headref(path.buf))
428 goto done;
430 strbuf_reset(&path);
431 get_common_dir(&path, suspect);
432 len = path.len;
434 /* Check non-worktree-related signatures */
435 if (getenv(DB_ENVIRONMENT)) {
436 if (access(getenv(DB_ENVIRONMENT), X_OK))
437 goto done;
439 else {
440 strbuf_setlen(&path, len);
441 strbuf_addstr(&path, "/objects");
442 if (access(path.buf, X_OK))
443 goto done;
446 strbuf_setlen(&path, len);
447 strbuf_addstr(&path, "/refs");
448 if (access(path.buf, X_OK))
449 goto done;
451 ret = 1;
452 done:
453 strbuf_release(&path);
454 return ret;
457 int is_nonbare_repository_dir(struct strbuf *path)
459 int ret = 0;
460 int gitfile_error;
461 size_t orig_path_len = path->len;
462 assert(orig_path_len != 0);
463 strbuf_complete(path, '/');
464 strbuf_addstr(path, ".git");
465 if (read_gitfile_gently(path->buf, &gitfile_error) || is_git_directory(path->buf))
466 ret = 1;
467 if (gitfile_error == READ_GITFILE_ERR_OPEN_FAILED ||
468 gitfile_error == READ_GITFILE_ERR_READ_FAILED)
469 ret = 1;
470 strbuf_setlen(path, orig_path_len);
471 return ret;
474 int is_inside_git_dir(void)
476 if (inside_git_dir < 0)
477 inside_git_dir = is_inside_dir(repo_get_git_dir(the_repository));
478 return inside_git_dir;
481 int is_inside_work_tree(void)
483 if (inside_work_tree < 0)
484 inside_work_tree = is_inside_dir(repo_get_work_tree(the_repository));
485 return inside_work_tree;
488 void setup_work_tree(void)
490 const char *work_tree;
491 static int initialized = 0;
493 if (initialized)
494 return;
496 if (work_tree_config_is_bogus)
497 die(_("unable to set up work tree using invalid config"));
499 work_tree = repo_get_work_tree(the_repository);
500 if (!work_tree || chdir_notify(work_tree))
501 die(_("this operation must be run in a work tree"));
504 * Make sure subsequent git processes find correct worktree
505 * if $GIT_WORK_TREE is set relative
507 if (getenv(GIT_WORK_TREE_ENVIRONMENT))
508 setenv(GIT_WORK_TREE_ENVIRONMENT, ".", 1);
510 initialized = 1;
513 static void setup_original_cwd(void)
515 struct strbuf tmp = STRBUF_INIT;
516 const char *worktree = NULL;
517 int offset = -1;
519 if (!tmp_original_cwd)
520 return;
523 * startup_info->original_cwd points to the current working
524 * directory we inherited from our parent process, which is a
525 * directory we want to avoid removing.
527 * For convenience, we would like to have the path relative to the
528 * worktree instead of an absolute path.
530 * Yes, startup_info->original_cwd is usually the same as 'prefix',
531 * but differs in two ways:
532 * - prefix has a trailing '/'
533 * - if the user passes '-C' to git, that modifies the prefix but
534 * not startup_info->original_cwd.
537 /* Normalize the directory */
538 if (!strbuf_realpath(&tmp, tmp_original_cwd, 0)) {
539 trace2_data_string("setup", the_repository,
540 "realpath-path", tmp_original_cwd);
541 trace2_data_string("setup", the_repository,
542 "realpath-failure", strerror(errno));
543 free((char*)tmp_original_cwd);
544 tmp_original_cwd = NULL;
545 return;
548 free((char*)tmp_original_cwd);
549 tmp_original_cwd = NULL;
550 startup_info->original_cwd = strbuf_detach(&tmp, NULL);
553 * Get our worktree; we only protect the current working directory
554 * if it's in the worktree.
556 worktree = repo_get_work_tree(the_repository);
557 if (!worktree)
558 goto no_prevention_needed;
560 offset = dir_inside_of(startup_info->original_cwd, worktree);
561 if (offset >= 0) {
563 * If startup_info->original_cwd == worktree, that is already
564 * protected and we don't need original_cwd as a secondary
565 * protection measure.
567 if (!*(startup_info->original_cwd + offset))
568 goto no_prevention_needed;
571 * original_cwd was inside worktree; precompose it just as
572 * we do prefix so that built up paths will match
574 startup_info->original_cwd = \
575 precompose_string_if_needed(startup_info->original_cwd
576 + offset);
577 return;
580 no_prevention_needed:
581 free((char*)startup_info->original_cwd);
582 startup_info->original_cwd = NULL;
585 static int read_worktree_config(const char *var, const char *value,
586 const struct config_context *ctx UNUSED,
587 void *vdata)
589 struct repository_format *data = vdata;
591 if (strcmp(var, "core.bare") == 0) {
592 data->is_bare = git_config_bool(var, value);
593 } else if (strcmp(var, "core.worktree") == 0) {
594 if (!value)
595 return config_error_nonbool(var);
596 free(data->work_tree);
597 data->work_tree = xstrdup(value);
599 return 0;
602 enum extension_result {
603 EXTENSION_ERROR = -1, /* compatible with error(), etc */
604 EXTENSION_UNKNOWN = 0,
605 EXTENSION_OK = 1
609 * Do not add new extensions to this function. It handles extensions which are
610 * respected even in v0-format repositories for historical compatibility.
612 static enum extension_result handle_extension_v0(const char *var,
613 const char *value,
614 const char *ext,
615 struct repository_format *data)
617 if (!strcmp(ext, "noop")) {
618 return EXTENSION_OK;
619 } else if (!strcmp(ext, "preciousobjects")) {
620 data->precious_objects = git_config_bool(var, value);
621 return EXTENSION_OK;
622 } else if (!strcmp(ext, "partialclone")) {
623 if (!value)
624 return config_error_nonbool(var);
625 data->partial_clone = xstrdup(value);
626 return EXTENSION_OK;
627 } else if (!strcmp(ext, "worktreeconfig")) {
628 data->worktree_config = git_config_bool(var, value);
629 return EXTENSION_OK;
632 return EXTENSION_UNKNOWN;
636 * Record any new extensions in this function.
638 static enum extension_result handle_extension(const char *var,
639 const char *value,
640 const char *ext,
641 struct repository_format *data)
643 if (!strcmp(ext, "noop-v1")) {
644 return EXTENSION_OK;
645 } else if (!strcmp(ext, "objectformat")) {
646 int format;
648 if (!value)
649 return config_error_nonbool(var);
650 format = hash_algo_by_name(value);
651 if (format == GIT_HASH_UNKNOWN)
652 return error(_("invalid value for '%s': '%s'"),
653 "extensions.objectformat", value);
654 data->hash_algo = format;
655 return EXTENSION_OK;
656 } else if (!strcmp(ext, "compatobjectformat")) {
657 struct string_list_item *item;
658 int format;
660 if (!value)
661 return config_error_nonbool(var);
662 format = hash_algo_by_name(value);
663 if (format == GIT_HASH_UNKNOWN)
664 return error(_("invalid value for '%s': '%s'"),
665 "extensions.compatobjectformat", value);
666 /* For now only support compatObjectFormat being specified once. */
667 for_each_string_list_item(item, &data->v1_only_extensions) {
668 if (!strcmp(item->string, "compatobjectformat"))
669 return error(_("'%s' already specified as '%s'"),
670 "extensions.compatobjectformat",
671 hash_algos[data->compat_hash_algo].name);
673 data->compat_hash_algo = format;
674 return EXTENSION_OK;
675 } else if (!strcmp(ext, "refstorage")) {
676 unsigned int format;
678 if (!value)
679 return config_error_nonbool(var);
680 format = ref_storage_format_by_name(value);
681 if (format == REF_STORAGE_FORMAT_UNKNOWN)
682 return error(_("invalid value for '%s': '%s'"),
683 "extensions.refstorage", value);
684 data->ref_storage_format = format;
685 return EXTENSION_OK;
687 return EXTENSION_UNKNOWN;
690 static int check_repo_format(const char *var, const char *value,
691 const struct config_context *ctx, void *vdata)
693 struct repository_format *data = vdata;
694 const char *ext;
696 if (strcmp(var, "core.repositoryformatversion") == 0)
697 data->version = git_config_int(var, value, ctx->kvi);
698 else if (skip_prefix(var, "extensions.", &ext)) {
699 switch (handle_extension_v0(var, value, ext, data)) {
700 case EXTENSION_ERROR:
701 return -1;
702 case EXTENSION_OK:
703 return 0;
704 case EXTENSION_UNKNOWN:
705 break;
708 switch (handle_extension(var, value, ext, data)) {
709 case EXTENSION_ERROR:
710 return -1;
711 case EXTENSION_OK:
712 string_list_append(&data->v1_only_extensions, ext);
713 return 0;
714 case EXTENSION_UNKNOWN:
715 string_list_append(&data->unknown_extensions, ext);
716 return 0;
720 return read_worktree_config(var, value, ctx, vdata);
723 static int check_repository_format_gently(const char *gitdir, struct repository_format *candidate, int *nongit_ok)
725 struct strbuf sb = STRBUF_INIT;
726 struct strbuf err = STRBUF_INIT;
727 int has_common;
729 has_common = get_common_dir(&sb, gitdir);
730 strbuf_addstr(&sb, "/config");
731 read_repository_format(candidate, sb.buf);
732 strbuf_release(&sb);
735 * For historical use of check_repository_format() in git-init,
736 * we treat a missing config as a silent "ok", even when nongit_ok
737 * is unset.
739 if (candidate->version < 0)
740 return 0;
742 if (verify_repository_format(candidate, &err) < 0) {
743 if (nongit_ok) {
744 warning("%s", err.buf);
745 strbuf_release(&err);
746 *nongit_ok = -1;
747 return -1;
749 die("%s", err.buf);
752 repository_format_precious_objects = candidate->precious_objects;
753 string_list_clear(&candidate->unknown_extensions, 0);
754 string_list_clear(&candidate->v1_only_extensions, 0);
756 if (candidate->worktree_config) {
758 * pick up core.bare and core.worktree from per-worktree
759 * config if present
761 strbuf_addf(&sb, "%s/config.worktree", gitdir);
762 git_config_from_file(read_worktree_config, sb.buf, candidate);
763 strbuf_release(&sb);
764 has_common = 0;
767 if (!has_common) {
768 if (candidate->is_bare != -1) {
769 is_bare_repository_cfg = candidate->is_bare;
770 if (is_bare_repository_cfg == 1)
771 inside_work_tree = -1;
773 if (candidate->work_tree) {
774 free(git_work_tree_cfg);
775 git_work_tree_cfg = xstrdup(candidate->work_tree);
776 inside_work_tree = -1;
780 return 0;
783 int upgrade_repository_format(int target_version)
785 struct strbuf sb = STRBUF_INIT;
786 struct strbuf err = STRBUF_INIT;
787 struct strbuf repo_version = STRBUF_INIT;
788 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
789 int ret;
791 strbuf_git_common_path(&sb, the_repository, "config");
792 read_repository_format(&repo_fmt, sb.buf);
793 strbuf_release(&sb);
795 if (repo_fmt.version >= target_version) {
796 ret = 0;
797 goto out;
800 if (verify_repository_format(&repo_fmt, &err) < 0) {
801 ret = error("cannot upgrade repository format from %d to %d: %s",
802 repo_fmt.version, target_version, err.buf);
803 goto out;
805 if (!repo_fmt.version && repo_fmt.unknown_extensions.nr) {
806 ret = error("cannot upgrade repository format: "
807 "unknown extension %s",
808 repo_fmt.unknown_extensions.items[0].string);
809 goto out;
812 strbuf_addf(&repo_version, "%d", target_version);
813 git_config_set("core.repositoryformatversion", repo_version.buf);
815 ret = 1;
817 out:
818 clear_repository_format(&repo_fmt);
819 strbuf_release(&repo_version);
820 strbuf_release(&err);
821 return ret;
824 static void init_repository_format(struct repository_format *format)
826 const struct repository_format fresh = REPOSITORY_FORMAT_INIT;
828 memcpy(format, &fresh, sizeof(fresh));
831 int read_repository_format(struct repository_format *format, const char *path)
833 clear_repository_format(format);
834 git_config_from_file(check_repo_format, path, format);
835 if (format->version == -1)
836 clear_repository_format(format);
837 return format->version;
840 void clear_repository_format(struct repository_format *format)
842 string_list_clear(&format->unknown_extensions, 0);
843 string_list_clear(&format->v1_only_extensions, 0);
844 free(format->work_tree);
845 free(format->partial_clone);
846 init_repository_format(format);
849 int verify_repository_format(const struct repository_format *format,
850 struct strbuf *err)
852 if (GIT_REPO_VERSION_READ < format->version) {
853 strbuf_addf(err, _("Expected git repo version <= %d, found %d"),
854 GIT_REPO_VERSION_READ, format->version);
855 return -1;
858 if (format->version >= 1 && format->unknown_extensions.nr) {
859 int i;
861 strbuf_addstr(err, Q_("unknown repository extension found:",
862 "unknown repository extensions found:",
863 format->unknown_extensions.nr));
865 for (i = 0; i < format->unknown_extensions.nr; i++)
866 strbuf_addf(err, "\n\t%s",
867 format->unknown_extensions.items[i].string);
868 return -1;
871 if (format->version == 0 && format->v1_only_extensions.nr) {
872 int i;
874 strbuf_addstr(err,
875 Q_("repo version is 0, but v1-only extension found:",
876 "repo version is 0, but v1-only extensions found:",
877 format->v1_only_extensions.nr));
879 for (i = 0; i < format->v1_only_extensions.nr; i++)
880 strbuf_addf(err, "\n\t%s",
881 format->v1_only_extensions.items[i].string);
882 return -1;
885 return 0;
888 void read_gitfile_error_die(int error_code, const char *path, const char *dir)
890 switch (error_code) {
891 case READ_GITFILE_ERR_STAT_FAILED:
892 case READ_GITFILE_ERR_NOT_A_FILE:
893 /* non-fatal; follow return path */
894 break;
895 case READ_GITFILE_ERR_OPEN_FAILED:
896 die_errno(_("error opening '%s'"), path);
897 case READ_GITFILE_ERR_TOO_LARGE:
898 die(_("too large to be a .git file: '%s'"), path);
899 case READ_GITFILE_ERR_READ_FAILED:
900 die(_("error reading %s"), path);
901 case READ_GITFILE_ERR_INVALID_FORMAT:
902 die(_("invalid gitfile format: %s"), path);
903 case READ_GITFILE_ERR_NO_PATH:
904 die(_("no path in gitfile: %s"), path);
905 case READ_GITFILE_ERR_NOT_A_REPO:
906 die(_("not a git repository: %s"), dir);
907 default:
908 BUG("unknown error code");
913 * Try to read the location of the git directory from the .git file,
914 * return path to git directory if found. The return value comes from
915 * a shared buffer.
917 * On failure, if return_error_code is not NULL, return_error_code
918 * will be set to an error code and NULL will be returned. If
919 * return_error_code is NULL the function will die instead (for most
920 * cases).
922 const char *read_gitfile_gently(const char *path, int *return_error_code)
924 const int max_file_size = 1 << 20; /* 1MB */
925 int error_code = 0;
926 char *buf = NULL;
927 char *dir = NULL;
928 const char *slash;
929 struct stat st;
930 int fd;
931 ssize_t len;
932 static struct strbuf realpath = STRBUF_INIT;
934 if (stat(path, &st)) {
935 /* NEEDSWORK: discern between ENOENT vs other errors */
936 error_code = READ_GITFILE_ERR_STAT_FAILED;
937 goto cleanup_return;
939 if (!S_ISREG(st.st_mode)) {
940 error_code = READ_GITFILE_ERR_NOT_A_FILE;
941 goto cleanup_return;
943 if (st.st_size > max_file_size) {
944 error_code = READ_GITFILE_ERR_TOO_LARGE;
945 goto cleanup_return;
947 fd = open(path, O_RDONLY);
948 if (fd < 0) {
949 error_code = READ_GITFILE_ERR_OPEN_FAILED;
950 goto cleanup_return;
952 buf = xmallocz(st.st_size);
953 len = read_in_full(fd, buf, st.st_size);
954 close(fd);
955 if (len != st.st_size) {
956 error_code = READ_GITFILE_ERR_READ_FAILED;
957 goto cleanup_return;
959 if (!starts_with(buf, "gitdir: ")) {
960 error_code = READ_GITFILE_ERR_INVALID_FORMAT;
961 goto cleanup_return;
963 while (buf[len - 1] == '\n' || buf[len - 1] == '\r')
964 len--;
965 if (len < 9) {
966 error_code = READ_GITFILE_ERR_NO_PATH;
967 goto cleanup_return;
969 buf[len] = '\0';
970 dir = buf + 8;
972 if (!is_absolute_path(dir) && (slash = strrchr(path, '/'))) {
973 size_t pathlen = slash+1 - path;
974 dir = xstrfmt("%.*s%.*s", (int)pathlen, path,
975 (int)(len - 8), buf + 8);
976 free(buf);
977 buf = dir;
979 if (!is_git_directory(dir)) {
980 error_code = READ_GITFILE_ERR_NOT_A_REPO;
981 goto cleanup_return;
984 strbuf_realpath(&realpath, dir, 1);
985 path = realpath.buf;
987 cleanup_return:
988 if (return_error_code)
989 *return_error_code = error_code;
990 else if (error_code)
991 read_gitfile_error_die(error_code, path, dir);
993 free(buf);
994 return error_code ? NULL : path;
997 static const char *setup_explicit_git_dir(const char *gitdirenv,
998 struct strbuf *cwd,
999 struct repository_format *repo_fmt,
1000 int *nongit_ok)
1002 const char *work_tree_env = getenv(GIT_WORK_TREE_ENVIRONMENT);
1003 const char *worktree;
1004 char *gitfile;
1005 int offset;
1007 if (PATH_MAX - 40 < strlen(gitdirenv))
1008 die(_("'$%s' too big"), GIT_DIR_ENVIRONMENT);
1010 gitfile = (char*)read_gitfile(gitdirenv);
1011 if (gitfile) {
1012 gitfile = xstrdup(gitfile);
1013 gitdirenv = gitfile;
1016 if (!is_git_directory(gitdirenv)) {
1017 if (nongit_ok) {
1018 *nongit_ok = 1;
1019 free(gitfile);
1020 return NULL;
1022 die(_("not a git repository: '%s'"), gitdirenv);
1025 if (check_repository_format_gently(gitdirenv, repo_fmt, nongit_ok)) {
1026 free(gitfile);
1027 return NULL;
1030 /* #3, #7, #11, #15, #19, #23, #27, #31 (see t1510) */
1031 if (work_tree_env)
1032 set_git_work_tree(work_tree_env);
1033 else if (is_bare_repository_cfg > 0) {
1034 if (git_work_tree_cfg) {
1035 /* #22.2, #30 */
1036 warning("core.bare and core.worktree do not make sense");
1037 work_tree_config_is_bogus = 1;
1040 /* #18, #26 */
1041 set_git_dir(gitdirenv, 0);
1042 free(gitfile);
1043 return NULL;
1045 else if (git_work_tree_cfg) { /* #6, #14 */
1046 if (is_absolute_path(git_work_tree_cfg))
1047 set_git_work_tree(git_work_tree_cfg);
1048 else {
1049 char *core_worktree;
1050 if (chdir(gitdirenv))
1051 die_errno(_("cannot chdir to '%s'"), gitdirenv);
1052 if (chdir(git_work_tree_cfg))
1053 die_errno(_("cannot chdir to '%s'"), git_work_tree_cfg);
1054 core_worktree = xgetcwd();
1055 if (chdir(cwd->buf))
1056 die_errno(_("cannot come back to cwd"));
1057 set_git_work_tree(core_worktree);
1058 free(core_worktree);
1061 else if (!git_env_bool(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, 1)) {
1062 /* #16d */
1063 set_git_dir(gitdirenv, 0);
1064 free(gitfile);
1065 return NULL;
1067 else /* #2, #10 */
1068 set_git_work_tree(".");
1070 /* set_git_work_tree() must have been called by now */
1071 worktree = repo_get_work_tree(the_repository);
1073 /* both repo_get_work_tree() and cwd are already normalized */
1074 if (!strcmp(cwd->buf, worktree)) { /* cwd == worktree */
1075 set_git_dir(gitdirenv, 0);
1076 free(gitfile);
1077 return NULL;
1080 offset = dir_inside_of(cwd->buf, worktree);
1081 if (offset >= 0) { /* cwd inside worktree? */
1082 set_git_dir(gitdirenv, 1);
1083 if (chdir(worktree))
1084 die_errno(_("cannot chdir to '%s'"), worktree);
1085 strbuf_addch(cwd, '/');
1086 free(gitfile);
1087 return cwd->buf + offset;
1090 /* cwd outside worktree */
1091 set_git_dir(gitdirenv, 0);
1092 free(gitfile);
1093 return NULL;
1096 static const char *setup_discovered_git_dir(const char *gitdir,
1097 struct strbuf *cwd, int offset,
1098 struct repository_format *repo_fmt,
1099 int *nongit_ok)
1101 if (check_repository_format_gently(gitdir, repo_fmt, nongit_ok))
1102 return NULL;
1104 /* --work-tree is set without --git-dir; use discovered one */
1105 if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
1106 char *to_free = NULL;
1107 const char *ret;
1109 if (offset != cwd->len && !is_absolute_path(gitdir))
1110 gitdir = to_free = real_pathdup(gitdir, 1);
1111 if (chdir(cwd->buf))
1112 die_errno(_("cannot come back to cwd"));
1113 ret = setup_explicit_git_dir(gitdir, cwd, repo_fmt, nongit_ok);
1114 free(to_free);
1115 return ret;
1118 /* #16.2, #17.2, #20.2, #21.2, #24, #25, #28, #29 (see t1510) */
1119 if (is_bare_repository_cfg > 0) {
1120 set_git_dir(gitdir, (offset != cwd->len));
1121 if (chdir(cwd->buf))
1122 die_errno(_("cannot come back to cwd"));
1123 return NULL;
1126 /* #0, #1, #5, #8, #9, #12, #13 */
1127 set_git_work_tree(".");
1128 if (strcmp(gitdir, DEFAULT_GIT_DIR_ENVIRONMENT))
1129 set_git_dir(gitdir, 0);
1130 inside_git_dir = 0;
1131 inside_work_tree = 1;
1132 if (offset >= cwd->len)
1133 return NULL;
1135 /* Make "offset" point past the '/' (already the case for root dirs) */
1136 if (offset != offset_1st_component(cwd->buf))
1137 offset++;
1138 /* Add a '/' at the end */
1139 strbuf_addch(cwd, '/');
1140 return cwd->buf + offset;
1143 /* #16.1, #17.1, #20.1, #21.1, #22.1 (see t1510) */
1144 static const char *setup_bare_git_dir(struct strbuf *cwd, int offset,
1145 struct repository_format *repo_fmt,
1146 int *nongit_ok)
1148 int root_len;
1150 if (check_repository_format_gently(".", repo_fmt, nongit_ok))
1151 return NULL;
1153 setenv(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, "0", 1);
1155 /* --work-tree is set without --git-dir; use discovered one */
1156 if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
1157 static const char *gitdir;
1159 gitdir = offset == cwd->len ? "." : xmemdupz(cwd->buf, offset);
1160 if (chdir(cwd->buf))
1161 die_errno(_("cannot come back to cwd"));
1162 return setup_explicit_git_dir(gitdir, cwd, repo_fmt, nongit_ok);
1165 inside_git_dir = 1;
1166 inside_work_tree = 0;
1167 if (offset != cwd->len) {
1168 if (chdir(cwd->buf))
1169 die_errno(_("cannot come back to cwd"));
1170 root_len = offset_1st_component(cwd->buf);
1171 strbuf_setlen(cwd, offset > root_len ? offset : root_len);
1172 set_git_dir(cwd->buf, 0);
1174 else
1175 set_git_dir(".", 0);
1176 return NULL;
1179 static dev_t get_device_or_die(const char *path, const char *prefix, int prefix_len)
1181 struct stat buf;
1182 if (stat(path, &buf)) {
1183 die_errno(_("failed to stat '%*s%s%s'"),
1184 prefix_len,
1185 prefix ? prefix : "",
1186 prefix ? "/" : "", path);
1188 return buf.st_dev;
1192 * A "string_list_each_func_t" function that canonicalizes an entry
1193 * from GIT_CEILING_DIRECTORIES using real_pathdup(), or
1194 * discards it if unusable. The presence of an empty entry in
1195 * GIT_CEILING_DIRECTORIES turns off canonicalization for all
1196 * subsequent entries.
1198 static int canonicalize_ceiling_entry(struct string_list_item *item,
1199 void *cb_data)
1201 int *empty_entry_found = cb_data;
1202 char *ceil = item->string;
1204 if (!*ceil) {
1205 *empty_entry_found = 1;
1206 return 0;
1207 } else if (!is_absolute_path(ceil)) {
1208 return 0;
1209 } else if (*empty_entry_found) {
1210 /* Keep entry but do not canonicalize it */
1211 return 1;
1212 } else {
1213 char *real_path = real_pathdup(ceil, 0);
1214 if (!real_path) {
1215 return 0;
1217 free(item->string);
1218 item->string = real_path;
1219 return 1;
1223 struct safe_directory_data {
1224 char *path;
1225 int is_safe;
1228 static int safe_directory_cb(const char *key, const char *value,
1229 const struct config_context *ctx UNUSED, void *d)
1231 struct safe_directory_data *data = d;
1233 if (strcmp(key, "safe.directory"))
1234 return 0;
1236 if (!value || !*value) {
1237 data->is_safe = 0;
1238 } else if (!strcmp(value, "*")) {
1239 data->is_safe = 1;
1240 } else {
1241 char *allowed = NULL;
1243 if (!git_config_pathname(&allowed, key, value)) {
1244 char *normalized = NULL;
1247 * Setting safe.directory to a non-absolute path
1248 * makes little sense---it won't be relative to
1249 * the configuration file the item is defined in.
1250 * Except for ".", which means "if we are at the top
1251 * level of a repository, then it is OK", which is
1252 * slightly tighter than "*" that allows discovery.
1254 if (!is_absolute_path(allowed) && strcmp(allowed, ".")) {
1255 warning(_("safe.directory '%s' not absolute"),
1256 allowed);
1257 goto next;
1261 * A .gitconfig in $HOME may be shared across
1262 * different machines and safe.directory entries
1263 * may or may not exist as paths on all of these
1264 * machines. In other words, it is not a warning
1265 * worthy event when there is no such path on this
1266 * machine---the entry may be useful elsewhere.
1268 normalized = real_pathdup(allowed, 0);
1269 if (!normalized)
1270 goto next;
1272 if (ends_with(normalized, "/*")) {
1273 size_t len = strlen(normalized);
1274 if (!fspathncmp(normalized, data->path, len - 1))
1275 data->is_safe = 1;
1276 } else if (!fspathcmp(data->path, normalized)) {
1277 data->is_safe = 1;
1279 next:
1280 free(normalized);
1281 free(allowed);
1285 return 0;
1289 * Check if a repository is safe, by verifying the ownership of the
1290 * worktree (if any), the git directory, and the gitfile (if any).
1292 * Exemptions for known-safe repositories can be added via `safe.directory`
1293 * config settings; for non-bare repositories, their worktree needs to be
1294 * added, for bare ones their git directory.
1296 static int ensure_valid_ownership(const char *gitfile,
1297 const char *worktree, const char *gitdir,
1298 struct strbuf *report)
1300 struct safe_directory_data data = { 0 };
1302 if (!git_env_bool("GIT_TEST_ASSUME_DIFFERENT_OWNER", 0) &&
1303 (!gitfile || is_path_owned_by_current_user(gitfile, report)) &&
1304 (!worktree || is_path_owned_by_current_user(worktree, report)) &&
1305 (!gitdir || is_path_owned_by_current_user(gitdir, report)))
1306 return 1;
1309 * normalize the data.path for comparison with normalized paths
1310 * that come from the configuration file. The path is unsafe
1311 * if it cannot be normalized.
1313 data.path = real_pathdup(worktree ? worktree : gitdir, 0);
1314 if (!data.path)
1315 return 0;
1318 * data.path is the "path" that identifies the repository and it is
1319 * constant regardless of what failed above. data.is_safe should be
1320 * initialized to false, and might be changed by the callback.
1322 git_protected_config(safe_directory_cb, &data);
1324 free(data.path);
1325 return data.is_safe;
1328 void die_upon_dubious_ownership(const char *gitfile, const char *worktree,
1329 const char *gitdir)
1331 struct strbuf report = STRBUF_INIT, quoted = STRBUF_INIT;
1332 const char *path;
1334 if (ensure_valid_ownership(gitfile, worktree, gitdir, &report))
1335 return;
1337 strbuf_complete(&report, '\n');
1338 path = gitfile ? gitfile : gitdir;
1339 sq_quote_buf_pretty(&quoted, path);
1341 die(_("detected dubious ownership in repository at '%s'\n"
1342 "%s"
1343 "To add an exception for this directory, call:\n"
1344 "\n"
1345 "\tgit config --global --add safe.directory %s"),
1346 path, report.buf, quoted.buf);
1349 static int allowed_bare_repo_cb(const char *key, const char *value,
1350 const struct config_context *ctx UNUSED,
1351 void *d)
1353 enum allowed_bare_repo *allowed_bare_repo = d;
1355 if (strcasecmp(key, "safe.bareRepository"))
1356 return 0;
1358 if (!strcmp(value, "explicit")) {
1359 *allowed_bare_repo = ALLOWED_BARE_REPO_EXPLICIT;
1360 return 0;
1362 if (!strcmp(value, "all")) {
1363 *allowed_bare_repo = ALLOWED_BARE_REPO_ALL;
1364 return 0;
1366 return -1;
1369 static enum allowed_bare_repo get_allowed_bare_repo(void)
1371 enum allowed_bare_repo result = ALLOWED_BARE_REPO_ALL;
1372 git_protected_config(allowed_bare_repo_cb, &result);
1373 return result;
1376 static const char *allowed_bare_repo_to_string(
1377 enum allowed_bare_repo allowed_bare_repo)
1379 switch (allowed_bare_repo) {
1380 case ALLOWED_BARE_REPO_EXPLICIT:
1381 return "explicit";
1382 case ALLOWED_BARE_REPO_ALL:
1383 return "all";
1384 default:
1385 BUG("invalid allowed_bare_repo %d",
1386 allowed_bare_repo);
1388 return NULL;
1391 static int is_implicit_bare_repo(const char *path)
1394 * what we found is a ".git" directory at the root of
1395 * the working tree.
1397 if (ends_with_path_components(path, ".git"))
1398 return 1;
1401 * we are inside $GIT_DIR of a secondary worktree of a
1402 * non-bare repository.
1404 if (strstr(path, "/.git/worktrees/"))
1405 return 1;
1408 * we are inside $GIT_DIR of a worktree of a non-embedded
1409 * submodule, whose superproject is not a bare repository.
1411 if (strstr(path, "/.git/modules/"))
1412 return 1;
1414 return 0;
1418 * We cannot decide in this function whether we are in the work tree or
1419 * not, since the config can only be read _after_ this function was called.
1421 * Also, we avoid changing any global state (such as the current working
1422 * directory) to allow early callers.
1424 * The directory where the search should start needs to be passed in via the
1425 * `dir` parameter; upon return, the `dir` buffer will contain the path of
1426 * the directory where the search ended, and `gitdir` will contain the path of
1427 * the discovered .git/ directory, if any. If `gitdir` is not absolute, it
1428 * is relative to `dir` (i.e. *not* necessarily the cwd).
1430 static enum discovery_result setup_git_directory_gently_1(struct strbuf *dir,
1431 struct strbuf *gitdir,
1432 struct strbuf *report,
1433 int die_on_error)
1435 const char *env_ceiling_dirs = getenv(CEILING_DIRECTORIES_ENVIRONMENT);
1436 struct string_list ceiling_dirs = STRING_LIST_INIT_DUP;
1437 const char *gitdirenv;
1438 int ceil_offset = -1, min_offset = offset_1st_component(dir->buf);
1439 dev_t current_device = 0;
1440 int one_filesystem = 1;
1443 * If GIT_DIR is set explicitly, we're not going
1444 * to do any discovery, but we still do repository
1445 * validation.
1447 gitdirenv = getenv(GIT_DIR_ENVIRONMENT);
1448 if (gitdirenv) {
1449 strbuf_addstr(gitdir, gitdirenv);
1450 return GIT_DIR_EXPLICIT;
1453 if (env_ceiling_dirs) {
1454 int empty_entry_found = 0;
1456 string_list_split(&ceiling_dirs, env_ceiling_dirs, PATH_SEP, -1);
1457 filter_string_list(&ceiling_dirs, 0,
1458 canonicalize_ceiling_entry, &empty_entry_found);
1459 ceil_offset = longest_ancestor_length(dir->buf, &ceiling_dirs);
1460 string_list_clear(&ceiling_dirs, 0);
1463 if (ceil_offset < 0)
1464 ceil_offset = min_offset - 2;
1466 if (min_offset && min_offset == dir->len &&
1467 !is_dir_sep(dir->buf[min_offset - 1])) {
1468 strbuf_addch(dir, '/');
1469 min_offset++;
1473 * Test in the following order (relative to the dir):
1474 * - .git (file containing "gitdir: <path>")
1475 * - .git/
1476 * - ./ (bare)
1477 * - ../.git
1478 * - ../.git/
1479 * - ../ (bare)
1480 * - ../../.git
1481 * etc.
1483 one_filesystem = !git_env_bool("GIT_DISCOVERY_ACROSS_FILESYSTEM", 0);
1484 if (one_filesystem)
1485 current_device = get_device_or_die(dir->buf, NULL, 0);
1486 for (;;) {
1487 int offset = dir->len, error_code = 0;
1488 char *gitdir_path = NULL;
1489 char *gitfile = NULL;
1491 if (offset > min_offset)
1492 strbuf_addch(dir, '/');
1493 strbuf_addstr(dir, DEFAULT_GIT_DIR_ENVIRONMENT);
1494 gitdirenv = read_gitfile_gently(dir->buf, die_on_error ?
1495 NULL : &error_code);
1496 if (!gitdirenv) {
1497 if (die_on_error ||
1498 error_code == READ_GITFILE_ERR_NOT_A_FILE) {
1499 /* NEEDSWORK: fail if .git is not file nor dir */
1500 if (is_git_directory(dir->buf)) {
1501 gitdirenv = DEFAULT_GIT_DIR_ENVIRONMENT;
1502 gitdir_path = xstrdup(dir->buf);
1504 } else if (error_code != READ_GITFILE_ERR_STAT_FAILED)
1505 return GIT_DIR_INVALID_GITFILE;
1506 } else
1507 gitfile = xstrdup(dir->buf);
1509 * Earlier, we tentatively added DEFAULT_GIT_DIR_ENVIRONMENT
1510 * to check that directory for a repository.
1511 * Now trim that tentative addition away, because we want to
1512 * focus on the real directory we are in.
1514 strbuf_setlen(dir, offset);
1515 if (gitdirenv) {
1516 enum discovery_result ret;
1517 const char *gitdir_candidate =
1518 gitdir_path ? gitdir_path : gitdirenv;
1520 if (ensure_valid_ownership(gitfile, dir->buf,
1521 gitdir_candidate, report)) {
1522 strbuf_addstr(gitdir, gitdirenv);
1523 ret = GIT_DIR_DISCOVERED;
1524 } else
1525 ret = GIT_DIR_INVALID_OWNERSHIP;
1528 * Earlier, during discovery, we might have allocated
1529 * string copies for gitdir_path or gitfile so make
1530 * sure we don't leak by freeing them now, before
1531 * leaving the loop and function.
1533 * Note: gitdirenv will be non-NULL whenever these are
1534 * allocated, therefore we need not take care of releasing
1535 * them outside of this conditional block.
1537 free(gitdir_path);
1538 free(gitfile);
1540 return ret;
1543 if (is_git_directory(dir->buf)) {
1544 trace2_data_string("setup", NULL, "implicit-bare-repository", dir->buf);
1545 if (get_allowed_bare_repo() == ALLOWED_BARE_REPO_EXPLICIT &&
1546 !is_implicit_bare_repo(dir->buf))
1547 return GIT_DIR_DISALLOWED_BARE;
1548 if (!ensure_valid_ownership(NULL, NULL, dir->buf, report))
1549 return GIT_DIR_INVALID_OWNERSHIP;
1550 strbuf_addstr(gitdir, ".");
1551 return GIT_DIR_BARE;
1554 if (offset <= min_offset)
1555 return GIT_DIR_HIT_CEILING;
1557 while (--offset > ceil_offset && !is_dir_sep(dir->buf[offset]))
1558 ; /* continue */
1559 if (offset <= ceil_offset)
1560 return GIT_DIR_HIT_CEILING;
1562 strbuf_setlen(dir, offset > min_offset ? offset : min_offset);
1563 if (one_filesystem &&
1564 current_device != get_device_or_die(dir->buf, NULL, offset))
1565 return GIT_DIR_HIT_MOUNT_POINT;
1569 enum discovery_result discover_git_directory_reason(struct strbuf *commondir,
1570 struct strbuf *gitdir)
1572 struct strbuf dir = STRBUF_INIT, err = STRBUF_INIT;
1573 size_t gitdir_offset = gitdir->len, cwd_len;
1574 size_t commondir_offset = commondir->len;
1575 struct repository_format candidate = REPOSITORY_FORMAT_INIT;
1576 enum discovery_result result;
1578 if (strbuf_getcwd(&dir))
1579 return GIT_DIR_CWD_FAILURE;
1581 cwd_len = dir.len;
1582 result = setup_git_directory_gently_1(&dir, gitdir, NULL, 0);
1583 if (result <= 0) {
1584 strbuf_release(&dir);
1585 return result;
1589 * The returned gitdir is relative to dir, and if dir does not reflect
1590 * the current working directory, we simply make the gitdir absolute.
1592 if (dir.len < cwd_len && !is_absolute_path(gitdir->buf + gitdir_offset)) {
1593 /* Avoid a trailing "/." */
1594 if (!strcmp(".", gitdir->buf + gitdir_offset))
1595 strbuf_setlen(gitdir, gitdir_offset);
1596 else
1597 strbuf_addch(&dir, '/');
1598 strbuf_insert(gitdir, gitdir_offset, dir.buf, dir.len);
1601 get_common_dir(commondir, gitdir->buf + gitdir_offset);
1603 strbuf_reset(&dir);
1604 strbuf_addf(&dir, "%s/config", commondir->buf + commondir_offset);
1605 read_repository_format(&candidate, dir.buf);
1606 strbuf_release(&dir);
1608 if (verify_repository_format(&candidate, &err) < 0) {
1609 warning("ignoring git dir '%s': %s",
1610 gitdir->buf + gitdir_offset, err.buf);
1611 strbuf_release(&err);
1612 strbuf_setlen(commondir, commondir_offset);
1613 strbuf_setlen(gitdir, gitdir_offset);
1614 clear_repository_format(&candidate);
1615 return GIT_DIR_INVALID_FORMAT;
1618 clear_repository_format(&candidate);
1619 return result;
1622 void setup_git_env(const char *git_dir)
1624 char *git_replace_ref_base;
1625 const char *shallow_file;
1626 const char *replace_ref_base;
1627 struct set_gitdir_args args = { NULL };
1628 struct strvec to_free = STRVEC_INIT;
1630 args.commondir = getenv_safe(&to_free, GIT_COMMON_DIR_ENVIRONMENT);
1631 args.object_dir = getenv_safe(&to_free, DB_ENVIRONMENT);
1632 args.graft_file = getenv_safe(&to_free, GRAFT_ENVIRONMENT);
1633 args.index_file = getenv_safe(&to_free, INDEX_ENVIRONMENT);
1634 args.alternate_db = getenv_safe(&to_free, ALTERNATE_DB_ENVIRONMENT);
1635 if (getenv(GIT_QUARANTINE_ENVIRONMENT)) {
1636 args.disable_ref_updates = 1;
1639 repo_set_gitdir(the_repository, git_dir, &args);
1640 strvec_clear(&to_free);
1642 if (getenv(NO_REPLACE_OBJECTS_ENVIRONMENT))
1643 disable_replace_refs();
1644 replace_ref_base = getenv(GIT_REPLACE_REF_BASE_ENVIRONMENT);
1645 git_replace_ref_base = xstrdup(replace_ref_base ? replace_ref_base
1646 : "refs/replace/");
1647 update_ref_namespace(NAMESPACE_REPLACE, git_replace_ref_base);
1649 shallow_file = getenv(GIT_SHALLOW_FILE_ENVIRONMENT);
1650 if (shallow_file)
1651 set_alternate_shallow_file(the_repository, shallow_file, 0);
1653 if (git_env_bool(NO_LAZY_FETCH_ENVIRONMENT, 0))
1654 fetch_if_missing = 0;
1657 static void set_git_dir_1(const char *path)
1659 xsetenv(GIT_DIR_ENVIRONMENT, path, 1);
1660 setup_git_env(path);
1663 static void update_relative_gitdir(const char *name UNUSED,
1664 const char *old_cwd,
1665 const char *new_cwd,
1666 void *data UNUSED)
1668 char *path = reparent_relative_path(old_cwd, new_cwd,
1669 repo_get_git_dir(the_repository));
1670 struct tmp_objdir *tmp_objdir = tmp_objdir_unapply_primary_odb();
1672 trace_printf_key(&trace_setup_key,
1673 "setup: move $GIT_DIR to '%s'",
1674 path);
1675 set_git_dir_1(path);
1676 if (tmp_objdir)
1677 tmp_objdir_reapply_primary_odb(tmp_objdir, old_cwd, new_cwd);
1678 free(path);
1681 void set_git_dir(const char *path, int make_realpath)
1683 struct strbuf realpath = STRBUF_INIT;
1685 if (make_realpath) {
1686 strbuf_realpath(&realpath, path, 1);
1687 path = realpath.buf;
1690 set_git_dir_1(path);
1691 if (!is_absolute_path(path))
1692 chdir_notify_register(NULL, update_relative_gitdir, NULL);
1694 strbuf_release(&realpath);
1697 static int git_work_tree_initialized;
1700 * Note. This works only before you used a work tree. This was added
1701 * primarily to support git-clone to work in a new repository it just
1702 * created, and is not meant to flip between different work trees.
1704 void set_git_work_tree(const char *new_work_tree)
1706 if (git_work_tree_initialized) {
1707 struct strbuf realpath = STRBUF_INIT;
1709 strbuf_realpath(&realpath, new_work_tree, 1);
1710 new_work_tree = realpath.buf;
1711 if (strcmp(new_work_tree, the_repository->worktree))
1712 die("internal error: work tree has already been set\n"
1713 "Current worktree: %s\nNew worktree: %s",
1714 the_repository->worktree, new_work_tree);
1715 strbuf_release(&realpath);
1716 return;
1718 git_work_tree_initialized = 1;
1719 repo_set_worktree(the_repository, new_work_tree);
1722 const char *setup_git_directory_gently(int *nongit_ok)
1724 static struct strbuf cwd = STRBUF_INIT;
1725 struct strbuf dir = STRBUF_INIT, gitdir = STRBUF_INIT, report = STRBUF_INIT;
1726 const char *prefix = NULL;
1727 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
1730 * We may have read an incomplete configuration before
1731 * setting-up the git directory. If so, clear the cache so
1732 * that the next queries to the configuration reload complete
1733 * configuration (including the per-repo config file that we
1734 * ignored previously).
1736 git_config_clear();
1739 * Let's assume that we are in a git repository.
1740 * If it turns out later that we are somewhere else, the value will be
1741 * updated accordingly.
1743 if (nongit_ok)
1744 *nongit_ok = 0;
1746 if (strbuf_getcwd(&cwd))
1747 die_errno(_("Unable to read current working directory"));
1748 strbuf_addbuf(&dir, &cwd);
1750 switch (setup_git_directory_gently_1(&dir, &gitdir, &report, 1)) {
1751 case GIT_DIR_EXPLICIT:
1752 prefix = setup_explicit_git_dir(gitdir.buf, &cwd, &repo_fmt, nongit_ok);
1753 break;
1754 case GIT_DIR_DISCOVERED:
1755 if (dir.len < cwd.len && chdir(dir.buf))
1756 die(_("cannot change to '%s'"), dir.buf);
1757 prefix = setup_discovered_git_dir(gitdir.buf, &cwd, dir.len,
1758 &repo_fmt, nongit_ok);
1759 break;
1760 case GIT_DIR_BARE:
1761 if (dir.len < cwd.len && chdir(dir.buf))
1762 die(_("cannot change to '%s'"), dir.buf);
1763 prefix = setup_bare_git_dir(&cwd, dir.len, &repo_fmt, nongit_ok);
1764 break;
1765 case GIT_DIR_HIT_CEILING:
1766 if (!nongit_ok)
1767 die(_("not a git repository (or any of the parent directories): %s"),
1768 DEFAULT_GIT_DIR_ENVIRONMENT);
1769 *nongit_ok = 1;
1770 break;
1771 case GIT_DIR_HIT_MOUNT_POINT:
1772 if (!nongit_ok)
1773 die(_("not a git repository (or any parent up to mount point %s)\n"
1774 "Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set)."),
1775 dir.buf);
1776 *nongit_ok = 1;
1777 break;
1778 case GIT_DIR_INVALID_OWNERSHIP:
1779 if (!nongit_ok) {
1780 struct strbuf quoted = STRBUF_INIT;
1782 strbuf_complete(&report, '\n');
1783 sq_quote_buf_pretty(&quoted, dir.buf);
1784 die(_("detected dubious ownership in repository at '%s'\n"
1785 "%s"
1786 "To add an exception for this directory, call:\n"
1787 "\n"
1788 "\tgit config --global --add safe.directory %s"),
1789 dir.buf, report.buf, quoted.buf);
1791 *nongit_ok = 1;
1792 break;
1793 case GIT_DIR_DISALLOWED_BARE:
1794 if (!nongit_ok) {
1795 die(_("cannot use bare repository '%s' (safe.bareRepository is '%s')"),
1796 dir.buf,
1797 allowed_bare_repo_to_string(get_allowed_bare_repo()));
1799 *nongit_ok = 1;
1800 break;
1801 case GIT_DIR_CWD_FAILURE:
1802 case GIT_DIR_INVALID_FORMAT:
1804 * As a safeguard against setup_git_directory_gently_1 returning
1805 * these values, fallthrough to BUG. Otherwise it is possible to
1806 * set startup_info->have_repository to 1 when we did nothing to
1807 * find a repository.
1809 default:
1810 BUG("unhandled setup_git_directory_gently_1() result");
1814 * At this point, nongit_ok is stable. If it is non-NULL and points
1815 * to a non-zero value, then this means that we haven't found a
1816 * repository and that the caller expects startup_info to reflect
1817 * this.
1819 * Regardless of the state of nongit_ok, startup_info->prefix and
1820 * the GIT_PREFIX environment variable must always match. For details
1821 * see Documentation/config/alias.txt.
1823 if (nongit_ok && *nongit_ok)
1824 startup_info->have_repository = 0;
1825 else
1826 startup_info->have_repository = 1;
1829 * Not all paths through the setup code will call 'set_git_dir()' (which
1830 * directly sets up the environment) so in order to guarantee that the
1831 * environment is in a consistent state after setup, explicitly setup
1832 * the environment if we have a repository.
1834 * NEEDSWORK: currently we allow bogus GIT_DIR values to be set in some
1835 * code paths so we also need to explicitly setup the environment if
1836 * the user has set GIT_DIR. It may be beneficial to disallow bogus
1837 * GIT_DIR values at some point in the future.
1839 if (/* GIT_DIR_EXPLICIT, GIT_DIR_DISCOVERED, GIT_DIR_BARE */
1840 startup_info->have_repository ||
1841 /* GIT_DIR_EXPLICIT */
1842 getenv(GIT_DIR_ENVIRONMENT)) {
1843 if (!the_repository->gitdir) {
1844 const char *gitdir = getenv(GIT_DIR_ENVIRONMENT);
1845 if (!gitdir)
1846 gitdir = DEFAULT_GIT_DIR_ENVIRONMENT;
1847 setup_git_env(gitdir);
1849 if (startup_info->have_repository) {
1850 repo_set_hash_algo(the_repository, repo_fmt.hash_algo);
1851 repo_set_compat_hash_algo(the_repository,
1852 repo_fmt.compat_hash_algo);
1853 repo_set_ref_storage_format(the_repository,
1854 repo_fmt.ref_storage_format);
1855 the_repository->repository_format_worktree_config =
1856 repo_fmt.worktree_config;
1857 /* take ownership of repo_fmt.partial_clone */
1858 the_repository->repository_format_partial_clone =
1859 repo_fmt.partial_clone;
1860 repo_fmt.partial_clone = NULL;
1864 * Since precompose_string_if_needed() needs to look at
1865 * the core.precomposeunicode configuration, this
1866 * has to happen after the above block that finds
1867 * out where the repository is, i.e. a preparation
1868 * for calling git_config_get_bool().
1870 if (prefix) {
1871 prefix = precompose_string_if_needed(prefix);
1872 startup_info->prefix = prefix;
1873 setenv(GIT_PREFIX_ENVIRONMENT, prefix, 1);
1874 } else {
1875 startup_info->prefix = NULL;
1876 setenv(GIT_PREFIX_ENVIRONMENT, "", 1);
1879 setup_original_cwd();
1881 strbuf_release(&dir);
1882 strbuf_release(&gitdir);
1883 strbuf_release(&report);
1884 clear_repository_format(&repo_fmt);
1886 return prefix;
1889 int git_config_perm(const char *var, const char *value)
1891 int i;
1892 char *endptr;
1894 if (!value)
1895 return PERM_GROUP;
1897 if (!strcmp(value, "umask"))
1898 return PERM_UMASK;
1899 if (!strcmp(value, "group"))
1900 return PERM_GROUP;
1901 if (!strcmp(value, "all") ||
1902 !strcmp(value, "world") ||
1903 !strcmp(value, "everybody"))
1904 return PERM_EVERYBODY;
1906 /* Parse octal numbers */
1907 i = strtol(value, &endptr, 8);
1909 /* If not an octal number, maybe true/false? */
1910 if (*endptr != 0)
1911 return git_config_bool(var, value) ? PERM_GROUP : PERM_UMASK;
1914 * Treat values 0, 1 and 2 as compatibility cases, otherwise it is
1915 * a chmod value to restrict to.
1917 switch (i) {
1918 case PERM_UMASK: /* 0 */
1919 return PERM_UMASK;
1920 case OLD_PERM_GROUP: /* 1 */
1921 return PERM_GROUP;
1922 case OLD_PERM_EVERYBODY: /* 2 */
1923 return PERM_EVERYBODY;
1926 /* A filemode value was given: 0xxx */
1928 if ((i & 0600) != 0600)
1929 die(_("problem with core.sharedRepository filemode value "
1930 "(0%.3o).\nThe owner of files must always have "
1931 "read and write permissions."), i);
1934 * Mask filemode value. Others can not get write permission.
1935 * x flags for directories are handled separately.
1937 return -(i & 0666);
1940 void check_repository_format(struct repository_format *fmt)
1942 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
1943 if (!fmt)
1944 fmt = &repo_fmt;
1945 check_repository_format_gently(repo_get_git_dir(the_repository), fmt, NULL);
1946 startup_info->have_repository = 1;
1947 repo_set_hash_algo(the_repository, fmt->hash_algo);
1948 repo_set_compat_hash_algo(the_repository, fmt->compat_hash_algo);
1949 repo_set_ref_storage_format(the_repository,
1950 fmt->ref_storage_format);
1951 the_repository->repository_format_worktree_config =
1952 fmt->worktree_config;
1953 the_repository->repository_format_partial_clone =
1954 xstrdup_or_null(fmt->partial_clone);
1955 clear_repository_format(&repo_fmt);
1959 * Returns the "prefix", a path to the current working directory
1960 * relative to the work tree root, or NULL, if the current working
1961 * directory is not a strict subdirectory of the work tree root. The
1962 * prefix always ends with a '/' character.
1964 const char *setup_git_directory(void)
1966 return setup_git_directory_gently(NULL);
1969 const char *resolve_gitdir_gently(const char *suspect, int *return_error_code)
1971 if (is_git_directory(suspect))
1972 return suspect;
1973 return read_gitfile_gently(suspect, return_error_code);
1976 /* if any standard file descriptor is missing open it to /dev/null */
1977 void sanitize_stdfds(void)
1979 int fd = xopen("/dev/null", O_RDWR);
1980 while (fd < 2)
1981 fd = xdup(fd);
1982 if (fd > 2)
1983 close(fd);
1986 int daemonize(void)
1988 #ifdef NO_POSIX_GOODIES
1989 errno = ENOSYS;
1990 return -1;
1991 #else
1992 switch (fork()) {
1993 case 0:
1994 break;
1995 case -1:
1996 die_errno(_("fork failed"));
1997 default:
1998 exit(0);
2000 if (setsid() == -1)
2001 die_errno(_("setsid failed"));
2002 close(0);
2003 close(1);
2004 close(2);
2005 sanitize_stdfds();
2006 return 0;
2007 #endif
2010 struct template_dir_cb_data {
2011 char *path;
2012 int initialized;
2015 static int template_dir_cb(const char *key, const char *value,
2016 const struct config_context *ctx UNUSED, void *d)
2018 struct template_dir_cb_data *data = d;
2020 if (strcmp(key, "init.templatedir"))
2021 return 0;
2023 if (!value) {
2024 data->path = NULL;
2025 } else {
2026 char *path = NULL;
2028 FREE_AND_NULL(data->path);
2029 if (!git_config_pathname(&path, key, value))
2030 data->path = path ? path : xstrdup(value);
2033 return 0;
2036 const char *get_template_dir(const char *option_template)
2038 const char *template_dir = option_template;
2040 if (!template_dir)
2041 template_dir = getenv(TEMPLATE_DIR_ENVIRONMENT);
2042 if (!template_dir) {
2043 static struct template_dir_cb_data data;
2045 if (!data.initialized) {
2046 git_protected_config(template_dir_cb, &data);
2047 data.initialized = 1;
2049 template_dir = data.path;
2051 if (!template_dir) {
2052 static char *dir;
2054 if (!dir)
2055 dir = system_path(DEFAULT_GIT_TEMPLATE_DIR);
2056 template_dir = dir;
2058 return template_dir;
2061 #ifdef NO_TRUSTABLE_FILEMODE
2062 #define TEST_FILEMODE 0
2063 #else
2064 #define TEST_FILEMODE 1
2065 #endif
2067 #define GIT_DEFAULT_HASH_ENVIRONMENT "GIT_DEFAULT_HASH"
2069 static void copy_templates_1(struct strbuf *path, struct strbuf *template_path,
2070 DIR *dir)
2072 size_t path_baselen = path->len;
2073 size_t template_baselen = template_path->len;
2074 struct dirent *de;
2076 /* Note: if ".git/hooks" file exists in the repository being
2077 * re-initialized, /etc/core-git/templates/hooks/update would
2078 * cause "git init" to fail here. I think this is sane but
2079 * it means that the set of templates we ship by default, along
2080 * with the way the namespace under .git/ is organized, should
2081 * be really carefully chosen.
2083 safe_create_dir(path->buf, 1);
2084 while ((de = readdir(dir)) != NULL) {
2085 struct stat st_git, st_template;
2086 int exists = 0;
2088 strbuf_setlen(path, path_baselen);
2089 strbuf_setlen(template_path, template_baselen);
2091 if (de->d_name[0] == '.')
2092 continue;
2093 strbuf_addstr(path, de->d_name);
2094 strbuf_addstr(template_path, de->d_name);
2095 if (lstat(path->buf, &st_git)) {
2096 if (errno != ENOENT)
2097 die_errno(_("cannot stat '%s'"), path->buf);
2099 else
2100 exists = 1;
2102 if (lstat(template_path->buf, &st_template))
2103 die_errno(_("cannot stat template '%s'"), template_path->buf);
2105 if (S_ISDIR(st_template.st_mode)) {
2106 DIR *subdir = opendir(template_path->buf);
2107 if (!subdir)
2108 die_errno(_("cannot opendir '%s'"), template_path->buf);
2109 strbuf_addch(path, '/');
2110 strbuf_addch(template_path, '/');
2111 copy_templates_1(path, template_path, subdir);
2112 closedir(subdir);
2114 else if (exists)
2115 continue;
2116 else if (S_ISLNK(st_template.st_mode)) {
2117 struct strbuf lnk = STRBUF_INIT;
2118 if (strbuf_readlink(&lnk, template_path->buf,
2119 st_template.st_size) < 0)
2120 die_errno(_("cannot readlink '%s'"), template_path->buf);
2121 if (symlink(lnk.buf, path->buf))
2122 die_errno(_("cannot symlink '%s' '%s'"),
2123 lnk.buf, path->buf);
2124 strbuf_release(&lnk);
2126 else if (S_ISREG(st_template.st_mode)) {
2127 if (copy_file(path->buf, template_path->buf, st_template.st_mode))
2128 die_errno(_("cannot copy '%s' to '%s'"),
2129 template_path->buf, path->buf);
2131 else
2132 error(_("ignoring template %s"), template_path->buf);
2136 static void copy_templates(const char *option_template)
2138 const char *template_dir = get_template_dir(option_template);
2139 struct strbuf path = STRBUF_INIT;
2140 struct strbuf template_path = STRBUF_INIT;
2141 size_t template_len;
2142 struct repository_format template_format = REPOSITORY_FORMAT_INIT;
2143 struct strbuf err = STRBUF_INIT;
2144 DIR *dir;
2145 char *to_free = NULL;
2147 if (!template_dir || !*template_dir)
2148 return;
2150 strbuf_addstr(&template_path, template_dir);
2151 strbuf_complete(&template_path, '/');
2152 template_len = template_path.len;
2154 dir = opendir(template_path.buf);
2155 if (!dir) {
2156 warning(_("templates not found in %s"), template_dir);
2157 goto free_return;
2160 /* Make sure that template is from the correct vintage */
2161 strbuf_addstr(&template_path, "config");
2162 read_repository_format(&template_format, template_path.buf);
2163 strbuf_setlen(&template_path, template_len);
2166 * No mention of version at all is OK, but anything else should be
2167 * verified.
2169 if (template_format.version >= 0 &&
2170 verify_repository_format(&template_format, &err) < 0) {
2171 warning(_("not copying templates from '%s': %s"),
2172 template_dir, err.buf);
2173 strbuf_release(&err);
2174 goto close_free_return;
2177 strbuf_addstr(&path, repo_get_common_dir(the_repository));
2178 strbuf_complete(&path, '/');
2179 copy_templates_1(&path, &template_path, dir);
2180 close_free_return:
2181 closedir(dir);
2182 free_return:
2183 free(to_free);
2184 strbuf_release(&path);
2185 strbuf_release(&template_path);
2186 clear_repository_format(&template_format);
2190 * If the git_dir is not directly inside the working tree, then git will not
2191 * find it by default, and we need to set the worktree explicitly.
2193 static int needs_work_tree_config(const char *git_dir, const char *work_tree)
2195 if (!strcmp(work_tree, "/") && !strcmp(git_dir, "/.git"))
2196 return 0;
2197 if (skip_prefix(git_dir, work_tree, &git_dir) &&
2198 !strcmp(git_dir, "/.git"))
2199 return 0;
2200 return 1;
2203 void initialize_repository_version(int hash_algo,
2204 enum ref_storage_format ref_storage_format,
2205 int reinit)
2207 char repo_version_string[10];
2208 int repo_version = GIT_REPO_VERSION;
2211 * Note that we initialize the repository version to 1 when the ref
2212 * storage format is unknown. This is on purpose so that we can add the
2213 * correct object format to the config during git-clone(1). The format
2214 * version will get adjusted by git-clone(1) once it has learned about
2215 * the remote repository's format.
2217 if (hash_algo != GIT_HASH_SHA1 ||
2218 ref_storage_format != REF_STORAGE_FORMAT_FILES)
2219 repo_version = GIT_REPO_VERSION_READ;
2221 /* This forces creation of new config file */
2222 xsnprintf(repo_version_string, sizeof(repo_version_string),
2223 "%d", repo_version);
2224 git_config_set("core.repositoryformatversion", repo_version_string);
2226 if (hash_algo != GIT_HASH_SHA1 && hash_algo != GIT_HASH_UNKNOWN)
2227 git_config_set("extensions.objectformat",
2228 hash_algos[hash_algo].name);
2229 else if (reinit)
2230 git_config_set_gently("extensions.objectformat", NULL);
2232 if (ref_storage_format != REF_STORAGE_FORMAT_FILES)
2233 git_config_set("extensions.refstorage",
2234 ref_storage_format_to_name(ref_storage_format));
2235 else if (reinit)
2236 git_config_set_gently("extensions.refstorage", NULL);
2239 static int is_reinit(void)
2241 struct strbuf buf = STRBUF_INIT;
2242 char junk[2];
2243 int ret;
2245 git_path_buf(&buf, "HEAD");
2246 ret = !access(buf.buf, R_OK) || readlink(buf.buf, junk, sizeof(junk) - 1) != -1;
2247 strbuf_release(&buf);
2248 return ret;
2251 void create_reference_database(enum ref_storage_format ref_storage_format,
2252 const char *initial_branch, int quiet)
2254 struct strbuf err = STRBUF_INIT;
2255 char *to_free = NULL;
2256 int reinit = is_reinit();
2258 repo_set_ref_storage_format(the_repository, ref_storage_format);
2259 if (ref_store_create_on_disk(get_main_ref_store(the_repository), 0, &err))
2260 die("failed to set up refs db: %s", err.buf);
2263 * Point the HEAD symref to the initial branch with if HEAD does
2264 * not yet exist.
2266 if (!reinit) {
2267 char *ref;
2269 if (!initial_branch)
2270 initial_branch = to_free =
2271 repo_default_branch_name(the_repository, quiet);
2273 ref = xstrfmt("refs/heads/%s", initial_branch);
2274 if (check_refname_format(ref, 0) < 0)
2275 die(_("invalid initial branch name: '%s'"),
2276 initial_branch);
2278 if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", ref, NULL) < 0)
2279 exit(1);
2280 free(ref);
2283 if (reinit && initial_branch)
2284 warning(_("re-init: ignored --initial-branch=%s"),
2285 initial_branch);
2287 strbuf_release(&err);
2288 free(to_free);
2291 static int create_default_files(const char *template_path,
2292 const char *original_git_dir,
2293 const struct repository_format *fmt,
2294 int init_shared_repository)
2296 struct stat st1;
2297 struct strbuf buf = STRBUF_INIT;
2298 char *path;
2299 int reinit;
2300 int filemode;
2301 const char *work_tree = repo_get_work_tree(the_repository);
2304 * First copy the templates -- we might have the default
2305 * config file there, in which case we would want to read
2306 * from it after installing.
2308 * Before reading that config, we also need to clear out any cached
2309 * values (since we've just potentially changed what's available on
2310 * disk).
2312 copy_templates(template_path);
2313 git_config_clear();
2314 reset_shared_repository();
2315 git_config(git_default_config, NULL);
2317 reinit = is_reinit();
2320 * We must make sure command-line options continue to override any
2321 * values we might have just re-read from the config.
2323 if (init_shared_repository != -1)
2324 set_shared_repository(init_shared_repository);
2326 is_bare_repository_cfg = !work_tree;
2329 * We would have created the above under user's umask -- under
2330 * shared-repository settings, we would need to fix them up.
2332 if (get_shared_repository()) {
2333 adjust_shared_perm(repo_get_git_dir(the_repository));
2336 initialize_repository_version(fmt->hash_algo, fmt->ref_storage_format, 0);
2338 /* Check filemode trustability */
2339 path = git_path_buf(&buf, "config");
2340 filemode = TEST_FILEMODE;
2341 if (TEST_FILEMODE && !lstat(path, &st1)) {
2342 struct stat st2;
2343 filemode = (!chmod(path, st1.st_mode ^ S_IXUSR) &&
2344 !lstat(path, &st2) &&
2345 st1.st_mode != st2.st_mode &&
2346 !chmod(path, st1.st_mode));
2347 if (filemode && !reinit && (st1.st_mode & S_IXUSR))
2348 filemode = 0;
2350 git_config_set("core.filemode", filemode ? "true" : "false");
2352 if (is_bare_repository())
2353 git_config_set("core.bare", "true");
2354 else {
2355 git_config_set("core.bare", "false");
2356 /* allow template config file to override the default */
2357 if (repo_settings_get_log_all_ref_updates(the_repository) == LOG_REFS_UNSET)
2358 git_config_set("core.logallrefupdates", "true");
2359 if (needs_work_tree_config(original_git_dir, work_tree))
2360 git_config_set("core.worktree", work_tree);
2363 if (!reinit) {
2364 /* Check if symlink is supported in the work tree */
2365 path = git_path_buf(&buf, "tXXXXXX");
2366 if (!close(xmkstemp(path)) &&
2367 !unlink(path) &&
2368 !symlink("testing", path) &&
2369 !lstat(path, &st1) &&
2370 S_ISLNK(st1.st_mode))
2371 unlink(path); /* good */
2372 else
2373 git_config_set("core.symlinks", "false");
2375 /* Check if the filesystem is case-insensitive */
2376 path = git_path_buf(&buf, "CoNfIg");
2377 if (!access(path, F_OK))
2378 git_config_set("core.ignorecase", "true");
2379 probe_utf8_pathname_composition();
2382 strbuf_release(&buf);
2383 return reinit;
2386 static void create_object_directory(void)
2388 struct strbuf path = STRBUF_INIT;
2389 size_t baselen;
2391 strbuf_addstr(&path, repo_get_object_directory(the_repository));
2392 baselen = path.len;
2394 safe_create_dir(path.buf, 1);
2396 strbuf_setlen(&path, baselen);
2397 strbuf_addstr(&path, "/pack");
2398 safe_create_dir(path.buf, 1);
2400 strbuf_setlen(&path, baselen);
2401 strbuf_addstr(&path, "/info");
2402 safe_create_dir(path.buf, 1);
2404 strbuf_release(&path);
2407 static void separate_git_dir(const char *git_dir, const char *git_link)
2409 struct stat st;
2411 if (!stat(git_link, &st)) {
2412 const char *src;
2414 if (S_ISREG(st.st_mode))
2415 src = read_gitfile(git_link);
2416 else if (S_ISDIR(st.st_mode))
2417 src = git_link;
2418 else
2419 die(_("unable to handle file type %d"), (int)st.st_mode);
2421 if (rename(src, git_dir))
2422 die_errno(_("unable to move %s to %s"), src, git_dir);
2423 repair_worktrees_after_gitdir_move(src);
2426 write_file(git_link, "gitdir: %s", git_dir);
2429 struct default_format_config {
2430 int hash;
2431 enum ref_storage_format ref_format;
2434 static int read_default_format_config(const char *key, const char *value,
2435 const struct config_context *ctx UNUSED,
2436 void *payload)
2438 struct default_format_config *cfg = payload;
2439 char *str = NULL;
2440 int ret;
2442 if (!strcmp(key, "init.defaultobjectformat")) {
2443 ret = git_config_string(&str, key, value);
2444 if (ret)
2445 goto out;
2446 cfg->hash = hash_algo_by_name(str);
2447 if (cfg->hash == GIT_HASH_UNKNOWN)
2448 warning(_("unknown hash algorithm '%s'"), str);
2449 goto out;
2452 if (!strcmp(key, "init.defaultrefformat")) {
2453 ret = git_config_string(&str, key, value);
2454 if (ret)
2455 goto out;
2456 cfg->ref_format = ref_storage_format_by_name(str);
2457 if (cfg->ref_format == REF_STORAGE_FORMAT_UNKNOWN)
2458 warning(_("unknown ref storage format '%s'"), str);
2459 goto out;
2462 ret = 0;
2463 out:
2464 free(str);
2465 return ret;
2468 static void repository_format_configure(struct repository_format *repo_fmt,
2469 int hash, enum ref_storage_format ref_format)
2471 struct default_format_config cfg = {
2472 .hash = GIT_HASH_UNKNOWN,
2473 .ref_format = REF_STORAGE_FORMAT_UNKNOWN,
2475 struct config_options opts = {
2476 .respect_includes = 1,
2477 .ignore_repo = 1,
2478 .ignore_worktree = 1,
2480 const char *env;
2482 config_with_options(read_default_format_config, &cfg, NULL, NULL, &opts);
2485 * If we already have an initialized repo, don't allow the user to
2486 * specify a different algorithm, as that could cause corruption.
2487 * Otherwise, if the user has specified one on the command line, use it.
2489 env = getenv(GIT_DEFAULT_HASH_ENVIRONMENT);
2490 if (repo_fmt->version >= 0 && hash != GIT_HASH_UNKNOWN && hash != repo_fmt->hash_algo)
2491 die(_("attempt to reinitialize repository with different hash"));
2492 else if (hash != GIT_HASH_UNKNOWN)
2493 repo_fmt->hash_algo = hash;
2494 else if (env) {
2495 int env_algo = hash_algo_by_name(env);
2496 if (env_algo == GIT_HASH_UNKNOWN)
2497 die(_("unknown hash algorithm '%s'"), env);
2498 repo_fmt->hash_algo = env_algo;
2499 } else if (cfg.hash != GIT_HASH_UNKNOWN) {
2500 repo_fmt->hash_algo = cfg.hash;
2502 repo_set_hash_algo(the_repository, repo_fmt->hash_algo);
2504 env = getenv("GIT_DEFAULT_REF_FORMAT");
2505 if (repo_fmt->version >= 0 &&
2506 ref_format != REF_STORAGE_FORMAT_UNKNOWN &&
2507 ref_format != repo_fmt->ref_storage_format) {
2508 die(_("attempt to reinitialize repository with different reference storage format"));
2509 } else if (ref_format != REF_STORAGE_FORMAT_UNKNOWN) {
2510 repo_fmt->ref_storage_format = ref_format;
2511 } else if (env) {
2512 ref_format = ref_storage_format_by_name(env);
2513 if (ref_format == REF_STORAGE_FORMAT_UNKNOWN)
2514 die(_("unknown ref storage format '%s'"), env);
2515 repo_fmt->ref_storage_format = ref_format;
2516 } else if (cfg.ref_format != REF_STORAGE_FORMAT_UNKNOWN) {
2517 repo_fmt->ref_storage_format = cfg.ref_format;
2519 repo_set_ref_storage_format(the_repository, repo_fmt->ref_storage_format);
2522 int init_db(const char *git_dir, const char *real_git_dir,
2523 const char *template_dir, int hash,
2524 enum ref_storage_format ref_storage_format,
2525 const char *initial_branch,
2526 int init_shared_repository, unsigned int flags)
2528 int reinit;
2529 int exist_ok = flags & INIT_DB_EXIST_OK;
2530 char *original_git_dir = real_pathdup(git_dir, 1);
2531 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
2533 if (real_git_dir) {
2534 struct stat st;
2536 if (!exist_ok && !stat(git_dir, &st))
2537 die(_("%s already exists"), git_dir);
2539 if (!exist_ok && !stat(real_git_dir, &st))
2540 die(_("%s already exists"), real_git_dir);
2542 set_git_dir(real_git_dir, 1);
2543 git_dir = repo_get_git_dir(the_repository);
2544 separate_git_dir(git_dir, original_git_dir);
2546 else {
2547 set_git_dir(git_dir, 1);
2548 git_dir = repo_get_git_dir(the_repository);
2550 startup_info->have_repository = 1;
2553 * Check to see if the repository version is right.
2554 * Note that a newly created repository does not have
2555 * config file, so this will not fail. What we are catching
2556 * is an attempt to reinitialize new repository with an old tool.
2558 check_repository_format(&repo_fmt);
2560 repository_format_configure(&repo_fmt, hash, ref_storage_format);
2563 * Ensure `core.hidedotfiles` is processed. This must happen after we
2564 * have set up the repository format such that we can evaluate
2565 * includeIf conditions correctly in the case of re-initialization.
2567 git_config(platform_core_config, NULL);
2569 safe_create_dir(git_dir, 0);
2571 reinit = create_default_files(template_dir, original_git_dir,
2572 &repo_fmt, init_shared_repository);
2574 if (!(flags & INIT_DB_SKIP_REFDB))
2575 create_reference_database(repo_fmt.ref_storage_format,
2576 initial_branch, flags & INIT_DB_QUIET);
2577 create_object_directory();
2579 if (get_shared_repository()) {
2580 char buf[10];
2581 /* We do not spell "group" and such, so that
2582 * the configuration can be read by older version
2583 * of git. Note, we use octal numbers for new share modes,
2584 * and compatibility values for PERM_GROUP and
2585 * PERM_EVERYBODY.
2587 if (get_shared_repository() < 0)
2588 /* force to the mode value */
2589 xsnprintf(buf, sizeof(buf), "0%o", -get_shared_repository());
2590 else if (get_shared_repository() == PERM_GROUP)
2591 xsnprintf(buf, sizeof(buf), "%d", OLD_PERM_GROUP);
2592 else if (get_shared_repository() == PERM_EVERYBODY)
2593 xsnprintf(buf, sizeof(buf), "%d", OLD_PERM_EVERYBODY);
2594 else
2595 BUG("invalid value for shared_repository");
2596 git_config_set("core.sharedrepository", buf);
2597 git_config_set("receive.denyNonFastforwards", "true");
2600 if (!(flags & INIT_DB_QUIET)) {
2601 int len = strlen(git_dir);
2603 if (reinit)
2604 printf(get_shared_repository()
2605 ? _("Reinitialized existing shared Git repository in %s%s\n")
2606 : _("Reinitialized existing Git repository in %s%s\n"),
2607 git_dir, len && git_dir[len-1] != '/' ? "/" : "");
2608 else
2609 printf(get_shared_repository()
2610 ? _("Initialized empty shared Git repository in %s%s\n")
2611 : _("Initialized empty Git repository in %s%s\n"),
2612 git_dir, len && git_dir[len-1] != '/' ? "/" : "");
2615 clear_repository_format(&repo_fmt);
2616 free(original_git_dir);
2617 return 0;