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
] = '/';
95 /* Not considered garbage for report_linked_checkout_garbage */
96 unsigned ignore_garbage
:1;
98 /* Not common even though its parent is */
103 static struct common_dir common_list
[] = {
104 { 0, 1, 0, "branches" },
105 { 0, 1, 0, "hooks" },
107 { 0, 0, 1, "info/sparse-checkout" },
109 { 1, 1, 1, "logs/HEAD" },
110 { 0, 1, 0, "lost-found" },
111 { 0, 1, 0, "objects" },
113 { 0, 1, 0, "remotes" },
114 { 0, 1, 0, "worktrees" },
115 { 0, 1, 0, "rr-cache" },
117 { 0, 0, 0, "config" },
118 { 1, 0, 0, "gc.pid" },
119 { 0, 0, 0, "packed-refs" },
120 { 0, 0, 0, "shallow" },
124 static void update_common_dir(struct strbuf
*buf
, int git_dir_len
)
126 char *base
= buf
->buf
+ git_dir_len
;
127 const struct common_dir
*p
;
129 if (is_dir_file(base
, "logs", "HEAD") ||
130 is_dir_file(base
, "info", "sparse-checkout"))
131 return; /* keep this in $GIT_DIR */
132 for (p
= common_list
; p
->dirname
; p
++) {
133 const char *path
= p
->dirname
;
134 if (p
->is_dir
&& dir_prefix(base
, path
)) {
135 replace_dir(buf
, git_dir_len
, get_git_common_dir());
138 if (!p
->is_dir
&& !strcmp(base
, path
)) {
139 replace_dir(buf
, git_dir_len
, get_git_common_dir());
145 void report_linked_checkout_garbage(void)
147 struct strbuf sb
= STRBUF_INIT
;
148 const struct common_dir
*p
;
151 if (!git_common_dir_env
)
153 strbuf_addf(&sb
, "%s/", get_git_dir());
155 for (p
= common_list
; p
->dirname
; p
++) {
156 const char *path
= p
->dirname
;
157 if (p
->ignore_garbage
)
159 strbuf_setlen(&sb
, len
);
160 strbuf_addstr(&sb
, path
);
161 if (file_exists(sb
.buf
))
162 report_garbage("unused in linked checkout", sb
.buf
);
167 static void adjust_git_path(struct strbuf
*buf
, int git_dir_len
)
169 const char *base
= buf
->buf
+ git_dir_len
;
170 if (git_graft_env
&& is_dir_file(base
, "info", "grafts"))
171 strbuf_splice(buf
, 0, buf
->len
,
172 get_graft_file(), strlen(get_graft_file()));
173 else if (git_index_env
&& !strcmp(base
, "index"))
174 strbuf_splice(buf
, 0, buf
->len
,
175 get_index_file(), strlen(get_index_file()));
176 else if (git_db_env
&& dir_prefix(base
, "objects"))
177 replace_dir(buf
, git_dir_len
+ 7, get_object_directory());
178 else if (git_common_dir_env
)
179 update_common_dir(buf
, git_dir_len
);
182 static void do_git_path(struct strbuf
*buf
, const char *fmt
, va_list args
)
185 strbuf_addstr(buf
, get_git_dir());
186 if (buf
->len
&& !is_dir_sep(buf
->buf
[buf
->len
- 1]))
187 strbuf_addch(buf
, '/');
188 gitdir_len
= buf
->len
;
189 strbuf_vaddf(buf
, fmt
, args
);
190 adjust_git_path(buf
, gitdir_len
);
191 strbuf_cleanup_path(buf
);
194 void strbuf_git_path(struct strbuf
*sb
, const char *fmt
, ...)
198 do_git_path(sb
, fmt
, args
);
202 const char *git_path(const char *fmt
, ...)
204 struct strbuf
*pathname
= get_pathname();
207 do_git_path(pathname
, fmt
, args
);
209 return pathname
->buf
;
212 char *git_pathdup(const char *fmt
, ...)
214 struct strbuf path
= STRBUF_INIT
;
217 do_git_path(&path
, fmt
, args
);
219 return strbuf_detach(&path
, NULL
);
222 char *mkpathdup(const char *fmt
, ...)
224 struct strbuf sb
= STRBUF_INIT
;
227 strbuf_vaddf(&sb
, fmt
, args
);
229 strbuf_cleanup_path(&sb
);
230 return strbuf_detach(&sb
, NULL
);
233 const char *mkpath(const char *fmt
, ...)
236 struct strbuf
*pathname
= get_pathname();
238 strbuf_vaddf(pathname
, fmt
, args
);
240 return cleanup_path(pathname
->buf
);
243 static void do_submodule_path(struct strbuf
*buf
, const char *path
,
244 const char *fmt
, va_list args
)
248 strbuf_addstr(buf
, path
);
249 if (buf
->len
&& buf
->buf
[buf
->len
- 1] != '/')
250 strbuf_addch(buf
, '/');
251 strbuf_addstr(buf
, ".git");
253 git_dir
= read_gitfile(buf
->buf
);
256 strbuf_addstr(buf
, git_dir
);
258 strbuf_addch(buf
, '/');
260 strbuf_vaddf(buf
, fmt
, args
);
261 strbuf_cleanup_path(buf
);
264 char *git_pathdup_submodule(const char *path
, const char *fmt
, ...)
267 struct strbuf buf
= STRBUF_INIT
;
269 do_submodule_path(&buf
, path
, fmt
, args
);
271 return strbuf_detach(&buf
, NULL
);
274 void strbuf_git_path_submodule(struct strbuf
*buf
, const char *path
,
275 const char *fmt
, ...)
279 do_submodule_path(buf
, path
, fmt
, args
);
283 int validate_headref(const char *path
)
286 char *buf
, buffer
[256];
287 unsigned char sha1
[20];
291 if (lstat(path
, &st
) < 0)
294 /* Make sure it is a "refs/.." symlink */
295 if (S_ISLNK(st
.st_mode
)) {
296 len
= readlink(path
, buffer
, sizeof(buffer
)-1);
297 if (len
>= 5 && !memcmp("refs/", buffer
, 5))
303 * Anything else, just open it and try to see if it is a symbolic ref.
305 fd
= open(path
, O_RDONLY
);
308 len
= read_in_full(fd
, buffer
, sizeof(buffer
)-1);
312 * Is it a symbolic ref?
316 if (!memcmp("ref:", buffer
, 4)) {
319 while (len
&& isspace(*buf
))
321 if (len
>= 5 && !memcmp("refs/", buf
, 5))
326 * Is this a detached HEAD?
328 if (!get_sha1_hex(buffer
, sha1
))
334 static struct passwd
*getpw_str(const char *username
, size_t len
)
337 char *username_z
= xmemdupz(username
, len
);
338 pw
= getpwnam(username_z
);
344 * Return a string with ~ and ~user expanded via getpw*. If buf != NULL,
345 * then it is a newly allocated string. Returns NULL on getpw failure or
348 char *expand_user_path(const char *path
)
350 struct strbuf user_path
= STRBUF_INIT
;
351 const char *to_copy
= path
;
355 if (path
[0] == '~') {
356 const char *first_slash
= strchrnul(path
, '/');
357 const char *username
= path
+ 1;
358 size_t username_len
= first_slash
- username
;
359 if (username_len
== 0) {
360 const char *home
= getenv("HOME");
363 strbuf_addstr(&user_path
, home
);
365 struct passwd
*pw
= getpw_str(username
, username_len
);
368 strbuf_addstr(&user_path
, pw
->pw_dir
);
370 to_copy
= first_slash
;
372 strbuf_addstr(&user_path
, to_copy
);
373 return strbuf_detach(&user_path
, NULL
);
375 strbuf_release(&user_path
);
380 * First, one directory to try is determined by the following algorithm.
382 * (0) If "strict" is given, the path is used as given and no DWIM is
384 * (1) "~/path" to mean path under the running user's home directory;
385 * (2) "~user/path" to mean path under named user's home directory;
386 * (3) "relative/path" to mean cwd relative directory; or
387 * (4) "/absolute/path" to mean absolute directory.
389 * Unless "strict" is given, we check "%s/.git", "%s", "%s.git/.git", "%s.git"
390 * in this order. We select the first one that is a valid git repository, and
391 * chdir() to it. If none match, or we fail to chdir, we return NULL.
393 * If all goes well, we return the directory we used to chdir() (but
394 * before ~user is expanded), avoiding getcwd() resolving symbolic
395 * links. User relative paths are also returned as they are given,
396 * except DWIM suffixing.
398 const char *enter_repo(const char *path
, int strict
)
400 static char used_path
[PATH_MAX
];
401 static char validated_path
[PATH_MAX
];
407 static const char *suffix
[] = {
408 "/.git", "", ".git/.git", ".git", NULL
,
411 int len
= strlen(path
);
413 while ((1 < len
) && (path
[len
-1] == '/'))
418 strncpy(used_path
, path
, len
); used_path
[len
] = 0 ;
419 strcpy(validated_path
, used_path
);
421 if (used_path
[0] == '~') {
422 char *newpath
= expand_user_path(used_path
);
423 if (!newpath
|| (PATH_MAX
- 10 < strlen(newpath
))) {
428 * Copy back into the static buffer. A pity
429 * since newpath was not bounded, but other
430 * branches of the if are limited by PATH_MAX
433 strcpy(used_path
, newpath
); free(newpath
);
435 else if (PATH_MAX
- 10 < len
)
437 len
= strlen(used_path
);
438 for (i
= 0; suffix
[i
]; i
++) {
440 strcpy(used_path
+ len
, suffix
[i
]);
441 if (!stat(used_path
, &st
) &&
442 (S_ISREG(st
.st_mode
) ||
443 (S_ISDIR(st
.st_mode
) && is_git_directory(used_path
)))) {
444 strcat(validated_path
, suffix
[i
]);
450 gitfile
= read_gitfile(used_path
) ;
452 strcpy(used_path
, gitfile
);
453 if (chdir(used_path
))
455 path
= validated_path
;
457 else if (chdir(path
))
460 if (access("objects", X_OK
) == 0 && access("refs", X_OK
) == 0 &&
461 validate_headref("HEAD") == 0) {
463 check_repository_format();
470 static int calc_shared_perm(int mode
)
474 if (shared_repository
< 0)
475 tweak
= -shared_repository
;
477 tweak
= shared_repository
;
479 if (!(mode
& S_IWUSR
))
482 /* Copy read bits to execute bits */
483 tweak
|= (tweak
& 0444) >> 2;
484 if (shared_repository
< 0)
485 mode
= (mode
& ~0777) | tweak
;
493 int adjust_shared_perm(const char *path
)
495 int old_mode
, new_mode
;
497 if (!shared_repository
)
499 if (get_st_mode_bits(path
, &old_mode
) < 0)
502 new_mode
= calc_shared_perm(old_mode
);
503 if (S_ISDIR(old_mode
)) {
504 /* Copy read bits to execute bits */
505 new_mode
|= (new_mode
& 0444) >> 2;
506 new_mode
|= FORCE_DIR_SET_GID
;
509 if (((old_mode
^ new_mode
) & ~S_IFMT
) &&
510 chmod(path
, (new_mode
& ~S_IFMT
)) < 0)
515 static int have_same_root(const char *path1
, const char *path2
)
517 int is_abs1
, is_abs2
;
519 is_abs1
= is_absolute_path(path1
);
520 is_abs2
= is_absolute_path(path2
);
521 return (is_abs1
&& is_abs2
&& tolower(path1
[0]) == tolower(path2
[0])) ||
522 (!is_abs1
&& !is_abs2
);
526 * Give path as relative to prefix.
528 * The strbuf may or may not be used, so do not assume it contains the
531 const char *relative_path(const char *in
, const char *prefix
,
534 int in_len
= in
? strlen(in
) : 0;
535 int prefix_len
= prefix
? strlen(prefix
) : 0;
542 else if (!prefix_len
)
545 if (have_same_root(in
, prefix
)) {
546 /* bypass dos_drive, for "c:" is identical to "C:" */
547 if (has_dos_drive_prefix(in
)) {
555 while (i
< prefix_len
&& j
< in_len
&& prefix
[i
] == in
[j
]) {
556 if (is_dir_sep(prefix
[i
])) {
557 while (is_dir_sep(prefix
[i
]))
559 while (is_dir_sep(in
[j
]))
570 /* "prefix" seems like prefix of "in" */
573 * but "/foo" is not a prefix of "/foobar"
574 * (i.e. prefix not end with '/')
576 prefix_off
< prefix_len
) {
578 /* in="/a/b", prefix="/a/b" */
580 } else if (is_dir_sep(in
[j
])) {
581 /* in="/a/b/c", prefix="/a/b" */
582 while (is_dir_sep(in
[j
]))
586 /* in="/a/bbb/c", prefix="/a/b" */
590 /* "in" is short than "prefix" */
592 /* "in" not end with '/' */
594 if (is_dir_sep(prefix
[i
])) {
595 /* in="/a/b", prefix="/a/b/c/" */
596 while (is_dir_sep(prefix
[i
]))
604 if (i
>= prefix_len
) {
612 strbuf_grow(sb
, in_len
);
614 while (i
< prefix_len
) {
615 if (is_dir_sep(prefix
[i
])) {
616 strbuf_addstr(sb
, "../");
617 while (is_dir_sep(prefix
[i
]))
623 if (!is_dir_sep(prefix
[prefix_len
- 1]))
624 strbuf_addstr(sb
, "../");
626 strbuf_addstr(sb
, in
);
632 * A simpler implementation of relative_path
634 * Get relative path by removing "prefix" from "in". This function
635 * first appears in v1.5.6-1-g044bbbc, and makes git_dir shorter
636 * to increase performance when traversing the path to work_tree.
638 const char *remove_leading_path(const char *in
, const char *prefix
)
640 static char buf
[PATH_MAX
+ 1];
643 if (!prefix
|| !prefix
[0])
646 if (is_dir_sep(prefix
[i
])) {
647 if (!is_dir_sep(in
[j
]))
649 while (is_dir_sep(prefix
[i
]))
651 while (is_dir_sep(in
[j
]))
654 } else if (in
[j
] != prefix
[i
]) {
661 /* "/foo" is a prefix of "/foo" */
663 /* "/foo" is not a prefix of "/foobar" */
664 !is_dir_sep(prefix
[i
-1]) && !is_dir_sep(in
[j
])
667 while (is_dir_sep(in
[j
]))
677 * It is okay if dst == src, but they should not overlap otherwise.
679 * Performs the following normalizations on src, storing the result in dst:
680 * - Ensures that components are separated by '/' (Windows only)
681 * - Squashes sequences of '/'.
682 * - Removes "." components.
683 * - Removes ".." components, and the components the precede them.
684 * Returns failure (non-zero) if a ".." component appears as first path
685 * component anytime during the normalization. Otherwise, returns success (0).
687 * Note that this function is purely textual. It does not follow symlinks,
688 * verify the existence of the path, or make any system calls.
690 * prefix_len != NULL is for a specific case of prefix_pathspec():
691 * assume that src == dst and src[0..prefix_len-1] is already
692 * normalized, any time "../" eats up to the prefix_len part,
693 * prefix_len is reduced. In the end prefix_len is the remaining
694 * prefix that has not been overridden by user pathspec.
696 int normalize_path_copy_len(char *dst
, const char *src
, int *prefix_len
)
700 if (has_dos_drive_prefix(src
)) {
706 if (is_dir_sep(*src
)) {
708 while (is_dir_sep(*src
))
716 * A path component that begins with . could be
718 * (1) "." and ends -- ignore and terminate.
719 * (2) "./" -- ignore them, eat slash and continue.
720 * (3) ".." and ends -- strip one and terminate.
721 * (4) "../" -- strip one, eat slash and continue.
727 } else if (is_dir_sep(src
[1])) {
730 while (is_dir_sep(*src
))
733 } else if (src
[1] == '.') {
738 } else if (is_dir_sep(src
[2])) {
741 while (is_dir_sep(*src
))
748 /* copy up to the next '/', and eat all '/' */
749 while ((c
= *src
++) != '\0' && !is_dir_sep(c
))
753 while (is_dir_sep(c
))
762 * dst0..dst is prefix portion, and dst[-1] is '/';
765 dst
--; /* go to trailing '/' */
768 /* Windows: dst[-1] cannot be backslash anymore */
769 while (dst0
< dst
&& dst
[-1] != '/')
771 if (prefix_len
&& *prefix_len
> dst
- dst0
)
772 *prefix_len
= dst
- dst0
;
778 int normalize_path_copy(char *dst
, const char *src
)
780 return normalize_path_copy_len(dst
, src
, NULL
);
784 * path = Canonical absolute path
785 * prefixes = string_list containing normalized, absolute paths without
786 * trailing slashes (except for the root directory, which is denoted by "/").
788 * Determines, for each path in prefixes, whether the "prefix"
789 * is an ancestor directory of path. Returns the length of the longest
790 * ancestor directory, excluding any trailing slashes, or -1 if no prefix
791 * is an ancestor. (Note that this means 0 is returned if prefixes is
792 * ["/"].) "/foo" is not considered an ancestor of "/foobar". Directories
793 * are not considered to be their own ancestors. path must be in a
794 * canonical form: empty components, or "." or ".." components are not
797 int longest_ancestor_length(const char *path
, struct string_list
*prefixes
)
801 if (!strcmp(path
, "/"))
804 for (i
= 0; i
< prefixes
->nr
; i
++) {
805 const char *ceil
= prefixes
->items
[i
].string
;
806 int len
= strlen(ceil
);
808 if (len
== 1 && ceil
[0] == '/')
809 len
= 0; /* root matches anything, with length 0 */
810 else if (!strncmp(path
, ceil
, len
) && path
[len
] == '/')
811 ; /* match of length len */
813 continue; /* no match */
822 /* strip arbitrary amount of directory separators at end of path */
823 static inline int chomp_trailing_dir_sep(const char *path
, int len
)
825 while (len
&& is_dir_sep(path
[len
- 1]))
831 * If path ends with suffix (complete path components), returns the
832 * part before suffix (sans trailing directory separators).
833 * Otherwise returns NULL.
835 char *strip_path_suffix(const char *path
, const char *suffix
)
837 int path_len
= strlen(path
), suffix_len
= strlen(suffix
);
843 if (is_dir_sep(path
[path_len
- 1])) {
844 if (!is_dir_sep(suffix
[suffix_len
- 1]))
846 path_len
= chomp_trailing_dir_sep(path
, path_len
);
847 suffix_len
= chomp_trailing_dir_sep(suffix
, suffix_len
);
849 else if (path
[--path_len
] != suffix
[--suffix_len
])
853 if (path_len
&& !is_dir_sep(path
[path_len
- 1]))
855 return xstrndup(path
, chomp_trailing_dir_sep(path
, path_len
));
858 int daemon_avoid_alias(const char *p
)
863 * This resurrects the belts and suspenders paranoia check by HPA
864 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
865 * does not do getcwd() based path canonicalization.
867 * sl becomes true immediately after seeing '/' and continues to
868 * be true as long as dots continue after that without intervening
871 if (!p
|| (*p
!= '/' && *p
!= '~'))
881 else if (ch
== '/') {
883 /* reject //, /./ and /../ */
888 if (0 < ndot
&& ndot
< 3)
889 /* reject /.$ and /..$ */
898 else if (ch
== '/') {
905 static int only_spaces_and_periods(const char *path
, size_t len
, size_t skip
)
913 if (c
!= ' ' && c
!= '.')
919 int is_ntfs_dotgit(const char *name
)
923 for (len
= 0; ; len
++)
924 if (!name
[len
] || name
[len
] == '\\' || is_dir_sep(name
[len
])) {
925 if (only_spaces_and_periods(name
, len
, 4) &&
926 !strncasecmp(name
, ".git", 4))
928 if (only_spaces_and_periods(name
, len
, 5) &&
929 !strncasecmp(name
, "git~1", 5))
931 if (name
[len
] != '\\')
938 char *xdg_config_home(const char *filename
)
940 const char *home
, *config_home
;
943 config_home
= getenv("XDG_CONFIG_HOME");
944 if (config_home
&& *config_home
)
945 return mkpathdup("%s/git/%s", config_home
, filename
);
947 home
= getenv("HOME");
949 return mkpathdup("%s/.config/git/%s", home
, filename
);
953 GIT_PATH_FUNC(git_path_cherry_pick_head
, "CHERRY_PICK_HEAD")
954 GIT_PATH_FUNC(git_path_revert_head
, "REVERT_HEAD")
955 GIT_PATH_FUNC(git_path_squash_msg
, "SQUASH_MSG")
956 GIT_PATH_FUNC(git_path_merge_msg
, "MERGE_MSG")
957 GIT_PATH_FUNC(git_path_merge_rr
, "MERGE_RR")
958 GIT_PATH_FUNC(git_path_merge_mode
, "MERGE_MODE")
959 GIT_PATH_FUNC(git_path_merge_head
, "MERGE_HEAD")
960 GIT_PATH_FUNC(git_path_fetch_head
, "FETCH_HEAD")
961 GIT_PATH_FUNC(git_path_shallow
, "shallow")