2 * Utilities for paths and pathnames
6 #include "string-list.h"
8 static int get_st_mode_bits(const char *path
, int *mode
)
11 if (lstat(path
, &st
) < 0)
17 static char bad_path
[] = "/bad-path/";
19 static struct strbuf
*get_pathname(void)
21 static struct strbuf pathname_array
[4] = {
22 STRBUF_INIT
, STRBUF_INIT
, STRBUF_INIT
, STRBUF_INIT
25 struct strbuf
*sb
= &pathname_array
[3 & ++index
];
30 static char *cleanup_path(char *path
)
33 if (!memcmp(path
, "./", 2)) {
41 static void strbuf_cleanup_path(struct strbuf
*sb
)
43 char *path
= cleanup_path(sb
->buf
);
45 strbuf_remove(sb
, 0, path
- sb
->buf
);
48 char *mksnpath(char *buf
, size_t n
, const char *fmt
, ...)
54 len
= vsnprintf(buf
, n
, fmt
, args
);
57 strlcpy(buf
, bad_path
, n
);
60 return cleanup_path(buf
);
63 static int dir_prefix(const char *buf
, const char *dir
)
65 int len
= strlen(dir
);
66 return !strncmp(buf
, dir
, len
) &&
67 (is_dir_sep(buf
[len
]) || buf
[len
] == '\0');
70 /* $buf =~ m|$dir/+$file| but without regex */
71 static int is_dir_file(const char *buf
, const char *dir
, const char *file
)
73 int len
= strlen(dir
);
74 if (strncmp(buf
, dir
, len
) || !is_dir_sep(buf
[len
]))
76 while (is_dir_sep(buf
[len
]))
78 return !strcmp(buf
+ len
, file
);
81 static void replace_dir(struct strbuf
*buf
, int len
, const char *newdir
)
83 int newlen
= strlen(newdir
);
84 int need_sep
= (buf
->buf
[len
] && !is_dir_sep(buf
->buf
[len
])) &&
85 !is_dir_sep(newdir
[newlen
- 1]);
87 len
--; /* keep one char, to be replaced with '/' */
88 strbuf_splice(buf
, 0, len
, newdir
, newlen
);
90 buf
->buf
[newlen
] = '/';
93 static void adjust_git_path(struct strbuf
*buf
, int git_dir_len
)
95 const char *base
= buf
->buf
+ git_dir_len
;
96 if (git_graft_env
&& is_dir_file(base
, "info", "grafts"))
97 strbuf_splice(buf
, 0, buf
->len
,
98 get_graft_file(), strlen(get_graft_file()));
99 else if (git_index_env
&& !strcmp(base
, "index"))
100 strbuf_splice(buf
, 0, buf
->len
,
101 get_index_file(), strlen(get_index_file()));
102 else if (git_db_env
&& dir_prefix(base
, "objects"))
103 replace_dir(buf
, git_dir_len
+ 7, get_object_directory());
106 static void do_git_path(struct strbuf
*buf
, const char *fmt
, va_list args
)
109 strbuf_addstr(buf
, get_git_dir());
110 if (buf
->len
&& !is_dir_sep(buf
->buf
[buf
->len
- 1]))
111 strbuf_addch(buf
, '/');
112 gitdir_len
= buf
->len
;
113 strbuf_vaddf(buf
, fmt
, args
);
114 adjust_git_path(buf
, gitdir_len
);
115 strbuf_cleanup_path(buf
);
118 void strbuf_git_path(struct strbuf
*sb
, const char *fmt
, ...)
122 do_git_path(sb
, fmt
, args
);
126 const char *git_path(const char *fmt
, ...)
128 struct strbuf
*pathname
= get_pathname();
131 do_git_path(pathname
, fmt
, args
);
133 return pathname
->buf
;
136 char *git_pathdup(const char *fmt
, ...)
138 struct strbuf path
= STRBUF_INIT
;
141 do_git_path(&path
, fmt
, args
);
143 return strbuf_detach(&path
, NULL
);
146 char *mkpathdup(const char *fmt
, ...)
148 struct strbuf sb
= STRBUF_INIT
;
151 strbuf_vaddf(&sb
, fmt
, args
);
153 strbuf_cleanup_path(&sb
);
154 return strbuf_detach(&sb
, NULL
);
157 const char *mkpath(const char *fmt
, ...)
160 struct strbuf
*pathname
= get_pathname();
162 strbuf_vaddf(pathname
, fmt
, args
);
164 return cleanup_path(pathname
->buf
);
167 void home_config_paths(char **global
, char **xdg
, char *file
)
169 char *xdg_home
= getenv("XDG_CONFIG_HOME");
170 char *home
= getenv("HOME");
171 char *to_free
= NULL
;
178 to_free
= mkpathdup("%s/.config", home
);
182 *global
= mkpathdup("%s/.gitconfig", home
);
189 *xdg
= mkpathdup("%s/git/%s", xdg_home
, file
);
195 const char *git_path_submodule(const char *path
, const char *fmt
, ...)
197 struct strbuf
*buf
= get_pathname();
201 strbuf_addstr(buf
, path
);
202 if (buf
->len
&& buf
->buf
[buf
->len
- 1] != '/')
203 strbuf_addch(buf
, '/');
204 strbuf_addstr(buf
, ".git");
206 git_dir
= read_gitfile(buf
->buf
);
209 strbuf_addstr(buf
, git_dir
);
211 strbuf_addch(buf
, '/');
214 strbuf_vaddf(buf
, fmt
, args
);
216 strbuf_cleanup_path(buf
);
220 int validate_headref(const char *path
)
223 char *buf
, buffer
[256];
224 unsigned char sha1
[20];
228 if (lstat(path
, &st
) < 0)
231 /* Make sure it is a "refs/.." symlink */
232 if (S_ISLNK(st
.st_mode
)) {
233 len
= readlink(path
, buffer
, sizeof(buffer
)-1);
234 if (len
>= 5 && !memcmp("refs/", buffer
, 5))
240 * Anything else, just open it and try to see if it is a symbolic ref.
242 fd
= open(path
, O_RDONLY
);
245 len
= read_in_full(fd
, buffer
, sizeof(buffer
)-1);
249 * Is it a symbolic ref?
253 if (!memcmp("ref:", buffer
, 4)) {
256 while (len
&& isspace(*buf
))
258 if (len
>= 5 && !memcmp("refs/", buf
, 5))
263 * Is this a detached HEAD?
265 if (!get_sha1_hex(buffer
, sha1
))
271 static struct passwd
*getpw_str(const char *username
, size_t len
)
274 char *username_z
= xmemdupz(username
, len
);
275 pw
= getpwnam(username_z
);
281 * Return a string with ~ and ~user expanded via getpw*. If buf != NULL,
282 * then it is a newly allocated string. Returns NULL on getpw failure or
285 char *expand_user_path(const char *path
)
287 struct strbuf user_path
= STRBUF_INIT
;
288 const char *to_copy
= path
;
292 if (path
[0] == '~') {
293 const char *first_slash
= strchrnul(path
, '/');
294 const char *username
= path
+ 1;
295 size_t username_len
= first_slash
- username
;
296 if (username_len
== 0) {
297 const char *home
= getenv("HOME");
300 strbuf_addstr(&user_path
, home
);
302 struct passwd
*pw
= getpw_str(username
, username_len
);
305 strbuf_addstr(&user_path
, pw
->pw_dir
);
307 to_copy
= first_slash
;
309 strbuf_addstr(&user_path
, to_copy
);
310 return strbuf_detach(&user_path
, NULL
);
312 strbuf_release(&user_path
);
317 * First, one directory to try is determined by the following algorithm.
319 * (0) If "strict" is given, the path is used as given and no DWIM is
321 * (1) "~/path" to mean path under the running user's home directory;
322 * (2) "~user/path" to mean path under named user's home directory;
323 * (3) "relative/path" to mean cwd relative directory; or
324 * (4) "/absolute/path" to mean absolute directory.
326 * Unless "strict" is given, we try access() for existence of "%s.git/.git",
327 * "%s/.git", "%s.git", "%s" in this order. The first one that exists is
330 * Second, we try chdir() to that. Upon failure, we return NULL.
332 * Then, we try if the current directory is a valid git repository.
333 * Upon failure, we return NULL.
335 * If all goes well, we return the directory we used to chdir() (but
336 * before ~user is expanded), avoiding getcwd() resolving symbolic
337 * links. User relative paths are also returned as they are given,
338 * except DWIM suffixing.
340 const char *enter_repo(const char *path
, int strict
)
342 static char used_path
[PATH_MAX
];
343 static char validated_path
[PATH_MAX
];
349 static const char *suffix
[] = {
350 "/.git", "", ".git/.git", ".git", NULL
,
353 int len
= strlen(path
);
355 while ((1 < len
) && (path
[len
-1] == '/'))
360 strncpy(used_path
, path
, len
); used_path
[len
] = 0 ;
361 strcpy(validated_path
, used_path
);
363 if (used_path
[0] == '~') {
364 char *newpath
= expand_user_path(used_path
);
365 if (!newpath
|| (PATH_MAX
- 10 < strlen(newpath
))) {
370 * Copy back into the static buffer. A pity
371 * since newpath was not bounded, but other
372 * branches of the if are limited by PATH_MAX
375 strcpy(used_path
, newpath
); free(newpath
);
377 else if (PATH_MAX
- 10 < len
)
379 len
= strlen(used_path
);
380 for (i
= 0; suffix
[i
]; i
++) {
382 strcpy(used_path
+ len
, suffix
[i
]);
383 if (!stat(used_path
, &st
) &&
384 (S_ISREG(st
.st_mode
) ||
385 (S_ISDIR(st
.st_mode
) && is_git_directory(used_path
)))) {
386 strcat(validated_path
, suffix
[i
]);
392 gitfile
= read_gitfile(used_path
) ;
394 strcpy(used_path
, gitfile
);
395 if (chdir(used_path
))
397 path
= validated_path
;
399 else if (chdir(path
))
402 if (access("objects", X_OK
) == 0 && access("refs", X_OK
) == 0 &&
403 validate_headref("HEAD") == 0) {
405 check_repository_format();
412 static int calc_shared_perm(int mode
)
416 if (shared_repository
< 0)
417 tweak
= -shared_repository
;
419 tweak
= shared_repository
;
421 if (!(mode
& S_IWUSR
))
424 /* Copy read bits to execute bits */
425 tweak
|= (tweak
& 0444) >> 2;
426 if (shared_repository
< 0)
427 mode
= (mode
& ~0777) | tweak
;
435 int adjust_shared_perm(const char *path
)
437 int old_mode
, new_mode
;
439 if (!shared_repository
)
441 if (get_st_mode_bits(path
, &old_mode
) < 0)
444 new_mode
= calc_shared_perm(old_mode
);
445 if (S_ISDIR(old_mode
)) {
446 /* Copy read bits to execute bits */
447 new_mode
|= (new_mode
& 0444) >> 2;
448 new_mode
|= FORCE_DIR_SET_GID
;
451 if (((old_mode
^ new_mode
) & ~S_IFMT
) &&
452 chmod(path
, (new_mode
& ~S_IFMT
)) < 0)
457 static int have_same_root(const char *path1
, const char *path2
)
459 int is_abs1
, is_abs2
;
461 is_abs1
= is_absolute_path(path1
);
462 is_abs2
= is_absolute_path(path2
);
463 return (is_abs1
&& is_abs2
&& tolower(path1
[0]) == tolower(path2
[0])) ||
464 (!is_abs1
&& !is_abs2
);
468 * Give path as relative to prefix.
470 * The strbuf may or may not be used, so do not assume it contains the
473 const char *relative_path(const char *in
, const char *prefix
,
476 int in_len
= in
? strlen(in
) : 0;
477 int prefix_len
= prefix
? strlen(prefix
) : 0;
484 else if (!prefix_len
)
487 if (have_same_root(in
, prefix
)) {
488 /* bypass dos_drive, for "c:" is identical to "C:" */
489 if (has_dos_drive_prefix(in
)) {
497 while (i
< prefix_len
&& j
< in_len
&& prefix
[i
] == in
[j
]) {
498 if (is_dir_sep(prefix
[i
])) {
499 while (is_dir_sep(prefix
[i
]))
501 while (is_dir_sep(in
[j
]))
512 /* "prefix" seems like prefix of "in" */
515 * but "/foo" is not a prefix of "/foobar"
516 * (i.e. prefix not end with '/')
518 prefix_off
< prefix_len
) {
520 /* in="/a/b", prefix="/a/b" */
522 } else if (is_dir_sep(in
[j
])) {
523 /* in="/a/b/c", prefix="/a/b" */
524 while (is_dir_sep(in
[j
]))
528 /* in="/a/bbb/c", prefix="/a/b" */
532 /* "in" is short than "prefix" */
534 /* "in" not end with '/' */
536 if (is_dir_sep(prefix
[i
])) {
537 /* in="/a/b", prefix="/a/b/c/" */
538 while (is_dir_sep(prefix
[i
]))
546 if (i
>= prefix_len
) {
554 strbuf_grow(sb
, in_len
);
556 while (i
< prefix_len
) {
557 if (is_dir_sep(prefix
[i
])) {
558 strbuf_addstr(sb
, "../");
559 while (is_dir_sep(prefix
[i
]))
565 if (!is_dir_sep(prefix
[prefix_len
- 1]))
566 strbuf_addstr(sb
, "../");
568 strbuf_addstr(sb
, in
);
574 * A simpler implementation of relative_path
576 * Get relative path by removing "prefix" from "in". This function
577 * first appears in v1.5.6-1-g044bbbc, and makes git_dir shorter
578 * to increase performance when traversing the path to work_tree.
580 const char *remove_leading_path(const char *in
, const char *prefix
)
582 static char buf
[PATH_MAX
+ 1];
585 if (!prefix
|| !prefix
[0])
588 if (is_dir_sep(prefix
[i
])) {
589 if (!is_dir_sep(in
[j
]))
591 while (is_dir_sep(prefix
[i
]))
593 while (is_dir_sep(in
[j
]))
596 } else if (in
[j
] != prefix
[i
]) {
603 /* "/foo" is a prefix of "/foo" */
605 /* "/foo" is not a prefix of "/foobar" */
606 !is_dir_sep(prefix
[i
-1]) && !is_dir_sep(in
[j
])
609 while (is_dir_sep(in
[j
]))
619 * It is okay if dst == src, but they should not overlap otherwise.
621 * Performs the following normalizations on src, storing the result in dst:
622 * - Ensures that components are separated by '/' (Windows only)
623 * - Squashes sequences of '/'.
624 * - Removes "." components.
625 * - Removes ".." components, and the components the precede them.
626 * Returns failure (non-zero) if a ".." component appears as first path
627 * component anytime during the normalization. Otherwise, returns success (0).
629 * Note that this function is purely textual. It does not follow symlinks,
630 * verify the existence of the path, or make any system calls.
632 * prefix_len != NULL is for a specific case of prefix_pathspec():
633 * assume that src == dst and src[0..prefix_len-1] is already
634 * normalized, any time "../" eats up to the prefix_len part,
635 * prefix_len is reduced. In the end prefix_len is the remaining
636 * prefix that has not been overridden by user pathspec.
638 int normalize_path_copy_len(char *dst
, const char *src
, int *prefix_len
)
642 if (has_dos_drive_prefix(src
)) {
648 if (is_dir_sep(*src
)) {
650 while (is_dir_sep(*src
))
658 * A path component that begins with . could be
660 * (1) "." and ends -- ignore and terminate.
661 * (2) "./" -- ignore them, eat slash and continue.
662 * (3) ".." and ends -- strip one and terminate.
663 * (4) "../" -- strip one, eat slash and continue.
669 } else if (is_dir_sep(src
[1])) {
672 while (is_dir_sep(*src
))
675 } else if (src
[1] == '.') {
680 } else if (is_dir_sep(src
[2])) {
683 while (is_dir_sep(*src
))
690 /* copy up to the next '/', and eat all '/' */
691 while ((c
= *src
++) != '\0' && !is_dir_sep(c
))
695 while (is_dir_sep(c
))
704 * dst0..dst is prefix portion, and dst[-1] is '/';
707 dst
--; /* go to trailing '/' */
710 /* Windows: dst[-1] cannot be backslash anymore */
711 while (dst0
< dst
&& dst
[-1] != '/')
713 if (prefix_len
&& *prefix_len
> dst
- dst0
)
714 *prefix_len
= dst
- dst0
;
720 int normalize_path_copy(char *dst
, const char *src
)
722 return normalize_path_copy_len(dst
, src
, NULL
);
726 * path = Canonical absolute path
727 * prefixes = string_list containing normalized, absolute paths without
728 * trailing slashes (except for the root directory, which is denoted by "/").
730 * Determines, for each path in prefixes, whether the "prefix"
731 * is an ancestor directory of path. Returns the length of the longest
732 * ancestor directory, excluding any trailing slashes, or -1 if no prefix
733 * is an ancestor. (Note that this means 0 is returned if prefixes is
734 * ["/"].) "/foo" is not considered an ancestor of "/foobar". Directories
735 * are not considered to be their own ancestors. path must be in a
736 * canonical form: empty components, or "." or ".." components are not
739 int longest_ancestor_length(const char *path
, struct string_list
*prefixes
)
743 if (!strcmp(path
, "/"))
746 for (i
= 0; i
< prefixes
->nr
; i
++) {
747 const char *ceil
= prefixes
->items
[i
].string
;
748 int len
= strlen(ceil
);
750 if (len
== 1 && ceil
[0] == '/')
751 len
= 0; /* root matches anything, with length 0 */
752 else if (!strncmp(path
, ceil
, len
) && path
[len
] == '/')
753 ; /* match of length len */
755 continue; /* no match */
764 /* strip arbitrary amount of directory separators at end of path */
765 static inline int chomp_trailing_dir_sep(const char *path
, int len
)
767 while (len
&& is_dir_sep(path
[len
- 1]))
773 * If path ends with suffix (complete path components), returns the
774 * part before suffix (sans trailing directory separators).
775 * Otherwise returns NULL.
777 char *strip_path_suffix(const char *path
, const char *suffix
)
779 int path_len
= strlen(path
), suffix_len
= strlen(suffix
);
785 if (is_dir_sep(path
[path_len
- 1])) {
786 if (!is_dir_sep(suffix
[suffix_len
- 1]))
788 path_len
= chomp_trailing_dir_sep(path
, path_len
);
789 suffix_len
= chomp_trailing_dir_sep(suffix
, suffix_len
);
791 else if (path
[--path_len
] != suffix
[--suffix_len
])
795 if (path_len
&& !is_dir_sep(path
[path_len
- 1]))
797 return xstrndup(path
, chomp_trailing_dir_sep(path
, path_len
));
800 int daemon_avoid_alias(const char *p
)
805 * This resurrects the belts and suspenders paranoia check by HPA
806 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
807 * does not do getcwd() based path canonicalization.
809 * sl becomes true immediately after seeing '/' and continues to
810 * be true as long as dots continue after that without intervening
813 if (!p
|| (*p
!= '/' && *p
!= '~'))
823 else if (ch
== '/') {
825 /* reject //, /./ and /../ */
830 if (0 < ndot
&& ndot
< 3)
831 /* reject /.$ and /..$ */
840 else if (ch
== '/') {