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 at '%s'"), path
,
125 absolute_path(get_git_work_tree()));
129 int path_inside_repo(const char *prefix
, const char *path
)
131 int len
= prefix
? strlen(prefix
) : 0;
132 char *r
= prefix_path_gently(prefix
, len
, NULL
, path
);
140 int check_filename(const char *prefix
, const char *arg
)
142 char *to_free
= NULL
;
145 if (skip_prefix(arg
, ":/", &arg
)) {
146 if (!*arg
) /* ":/" is root dir, always exists */
149 } else if (skip_prefix(arg
, ":!", &arg
) ||
150 skip_prefix(arg
, ":^", &arg
)) {
151 if (!*arg
) /* excluding everything is silly, but allowed */
156 arg
= to_free
= prefix_filename(prefix
, arg
);
158 if (!lstat(arg
, &st
)) {
160 return 1; /* file exists */
162 if (is_missing_file_error(errno
)) {
164 return 0; /* file does not exist */
166 die_errno(_("failed to stat '%s'"), arg
);
169 static void NORETURN
die_verify_filename(struct repository
*r
,
172 int diagnose_misspelt_rev
)
174 if (!diagnose_misspelt_rev
)
175 die(_("%s: no such path in the working tree.\n"
176 "Use 'git <command> -- <path>...' to specify paths that do not exist locally."),
179 * Saying "'(icase)foo' does not exist in the index" when the
180 * user gave us ":(icase)foo" is just stupid. A magic pathspec
181 * begins with a colon and is followed by a non-alnum; do not
182 * let maybe_die_on_misspelt_object_name() even trigger.
184 if (!(arg
[0] == ':' && !isalnum(arg
[1])))
185 maybe_die_on_misspelt_object_name(r
, arg
, prefix
);
187 /* ... or fall back the most general message. */
188 die(_("ambiguous argument '%s': unknown revision or path not in the working tree.\n"
189 "Use '--' to separate paths from revisions, like this:\n"
190 "'git <command> [<revision>...] -- [<file>...]'"), arg
);
195 * Check for arguments that don't resolve as actual files,
196 * but which look sufficiently like pathspecs that we'll consider
197 * them such for the purposes of rev/pathspec DWIM parsing.
199 static int looks_like_pathspec(const char *arg
)
205 * Wildcard characters imply the user is looking to match pathspecs
206 * that aren't in the filesystem. Note that this doesn't include
207 * backslash even though it's a glob special; by itself it doesn't
208 * cause any increase in the match. Likewise ignore backslash-escaped
209 * wildcard characters.
211 for (p
= arg
; *p
; p
++) {
214 } else if (is_glob_special(*p
)) {
222 /* long-form pathspec magic */
223 if (starts_with(arg
, ":("))
230 * Verify a filename that we got as an argument for a pathspec
231 * entry. Note that a filename that begins with "-" never verifies
232 * as true, because even if such a filename were to exist, we want
233 * it to be preceded by the "--" marker (or we want the user to
234 * use a format like "./-filename")
236 * The "diagnose_misspelt_rev" is used to provide a user-friendly
237 * diagnosis when dying upon finding that "name" is not a pathname.
238 * If set to 1, the diagnosis will try to diagnose "name" as an
239 * invalid object name (e.g. HEAD:foo). If set to 0, the diagnosis
240 * will only complain about an inexisting file.
242 * This function is typically called to check that a "file or rev"
243 * argument is unambiguous. In this case, the caller will want
244 * diagnose_misspelt_rev == 1 when verifying the first non-rev
245 * argument (which could have been a revision), and
246 * diagnose_misspelt_rev == 0 for the next ones (because we already
247 * saw a filename, there's not ambiguity anymore).
249 void verify_filename(const char *prefix
,
251 int diagnose_misspelt_rev
)
254 die(_("option '%s' must come before non-option arguments"), arg
);
255 if (looks_like_pathspec(arg
) || check_filename(prefix
, arg
))
257 die_verify_filename(the_repository
, prefix
, arg
, diagnose_misspelt_rev
);
261 * Opposite of the above: the command line did not have -- marker
262 * and we parsed the arg as a refname. It should not be interpretable
265 void verify_non_filename(const char *prefix
, const char *arg
)
267 if (!is_inside_work_tree() || is_inside_git_dir())
271 if (!check_filename(prefix
, arg
))
273 die(_("ambiguous argument '%s': both revision and filename\n"
274 "Use '--' to separate paths from revisions, like this:\n"
275 "'git <command> [<revision>...] -- [<file>...]'"), arg
);
278 int get_common_dir(struct strbuf
*sb
, const char *gitdir
)
280 const char *git_env_common_dir
= getenv(GIT_COMMON_DIR_ENVIRONMENT
);
281 if (git_env_common_dir
) {
282 strbuf_addstr(sb
, git_env_common_dir
);
285 return get_common_dir_noenv(sb
, gitdir
);
289 int get_common_dir_noenv(struct strbuf
*sb
, const char *gitdir
)
291 struct strbuf data
= STRBUF_INIT
;
292 struct strbuf path
= STRBUF_INIT
;
295 strbuf_addf(&path
, "%s/commondir", gitdir
);
296 if (file_exists(path
.buf
)) {
297 if (strbuf_read_file(&data
, path
.buf
, 0) <= 0)
298 die_errno(_("failed to read %s"), path
.buf
);
299 while (data
.len
&& (data
.buf
[data
.len
- 1] == '\n' ||
300 data
.buf
[data
.len
- 1] == '\r'))
302 data
.buf
[data
.len
] = '\0';
304 if (!is_absolute_path(data
.buf
))
305 strbuf_addf(&path
, "%s/", gitdir
);
306 strbuf_addbuf(&path
, &data
);
307 strbuf_add_real_path(sb
, path
.buf
);
310 strbuf_addstr(sb
, gitdir
);
313 strbuf_release(&data
);
314 strbuf_release(&path
);
319 * Test if it looks like we're at a git directory.
322 * - either an objects/ directory _or_ the proper
323 * GIT_OBJECT_DIRECTORY environment variable
324 * - a refs/ directory
325 * - either a HEAD symlink or a HEAD file that is formatted as
326 * a proper "ref:", or a regular file HEAD that has a properly
327 * formatted sha1 object name.
329 int is_git_directory(const char *suspect
)
331 struct strbuf path
= STRBUF_INIT
;
335 /* Check worktree-related signatures */
336 strbuf_addstr(&path
, suspect
);
337 strbuf_complete(&path
, '/');
338 strbuf_addstr(&path
, "HEAD");
339 if (validate_headref(path
.buf
))
343 get_common_dir(&path
, suspect
);
346 /* Check non-worktree-related signatures */
347 if (getenv(DB_ENVIRONMENT
)) {
348 if (access(getenv(DB_ENVIRONMENT
), X_OK
))
352 strbuf_setlen(&path
, len
);
353 strbuf_addstr(&path
, "/objects");
354 if (access(path
.buf
, X_OK
))
358 strbuf_setlen(&path
, len
);
359 strbuf_addstr(&path
, "/refs");
360 if (access(path
.buf
, X_OK
))
365 strbuf_release(&path
);
369 int is_nonbare_repository_dir(struct strbuf
*path
)
373 size_t orig_path_len
= path
->len
;
374 assert(orig_path_len
!= 0);
375 strbuf_complete(path
, '/');
376 strbuf_addstr(path
, ".git");
377 if (read_gitfile_gently(path
->buf
, &gitfile_error
) || is_git_directory(path
->buf
))
379 if (gitfile_error
== READ_GITFILE_ERR_OPEN_FAILED
||
380 gitfile_error
== READ_GITFILE_ERR_READ_FAILED
)
382 strbuf_setlen(path
, orig_path_len
);
386 int is_inside_git_dir(void)
388 if (inside_git_dir
< 0)
389 inside_git_dir
= is_inside_dir(get_git_dir());
390 return inside_git_dir
;
393 int is_inside_work_tree(void)
395 if (inside_work_tree
< 0)
396 inside_work_tree
= is_inside_dir(get_git_work_tree());
397 return inside_work_tree
;
400 void setup_work_tree(void)
402 const char *work_tree
;
403 static int initialized
= 0;
408 if (work_tree_config_is_bogus
)
409 die(_("unable to set up work tree using invalid config"));
411 work_tree
= get_git_work_tree();
412 if (!work_tree
|| chdir_notify(work_tree
))
413 die(_("this operation must be run in a work tree"));
416 * Make sure subsequent git processes find correct worktree
417 * if $GIT_WORK_TREE is set relative
419 if (getenv(GIT_WORK_TREE_ENVIRONMENT
))
420 setenv(GIT_WORK_TREE_ENVIRONMENT
, ".", 1);
425 static int read_worktree_config(const char *var
, const char *value
, void *vdata
)
427 struct repository_format
*data
= vdata
;
429 if (strcmp(var
, "core.bare") == 0) {
430 data
->is_bare
= git_config_bool(var
, value
);
431 } else if (strcmp(var
, "core.worktree") == 0) {
433 return config_error_nonbool(var
);
434 free(data
->work_tree
);
435 data
->work_tree
= xstrdup(value
);
440 static int check_repo_format(const char *var
, const char *value
, void *vdata
)
442 struct repository_format
*data
= vdata
;
445 if (strcmp(var
, "core.repositoryformatversion") == 0)
446 data
->version
= git_config_int(var
, value
);
447 else if (skip_prefix(var
, "extensions.", &ext
)) {
449 * record any known extensions here; otherwise,
450 * we fall through to recording it as unknown, and
451 * check_repository_format will complain
453 if (!strcmp(ext
, "noop"))
455 else if (!strcmp(ext
, "preciousobjects"))
456 data
->precious_objects
= git_config_bool(var
, value
);
457 else if (!strcmp(ext
, "partialclone")) {
459 return config_error_nonbool(var
);
460 data
->partial_clone
= xstrdup(value
);
461 } else if (!strcmp(ext
, "worktreeconfig"))
462 data
->worktree_config
= git_config_bool(var
, value
);
464 string_list_append(&data
->unknown_extensions
, ext
);
467 return read_worktree_config(var
, value
, vdata
);
470 static int check_repository_format_gently(const char *gitdir
, struct repository_format
*candidate
, int *nongit_ok
)
472 struct strbuf sb
= STRBUF_INIT
;
473 struct strbuf err
= STRBUF_INIT
;
476 has_common
= get_common_dir(&sb
, gitdir
);
477 strbuf_addstr(&sb
, "/config");
478 read_repository_format(candidate
, sb
.buf
);
482 * For historical use of check_repository_format() in git-init,
483 * we treat a missing config as a silent "ok", even when nongit_ok
486 if (candidate
->version
< 0)
489 if (verify_repository_format(candidate
, &err
) < 0) {
491 warning("%s", err
.buf
);
492 strbuf_release(&err
);
499 repository_format_precious_objects
= candidate
->precious_objects
;
500 set_repository_format_partial_clone(candidate
->partial_clone
);
501 repository_format_worktree_config
= candidate
->worktree_config
;
502 string_list_clear(&candidate
->unknown_extensions
, 0);
504 if (repository_format_worktree_config
) {
506 * pick up core.bare and core.worktree from per-worktree
509 strbuf_addf(&sb
, "%s/config.worktree", gitdir
);
510 git_config_from_file(read_worktree_config
, sb
.buf
, candidate
);
516 if (candidate
->is_bare
!= -1) {
517 is_bare_repository_cfg
= candidate
->is_bare
;
518 if (is_bare_repository_cfg
== 1)
519 inside_work_tree
= -1;
521 if (candidate
->work_tree
) {
522 free(git_work_tree_cfg
);
523 git_work_tree_cfg
= xstrdup(candidate
->work_tree
);
524 inside_work_tree
= -1;
531 static void init_repository_format(struct repository_format
*format
)
533 const struct repository_format fresh
= REPOSITORY_FORMAT_INIT
;
535 memcpy(format
, &fresh
, sizeof(fresh
));
538 int read_repository_format(struct repository_format
*format
, const char *path
)
540 clear_repository_format(format
);
541 git_config_from_file(check_repo_format
, path
, format
);
542 if (format
->version
== -1)
543 clear_repository_format(format
);
544 return format
->version
;
547 void clear_repository_format(struct repository_format
*format
)
549 string_list_clear(&format
->unknown_extensions
, 0);
550 free(format
->work_tree
);
551 free(format
->partial_clone
);
552 init_repository_format(format
);
555 int verify_repository_format(const struct repository_format
*format
,
558 if (GIT_REPO_VERSION_READ
< format
->version
) {
559 strbuf_addf(err
, _("Expected git repo version <= %d, found %d"),
560 GIT_REPO_VERSION_READ
, format
->version
);
564 if (format
->version
>= 1 && format
->unknown_extensions
.nr
) {
567 strbuf_addstr(err
, _("unknown repository extensions found:"));
569 for (i
= 0; i
< format
->unknown_extensions
.nr
; i
++)
570 strbuf_addf(err
, "\n\t%s",
571 format
->unknown_extensions
.items
[i
].string
);
578 void read_gitfile_error_die(int error_code
, const char *path
, const char *dir
)
580 switch (error_code
) {
581 case READ_GITFILE_ERR_STAT_FAILED
:
582 case READ_GITFILE_ERR_NOT_A_FILE
:
583 /* non-fatal; follow return path */
585 case READ_GITFILE_ERR_OPEN_FAILED
:
586 die_errno(_("error opening '%s'"), path
);
587 case READ_GITFILE_ERR_TOO_LARGE
:
588 die(_("too large to be a .git file: '%s'"), path
);
589 case READ_GITFILE_ERR_READ_FAILED
:
590 die(_("error reading %s"), path
);
591 case READ_GITFILE_ERR_INVALID_FORMAT
:
592 die(_("invalid gitfile format: %s"), path
);
593 case READ_GITFILE_ERR_NO_PATH
:
594 die(_("no path in gitfile: %s"), path
);
595 case READ_GITFILE_ERR_NOT_A_REPO
:
596 die(_("not a git repository: %s"), dir
);
598 BUG("unknown error code");
603 * Try to read the location of the git directory from the .git file,
604 * return path to git directory if found. The return value comes from
607 * On failure, if return_error_code is not NULL, return_error_code
608 * will be set to an error code and NULL will be returned. If
609 * return_error_code is NULL the function will die instead (for most
612 const char *read_gitfile_gently(const char *path
, int *return_error_code
)
614 const int max_file_size
= 1 << 20; /* 1MB */
623 if (stat(path
, &st
)) {
624 /* NEEDSWORK: discern between ENOENT vs other errors */
625 error_code
= READ_GITFILE_ERR_STAT_FAILED
;
628 if (!S_ISREG(st
.st_mode
)) {
629 error_code
= READ_GITFILE_ERR_NOT_A_FILE
;
632 if (st
.st_size
> max_file_size
) {
633 error_code
= READ_GITFILE_ERR_TOO_LARGE
;
636 fd
= open(path
, O_RDONLY
);
638 error_code
= READ_GITFILE_ERR_OPEN_FAILED
;
641 buf
= xmallocz(st
.st_size
);
642 len
= read_in_full(fd
, buf
, st
.st_size
);
644 if (len
!= st
.st_size
) {
645 error_code
= READ_GITFILE_ERR_READ_FAILED
;
648 if (!starts_with(buf
, "gitdir: ")) {
649 error_code
= READ_GITFILE_ERR_INVALID_FORMAT
;
652 while (buf
[len
- 1] == '\n' || buf
[len
- 1] == '\r')
655 error_code
= READ_GITFILE_ERR_NO_PATH
;
661 if (!is_absolute_path(dir
) && (slash
= strrchr(path
, '/'))) {
662 size_t pathlen
= slash
+1 - path
;
663 dir
= xstrfmt("%.*s%.*s", (int)pathlen
, path
,
664 (int)(len
- 8), buf
+ 8);
668 if (!is_git_directory(dir
)) {
669 error_code
= READ_GITFILE_ERR_NOT_A_REPO
;
672 path
= real_path(dir
);
675 if (return_error_code
)
676 *return_error_code
= error_code
;
678 read_gitfile_error_die(error_code
, path
, dir
);
681 return error_code
? NULL
: path
;
684 static const char *setup_explicit_git_dir(const char *gitdirenv
,
686 struct repository_format
*repo_fmt
,
689 const char *work_tree_env
= getenv(GIT_WORK_TREE_ENVIRONMENT
);
690 const char *worktree
;
694 if (PATH_MAX
- 40 < strlen(gitdirenv
))
695 die(_("'$%s' too big"), GIT_DIR_ENVIRONMENT
);
697 gitfile
= (char*)read_gitfile(gitdirenv
);
699 gitfile
= xstrdup(gitfile
);
703 if (!is_git_directory(gitdirenv
)) {
709 die(_("not a git repository: '%s'"), gitdirenv
);
712 if (check_repository_format_gently(gitdirenv
, repo_fmt
, nongit_ok
)) {
717 /* #3, #7, #11, #15, #19, #23, #27, #31 (see t1510) */
719 set_git_work_tree(work_tree_env
);
720 else if (is_bare_repository_cfg
> 0) {
721 if (git_work_tree_cfg
) {
723 warning("core.bare and core.worktree do not make sense");
724 work_tree_config_is_bogus
= 1;
728 set_git_dir(gitdirenv
);
732 else if (git_work_tree_cfg
) { /* #6, #14 */
733 if (is_absolute_path(git_work_tree_cfg
))
734 set_git_work_tree(git_work_tree_cfg
);
737 if (chdir(gitdirenv
))
738 die_errno(_("cannot chdir to '%s'"), gitdirenv
);
739 if (chdir(git_work_tree_cfg
))
740 die_errno(_("cannot chdir to '%s'"), git_work_tree_cfg
);
741 core_worktree
= xgetcwd();
743 die_errno(_("cannot come back to cwd"));
744 set_git_work_tree(core_worktree
);
748 else if (!git_env_bool(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT
, 1)) {
750 set_git_dir(gitdirenv
);
755 set_git_work_tree(".");
757 /* set_git_work_tree() must have been called by now */
758 worktree
= get_git_work_tree();
760 /* both get_git_work_tree() and cwd are already normalized */
761 if (!strcmp(cwd
->buf
, worktree
)) { /* cwd == worktree */
762 set_git_dir(gitdirenv
);
767 offset
= dir_inside_of(cwd
->buf
, worktree
);
768 if (offset
>= 0) { /* cwd inside worktree? */
769 set_git_dir(real_path(gitdirenv
));
771 die_errno(_("cannot chdir to '%s'"), worktree
);
772 strbuf_addch(cwd
, '/');
774 return cwd
->buf
+ offset
;
777 /* cwd outside worktree */
778 set_git_dir(gitdirenv
);
783 static const char *setup_discovered_git_dir(const char *gitdir
,
784 struct strbuf
*cwd
, int offset
,
785 struct repository_format
*repo_fmt
,
788 if (check_repository_format_gently(gitdir
, repo_fmt
, nongit_ok
))
791 /* --work-tree is set without --git-dir; use discovered one */
792 if (getenv(GIT_WORK_TREE_ENVIRONMENT
) || git_work_tree_cfg
) {
793 char *to_free
= NULL
;
796 if (offset
!= cwd
->len
&& !is_absolute_path(gitdir
))
797 gitdir
= to_free
= real_pathdup(gitdir
, 1);
799 die_errno(_("cannot come back to cwd"));
800 ret
= setup_explicit_git_dir(gitdir
, cwd
, repo_fmt
, nongit_ok
);
805 /* #16.2, #17.2, #20.2, #21.2, #24, #25, #28, #29 (see t1510) */
806 if (is_bare_repository_cfg
> 0) {
807 set_git_dir(offset
== cwd
->len
? gitdir
: real_path(gitdir
));
809 die_errno(_("cannot come back to cwd"));
813 /* #0, #1, #5, #8, #9, #12, #13 */
814 set_git_work_tree(".");
815 if (strcmp(gitdir
, DEFAULT_GIT_DIR_ENVIRONMENT
))
818 inside_work_tree
= 1;
819 if (offset
>= cwd
->len
)
822 /* Make "offset" point past the '/' (already the case for root dirs) */
823 if (offset
!= offset_1st_component(cwd
->buf
))
825 /* Add a '/' at the end */
826 strbuf_addch(cwd
, '/');
827 return cwd
->buf
+ offset
;
830 /* #16.1, #17.1, #20.1, #21.1, #22.1 (see t1510) */
831 static const char *setup_bare_git_dir(struct strbuf
*cwd
, int offset
,
832 struct repository_format
*repo_fmt
,
837 if (check_repository_format_gently(".", repo_fmt
, nongit_ok
))
840 setenv(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT
, "0", 1);
842 /* --work-tree is set without --git-dir; use discovered one */
843 if (getenv(GIT_WORK_TREE_ENVIRONMENT
) || git_work_tree_cfg
) {
844 static const char *gitdir
;
846 gitdir
= offset
== cwd
->len
? "." : xmemdupz(cwd
->buf
, offset
);
848 die_errno(_("cannot come back to cwd"));
849 return setup_explicit_git_dir(gitdir
, cwd
, repo_fmt
, nongit_ok
);
853 inside_work_tree
= 0;
854 if (offset
!= cwd
->len
) {
856 die_errno(_("cannot come back to cwd"));
857 root_len
= offset_1st_component(cwd
->buf
);
858 strbuf_setlen(cwd
, offset
> root_len
? offset
: root_len
);
859 set_git_dir(cwd
->buf
);
866 static dev_t
get_device_or_die(const char *path
, const char *prefix
, int prefix_len
)
869 if (stat(path
, &buf
)) {
870 die_errno(_("failed to stat '%*s%s%s'"),
872 prefix
? prefix
: "",
873 prefix
? "/" : "", path
);
879 * A "string_list_each_func_t" function that canonicalizes an entry
880 * from GIT_CEILING_DIRECTORIES using real_path_if_valid(), or
881 * discards it if unusable. The presence of an empty entry in
882 * GIT_CEILING_DIRECTORIES turns off canonicalization for all
883 * subsequent entries.
885 static int canonicalize_ceiling_entry(struct string_list_item
*item
,
888 int *empty_entry_found
= cb_data
;
889 char *ceil
= item
->string
;
892 *empty_entry_found
= 1;
894 } else if (!is_absolute_path(ceil
)) {
896 } else if (*empty_entry_found
) {
897 /* Keep entry but do not canonicalize it */
900 char *real_path
= real_pathdup(ceil
, 0);
905 item
->string
= real_path
;
910 enum discovery_result
{
915 /* these are errors */
916 GIT_DIR_HIT_CEILING
= -1,
917 GIT_DIR_HIT_MOUNT_POINT
= -2,
918 GIT_DIR_INVALID_GITFILE
= -3
922 * We cannot decide in this function whether we are in the work tree or
923 * not, since the config can only be read _after_ this function was called.
925 * Also, we avoid changing any global state (such as the current working
926 * directory) to allow early callers.
928 * The directory where the search should start needs to be passed in via the
929 * `dir` parameter; upon return, the `dir` buffer will contain the path of
930 * the directory where the search ended, and `gitdir` will contain the path of
931 * the discovered .git/ directory, if any. If `gitdir` is not absolute, it
932 * is relative to `dir` (i.e. *not* necessarily the cwd).
934 static enum discovery_result
setup_git_directory_gently_1(struct strbuf
*dir
,
935 struct strbuf
*gitdir
,
938 const char *env_ceiling_dirs
= getenv(CEILING_DIRECTORIES_ENVIRONMENT
);
939 struct string_list ceiling_dirs
= STRING_LIST_INIT_DUP
;
940 const char *gitdirenv
;
941 int ceil_offset
= -1, min_offset
= offset_1st_component(dir
->buf
);
942 dev_t current_device
= 0;
943 int one_filesystem
= 1;
946 * If GIT_DIR is set explicitly, we're not going
947 * to do any discovery, but we still do repository
950 gitdirenv
= getenv(GIT_DIR_ENVIRONMENT
);
952 strbuf_addstr(gitdir
, gitdirenv
);
953 return GIT_DIR_EXPLICIT
;
956 if (env_ceiling_dirs
) {
957 int empty_entry_found
= 0;
959 string_list_split(&ceiling_dirs
, env_ceiling_dirs
, PATH_SEP
, -1);
960 filter_string_list(&ceiling_dirs
, 0,
961 canonicalize_ceiling_entry
, &empty_entry_found
);
962 ceil_offset
= longest_ancestor_length(dir
->buf
, &ceiling_dirs
);
963 string_list_clear(&ceiling_dirs
, 0);
967 ceil_offset
= min_offset
- 2;
969 if (min_offset
&& min_offset
== dir
->len
&&
970 !is_dir_sep(dir
->buf
[min_offset
- 1])) {
971 strbuf_addch(dir
, '/');
976 * Test in the following order (relative to the dir):
977 * - .git (file containing "gitdir: <path>")
986 one_filesystem
= !git_env_bool("GIT_DISCOVERY_ACROSS_FILESYSTEM", 0);
988 current_device
= get_device_or_die(dir
->buf
, NULL
, 0);
990 int offset
= dir
->len
, error_code
= 0;
992 if (offset
> min_offset
)
993 strbuf_addch(dir
, '/');
994 strbuf_addstr(dir
, DEFAULT_GIT_DIR_ENVIRONMENT
);
995 gitdirenv
= read_gitfile_gently(dir
->buf
, die_on_error
?
999 error_code
== READ_GITFILE_ERR_NOT_A_FILE
) {
1000 /* NEEDSWORK: fail if .git is not file nor dir */
1001 if (is_git_directory(dir
->buf
))
1002 gitdirenv
= DEFAULT_GIT_DIR_ENVIRONMENT
;
1003 } else if (error_code
!= READ_GITFILE_ERR_STAT_FAILED
)
1004 return GIT_DIR_INVALID_GITFILE
;
1006 strbuf_setlen(dir
, offset
);
1008 strbuf_addstr(gitdir
, gitdirenv
);
1009 return GIT_DIR_DISCOVERED
;
1012 if (is_git_directory(dir
->buf
)) {
1013 strbuf_addstr(gitdir
, ".");
1014 return GIT_DIR_BARE
;
1017 if (offset
<= min_offset
)
1018 return GIT_DIR_HIT_CEILING
;
1020 while (--offset
> ceil_offset
&& !is_dir_sep(dir
->buf
[offset
]))
1022 if (offset
<= ceil_offset
)
1023 return GIT_DIR_HIT_CEILING
;
1025 strbuf_setlen(dir
, offset
> min_offset
? offset
: min_offset
);
1026 if (one_filesystem
&&
1027 current_device
!= get_device_or_die(dir
->buf
, NULL
, offset
))
1028 return GIT_DIR_HIT_MOUNT_POINT
;
1032 int discover_git_directory(struct strbuf
*commondir
,
1033 struct strbuf
*gitdir
)
1035 struct strbuf dir
= STRBUF_INIT
, err
= STRBUF_INIT
;
1036 size_t gitdir_offset
= gitdir
->len
, cwd_len
;
1037 size_t commondir_offset
= commondir
->len
;
1038 struct repository_format candidate
= REPOSITORY_FORMAT_INIT
;
1040 if (strbuf_getcwd(&dir
))
1044 if (setup_git_directory_gently_1(&dir
, gitdir
, 0) <= 0) {
1045 strbuf_release(&dir
);
1050 * The returned gitdir is relative to dir, and if dir does not reflect
1051 * the current working directory, we simply make the gitdir absolute.
1053 if (dir
.len
< cwd_len
&& !is_absolute_path(gitdir
->buf
+ gitdir_offset
)) {
1054 /* Avoid a trailing "/." */
1055 if (!strcmp(".", gitdir
->buf
+ gitdir_offset
))
1056 strbuf_setlen(gitdir
, gitdir_offset
);
1058 strbuf_addch(&dir
, '/');
1059 strbuf_insert(gitdir
, gitdir_offset
, dir
.buf
, dir
.len
);
1062 get_common_dir(commondir
, gitdir
->buf
+ gitdir_offset
);
1065 strbuf_addf(&dir
, "%s/config", commondir
->buf
+ commondir_offset
);
1066 read_repository_format(&candidate
, dir
.buf
);
1067 strbuf_release(&dir
);
1069 if (verify_repository_format(&candidate
, &err
) < 0) {
1070 warning("ignoring git dir '%s': %s",
1071 gitdir
->buf
+ gitdir_offset
, err
.buf
);
1072 strbuf_release(&err
);
1073 strbuf_setlen(commondir
, commondir_offset
);
1074 strbuf_setlen(gitdir
, gitdir_offset
);
1075 clear_repository_format(&candidate
);
1079 clear_repository_format(&candidate
);
1083 const char *setup_git_directory_gently(int *nongit_ok
)
1085 static struct strbuf cwd
= STRBUF_INIT
;
1086 struct strbuf dir
= STRBUF_INIT
, gitdir
= STRBUF_INIT
;
1087 const char *prefix
= NULL
;
1088 struct repository_format repo_fmt
= REPOSITORY_FORMAT_INIT
;
1091 * We may have read an incomplete configuration before
1092 * setting-up the git directory. If so, clear the cache so
1093 * that the next queries to the configuration reload complete
1094 * configuration (including the per-repo config file that we
1095 * ignored previously).
1100 * Let's assume that we are in a git repository.
1101 * If it turns out later that we are somewhere else, the value will be
1102 * updated accordingly.
1107 if (strbuf_getcwd(&cwd
))
1108 die_errno(_("Unable to read current working directory"));
1109 strbuf_addbuf(&dir
, &cwd
);
1111 switch (setup_git_directory_gently_1(&dir
, &gitdir
, 1)) {
1112 case GIT_DIR_EXPLICIT
:
1113 prefix
= setup_explicit_git_dir(gitdir
.buf
, &cwd
, &repo_fmt
, nongit_ok
);
1115 case GIT_DIR_DISCOVERED
:
1116 if (dir
.len
< cwd
.len
&& chdir(dir
.buf
))
1117 die(_("cannot change to '%s'"), dir
.buf
);
1118 prefix
= setup_discovered_git_dir(gitdir
.buf
, &cwd
, dir
.len
,
1119 &repo_fmt
, nongit_ok
);
1122 if (dir
.len
< cwd
.len
&& chdir(dir
.buf
))
1123 die(_("cannot change to '%s'"), dir
.buf
);
1124 prefix
= setup_bare_git_dir(&cwd
, dir
.len
, &repo_fmt
, nongit_ok
);
1126 case GIT_DIR_HIT_CEILING
:
1128 die(_("not a git repository (or any of the parent directories): %s"),
1129 DEFAULT_GIT_DIR_ENVIRONMENT
);
1132 case GIT_DIR_HIT_MOUNT_POINT
:
1134 die(_("not a git repository (or any parent up to mount point %s)\n"
1135 "Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set)."),
1141 * As a safeguard against setup_git_directory_gently_1 returning
1142 * this value, fallthrough to BUG. Otherwise it is possible to
1143 * set startup_info->have_repository to 1 when we did nothing to
1144 * find a repository.
1147 BUG("unhandled setup_git_directory_1() result");
1151 * At this point, nongit_ok is stable. If it is non-NULL and points
1152 * to a non-zero value, then this means that we haven't found a
1153 * repository and that the caller expects startup_info to reflect
1156 * Regardless of the state of nongit_ok, startup_info->prefix and
1157 * the GIT_PREFIX environment variable must always match. For details
1158 * see Documentation/config/alias.txt.
1160 if (nongit_ok
&& *nongit_ok
) {
1161 startup_info
->have_repository
= 0;
1162 startup_info
->prefix
= NULL
;
1163 setenv(GIT_PREFIX_ENVIRONMENT
, "", 1);
1165 startup_info
->have_repository
= 1;
1166 startup_info
->prefix
= prefix
;
1168 setenv(GIT_PREFIX_ENVIRONMENT
, prefix
, 1);
1170 setenv(GIT_PREFIX_ENVIRONMENT
, "", 1);
1174 * Not all paths through the setup code will call 'set_git_dir()' (which
1175 * directly sets up the environment) so in order to guarantee that the
1176 * environment is in a consistent state after setup, explicitly setup
1177 * the environment if we have a repository.
1179 * NEEDSWORK: currently we allow bogus GIT_DIR values to be set in some
1180 * code paths so we also need to explicitly setup the environment if
1181 * the user has set GIT_DIR. It may be beneficial to disallow bogus
1182 * GIT_DIR values at some point in the future.
1184 if (/* GIT_DIR_EXPLICIT, GIT_DIR_DISCOVERED, GIT_DIR_BARE */
1185 startup_info
->have_repository
||
1186 /* GIT_DIR_EXPLICIT */
1187 getenv(GIT_DIR_ENVIRONMENT
)) {
1188 if (!the_repository
->gitdir
) {
1189 const char *gitdir
= getenv(GIT_DIR_ENVIRONMENT
);
1191 gitdir
= DEFAULT_GIT_DIR_ENVIRONMENT
;
1192 setup_git_env(gitdir
);
1194 if (startup_info
->have_repository
)
1195 repo_set_hash_algo(the_repository
, repo_fmt
.hash_algo
);
1198 strbuf_release(&dir
);
1199 strbuf_release(&gitdir
);
1200 clear_repository_format(&repo_fmt
);
1205 int git_config_perm(const char *var
, const char *value
)
1213 if (!strcmp(value
, "umask"))
1215 if (!strcmp(value
, "group"))
1217 if (!strcmp(value
, "all") ||
1218 !strcmp(value
, "world") ||
1219 !strcmp(value
, "everybody"))
1220 return PERM_EVERYBODY
;
1222 /* Parse octal numbers */
1223 i
= strtol(value
, &endptr
, 8);
1225 /* If not an octal number, maybe true/false? */
1227 return git_config_bool(var
, value
) ? PERM_GROUP
: PERM_UMASK
;
1230 * Treat values 0, 1 and 2 as compatibility cases, otherwise it is
1231 * a chmod value to restrict to.
1234 case PERM_UMASK
: /* 0 */
1236 case OLD_PERM_GROUP
: /* 1 */
1238 case OLD_PERM_EVERYBODY
: /* 2 */
1239 return PERM_EVERYBODY
;
1242 /* A filemode value was given: 0xxx */
1244 if ((i
& 0600) != 0600)
1245 die(_("problem with core.sharedRepository filemode value "
1246 "(0%.3o).\nThe owner of files must always have "
1247 "read and write permissions."), i
);
1250 * Mask filemode value. Others can not get write permission.
1251 * x flags for directories are handled separately.
1256 void check_repository_format(void)
1258 struct repository_format repo_fmt
= REPOSITORY_FORMAT_INIT
;
1259 check_repository_format_gently(get_git_dir(), &repo_fmt
, NULL
);
1260 startup_info
->have_repository
= 1;
1261 clear_repository_format(&repo_fmt
);
1265 * Returns the "prefix", a path to the current working directory
1266 * relative to the work tree root, or NULL, if the current working
1267 * directory is not a strict subdirectory of the work tree root. The
1268 * prefix always ends with a '/' character.
1270 const char *setup_git_directory(void)
1272 return setup_git_directory_gently(NULL
);
1275 const char *resolve_gitdir_gently(const char *suspect
, int *return_error_code
)
1277 if (is_git_directory(suspect
))
1279 return read_gitfile_gently(suspect
, return_error_code
);
1282 /* if any standard file descriptor is missing open it to /dev/null */
1283 void sanitize_stdfds(void)
1285 int fd
= open("/dev/null", O_RDWR
, 0);
1286 while (fd
!= -1 && fd
< 2)
1289 die_errno(_("open /dev/null or dup failed"));
1296 #ifdef NO_POSIX_GOODIES
1304 die_errno(_("fork failed"));
1309 die_errno(_("setsid failed"));