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)
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;
118 if (is_dir && dir_prefix(base, path)) {
119 replace_dir(buf, git_dir_len, get_git_common_dir());
122 if (!is_dir && !strcmp(base, path)) {
123 replace_dir(buf, git_dir_len, get_git_common_dir());
129 void report_linked_checkout_garbage(void)
131 struct strbuf sb = STRBUF_INIT;
135 if (!git_common_dir_env)
137 strbuf_addf(&sb, "%s/", get_git_dir());
139 for (p = common_list; *p; p++) {
140 const char *path = *p;
143 strbuf_setlen(&sb, len);
144 strbuf_addstr(&sb, path);
145 if (file_exists(sb.buf))
146 report_garbage("unused in linked checkout", sb.buf);
151 static void adjust_git_path(struct strbuf *buf, int git_dir_len)
153 const char *base = buf->buf + git_dir_len;
154 if (git_graft_env && is_dir_file(base, "info", "grafts"))
155 strbuf_splice(buf, 0, buf->len,
156 get_graft_file(), strlen(get_graft_file()));
157 else if (git_index_env && !strcmp(base, "index"))
158 strbuf_splice(buf, 0, buf->len,
159 get_index_file(), strlen(get_index_file()));
160 else if (git_db_env && dir_prefix(base, "objects"))
161 replace_dir(buf, git_dir_len + 7, get_object_directory());
162 else if (git_common_dir_env)
163 update_common_dir(buf, git_dir_len);
166 static void do_git_path(struct strbuf *buf, const char *fmt, va_list args)
169 strbuf_addstr(buf, get_git_dir());
170 if (buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
171 strbuf_addch(buf, '/');
172 gitdir_len = buf->len;
173 strbuf_vaddf(buf, fmt, args);
174 adjust_git_path(buf, gitdir_len);
175 strbuf_cleanup_path(buf);
178 char *git_path_buf(struct strbuf *buf, const char *fmt, ...)
183 do_git_path(buf, fmt, args);
188 void strbuf_git_path(struct strbuf *sb, const char *fmt, ...)
192 do_git_path(sb, fmt, args);
196 const char *git_path(const char *fmt, ...)
198 struct strbuf *pathname = get_pathname();
201 do_git_path(pathname, fmt, args);
203 return pathname->buf;
206 char *git_pathdup(const char *fmt, ...)
208 struct strbuf path = STRBUF_INIT;
211 do_git_path(&path, fmt, args);
213 return strbuf_detach(&path, NULL);
216 char *mkpathdup(const char *fmt, ...)
218 struct strbuf sb = STRBUF_INIT;
221 strbuf_vaddf(&sb, fmt, args);
223 strbuf_cleanup_path(&sb);
224 return strbuf_detach(&sb, NULL);
227 const char *mkpath(const char *fmt, ...)
230 struct strbuf *pathname = get_pathname();
232 strbuf_vaddf(pathname, fmt, args);
234 return cleanup_path(pathname->buf);
237 static void do_submodule_path(struct strbuf *buf, const char *path,
238 const char *fmt, va_list args)
242 strbuf_addstr(buf, path);
243 if (buf->len && buf->buf[buf->len - 1] != '/')
244 strbuf_addch(buf, '/');
245 strbuf_addstr(buf, ".git");
247 git_dir = read_gitfile(buf->buf);
250 strbuf_addstr(buf, git_dir);
252 strbuf_addch(buf, '/');
254 strbuf_vaddf(buf, fmt, args);
255 strbuf_cleanup_path(buf);
258 char *git_pathdup_submodule(const char *path, const char *fmt, ...)
261 struct strbuf buf = STRBUF_INIT;
263 do_submodule_path(&buf, path, fmt, args);
265 return strbuf_detach(&buf, NULL);
268 void strbuf_git_path_submodule(struct strbuf *buf, const char *path,
269 const char *fmt, ...)
273 do_submodule_path(buf, path, fmt, args);
277 int validate_headref(const char *path)
280 char *buf, buffer[256];
281 unsigned char sha1[20];
285 if (lstat(path, &st) < 0)
288 /* Make sure it is a "refs/.." symlink */
289 if (S_ISLNK(st.st_mode)) {
290 len = readlink(path, buffer, sizeof(buffer)-1);
291 if (len >= 5 && !memcmp("refs/", buffer, 5))
297 * Anything else, just open it and try to see if it is a symbolic ref.
299 fd = open(path, O_RDONLY);
302 len = read_in_full(fd, buffer, sizeof(buffer)-1);
306 * Is it a symbolic ref?
310 if (!memcmp("ref:", buffer, 4)) {
313 while (len && isspace(*buf))
315 if (len >= 5 && !memcmp("refs/", buf, 5))
320 * Is this a detached HEAD?
322 if (!get_sha1_hex(buffer, sha1))
328 static struct passwd *getpw_str(const char *username, size_t len)
331 char *username_z = xmemdupz(username, len);
332 pw = getpwnam(username_z);
338 * Return a string with ~ and ~user expanded via getpw*. If buf != NULL,
339 * then it is a newly allocated string. Returns NULL on getpw failure or
342 char *expand_user_path(const char *path)
344 struct strbuf user_path = STRBUF_INIT;
345 const char *to_copy = path;
349 if (path[0] == '~') {
350 const char *first_slash = strchrnul(path, '/');
351 const char *username = path + 1;
352 size_t username_len = first_slash - username;
353 if (username_len == 0) {
354 const char *home = getenv("HOME");
357 strbuf_addstr(&user_path, home);
359 struct passwd *pw = getpw_str(username, username_len);
362 strbuf_addstr(&user_path, pw->pw_dir);
364 to_copy = first_slash;
366 strbuf_addstr(&user_path, to_copy);
367 return strbuf_detach(&user_path, NULL);
369 strbuf_release(&user_path);
374 * First, one directory to try is determined by the following algorithm.
376 * (0) If "strict" is given, the path is used as given and no DWIM is
378 * (1) "~/path" to mean path under the running user's home directory;
379 * (2) "~user/path" to mean path under named user's home directory;
380 * (3) "relative/path" to mean cwd relative directory; or
381 * (4) "/absolute/path" to mean absolute directory.
383 * Unless "strict" is given, we check "%s/.git", "%s", "%s.git/.git", "%s.git"
384 * in this order. We select the first one that is a valid git repository, and
385 * chdir() to it. If none match, or we fail to chdir, we return NULL.
387 * If all goes well, we return the directory we used to chdir() (but
388 * before ~user is expanded), avoiding getcwd() resolving symbolic
389 * links. User relative paths are also returned as they are given,
390 * except DWIM suffixing.
392 const char *enter_repo(const char *path, int strict)
394 static char used_path[PATH_MAX];
395 static char validated_path[PATH_MAX];
401 static const char *suffix[] = {
402 "/.git", "", ".git/.git", ".git", NULL,
405 int len = strlen(path);
407 while ((1 < len) && (path[len-1] == '/'))
412 strncpy(used_path, path, len); used_path[len] = 0 ;
413 strcpy(validated_path, used_path);
415 if (used_path[0] == '~') {
416 char *newpath = expand_user_path(used_path);
417 if (!newpath || (PATH_MAX - 10 < strlen(newpath))) {
422 * Copy back into the static buffer. A pity
423 * since newpath was not bounded, but other
424 * branches of the if are limited by PATH_MAX
427 strcpy(used_path, newpath); free(newpath);
429 else if (PATH_MAX - 10 < len)
431 len = strlen(used_path);
432 for (i = 0; suffix[i]; i++) {
434 strcpy(used_path + len, suffix[i]);
435 if (!stat(used_path, &st) &&
436 (S_ISREG(st.st_mode) ||
437 (S_ISDIR(st.st_mode) && is_git_directory(used_path)))) {
438 strcat(validated_path, suffix[i]);
444 gitfile = read_gitfile(used_path) ;
446 strcpy(used_path, gitfile);
447 if (chdir(used_path))
449 path = validated_path;
451 else if (chdir(path))
454 if (access("objects", X_OK) == 0 && access("refs", X_OK) == 0 &&
455 validate_headref("HEAD") == 0) {
457 check_repository_format();
464 static int calc_shared_perm(int mode)
468 if (shared_repository < 0)
469 tweak = -shared_repository;
471 tweak = shared_repository;
473 if (!(mode & S_IWUSR))
476 /* Copy read bits to execute bits */
477 tweak |= (tweak & 0444) >> 2;
478 if (shared_repository < 0)
479 mode = (mode & ~0777) | tweak;
487 int adjust_shared_perm(const char *path)
489 int old_mode, new_mode;
491 if (!shared_repository)
493 if (get_st_mode_bits(path, &old_mode) < 0)
496 new_mode = calc_shared_perm(old_mode);
497 if (S_ISDIR(old_mode)) {
498 /* Copy read bits to execute bits */
499 new_mode |= (new_mode & 0444) >> 2;
500 new_mode |= FORCE_DIR_SET_GID;
503 if (((old_mode ^ new_mode) & ~S_IFMT) &&
504 chmod(path, (new_mode & ~S_IFMT)) < 0)
509 static int have_same_root(const char *path1, const char *path2)
511 int is_abs1, is_abs2;
513 is_abs1 = is_absolute_path(path1);
514 is_abs2 = is_absolute_path(path2);
515 return (is_abs1 && is_abs2 && tolower(path1[0]) == tolower(path2[0])) ||
516 (!is_abs1 && !is_abs2);
520 * Give path as relative to prefix.
522 * The strbuf may or may not be used, so do not assume it contains the
525 const char *relative_path(const char *in, const char *prefix,
528 int in_len = in ? strlen(in) : 0;
529 int prefix_len = prefix ? strlen(prefix) : 0;
536 else if (!prefix_len)
539 if (have_same_root(in, prefix)) {
540 /* bypass dos_drive, for "c:" is identical to "C:" */
541 if (has_dos_drive_prefix(in)) {
549 while (i < prefix_len && j < in_len && prefix[i] == in[j]) {
550 if (is_dir_sep(prefix[i])) {
551 while (is_dir_sep(prefix[i]))
553 while (is_dir_sep(in[j]))
564 /* "prefix" seems like prefix of "in" */
567 * but "/foo" is not a prefix of "/foobar"
568 * (i.e. prefix not end with '/')
570 prefix_off < prefix_len) {
572 /* in="/a/b", prefix="/a/b" */
574 } else if (is_dir_sep(in[j])) {
575 /* in="/a/b/c", prefix="/a/b" */
576 while (is_dir_sep(in[j]))
580 /* in="/a/bbb/c", prefix="/a/b" */
584 /* "in" is short than "prefix" */
586 /* "in" not end with '/' */
588 if (is_dir_sep(prefix[i])) {
589 /* in="/a/b", prefix="/a/b/c/" */
590 while (is_dir_sep(prefix[i]))
598 if (i >= prefix_len) {
606 strbuf_grow(sb, in_len);
608 while (i < prefix_len) {
609 if (is_dir_sep(prefix[i])) {
610 strbuf_addstr(sb, "../");
611 while (is_dir_sep(prefix[i]))
617 if (!is_dir_sep(prefix[prefix_len - 1]))
618 strbuf_addstr(sb, "../");
620 strbuf_addstr(sb, in);
626 * A simpler implementation of relative_path
628 * Get relative path by removing "prefix" from "in". This function
629 * first appears in v1.5.6-1-g044bbbc, and makes git_dir shorter
630 * to increase performance when traversing the path to work_tree.
632 const char *remove_leading_path(const char *in, const char *prefix)
634 static char buf[PATH_MAX + 1];
637 if (!prefix || !prefix[0])
640 if (is_dir_sep(prefix[i])) {
641 if (!is_dir_sep(in[j]))
643 while (is_dir_sep(prefix[i]))
645 while (is_dir_sep(in[j]))
648 } else if (in[j] != prefix[i]) {
655 /* "/foo" is a prefix of "/foo" */
657 /* "/foo" is not a prefix of "/foobar" */
658 !is_dir_sep(prefix[i-1]) && !is_dir_sep(in[j])
661 while (is_dir_sep(in[j]))
671 * It is okay if dst == src, but they should not overlap otherwise.
673 * Performs the following normalizations on src, storing the result in dst:
674 * - Ensures that components are separated by '/' (Windows only)
675 * - Squashes sequences of '/'.
676 * - Removes "." components.
677 * - Removes ".." components, and the components the precede them.
678 * Returns failure (non-zero) if a ".." component appears as first path
679 * component anytime during the normalization. Otherwise, returns success (0).
681 * Note that this function is purely textual. It does not follow symlinks,
682 * verify the existence of the path, or make any system calls.
684 * prefix_len != NULL is for a specific case of prefix_pathspec():
685 * assume that src == dst and src[0..prefix_len-1] is already
686 * normalized, any time "../" eats up to the prefix_len part,
687 * prefix_len is reduced. In the end prefix_len is the remaining
688 * prefix that has not been overridden by user pathspec.
690 int normalize_path_copy_len(char *dst, const char *src, int *prefix_len)
694 if (has_dos_drive_prefix(src)) {
700 if (is_dir_sep(*src)) {
702 while (is_dir_sep(*src))
710 * A path component that begins with . could be
712 * (1) "." and ends -- ignore and terminate.
713 * (2) "./" -- ignore them, eat slash and continue.
714 * (3) ".." and ends -- strip one and terminate.
715 * (4) "../" -- strip one, eat slash and continue.
721 } else if (is_dir_sep(src[1])) {
724 while (is_dir_sep(*src))
727 } else if (src[1] == '.') {
732 } else if (is_dir_sep(src[2])) {
735 while (is_dir_sep(*src))
742 /* copy up to the next '/', and eat all '/' */
743 while ((c = *src++) != '\0' && !is_dir_sep(c))
747 while (is_dir_sep(c))
756 * dst0..dst is prefix portion, and dst[-1] is '/';
759 dst--; /* go to trailing '/' */
762 /* Windows: dst[-1] cannot be backslash anymore */
763 while (dst0 < dst && dst[-1] != '/')
765 if (prefix_len && *prefix_len > dst - dst0)
766 *prefix_len = dst - dst0;
772 int normalize_path_copy(char *dst, const char *src)
774 return normalize_path_copy_len(dst, src, NULL);
778 * path = Canonical absolute path
779 * prefixes = string_list containing normalized, absolute paths without
780 * trailing slashes (except for the root directory, which is denoted by "/").
782 * Determines, for each path in prefixes, whether the "prefix"
783 * is an ancestor directory of path. Returns the length of the longest
784 * ancestor directory, excluding any trailing slashes, or -1 if no prefix
785 * is an ancestor. (Note that this means 0 is returned if prefixes is
786 * ["/"].) "/foo" is not considered an ancestor of "/foobar". Directories
787 * are not considered to be their own ancestors. path must be in a
788 * canonical form: empty components, or "." or ".." components are not
791 int longest_ancestor_length(const char *path, struct string_list *prefixes)
795 if (!strcmp(path, "/"))
798 for (i = 0; i < prefixes->nr; i++) {
799 const char *ceil = prefixes->items[i].string;
800 int len = strlen(ceil);
802 if (len == 1 && ceil[0] == '/')
803 len = 0; /* root matches anything, with length 0 */
804 else if (!strncmp(path, ceil, len) && path[len] == '/')
805 ; /* match of length len */
807 continue; /* no match */
816 /* strip arbitrary amount of directory separators at end of path */
817 static inline int chomp_trailing_dir_sep(const char *path, int len)
819 while (len && is_dir_sep(path[len - 1]))
825 * If path ends with suffix (complete path components), returns the
826 * part before suffix (sans trailing directory separators).
827 * Otherwise returns NULL.
829 char *strip_path_suffix(const char *path, const char *suffix)
831 int path_len = strlen(path), suffix_len = strlen(suffix);
837 if (is_dir_sep(path[path_len - 1])) {
838 if (!is_dir_sep(suffix[suffix_len - 1]))
840 path_len = chomp_trailing_dir_sep(path, path_len);
841 suffix_len = chomp_trailing_dir_sep(suffix, suffix_len);
843 else if (path[--path_len] != suffix[--suffix_len])
847 if (path_len && !is_dir_sep(path[path_len - 1]))
849 return xstrndup(path, chomp_trailing_dir_sep(path, path_len));
852 int daemon_avoid_alias(const char *p)
857 * This resurrects the belts and suspenders paranoia check by HPA
858 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
859 * does not do getcwd() based path canonicalization.
861 * sl becomes true immediately after seeing '/' and continues to
862 * be true as long as dots continue after that without intervening
865 if (!p || (*p != '/' && *p != '~'))
875 else if (ch == '/') {
877 /* reject //, /./ and /../ */
882 if (0 < ndot && ndot < 3)
883 /* reject /.$ and /..$ */
892 else if (ch == '/') {
899 static int only_spaces_and_periods(const char *path, size_t len, size_t skip)
907 if (c != ' ' && c != '.')
913 int is_ntfs_dotgit(const char *name)
917 for (len = 0; ; len++)
918 if (!name[len] || name[len] == '\\' || is_dir_sep(name[len])) {
919 if (only_spaces_and_periods(name, len, 4) &&
920 !strncasecmp(name, ".git", 4))
922 if (only_spaces_and_periods(name, len, 5) &&
923 !strncasecmp(name, "git~1", 5))
925 if (name[len] != '\\')
932 char *xdg_config_home(const char *filename)
934 const char *home, *config_home;
937 config_home = getenv("XDG_CONFIG_HOME");
938 if (config_home && *config_home)
939 return mkpathdup("%s/git/%s", config_home, filename);
941 home = getenv("HOME");
943 return mkpathdup("%s/.config/git/%s", home, filename);
947 GIT_PATH_FUNC(git_path_cherry_pick_head, "CHERRY_PICK_HEAD")
948 GIT_PATH_FUNC(git_path_revert_head, "REVERT_HEAD")
949 GIT_PATH_FUNC(git_path_squash_msg, "SQUASH_MSG")
950 GIT_PATH_FUNC(git_path_merge_msg, "MERGE_MSG")
951 GIT_PATH_FUNC(git_path_merge_rr, "MERGE_RR")
952 GIT_PATH_FUNC(git_path_merge_mode, "MERGE_MODE")
953 GIT_PATH_FUNC(git_path_merge_head, "MERGE_HEAD")
954 GIT_PATH_FUNC(git_path_fetch_head, "FETCH_HEAD")
955 GIT_PATH_FUNC(git_path_shallow, "shallow")