init.templateDir: consider this config setting protected
[git.git] / setup.c
blobc3301f5ab824b5c7d8d12c835dd2819368c6ffd0
1 #include "cache.h"
2 #include "repository.h"
3 #include "config.h"
4 #include "dir.h"
5 #include "string-list.h"
6 #include "chdir-notify.h"
7 #include "promisor-remote.h"
8 #include "quote.h"
9 #include "exec-cmd.h"
11 static int inside_git_dir = -1;
12 static int inside_work_tree = -1;
13 static int work_tree_config_is_bogus;
14 enum allowed_bare_repo {
15 ALLOWED_BARE_REPO_EXPLICIT = 0,
16 ALLOWED_BARE_REPO_ALL,
19 static struct startup_info the_startup_info;
20 struct startup_info *startup_info = &the_startup_info;
21 const char *tmp_original_cwd;
24 * The input parameter must contain an absolute path, and it must already be
25 * normalized.
27 * Find the part of an absolute path that lies inside the work tree by
28 * dereferencing symlinks outside the work tree, for example:
29 * /dir1/repo/dir2/file (work tree is /dir1/repo) -> dir2/file
30 * /dir/file (work tree is /) -> dir/file
31 * /dir/symlink1/symlink2 (symlink1 points to work tree) -> symlink2
32 * /dir/repolink/file (repolink points to /dir/repo) -> file
33 * /dir/repo (exactly equal to work tree) -> (empty string)
35 static int abspath_part_inside_repo(char *path)
37 size_t len;
38 size_t wtlen;
39 char *path0;
40 int off;
41 const char *work_tree = get_git_work_tree();
42 struct strbuf realpath = STRBUF_INIT;
44 if (!work_tree)
45 return -1;
46 wtlen = strlen(work_tree);
47 len = strlen(path);
48 off = offset_1st_component(path);
50 /* check if work tree is already the prefix */
51 if (wtlen <= len && !fspathncmp(path, work_tree, wtlen)) {
52 if (path[wtlen] == '/') {
53 memmove(path, path + wtlen + 1, len - wtlen);
54 return 0;
55 } else if (path[wtlen - 1] == '/' || path[wtlen] == '\0') {
56 /* work tree is the root, or the whole path */
57 memmove(path, path + wtlen, len - wtlen + 1);
58 return 0;
60 /* work tree might match beginning of a symlink to work tree */
61 off = wtlen;
63 path0 = path;
64 path += off;
66 /* check each '/'-terminated level */
67 while (*path) {
68 path++;
69 if (*path == '/') {
70 *path = '\0';
71 strbuf_realpath(&realpath, path0, 1);
72 if (fspathcmp(realpath.buf, work_tree) == 0) {
73 memmove(path0, path + 1, len - (path - path0));
74 strbuf_release(&realpath);
75 return 0;
77 *path = '/';
81 /* check whole path */
82 strbuf_realpath(&realpath, path0, 1);
83 if (fspathcmp(realpath.buf, work_tree) == 0) {
84 *path0 = '\0';
85 strbuf_release(&realpath);
86 return 0;
89 strbuf_release(&realpath);
90 return -1;
94 * Normalize "path", prepending the "prefix" for relative paths. If
95 * remaining_prefix is not NULL, return the actual prefix still
96 * remains in the path. For example, prefix = sub1/sub2/ and path is
98 * foo -> sub1/sub2/foo (full prefix)
99 * ../foo -> sub1/foo (remaining prefix is sub1/)
100 * ../../bar -> bar (no remaining prefix)
101 * ../../sub1/sub2/foo -> sub1/sub2/foo (but no remaining prefix)
102 * `pwd`/../bar -> sub1/bar (no remaining prefix)
104 char *prefix_path_gently(const char *prefix, int len,
105 int *remaining_prefix, const char *path)
107 const char *orig = path;
108 char *sanitized;
109 if (is_absolute_path(orig)) {
110 sanitized = xmallocz(strlen(path));
111 if (remaining_prefix)
112 *remaining_prefix = 0;
113 if (normalize_path_copy_len(sanitized, path, remaining_prefix)) {
114 free(sanitized);
115 return NULL;
117 if (abspath_part_inside_repo(sanitized)) {
118 free(sanitized);
119 return NULL;
121 } else {
122 sanitized = xstrfmt("%.*s%s", len, len ? prefix : "", path);
123 if (remaining_prefix)
124 *remaining_prefix = len;
125 if (normalize_path_copy_len(sanitized, sanitized, remaining_prefix)) {
126 free(sanitized);
127 return NULL;
130 return sanitized;
133 char *prefix_path(const char *prefix, int len, const char *path)
135 char *r = prefix_path_gently(prefix, len, NULL, path);
136 if (!r) {
137 const char *hint_path = get_git_work_tree();
138 if (!hint_path)
139 hint_path = get_git_dir();
140 die(_("'%s' is outside repository at '%s'"), path,
141 absolute_path(hint_path));
143 return r;
146 int path_inside_repo(const char *prefix, const char *path)
148 int len = prefix ? strlen(prefix) : 0;
149 char *r = prefix_path_gently(prefix, len, NULL, path);
150 if (r) {
151 free(r);
152 return 1;
154 return 0;
157 int check_filename(const char *prefix, const char *arg)
159 char *to_free = NULL;
160 struct stat st;
162 if (skip_prefix(arg, ":/", &arg)) {
163 if (!*arg) /* ":/" is root dir, always exists */
164 return 1;
165 prefix = NULL;
166 } else if (skip_prefix(arg, ":!", &arg) ||
167 skip_prefix(arg, ":^", &arg)) {
168 if (!*arg) /* excluding everything is silly, but allowed */
169 return 1;
172 if (prefix)
173 arg = to_free = prefix_filename(prefix, arg);
175 if (!lstat(arg, &st)) {
176 free(to_free);
177 return 1; /* file exists */
179 if (is_missing_file_error(errno)) {
180 free(to_free);
181 return 0; /* file does not exist */
183 die_errno(_("failed to stat '%s'"), arg);
186 static void NORETURN die_verify_filename(struct repository *r,
187 const char *prefix,
188 const char *arg,
189 int diagnose_misspelt_rev)
191 if (!diagnose_misspelt_rev)
192 die(_("%s: no such path in the working tree.\n"
193 "Use 'git <command> -- <path>...' to specify paths that do not exist locally."),
194 arg);
196 * Saying "'(icase)foo' does not exist in the index" when the
197 * user gave us ":(icase)foo" is just stupid. A magic pathspec
198 * begins with a colon and is followed by a non-alnum; do not
199 * let maybe_die_on_misspelt_object_name() even trigger.
201 if (!(arg[0] == ':' && !isalnum(arg[1])))
202 maybe_die_on_misspelt_object_name(r, arg, prefix);
204 /* ... or fall back the most general message. */
205 die(_("ambiguous argument '%s': unknown revision or path not in the working tree.\n"
206 "Use '--' to separate paths from revisions, like this:\n"
207 "'git <command> [<revision>...] -- [<file>...]'"), arg);
212 * Check for arguments that don't resolve as actual files,
213 * but which look sufficiently like pathspecs that we'll consider
214 * them such for the purposes of rev/pathspec DWIM parsing.
216 static int looks_like_pathspec(const char *arg)
218 const char *p;
219 int escaped = 0;
222 * Wildcard characters imply the user is looking to match pathspecs
223 * that aren't in the filesystem. Note that this doesn't include
224 * backslash even though it's a glob special; by itself it doesn't
225 * cause any increase in the match. Likewise ignore backslash-escaped
226 * wildcard characters.
228 for (p = arg; *p; p++) {
229 if (escaped) {
230 escaped = 0;
231 } else if (is_glob_special(*p)) {
232 if (*p == '\\')
233 escaped = 1;
234 else
235 return 1;
239 /* long-form pathspec magic */
240 if (starts_with(arg, ":("))
241 return 1;
243 return 0;
247 * Verify a filename that we got as an argument for a pathspec
248 * entry. Note that a filename that begins with "-" never verifies
249 * as true, because even if such a filename were to exist, we want
250 * it to be preceded by the "--" marker (or we want the user to
251 * use a format like "./-filename")
253 * The "diagnose_misspelt_rev" is used to provide a user-friendly
254 * diagnosis when dying upon finding that "name" is not a pathname.
255 * If set to 1, the diagnosis will try to diagnose "name" as an
256 * invalid object name (e.g. HEAD:foo). If set to 0, the diagnosis
257 * will only complain about an inexisting file.
259 * This function is typically called to check that a "file or rev"
260 * argument is unambiguous. In this case, the caller will want
261 * diagnose_misspelt_rev == 1 when verifying the first non-rev
262 * argument (which could have been a revision), and
263 * diagnose_misspelt_rev == 0 for the next ones (because we already
264 * saw a filename, there's not ambiguity anymore).
266 void verify_filename(const char *prefix,
267 const char *arg,
268 int diagnose_misspelt_rev)
270 if (*arg == '-')
271 die(_("option '%s' must come before non-option arguments"), arg);
272 if (looks_like_pathspec(arg) || check_filename(prefix, arg))
273 return;
274 die_verify_filename(the_repository, prefix, arg, diagnose_misspelt_rev);
278 * Opposite of the above: the command line did not have -- marker
279 * and we parsed the arg as a refname. It should not be interpretable
280 * as a filename.
282 void verify_non_filename(const char *prefix, const char *arg)
284 if (!is_inside_work_tree() || is_inside_git_dir())
285 return;
286 if (*arg == '-')
287 return; /* flag */
288 if (!check_filename(prefix, arg))
289 return;
290 die(_("ambiguous argument '%s': both revision and filename\n"
291 "Use '--' to separate paths from revisions, like this:\n"
292 "'git <command> [<revision>...] -- [<file>...]'"), arg);
295 int get_common_dir(struct strbuf *sb, const char *gitdir)
297 const char *git_env_common_dir = getenv(GIT_COMMON_DIR_ENVIRONMENT);
298 if (git_env_common_dir) {
299 strbuf_addstr(sb, git_env_common_dir);
300 return 1;
301 } else {
302 return get_common_dir_noenv(sb, gitdir);
306 int get_common_dir_noenv(struct strbuf *sb, const char *gitdir)
308 struct strbuf data = STRBUF_INIT;
309 struct strbuf path = STRBUF_INIT;
310 int ret = 0;
312 strbuf_addf(&path, "%s/commondir", gitdir);
313 if (file_exists(path.buf)) {
314 if (strbuf_read_file(&data, path.buf, 0) <= 0)
315 die_errno(_("failed to read %s"), path.buf);
316 while (data.len && (data.buf[data.len - 1] == '\n' ||
317 data.buf[data.len - 1] == '\r'))
318 data.len--;
319 data.buf[data.len] = '\0';
320 strbuf_reset(&path);
321 if (!is_absolute_path(data.buf))
322 strbuf_addf(&path, "%s/", gitdir);
323 strbuf_addbuf(&path, &data);
324 strbuf_add_real_path(sb, path.buf);
325 ret = 1;
326 } else {
327 strbuf_addstr(sb, gitdir);
330 strbuf_release(&data);
331 strbuf_release(&path);
332 return ret;
336 * Test if it looks like we're at a git directory.
337 * We want to see:
339 * - either an objects/ directory _or_ the proper
340 * GIT_OBJECT_DIRECTORY environment variable
341 * - a refs/ directory
342 * - either a HEAD symlink or a HEAD file that is formatted as
343 * a proper "ref:", or a regular file HEAD that has a properly
344 * formatted sha1 object name.
346 int is_git_directory(const char *suspect)
348 struct strbuf path = STRBUF_INIT;
349 int ret = 0;
350 size_t len;
352 /* Check worktree-related signatures */
353 strbuf_addstr(&path, suspect);
354 strbuf_complete(&path, '/');
355 strbuf_addstr(&path, "HEAD");
356 if (validate_headref(path.buf))
357 goto done;
359 strbuf_reset(&path);
360 get_common_dir(&path, suspect);
361 len = path.len;
363 /* Check non-worktree-related signatures */
364 if (getenv(DB_ENVIRONMENT)) {
365 if (access(getenv(DB_ENVIRONMENT), X_OK))
366 goto done;
368 else {
369 strbuf_setlen(&path, len);
370 strbuf_addstr(&path, "/objects");
371 if (access(path.buf, X_OK))
372 goto done;
375 strbuf_setlen(&path, len);
376 strbuf_addstr(&path, "/refs");
377 if (access(path.buf, X_OK))
378 goto done;
380 ret = 1;
381 done:
382 strbuf_release(&path);
383 return ret;
386 int is_nonbare_repository_dir(struct strbuf *path)
388 int ret = 0;
389 int gitfile_error;
390 size_t orig_path_len = path->len;
391 assert(orig_path_len != 0);
392 strbuf_complete(path, '/');
393 strbuf_addstr(path, ".git");
394 if (read_gitfile_gently(path->buf, &gitfile_error) || is_git_directory(path->buf))
395 ret = 1;
396 if (gitfile_error == READ_GITFILE_ERR_OPEN_FAILED ||
397 gitfile_error == READ_GITFILE_ERR_READ_FAILED)
398 ret = 1;
399 strbuf_setlen(path, orig_path_len);
400 return ret;
403 int is_inside_git_dir(void)
405 if (inside_git_dir < 0)
406 inside_git_dir = is_inside_dir(get_git_dir());
407 return inside_git_dir;
410 int is_inside_work_tree(void)
412 if (inside_work_tree < 0)
413 inside_work_tree = is_inside_dir(get_git_work_tree());
414 return inside_work_tree;
417 void setup_work_tree(void)
419 const char *work_tree;
420 static int initialized = 0;
422 if (initialized)
423 return;
425 if (work_tree_config_is_bogus)
426 die(_("unable to set up work tree using invalid config"));
428 work_tree = get_git_work_tree();
429 if (!work_tree || chdir_notify(work_tree))
430 die(_("this operation must be run in a work tree"));
433 * Make sure subsequent git processes find correct worktree
434 * if $GIT_WORK_TREE is set relative
436 if (getenv(GIT_WORK_TREE_ENVIRONMENT))
437 setenv(GIT_WORK_TREE_ENVIRONMENT, ".", 1);
439 initialized = 1;
442 static void setup_original_cwd(void)
444 struct strbuf tmp = STRBUF_INIT;
445 const char *worktree = NULL;
446 int offset = -1;
448 if (!tmp_original_cwd)
449 return;
452 * startup_info->original_cwd points to the current working
453 * directory we inherited from our parent process, which is a
454 * directory we want to avoid removing.
456 * For convience, we would like to have the path relative to the
457 * worktree instead of an absolute path.
459 * Yes, startup_info->original_cwd is usually the same as 'prefix',
460 * but differs in two ways:
461 * - prefix has a trailing '/'
462 * - if the user passes '-C' to git, that modifies the prefix but
463 * not startup_info->original_cwd.
466 /* Normalize the directory */
467 if (!strbuf_realpath(&tmp, tmp_original_cwd, 0)) {
468 trace2_data_string("setup", the_repository,
469 "realpath-path", tmp_original_cwd);
470 trace2_data_string("setup", the_repository,
471 "realpath-failure", strerror(errno));
472 free((char*)tmp_original_cwd);
473 tmp_original_cwd = NULL;
474 return;
477 free((char*)tmp_original_cwd);
478 tmp_original_cwd = NULL;
479 startup_info->original_cwd = strbuf_detach(&tmp, NULL);
482 * Get our worktree; we only protect the current working directory
483 * if it's in the worktree.
485 worktree = get_git_work_tree();
486 if (!worktree)
487 goto no_prevention_needed;
489 offset = dir_inside_of(startup_info->original_cwd, worktree);
490 if (offset >= 0) {
492 * If startup_info->original_cwd == worktree, that is already
493 * protected and we don't need original_cwd as a secondary
494 * protection measure.
496 if (!*(startup_info->original_cwd + offset))
497 goto no_prevention_needed;
500 * original_cwd was inside worktree; precompose it just as
501 * we do prefix so that built up paths will match
503 startup_info->original_cwd = \
504 precompose_string_if_needed(startup_info->original_cwd
505 + offset);
506 return;
509 no_prevention_needed:
510 free((char*)startup_info->original_cwd);
511 startup_info->original_cwd = NULL;
514 static int read_worktree_config(const char *var, const char *value, void *vdata)
516 struct repository_format *data = vdata;
518 if (strcmp(var, "core.bare") == 0) {
519 data->is_bare = git_config_bool(var, value);
520 } else if (strcmp(var, "core.worktree") == 0) {
521 if (!value)
522 return config_error_nonbool(var);
523 free(data->work_tree);
524 data->work_tree = xstrdup(value);
526 return 0;
529 enum extension_result {
530 EXTENSION_ERROR = -1, /* compatible with error(), etc */
531 EXTENSION_UNKNOWN = 0,
532 EXTENSION_OK = 1
536 * Do not add new extensions to this function. It handles extensions which are
537 * respected even in v0-format repositories for historical compatibility.
539 static enum extension_result handle_extension_v0(const char *var,
540 const char *value,
541 const char *ext,
542 struct repository_format *data)
544 if (!strcmp(ext, "noop")) {
545 return EXTENSION_OK;
546 } else if (!strcmp(ext, "preciousobjects")) {
547 data->precious_objects = git_config_bool(var, value);
548 return EXTENSION_OK;
549 } else if (!strcmp(ext, "partialclone")) {
550 data->partial_clone = xstrdup(value);
551 return EXTENSION_OK;
552 } else if (!strcmp(ext, "worktreeconfig")) {
553 data->worktree_config = git_config_bool(var, value);
554 return EXTENSION_OK;
557 return EXTENSION_UNKNOWN;
561 * Record any new extensions in this function.
563 static enum extension_result handle_extension(const char *var,
564 const char *value,
565 const char *ext,
566 struct repository_format *data)
568 if (!strcmp(ext, "noop-v1")) {
569 return EXTENSION_OK;
570 } else if (!strcmp(ext, "objectformat")) {
571 int format;
573 if (!value)
574 return config_error_nonbool(var);
575 format = hash_algo_by_name(value);
576 if (format == GIT_HASH_UNKNOWN)
577 return error(_("invalid value for '%s': '%s'"),
578 "extensions.objectformat", value);
579 data->hash_algo = format;
580 return EXTENSION_OK;
582 return EXTENSION_UNKNOWN;
585 static int check_repo_format(const char *var, const char *value, void *vdata)
587 struct repository_format *data = vdata;
588 const char *ext;
590 if (strcmp(var, "core.repositoryformatversion") == 0)
591 data->version = git_config_int(var, value);
592 else if (skip_prefix(var, "extensions.", &ext)) {
593 switch (handle_extension_v0(var, value, ext, data)) {
594 case EXTENSION_ERROR:
595 return -1;
596 case EXTENSION_OK:
597 return 0;
598 case EXTENSION_UNKNOWN:
599 break;
602 switch (handle_extension(var, value, ext, data)) {
603 case EXTENSION_ERROR:
604 return -1;
605 case EXTENSION_OK:
606 string_list_append(&data->v1_only_extensions, ext);
607 return 0;
608 case EXTENSION_UNKNOWN:
609 string_list_append(&data->unknown_extensions, ext);
610 return 0;
614 return read_worktree_config(var, value, vdata);
617 static int check_repository_format_gently(const char *gitdir, struct repository_format *candidate, int *nongit_ok)
619 struct strbuf sb = STRBUF_INIT;
620 struct strbuf err = STRBUF_INIT;
621 int has_common;
623 has_common = get_common_dir(&sb, gitdir);
624 strbuf_addstr(&sb, "/config");
625 read_repository_format(candidate, sb.buf);
626 strbuf_release(&sb);
629 * For historical use of check_repository_format() in git-init,
630 * we treat a missing config as a silent "ok", even when nongit_ok
631 * is unset.
633 if (candidate->version < 0)
634 return 0;
636 if (verify_repository_format(candidate, &err) < 0) {
637 if (nongit_ok) {
638 warning("%s", err.buf);
639 strbuf_release(&err);
640 *nongit_ok = -1;
641 return -1;
643 die("%s", err.buf);
646 repository_format_precious_objects = candidate->precious_objects;
647 repository_format_worktree_config = candidate->worktree_config;
648 string_list_clear(&candidate->unknown_extensions, 0);
649 string_list_clear(&candidate->v1_only_extensions, 0);
651 if (repository_format_worktree_config) {
653 * pick up core.bare and core.worktree from per-worktree
654 * config if present
656 strbuf_addf(&sb, "%s/config.worktree", gitdir);
657 git_config_from_file(read_worktree_config, sb.buf, candidate);
658 strbuf_release(&sb);
659 has_common = 0;
662 if (!has_common) {
663 if (candidate->is_bare != -1) {
664 is_bare_repository_cfg = candidate->is_bare;
665 if (is_bare_repository_cfg == 1)
666 inside_work_tree = -1;
668 if (candidate->work_tree) {
669 free(git_work_tree_cfg);
670 git_work_tree_cfg = xstrdup(candidate->work_tree);
671 inside_work_tree = -1;
675 return 0;
678 int upgrade_repository_format(int target_version)
680 struct strbuf sb = STRBUF_INIT;
681 struct strbuf err = STRBUF_INIT;
682 struct strbuf repo_version = STRBUF_INIT;
683 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
685 strbuf_git_common_path(&sb, the_repository, "config");
686 read_repository_format(&repo_fmt, sb.buf);
687 strbuf_release(&sb);
689 if (repo_fmt.version >= target_version)
690 return 0;
692 if (verify_repository_format(&repo_fmt, &err) < 0) {
693 error("cannot upgrade repository format from %d to %d: %s",
694 repo_fmt.version, target_version, err.buf);
695 strbuf_release(&err);
696 return -1;
698 if (!repo_fmt.version && repo_fmt.unknown_extensions.nr)
699 return error("cannot upgrade repository format: "
700 "unknown extension %s",
701 repo_fmt.unknown_extensions.items[0].string);
703 strbuf_addf(&repo_version, "%d", target_version);
704 git_config_set("core.repositoryformatversion", repo_version.buf);
705 strbuf_release(&repo_version);
706 return 1;
709 static void init_repository_format(struct repository_format *format)
711 const struct repository_format fresh = REPOSITORY_FORMAT_INIT;
713 memcpy(format, &fresh, sizeof(fresh));
716 int read_repository_format(struct repository_format *format, const char *path)
718 clear_repository_format(format);
719 git_config_from_file(check_repo_format, path, format);
720 if (format->version == -1)
721 clear_repository_format(format);
722 return format->version;
725 void clear_repository_format(struct repository_format *format)
727 string_list_clear(&format->unknown_extensions, 0);
728 string_list_clear(&format->v1_only_extensions, 0);
729 free(format->work_tree);
730 free(format->partial_clone);
731 init_repository_format(format);
734 int verify_repository_format(const struct repository_format *format,
735 struct strbuf *err)
737 if (GIT_REPO_VERSION_READ < format->version) {
738 strbuf_addf(err, _("Expected git repo version <= %d, found %d"),
739 GIT_REPO_VERSION_READ, format->version);
740 return -1;
743 if (format->version >= 1 && format->unknown_extensions.nr) {
744 int i;
746 strbuf_addstr(err, Q_("unknown repository extension found:",
747 "unknown repository extensions found:",
748 format->unknown_extensions.nr));
750 for (i = 0; i < format->unknown_extensions.nr; i++)
751 strbuf_addf(err, "\n\t%s",
752 format->unknown_extensions.items[i].string);
753 return -1;
756 if (format->version == 0 && format->v1_only_extensions.nr) {
757 int i;
759 strbuf_addstr(err,
760 Q_("repo version is 0, but v1-only extension found:",
761 "repo version is 0, but v1-only extensions found:",
762 format->v1_only_extensions.nr));
764 for (i = 0; i < format->v1_only_extensions.nr; i++)
765 strbuf_addf(err, "\n\t%s",
766 format->v1_only_extensions.items[i].string);
767 return -1;
770 return 0;
773 void read_gitfile_error_die(int error_code, const char *path, const char *dir)
775 switch (error_code) {
776 case READ_GITFILE_ERR_STAT_FAILED:
777 case READ_GITFILE_ERR_NOT_A_FILE:
778 /* non-fatal; follow return path */
779 break;
780 case READ_GITFILE_ERR_OPEN_FAILED:
781 die_errno(_("error opening '%s'"), path);
782 case READ_GITFILE_ERR_TOO_LARGE:
783 die(_("too large to be a .git file: '%s'"), path);
784 case READ_GITFILE_ERR_READ_FAILED:
785 die(_("error reading %s"), path);
786 case READ_GITFILE_ERR_INVALID_FORMAT:
787 die(_("invalid gitfile format: %s"), path);
788 case READ_GITFILE_ERR_NO_PATH:
789 die(_("no path in gitfile: %s"), path);
790 case READ_GITFILE_ERR_NOT_A_REPO:
791 die(_("not a git repository: %s"), dir);
792 default:
793 BUG("unknown error code");
798 * Try to read the location of the git directory from the .git file,
799 * return path to git directory if found. The return value comes from
800 * a shared buffer.
802 * On failure, if return_error_code is not NULL, return_error_code
803 * will be set to an error code and NULL will be returned. If
804 * return_error_code is NULL the function will die instead (for most
805 * cases).
807 const char *read_gitfile_gently(const char *path, int *return_error_code)
809 const int max_file_size = 1 << 20; /* 1MB */
810 int error_code = 0;
811 char *buf = NULL;
812 char *dir = NULL;
813 const char *slash;
814 struct stat st;
815 int fd;
816 ssize_t len;
817 static struct strbuf realpath = STRBUF_INIT;
819 if (stat(path, &st)) {
820 /* NEEDSWORK: discern between ENOENT vs other errors */
821 error_code = READ_GITFILE_ERR_STAT_FAILED;
822 goto cleanup_return;
824 if (!S_ISREG(st.st_mode)) {
825 error_code = READ_GITFILE_ERR_NOT_A_FILE;
826 goto cleanup_return;
828 if (st.st_size > max_file_size) {
829 error_code = READ_GITFILE_ERR_TOO_LARGE;
830 goto cleanup_return;
832 fd = open(path, O_RDONLY);
833 if (fd < 0) {
834 error_code = READ_GITFILE_ERR_OPEN_FAILED;
835 goto cleanup_return;
837 buf = xmallocz(st.st_size);
838 len = read_in_full(fd, buf, st.st_size);
839 close(fd);
840 if (len != st.st_size) {
841 error_code = READ_GITFILE_ERR_READ_FAILED;
842 goto cleanup_return;
844 if (!starts_with(buf, "gitdir: ")) {
845 error_code = READ_GITFILE_ERR_INVALID_FORMAT;
846 goto cleanup_return;
848 while (buf[len - 1] == '\n' || buf[len - 1] == '\r')
849 len--;
850 if (len < 9) {
851 error_code = READ_GITFILE_ERR_NO_PATH;
852 goto cleanup_return;
854 buf[len] = '\0';
855 dir = buf + 8;
857 if (!is_absolute_path(dir) && (slash = strrchr(path, '/'))) {
858 size_t pathlen = slash+1 - path;
859 dir = xstrfmt("%.*s%.*s", (int)pathlen, path,
860 (int)(len - 8), buf + 8);
861 free(buf);
862 buf = dir;
864 if (!is_git_directory(dir)) {
865 error_code = READ_GITFILE_ERR_NOT_A_REPO;
866 goto cleanup_return;
869 strbuf_realpath(&realpath, dir, 1);
870 path = realpath.buf;
872 cleanup_return:
873 if (return_error_code)
874 *return_error_code = error_code;
875 else if (error_code)
876 read_gitfile_error_die(error_code, path, dir);
878 free(buf);
879 return error_code ? NULL : path;
882 static const char *setup_explicit_git_dir(const char *gitdirenv,
883 struct strbuf *cwd,
884 struct repository_format *repo_fmt,
885 int *nongit_ok)
887 const char *work_tree_env = getenv(GIT_WORK_TREE_ENVIRONMENT);
888 const char *worktree;
889 char *gitfile;
890 int offset;
892 if (PATH_MAX - 40 < strlen(gitdirenv))
893 die(_("'$%s' too big"), GIT_DIR_ENVIRONMENT);
895 gitfile = (char*)read_gitfile(gitdirenv);
896 if (gitfile) {
897 gitfile = xstrdup(gitfile);
898 gitdirenv = gitfile;
901 if (!is_git_directory(gitdirenv)) {
902 if (nongit_ok) {
903 *nongit_ok = 1;
904 free(gitfile);
905 return NULL;
907 die(_("not a git repository: '%s'"), gitdirenv);
910 if (check_repository_format_gently(gitdirenv, repo_fmt, nongit_ok)) {
911 free(gitfile);
912 return NULL;
915 /* #3, #7, #11, #15, #19, #23, #27, #31 (see t1510) */
916 if (work_tree_env)
917 set_git_work_tree(work_tree_env);
918 else if (is_bare_repository_cfg > 0) {
919 if (git_work_tree_cfg) {
920 /* #22.2, #30 */
921 warning("core.bare and core.worktree do not make sense");
922 work_tree_config_is_bogus = 1;
925 /* #18, #26 */
926 set_git_dir(gitdirenv, 0);
927 free(gitfile);
928 return NULL;
930 else if (git_work_tree_cfg) { /* #6, #14 */
931 if (is_absolute_path(git_work_tree_cfg))
932 set_git_work_tree(git_work_tree_cfg);
933 else {
934 char *core_worktree;
935 if (chdir(gitdirenv))
936 die_errno(_("cannot chdir to '%s'"), gitdirenv);
937 if (chdir(git_work_tree_cfg))
938 die_errno(_("cannot chdir to '%s'"), git_work_tree_cfg);
939 core_worktree = xgetcwd();
940 if (chdir(cwd->buf))
941 die_errno(_("cannot come back to cwd"));
942 set_git_work_tree(core_worktree);
943 free(core_worktree);
946 else if (!git_env_bool(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, 1)) {
947 /* #16d */
948 set_git_dir(gitdirenv, 0);
949 free(gitfile);
950 return NULL;
952 else /* #2, #10 */
953 set_git_work_tree(".");
955 /* set_git_work_tree() must have been called by now */
956 worktree = get_git_work_tree();
958 /* both get_git_work_tree() and cwd are already normalized */
959 if (!strcmp(cwd->buf, worktree)) { /* cwd == worktree */
960 set_git_dir(gitdirenv, 0);
961 free(gitfile);
962 return NULL;
965 offset = dir_inside_of(cwd->buf, worktree);
966 if (offset >= 0) { /* cwd inside worktree? */
967 set_git_dir(gitdirenv, 1);
968 if (chdir(worktree))
969 die_errno(_("cannot chdir to '%s'"), worktree);
970 strbuf_addch(cwd, '/');
971 free(gitfile);
972 return cwd->buf + offset;
975 /* cwd outside worktree */
976 set_git_dir(gitdirenv, 0);
977 free(gitfile);
978 return NULL;
981 static const char *setup_discovered_git_dir(const char *gitdir,
982 struct strbuf *cwd, int offset,
983 struct repository_format *repo_fmt,
984 int *nongit_ok)
986 if (check_repository_format_gently(gitdir, repo_fmt, nongit_ok))
987 return NULL;
989 /* --work-tree is set without --git-dir; use discovered one */
990 if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
991 char *to_free = NULL;
992 const char *ret;
994 if (offset != cwd->len && !is_absolute_path(gitdir))
995 gitdir = to_free = real_pathdup(gitdir, 1);
996 if (chdir(cwd->buf))
997 die_errno(_("cannot come back to cwd"));
998 ret = setup_explicit_git_dir(gitdir, cwd, repo_fmt, nongit_ok);
999 free(to_free);
1000 return ret;
1003 /* #16.2, #17.2, #20.2, #21.2, #24, #25, #28, #29 (see t1510) */
1004 if (is_bare_repository_cfg > 0) {
1005 set_git_dir(gitdir, (offset != cwd->len));
1006 if (chdir(cwd->buf))
1007 die_errno(_("cannot come back to cwd"));
1008 return NULL;
1011 /* #0, #1, #5, #8, #9, #12, #13 */
1012 set_git_work_tree(".");
1013 if (strcmp(gitdir, DEFAULT_GIT_DIR_ENVIRONMENT))
1014 set_git_dir(gitdir, 0);
1015 inside_git_dir = 0;
1016 inside_work_tree = 1;
1017 if (offset >= cwd->len)
1018 return NULL;
1020 /* Make "offset" point past the '/' (already the case for root dirs) */
1021 if (offset != offset_1st_component(cwd->buf))
1022 offset++;
1023 /* Add a '/' at the end */
1024 strbuf_addch(cwd, '/');
1025 return cwd->buf + offset;
1028 /* #16.1, #17.1, #20.1, #21.1, #22.1 (see t1510) */
1029 static const char *setup_bare_git_dir(struct strbuf *cwd, int offset,
1030 struct repository_format *repo_fmt,
1031 int *nongit_ok)
1033 int root_len;
1035 if (check_repository_format_gently(".", repo_fmt, nongit_ok))
1036 return NULL;
1038 setenv(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, "0", 1);
1040 /* --work-tree is set without --git-dir; use discovered one */
1041 if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
1042 static const char *gitdir;
1044 gitdir = offset == cwd->len ? "." : xmemdupz(cwd->buf, offset);
1045 if (chdir(cwd->buf))
1046 die_errno(_("cannot come back to cwd"));
1047 return setup_explicit_git_dir(gitdir, cwd, repo_fmt, nongit_ok);
1050 inside_git_dir = 1;
1051 inside_work_tree = 0;
1052 if (offset != cwd->len) {
1053 if (chdir(cwd->buf))
1054 die_errno(_("cannot come back to cwd"));
1055 root_len = offset_1st_component(cwd->buf);
1056 strbuf_setlen(cwd, offset > root_len ? offset : root_len);
1057 set_git_dir(cwd->buf, 0);
1059 else
1060 set_git_dir(".", 0);
1061 return NULL;
1064 static dev_t get_device_or_die(const char *path, const char *prefix, int prefix_len)
1066 struct stat buf;
1067 if (stat(path, &buf)) {
1068 die_errno(_("failed to stat '%*s%s%s'"),
1069 prefix_len,
1070 prefix ? prefix : "",
1071 prefix ? "/" : "", path);
1073 return buf.st_dev;
1077 * A "string_list_each_func_t" function that canonicalizes an entry
1078 * from GIT_CEILING_DIRECTORIES using real_pathdup(), or
1079 * discards it if unusable. The presence of an empty entry in
1080 * GIT_CEILING_DIRECTORIES turns off canonicalization for all
1081 * subsequent entries.
1083 static int canonicalize_ceiling_entry(struct string_list_item *item,
1084 void *cb_data)
1086 int *empty_entry_found = cb_data;
1087 char *ceil = item->string;
1089 if (!*ceil) {
1090 *empty_entry_found = 1;
1091 return 0;
1092 } else if (!is_absolute_path(ceil)) {
1093 return 0;
1094 } else if (*empty_entry_found) {
1095 /* Keep entry but do not canonicalize it */
1096 return 1;
1097 } else {
1098 char *real_path = real_pathdup(ceil, 0);
1099 if (!real_path) {
1100 return 0;
1102 free(item->string);
1103 item->string = real_path;
1104 return 1;
1108 struct safe_directory_data {
1109 const char *path;
1110 int is_safe;
1113 static int safe_directory_cb(const char *key, const char *value, void *d)
1115 struct safe_directory_data *data = d;
1117 if (strcmp(key, "safe.directory"))
1118 return 0;
1120 if (!value || !*value) {
1121 data->is_safe = 0;
1122 } else if (!strcmp(value, "*")) {
1123 data->is_safe = 1;
1124 } else {
1125 const char *interpolated = NULL;
1127 if (!git_config_pathname(&interpolated, key, value) &&
1128 !fspathcmp(data->path, interpolated ? interpolated : value))
1129 data->is_safe = 1;
1131 free((char *)interpolated);
1134 return 0;
1138 * Check if a repository is safe, by verifying the ownership of the
1139 * worktree (if any), the git directory, and the gitfile (if any).
1141 * Exemptions for known-safe repositories can be added via `safe.directory`
1142 * config settings; for non-bare repositories, their worktree needs to be
1143 * added, for bare ones their git directory.
1145 static int ensure_valid_ownership(const char *gitfile,
1146 const char *worktree, const char *gitdir,
1147 struct strbuf *report)
1149 struct safe_directory_data data = {
1150 .path = worktree ? worktree : gitdir
1153 if (!git_env_bool("GIT_TEST_ASSUME_DIFFERENT_OWNER", 0) &&
1154 (!gitfile || is_path_owned_by_current_user(gitfile, report)) &&
1155 (!worktree || is_path_owned_by_current_user(worktree, report)) &&
1156 (!gitdir || is_path_owned_by_current_user(gitdir, report)))
1157 return 1;
1160 * data.path is the "path" that identifies the repository and it is
1161 * constant regardless of what failed above. data.is_safe should be
1162 * initialized to false, and might be changed by the callback.
1164 git_protected_config(safe_directory_cb, &data);
1166 return data.is_safe;
1169 void die_upon_dubious_ownership(const char *gitfile, const char *worktree,
1170 const char *gitdir)
1172 struct strbuf report = STRBUF_INIT, quoted = STRBUF_INIT;
1173 const char *path;
1175 if (ensure_valid_ownership(gitfile, worktree, gitdir, &report))
1176 return;
1178 strbuf_complete(&report, '\n');
1179 path = gitfile ? gitfile : gitdir;
1180 sq_quote_buf_pretty(&quoted, path);
1182 die(_("detected dubious ownership in repository at '%s'\n"
1183 "%s"
1184 "To add an exception for this directory, call:\n"
1185 "\n"
1186 "\tgit config --global --add safe.directory %s"),
1187 path, report.buf, quoted.buf);
1190 static int allowed_bare_repo_cb(const char *key, const char *value, void *d)
1192 enum allowed_bare_repo *allowed_bare_repo = d;
1194 if (strcasecmp(key, "safe.bareRepository"))
1195 return 0;
1197 if (!strcmp(value, "explicit")) {
1198 *allowed_bare_repo = ALLOWED_BARE_REPO_EXPLICIT;
1199 return 0;
1201 if (!strcmp(value, "all")) {
1202 *allowed_bare_repo = ALLOWED_BARE_REPO_ALL;
1203 return 0;
1205 return -1;
1208 static enum allowed_bare_repo get_allowed_bare_repo(void)
1210 enum allowed_bare_repo result = ALLOWED_BARE_REPO_ALL;
1211 git_protected_config(allowed_bare_repo_cb, &result);
1212 return result;
1215 static const char *allowed_bare_repo_to_string(
1216 enum allowed_bare_repo allowed_bare_repo)
1218 switch (allowed_bare_repo) {
1219 case ALLOWED_BARE_REPO_EXPLICIT:
1220 return "explicit";
1221 case ALLOWED_BARE_REPO_ALL:
1222 return "all";
1223 default:
1224 BUG("invalid allowed_bare_repo %d",
1225 allowed_bare_repo);
1227 return NULL;
1230 enum discovery_result {
1231 GIT_DIR_NONE = 0,
1232 GIT_DIR_EXPLICIT,
1233 GIT_DIR_DISCOVERED,
1234 GIT_DIR_BARE,
1235 /* these are errors */
1236 GIT_DIR_HIT_CEILING = -1,
1237 GIT_DIR_HIT_MOUNT_POINT = -2,
1238 GIT_DIR_INVALID_GITFILE = -3,
1239 GIT_DIR_INVALID_OWNERSHIP = -4,
1240 GIT_DIR_DISALLOWED_BARE = -5,
1244 * We cannot decide in this function whether we are in the work tree or
1245 * not, since the config can only be read _after_ this function was called.
1247 * Also, we avoid changing any global state (such as the current working
1248 * directory) to allow early callers.
1250 * The directory where the search should start needs to be passed in via the
1251 * `dir` parameter; upon return, the `dir` buffer will contain the path of
1252 * the directory where the search ended, and `gitdir` will contain the path of
1253 * the discovered .git/ directory, if any. If `gitdir` is not absolute, it
1254 * is relative to `dir` (i.e. *not* necessarily the cwd).
1256 static enum discovery_result setup_git_directory_gently_1(struct strbuf *dir,
1257 struct strbuf *gitdir,
1258 struct strbuf *report,
1259 int die_on_error)
1261 const char *env_ceiling_dirs = getenv(CEILING_DIRECTORIES_ENVIRONMENT);
1262 struct string_list ceiling_dirs = STRING_LIST_INIT_DUP;
1263 const char *gitdirenv;
1264 int ceil_offset = -1, min_offset = offset_1st_component(dir->buf);
1265 dev_t current_device = 0;
1266 int one_filesystem = 1;
1269 * If GIT_DIR is set explicitly, we're not going
1270 * to do any discovery, but we still do repository
1271 * validation.
1273 gitdirenv = getenv(GIT_DIR_ENVIRONMENT);
1274 if (gitdirenv) {
1275 strbuf_addstr(gitdir, gitdirenv);
1276 return GIT_DIR_EXPLICIT;
1279 if (env_ceiling_dirs) {
1280 int empty_entry_found = 0;
1282 string_list_split(&ceiling_dirs, env_ceiling_dirs, PATH_SEP, -1);
1283 filter_string_list(&ceiling_dirs, 0,
1284 canonicalize_ceiling_entry, &empty_entry_found);
1285 ceil_offset = longest_ancestor_length(dir->buf, &ceiling_dirs);
1286 string_list_clear(&ceiling_dirs, 0);
1289 if (ceil_offset < 0)
1290 ceil_offset = min_offset - 2;
1292 if (min_offset && min_offset == dir->len &&
1293 !is_dir_sep(dir->buf[min_offset - 1])) {
1294 strbuf_addch(dir, '/');
1295 min_offset++;
1299 * Test in the following order (relative to the dir):
1300 * - .git (file containing "gitdir: <path>")
1301 * - .git/
1302 * - ./ (bare)
1303 * - ../.git
1304 * - ../.git/
1305 * - ../ (bare)
1306 * - ../../.git
1307 * etc.
1309 one_filesystem = !git_env_bool("GIT_DISCOVERY_ACROSS_FILESYSTEM", 0);
1310 if (one_filesystem)
1311 current_device = get_device_or_die(dir->buf, NULL, 0);
1312 for (;;) {
1313 int offset = dir->len, error_code = 0;
1314 char *gitdir_path = NULL;
1315 char *gitfile = NULL;
1317 if (offset > min_offset)
1318 strbuf_addch(dir, '/');
1319 strbuf_addstr(dir, DEFAULT_GIT_DIR_ENVIRONMENT);
1320 gitdirenv = read_gitfile_gently(dir->buf, die_on_error ?
1321 NULL : &error_code);
1322 if (!gitdirenv) {
1323 if (die_on_error ||
1324 error_code == READ_GITFILE_ERR_NOT_A_FILE) {
1325 /* NEEDSWORK: fail if .git is not file nor dir */
1326 if (is_git_directory(dir->buf)) {
1327 gitdirenv = DEFAULT_GIT_DIR_ENVIRONMENT;
1328 gitdir_path = xstrdup(dir->buf);
1330 } else if (error_code != READ_GITFILE_ERR_STAT_FAILED)
1331 return GIT_DIR_INVALID_GITFILE;
1332 } else
1333 gitfile = xstrdup(dir->buf);
1335 * Earlier, we tentatively added DEFAULT_GIT_DIR_ENVIRONMENT
1336 * to check that directory for a repository.
1337 * Now trim that tentative addition away, because we want to
1338 * focus on the real directory we are in.
1340 strbuf_setlen(dir, offset);
1341 if (gitdirenv) {
1342 enum discovery_result ret;
1343 const char *gitdir_candidate =
1344 gitdir_path ? gitdir_path : gitdirenv;
1346 if (ensure_valid_ownership(gitfile, dir->buf,
1347 gitdir_candidate, report)) {
1348 strbuf_addstr(gitdir, gitdirenv);
1349 ret = GIT_DIR_DISCOVERED;
1350 } else
1351 ret = GIT_DIR_INVALID_OWNERSHIP;
1354 * Earlier, during discovery, we might have allocated
1355 * string copies for gitdir_path or gitfile so make
1356 * sure we don't leak by freeing them now, before
1357 * leaving the loop and function.
1359 * Note: gitdirenv will be non-NULL whenever these are
1360 * allocated, therefore we need not take care of releasing
1361 * them outside of this conditional block.
1363 free(gitdir_path);
1364 free(gitfile);
1366 return ret;
1369 if (is_git_directory(dir->buf)) {
1370 if (get_allowed_bare_repo() == ALLOWED_BARE_REPO_EXPLICIT)
1371 return GIT_DIR_DISALLOWED_BARE;
1372 if (!ensure_valid_ownership(NULL, NULL, dir->buf, report))
1373 return GIT_DIR_INVALID_OWNERSHIP;
1374 strbuf_addstr(gitdir, ".");
1375 return GIT_DIR_BARE;
1378 if (offset <= min_offset)
1379 return GIT_DIR_HIT_CEILING;
1381 while (--offset > ceil_offset && !is_dir_sep(dir->buf[offset]))
1382 ; /* continue */
1383 if (offset <= ceil_offset)
1384 return GIT_DIR_HIT_CEILING;
1386 strbuf_setlen(dir, offset > min_offset ? offset : min_offset);
1387 if (one_filesystem &&
1388 current_device != get_device_or_die(dir->buf, NULL, offset))
1389 return GIT_DIR_HIT_MOUNT_POINT;
1393 int discover_git_directory(struct strbuf *commondir,
1394 struct strbuf *gitdir)
1396 struct strbuf dir = STRBUF_INIT, err = STRBUF_INIT;
1397 size_t gitdir_offset = gitdir->len, cwd_len;
1398 size_t commondir_offset = commondir->len;
1399 struct repository_format candidate = REPOSITORY_FORMAT_INIT;
1401 if (strbuf_getcwd(&dir))
1402 return -1;
1404 cwd_len = dir.len;
1405 if (setup_git_directory_gently_1(&dir, gitdir, NULL, 0) <= 0) {
1406 strbuf_release(&dir);
1407 return -1;
1411 * The returned gitdir is relative to dir, and if dir does not reflect
1412 * the current working directory, we simply make the gitdir absolute.
1414 if (dir.len < cwd_len && !is_absolute_path(gitdir->buf + gitdir_offset)) {
1415 /* Avoid a trailing "/." */
1416 if (!strcmp(".", gitdir->buf + gitdir_offset))
1417 strbuf_setlen(gitdir, gitdir_offset);
1418 else
1419 strbuf_addch(&dir, '/');
1420 strbuf_insert(gitdir, gitdir_offset, dir.buf, dir.len);
1423 get_common_dir(commondir, gitdir->buf + gitdir_offset);
1425 strbuf_reset(&dir);
1426 strbuf_addf(&dir, "%s/config", commondir->buf + commondir_offset);
1427 read_repository_format(&candidate, dir.buf);
1428 strbuf_release(&dir);
1430 if (verify_repository_format(&candidate, &err) < 0) {
1431 warning("ignoring git dir '%s': %s",
1432 gitdir->buf + gitdir_offset, err.buf);
1433 strbuf_release(&err);
1434 strbuf_setlen(commondir, commondir_offset);
1435 strbuf_setlen(gitdir, gitdir_offset);
1436 clear_repository_format(&candidate);
1437 return -1;
1440 /* take ownership of candidate.partial_clone */
1441 the_repository->repository_format_partial_clone =
1442 candidate.partial_clone;
1443 candidate.partial_clone = NULL;
1445 clear_repository_format(&candidate);
1446 return 0;
1449 const char *setup_git_directory_gently(int *nongit_ok)
1451 static struct strbuf cwd = STRBUF_INIT;
1452 struct strbuf dir = STRBUF_INIT, gitdir = STRBUF_INIT, report = STRBUF_INIT;
1453 const char *prefix = NULL;
1454 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
1457 * We may have read an incomplete configuration before
1458 * setting-up the git directory. If so, clear the cache so
1459 * that the next queries to the configuration reload complete
1460 * configuration (including the per-repo config file that we
1461 * ignored previously).
1463 git_config_clear();
1466 * Let's assume that we are in a git repository.
1467 * If it turns out later that we are somewhere else, the value will be
1468 * updated accordingly.
1470 if (nongit_ok)
1471 *nongit_ok = 0;
1473 if (strbuf_getcwd(&cwd))
1474 die_errno(_("Unable to read current working directory"));
1475 strbuf_addbuf(&dir, &cwd);
1477 switch (setup_git_directory_gently_1(&dir, &gitdir, &report, 1)) {
1478 case GIT_DIR_EXPLICIT:
1479 prefix = setup_explicit_git_dir(gitdir.buf, &cwd, &repo_fmt, nongit_ok);
1480 break;
1481 case GIT_DIR_DISCOVERED:
1482 if (dir.len < cwd.len && chdir(dir.buf))
1483 die(_("cannot change to '%s'"), dir.buf);
1484 prefix = setup_discovered_git_dir(gitdir.buf, &cwd, dir.len,
1485 &repo_fmt, nongit_ok);
1486 break;
1487 case GIT_DIR_BARE:
1488 if (dir.len < cwd.len && chdir(dir.buf))
1489 die(_("cannot change to '%s'"), dir.buf);
1490 prefix = setup_bare_git_dir(&cwd, dir.len, &repo_fmt, nongit_ok);
1491 break;
1492 case GIT_DIR_HIT_CEILING:
1493 if (!nongit_ok)
1494 die(_("not a git repository (or any of the parent directories): %s"),
1495 DEFAULT_GIT_DIR_ENVIRONMENT);
1496 *nongit_ok = 1;
1497 break;
1498 case GIT_DIR_HIT_MOUNT_POINT:
1499 if (!nongit_ok)
1500 die(_("not a git repository (or any parent up to mount point %s)\n"
1501 "Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set)."),
1502 dir.buf);
1503 *nongit_ok = 1;
1504 break;
1505 case GIT_DIR_INVALID_OWNERSHIP:
1506 if (!nongit_ok) {
1507 struct strbuf quoted = STRBUF_INIT;
1509 strbuf_complete(&report, '\n');
1510 sq_quote_buf_pretty(&quoted, dir.buf);
1511 die(_("detected dubious ownership in repository at '%s'\n"
1512 "%s"
1513 "To add an exception for this directory, call:\n"
1514 "\n"
1515 "\tgit config --global --add safe.directory %s"),
1516 dir.buf, report.buf, quoted.buf);
1518 *nongit_ok = 1;
1519 break;
1520 case GIT_DIR_DISALLOWED_BARE:
1521 if (!nongit_ok) {
1522 die(_("cannot use bare repository '%s' (safe.bareRepository is '%s')"),
1523 dir.buf,
1524 allowed_bare_repo_to_string(get_allowed_bare_repo()));
1526 *nongit_ok = 1;
1527 break;
1528 case GIT_DIR_NONE:
1530 * As a safeguard against setup_git_directory_gently_1 returning
1531 * this value, fallthrough to BUG. Otherwise it is possible to
1532 * set startup_info->have_repository to 1 when we did nothing to
1533 * find a repository.
1535 default:
1536 BUG("unhandled setup_git_directory_gently_1() result");
1540 * At this point, nongit_ok is stable. If it is non-NULL and points
1541 * to a non-zero value, then this means that we haven't found a
1542 * repository and that the caller expects startup_info to reflect
1543 * this.
1545 * Regardless of the state of nongit_ok, startup_info->prefix and
1546 * the GIT_PREFIX environment variable must always match. For details
1547 * see Documentation/config/alias.txt.
1549 if (nongit_ok && *nongit_ok)
1550 startup_info->have_repository = 0;
1551 else
1552 startup_info->have_repository = 1;
1555 * Not all paths through the setup code will call 'set_git_dir()' (which
1556 * directly sets up the environment) so in order to guarantee that the
1557 * environment is in a consistent state after setup, explicitly setup
1558 * the environment if we have a repository.
1560 * NEEDSWORK: currently we allow bogus GIT_DIR values to be set in some
1561 * code paths so we also need to explicitly setup the environment if
1562 * the user has set GIT_DIR. It may be beneficial to disallow bogus
1563 * GIT_DIR values at some point in the future.
1565 if (/* GIT_DIR_EXPLICIT, GIT_DIR_DISCOVERED, GIT_DIR_BARE */
1566 startup_info->have_repository ||
1567 /* GIT_DIR_EXPLICIT */
1568 getenv(GIT_DIR_ENVIRONMENT)) {
1569 if (!the_repository->gitdir) {
1570 const char *gitdir = getenv(GIT_DIR_ENVIRONMENT);
1571 if (!gitdir)
1572 gitdir = DEFAULT_GIT_DIR_ENVIRONMENT;
1573 setup_git_env(gitdir);
1575 if (startup_info->have_repository) {
1576 repo_set_hash_algo(the_repository, repo_fmt.hash_algo);
1577 /* take ownership of repo_fmt.partial_clone */
1578 the_repository->repository_format_partial_clone =
1579 repo_fmt.partial_clone;
1580 repo_fmt.partial_clone = NULL;
1584 * Since precompose_string_if_needed() needs to look at
1585 * the core.precomposeunicode configuration, this
1586 * has to happen after the above block that finds
1587 * out where the repository is, i.e. a preparation
1588 * for calling git_config_get_bool().
1590 if (prefix) {
1591 prefix = precompose_string_if_needed(prefix);
1592 startup_info->prefix = prefix;
1593 setenv(GIT_PREFIX_ENVIRONMENT, prefix, 1);
1594 } else {
1595 startup_info->prefix = NULL;
1596 setenv(GIT_PREFIX_ENVIRONMENT, "", 1);
1599 setup_original_cwd();
1601 strbuf_release(&dir);
1602 strbuf_release(&gitdir);
1603 strbuf_release(&report);
1604 clear_repository_format(&repo_fmt);
1606 return prefix;
1609 int git_config_perm(const char *var, const char *value)
1611 int i;
1612 char *endptr;
1614 if (!value)
1615 return PERM_GROUP;
1617 if (!strcmp(value, "umask"))
1618 return PERM_UMASK;
1619 if (!strcmp(value, "group"))
1620 return PERM_GROUP;
1621 if (!strcmp(value, "all") ||
1622 !strcmp(value, "world") ||
1623 !strcmp(value, "everybody"))
1624 return PERM_EVERYBODY;
1626 /* Parse octal numbers */
1627 i = strtol(value, &endptr, 8);
1629 /* If not an octal number, maybe true/false? */
1630 if (*endptr != 0)
1631 return git_config_bool(var, value) ? PERM_GROUP : PERM_UMASK;
1634 * Treat values 0, 1 and 2 as compatibility cases, otherwise it is
1635 * a chmod value to restrict to.
1637 switch (i) {
1638 case PERM_UMASK: /* 0 */
1639 return PERM_UMASK;
1640 case OLD_PERM_GROUP: /* 1 */
1641 return PERM_GROUP;
1642 case OLD_PERM_EVERYBODY: /* 2 */
1643 return PERM_EVERYBODY;
1646 /* A filemode value was given: 0xxx */
1648 if ((i & 0600) != 0600)
1649 die(_("problem with core.sharedRepository filemode value "
1650 "(0%.3o).\nThe owner of files must always have "
1651 "read and write permissions."), i);
1654 * Mask filemode value. Others can not get write permission.
1655 * x flags for directories are handled separately.
1657 return -(i & 0666);
1660 void check_repository_format(struct repository_format *fmt)
1662 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
1663 if (!fmt)
1664 fmt = &repo_fmt;
1665 check_repository_format_gently(get_git_dir(), fmt, NULL);
1666 startup_info->have_repository = 1;
1667 repo_set_hash_algo(the_repository, fmt->hash_algo);
1668 the_repository->repository_format_partial_clone =
1669 xstrdup_or_null(fmt->partial_clone);
1670 clear_repository_format(&repo_fmt);
1674 * Returns the "prefix", a path to the current working directory
1675 * relative to the work tree root, or NULL, if the current working
1676 * directory is not a strict subdirectory of the work tree root. The
1677 * prefix always ends with a '/' character.
1679 const char *setup_git_directory(void)
1681 return setup_git_directory_gently(NULL);
1684 const char *resolve_gitdir_gently(const char *suspect, int *return_error_code)
1686 if (is_git_directory(suspect))
1687 return suspect;
1688 return read_gitfile_gently(suspect, return_error_code);
1691 /* if any standard file descriptor is missing open it to /dev/null */
1692 void sanitize_stdfds(void)
1694 int fd = xopen("/dev/null", O_RDWR);
1695 while (fd < 2)
1696 fd = xdup(fd);
1697 if (fd > 2)
1698 close(fd);
1701 int daemonize(void)
1703 #ifdef NO_POSIX_GOODIES
1704 errno = ENOSYS;
1705 return -1;
1706 #else
1707 switch (fork()) {
1708 case 0:
1709 break;
1710 case -1:
1711 die_errno(_("fork failed"));
1712 default:
1713 exit(0);
1715 if (setsid() == -1)
1716 die_errno(_("setsid failed"));
1717 close(0);
1718 close(1);
1719 close(2);
1720 sanitize_stdfds();
1721 return 0;
1722 #endif
1725 #ifndef DEFAULT_GIT_TEMPLATE_DIR
1726 #define DEFAULT_GIT_TEMPLATE_DIR "/usr/share/git-core/templates"
1727 #endif
1729 struct template_dir_cb_data {
1730 char *path;
1731 int initialized;
1734 static int template_dir_cb(const char *key, const char *value, void *d)
1736 struct template_dir_cb_data *data = d;
1738 if (strcmp(key, "init.templatedir"))
1739 return 0;
1741 if (!value) {
1742 data->path = NULL;
1743 } else {
1744 char *path = NULL;
1746 FREE_AND_NULL(data->path);
1747 if (!git_config_pathname((const char **)&path, key, value))
1748 data->path = path ? path : xstrdup(value);
1751 return 0;
1754 const char *get_template_dir(const char *option_template)
1756 const char *template_dir = option_template;
1758 if (!template_dir)
1759 template_dir = getenv(TEMPLATE_DIR_ENVIRONMENT);
1760 if (!template_dir) {
1761 static struct template_dir_cb_data data;
1763 if (!data.initialized) {
1764 git_protected_config(template_dir_cb, &data);
1765 data.initialized = 1;
1767 template_dir = data.path;
1769 if (!template_dir) {
1770 static char *dir;
1772 if (!dir)
1773 dir = system_path(DEFAULT_GIT_TEMPLATE_DIR);
1774 template_dir = dir;
1776 return template_dir;