4 static int inside_git_dir
= -1;
5 static int inside_work_tree
= -1;
7 char *prefix_path(const char *prefix
, int len
, const char *path
)
9 const char *orig
= path
;
11 if (is_absolute_path(orig
)) {
12 const char *temp
= real_path(path
);
13 sanitized
= xmalloc(len
+ strlen(temp
) + 1);
14 strcpy(sanitized
, temp
);
16 sanitized
= xmalloc(len
+ strlen(path
) + 1);
18 memcpy(sanitized
, prefix
, len
);
19 strcpy(sanitized
+ len
, path
);
21 if (normalize_path_copy(sanitized
, sanitized
))
23 if (is_absolute_path(orig
)) {
24 size_t root_len
, len
, total
;
25 const char *work_tree
= get_git_work_tree();
28 len
= strlen(work_tree
);
29 root_len
= offset_1st_component(work_tree
);
30 total
= strlen(sanitized
) + 1;
31 if (strncmp(sanitized
, work_tree
, len
) ||
32 (len
> root_len
&& sanitized
[len
] != '\0' && sanitized
[len
] != '/')) {
34 die("'%s' is outside repository", orig
);
36 if (sanitized
[len
] == '/')
38 memmove(sanitized
, sanitized
+ len
, total
- len
);
43 int check_filename(const char *prefix
, const char *arg
)
48 name
= prefix
? prefix_filename(prefix
, strlen(prefix
), arg
) : arg
;
49 if (!lstat(name
, &st
))
50 return 1; /* file exists */
51 if (errno
== ENOENT
|| errno
== ENOTDIR
)
52 return 0; /* file does not exist */
53 die_errno("failed to stat '%s'", arg
);
56 static void NORETURN
die_verify_filename(const char *prefix
, const char *arg
)
59 * Saying "'(icase)foo' does not exist in the index" when the
60 * user gave us ":(icase)foo" is just stupid. A magic pathspec
61 * begins with a colon and is followed by a non-alnum; do not
62 * let maybe_die_on_misspelt_object_name() even trigger.
64 if (!(arg
[0] == ':' && !isalnum(arg
[1])))
65 maybe_die_on_misspelt_object_name(arg
, prefix
);
67 /* ... or fall back the most general message. */
68 die("ambiguous argument '%s': unknown revision or path not in the working tree.\n"
69 "Use '--' to separate paths from revisions", arg
);
74 * Verify a filename that we got as an argument for a pathspec
75 * entry. Note that a filename that begins with "-" never verifies
76 * as true, because even if such a filename were to exist, we want
77 * it to be preceded by the "--" marker (or we want the user to
78 * use a format like "./-filename")
80 void verify_filename(const char *prefix
, const char *arg
)
83 die("bad flag '%s' used after filename", arg
);
84 if (check_filename(prefix
, arg
))
86 die_verify_filename(prefix
, arg
);
90 * Opposite of the above: the command line did not have -- marker
91 * and we parsed the arg as a refname. It should not be interpretable
94 void verify_non_filename(const char *prefix
, const char *arg
)
96 if (!is_inside_work_tree() || is_inside_git_dir())
100 if (!check_filename(prefix
, arg
))
102 die("ambiguous argument '%s': both revision and filename\n"
103 "Use '--' to separate filenames from revisions", arg
);
109 * NEEDSWORK: These need to be moved to dir.h or even to a new
110 * pathspec.h when we restructure get_pathspec() users to use the
111 * "struct pathspec" interface.
113 * Possible future magic semantics include stuff like:
115 * { PATHSPEC_NOGLOB, '!', "noglob" },
116 * { PATHSPEC_ICASE, '\0', "icase" },
117 * { PATHSPEC_RECURSIVE, '*', "recursive" },
118 * { PATHSPEC_REGEXP, '\0', "regexp" },
121 #define PATHSPEC_FROMTOP (1<<0)
123 static struct pathspec_magic
{
125 char mnemonic
; /* this cannot be ':'! */
127 } pathspec_magic
[] = {
128 { PATHSPEC_FROMTOP
, '/', "top" },
132 * Take an element of a pathspec and check for magic signatures.
133 * Append the result to the prefix.
135 * For now, we only parse the syntax and throw out anything other than
138 * NEEDSWORK: This needs to be rewritten when we start migrating
139 * get_pathspec() users to use the "struct pathspec" interface. For
140 * example, a pathspec element may be marked as case-insensitive, but
141 * the prefix part must always match literally, and a single stupid
142 * string cannot express such a case.
144 static const char *prefix_pathspec(const char *prefix
, int prefixlen
, const char *elt
)
147 const char *copyfrom
= elt
;
151 ; /* nothing to do */
152 } else if (elt
[1] == '(') {
155 for (copyfrom
= elt
+ 2;
156 *copyfrom
&& *copyfrom
!= ')';
158 size_t len
= strcspn(copyfrom
, ",)");
159 if (copyfrom
[len
] == ')')
160 nextat
= copyfrom
+ len
;
162 nextat
= copyfrom
+ len
+ 1;
165 for (i
= 0; i
< ARRAY_SIZE(pathspec_magic
); i
++)
166 if (strlen(pathspec_magic
[i
].name
) == len
&&
167 !strncmp(pathspec_magic
[i
].name
, copyfrom
, len
)) {
168 magic
|= pathspec_magic
[i
].bit
;
171 if (ARRAY_SIZE(pathspec_magic
) <= i
)
172 die("Invalid pathspec magic '%.*s' in '%s'",
173 (int) len
, copyfrom
, elt
);
175 if (*copyfrom
== ')')
179 for (copyfrom
= elt
+ 1;
180 *copyfrom
&& *copyfrom
!= ':';
184 if (!is_pathspec_magic(ch
))
186 for (i
= 0; i
< ARRAY_SIZE(pathspec_magic
); i
++)
187 if (pathspec_magic
[i
].mnemonic
== ch
) {
188 magic
|= pathspec_magic
[i
].bit
;
191 if (ARRAY_SIZE(pathspec_magic
) <= i
)
192 die("Unimplemented pathspec magic '%c' in '%s'",
195 if (*copyfrom
== ':')
199 if (magic
& PATHSPEC_FROMTOP
)
200 return xstrdup(copyfrom
);
202 return prefix_path(prefix
, prefixlen
, copyfrom
);
205 const char **get_pathspec(const char *prefix
, const char **pathspec
)
207 const char *entry
= *pathspec
;
208 const char **src
, **dst
;
211 if (!prefix
&& !entry
)
215 static const char *spec
[2];
221 /* Otherwise we have to re-write the entries.. */
224 prefixlen
= prefix
? strlen(prefix
) : 0;
226 *(dst
++) = prefix_pathspec(prefix
, prefixlen
, *src
);
236 * Test if it looks like we're at a git directory.
239 * - either an objects/ directory _or_ the proper
240 * GIT_OBJECT_DIRECTORY environment variable
241 * - a refs/ directory
242 * - either a HEAD symlink or a HEAD file that is formatted as
243 * a proper "ref:", or a regular file HEAD that has a properly
244 * formatted sha1 object name.
246 static int is_git_directory(const char *suspect
)
249 size_t len
= strlen(suspect
);
251 if (PATH_MAX
<= len
+ strlen("/objects"))
252 die("Too long path: %.*s", 60, suspect
);
253 strcpy(path
, suspect
);
254 if (getenv(DB_ENVIRONMENT
)) {
255 if (access(getenv(DB_ENVIRONMENT
), X_OK
))
259 strcpy(path
+ len
, "/objects");
260 if (access(path
, X_OK
))
264 strcpy(path
+ len
, "/refs");
265 if (access(path
, X_OK
))
268 strcpy(path
+ len
, "/HEAD");
269 if (validate_headref(path
))
275 int is_inside_git_dir(void)
277 if (inside_git_dir
< 0)
278 inside_git_dir
= is_inside_dir(get_git_dir());
279 return inside_git_dir
;
282 int is_inside_work_tree(void)
284 if (inside_work_tree
< 0)
285 inside_work_tree
= is_inside_dir(get_git_work_tree());
286 return inside_work_tree
;
289 void setup_work_tree(void)
291 const char *work_tree
, *git_dir
;
292 static int initialized
= 0;
296 work_tree
= get_git_work_tree();
297 git_dir
= get_git_dir();
298 if (!is_absolute_path(git_dir
))
299 git_dir
= real_path(get_git_dir());
300 if (!work_tree
|| chdir(work_tree
))
301 die("This operation must be run in a work tree");
304 * Make sure subsequent git processes find correct worktree
305 * if $GIT_WORK_TREE is set relative
307 if (getenv(GIT_WORK_TREE_ENVIRONMENT
))
308 setenv(GIT_WORK_TREE_ENVIRONMENT
, ".", 1);
310 set_git_dir(relative_path(git_dir
, work_tree
));
314 static int check_repository_format_gently(const char *gitdir
, int *nongit_ok
)
316 char repo_config
[PATH_MAX
+1];
319 * git_config() can't be used here because it calls git_pathdup()
320 * to get $GIT_CONFIG/config. That call will make setup_git_env()
321 * set git_dir to ".git".
323 * We are in gitdir setup, no git dir has been found useable yet.
324 * Use a gentler version of git_config() to check if this repo
327 snprintf(repo_config
, PATH_MAX
, "%s/config", gitdir
);
328 git_config_early(check_repository_format_version
, NULL
, repo_config
);
329 if (GIT_REPO_VERSION
< repository_format_version
) {
331 die ("Expected git repo version <= %d, found %d",
332 GIT_REPO_VERSION
, repository_format_version
);
333 warning("Expected git repo version <= %d, found %d",
334 GIT_REPO_VERSION
, repository_format_version
);
335 warning("Please upgrade Git");
343 * Try to read the location of the git directory from the .git file,
344 * return path to git directory if found.
346 const char *read_gitfile(const char *path
)
357 if (!S_ISREG(st
.st_mode
))
359 fd
= open(path
, O_RDONLY
);
361 die_errno("Error opening '%s'", path
);
362 buf
= xmalloc(st
.st_size
+ 1);
363 len
= read_in_full(fd
, buf
, st
.st_size
);
365 if (len
!= st
.st_size
)
366 die("Error reading %s", path
);
368 if (prefixcmp(buf
, "gitdir: "))
369 die("Invalid gitfile format: %s", path
);
370 while (buf
[len
- 1] == '\n' || buf
[len
- 1] == '\r')
373 die("No path in gitfile: %s", path
);
377 if (!is_absolute_path(dir
) && (slash
= strrchr(path
, '/'))) {
378 size_t pathlen
= slash
+1 - path
;
379 size_t dirlen
= pathlen
+ len
- 8;
380 dir
= xmalloc(dirlen
+ 1);
381 strncpy(dir
, path
, pathlen
);
382 strncpy(dir
+ pathlen
, buf
+ 8, len
- 8);
388 if (!is_git_directory(dir
))
389 die("Not a git repository: %s", dir
);
390 path
= real_path(dir
);
396 static const char *setup_explicit_git_dir(const char *gitdirenv
,
400 const char *work_tree_env
= getenv(GIT_WORK_TREE_ENVIRONMENT
);
401 const char *worktree
;
405 if (PATH_MAX
- 40 < strlen(gitdirenv
))
406 die("'$%s' too big", GIT_DIR_ENVIRONMENT
);
408 gitfile
= (char*)read_gitfile(gitdirenv
);
410 gitfile
= xstrdup(gitfile
);
414 if (!is_git_directory(gitdirenv
)) {
420 die("Not a git repository: '%s'", gitdirenv
);
423 if (check_repository_format_gently(gitdirenv
, nongit_ok
)) {
428 /* #3, #7, #11, #15, #19, #23, #27, #31 (see t1510) */
430 set_git_work_tree(work_tree_env
);
431 else if (is_bare_repository_cfg
> 0) {
432 if (git_work_tree_cfg
) /* #22.2, #30 */
433 die("core.bare and core.worktree do not make sense");
436 set_git_dir(gitdirenv
);
440 else if (git_work_tree_cfg
) { /* #6, #14 */
441 if (is_absolute_path(git_work_tree_cfg
))
442 set_git_work_tree(git_work_tree_cfg
);
444 char core_worktree
[PATH_MAX
];
445 if (chdir(gitdirenv
))
446 die_errno("Could not chdir to '%s'", gitdirenv
);
447 if (chdir(git_work_tree_cfg
))
448 die_errno("Could not chdir to '%s'", git_work_tree_cfg
);
449 if (!getcwd(core_worktree
, PATH_MAX
))
450 die_errno("Could not get directory '%s'", git_work_tree_cfg
);
452 die_errno("Could not come back to cwd");
453 set_git_work_tree(core_worktree
);
457 set_git_work_tree(".");
459 /* set_git_work_tree() must have been called by now */
460 worktree
= get_git_work_tree();
462 /* both get_git_work_tree() and cwd are already normalized */
463 if (!strcmp(cwd
, worktree
)) { /* cwd == worktree */
464 set_git_dir(gitdirenv
);
469 offset
= dir_inside_of(cwd
, worktree
);
470 if (offset
>= 0) { /* cwd inside worktree? */
471 set_git_dir(real_path(gitdirenv
));
473 die_errno("Could not chdir to '%s'", worktree
);
480 /* cwd outside worktree */
481 set_git_dir(gitdirenv
);
486 static const char *setup_discovered_git_dir(const char *gitdir
,
487 char *cwd
, int offset
, int len
,
490 if (check_repository_format_gently(gitdir
, nongit_ok
))
493 /* --work-tree is set without --git-dir; use discovered one */
494 if (getenv(GIT_WORK_TREE_ENVIRONMENT
) || git_work_tree_cfg
) {
495 if (offset
!= len
&& !is_absolute_path(gitdir
))
496 gitdir
= xstrdup(real_path(gitdir
));
498 die_errno("Could not come back to cwd");
499 return setup_explicit_git_dir(gitdir
, cwd
, len
, nongit_ok
);
502 /* #16.2, #17.2, #20.2, #21.2, #24, #25, #28, #29 (see t1510) */
503 if (is_bare_repository_cfg
> 0) {
504 set_git_dir(offset
== len
? gitdir
: real_path(gitdir
));
506 die_errno("Could not come back to cwd");
510 /* #0, #1, #5, #8, #9, #12, #13 */
511 set_git_work_tree(".");
512 if (strcmp(gitdir
, DEFAULT_GIT_DIR_ENVIRONMENT
))
515 inside_work_tree
= 1;
519 /* Make "offset" point to past the '/', and add a '/' at the end */
526 /* #16.1, #17.1, #20.1, #21.1, #22.1 (see t1510) */
527 static const char *setup_bare_git_dir(char *cwd
, int offset
, int len
, int *nongit_ok
)
531 if (check_repository_format_gently(".", nongit_ok
))
534 /* --work-tree is set without --git-dir; use discovered one */
535 if (getenv(GIT_WORK_TREE_ENVIRONMENT
) || git_work_tree_cfg
) {
538 gitdir
= offset
== len
? "." : xmemdupz(cwd
, offset
);
540 die_errno("Could not come back to cwd");
541 return setup_explicit_git_dir(gitdir
, cwd
, len
, nongit_ok
);
545 inside_work_tree
= 0;
548 die_errno("Cannot come back to cwd");
549 root_len
= offset_1st_component(cwd
);
550 cwd
[offset
> root_len
? offset
: root_len
] = '\0';
558 static const char *setup_nongit(const char *cwd
, int *nongit_ok
)
561 die("Not a git repository (or any of the parent directories): %s", DEFAULT_GIT_DIR_ENVIRONMENT
);
563 die_errno("Cannot come back to cwd");
568 static dev_t
get_device_or_die(const char *path
, const char *prefix
)
571 if (stat(path
, &buf
))
572 die_errno("failed to stat '%s%s%s'",
573 prefix
? prefix
: "",
574 prefix
? "/" : "", path
);
579 * We cannot decide in this function whether we are in the work tree or
580 * not, since the config can only be read _after_ this function was called.
582 static const char *setup_git_directory_gently_1(int *nongit_ok
)
584 const char *env_ceiling_dirs
= getenv(CEILING_DIRECTORIES_ENVIRONMENT
);
585 static char cwd
[PATH_MAX
+1];
586 const char *gitdirenv
, *ret
;
588 int len
, offset
, ceil_offset
;
589 dev_t current_device
= 0;
590 int one_filesystem
= 1;
593 * Let's assume that we are in a git repository.
594 * If it turns out later that we are somewhere else, the value will be
595 * updated accordingly.
600 if (!getcwd(cwd
, sizeof(cwd
)-1))
601 die_errno("Unable to read current working directory");
602 offset
= len
= strlen(cwd
);
605 * If GIT_DIR is set explicitly, we're not going
606 * to do any discovery, but we still do repository
609 gitdirenv
= getenv(GIT_DIR_ENVIRONMENT
);
611 return setup_explicit_git_dir(gitdirenv
, cwd
, len
, nongit_ok
);
613 ceil_offset
= longest_ancestor_length(cwd
, env_ceiling_dirs
);
614 if (ceil_offset
< 0 && has_dos_drive_prefix(cwd
))
618 * Test in the following order (relative to the cwd):
619 * - .git (file containing "gitdir: <path>")
628 one_filesystem
= !git_env_bool("GIT_DISCOVERY_ACROSS_FILESYSTEM", 0);
630 current_device
= get_device_or_die(".", NULL
);
632 gitfile
= (char*)read_gitfile(DEFAULT_GIT_DIR_ENVIRONMENT
);
634 gitdirenv
= gitfile
= xstrdup(gitfile
);
636 if (is_git_directory(DEFAULT_GIT_DIR_ENVIRONMENT
))
637 gitdirenv
= DEFAULT_GIT_DIR_ENVIRONMENT
;
641 ret
= setup_discovered_git_dir(gitdirenv
,
649 if (is_git_directory("."))
650 return setup_bare_git_dir(cwd
, offset
, len
, nongit_ok
);
652 while (--offset
> ceil_offset
&& cwd
[offset
] != '/');
653 if (offset
<= ceil_offset
)
654 return setup_nongit(cwd
, nongit_ok
);
655 if (one_filesystem
) {
656 dev_t parent_device
= get_device_or_die("..", cwd
);
657 if (parent_device
!= current_device
) {
660 die_errno("Cannot come back to cwd");
665 die("Not a git repository (or any parent up to mount parent %s)\n"
666 "Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).", cwd
);
671 die_errno("Cannot change to '%s/..'", cwd
);
676 const char *setup_git_directory_gently(int *nongit_ok
)
680 prefix
= setup_git_directory_gently_1(nongit_ok
);
682 setenv("GIT_PREFIX", prefix
, 1);
684 setenv("GIT_PREFIX", "", 1);
687 startup_info
->have_repository
= !nongit_ok
|| !*nongit_ok
;
688 startup_info
->prefix
= prefix
;
693 int git_config_perm(const char *var
, const char *value
)
701 if (!strcmp(value
, "umask"))
703 if (!strcmp(value
, "group"))
705 if (!strcmp(value
, "all") ||
706 !strcmp(value
, "world") ||
707 !strcmp(value
, "everybody"))
708 return PERM_EVERYBODY
;
710 /* Parse octal numbers */
711 i
= strtol(value
, &endptr
, 8);
713 /* If not an octal number, maybe true/false? */
715 return git_config_bool(var
, value
) ? PERM_GROUP
: PERM_UMASK
;
718 * Treat values 0, 1 and 2 as compatibility cases, otherwise it is
719 * a chmod value to restrict to.
722 case PERM_UMASK
: /* 0 */
724 case OLD_PERM_GROUP
: /* 1 */
726 case OLD_PERM_EVERYBODY
: /* 2 */
727 return PERM_EVERYBODY
;
730 /* A filemode value was given: 0xxx */
732 if ((i
& 0600) != 0600)
733 die("Problem with core.sharedRepository filemode value "
734 "(0%.3o).\nThe owner of files must always have "
735 "read and write permissions.", i
);
738 * Mask filemode value. Others can not get write permission.
739 * x flags for directories are handled separately.
744 int check_repository_format_version(const char *var
, const char *value
, void *cb
)
746 if (strcmp(var
, "core.repositoryformatversion") == 0)
747 repository_format_version
= git_config_int(var
, value
);
748 else if (strcmp(var
, "core.sharedrepository") == 0)
749 shared_repository
= git_config_perm(var
, value
);
750 else if (strcmp(var
, "core.bare") == 0) {
751 is_bare_repository_cfg
= git_config_bool(var
, value
);
752 if (is_bare_repository_cfg
== 1)
753 inside_work_tree
= -1;
754 } else if (strcmp(var
, "core.worktree") == 0) {
756 return config_error_nonbool(var
);
757 free(git_work_tree_cfg
);
758 git_work_tree_cfg
= xstrdup(value
);
759 inside_work_tree
= -1;
764 int check_repository_format(void)
766 return check_repository_format_gently(get_git_dir(), NULL
);
770 * Returns the "prefix", a path to the current working directory
771 * relative to the work tree root, or NULL, if the current working
772 * directory is not a strict subdirectory of the work tree root. The
773 * prefix always ends with a '/' character.
775 const char *setup_git_directory(void)
777 return setup_git_directory_gently(NULL
);
780 const char *resolve_gitdir(const char *suspect
)
782 if (is_git_directory(suspect
))
784 return read_gitfile(suspect
);