2 * Utilities for paths and pathnames
6 #include "string-list.h"
9 static int get_st_mode_bits(const char *path
, int *mode
)
12 if (lstat(path
, &st
) < 0)
18 static char bad_path
[] = "/bad-path/";
20 static struct strbuf
*get_pathname(void)
22 static struct strbuf pathname_array
[4] = {
23 STRBUF_INIT
, STRBUF_INIT
, STRBUF_INIT
, STRBUF_INIT
26 struct strbuf
*sb
= &pathname_array
[3 & ++index
];
31 static char *cleanup_path(char *path
)
34 if (!memcmp(path
, "./", 2)) {
42 static void strbuf_cleanup_path(struct strbuf
*sb
)
44 char *path
= cleanup_path(sb
->buf
);
46 strbuf_remove(sb
, 0, path
- sb
->buf
);
49 char *mksnpath(char *buf
, size_t n
, const char *fmt
, ...)
55 len
= vsnprintf(buf
, n
, fmt
, args
);
58 strlcpy(buf
, bad_path
, n
);
61 return cleanup_path(buf
);
64 static int dir_prefix(const char *buf
, const char *dir
)
66 int len
= strlen(dir
);
67 return !strncmp(buf
, dir
, len
) &&
68 (is_dir_sep(buf
[len
]) || buf
[len
] == '\0');
71 /* $buf =~ m|$dir/+$file| but without regex */
72 static int is_dir_file(const char *buf
, const char *dir
, const char *file
)
74 int len
= strlen(dir
);
75 if (strncmp(buf
, dir
, len
) || !is_dir_sep(buf
[len
]))
77 while (is_dir_sep(buf
[len
]))
79 return !strcmp(buf
+ len
, file
);
82 static void replace_dir(struct strbuf
*buf
, int len
, const char *newdir
)
84 int newlen
= strlen(newdir
);
85 int need_sep
= (buf
->buf
[len
] && !is_dir_sep(buf
->buf
[len
])) &&
86 !is_dir_sep(newdir
[newlen
- 1]);
88 len
--; /* keep one char, to be replaced with '/' */
89 strbuf_splice(buf
, 0, len
, newdir
, newlen
);
91 buf
->buf
[newlen
] = '/';
94 static const char *common_list
[] = {
95 "/branches", "/hooks", "/info", "!/logs", "/lost-found",
96 "/objects", "/refs", "/remotes", "/worktrees", "/rr-cache", "/svn",
97 "config", "!gc.pid", "packed-refs", "shallow",
101 static void update_common_dir(struct strbuf
*buf
, int git_dir_len
, const char *common_dir
)
103 char *base
= buf
->buf
+ git_dir_len
;
106 if (is_dir_file(base
, "logs", "HEAD") ||
107 is_dir_file(base
, "info", "sparse-checkout"))
108 return; /* keep this in $GIT_DIR */
109 for (p
= common_list
; *p
; p
++) {
110 const char *path
= *p
;
120 common_dir
= get_git_common_dir();
122 if (is_dir
&& dir_prefix(base
, path
)) {
123 replace_dir(buf
, git_dir_len
, common_dir
);
126 if (!is_dir
&& !strcmp(base
, path
)) {
127 replace_dir(buf
, git_dir_len
, common_dir
);
133 void report_linked_checkout_garbage(void)
135 struct strbuf sb
= STRBUF_INIT
;
139 if (!git_common_dir_env
)
141 strbuf_addf(&sb
, "%s/", get_git_dir());
143 for (p
= common_list
; *p
; p
++) {
144 const char *path
= *p
;
147 strbuf_setlen(&sb
, len
);
148 strbuf_addstr(&sb
, path
);
149 if (file_exists(sb
.buf
))
150 report_garbage(PACKDIR_FILE_GARBAGE
, sb
.buf
);
155 static void adjust_git_path(struct strbuf
*buf
, int git_dir_len
)
157 const char *base
= buf
->buf
+ git_dir_len
;
158 if (git_graft_env
&& is_dir_file(base
, "info", "grafts"))
159 strbuf_splice(buf
, 0, buf
->len
,
160 get_graft_file(), strlen(get_graft_file()));
161 else if (git_index_env
&& !strcmp(base
, "index"))
162 strbuf_splice(buf
, 0, buf
->len
,
163 get_index_file(), strlen(get_index_file()));
164 else if (git_db_env
&& dir_prefix(base
, "objects"))
165 replace_dir(buf
, git_dir_len
+ 7, get_object_directory());
166 else if (git_common_dir_env
)
167 update_common_dir(buf
, git_dir_len
, NULL
);
170 static void do_git_path(struct strbuf
*buf
, const char *fmt
, va_list args
)
173 strbuf_addstr(buf
, get_git_dir());
174 if (buf
->len
&& !is_dir_sep(buf
->buf
[buf
->len
- 1]))
175 strbuf_addch(buf
, '/');
176 gitdir_len
= buf
->len
;
177 strbuf_vaddf(buf
, fmt
, args
);
178 adjust_git_path(buf
, gitdir_len
);
179 strbuf_cleanup_path(buf
);
182 void strbuf_git_path(struct strbuf
*sb
, const char *fmt
, ...)
186 do_git_path(sb
, fmt
, args
);
190 const char *git_path(const char *fmt
, ...)
192 struct strbuf
*pathname
= get_pathname();
195 do_git_path(pathname
, fmt
, args
);
197 return pathname
->buf
;
200 char *git_pathdup(const char *fmt
, ...)
202 struct strbuf path
= STRBUF_INIT
;
205 do_git_path(&path
, fmt
, args
);
207 return strbuf_detach(&path
, NULL
);
210 char *mkpathdup(const char *fmt
, ...)
212 struct strbuf sb
= STRBUF_INIT
;
215 strbuf_vaddf(&sb
, fmt
, args
);
217 strbuf_cleanup_path(&sb
);
218 return strbuf_detach(&sb
, NULL
);
221 const char *mkpath(const char *fmt
, ...)
224 struct strbuf
*pathname
= get_pathname();
226 strbuf_vaddf(pathname
, fmt
, args
);
228 return cleanup_path(pathname
->buf
);
231 static void do_submodule_path(struct strbuf
*buf
, const char *path
,
232 const char *fmt
, va_list args
)
235 struct strbuf git_submodule_common_dir
= STRBUF_INIT
;
236 struct strbuf git_submodule_dir
= STRBUF_INIT
;
238 strbuf_addstr(buf
, path
);
239 if (buf
->len
&& buf
->buf
[buf
->len
- 1] != '/')
240 strbuf_addch(buf
, '/');
241 strbuf_addstr(buf
, ".git");
243 git_dir
= read_gitfile(buf
->buf
);
246 strbuf_addstr(buf
, git_dir
);
248 strbuf_addch(buf
, '/');
249 strbuf_addstr(&git_submodule_dir
, buf
->buf
);
251 strbuf_vaddf(buf
, fmt
, args
);
253 if (get_common_dir_noenv(&git_submodule_common_dir
, git_submodule_dir
.buf
))
254 update_common_dir(buf
, git_submodule_dir
.len
, git_submodule_common_dir
.buf
);
256 strbuf_cleanup_path(buf
);
258 strbuf_release(&git_submodule_dir
);
259 strbuf_release(&git_submodule_common_dir
);
262 char *git_pathdup_submodule(const char *path
, const char *fmt
, ...)
265 struct strbuf buf
= STRBUF_INIT
;
267 do_submodule_path(&buf
, path
, fmt
, args
);
269 return strbuf_detach(&buf
, NULL
);
272 void strbuf_git_path_submodule(struct strbuf
*buf
, const char *path
,
273 const char *fmt
, ...)
277 do_submodule_path(buf
, path
, fmt
, args
);
281 int validate_headref(const char *path
)
284 char *buf
, buffer
[256];
285 unsigned char sha1
[20];
289 if (lstat(path
, &st
) < 0)
292 /* Make sure it is a "refs/.." symlink */
293 if (S_ISLNK(st
.st_mode
)) {
294 len
= readlink(path
, buffer
, sizeof(buffer
)-1);
295 if (len
>= 5 && !memcmp("refs/", buffer
, 5))
301 * Anything else, just open it and try to see if it is a symbolic ref.
303 fd
= open(path
, O_RDONLY
);
306 len
= read_in_full(fd
, buffer
, sizeof(buffer
)-1);
310 * Is it a symbolic ref?
314 if (!memcmp("ref:", buffer
, 4)) {
317 while (len
&& isspace(*buf
))
319 if (len
>= 5 && !memcmp("refs/", buf
, 5))
324 * Is this a detached HEAD?
326 if (!get_sha1_hex(buffer
, sha1
))
332 static struct passwd
*getpw_str(const char *username
, size_t len
)
335 char *username_z
= xmemdupz(username
, len
);
336 pw
= getpwnam(username_z
);
342 * Return a string with ~ and ~user expanded via getpw*. If buf != NULL,
343 * then it is a newly allocated string. Returns NULL on getpw failure or
346 char *expand_user_path(const char *path
)
348 struct strbuf user_path
= STRBUF_INIT
;
349 const char *to_copy
= path
;
353 if (path
[0] == '~') {
354 const char *first_slash
= strchrnul(path
, '/');
355 const char *username
= path
+ 1;
356 size_t username_len
= first_slash
- username
;
357 if (username_len
== 0) {
358 const char *home
= getenv("HOME");
361 strbuf_addstr(&user_path
, home
);
363 struct passwd
*pw
= getpw_str(username
, username_len
);
366 strbuf_addstr(&user_path
, pw
->pw_dir
);
368 to_copy
= first_slash
;
370 strbuf_addstr(&user_path
, to_copy
);
371 return strbuf_detach(&user_path
, NULL
);
373 strbuf_release(&user_path
);
378 * First, one directory to try is determined by the following algorithm.
380 * (0) If "strict" is given, the path is used as given and no DWIM is
382 * (1) "~/path" to mean path under the running user's home directory;
383 * (2) "~user/path" to mean path under named user's home directory;
384 * (3) "relative/path" to mean cwd relative directory; or
385 * (4) "/absolute/path" to mean absolute directory.
387 * Unless "strict" is given, we check "%s/.git", "%s", "%s.git/.git", "%s.git"
388 * in this order. We select the first one that is a valid git repository, and
389 * chdir() to it. If none match, or we fail to chdir, we return NULL.
391 * If all goes well, we return the directory we used to chdir() (but
392 * before ~user is expanded), avoiding getcwd() resolving symbolic
393 * links. User relative paths are also returned as they are given,
394 * except DWIM suffixing.
396 const char *enter_repo(const char *path
, int strict
)
398 static char used_path
[PATH_MAX
];
399 static char validated_path
[PATH_MAX
];
405 static const char *suffix
[] = {
406 "/.git", "", ".git/.git", ".git", NULL
,
409 int len
= strlen(path
);
411 while ((1 < len
) && (path
[len
-1] == '/'))
416 strncpy(used_path
, path
, len
); used_path
[len
] = 0 ;
417 strcpy(validated_path
, used_path
);
419 if (used_path
[0] == '~') {
420 char *newpath
= expand_user_path(used_path
);
421 if (!newpath
|| (PATH_MAX
- 10 < strlen(newpath
))) {
426 * Copy back into the static buffer. A pity
427 * since newpath was not bounded, but other
428 * branches of the if are limited by PATH_MAX
431 strcpy(used_path
, newpath
); free(newpath
);
433 else if (PATH_MAX
- 10 < len
)
435 len
= strlen(used_path
);
436 for (i
= 0; suffix
[i
]; i
++) {
438 strcpy(used_path
+ len
, suffix
[i
]);
439 if (!stat(used_path
, &st
) &&
440 (S_ISREG(st
.st_mode
) ||
441 (S_ISDIR(st
.st_mode
) && is_git_directory(used_path
)))) {
442 strcat(validated_path
, suffix
[i
]);
448 gitfile
= read_gitfile(used_path
);
450 strcpy(used_path
, gitfile
);
451 if (chdir(used_path
))
453 path
= validated_path
;
456 const char *gitfile
= read_gitfile(path
);
463 if (is_git_directory(".")) {
465 check_repository_format();
472 static int calc_shared_perm(int mode
)
476 if (shared_repository
< 0)
477 tweak
= -shared_repository
;
479 tweak
= shared_repository
;
481 if (!(mode
& S_IWUSR
))
484 /* Copy read bits to execute bits */
485 tweak
|= (tweak
& 0444) >> 2;
486 if (shared_repository
< 0)
487 mode
= (mode
& ~0777) | tweak
;
495 int adjust_shared_perm(const char *path
)
497 int old_mode
, new_mode
;
499 if (!shared_repository
)
501 if (get_st_mode_bits(path
, &old_mode
) < 0)
504 new_mode
= calc_shared_perm(old_mode
);
505 if (S_ISDIR(old_mode
)) {
506 /* Copy read bits to execute bits */
507 new_mode
|= (new_mode
& 0444) >> 2;
508 new_mode
|= FORCE_DIR_SET_GID
;
511 if (((old_mode
^ new_mode
) & ~S_IFMT
) &&
512 chmod(path
, (new_mode
& ~S_IFMT
)) < 0)
517 static int have_same_root(const char *path1
, const char *path2
)
519 int is_abs1
, is_abs2
;
521 is_abs1
= is_absolute_path(path1
);
522 is_abs2
= is_absolute_path(path2
);
523 return (is_abs1
&& is_abs2
&& tolower(path1
[0]) == tolower(path2
[0])) ||
524 (!is_abs1
&& !is_abs2
);
528 * Give path as relative to prefix.
530 * The strbuf may or may not be used, so do not assume it contains the
533 const char *relative_path(const char *in
, const char *prefix
,
536 int in_len
= in
? strlen(in
) : 0;
537 int prefix_len
= prefix
? strlen(prefix
) : 0;
544 else if (!prefix_len
)
547 if (have_same_root(in
, prefix
)) {
548 /* bypass dos_drive, for "c:" is identical to "C:" */
549 if (has_dos_drive_prefix(in
)) {
557 while (i
< prefix_len
&& j
< in_len
&& prefix
[i
] == in
[j
]) {
558 if (is_dir_sep(prefix
[i
])) {
559 while (is_dir_sep(prefix
[i
]))
561 while (is_dir_sep(in
[j
]))
572 /* "prefix" seems like prefix of "in" */
575 * but "/foo" is not a prefix of "/foobar"
576 * (i.e. prefix not end with '/')
578 prefix_off
< prefix_len
) {
580 /* in="/a/b", prefix="/a/b" */
582 } else if (is_dir_sep(in
[j
])) {
583 /* in="/a/b/c", prefix="/a/b" */
584 while (is_dir_sep(in
[j
]))
588 /* in="/a/bbb/c", prefix="/a/b" */
592 /* "in" is short than "prefix" */
594 /* "in" not end with '/' */
596 if (is_dir_sep(prefix
[i
])) {
597 /* in="/a/b", prefix="/a/b/c/" */
598 while (is_dir_sep(prefix
[i
]))
606 if (i
>= prefix_len
) {
614 strbuf_grow(sb
, in_len
);
616 while (i
< prefix_len
) {
617 if (is_dir_sep(prefix
[i
])) {
618 strbuf_addstr(sb
, "../");
619 while (is_dir_sep(prefix
[i
]))
625 if (!is_dir_sep(prefix
[prefix_len
- 1]))
626 strbuf_addstr(sb
, "../");
628 strbuf_addstr(sb
, in
);
634 * A simpler implementation of relative_path
636 * Get relative path by removing "prefix" from "in". This function
637 * first appears in v1.5.6-1-g044bbbc, and makes git_dir shorter
638 * to increase performance when traversing the path to work_tree.
640 const char *remove_leading_path(const char *in
, const char *prefix
)
642 static char buf
[PATH_MAX
+ 1];
645 if (!prefix
|| !prefix
[0])
648 if (is_dir_sep(prefix
[i
])) {
649 if (!is_dir_sep(in
[j
]))
651 while (is_dir_sep(prefix
[i
]))
653 while (is_dir_sep(in
[j
]))
656 } else if (in
[j
] != prefix
[i
]) {
663 /* "/foo" is a prefix of "/foo" */
665 /* "/foo" is not a prefix of "/foobar" */
666 !is_dir_sep(prefix
[i
-1]) && !is_dir_sep(in
[j
])
669 while (is_dir_sep(in
[j
]))
679 * It is okay if dst == src, but they should not overlap otherwise.
681 * Performs the following normalizations on src, storing the result in dst:
682 * - Ensures that components are separated by '/' (Windows only)
683 * - Squashes sequences of '/'.
684 * - Removes "." components.
685 * - Removes ".." components, and the components the precede them.
686 * Returns failure (non-zero) if a ".." component appears as first path
687 * component anytime during the normalization. Otherwise, returns success (0).
689 * Note that this function is purely textual. It does not follow symlinks,
690 * verify the existence of the path, or make any system calls.
692 * prefix_len != NULL is for a specific case of prefix_pathspec():
693 * assume that src == dst and src[0..prefix_len-1] is already
694 * normalized, any time "../" eats up to the prefix_len part,
695 * prefix_len is reduced. In the end prefix_len is the remaining
696 * prefix that has not been overridden by user pathspec.
698 * NEEDSWORK: This function doesn't perform normalization w.r.t. trailing '/'.
699 * For everything but the root folder itself, the normalized path should not
700 * end with a '/', then the callers need to be fixed up accordingly.
703 int normalize_path_copy_len(char *dst
, const char *src
, int *prefix_len
)
707 if (has_dos_drive_prefix(src
)) {
713 if (is_dir_sep(*src
)) {
715 while (is_dir_sep(*src
))
723 * A path component that begins with . could be
725 * (1) "." and ends -- ignore and terminate.
726 * (2) "./" -- ignore them, eat slash and continue.
727 * (3) ".." and ends -- strip one and terminate.
728 * (4) "../" -- strip one, eat slash and continue.
734 } else if (is_dir_sep(src
[1])) {
737 while (is_dir_sep(*src
))
740 } else if (src
[1] == '.') {
745 } else if (is_dir_sep(src
[2])) {
748 while (is_dir_sep(*src
))
755 /* copy up to the next '/', and eat all '/' */
756 while ((c
= *src
++) != '\0' && !is_dir_sep(c
))
760 while (is_dir_sep(c
))
769 * dst0..dst is prefix portion, and dst[-1] is '/';
772 dst
--; /* go to trailing '/' */
775 /* Windows: dst[-1] cannot be backslash anymore */
776 while (dst0
< dst
&& dst
[-1] != '/')
778 if (prefix_len
&& *prefix_len
> dst
- dst0
)
779 *prefix_len
= dst
- dst0
;
785 int normalize_path_copy(char *dst
, const char *src
)
787 return normalize_path_copy_len(dst
, src
, NULL
);
791 * path = Canonical absolute path
792 * prefixes = string_list containing normalized, absolute paths without
793 * trailing slashes (except for the root directory, which is denoted by "/").
795 * Determines, for each path in prefixes, whether the "prefix"
796 * is an ancestor directory of path. Returns the length of the longest
797 * ancestor directory, excluding any trailing slashes, or -1 if no prefix
798 * is an ancestor. (Note that this means 0 is returned if prefixes is
799 * ["/"].) "/foo" is not considered an ancestor of "/foobar". Directories
800 * are not considered to be their own ancestors. path must be in a
801 * canonical form: empty components, or "." or ".." components are not
804 int longest_ancestor_length(const char *path
, struct string_list
*prefixes
)
808 if (!strcmp(path
, "/"))
811 for (i
= 0; i
< prefixes
->nr
; i
++) {
812 const char *ceil
= prefixes
->items
[i
].string
;
813 int len
= strlen(ceil
);
815 if (len
== 1 && ceil
[0] == '/')
816 len
= 0; /* root matches anything, with length 0 */
817 else if (!strncmp(path
, ceil
, len
) && path
[len
] == '/')
818 ; /* match of length len */
820 continue; /* no match */
829 /* strip arbitrary amount of directory separators at end of path */
830 static inline int chomp_trailing_dir_sep(const char *path
, int len
)
832 while (len
&& is_dir_sep(path
[len
- 1]))
838 * If path ends with suffix (complete path components), returns the
839 * part before suffix (sans trailing directory separators).
840 * Otherwise returns NULL.
842 char *strip_path_suffix(const char *path
, const char *suffix
)
844 int path_len
= strlen(path
), suffix_len
= strlen(suffix
);
850 if (is_dir_sep(path
[path_len
- 1])) {
851 if (!is_dir_sep(suffix
[suffix_len
- 1]))
853 path_len
= chomp_trailing_dir_sep(path
, path_len
);
854 suffix_len
= chomp_trailing_dir_sep(suffix
, suffix_len
);
856 else if (path
[--path_len
] != suffix
[--suffix_len
])
860 if (path_len
&& !is_dir_sep(path
[path_len
- 1]))
862 return xstrndup(path
, chomp_trailing_dir_sep(path
, path_len
));
865 int daemon_avoid_alias(const char *p
)
870 * This resurrects the belts and suspenders paranoia check by HPA
871 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
872 * does not do getcwd() based path canonicalization.
874 * sl becomes true immediately after seeing '/' and continues to
875 * be true as long as dots continue after that without intervening
878 if (!p
|| (*p
!= '/' && *p
!= '~'))
888 else if (ch
== '/') {
890 /* reject //, /./ and /../ */
895 if (0 < ndot
&& ndot
< 3)
896 /* reject /.$ and /..$ */
905 else if (ch
== '/') {
912 static int only_spaces_and_periods(const char *path
, size_t len
, size_t skip
)
920 if (c
!= ' ' && c
!= '.')
926 int is_ntfs_dotgit(const char *name
)
930 for (len
= 0; ; len
++)
931 if (!name
[len
] || name
[len
] == '\\' || is_dir_sep(name
[len
])) {
932 if (only_spaces_and_periods(name
, len
, 4) &&
933 !strncasecmp(name
, ".git", 4))
935 if (only_spaces_and_periods(name
, len
, 5) &&
936 !strncasecmp(name
, "git~1", 5))
938 if (name
[len
] != '\\')
945 char *xdg_config_home(const char *filename
)
947 const char *home
, *config_home
;
950 config_home
= getenv("XDG_CONFIG_HOME");
951 if (config_home
&& *config_home
)
952 return mkpathdup("%s/git/%s", config_home
, filename
);
954 home
= getenv("HOME");
956 return mkpathdup("%s/.config/git/%s", home
, filename
);
960 GIT_PATH_FUNC(git_path_cherry_pick_head
, "CHERRY_PICK_HEAD")
961 GIT_PATH_FUNC(git_path_revert_head
, "REVERT_HEAD")
962 GIT_PATH_FUNC(git_path_squash_msg
, "SQUASH_MSG")
963 GIT_PATH_FUNC(git_path_merge_msg
, "MERGE_MSG")
964 GIT_PATH_FUNC(git_path_merge_rr
, "MERGE_RR")
965 GIT_PATH_FUNC(git_path_merge_mode
, "MERGE_MODE")
966 GIT_PATH_FUNC(git_path_merge_head
, "MERGE_HEAD")
967 GIT_PATH_FUNC(git_path_fetch_head
, "FETCH_HEAD")
968 GIT_PATH_FUNC(git_path_shallow
, "shallow")