2 #include "repository.h"
5 #include "string-list.h"
6 #include "chdir-notify.h"
8 static int inside_git_dir = -1;
9 static int inside_work_tree = -1;
10 static int work_tree_config_is_bogus;
12 static struct startup_info the_startup_info;
13 struct startup_info *startup_info = &the_startup_info;
16 * The input parameter must contain an absolute path, and it must already be
19 * Find the part of an absolute path that lies inside the work tree by
20 * dereferencing symlinks outside the work tree, for example:
21 * /dir1/repo/dir2/file (work tree is /dir1/repo) -> dir2/file
22 * /dir/file (work tree is /) -> dir/file
23 * /dir/symlink1/symlink2 (symlink1 points to work tree) -> symlink2
24 * /dir/repolink/file (repolink points to /dir/repo) -> file
25 * /dir/repo (exactly equal to work tree) -> (empty string)
27 static int abspath_part_inside_repo(char *path)
33 const char *work_tree = get_git_work_tree();
37 wtlen = strlen(work_tree);
39 off = offset_1st_component(path);
41 /* check if work tree is already the prefix */
42 if (wtlen <= len && !fspathncmp(path, work_tree, wtlen)) {
43 if (path[wtlen] == '/') {
44 memmove(path, path + wtlen + 1, len - wtlen);
46 } else if (path[wtlen - 1] == '/' || path[wtlen] == '\0') {
47 /* work tree is the root, or the whole path */
48 memmove(path, path + wtlen, len - wtlen + 1);
51 /* work tree might match beginning of a symlink to work tree */
57 /* check each '/'-terminated level */
62 if (fspathcmp(real_path(path0), work_tree) == 0) {
63 memmove(path0, path + 1, len - (path - path0));
70 /* check whole path */
71 if (fspathcmp(real_path(path0), work_tree) == 0) {
80 * Normalize "path", prepending the "prefix" for relative paths. If
81 * remaining_prefix is not NULL, return the actual prefix still
82 * remains in the path. For example, prefix = sub1/sub2/ and path is
84 * foo -> sub1/sub2/foo (full prefix)
85 * ../foo -> sub1/foo (remaining prefix is sub1/)
86 * ../../bar -> bar (no remaining prefix)
87 * ../../sub1/sub2/foo -> sub1/sub2/foo (but no remaining prefix)
88 * `pwd`/../bar -> sub1/bar (no remaining prefix)
90 char *prefix_path_gently(const char *prefix, int len,
91 int *remaining_prefix, const char *path)
93 const char *orig = path;
95 if (is_absolute_path(orig)) {
96 sanitized = xmallocz(strlen(path));
98 *remaining_prefix = 0;
99 if (normalize_path_copy_len(sanitized, path, remaining_prefix)) {
103 if (abspath_part_inside_repo(sanitized)) {
108 sanitized = xstrfmt("%.*s%s", len, len ? prefix : "", path);
109 if (remaining_prefix)
110 *remaining_prefix = len;
111 if (normalize_path_copy_len(sanitized, sanitized, remaining_prefix)) {
119 char *prefix_path(const char *prefix, int len, const char *path)
121 char *r = prefix_path_gently(prefix, len, NULL, path);
123 die(_("'%s' is outside repository"), path);
127 int path_inside_repo(const char *prefix, const char *path)
129 int len = prefix ? strlen(prefix) : 0;
130 char *r = prefix_path_gently(prefix, len, NULL, path);
138 int check_filename(const char *prefix, const char *arg)
140 char *to_free = NULL;
143 if (skip_prefix(arg, ":/", &arg)) {
144 if (!*arg) /* ":/" is root dir, always exists */
147 } else if (skip_prefix(arg, ":!", &arg) ||
148 skip_prefix(arg, ":^", &arg)) {
149 if (!*arg) /* excluding everything is silly, but allowed */
154 arg = to_free = prefix_filename(prefix, arg);
156 if (!lstat(arg, &st)) {
158 return 1; /* file exists */
160 if (is_missing_file_error(errno)) {
162 return 0; /* file does not exist */
164 die_errno(_("failed to stat '%s'"), arg);
167 static void NORETURN die_verify_filename(const char *prefix,
169 int diagnose_misspelt_rev)
171 if (!diagnose_misspelt_rev)
172 die(_("%s: no such path in the working tree.\n"
173 "Use 'git <command> -- <path>...' to specify paths that do not exist locally."),
176 * Saying "'(icase)foo' does not exist in the index" when the
177 * user gave us ":(icase)foo" is just stupid. A magic pathspec
178 * begins with a colon and is followed by a non-alnum; do not
179 * let maybe_die_on_misspelt_object_name() even trigger.
181 if (!(arg[0] == ':' && !isalnum(arg[1])))
182 maybe_die_on_misspelt_object_name(arg, prefix);
184 /* ... or fall back the most general message. */
185 die(_("ambiguous argument '%s': unknown revision or path not in the working tree.\n"
186 "Use '--' to separate paths from revisions, like this:\n"
187 "'git <command> [<revision>...] -- [<file>...]'"), arg);
192 * Check for arguments that don't resolve as actual files,
193 * but which look sufficiently like pathspecs that we'll consider
194 * them such for the purposes of rev/pathspec DWIM parsing.
196 static int looks_like_pathspec(const char *arg)
198 /* anything with a wildcard character */
199 if (!no_wildcard(arg))
202 /* long-form pathspec magic */
203 if (starts_with(arg, ":("))
210 * Verify a filename that we got as an argument for a pathspec
211 * entry. Note that a filename that begins with "-" never verifies
212 * as true, because even if such a filename were to exist, we want
213 * it to be preceded by the "--" marker (or we want the user to
214 * use a format like "./-filename")
216 * The "diagnose_misspelt_rev" is used to provide a user-friendly
217 * diagnosis when dying upon finding that "name" is not a pathname.
218 * If set to 1, the diagnosis will try to diagnose "name" as an
219 * invalid object name (e.g. HEAD:foo). If set to 0, the diagnosis
220 * will only complain about an inexisting file.
222 * This function is typically called to check that a "file or rev"
223 * argument is unambiguous. In this case, the caller will want
224 * diagnose_misspelt_rev == 1 when verifying the first non-rev
225 * argument (which could have been a revision), and
226 * diagnose_misspelt_rev == 0 for the next ones (because we already
227 * saw a filename, there's not ambiguity anymore).
229 void verify_filename(const char *prefix,
231 int diagnose_misspelt_rev)
234 die(_("option '%s' must come before non-option arguments"), arg);
235 if (looks_like_pathspec(arg) || check_filename(prefix, arg))
237 die_verify_filename(prefix, arg, diagnose_misspelt_rev);
241 * Opposite of the above: the command line did not have -- marker
242 * and we parsed the arg as a refname. It should not be interpretable
245 void verify_non_filename(const char *prefix, const char *arg)
247 if (!is_inside_work_tree() || is_inside_git_dir())
251 if (!check_filename(prefix, arg))
253 die(_("ambiguous argument '%s': both revision and filename\n"
254 "Use '--' to separate paths from revisions, like this:\n"
255 "'git <command> [<revision>...] -- [<file>...]'"), arg);
258 int get_common_dir(struct strbuf *sb, const char *gitdir)
260 const char *git_env_common_dir = getenv(GIT_COMMON_DIR_ENVIRONMENT);
261 if (git_env_common_dir) {
262 strbuf_addstr(sb, git_env_common_dir);
265 return get_common_dir_noenv(sb, gitdir);
269 int get_common_dir_noenv(struct strbuf *sb, const char *gitdir)
271 struct strbuf data = STRBUF_INIT;
272 struct strbuf path = STRBUF_INIT;
275 strbuf_addf(&path, "%s/commondir", gitdir);
276 if (file_exists(path.buf)) {
277 if (strbuf_read_file(&data, path.buf, 0) <= 0)
278 die_errno(_("failed to read %s"), path.buf);
279 while (data.len && (data.buf[data.len - 1] == '\n' ||
280 data.buf[data.len - 1] == '\r'))
282 data.buf[data.len] = '\0';
284 if (!is_absolute_path(data.buf))
285 strbuf_addf(&path, "%s/", gitdir);
286 strbuf_addbuf(&path, &data);
287 strbuf_add_real_path(sb, path.buf);
290 strbuf_addstr(sb, gitdir);
293 strbuf_release(&data);
294 strbuf_release(&path);
299 * Test if it looks like we're at a git directory.
302 * - either an objects/ directory _or_ the proper
303 * GIT_OBJECT_DIRECTORY environment variable
304 * - a refs/ directory
305 * - either a HEAD symlink or a HEAD file that is formatted as
306 * a proper "ref:", or a regular file HEAD that has a properly
307 * formatted sha1 object name.
309 int is_git_directory(const char *suspect)
311 struct strbuf path = STRBUF_INIT;
315 /* Check worktree-related signatures */
316 strbuf_addstr(&path, suspect);
317 strbuf_complete(&path, '/');
318 strbuf_addstr(&path, "HEAD");
319 if (validate_headref(path.buf))
323 get_common_dir(&path, suspect);
326 /* Check non-worktree-related signatures */
327 if (getenv(DB_ENVIRONMENT)) {
328 if (access(getenv(DB_ENVIRONMENT), X_OK))
332 strbuf_setlen(&path, len);
333 strbuf_addstr(&path, "/objects");
334 if (access(path.buf, X_OK))
338 strbuf_setlen(&path, len);
339 strbuf_addstr(&path, "/refs");
340 if (access(path.buf, X_OK))
345 strbuf_release(&path);
349 int is_nonbare_repository_dir(struct strbuf *path)
353 size_t orig_path_len = path->len;
354 assert(orig_path_len != 0);
355 strbuf_complete(path, '/');
356 strbuf_addstr(path, ".git");
357 if (read_gitfile_gently(path->buf, &gitfile_error) || is_git_directory(path->buf))
359 if (gitfile_error == READ_GITFILE_ERR_OPEN_FAILED ||
360 gitfile_error == READ_GITFILE_ERR_READ_FAILED)
362 strbuf_setlen(path, orig_path_len);
366 int is_inside_git_dir(void)
368 if (inside_git_dir < 0)
369 inside_git_dir = is_inside_dir(get_git_dir());
370 return inside_git_dir;
373 int is_inside_work_tree(void)
375 if (inside_work_tree < 0)
376 inside_work_tree = is_inside_dir(get_git_work_tree());
377 return inside_work_tree;
380 void setup_work_tree(void)
382 const char *work_tree;
383 static int initialized = 0;
388 if (work_tree_config_is_bogus)
389 die(_("unable to set up work tree using invalid config"));
391 work_tree = get_git_work_tree();
392 if (!work_tree || chdir_notify(work_tree))
393 die(_("this operation must be run in a work tree"));
396 * Make sure subsequent git processes find correct worktree
397 * if $GIT_WORK_TREE is set relative
399 if (getenv(GIT_WORK_TREE_ENVIRONMENT))
400 setenv(GIT_WORK_TREE_ENVIRONMENT, ".", 1);
405 static int read_worktree_config(const char *var, const char *value, void *vdata)
407 struct repository_format *data = vdata;
409 if (strcmp(var, "core.bare") == 0) {
410 data->is_bare = git_config_bool(var, value);
411 } else if (strcmp(var, "core.worktree") == 0) {
413 return config_error_nonbool(var);
414 data->work_tree = xstrdup(value);
419 static int check_repo_format(const char *var, const char *value, void *vdata)
421 struct repository_format *data = vdata;
424 if (strcmp(var, "core.repositoryformatversion") == 0)
425 data->version = git_config_int(var, value);
426 else if (skip_prefix(var, "extensions.", &ext)) {
428 * record any known extensions here; otherwise,
429 * we fall through to recording it as unknown, and
430 * check_repository_format will complain
432 if (!strcmp(ext, "noop"))
434 else if (!strcmp(ext, "preciousobjects"))
435 data->precious_objects = git_config_bool(var, value);
436 else if (!strcmp(ext, "partialclone")) {
438 return config_error_nonbool(var);
439 data->partial_clone = xstrdup(value);
440 } else if (!strcmp(ext, "worktreeconfig"))
441 data->worktree_config = git_config_bool(var, value);
443 string_list_append(&data->unknown_extensions, ext);
446 return read_worktree_config(var, value, vdata);
449 static int check_repository_format_gently(const char *gitdir, struct repository_format *candidate, int *nongit_ok)
451 struct strbuf sb = STRBUF_INIT;
452 struct strbuf err = STRBUF_INIT;
455 has_common = get_common_dir(&sb, gitdir);
456 strbuf_addstr(&sb, "/config");
457 read_repository_format(candidate, sb.buf);
461 * For historical use of check_repository_format() in git-init,
462 * we treat a missing config as a silent "ok", even when nongit_ok
465 if (candidate->version < 0)
468 if (verify_repository_format(candidate, &err) < 0) {
470 warning("%s", err.buf);
471 strbuf_release(&err);
478 repository_format_precious_objects = candidate->precious_objects;
479 repository_format_partial_clone = candidate->partial_clone;
480 repository_format_worktree_config = candidate->worktree_config;
481 string_list_clear(&candidate->unknown_extensions, 0);
483 if (repository_format_worktree_config) {
485 * pick up core.bare and core.worktree from per-worktree
488 strbuf_addf(&sb, "%s/config.worktree", gitdir);
489 git_config_from_file(read_worktree_config, sb.buf, candidate);
495 if (candidate->is_bare != -1) {
496 is_bare_repository_cfg = candidate->is_bare;
497 if (is_bare_repository_cfg == 1)
498 inside_work_tree = -1;
500 if (candidate->work_tree) {
501 free(git_work_tree_cfg);
502 git_work_tree_cfg = candidate->work_tree;
503 inside_work_tree = -1;
506 free(candidate->work_tree);
512 int read_repository_format(struct repository_format *format, const char *path)
514 memset(format, 0, sizeof(*format));
515 format->version = -1;
516 format->is_bare = -1;
517 format->hash_algo = GIT_HASH_SHA1;
518 string_list_init(&format->unknown_extensions, 1);
519 git_config_from_file(check_repo_format, path, format);
520 return format->version;
523 int verify_repository_format(const struct repository_format *format,
526 if (GIT_REPO_VERSION_READ < format->version) {
527 strbuf_addf(err, _("Expected git repo version <= %d, found %d"),
528 GIT_REPO_VERSION_READ, format->version);
532 if (format->version >= 1 && format->unknown_extensions.nr) {
535 strbuf_addstr(err, _("unknown repository extensions found:"));
537 for (i = 0; i < format->unknown_extensions.nr; i++)
538 strbuf_addf(err, "\n\t%s",
539 format->unknown_extensions.items[i].string);
546 void read_gitfile_error_die(int error_code, const char *path, const char *dir)
548 switch (error_code) {
549 case READ_GITFILE_ERR_STAT_FAILED:
550 case READ_GITFILE_ERR_NOT_A_FILE:
551 /* non-fatal; follow return path */
553 case READ_GITFILE_ERR_OPEN_FAILED:
554 die_errno(_("error opening '%s'"), path);
555 case READ_GITFILE_ERR_TOO_LARGE:
556 die(_("too large to be a .git file: '%s'"), path);
557 case READ_GITFILE_ERR_READ_FAILED:
558 die(_("error reading %s"), path);
559 case READ_GITFILE_ERR_INVALID_FORMAT:
560 die(_("invalid gitfile format: %s"), path);
561 case READ_GITFILE_ERR_NO_PATH:
562 die(_("no path in gitfile: %s"), path);
563 case READ_GITFILE_ERR_NOT_A_REPO:
564 die(_("not a git repository: %s"), dir);
566 BUG("unknown error code");
571 * Try to read the location of the git directory from the .git file,
572 * return path to git directory if found. The return value comes from
575 * On failure, if return_error_code is not NULL, return_error_code
576 * will be set to an error code and NULL will be returned. If
577 * return_error_code is NULL the function will die instead (for most
580 const char *read_gitfile_gently(const char *path, int *return_error_code)
582 const int max_file_size = 1 << 20; /* 1MB */
591 if (stat(path, &st)) {
592 /* NEEDSWORK: discern between ENOENT vs other errors */
593 error_code = READ_GITFILE_ERR_STAT_FAILED;
596 if (!S_ISREG(st.st_mode)) {
597 error_code = READ_GITFILE_ERR_NOT_A_FILE;
600 if (st.st_size > max_file_size) {
601 error_code = READ_GITFILE_ERR_TOO_LARGE;
604 fd = open(path, O_RDONLY);
606 error_code = READ_GITFILE_ERR_OPEN_FAILED;
609 buf = xmallocz(st.st_size);
610 len = read_in_full(fd, buf, st.st_size);
612 if (len != st.st_size) {
613 error_code = READ_GITFILE_ERR_READ_FAILED;
616 if (!starts_with(buf, "gitdir: ")) {
617 error_code = READ_GITFILE_ERR_INVALID_FORMAT;
620 while (buf[len - 1] == '\n' || buf[len - 1] == '\r')
623 error_code = READ_GITFILE_ERR_NO_PATH;
629 if (!is_absolute_path(dir) && (slash = strrchr(path, '/'))) {
630 size_t pathlen = slash+1 - path;
631 dir = xstrfmt("%.*s%.*s", (int)pathlen, path,
632 (int)(len - 8), buf + 8);
636 if (!is_git_directory(dir)) {
637 error_code = READ_GITFILE_ERR_NOT_A_REPO;
640 path = real_path(dir);
643 if (return_error_code)
644 *return_error_code = error_code;
646 read_gitfile_error_die(error_code, path, dir);
649 return error_code ? NULL : path;
652 static const char *setup_explicit_git_dir(const char *gitdirenv,
654 struct repository_format *repo_fmt,
657 const char *work_tree_env = getenv(GIT_WORK_TREE_ENVIRONMENT);
658 const char *worktree;
662 if (PATH_MAX - 40 < strlen(gitdirenv))
663 die(_("'$%s' too big"), GIT_DIR_ENVIRONMENT);
665 gitfile = (char*)read_gitfile(gitdirenv);
667 gitfile = xstrdup(gitfile);
671 if (!is_git_directory(gitdirenv)) {
677 die(_("not a git repository: '%s'"), gitdirenv);
680 if (check_repository_format_gently(gitdirenv, repo_fmt, nongit_ok)) {
685 /* #3, #7, #11, #15, #19, #23, #27, #31 (see t1510) */
687 set_git_work_tree(work_tree_env);
688 else if (is_bare_repository_cfg > 0) {
689 if (git_work_tree_cfg) {
691 warning("core.bare and core.worktree do not make sense");
692 work_tree_config_is_bogus = 1;
696 set_git_dir(gitdirenv);
700 else if (git_work_tree_cfg) { /* #6, #14 */
701 if (is_absolute_path(git_work_tree_cfg))
702 set_git_work_tree(git_work_tree_cfg);
705 if (chdir(gitdirenv))
706 die_errno(_("cannot chdir to '%s'"), gitdirenv);
707 if (chdir(git_work_tree_cfg))
708 die_errno(_("cannot chdir to '%s'"), git_work_tree_cfg);
709 core_worktree = xgetcwd();
711 die_errno(_("cannot come back to cwd"));
712 set_git_work_tree(core_worktree);
716 else if (!git_env_bool(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, 1)) {
718 set_git_dir(gitdirenv);
723 set_git_work_tree(".");
725 /* set_git_work_tree() must have been called by now */
726 worktree = get_git_work_tree();
728 /* both get_git_work_tree() and cwd are already normalized */
729 if (!strcmp(cwd->buf, worktree)) { /* cwd == worktree */
730 set_git_dir(gitdirenv);
735 offset = dir_inside_of(cwd->buf, worktree);
736 if (offset >= 0) { /* cwd inside worktree? */
737 set_git_dir(real_path(gitdirenv));
739 die_errno(_("cannot chdir to '%s'"), worktree);
740 strbuf_addch(cwd, '/');
742 return cwd->buf + offset;
745 /* cwd outside worktree */
746 set_git_dir(gitdirenv);
751 static const char *setup_discovered_git_dir(const char *gitdir,
752 struct strbuf *cwd, int offset,
753 struct repository_format *repo_fmt,
756 if (check_repository_format_gently(gitdir, repo_fmt, nongit_ok))
759 /* --work-tree is set without --git-dir; use discovered one */
760 if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
761 char *to_free = NULL;
764 if (offset != cwd->len && !is_absolute_path(gitdir))
765 gitdir = to_free = real_pathdup(gitdir, 1);
767 die_errno(_("cannot come back to cwd"));
768 ret = setup_explicit_git_dir(gitdir, cwd, repo_fmt, nongit_ok);
773 /* #16.2, #17.2, #20.2, #21.2, #24, #25, #28, #29 (see t1510) */
774 if (is_bare_repository_cfg > 0) {
775 set_git_dir(offset == cwd->len ? gitdir : real_path(gitdir));
777 die_errno(_("cannot come back to cwd"));
781 /* #0, #1, #5, #8, #9, #12, #13 */
782 set_git_work_tree(".");
783 if (strcmp(gitdir, DEFAULT_GIT_DIR_ENVIRONMENT))
786 inside_work_tree = 1;
787 if (offset == cwd->len)
790 /* Make "offset" point past the '/' (already the case for root dirs) */
791 if (offset != offset_1st_component(cwd->buf))
793 /* Add a '/' at the end */
794 strbuf_addch(cwd, '/');
795 return cwd->buf + offset;
798 /* #16.1, #17.1, #20.1, #21.1, #22.1 (see t1510) */
799 static const char *setup_bare_git_dir(struct strbuf *cwd, int offset,
800 struct repository_format *repo_fmt,
805 if (check_repository_format_gently(".", repo_fmt, nongit_ok))
808 setenv(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, "0", 1);
810 /* --work-tree is set without --git-dir; use discovered one */
811 if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
812 static const char *gitdir;
814 gitdir = offset == cwd->len ? "." : xmemdupz(cwd->buf, offset);
816 die_errno(_("cannot come back to cwd"));
817 return setup_explicit_git_dir(gitdir, cwd, repo_fmt, nongit_ok);
821 inside_work_tree = 0;
822 if (offset != cwd->len) {
824 die_errno(_("cannot come back to cwd"));
825 root_len = offset_1st_component(cwd->buf);
826 strbuf_setlen(cwd, offset > root_len ? offset : root_len);
827 set_git_dir(cwd->buf);
834 static dev_t get_device_or_die(const char *path, const char *prefix, int prefix_len)
837 if (stat(path, &buf)) {
838 die_errno(_("failed to stat '%*s%s%s'"),
840 prefix ? prefix : "",
841 prefix ? "/" : "", path);
847 * A "string_list_each_func_t" function that canonicalizes an entry
848 * from GIT_CEILING_DIRECTORIES using real_path_if_valid(), or
849 * discards it if unusable. The presence of an empty entry in
850 * GIT_CEILING_DIRECTORIES turns off canonicalization for all
851 * subsequent entries.
853 static int canonicalize_ceiling_entry(struct string_list_item *item,
856 int *empty_entry_found = cb_data;
857 char *ceil = item->string;
860 *empty_entry_found = 1;
862 } else if (!is_absolute_path(ceil)) {
864 } else if (*empty_entry_found) {
865 /* Keep entry but do not canonicalize it */
868 char *real_path = real_pathdup(ceil, 0);
873 item->string = real_path;
878 enum discovery_result {
883 /* these are errors */
884 GIT_DIR_HIT_CEILING = -1,
885 GIT_DIR_HIT_MOUNT_POINT = -2,
886 GIT_DIR_INVALID_GITFILE = -3
890 * We cannot decide in this function whether we are in the work tree or
891 * not, since the config can only be read _after_ this function was called.
893 * Also, we avoid changing any global state (such as the current working
894 * directory) to allow early callers.
896 * The directory where the search should start needs to be passed in via the
897 * `dir` parameter; upon return, the `dir` buffer will contain the path of
898 * the directory where the search ended, and `gitdir` will contain the path of
899 * the discovered .git/ directory, if any. If `gitdir` is not absolute, it
900 * is relative to `dir` (i.e. *not* necessarily the cwd).
902 static enum discovery_result setup_git_directory_gently_1(struct strbuf *dir,
903 struct strbuf *gitdir,
906 const char *env_ceiling_dirs = getenv(CEILING_DIRECTORIES_ENVIRONMENT);
907 struct string_list ceiling_dirs = STRING_LIST_INIT_DUP;
908 const char *gitdirenv;
909 int ceil_offset = -1, min_offset = has_dos_drive_prefix(dir->buf) ? 3 : 1;
910 dev_t current_device = 0;
911 int one_filesystem = 1;
914 * If GIT_DIR is set explicitly, we're not going
915 * to do any discovery, but we still do repository
918 gitdirenv = getenv(GIT_DIR_ENVIRONMENT);
920 strbuf_addstr(gitdir, gitdirenv);
921 return GIT_DIR_EXPLICIT;
924 if (env_ceiling_dirs) {
925 int empty_entry_found = 0;
927 string_list_split(&ceiling_dirs, env_ceiling_dirs, PATH_SEP, -1);
928 filter_string_list(&ceiling_dirs, 0,
929 canonicalize_ceiling_entry, &empty_entry_found);
930 ceil_offset = longest_ancestor_length(dir->buf, &ceiling_dirs);
931 string_list_clear(&ceiling_dirs, 0);
935 ceil_offset = min_offset - 2;
938 * Test in the following order (relative to the dir):
939 * - .git (file containing "gitdir: <path>")
948 one_filesystem = !git_env_bool("GIT_DISCOVERY_ACROSS_FILESYSTEM", 0);
950 current_device = get_device_or_die(dir->buf, NULL, 0);
952 int offset = dir->len, error_code = 0;
954 if (offset > min_offset)
955 strbuf_addch(dir, '/');
956 strbuf_addstr(dir, DEFAULT_GIT_DIR_ENVIRONMENT);
957 gitdirenv = read_gitfile_gently(dir->buf, die_on_error ?
961 error_code == READ_GITFILE_ERR_NOT_A_FILE) {
962 /* NEEDSWORK: fail if .git is not file nor dir */
963 if (is_git_directory(dir->buf))
964 gitdirenv = DEFAULT_GIT_DIR_ENVIRONMENT;
965 } else if (error_code != READ_GITFILE_ERR_STAT_FAILED)
966 return GIT_DIR_INVALID_GITFILE;
968 strbuf_setlen(dir, offset);
970 strbuf_addstr(gitdir, gitdirenv);
971 return GIT_DIR_DISCOVERED;
974 if (is_git_directory(dir->buf)) {
975 strbuf_addstr(gitdir, ".");
979 if (offset <= min_offset)
980 return GIT_DIR_HIT_CEILING;
982 while (--offset > ceil_offset && !is_dir_sep(dir->buf[offset]))
984 if (offset <= ceil_offset)
985 return GIT_DIR_HIT_CEILING;
987 strbuf_setlen(dir, offset > min_offset ? offset : min_offset);
988 if (one_filesystem &&
989 current_device != get_device_or_die(dir->buf, NULL, offset))
990 return GIT_DIR_HIT_MOUNT_POINT;
994 int discover_git_directory(struct strbuf *commondir,
995 struct strbuf *gitdir)
997 struct strbuf dir = STRBUF_INIT, err = STRBUF_INIT;
998 size_t gitdir_offset = gitdir->len, cwd_len;
999 size_t commondir_offset = commondir->len;
1000 struct repository_format candidate;
1002 if (strbuf_getcwd(&dir))
1006 if (setup_git_directory_gently_1(&dir, gitdir, 0) <= 0) {
1007 strbuf_release(&dir);
1012 * The returned gitdir is relative to dir, and if dir does not reflect
1013 * the current working directory, we simply make the gitdir absolute.
1015 if (dir.len < cwd_len && !is_absolute_path(gitdir->buf + gitdir_offset)) {
1016 /* Avoid a trailing "/." */
1017 if (!strcmp(".", gitdir->buf + gitdir_offset))
1018 strbuf_setlen(gitdir, gitdir_offset);
1020 strbuf_addch(&dir, '/');
1021 strbuf_insert(gitdir, gitdir_offset, dir.buf, dir.len);
1024 get_common_dir(commondir, gitdir->buf + gitdir_offset);
1027 strbuf_addf(&dir, "%s/config", commondir->buf + commondir_offset);
1028 read_repository_format(&candidate, dir.buf);
1029 strbuf_release(&dir);
1031 if (verify_repository_format(&candidate, &err) < 0) {
1032 warning("ignoring git dir '%s': %s",
1033 gitdir->buf + gitdir_offset, err.buf);
1034 strbuf_release(&err);
1035 strbuf_setlen(commondir, commondir_offset);
1036 strbuf_setlen(gitdir, gitdir_offset);
1043 const char *setup_git_directory_gently(int *nongit_ok)
1045 static struct strbuf cwd = STRBUF_INIT;
1046 struct strbuf dir = STRBUF_INIT, gitdir = STRBUF_INIT;
1047 const char *prefix = NULL;
1048 struct repository_format repo_fmt;
1051 * We may have read an incomplete configuration before
1052 * setting-up the git directory. If so, clear the cache so
1053 * that the next queries to the configuration reload complete
1054 * configuration (including the per-repo config file that we
1055 * ignored previously).
1060 * Let's assume that we are in a git repository.
1061 * If it turns out later that we are somewhere else, the value will be
1062 * updated accordingly.
1067 if (strbuf_getcwd(&cwd))
1068 die_errno(_("Unable to read current working directory"));
1069 strbuf_addbuf(&dir, &cwd);
1071 switch (setup_git_directory_gently_1(&dir, &gitdir, 1)) {
1072 case GIT_DIR_EXPLICIT:
1073 prefix = setup_explicit_git_dir(gitdir.buf, &cwd, &repo_fmt, nongit_ok);
1075 case GIT_DIR_DISCOVERED:
1076 if (dir.len < cwd.len && chdir(dir.buf))
1077 die(_("cannot change to '%s'"), dir.buf);
1078 prefix = setup_discovered_git_dir(gitdir.buf, &cwd, dir.len,
1079 &repo_fmt, nongit_ok);
1082 if (dir.len < cwd.len && chdir(dir.buf))
1083 die(_("cannot change to '%s'"), dir.buf);
1084 prefix = setup_bare_git_dir(&cwd, dir.len, &repo_fmt, nongit_ok);
1086 case GIT_DIR_HIT_CEILING:
1088 die(_("not a git repository (or any of the parent directories): %s"),
1089 DEFAULT_GIT_DIR_ENVIRONMENT);
1092 case GIT_DIR_HIT_MOUNT_POINT:
1094 die(_("not a git repository (or any parent up to mount point %s)\n"
1095 "Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set)."),
1101 * As a safeguard against setup_git_directory_gently_1 returning
1102 * this value, fallthrough to BUG. Otherwise it is possible to
1103 * set startup_info->have_repository to 1 when we did nothing to
1104 * find a repository.
1107 BUG("unhandled setup_git_directory_1() result");
1111 * At this point, nongit_ok is stable. If it is non-NULL and points
1112 * to a non-zero value, then this means that we haven't found a
1113 * repository and that the caller expects startup_info to reflect
1116 * Regardless of the state of nongit_ok, startup_info->prefix and
1117 * the GIT_PREFIX environment variable must always match. For details
1118 * see Documentation/config/alias.txt.
1120 if (nongit_ok && *nongit_ok) {
1121 startup_info->have_repository = 0;
1122 startup_info->prefix = NULL;
1123 setenv(GIT_PREFIX_ENVIRONMENT, "", 1);
1125 startup_info->have_repository = 1;
1126 startup_info->prefix = prefix;
1128 setenv(GIT_PREFIX_ENVIRONMENT, prefix, 1);
1130 setenv(GIT_PREFIX_ENVIRONMENT, "", 1);
1134 * Not all paths through the setup code will call 'set_git_dir()' (which
1135 * directly sets up the environment) so in order to guarantee that the
1136 * environment is in a consistent state after setup, explicitly setup
1137 * the environment if we have a repository.
1139 * NEEDSWORK: currently we allow bogus GIT_DIR values to be set in some
1140 * code paths so we also need to explicitly setup the environment if
1141 * the user has set GIT_DIR. It may be beneficial to disallow bogus
1142 * GIT_DIR values at some point in the future.
1144 if (/* GIT_DIR_EXPLICIT, GIT_DIR_DISCOVERED, GIT_DIR_BARE */
1145 startup_info->have_repository ||
1146 /* GIT_DIR_EXPLICIT */
1147 getenv(GIT_DIR_ENVIRONMENT)) {
1148 if (!the_repository->gitdir) {
1149 const char *gitdir = getenv(GIT_DIR_ENVIRONMENT);
1151 gitdir = DEFAULT_GIT_DIR_ENVIRONMENT;
1152 setup_git_env(gitdir);
1154 if (startup_info->have_repository)
1155 repo_set_hash_algo(the_repository, repo_fmt.hash_algo);
1158 strbuf_release(&dir);
1159 strbuf_release(&gitdir);
1164 int git_config_perm(const char *var, const char *value)
1172 if (!strcmp(value, "umask"))
1174 if (!strcmp(value, "group"))
1176 if (!strcmp(value, "all") ||
1177 !strcmp(value, "world") ||
1178 !strcmp(value, "everybody"))
1179 return PERM_EVERYBODY;
1181 /* Parse octal numbers */
1182 i = strtol(value, &endptr, 8);
1184 /* If not an octal number, maybe true/false? */
1186 return git_config_bool(var, value) ? PERM_GROUP : PERM_UMASK;
1189 * Treat values 0, 1 and 2 as compatibility cases, otherwise it is
1190 * a chmod value to restrict to.
1193 case PERM_UMASK: /* 0 */
1195 case OLD_PERM_GROUP: /* 1 */
1197 case OLD_PERM_EVERYBODY: /* 2 */
1198 return PERM_EVERYBODY;
1201 /* A filemode value was given: 0xxx */
1203 if ((i & 0600) != 0600)
1204 die(_("problem with core.sharedRepository filemode value "
1205 "(0%.3o).\nThe owner of files must always have "
1206 "read and write permissions."), i);
1209 * Mask filemode value. Others can not get write permission.
1210 * x flags for directories are handled separately.
1215 void check_repository_format(void)
1217 struct repository_format repo_fmt;
1218 check_repository_format_gently(get_git_dir(), &repo_fmt, NULL);
1219 startup_info->have_repository = 1;
1223 * Returns the "prefix", a path to the current working directory
1224 * relative to the work tree root, or NULL, if the current working
1225 * directory is not a strict subdirectory of the work tree root. The
1226 * prefix always ends with a '/' character.
1228 const char *setup_git_directory(void)
1230 return setup_git_directory_gently(NULL);
1233 const char *resolve_gitdir_gently(const char *suspect, int *return_error_code)
1235 if (is_git_directory(suspect))
1237 return read_gitfile_gently(suspect, return_error_code);
1240 /* if any standard file descriptor is missing open it to /dev/null */
1241 void sanitize_stdfds(void)
1243 int fd = open("/dev/null", O_RDWR, 0);
1244 while (fd != -1 && fd < 2)
1247 die_errno(_("open /dev/null or dup failed"));
1254 #ifdef NO_POSIX_GOODIES
1262 die_errno(_("fork failed"));
1267 die_errno(_("setsid failed"));