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 const char *common_list
[] = {
94 "/branches", "/hooks", "/info", "/logs", "/lost-found", "/modules",
95 "/objects", "/refs", "/remotes", "/worktrees", "/rr-cache", "/svn",
96 "config", "gc.pid", "packed-refs", "shallow",
100 static void update_common_dir(struct strbuf
*buf
, int git_dir_len
)
102 char *base
= buf
->buf
+ git_dir_len
;
105 if (is_dir_file(base
, "logs", "HEAD"))
106 return; /* keep this in $GIT_DIR */
107 for (p
= common_list
; *p
; p
++) {
108 const char *path
= *p
;
114 if (is_dir
&& dir_prefix(base
, path
)) {
115 replace_dir(buf
, git_dir_len
, get_git_common_dir());
118 if (!is_dir
&& !strcmp(base
, path
)) {
119 replace_dir(buf
, git_dir_len
, get_git_common_dir());
125 static void adjust_git_path(struct strbuf
*buf
, int git_dir_len
)
127 const char *base
= buf
->buf
+ git_dir_len
;
128 if (git_graft_env
&& is_dir_file(base
, "info", "grafts"))
129 strbuf_splice(buf
, 0, buf
->len
,
130 get_graft_file(), strlen(get_graft_file()));
131 else if (git_index_env
&& !strcmp(base
, "index"))
132 strbuf_splice(buf
, 0, buf
->len
,
133 get_index_file(), strlen(get_index_file()));
134 else if (git_db_env
&& dir_prefix(base
, "objects"))
135 replace_dir(buf
, git_dir_len
+ 7, get_object_directory());
136 else if (git_common_dir_env
)
137 update_common_dir(buf
, git_dir_len
);
140 static void do_git_path(struct strbuf
*buf
, const char *fmt
, va_list args
)
143 strbuf_addstr(buf
, get_git_dir());
144 if (buf
->len
&& !is_dir_sep(buf
->buf
[buf
->len
- 1]))
145 strbuf_addch(buf
, '/');
146 gitdir_len
= buf
->len
;
147 strbuf_vaddf(buf
, fmt
, args
);
148 adjust_git_path(buf
, gitdir_len
);
149 strbuf_cleanup_path(buf
);
152 void strbuf_git_path(struct strbuf
*sb
, const char *fmt
, ...)
156 do_git_path(sb
, fmt
, args
);
160 const char *git_path(const char *fmt
, ...)
162 struct strbuf
*pathname
= get_pathname();
165 do_git_path(pathname
, fmt
, args
);
167 return pathname
->buf
;
170 char *git_pathdup(const char *fmt
, ...)
172 struct strbuf path
= STRBUF_INIT
;
175 do_git_path(&path
, fmt
, args
);
177 return strbuf_detach(&path
, NULL
);
180 char *mkpathdup(const char *fmt
, ...)
182 struct strbuf sb
= STRBUF_INIT
;
185 strbuf_vaddf(&sb
, fmt
, args
);
187 strbuf_cleanup_path(&sb
);
188 return strbuf_detach(&sb
, NULL
);
191 const char *mkpath(const char *fmt
, ...)
194 struct strbuf
*pathname
= get_pathname();
196 strbuf_vaddf(pathname
, fmt
, args
);
198 return cleanup_path(pathname
->buf
);
201 void home_config_paths(char **global
, char **xdg
, char *file
)
203 char *xdg_home
= getenv("XDG_CONFIG_HOME");
204 char *home
= getenv("HOME");
205 char *to_free
= NULL
;
212 to_free
= mkpathdup("%s/.config", home
);
216 *global
= mkpathdup("%s/.gitconfig", home
);
223 *xdg
= mkpathdup("%s/git/%s", xdg_home
, file
);
229 const char *git_path_submodule(const char *path
, const char *fmt
, ...)
231 struct strbuf
*buf
= get_pathname();
235 strbuf_addstr(buf
, path
);
236 if (buf
->len
&& buf
->buf
[buf
->len
- 1] != '/')
237 strbuf_addch(buf
, '/');
238 strbuf_addstr(buf
, ".git");
240 git_dir
= read_gitfile(buf
->buf
);
243 strbuf_addstr(buf
, git_dir
);
245 strbuf_addch(buf
, '/');
248 strbuf_vaddf(buf
, fmt
, args
);
250 strbuf_cleanup_path(buf
);
254 int validate_headref(const char *path
)
257 char *buf
, buffer
[256];
258 unsigned char sha1
[20];
262 if (lstat(path
, &st
) < 0)
265 /* Make sure it is a "refs/.." symlink */
266 if (S_ISLNK(st
.st_mode
)) {
267 len
= readlink(path
, buffer
, sizeof(buffer
)-1);
268 if (len
>= 5 && !memcmp("refs/", buffer
, 5))
274 * Anything else, just open it and try to see if it is a symbolic ref.
276 fd
= open(path
, O_RDONLY
);
279 len
= read_in_full(fd
, buffer
, sizeof(buffer
)-1);
283 * Is it a symbolic ref?
287 if (!memcmp("ref:", buffer
, 4)) {
290 while (len
&& isspace(*buf
))
292 if (len
>= 5 && !memcmp("refs/", buf
, 5))
297 * Is this a detached HEAD?
299 if (!get_sha1_hex(buffer
, sha1
))
305 static struct passwd
*getpw_str(const char *username
, size_t len
)
308 char *username_z
= xmemdupz(username
, len
);
309 pw
= getpwnam(username_z
);
315 * Return a string with ~ and ~user expanded via getpw*. If buf != NULL,
316 * then it is a newly allocated string. Returns NULL on getpw failure or
319 char *expand_user_path(const char *path
)
321 struct strbuf user_path
= STRBUF_INIT
;
322 const char *to_copy
= path
;
326 if (path
[0] == '~') {
327 const char *first_slash
= strchrnul(path
, '/');
328 const char *username
= path
+ 1;
329 size_t username_len
= first_slash
- username
;
330 if (username_len
== 0) {
331 const char *home
= getenv("HOME");
334 strbuf_addstr(&user_path
, home
);
336 struct passwd
*pw
= getpw_str(username
, username_len
);
339 strbuf_addstr(&user_path
, pw
->pw_dir
);
341 to_copy
= first_slash
;
343 strbuf_addstr(&user_path
, to_copy
);
344 return strbuf_detach(&user_path
, NULL
);
346 strbuf_release(&user_path
);
351 * First, one directory to try is determined by the following algorithm.
353 * (0) If "strict" is given, the path is used as given and no DWIM is
355 * (1) "~/path" to mean path under the running user's home directory;
356 * (2) "~user/path" to mean path under named user's home directory;
357 * (3) "relative/path" to mean cwd relative directory; or
358 * (4) "/absolute/path" to mean absolute directory.
360 * Unless "strict" is given, we try access() for existence of "%s.git/.git",
361 * "%s/.git", "%s.git", "%s" in this order. The first one that exists is
364 * Second, we try chdir() to that. Upon failure, we return NULL.
366 * Then, we try if the current directory is a valid git repository.
367 * Upon failure, we return NULL.
369 * If all goes well, we return the directory we used to chdir() (but
370 * before ~user is expanded), avoiding getcwd() resolving symbolic
371 * links. User relative paths are also returned as they are given,
372 * except DWIM suffixing.
374 const char *enter_repo(const char *path
, int strict
)
376 static char used_path
[PATH_MAX
];
377 static char validated_path
[PATH_MAX
];
383 static const char *suffix
[] = {
384 "/.git", "", ".git/.git", ".git", NULL
,
387 int len
= strlen(path
);
389 while ((1 < len
) && (path
[len
-1] == '/'))
394 strncpy(used_path
, path
, len
); used_path
[len
] = 0 ;
395 strcpy(validated_path
, used_path
);
397 if (used_path
[0] == '~') {
398 char *newpath
= expand_user_path(used_path
);
399 if (!newpath
|| (PATH_MAX
- 10 < strlen(newpath
))) {
404 * Copy back into the static buffer. A pity
405 * since newpath was not bounded, but other
406 * branches of the if are limited by PATH_MAX
409 strcpy(used_path
, newpath
); free(newpath
);
411 else if (PATH_MAX
- 10 < len
)
413 len
= strlen(used_path
);
414 for (i
= 0; suffix
[i
]; i
++) {
416 strcpy(used_path
+ len
, suffix
[i
]);
417 if (!stat(used_path
, &st
) &&
418 (S_ISREG(st
.st_mode
) ||
419 (S_ISDIR(st
.st_mode
) && is_git_directory(used_path
)))) {
420 strcat(validated_path
, suffix
[i
]);
426 gitfile
= read_gitfile(used_path
) ;
428 strcpy(used_path
, gitfile
);
429 if (chdir(used_path
))
431 path
= validated_path
;
433 else if (chdir(path
))
436 if (access("objects", X_OK
) == 0 && access("refs", X_OK
) == 0 &&
437 validate_headref("HEAD") == 0) {
439 check_repository_format();
446 static int calc_shared_perm(int mode
)
450 if (shared_repository
< 0)
451 tweak
= -shared_repository
;
453 tweak
= shared_repository
;
455 if (!(mode
& S_IWUSR
))
458 /* Copy read bits to execute bits */
459 tweak
|= (tweak
& 0444) >> 2;
460 if (shared_repository
< 0)
461 mode
= (mode
& ~0777) | tweak
;
469 int adjust_shared_perm(const char *path
)
471 int old_mode
, new_mode
;
473 if (!shared_repository
)
475 if (get_st_mode_bits(path
, &old_mode
) < 0)
478 new_mode
= calc_shared_perm(old_mode
);
479 if (S_ISDIR(old_mode
)) {
480 /* Copy read bits to execute bits */
481 new_mode
|= (new_mode
& 0444) >> 2;
482 new_mode
|= FORCE_DIR_SET_GID
;
485 if (((old_mode
^ new_mode
) & ~S_IFMT
) &&
486 chmod(path
, (new_mode
& ~S_IFMT
)) < 0)
491 static int have_same_root(const char *path1
, const char *path2
)
493 int is_abs1
, is_abs2
;
495 is_abs1
= is_absolute_path(path1
);
496 is_abs2
= is_absolute_path(path2
);
497 return (is_abs1
&& is_abs2
&& tolower(path1
[0]) == tolower(path2
[0])) ||
498 (!is_abs1
&& !is_abs2
);
502 * Give path as relative to prefix.
504 * The strbuf may or may not be used, so do not assume it contains the
507 const char *relative_path(const char *in
, const char *prefix
,
510 int in_len
= in
? strlen(in
) : 0;
511 int prefix_len
= prefix
? strlen(prefix
) : 0;
518 else if (!prefix_len
)
521 if (have_same_root(in
, prefix
)) {
522 /* bypass dos_drive, for "c:" is identical to "C:" */
523 if (has_dos_drive_prefix(in
)) {
531 while (i
< prefix_len
&& j
< in_len
&& prefix
[i
] == in
[j
]) {
532 if (is_dir_sep(prefix
[i
])) {
533 while (is_dir_sep(prefix
[i
]))
535 while (is_dir_sep(in
[j
]))
546 /* "prefix" seems like prefix of "in" */
549 * but "/foo" is not a prefix of "/foobar"
550 * (i.e. prefix not end with '/')
552 prefix_off
< prefix_len
) {
554 /* in="/a/b", prefix="/a/b" */
556 } else if (is_dir_sep(in
[j
])) {
557 /* in="/a/b/c", prefix="/a/b" */
558 while (is_dir_sep(in
[j
]))
562 /* in="/a/bbb/c", prefix="/a/b" */
566 /* "in" is short than "prefix" */
568 /* "in" not end with '/' */
570 if (is_dir_sep(prefix
[i
])) {
571 /* in="/a/b", prefix="/a/b/c/" */
572 while (is_dir_sep(prefix
[i
]))
580 if (i
>= prefix_len
) {
588 strbuf_grow(sb
, in_len
);
590 while (i
< prefix_len
) {
591 if (is_dir_sep(prefix
[i
])) {
592 strbuf_addstr(sb
, "../");
593 while (is_dir_sep(prefix
[i
]))
599 if (!is_dir_sep(prefix
[prefix_len
- 1]))
600 strbuf_addstr(sb
, "../");
602 strbuf_addstr(sb
, in
);
608 * A simpler implementation of relative_path
610 * Get relative path by removing "prefix" from "in". This function
611 * first appears in v1.5.6-1-g044bbbc, and makes git_dir shorter
612 * to increase performance when traversing the path to work_tree.
614 const char *remove_leading_path(const char *in
, const char *prefix
)
616 static char buf
[PATH_MAX
+ 1];
619 if (!prefix
|| !prefix
[0])
622 if (is_dir_sep(prefix
[i
])) {
623 if (!is_dir_sep(in
[j
]))
625 while (is_dir_sep(prefix
[i
]))
627 while (is_dir_sep(in
[j
]))
630 } else if (in
[j
] != prefix
[i
]) {
637 /* "/foo" is a prefix of "/foo" */
639 /* "/foo" is not a prefix of "/foobar" */
640 !is_dir_sep(prefix
[i
-1]) && !is_dir_sep(in
[j
])
643 while (is_dir_sep(in
[j
]))
653 * It is okay if dst == src, but they should not overlap otherwise.
655 * Performs the following normalizations on src, storing the result in dst:
656 * - Ensures that components are separated by '/' (Windows only)
657 * - Squashes sequences of '/'.
658 * - Removes "." components.
659 * - Removes ".." components, and the components the precede them.
660 * Returns failure (non-zero) if a ".." component appears as first path
661 * component anytime during the normalization. Otherwise, returns success (0).
663 * Note that this function is purely textual. It does not follow symlinks,
664 * verify the existence of the path, or make any system calls.
666 * prefix_len != NULL is for a specific case of prefix_pathspec():
667 * assume that src == dst and src[0..prefix_len-1] is already
668 * normalized, any time "../" eats up to the prefix_len part,
669 * prefix_len is reduced. In the end prefix_len is the remaining
670 * prefix that has not been overridden by user pathspec.
672 int normalize_path_copy_len(char *dst
, const char *src
, int *prefix_len
)
676 if (has_dos_drive_prefix(src
)) {
682 if (is_dir_sep(*src
)) {
684 while (is_dir_sep(*src
))
692 * A path component that begins with . could be
694 * (1) "." and ends -- ignore and terminate.
695 * (2) "./" -- ignore them, eat slash and continue.
696 * (3) ".." and ends -- strip one and terminate.
697 * (4) "../" -- strip one, eat slash and continue.
703 } else if (is_dir_sep(src
[1])) {
706 while (is_dir_sep(*src
))
709 } else if (src
[1] == '.') {
714 } else if (is_dir_sep(src
[2])) {
717 while (is_dir_sep(*src
))
724 /* copy up to the next '/', and eat all '/' */
725 while ((c
= *src
++) != '\0' && !is_dir_sep(c
))
729 while (is_dir_sep(c
))
738 * dst0..dst is prefix portion, and dst[-1] is '/';
741 dst
--; /* go to trailing '/' */
744 /* Windows: dst[-1] cannot be backslash anymore */
745 while (dst0
< dst
&& dst
[-1] != '/')
747 if (prefix_len
&& *prefix_len
> dst
- dst0
)
748 *prefix_len
= dst
- dst0
;
754 int normalize_path_copy(char *dst
, const char *src
)
756 return normalize_path_copy_len(dst
, src
, NULL
);
760 * path = Canonical absolute path
761 * prefixes = string_list containing normalized, absolute paths without
762 * trailing slashes (except for the root directory, which is denoted by "/").
764 * Determines, for each path in prefixes, whether the "prefix"
765 * is an ancestor directory of path. Returns the length of the longest
766 * ancestor directory, excluding any trailing slashes, or -1 if no prefix
767 * is an ancestor. (Note that this means 0 is returned if prefixes is
768 * ["/"].) "/foo" is not considered an ancestor of "/foobar". Directories
769 * are not considered to be their own ancestors. path must be in a
770 * canonical form: empty components, or "." or ".." components are not
773 int longest_ancestor_length(const char *path
, struct string_list
*prefixes
)
777 if (!strcmp(path
, "/"))
780 for (i
= 0; i
< prefixes
->nr
; i
++) {
781 const char *ceil
= prefixes
->items
[i
].string
;
782 int len
= strlen(ceil
);
784 if (len
== 1 && ceil
[0] == '/')
785 len
= 0; /* root matches anything, with length 0 */
786 else if (!strncmp(path
, ceil
, len
) && path
[len
] == '/')
787 ; /* match of length len */
789 continue; /* no match */
798 /* strip arbitrary amount of directory separators at end of path */
799 static inline int chomp_trailing_dir_sep(const char *path
, int len
)
801 while (len
&& is_dir_sep(path
[len
- 1]))
807 * If path ends with suffix (complete path components), returns the
808 * part before suffix (sans trailing directory separators).
809 * Otherwise returns NULL.
811 char *strip_path_suffix(const char *path
, const char *suffix
)
813 int path_len
= strlen(path
), suffix_len
= strlen(suffix
);
819 if (is_dir_sep(path
[path_len
- 1])) {
820 if (!is_dir_sep(suffix
[suffix_len
- 1]))
822 path_len
= chomp_trailing_dir_sep(path
, path_len
);
823 suffix_len
= chomp_trailing_dir_sep(suffix
, suffix_len
);
825 else if (path
[--path_len
] != suffix
[--suffix_len
])
829 if (path_len
&& !is_dir_sep(path
[path_len
- 1]))
831 return xstrndup(path
, chomp_trailing_dir_sep(path
, path_len
));
834 int daemon_avoid_alias(const char *p
)
839 * This resurrects the belts and suspenders paranoia check by HPA
840 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
841 * does not do getcwd() based path canonicalization.
843 * sl becomes true immediately after seeing '/' and continues to
844 * be true as long as dots continue after that without intervening
847 if (!p
|| (*p
!= '/' && *p
!= '~'))
857 else if (ch
== '/') {
859 /* reject //, /./ and /../ */
864 if (0 < ndot
&& ndot
< 3)
865 /* reject /.$ and /..$ */
874 else if (ch
== '/') {