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 char *get_pathname(void)
21 static char pathname_array
[4][PATH_MAX
];
23 return pathname_array
[3 & ++index
];
26 static char *cleanup_path(char *path
)
29 if (!memcmp(path
, "./", 2)) {
37 char *mksnpath(char *buf
, size_t n
, const char *fmt
, ...)
43 len
= vsnprintf(buf
, n
, fmt
, args
);
46 strlcpy(buf
, bad_path
, n
);
49 return cleanup_path(buf
);
52 static char *vsnpath(char *buf
, size_t n
, const char *fmt
, va_list args
)
54 const char *git_dir
= get_git_dir();
57 len
= strlen(git_dir
);
60 memcpy(buf
, git_dir
, len
);
61 if (len
&& !is_dir_sep(git_dir
[len
-1]))
63 len
+= vsnprintf(buf
+ len
, n
- len
, fmt
, args
);
66 return cleanup_path(buf
);
68 strlcpy(buf
, bad_path
, n
);
72 char *git_snpath(char *buf
, size_t n
, const char *fmt
, ...)
77 ret
= vsnpath(buf
, n
, fmt
, args
);
82 char *git_pathdup(const char *fmt
, ...)
84 char path
[PATH_MAX
], *ret
;
87 ret
= vsnpath(path
, sizeof(path
), fmt
, args
);
92 char *mkpathdup(const char *fmt
, ...)
95 struct strbuf sb
= STRBUF_INIT
;
99 strbuf_vaddf(&sb
, fmt
, args
);
101 path
= xstrdup(cleanup_path(sb
.buf
));
107 char *mkpath(const char *fmt
, ...)
111 char *pathname
= get_pathname();
114 len
= vsnprintf(pathname
, PATH_MAX
, fmt
, args
);
118 return cleanup_path(pathname
);
121 char *git_path(const char *fmt
, ...)
123 char *pathname
= get_pathname();
128 ret
= vsnpath(pathname
, PATH_MAX
, fmt
, args
);
133 char *git_path_submodule(const char *path
, const char *fmt
, ...)
135 char *pathname
= get_pathname();
136 struct strbuf buf
= STRBUF_INIT
;
142 if (len
> PATH_MAX
-100)
145 strbuf_addstr(&buf
, path
);
146 if (len
&& path
[len
-1] != '/')
147 strbuf_addch(&buf
, '/');
148 strbuf_addstr(&buf
, ".git");
150 git_dir
= read_gitfile(buf
.buf
);
153 strbuf_addstr(&buf
, git_dir
);
155 strbuf_addch(&buf
, '/');
157 if (buf
.len
>= PATH_MAX
)
159 memcpy(pathname
, buf
.buf
, buf
.len
+ 1);
161 strbuf_release(&buf
);
162 len
= strlen(pathname
);
165 len
+= vsnprintf(pathname
+ len
, PATH_MAX
- len
, fmt
, args
);
169 return cleanup_path(pathname
);
172 int validate_headref(const char *path
)
175 char *buf
, buffer
[256];
176 unsigned char sha1
[20];
180 if (lstat(path
, &st
) < 0)
183 /* Make sure it is a "refs/.." symlink */
184 if (S_ISLNK(st
.st_mode
)) {
185 len
= readlink(path
, buffer
, sizeof(buffer
)-1);
186 if (len
>= 5 && !memcmp("refs/", buffer
, 5))
192 * Anything else, just open it and try to see if it is a symbolic ref.
194 fd
= open(path
, O_RDONLY
);
197 len
= read_in_full(fd
, buffer
, sizeof(buffer
)-1);
201 * Is it a symbolic ref?
205 if (!memcmp("ref:", buffer
, 4)) {
208 while (len
&& isspace(*buf
))
210 if (len
>= 5 && !memcmp("refs/", buf
, 5))
215 * Is this a detached HEAD?
217 if (!get_sha1_hex(buffer
, sha1
))
223 static struct passwd
*getpw_str(const char *username
, size_t len
)
226 char *username_z
= xmemdupz(username
, len
);
227 pw
= getpwnam(username_z
);
233 * Return a string with ~ and ~user expanded via getpw*. If buf != NULL,
234 * then it is a newly allocated string. Returns NULL on getpw failure or
237 char *expand_user_path(const char *path
)
239 struct strbuf user_path
= STRBUF_INIT
;
240 const char *to_copy
= path
;
244 if (path
[0] == '~') {
245 const char *first_slash
= strchrnul(path
, '/');
246 const char *username
= path
+ 1;
247 size_t username_len
= first_slash
- username
;
248 if (username_len
== 0) {
249 const char *home
= getenv("HOME");
252 strbuf_addstr(&user_path
, home
);
254 struct passwd
*pw
= getpw_str(username
, username_len
);
257 strbuf_addstr(&user_path
, pw
->pw_dir
);
259 to_copy
= first_slash
;
261 strbuf_addstr(&user_path
, to_copy
);
262 return strbuf_detach(&user_path
, NULL
);
264 strbuf_release(&user_path
);
269 * First, one directory to try is determined by the following algorithm.
271 * (0) If "strict" is given, the path is used as given and no DWIM is
273 * (1) "~/path" to mean path under the running user's home directory;
274 * (2) "~user/path" to mean path under named user's home directory;
275 * (3) "relative/path" to mean cwd relative directory; or
276 * (4) "/absolute/path" to mean absolute directory.
278 * Unless "strict" is given, we check "%s/.git", "%s", "%s.git/.git", "%s.git"
279 * in this order. We select the first one that is a valid git repository, and
280 * chdir() to it. If none match, or we fail to chdir, we return NULL.
282 * If all goes well, we return the directory we used to chdir() (but
283 * before ~user is expanded), avoiding getcwd() resolving symbolic
284 * links. User relative paths are also returned as they are given,
285 * except DWIM suffixing.
287 const char *enter_repo(const char *path
, int strict
)
289 static char used_path
[PATH_MAX
];
290 static char validated_path
[PATH_MAX
];
296 static const char *suffix
[] = {
297 "/.git", "", ".git/.git", ".git", NULL
,
300 int len
= strlen(path
);
302 while ((1 < len
) && (path
[len
-1] == '/'))
307 strncpy(used_path
, path
, len
); used_path
[len
] = 0 ;
308 strcpy(validated_path
, used_path
);
310 if (used_path
[0] == '~') {
311 char *newpath
= expand_user_path(used_path
);
312 if (!newpath
|| (PATH_MAX
- 10 < strlen(newpath
))) {
317 * Copy back into the static buffer. A pity
318 * since newpath was not bounded, but other
319 * branches of the if are limited by PATH_MAX
322 strcpy(used_path
, newpath
); free(newpath
);
324 else if (PATH_MAX
- 10 < len
)
326 len
= strlen(used_path
);
327 for (i
= 0; suffix
[i
]; i
++) {
329 strcpy(used_path
+ len
, suffix
[i
]);
330 if (!stat(used_path
, &st
) &&
331 (S_ISREG(st
.st_mode
) ||
332 (S_ISDIR(st
.st_mode
) && is_git_directory(used_path
)))) {
333 strcat(validated_path
, suffix
[i
]);
339 gitfile
= read_gitfile(used_path
) ;
341 strcpy(used_path
, gitfile
);
342 if (chdir(used_path
))
344 path
= validated_path
;
346 else if (chdir(path
))
349 if (access("objects", X_OK
) == 0 && access("refs", X_OK
) == 0 &&
350 validate_headref("HEAD") == 0) {
352 check_repository_format();
359 static int calc_shared_perm(int mode
)
363 if (shared_repository
< 0)
364 tweak
= -shared_repository
;
366 tweak
= shared_repository
;
368 if (!(mode
& S_IWUSR
))
371 /* Copy read bits to execute bits */
372 tweak
|= (tweak
& 0444) >> 2;
373 if (shared_repository
< 0)
374 mode
= (mode
& ~0777) | tweak
;
382 int adjust_shared_perm(const char *path
)
384 int old_mode
, new_mode
;
386 if (!shared_repository
)
388 if (get_st_mode_bits(path
, &old_mode
) < 0)
391 new_mode
= calc_shared_perm(old_mode
);
392 if (S_ISDIR(old_mode
)) {
393 /* Copy read bits to execute bits */
394 new_mode
|= (new_mode
& 0444) >> 2;
395 new_mode
|= FORCE_DIR_SET_GID
;
398 if (((old_mode
^ new_mode
) & ~S_IFMT
) &&
399 chmod(path
, (new_mode
& ~S_IFMT
)) < 0)
404 static int have_same_root(const char *path1
, const char *path2
)
406 int is_abs1
, is_abs2
;
408 is_abs1
= is_absolute_path(path1
);
409 is_abs2
= is_absolute_path(path2
);
410 return (is_abs1
&& is_abs2
&& tolower(path1
[0]) == tolower(path2
[0])) ||
411 (!is_abs1
&& !is_abs2
);
415 * Give path as relative to prefix.
417 * The strbuf may or may not be used, so do not assume it contains the
420 const char *relative_path(const char *in
, const char *prefix
,
423 int in_len
= in
? strlen(in
) : 0;
424 int prefix_len
= prefix
? strlen(prefix
) : 0;
431 else if (!prefix_len
)
434 if (have_same_root(in
, prefix
)) {
435 /* bypass dos_drive, for "c:" is identical to "C:" */
436 if (has_dos_drive_prefix(in
)) {
444 while (i
< prefix_len
&& j
< in_len
&& prefix
[i
] == in
[j
]) {
445 if (is_dir_sep(prefix
[i
])) {
446 while (is_dir_sep(prefix
[i
]))
448 while (is_dir_sep(in
[j
]))
459 /* "prefix" seems like prefix of "in" */
462 * but "/foo" is not a prefix of "/foobar"
463 * (i.e. prefix not end with '/')
465 prefix_off
< prefix_len
) {
467 /* in="/a/b", prefix="/a/b" */
469 } else if (is_dir_sep(in
[j
])) {
470 /* in="/a/b/c", prefix="/a/b" */
471 while (is_dir_sep(in
[j
]))
475 /* in="/a/bbb/c", prefix="/a/b" */
479 /* "in" is short than "prefix" */
481 /* "in" not end with '/' */
483 if (is_dir_sep(prefix
[i
])) {
484 /* in="/a/b", prefix="/a/b/c/" */
485 while (is_dir_sep(prefix
[i
]))
493 if (i
>= prefix_len
) {
501 strbuf_grow(sb
, in_len
);
503 while (i
< prefix_len
) {
504 if (is_dir_sep(prefix
[i
])) {
505 strbuf_addstr(sb
, "../");
506 while (is_dir_sep(prefix
[i
]))
512 if (!is_dir_sep(prefix
[prefix_len
- 1]))
513 strbuf_addstr(sb
, "../");
515 strbuf_addstr(sb
, in
);
521 * A simpler implementation of relative_path
523 * Get relative path by removing "prefix" from "in". This function
524 * first appears in v1.5.6-1-g044bbbc, and makes git_dir shorter
525 * to increase performance when traversing the path to work_tree.
527 const char *remove_leading_path(const char *in
, const char *prefix
)
529 static char buf
[PATH_MAX
+ 1];
532 if (!prefix
|| !prefix
[0])
535 if (is_dir_sep(prefix
[i
])) {
536 if (!is_dir_sep(in
[j
]))
538 while (is_dir_sep(prefix
[i
]))
540 while (is_dir_sep(in
[j
]))
543 } else if (in
[j
] != prefix
[i
]) {
550 /* "/foo" is a prefix of "/foo" */
552 /* "/foo" is not a prefix of "/foobar" */
553 !is_dir_sep(prefix
[i
-1]) && !is_dir_sep(in
[j
])
556 while (is_dir_sep(in
[j
]))
566 * It is okay if dst == src, but they should not overlap otherwise.
568 * Performs the following normalizations on src, storing the result in dst:
569 * - Ensures that components are separated by '/' (Windows only)
570 * - Squashes sequences of '/'.
571 * - Removes "." components.
572 * - Removes ".." components, and the components the precede them.
573 * Returns failure (non-zero) if a ".." component appears as first path
574 * component anytime during the normalization. Otherwise, returns success (0).
576 * Note that this function is purely textual. It does not follow symlinks,
577 * verify the existence of the path, or make any system calls.
579 * prefix_len != NULL is for a specific case of prefix_pathspec():
580 * assume that src == dst and src[0..prefix_len-1] is already
581 * normalized, any time "../" eats up to the prefix_len part,
582 * prefix_len is reduced. In the end prefix_len is the remaining
583 * prefix that has not been overridden by user pathspec.
585 int normalize_path_copy_len(char *dst
, const char *src
, int *prefix_len
)
589 if (has_dos_drive_prefix(src
)) {
595 if (is_dir_sep(*src
)) {
597 while (is_dir_sep(*src
))
605 * A path component that begins with . could be
607 * (1) "." and ends -- ignore and terminate.
608 * (2) "./" -- ignore them, eat slash and continue.
609 * (3) ".." and ends -- strip one and terminate.
610 * (4) "../" -- strip one, eat slash and continue.
616 } else if (is_dir_sep(src
[1])) {
619 while (is_dir_sep(*src
))
622 } else if (src
[1] == '.') {
627 } else if (is_dir_sep(src
[2])) {
630 while (is_dir_sep(*src
))
637 /* copy up to the next '/', and eat all '/' */
638 while ((c
= *src
++) != '\0' && !is_dir_sep(c
))
642 while (is_dir_sep(c
))
651 * dst0..dst is prefix portion, and dst[-1] is '/';
654 dst
--; /* go to trailing '/' */
657 /* Windows: dst[-1] cannot be backslash anymore */
658 while (dst0
< dst
&& dst
[-1] != '/')
660 if (prefix_len
&& *prefix_len
> dst
- dst0
)
661 *prefix_len
= dst
- dst0
;
667 int normalize_path_copy(char *dst
, const char *src
)
669 return normalize_path_copy_len(dst
, src
, NULL
);
673 * path = Canonical absolute path
674 * prefixes = string_list containing normalized, absolute paths without
675 * trailing slashes (except for the root directory, which is denoted by "/").
677 * Determines, for each path in prefixes, whether the "prefix"
678 * is an ancestor directory of path. Returns the length of the longest
679 * ancestor directory, excluding any trailing slashes, or -1 if no prefix
680 * is an ancestor. (Note that this means 0 is returned if prefixes is
681 * ["/"].) "/foo" is not considered an ancestor of "/foobar". Directories
682 * are not considered to be their own ancestors. path must be in a
683 * canonical form: empty components, or "." or ".." components are not
686 int longest_ancestor_length(const char *path
, struct string_list
*prefixes
)
690 if (!strcmp(path
, "/"))
693 for (i
= 0; i
< prefixes
->nr
; i
++) {
694 const char *ceil
= prefixes
->items
[i
].string
;
695 int len
= strlen(ceil
);
697 if (len
== 1 && ceil
[0] == '/')
698 len
= 0; /* root matches anything, with length 0 */
699 else if (!strncmp(path
, ceil
, len
) && path
[len
] == '/')
700 ; /* match of length len */
702 continue; /* no match */
711 /* strip arbitrary amount of directory separators at end of path */
712 static inline int chomp_trailing_dir_sep(const char *path
, int len
)
714 while (len
&& is_dir_sep(path
[len
- 1]))
720 * If path ends with suffix (complete path components), returns the
721 * part before suffix (sans trailing directory separators).
722 * Otherwise returns NULL.
724 char *strip_path_suffix(const char *path
, const char *suffix
)
726 int path_len
= strlen(path
), suffix_len
= strlen(suffix
);
732 if (is_dir_sep(path
[path_len
- 1])) {
733 if (!is_dir_sep(suffix
[suffix_len
- 1]))
735 path_len
= chomp_trailing_dir_sep(path
, path_len
);
736 suffix_len
= chomp_trailing_dir_sep(suffix
, suffix_len
);
738 else if (path
[--path_len
] != suffix
[--suffix_len
])
742 if (path_len
&& !is_dir_sep(path
[path_len
- 1]))
744 return xstrndup(path
, chomp_trailing_dir_sep(path
, path_len
));
747 int daemon_avoid_alias(const char *p
)
752 * This resurrects the belts and suspenders paranoia check by HPA
753 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
754 * does not do getcwd() based path canonicalization.
756 * sl becomes true immediately after seeing '/' and continues to
757 * be true as long as dots continue after that without intervening
760 if (!p
|| (*p
!= '/' && *p
!= '~'))
770 else if (ch
== '/') {
772 /* reject //, /./ and /../ */
777 if (0 < ndot
&& ndot
< 3)
778 /* reject /.$ and /..$ */
787 else if (ch
== '/') {
794 static int only_spaces_and_periods(const char *path
, size_t len
, size_t skip
)
802 if (c
!= ' ' && c
!= '.')
808 int is_ntfs_dotgit(const char *name
)
812 for (len
= 0; ; len
++)
813 if (!name
[len
] || name
[len
] == '\\' || is_dir_sep(name
[len
])) {
814 if (only_spaces_and_periods(name
, len
, 4) &&
815 !strncasecmp(name
, ".git", 4))
817 if (only_spaces_and_periods(name
, len
, 5) &&
818 !strncasecmp(name
, "git~1", 5))
820 if (name
[len
] != '\\')
827 char *xdg_config_home(const char *filename
)
829 const char *home
, *config_home
;
832 config_home
= getenv("XDG_CONFIG_HOME");
833 if (config_home
&& *config_home
)
834 return mkpathdup("%s/git/%s", config_home
, filename
);
836 home
= getenv("HOME");
838 return mkpathdup("%s/.config/git/%s", home
, filename
);