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
)
58 unsigned char sha1
[20];
62 * Saying "'(icase)foo' does not exist in the index" when the
63 * user gave us ":(icase)foo" is just stupid. A magic pathspec
64 * begins with a colon and is followed by a non-alnum; do not
65 * let get_sha1_with_mode_1(only_to_die=1) to even trigger.
67 if (!(arg
[0] == ':' && !isalnum(arg
[1])))
68 /* try a detailed diagnostic ... */
69 get_sha1_with_mode_1(arg
, sha1
, &mode
, 1, prefix
);
71 /* ... or fall back the most general message. */
72 die("ambiguous argument '%s': unknown revision or path not in the working tree.\n"
73 "Use '--' to separate paths from revisions", arg
);
78 * Verify a filename that we got as an argument for a pathspec
79 * entry. Note that a filename that begins with "-" never verifies
80 * as true, because even if such a filename were to exist, we want
81 * it to be preceded by the "--" marker (or we want the user to
82 * use a format like "./-filename")
84 void verify_filename(const char *prefix
, const char *arg
)
87 die("bad flag '%s' used after filename", arg
);
88 if (check_filename(prefix
, arg
))
90 die_verify_filename(prefix
, arg
);
94 * Opposite of the above: the command line did not have -- marker
95 * and we parsed the arg as a refname. It should not be interpretable
98 void verify_non_filename(const char *prefix
, const char *arg
)
100 if (!is_inside_work_tree() || is_inside_git_dir())
104 if (!check_filename(prefix
, arg
))
106 die("ambiguous argument '%s': both revision and filename\n"
107 "Use '--' to separate filenames from revisions", arg
);
113 * NEEDSWORK: These need to be moved to dir.h or even to a new
114 * pathspec.h when we restructure get_pathspec() users to use the
115 * "struct pathspec" interface.
117 * Possible future magic semantics include stuff like:
119 * { PATHSPEC_NOGLOB, '!', "noglob" },
120 * { PATHSPEC_ICASE, '\0', "icase" },
121 * { PATHSPEC_RECURSIVE, '*', "recursive" },
122 * { PATHSPEC_REGEXP, '\0', "regexp" },
125 #define PATHSPEC_FROMTOP (1<<0)
127 static struct pathspec_magic
{
129 char mnemonic
; /* this cannot be ':'! */
131 } pathspec_magic
[] = {
132 { PATHSPEC_FROMTOP
, '/', "top" },
136 * Take an element of a pathspec and check for magic signatures.
137 * Append the result to the prefix.
139 * For now, we only parse the syntax and throw out anything other than
142 * NEEDSWORK: This needs to be rewritten when we start migrating
143 * get_pathspec() users to use the "struct pathspec" interface. For
144 * example, a pathspec element may be marked as case-insensitive, but
145 * the prefix part must always match literally, and a single stupid
146 * string cannot express such a case.
148 static const char *prefix_pathspec(const char *prefix
, int prefixlen
, const char *elt
)
151 const char *copyfrom
= elt
;
155 ; /* nothing to do */
156 } else if (elt
[1] == '(') {
159 for (copyfrom
= elt
+ 2;
160 *copyfrom
&& *copyfrom
!= ')';
162 size_t len
= strcspn(copyfrom
, ",)");
163 if (copyfrom
[len
] == ')')
164 nextat
= copyfrom
+ len
;
166 nextat
= copyfrom
+ len
+ 1;
169 for (i
= 0; i
< ARRAY_SIZE(pathspec_magic
); i
++)
170 if (strlen(pathspec_magic
[i
].name
) == len
&&
171 !strncmp(pathspec_magic
[i
].name
, copyfrom
, len
)) {
172 magic
|= pathspec_magic
[i
].bit
;
175 if (ARRAY_SIZE(pathspec_magic
) <= i
)
176 die("Invalid pathspec magic '%.*s' in '%s'",
177 (int) len
, copyfrom
, elt
);
179 if (*copyfrom
== ')')
183 for (copyfrom
= elt
+ 1;
184 *copyfrom
&& *copyfrom
!= ':';
188 if (!is_pathspec_magic(ch
))
190 for (i
= 0; i
< ARRAY_SIZE(pathspec_magic
); i
++)
191 if (pathspec_magic
[i
].mnemonic
== ch
) {
192 magic
|= pathspec_magic
[i
].bit
;
195 if (ARRAY_SIZE(pathspec_magic
) <= i
)
196 die("Unimplemented pathspec magic '%c' in '%s'",
199 if (*copyfrom
== ':')
203 if (magic
& PATHSPEC_FROMTOP
)
204 return xstrdup(copyfrom
);
206 return prefix_path(prefix
, prefixlen
, copyfrom
);
209 const char **get_pathspec(const char *prefix
, const char **pathspec
)
211 const char *entry
= *pathspec
;
212 const char **src
, **dst
;
215 if (!prefix
&& !entry
)
219 static const char *spec
[2];
225 /* Otherwise we have to re-write the entries.. */
228 prefixlen
= prefix
? strlen(prefix
) : 0;
230 *(dst
++) = prefix_pathspec(prefix
, prefixlen
, *src
);
240 * Test if it looks like we're at a git directory.
243 * - either an objects/ directory _or_ the proper
244 * GIT_OBJECT_DIRECTORY environment variable
245 * - a refs/ directory
246 * - either a HEAD symlink or a HEAD file that is formatted as
247 * a proper "ref:", or a regular file HEAD that has a properly
248 * formatted sha1 object name.
250 int is_git_directory(const char *suspect
)
253 size_t len
= strlen(suspect
);
255 if (PATH_MAX
<= len
+ strlen("/objects"))
256 die("Too long path: %.*s", 60, suspect
);
257 strcpy(path
, suspect
);
258 if (getenv(DB_ENVIRONMENT
)) {
259 if (access(getenv(DB_ENVIRONMENT
), X_OK
))
263 strcpy(path
+ len
, "/objects");
264 if (access(path
, X_OK
))
268 strcpy(path
+ len
, "/refs");
269 if (access(path
, X_OK
))
272 strcpy(path
+ len
, "/HEAD");
273 if (validate_headref(path
))
279 int is_inside_git_dir(void)
281 if (inside_git_dir
< 0)
282 inside_git_dir
= is_inside_dir(get_git_dir());
283 return inside_git_dir
;
286 int is_inside_work_tree(void)
288 if (inside_work_tree
< 0)
289 inside_work_tree
= is_inside_dir(get_git_work_tree());
290 return inside_work_tree
;
293 void setup_work_tree(void)
295 const char *work_tree
, *git_dir
;
296 static int initialized
= 0;
300 work_tree
= get_git_work_tree();
301 git_dir
= get_git_dir();
302 if (!is_absolute_path(git_dir
))
303 git_dir
= real_path(get_git_dir());
304 if (!work_tree
|| chdir(work_tree
))
305 die("This operation must be run in a work tree");
308 * Make sure subsequent git processes find correct worktree
309 * if $GIT_WORK_TREE is set relative
311 if (getenv(GIT_WORK_TREE_ENVIRONMENT
))
312 setenv(GIT_WORK_TREE_ENVIRONMENT
, ".", 1);
314 set_git_dir(relative_path(git_dir
, work_tree
));
318 static int check_repository_format_gently(const char *gitdir
, int *nongit_ok
)
320 char repo_config
[PATH_MAX
+1];
323 * git_config() can't be used here because it calls git_pathdup()
324 * to get $GIT_CONFIG/config. That call will make setup_git_env()
325 * set git_dir to ".git".
327 * We are in gitdir setup, no git dir has been found useable yet.
328 * Use a gentler version of git_config() to check if this repo
331 snprintf(repo_config
, PATH_MAX
, "%s/config", gitdir
);
332 git_config_early(check_repository_format_version
, NULL
, repo_config
);
333 if (GIT_REPO_VERSION
< repository_format_version
) {
335 die ("Expected git repo version <= %d, found %d",
336 GIT_REPO_VERSION
, repository_format_version
);
337 warning("Expected git repo version <= %d, found %d",
338 GIT_REPO_VERSION
, repository_format_version
);
339 warning("Please upgrade Git");
347 * Try to read the location of the git directory from the .git file,
348 * return path to git directory if found.
350 const char *read_gitfile(const char *path
)
361 if (!S_ISREG(st
.st_mode
))
363 fd
= open(path
, O_RDONLY
);
365 die_errno("Error opening '%s'", path
);
366 buf
= xmalloc(st
.st_size
+ 1);
367 len
= read_in_full(fd
, buf
, st
.st_size
);
369 if (len
!= st
.st_size
)
370 die("Error reading %s", path
);
372 if (prefixcmp(buf
, "gitdir: "))
373 die("Invalid gitfile format: %s", path
);
374 while (buf
[len
- 1] == '\n' || buf
[len
- 1] == '\r')
377 die("No path in gitfile: %s", path
);
381 if (!is_absolute_path(dir
) && (slash
= strrchr(path
, '/'))) {
382 size_t pathlen
= slash
+1 - path
;
383 size_t dirlen
= pathlen
+ len
- 8;
384 dir
= xmalloc(dirlen
+ 1);
385 strncpy(dir
, path
, pathlen
);
386 strncpy(dir
+ pathlen
, buf
+ 8, len
- 8);
392 if (!is_git_directory(dir
))
393 die("Not a git repository: %s", dir
);
394 path
= real_path(dir
);
400 static const char *setup_explicit_git_dir(const char *gitdirenv
,
404 const char *work_tree_env
= getenv(GIT_WORK_TREE_ENVIRONMENT
);
405 const char *worktree
;
409 if (PATH_MAX
- 40 < strlen(gitdirenv
))
410 die("'$%s' too big", GIT_DIR_ENVIRONMENT
);
412 gitfile
= (char*)read_gitfile(gitdirenv
);
414 gitfile
= xstrdup(gitfile
);
418 if (!is_git_directory(gitdirenv
)) {
424 die("Not a git repository: '%s'", gitdirenv
);
427 if (check_repository_format_gently(gitdirenv
, nongit_ok
)) {
432 /* #3, #7, #11, #15, #19, #23, #27, #31 (see t1510) */
434 set_git_work_tree(work_tree_env
);
435 else if (is_bare_repository_cfg
> 0) {
436 if (git_work_tree_cfg
) /* #22.2, #30 */
437 die("core.bare and core.worktree do not make sense");
440 set_git_dir(gitdirenv
);
444 else if (git_work_tree_cfg
) { /* #6, #14 */
445 if (is_absolute_path(git_work_tree_cfg
))
446 set_git_work_tree(git_work_tree_cfg
);
448 char core_worktree
[PATH_MAX
];
449 if (chdir(gitdirenv
))
450 die_errno("Could not chdir to '%s'", gitdirenv
);
451 if (chdir(git_work_tree_cfg
))
452 die_errno("Could not chdir to '%s'", git_work_tree_cfg
);
453 if (!getcwd(core_worktree
, PATH_MAX
))
454 die_errno("Could not get directory '%s'", git_work_tree_cfg
);
456 die_errno("Could not come back to cwd");
457 set_git_work_tree(core_worktree
);
461 set_git_work_tree(".");
463 /* set_git_work_tree() must have been called by now */
464 worktree
= get_git_work_tree();
466 /* both get_git_work_tree() and cwd are already normalized */
467 if (!strcmp(cwd
, worktree
)) { /* cwd == worktree */
468 set_git_dir(gitdirenv
);
473 offset
= dir_inside_of(cwd
, worktree
);
474 if (offset
>= 0) { /* cwd inside worktree? */
475 set_git_dir(real_path(gitdirenv
));
477 die_errno("Could not chdir to '%s'", worktree
);
484 /* cwd outside worktree */
485 set_git_dir(gitdirenv
);
490 static const char *setup_discovered_git_dir(const char *gitdir
,
491 char *cwd
, int offset
, int len
,
494 if (check_repository_format_gently(gitdir
, nongit_ok
))
497 /* --work-tree is set without --git-dir; use discovered one */
498 if (getenv(GIT_WORK_TREE_ENVIRONMENT
) || git_work_tree_cfg
) {
499 if (offset
!= len
&& !is_absolute_path(gitdir
))
500 gitdir
= xstrdup(real_path(gitdir
));
502 die_errno("Could not come back to cwd");
503 return setup_explicit_git_dir(gitdir
, cwd
, len
, nongit_ok
);
506 /* #16.2, #17.2, #20.2, #21.2, #24, #25, #28, #29 (see t1510) */
507 if (is_bare_repository_cfg
> 0) {
508 set_git_dir(offset
== len
? gitdir
: real_path(gitdir
));
510 die_errno("Could not come back to cwd");
514 /* #0, #1, #5, #8, #9, #12, #13 */
515 set_git_work_tree(".");
516 if (strcmp(gitdir
, DEFAULT_GIT_DIR_ENVIRONMENT
))
519 inside_work_tree
= 1;
523 /* Make "offset" point to past the '/', and add a '/' at the end */
530 /* #16.1, #17.1, #20.1, #21.1, #22.1 (see t1510) */
531 static const char *setup_bare_git_dir(char *cwd
, int offset
, int len
, int *nongit_ok
)
535 if (check_repository_format_gently(".", nongit_ok
))
538 /* --work-tree is set without --git-dir; use discovered one */
539 if (getenv(GIT_WORK_TREE_ENVIRONMENT
) || git_work_tree_cfg
) {
542 gitdir
= offset
== len
? "." : xmemdupz(cwd
, offset
);
544 die_errno("Could not come back to cwd");
545 return setup_explicit_git_dir(gitdir
, cwd
, len
, nongit_ok
);
549 inside_work_tree
= 0;
552 die_errno("Cannot come back to cwd");
553 root_len
= offset_1st_component(cwd
);
554 cwd
[offset
> root_len
? offset
: root_len
] = '\0';
562 static const char *setup_nongit(const char *cwd
, int *nongit_ok
)
565 die("Not a git repository (or any of the parent directories): %s", DEFAULT_GIT_DIR_ENVIRONMENT
);
567 die_errno("Cannot come back to cwd");
572 static dev_t
get_device_or_die(const char *path
, const char *prefix
)
575 if (stat(path
, &buf
))
576 die_errno("failed to stat '%s%s%s'",
577 prefix
? prefix
: "",
578 prefix
? "/" : "", path
);
583 * We cannot decide in this function whether we are in the work tree or
584 * not, since the config can only be read _after_ this function was called.
586 static const char *setup_git_directory_gently_1(int *nongit_ok
)
588 const char *env_ceiling_dirs
= getenv(CEILING_DIRECTORIES_ENVIRONMENT
);
589 static char cwd
[PATH_MAX
+1];
590 const char *gitdirenv
, *ret
;
592 int len
, offset
, ceil_offset
;
593 dev_t current_device
= 0;
594 int one_filesystem
= 1;
597 * Let's assume that we are in a git repository.
598 * If it turns out later that we are somewhere else, the value will be
599 * updated accordingly.
604 if (!getcwd(cwd
, sizeof(cwd
)-1))
605 die_errno("Unable to read current working directory");
606 offset
= len
= strlen(cwd
);
609 * If GIT_DIR is set explicitly, we're not going
610 * to do any discovery, but we still do repository
613 gitdirenv
= getenv(GIT_DIR_ENVIRONMENT
);
615 return setup_explicit_git_dir(gitdirenv
, cwd
, len
, nongit_ok
);
617 ceil_offset
= longest_ancestor_length(cwd
, env_ceiling_dirs
);
618 if (ceil_offset
< 0 && has_dos_drive_prefix(cwd
))
622 * Test in the following order (relative to the cwd):
623 * - .git (file containing "gitdir: <path>")
632 one_filesystem
= !git_env_bool("GIT_DISCOVERY_ACROSS_FILESYSTEM", 0);
634 current_device
= get_device_or_die(".", NULL
);
636 gitfile
= (char*)read_gitfile(DEFAULT_GIT_DIR_ENVIRONMENT
);
638 gitdirenv
= gitfile
= xstrdup(gitfile
);
640 if (is_git_directory(DEFAULT_GIT_DIR_ENVIRONMENT
))
641 gitdirenv
= DEFAULT_GIT_DIR_ENVIRONMENT
;
645 ret
= setup_discovered_git_dir(gitdirenv
,
653 if (is_git_directory("."))
654 return setup_bare_git_dir(cwd
, offset
, len
, nongit_ok
);
656 while (--offset
> ceil_offset
&& cwd
[offset
] != '/');
657 if (offset
<= ceil_offset
)
658 return setup_nongit(cwd
, nongit_ok
);
659 if (one_filesystem
) {
660 dev_t parent_device
= get_device_or_die("..", cwd
);
661 if (parent_device
!= current_device
) {
664 die_errno("Cannot come back to cwd");
669 die("Not a git repository (or any parent up to mount parent %s)\n"
670 "Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).", cwd
);
675 die_errno("Cannot change to '%s/..'", cwd
);
680 const char *setup_git_directory_gently(int *nongit_ok
)
684 prefix
= setup_git_directory_gently_1(nongit_ok
);
686 setenv("GIT_PREFIX", prefix
, 1);
688 setenv("GIT_PREFIX", "", 1);
691 startup_info
->have_repository
= !nongit_ok
|| !*nongit_ok
;
692 startup_info
->prefix
= prefix
;
697 int git_config_perm(const char *var
, const char *value
)
705 if (!strcmp(value
, "umask"))
707 if (!strcmp(value
, "group"))
709 if (!strcmp(value
, "all") ||
710 !strcmp(value
, "world") ||
711 !strcmp(value
, "everybody"))
712 return PERM_EVERYBODY
;
714 /* Parse octal numbers */
715 i
= strtol(value
, &endptr
, 8);
717 /* If not an octal number, maybe true/false? */
719 return git_config_bool(var
, value
) ? PERM_GROUP
: PERM_UMASK
;
722 * Treat values 0, 1 and 2 as compatibility cases, otherwise it is
723 * a chmod value to restrict to.
726 case PERM_UMASK
: /* 0 */
728 case OLD_PERM_GROUP
: /* 1 */
730 case OLD_PERM_EVERYBODY
: /* 2 */
731 return PERM_EVERYBODY
;
734 /* A filemode value was given: 0xxx */
736 if ((i
& 0600) != 0600)
737 die("Problem with core.sharedRepository filemode value "
738 "(0%.3o).\nThe owner of files must always have "
739 "read and write permissions.", i
);
742 * Mask filemode value. Others can not get write permission.
743 * x flags for directories are handled separately.
748 int check_repository_format_version(const char *var
, const char *value
, void *cb
)
750 if (strcmp(var
, "core.repositoryformatversion") == 0)
751 repository_format_version
= git_config_int(var
, value
);
752 else if (strcmp(var
, "core.sharedrepository") == 0)
753 shared_repository
= git_config_perm(var
, value
);
754 else if (strcmp(var
, "core.bare") == 0) {
755 is_bare_repository_cfg
= git_config_bool(var
, value
);
756 if (is_bare_repository_cfg
== 1)
757 inside_work_tree
= -1;
758 } else if (strcmp(var
, "core.worktree") == 0) {
760 return config_error_nonbool(var
);
761 free(git_work_tree_cfg
);
762 git_work_tree_cfg
= xstrdup(value
);
763 inside_work_tree
= -1;
768 int check_repository_format(void)
770 return check_repository_format_gently(get_git_dir(), NULL
);
774 * Returns the "prefix", a path to the current working directory
775 * relative to the work tree root, or NULL, if the current working
776 * directory is not a strict subdirectory of the work tree root. The
777 * prefix always ends with a '/' character.
779 const char *setup_git_directory(void)
781 return setup_git_directory_gently(NULL
);
784 const char *resolve_gitdir(const char *suspect
)
786 if (is_git_directory(suspect
))
788 return read_gitfile(suspect
);