2 #include "repository.h"
5 #include "string-list.h"
6 #include "chdir-notify.h"
7 #include "promisor-remote.h"
9 static int inside_git_dir = -1;
10 static int inside_work_tree = -1;
11 static int work_tree_config_is_bogus;
13 static struct startup_info the_startup_info;
14 struct startup_info *startup_info = &the_startup_info;
17 * The input parameter must contain an absolute path, and it must already be
20 * Find the part of an absolute path that lies inside the work tree by
21 * dereferencing symlinks outside the work tree, for example:
22 * /dir1/repo/dir2/file (work tree is /dir1/repo) -> dir2/file
23 * /dir/file (work tree is /) -> dir/file
24 * /dir/symlink1/symlink2 (symlink1 points to work tree) -> symlink2
25 * /dir/repolink/file (repolink points to /dir/repo) -> file
26 * /dir/repo (exactly equal to work tree) -> (empty string)
28 static int abspath_part_inside_repo(char *path)
34 const char *work_tree = get_git_work_tree();
38 wtlen = strlen(work_tree);
40 off = offset_1st_component(path);
42 /* check if work tree is already the prefix */
43 if (wtlen <= len && !fspathncmp(path, work_tree, wtlen)) {
44 if (path[wtlen] == '/') {
45 memmove(path, path + wtlen + 1, len - wtlen);
47 } else if (path[wtlen - 1] == '/' || path[wtlen] == '\0') {
48 /* work tree is the root, or the whole path */
49 memmove(path, path + wtlen, len - wtlen + 1);
52 /* work tree might match beginning of a symlink to work tree */
58 /* check each '/'-terminated level */
63 if (fspathcmp(real_path(path0), work_tree) == 0) {
64 memmove(path0, path + 1, len - (path - path0));
71 /* check whole path */
72 if (fspathcmp(real_path(path0), work_tree) == 0) {
81 * Normalize "path", prepending the "prefix" for relative paths. If
82 * remaining_prefix is not NULL, return the actual prefix still
83 * remains in the path. For example, prefix = sub1/sub2/ and path is
85 * foo -> sub1/sub2/foo (full prefix)
86 * ../foo -> sub1/foo (remaining prefix is sub1/)
87 * ../../bar -> bar (no remaining prefix)
88 * ../../sub1/sub2/foo -> sub1/sub2/foo (but no remaining prefix)
89 * `pwd`/../bar -> sub1/bar (no remaining prefix)
91 char *prefix_path_gently(const char *prefix, int len,
92 int *remaining_prefix, const char *path)
94 const char *orig = path;
96 if (is_absolute_path(orig)) {
97 sanitized = xmallocz(strlen(path));
99 *remaining_prefix = 0;
100 if (normalize_path_copy_len(sanitized, path, remaining_prefix)) {
104 if (abspath_part_inside_repo(sanitized)) {
109 sanitized = xstrfmt("%.*s%s", len, len ? prefix : "", path);
110 if (remaining_prefix)
111 *remaining_prefix = len;
112 if (normalize_path_copy_len(sanitized, sanitized, remaining_prefix)) {
120 char *prefix_path(const char *prefix, int len, const char *path)
122 char *r = prefix_path_gently(prefix, len, NULL, path);
124 die(_("'%s' is outside repository"), path);
128 int path_inside_repo(const char *prefix, const char *path)
130 int len = prefix ? strlen(prefix) : 0;
131 char *r = prefix_path_gently(prefix, len, NULL, path);
139 int check_filename(const char *prefix, const char *arg)
141 char *to_free = NULL;
144 if (skip_prefix(arg, ":/", &arg)) {
145 if (!*arg) /* ":/" is root dir, always exists */
148 } else if (skip_prefix(arg, ":!", &arg) ||
149 skip_prefix(arg, ":^", &arg)) {
150 if (!*arg) /* excluding everything is silly, but allowed */
155 arg = to_free = prefix_filename(prefix, arg);
157 if (!lstat(arg, &st)) {
159 return 1; /* file exists */
161 if (is_missing_file_error(errno)) {
163 return 0; /* file does not exist */
165 die_errno(_("failed to stat '%s'"), arg);
168 static void NORETURN die_verify_filename(struct repository *r,
171 int diagnose_misspelt_rev)
173 if (!diagnose_misspelt_rev)
174 die(_("%s: no such path in the working tree.\n"
175 "Use 'git <command> -- <path>...' to specify paths that do not exist locally."),
178 * Saying "'(icase)foo' does not exist in the index" when the
179 * user gave us ":(icase)foo" is just stupid. A magic pathspec
180 * begins with a colon and is followed by a non-alnum; do not
181 * let maybe_die_on_misspelt_object_name() even trigger.
183 if (!(arg[0] == ':' && !isalnum(arg[1])))
184 maybe_die_on_misspelt_object_name(r, arg, prefix);
186 /* ... or fall back the most general message. */
187 die(_("ambiguous argument '%s': unknown revision or path not in the working tree.\n"
188 "Use '--' to separate paths from revisions, like this:\n"
189 "'git <command> [<revision>...] -- [<file>...]'"), arg);
194 * Check for arguments that don't resolve as actual files,
195 * but which look sufficiently like pathspecs that we'll consider
196 * them such for the purposes of rev/pathspec DWIM parsing.
198 static int looks_like_pathspec(const char *arg)
204 * Wildcard characters imply the user is looking to match pathspecs
205 * that aren't in the filesystem. Note that this doesn't include
206 * backslash even though it's a glob special; by itself it doesn't
207 * cause any increase in the match. Likewise ignore backslash-escaped
208 * wildcard characters.
210 for (p = arg; *p; p++) {
213 } else if (is_glob_special(*p)) {
221 /* long-form pathspec magic */
222 if (starts_with(arg, ":("))
229 * Verify a filename that we got as an argument for a pathspec
230 * entry. Note that a filename that begins with "-" never verifies
231 * as true, because even if such a filename were to exist, we want
232 * it to be preceded by the "--" marker (or we want the user to
233 * use a format like "./-filename")
235 * The "diagnose_misspelt_rev" is used to provide a user-friendly
236 * diagnosis when dying upon finding that "name" is not a pathname.
237 * If set to 1, the diagnosis will try to diagnose "name" as an
238 * invalid object name (e.g. HEAD:foo). If set to 0, the diagnosis
239 * will only complain about an inexisting file.
241 * This function is typically called to check that a "file or rev"
242 * argument is unambiguous. In this case, the caller will want
243 * diagnose_misspelt_rev == 1 when verifying the first non-rev
244 * argument (which could have been a revision), and
245 * diagnose_misspelt_rev == 0 for the next ones (because we already
246 * saw a filename, there's not ambiguity anymore).
248 void verify_filename(const char *prefix,
250 int diagnose_misspelt_rev)
253 die(_("option '%s' must come before non-option arguments"), arg);
254 if (looks_like_pathspec(arg) || check_filename(prefix, arg))
256 die_verify_filename(the_repository, prefix, arg, diagnose_misspelt_rev);
260 * Opposite of the above: the command line did not have -- marker
261 * and we parsed the arg as a refname. It should not be interpretable
264 void verify_non_filename(const char *prefix, const char *arg)
266 if (!is_inside_work_tree() || is_inside_git_dir())
270 if (!check_filename(prefix, arg))
272 die(_("ambiguous argument '%s': both revision and filename\n"
273 "Use '--' to separate paths from revisions, like this:\n"
274 "'git <command> [<revision>...] -- [<file>...]'"), arg);
277 int get_common_dir(struct strbuf *sb, const char *gitdir)
279 const char *git_env_common_dir = getenv(GIT_COMMON_DIR_ENVIRONMENT);
280 if (git_env_common_dir) {
281 strbuf_addstr(sb, git_env_common_dir);
284 return get_common_dir_noenv(sb, gitdir);
288 int get_common_dir_noenv(struct strbuf *sb, const char *gitdir)
290 struct strbuf data = STRBUF_INIT;
291 struct strbuf path = STRBUF_INIT;
294 strbuf_addf(&path, "%s/commondir", gitdir);
295 if (file_exists(path.buf)) {
296 if (strbuf_read_file(&data, path.buf, 0) <= 0)
297 die_errno(_("failed to read %s"), path.buf);
298 while (data.len && (data.buf[data.len - 1] == '\n' ||
299 data.buf[data.len - 1] == '\r'))
301 data.buf[data.len] = '\0';
303 if (!is_absolute_path(data.buf))
304 strbuf_addf(&path, "%s/", gitdir);
305 strbuf_addbuf(&path, &data);
306 strbuf_add_real_path(sb, path.buf);
309 strbuf_addstr(sb, gitdir);
312 strbuf_release(&data);
313 strbuf_release(&path);
318 * Test if it looks like we're at a git directory.
321 * - either an objects/ directory _or_ the proper
322 * GIT_OBJECT_DIRECTORY environment variable
323 * - a refs/ directory
324 * - either a HEAD symlink or a HEAD file that is formatted as
325 * a proper "ref:", or a regular file HEAD that has a properly
326 * formatted sha1 object name.
328 int is_git_directory(const char *suspect)
330 struct strbuf path = STRBUF_INIT;
334 /* Check worktree-related signatures */
335 strbuf_addstr(&path, suspect);
336 strbuf_complete(&path, '/');
337 strbuf_addstr(&path, "HEAD");
338 if (validate_headref(path.buf))
342 get_common_dir(&path, suspect);
345 /* Check non-worktree-related signatures */
346 if (getenv(DB_ENVIRONMENT)) {
347 if (access(getenv(DB_ENVIRONMENT), X_OK))
351 strbuf_setlen(&path, len);
352 strbuf_addstr(&path, "/objects");
353 if (access(path.buf, X_OK))
357 strbuf_setlen(&path, len);
358 strbuf_addstr(&path, "/refs");
359 if (access(path.buf, X_OK))
364 strbuf_release(&path);
368 int is_nonbare_repository_dir(struct strbuf *path)
372 size_t orig_path_len = path->len;
373 assert(orig_path_len != 0);
374 strbuf_complete(path, '/');
375 strbuf_addstr(path, ".git");
376 if (read_gitfile_gently(path->buf, &gitfile_error) || is_git_directory(path->buf))
378 if (gitfile_error == READ_GITFILE_ERR_OPEN_FAILED ||
379 gitfile_error == READ_GITFILE_ERR_READ_FAILED)
381 strbuf_setlen(path, orig_path_len);
385 int is_inside_git_dir(void)
387 if (inside_git_dir < 0)
388 inside_git_dir = is_inside_dir(get_git_dir());
389 return inside_git_dir;
392 int is_inside_work_tree(void)
394 if (inside_work_tree < 0)
395 inside_work_tree = is_inside_dir(get_git_work_tree());
396 return inside_work_tree;
399 void setup_work_tree(void)
401 const char *work_tree;
402 static int initialized = 0;
407 if (work_tree_config_is_bogus)
408 die(_("unable to set up work tree using invalid config"));
410 work_tree = get_git_work_tree();
411 if (!work_tree || chdir_notify(work_tree))
412 die(_("this operation must be run in a work tree"));
415 * Make sure subsequent git processes find correct worktree
416 * if $GIT_WORK_TREE is set relative
418 if (getenv(GIT_WORK_TREE_ENVIRONMENT))
419 setenv(GIT_WORK_TREE_ENVIRONMENT, ".", 1);
424 static int read_worktree_config(const char *var, const char *value, void *vdata)
426 struct repository_format *data = vdata;
428 if (strcmp(var, "core.bare") == 0) {
429 data->is_bare = git_config_bool(var, value);
430 } else if (strcmp(var, "core.worktree") == 0) {
432 return config_error_nonbool(var);
433 free(data->work_tree);
434 data->work_tree = xstrdup(value);
439 static int check_repo_format(const char *var, const char *value, void *vdata)
441 struct repository_format *data = vdata;
444 if (strcmp(var, "core.repositoryformatversion") == 0)
445 data->version = git_config_int(var, value);
446 else if (skip_prefix(var, "extensions.", &ext)) {
448 * record any known extensions here; otherwise,
449 * we fall through to recording it as unknown, and
450 * check_repository_format will complain
452 if (!strcmp(ext, "noop"))
454 else if (!strcmp(ext, "preciousobjects"))
455 data->precious_objects = git_config_bool(var, value);
456 else if (!strcmp(ext, "partialclone")) {
458 return config_error_nonbool(var);
459 data->partial_clone = xstrdup(value);
460 } else if (!strcmp(ext, "worktreeconfig"))
461 data->worktree_config = git_config_bool(var, value);
463 string_list_append(&data->unknown_extensions, ext);
466 return read_worktree_config(var, value, vdata);
469 static int check_repository_format_gently(const char *gitdir, struct repository_format *candidate, int *nongit_ok)
471 struct strbuf sb = STRBUF_INIT;
472 struct strbuf err = STRBUF_INIT;
475 has_common = get_common_dir(&sb, gitdir);
476 strbuf_addstr(&sb, "/config");
477 read_repository_format(candidate, sb.buf);
481 * For historical use of check_repository_format() in git-init,
482 * we treat a missing config as a silent "ok", even when nongit_ok
485 if (candidate->version < 0)
488 if (verify_repository_format(candidate, &err) < 0) {
490 warning("%s", err.buf);
491 strbuf_release(&err);
498 repository_format_precious_objects = candidate->precious_objects;
499 set_repository_format_partial_clone(candidate->partial_clone);
500 repository_format_worktree_config = candidate->worktree_config;
501 string_list_clear(&candidate->unknown_extensions, 0);
503 if (repository_format_worktree_config) {
505 * pick up core.bare and core.worktree from per-worktree
508 strbuf_addf(&sb, "%s/config.worktree", gitdir);
509 git_config_from_file(read_worktree_config, sb.buf, candidate);
515 if (candidate->is_bare != -1) {
516 is_bare_repository_cfg = candidate->is_bare;
517 if (is_bare_repository_cfg == 1)
518 inside_work_tree = -1;
520 if (candidate->work_tree) {
521 free(git_work_tree_cfg);
522 git_work_tree_cfg = xstrdup(candidate->work_tree);
523 inside_work_tree = -1;
530 static void init_repository_format(struct repository_format *format)
532 const struct repository_format fresh = REPOSITORY_FORMAT_INIT;
534 memcpy(format, &fresh, sizeof(fresh));
537 int read_repository_format(struct repository_format *format, const char *path)
539 clear_repository_format(format);
540 git_config_from_file(check_repo_format, path, format);
541 if (format->version == -1)
542 clear_repository_format(format);
543 return format->version;
546 void clear_repository_format(struct repository_format *format)
548 string_list_clear(&format->unknown_extensions, 0);
549 free(format->work_tree);
550 free(format->partial_clone);
551 init_repository_format(format);
554 int verify_repository_format(const struct repository_format *format,
557 if (GIT_REPO_VERSION_READ < format->version) {
558 strbuf_addf(err, _("Expected git repo version <= %d, found %d"),
559 GIT_REPO_VERSION_READ, format->version);
563 if (format->version >= 1 && format->unknown_extensions.nr) {
566 strbuf_addstr(err, _("unknown repository extensions found:"));
568 for (i = 0; i < format->unknown_extensions.nr; i++)
569 strbuf_addf(err, "\n\t%s",
570 format->unknown_extensions.items[i].string);
577 void read_gitfile_error_die(int error_code, const char *path, const char *dir)
579 switch (error_code) {
580 case READ_GITFILE_ERR_STAT_FAILED:
581 case READ_GITFILE_ERR_NOT_A_FILE:
582 /* non-fatal; follow return path */
584 case READ_GITFILE_ERR_OPEN_FAILED:
585 die_errno(_("error opening '%s'"), path);
586 case READ_GITFILE_ERR_TOO_LARGE:
587 die(_("too large to be a .git file: '%s'"), path);
588 case READ_GITFILE_ERR_READ_FAILED:
589 die(_("error reading %s"), path);
590 case READ_GITFILE_ERR_INVALID_FORMAT:
591 die(_("invalid gitfile format: %s"), path);
592 case READ_GITFILE_ERR_NO_PATH:
593 die(_("no path in gitfile: %s"), path);
594 case READ_GITFILE_ERR_NOT_A_REPO:
595 die(_("not a git repository: %s"), dir);
597 BUG("unknown error code");
602 * Try to read the location of the git directory from the .git file,
603 * return path to git directory if found. The return value comes from
606 * On failure, if return_error_code is not NULL, return_error_code
607 * will be set to an error code and NULL will be returned. If
608 * return_error_code is NULL the function will die instead (for most
611 const char *read_gitfile_gently(const char *path, int *return_error_code)
613 const int max_file_size = 1 << 20; /* 1MB */
622 if (stat(path, &st)) {
623 /* NEEDSWORK: discern between ENOENT vs other errors */
624 error_code = READ_GITFILE_ERR_STAT_FAILED;
627 if (!S_ISREG(st.st_mode)) {
628 error_code = READ_GITFILE_ERR_NOT_A_FILE;
631 if (st.st_size > max_file_size) {
632 error_code = READ_GITFILE_ERR_TOO_LARGE;
635 fd = open(path, O_RDONLY);
637 error_code = READ_GITFILE_ERR_OPEN_FAILED;
640 buf = xmallocz(st.st_size);
641 len = read_in_full(fd, buf, st.st_size);
643 if (len != st.st_size) {
644 error_code = READ_GITFILE_ERR_READ_FAILED;
647 if (!starts_with(buf, "gitdir: ")) {
648 error_code = READ_GITFILE_ERR_INVALID_FORMAT;
651 while (buf[len - 1] == '\n' || buf[len - 1] == '\r')
654 error_code = READ_GITFILE_ERR_NO_PATH;
660 if (!is_absolute_path(dir) && (slash = strrchr(path, '/'))) {
661 size_t pathlen = slash+1 - path;
662 dir = xstrfmt("%.*s%.*s", (int)pathlen, path,
663 (int)(len - 8), buf + 8);
667 if (!is_git_directory(dir)) {
668 error_code = READ_GITFILE_ERR_NOT_A_REPO;
671 path = real_path(dir);
674 if (return_error_code)
675 *return_error_code = error_code;
677 read_gitfile_error_die(error_code, path, dir);
680 return error_code ? NULL : path;
683 static const char *setup_explicit_git_dir(const char *gitdirenv,
685 struct repository_format *repo_fmt,
688 const char *work_tree_env = getenv(GIT_WORK_TREE_ENVIRONMENT);
689 const char *worktree;
693 if (PATH_MAX - 40 < strlen(gitdirenv))
694 die(_("'$%s' too big"), GIT_DIR_ENVIRONMENT);
696 gitfile = (char*)read_gitfile(gitdirenv);
698 gitfile = xstrdup(gitfile);
702 if (!is_git_directory(gitdirenv)) {
708 die(_("not a git repository: '%s'"), gitdirenv);
711 if (check_repository_format_gently(gitdirenv, repo_fmt, nongit_ok)) {
716 /* #3, #7, #11, #15, #19, #23, #27, #31 (see t1510) */
718 set_git_work_tree(work_tree_env);
719 else if (is_bare_repository_cfg > 0) {
720 if (git_work_tree_cfg) {
722 warning("core.bare and core.worktree do not make sense");
723 work_tree_config_is_bogus = 1;
727 set_git_dir(gitdirenv);
731 else if (git_work_tree_cfg) { /* #6, #14 */
732 if (is_absolute_path(git_work_tree_cfg))
733 set_git_work_tree(git_work_tree_cfg);
736 if (chdir(gitdirenv))
737 die_errno(_("cannot chdir to '%s'"), gitdirenv);
738 if (chdir(git_work_tree_cfg))
739 die_errno(_("cannot chdir to '%s'"), git_work_tree_cfg);
740 core_worktree = xgetcwd();
742 die_errno(_("cannot come back to cwd"));
743 set_git_work_tree(core_worktree);
747 else if (!git_env_bool(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, 1)) {
749 set_git_dir(gitdirenv);
754 set_git_work_tree(".");
756 /* set_git_work_tree() must have been called by now */
757 worktree = get_git_work_tree();
759 /* both get_git_work_tree() and cwd are already normalized */
760 if (!strcmp(cwd->buf, worktree)) { /* cwd == worktree */
761 set_git_dir(gitdirenv);
766 offset = dir_inside_of(cwd->buf, worktree);
767 if (offset >= 0) { /* cwd inside worktree? */
768 set_git_dir(real_path(gitdirenv));
770 die_errno(_("cannot chdir to '%s'"), worktree);
771 strbuf_addch(cwd, '/');
773 return cwd->buf + offset;
776 /* cwd outside worktree */
777 set_git_dir(gitdirenv);
782 static const char *setup_discovered_git_dir(const char *gitdir,
783 struct strbuf *cwd, int offset,
784 struct repository_format *repo_fmt,
787 if (check_repository_format_gently(gitdir, repo_fmt, nongit_ok))
790 /* --work-tree is set without --git-dir; use discovered one */
791 if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
792 char *to_free = NULL;
795 if (offset != cwd->len && !is_absolute_path(gitdir))
796 gitdir = to_free = real_pathdup(gitdir, 1);
798 die_errno(_("cannot come back to cwd"));
799 ret = setup_explicit_git_dir(gitdir, cwd, repo_fmt, nongit_ok);
804 /* #16.2, #17.2, #20.2, #21.2, #24, #25, #28, #29 (see t1510) */
805 if (is_bare_repository_cfg > 0) {
806 set_git_dir(offset == cwd->len ? gitdir : real_path(gitdir));
808 die_errno(_("cannot come back to cwd"));
812 /* #0, #1, #5, #8, #9, #12, #13 */
813 set_git_work_tree(".");
814 if (strcmp(gitdir, DEFAULT_GIT_DIR_ENVIRONMENT))
817 inside_work_tree = 1;
818 if (offset >= cwd->len)
821 /* Make "offset" point past the '/' (already the case for root dirs) */
822 if (offset != offset_1st_component(cwd->buf))
824 /* Add a '/' at the end */
825 strbuf_addch(cwd, '/');
826 return cwd->buf + offset;
829 /* #16.1, #17.1, #20.1, #21.1, #22.1 (see t1510) */
830 static const char *setup_bare_git_dir(struct strbuf *cwd, int offset,
831 struct repository_format *repo_fmt,
836 if (check_repository_format_gently(".", repo_fmt, nongit_ok))
839 setenv(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, "0", 1);
841 /* --work-tree is set without --git-dir; use discovered one */
842 if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
843 static const char *gitdir;
845 gitdir = offset == cwd->len ? "." : xmemdupz(cwd->buf, offset);
847 die_errno(_("cannot come back to cwd"));
848 return setup_explicit_git_dir(gitdir, cwd, repo_fmt, nongit_ok);
852 inside_work_tree = 0;
853 if (offset != cwd->len) {
855 die_errno(_("cannot come back to cwd"));
856 root_len = offset_1st_component(cwd->buf);
857 strbuf_setlen(cwd, offset > root_len ? offset : root_len);
858 set_git_dir(cwd->buf);
865 static dev_t get_device_or_die(const char *path, const char *prefix, int prefix_len)
868 if (stat(path, &buf)) {
869 die_errno(_("failed to stat '%*s%s%s'"),
871 prefix ? prefix : "",
872 prefix ? "/" : "", path);
878 * A "string_list_each_func_t" function that canonicalizes an entry
879 * from GIT_CEILING_DIRECTORIES using real_path_if_valid(), or
880 * discards it if unusable. The presence of an empty entry in
881 * GIT_CEILING_DIRECTORIES turns off canonicalization for all
882 * subsequent entries.
884 static int canonicalize_ceiling_entry(struct string_list_item *item,
887 int *empty_entry_found = cb_data;
888 char *ceil = item->string;
891 *empty_entry_found = 1;
893 } else if (!is_absolute_path(ceil)) {
895 } else if (*empty_entry_found) {
896 /* Keep entry but do not canonicalize it */
899 char *real_path = real_pathdup(ceil, 0);
904 item->string = real_path;
909 enum discovery_result {
914 /* these are errors */
915 GIT_DIR_HIT_CEILING = -1,
916 GIT_DIR_HIT_MOUNT_POINT = -2,
917 GIT_DIR_INVALID_GITFILE = -3
921 * We cannot decide in this function whether we are in the work tree or
922 * not, since the config can only be read _after_ this function was called.
924 * Also, we avoid changing any global state (such as the current working
925 * directory) to allow early callers.
927 * The directory where the search should start needs to be passed in via the
928 * `dir` parameter; upon return, the `dir` buffer will contain the path of
929 * the directory where the search ended, and `gitdir` will contain the path of
930 * the discovered .git/ directory, if any. If `gitdir` is not absolute, it
931 * is relative to `dir` (i.e. *not* necessarily the cwd).
933 static enum discovery_result setup_git_directory_gently_1(struct strbuf *dir,
934 struct strbuf *gitdir,
937 const char *env_ceiling_dirs = getenv(CEILING_DIRECTORIES_ENVIRONMENT);
938 struct string_list ceiling_dirs = STRING_LIST_INIT_DUP;
939 const char *gitdirenv;
940 int ceil_offset = -1, min_offset = offset_1st_component(dir->buf);
941 dev_t current_device = 0;
942 int one_filesystem = 1;
945 * If GIT_DIR is set explicitly, we're not going
946 * to do any discovery, but we still do repository
949 gitdirenv = getenv(GIT_DIR_ENVIRONMENT);
951 strbuf_addstr(gitdir, gitdirenv);
952 return GIT_DIR_EXPLICIT;
955 if (env_ceiling_dirs) {
956 int empty_entry_found = 0;
958 string_list_split(&ceiling_dirs, env_ceiling_dirs, PATH_SEP, -1);
959 filter_string_list(&ceiling_dirs, 0,
960 canonicalize_ceiling_entry, &empty_entry_found);
961 ceil_offset = longest_ancestor_length(dir->buf, &ceiling_dirs);
962 string_list_clear(&ceiling_dirs, 0);
966 ceil_offset = min_offset - 2;
968 if (min_offset && min_offset == dir->len &&
969 !is_dir_sep(dir->buf[min_offset - 1])) {
970 strbuf_addch(dir, '/');
975 * Test in the following order (relative to the dir):
976 * - .git (file containing "gitdir: <path>")
985 one_filesystem = !git_env_bool("GIT_DISCOVERY_ACROSS_FILESYSTEM", 0);
987 current_device = get_device_or_die(dir->buf, NULL, 0);
989 int offset = dir->len, error_code = 0;
991 if (offset > min_offset)
992 strbuf_addch(dir, '/');
993 strbuf_addstr(dir, DEFAULT_GIT_DIR_ENVIRONMENT);
994 gitdirenv = read_gitfile_gently(dir->buf, die_on_error ?
998 error_code == READ_GITFILE_ERR_NOT_A_FILE) {
999 /* NEEDSWORK: fail if .git is not file nor dir */
1000 if (is_git_directory(dir->buf))
1001 gitdirenv = DEFAULT_GIT_DIR_ENVIRONMENT;
1002 } else if (error_code != READ_GITFILE_ERR_STAT_FAILED)
1003 return GIT_DIR_INVALID_GITFILE;
1005 strbuf_setlen(dir, offset);
1007 strbuf_addstr(gitdir, gitdirenv);
1008 return GIT_DIR_DISCOVERED;
1011 if (is_git_directory(dir->buf)) {
1012 strbuf_addstr(gitdir, ".");
1013 return GIT_DIR_BARE;
1016 if (offset <= min_offset)
1017 return GIT_DIR_HIT_CEILING;
1019 while (--offset > ceil_offset && !is_dir_sep(dir->buf[offset]))
1021 if (offset <= ceil_offset)
1022 return GIT_DIR_HIT_CEILING;
1024 strbuf_setlen(dir, offset > min_offset ? offset : min_offset);
1025 if (one_filesystem &&
1026 current_device != get_device_or_die(dir->buf, NULL, offset))
1027 return GIT_DIR_HIT_MOUNT_POINT;
1031 int discover_git_directory(struct strbuf *commondir,
1032 struct strbuf *gitdir)
1034 struct strbuf dir = STRBUF_INIT, err = STRBUF_INIT;
1035 size_t gitdir_offset = gitdir->len, cwd_len;
1036 size_t commondir_offset = commondir->len;
1037 struct repository_format candidate = REPOSITORY_FORMAT_INIT;
1039 if (strbuf_getcwd(&dir))
1043 if (setup_git_directory_gently_1(&dir, gitdir, 0) <= 0) {
1044 strbuf_release(&dir);
1049 * The returned gitdir is relative to dir, and if dir does not reflect
1050 * the current working directory, we simply make the gitdir absolute.
1052 if (dir.len < cwd_len && !is_absolute_path(gitdir->buf + gitdir_offset)) {
1053 /* Avoid a trailing "/." */
1054 if (!strcmp(".", gitdir->buf + gitdir_offset))
1055 strbuf_setlen(gitdir, gitdir_offset);
1057 strbuf_addch(&dir, '/');
1058 strbuf_insert(gitdir, gitdir_offset, dir.buf, dir.len);
1061 get_common_dir(commondir, gitdir->buf + gitdir_offset);
1064 strbuf_addf(&dir, "%s/config", commondir->buf + commondir_offset);
1065 read_repository_format(&candidate, dir.buf);
1066 strbuf_release(&dir);
1068 if (verify_repository_format(&candidate, &err) < 0) {
1069 warning("ignoring git dir '%s': %s",
1070 gitdir->buf + gitdir_offset, err.buf);
1071 strbuf_release(&err);
1072 strbuf_setlen(commondir, commondir_offset);
1073 strbuf_setlen(gitdir, gitdir_offset);
1074 clear_repository_format(&candidate);
1078 clear_repository_format(&candidate);
1082 const char *setup_git_directory_gently(int *nongit_ok)
1084 static struct strbuf cwd = STRBUF_INIT;
1085 struct strbuf dir = STRBUF_INIT, gitdir = STRBUF_INIT;
1086 const char *prefix = NULL;
1087 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
1090 * We may have read an incomplete configuration before
1091 * setting-up the git directory. If so, clear the cache so
1092 * that the next queries to the configuration reload complete
1093 * configuration (including the per-repo config file that we
1094 * ignored previously).
1099 * Let's assume that we are in a git repository.
1100 * If it turns out later that we are somewhere else, the value will be
1101 * updated accordingly.
1106 if (strbuf_getcwd(&cwd))
1107 die_errno(_("Unable to read current working directory"));
1108 strbuf_addbuf(&dir, &cwd);
1110 switch (setup_git_directory_gently_1(&dir, &gitdir, 1)) {
1111 case GIT_DIR_EXPLICIT:
1112 prefix = setup_explicit_git_dir(gitdir.buf, &cwd, &repo_fmt, nongit_ok);
1114 case GIT_DIR_DISCOVERED:
1115 if (dir.len < cwd.len && chdir(dir.buf))
1116 die(_("cannot change to '%s'"), dir.buf);
1117 prefix = setup_discovered_git_dir(gitdir.buf, &cwd, dir.len,
1118 &repo_fmt, nongit_ok);
1121 if (dir.len < cwd.len && chdir(dir.buf))
1122 die(_("cannot change to '%s'"), dir.buf);
1123 prefix = setup_bare_git_dir(&cwd, dir.len, &repo_fmt, nongit_ok);
1125 case GIT_DIR_HIT_CEILING:
1127 die(_("not a git repository (or any of the parent directories): %s"),
1128 DEFAULT_GIT_DIR_ENVIRONMENT);
1131 case GIT_DIR_HIT_MOUNT_POINT:
1133 die(_("not a git repository (or any parent up to mount point %s)\n"
1134 "Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set)."),
1140 * As a safeguard against setup_git_directory_gently_1 returning
1141 * this value, fallthrough to BUG. Otherwise it is possible to
1142 * set startup_info->have_repository to 1 when we did nothing to
1143 * find a repository.
1146 BUG("unhandled setup_git_directory_1() result");
1150 * At this point, nongit_ok is stable. If it is non-NULL and points
1151 * to a non-zero value, then this means that we haven't found a
1152 * repository and that the caller expects startup_info to reflect
1155 * Regardless of the state of nongit_ok, startup_info->prefix and
1156 * the GIT_PREFIX environment variable must always match. For details
1157 * see Documentation/config/alias.txt.
1159 if (nongit_ok && *nongit_ok) {
1160 startup_info->have_repository = 0;
1161 startup_info->prefix = NULL;
1162 setenv(GIT_PREFIX_ENVIRONMENT, "", 1);
1164 startup_info->have_repository = 1;
1165 startup_info->prefix = prefix;
1167 setenv(GIT_PREFIX_ENVIRONMENT, prefix, 1);
1169 setenv(GIT_PREFIX_ENVIRONMENT, "", 1);
1173 * Not all paths through the setup code will call 'set_git_dir()' (which
1174 * directly sets up the environment) so in order to guarantee that the
1175 * environment is in a consistent state after setup, explicitly setup
1176 * the environment if we have a repository.
1178 * NEEDSWORK: currently we allow bogus GIT_DIR values to be set in some
1179 * code paths so we also need to explicitly setup the environment if
1180 * the user has set GIT_DIR. It may be beneficial to disallow bogus
1181 * GIT_DIR values at some point in the future.
1183 if (/* GIT_DIR_EXPLICIT, GIT_DIR_DISCOVERED, GIT_DIR_BARE */
1184 startup_info->have_repository ||
1185 /* GIT_DIR_EXPLICIT */
1186 getenv(GIT_DIR_ENVIRONMENT)) {
1187 if (!the_repository->gitdir) {
1188 const char *gitdir = getenv(GIT_DIR_ENVIRONMENT);
1190 gitdir = DEFAULT_GIT_DIR_ENVIRONMENT;
1191 setup_git_env(gitdir);
1193 if (startup_info->have_repository)
1194 repo_set_hash_algo(the_repository, repo_fmt.hash_algo);
1197 strbuf_release(&dir);
1198 strbuf_release(&gitdir);
1199 clear_repository_format(&repo_fmt);
1204 int git_config_perm(const char *var, const char *value)
1212 if (!strcmp(value, "umask"))
1214 if (!strcmp(value, "group"))
1216 if (!strcmp(value, "all") ||
1217 !strcmp(value, "world") ||
1218 !strcmp(value, "everybody"))
1219 return PERM_EVERYBODY;
1221 /* Parse octal numbers */
1222 i = strtol(value, &endptr, 8);
1224 /* If not an octal number, maybe true/false? */
1226 return git_config_bool(var, value) ? PERM_GROUP : PERM_UMASK;
1229 * Treat values 0, 1 and 2 as compatibility cases, otherwise it is
1230 * a chmod value to restrict to.
1233 case PERM_UMASK: /* 0 */
1235 case OLD_PERM_GROUP: /* 1 */
1237 case OLD_PERM_EVERYBODY: /* 2 */
1238 return PERM_EVERYBODY;
1241 /* A filemode value was given: 0xxx */
1243 if ((i & 0600) != 0600)
1244 die(_("problem with core.sharedRepository filemode value "
1245 "(0%.3o).\nThe owner of files must always have "
1246 "read and write permissions."), i);
1249 * Mask filemode value. Others can not get write permission.
1250 * x flags for directories are handled separately.
1255 void check_repository_format(void)
1257 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
1258 check_repository_format_gently(get_git_dir(), &repo_fmt, NULL);
1259 startup_info->have_repository = 1;
1260 clear_repository_format(&repo_fmt);
1264 * Returns the "prefix", a path to the current working directory
1265 * relative to the work tree root, or NULL, if the current working
1266 * directory is not a strict subdirectory of the work tree root. The
1267 * prefix always ends with a '/' character.
1269 const char *setup_git_directory(void)
1271 return setup_git_directory_gently(NULL);
1274 const char *resolve_gitdir_gently(const char *suspect, int *return_error_code)
1276 if (is_git_directory(suspect))
1278 return read_gitfile_gently(suspect, return_error_code);
1281 /* if any standard file descriptor is missing open it to /dev/null */
1282 void sanitize_stdfds(void)
1284 int fd = open("/dev/null", O_RDWR, 0);
1285 while (fd != -1 && fd < 2)
1288 die_errno(_("open /dev/null or dup failed"));
1295 #ifdef NO_POSIX_GOODIES
1303 die_errno(_("fork failed"));
1308 die_errno(_("setsid failed"));