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 void vsnpath(struct strbuf *buf, const char *fmt, va_list args)
65 const char *git_dir = get_git_dir();
66 strbuf_addstr(buf, git_dir);
67 if (buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
68 strbuf_addch(buf, '/');
69 strbuf_vaddf(buf, fmt, args);
70 strbuf_cleanup_path(buf);
73 char *git_snpath(char *buf, size_t n, const char *fmt, ...)
75 struct strbuf sb = STRBUF_INIT;
78 vsnpath(&sb, fmt, args);
81 strlcpy(buf, bad_path, n);
83 memcpy(buf, sb.buf, sb.len + 1);
88 char *git_pathdup(const char *fmt, ...)
90 struct strbuf path = STRBUF_INIT;
93 vsnpath(&path, fmt, args);
95 return strbuf_detach(&path, NULL);
98 char *mkpathdup(const char *fmt, ...)
100 struct strbuf sb = STRBUF_INIT;
103 strbuf_vaddf(&sb, fmt, args);
105 strbuf_cleanup_path(&sb);
106 return strbuf_detach(&sb, NULL);
109 const char *mkpath(const char *fmt, ...)
112 struct strbuf *pathname = get_pathname();
114 strbuf_vaddf(pathname, fmt, args);
116 return cleanup_path(pathname->buf);
119 const char *git_path(const char *fmt, ...)
121 struct strbuf *pathname = get_pathname();
124 vsnpath(pathname, fmt, args);
126 return pathname->buf;
129 void home_config_paths(char **global, char **xdg, char *file)
131 char *xdg_home = getenv("XDG_CONFIG_HOME");
132 char *home = getenv("HOME");
133 char *to_free = NULL;
140 to_free = mkpathdup("%s/.config", home);
144 *global = mkpathdup("%s/.gitconfig", home);
151 *xdg = mkpathdup("%s/git/%s", xdg_home, file);
157 const char *git_path_submodule(const char *path, const char *fmt, ...)
159 struct strbuf *buf = get_pathname();
163 strbuf_addstr(buf, path);
164 if (buf->len && buf->buf[buf->len - 1] != '/')
165 strbuf_addch(buf, '/');
166 strbuf_addstr(buf, ".git");
168 git_dir = read_gitfile(buf->buf);
171 strbuf_addstr(buf, git_dir);
173 strbuf_addch(buf, '/');
176 strbuf_vaddf(buf, fmt, args);
178 strbuf_cleanup_path(buf);
182 int validate_headref(const char *path)
185 char *buf, buffer[256];
186 unsigned char sha1[20];
190 if (lstat(path, &st) < 0)
193 /* Make sure it is a "refs/.." symlink */
194 if (S_ISLNK(st.st_mode)) {
195 len = readlink(path, buffer, sizeof(buffer)-1);
196 if (len >= 5 && !memcmp("refs/", buffer, 5))
202 * Anything else, just open it and try to see if it is a symbolic ref.
204 fd = open(path, O_RDONLY);
207 len = read_in_full(fd, buffer, sizeof(buffer)-1);
211 * Is it a symbolic ref?
215 if (!memcmp("ref:", buffer, 4)) {
218 while (len && isspace(*buf))
220 if (len >= 5 && !memcmp("refs/", buf, 5))
225 * Is this a detached HEAD?
227 if (!get_sha1_hex(buffer, sha1))
233 static struct passwd *getpw_str(const char *username, size_t len)
236 char *username_z = xmemdupz(username, len);
237 pw = getpwnam(username_z);
243 * Return a string with ~ and ~user expanded via getpw*. If buf != NULL,
244 * then it is a newly allocated string. Returns NULL on getpw failure or
247 char *expand_user_path(const char *path)
249 struct strbuf user_path = STRBUF_INIT;
250 const char *to_copy = path;
254 if (path[0] == '~') {
255 const char *first_slash = strchrnul(path, '/');
256 const char *username = path + 1;
257 size_t username_len = first_slash - username;
258 if (username_len == 0) {
259 const char *home = getenv("HOME");
262 strbuf_addstr(&user_path, home);
264 struct passwd *pw = getpw_str(username, username_len);
267 strbuf_addstr(&user_path, pw->pw_dir);
269 to_copy = first_slash;
271 strbuf_addstr(&user_path, to_copy);
272 return strbuf_detach(&user_path, NULL);
274 strbuf_release(&user_path);
279 * First, one directory to try is determined by the following algorithm.
281 * (0) If "strict" is given, the path is used as given and no DWIM is
283 * (1) "~/path" to mean path under the running user's home directory;
284 * (2) "~user/path" to mean path under named user's home directory;
285 * (3) "relative/path" to mean cwd relative directory; or
286 * (4) "/absolute/path" to mean absolute directory.
288 * Unless "strict" is given, we try access() for existence of "%s.git/.git",
289 * "%s/.git", "%s.git", "%s" in this order. The first one that exists is
292 * Second, we try chdir() to that. Upon failure, we return NULL.
294 * Then, we try if the current directory is a valid git repository.
295 * Upon failure, we return NULL.
297 * If all goes well, we return the directory we used to chdir() (but
298 * before ~user is expanded), avoiding getcwd() resolving symbolic
299 * links. User relative paths are also returned as they are given,
300 * except DWIM suffixing.
302 const char *enter_repo(const char *path, int strict)
304 static char used_path[PATH_MAX];
305 static char validated_path[PATH_MAX];
311 static const char *suffix[] = {
312 "/.git", "", ".git/.git", ".git", NULL,
315 int len = strlen(path);
317 while ((1 < len) && (path[len-1] == '/'))
322 strncpy(used_path, path, len); used_path[len] = 0 ;
323 strcpy(validated_path, used_path);
325 if (used_path[0] == '~') {
326 char *newpath = expand_user_path(used_path);
327 if (!newpath || (PATH_MAX - 10 < strlen(newpath))) {
332 * Copy back into the static buffer. A pity
333 * since newpath was not bounded, but other
334 * branches of the if are limited by PATH_MAX
337 strcpy(used_path, newpath); free(newpath);
339 else if (PATH_MAX - 10 < len)
341 len = strlen(used_path);
342 for (i = 0; suffix[i]; i++) {
344 strcpy(used_path + len, suffix[i]);
345 if (!stat(used_path, &st) &&
346 (S_ISREG(st.st_mode) ||
347 (S_ISDIR(st.st_mode) && is_git_directory(used_path)))) {
348 strcat(validated_path, suffix[i]);
354 gitfile = read_gitfile(used_path) ;
356 strcpy(used_path, gitfile);
357 if (chdir(used_path))
359 path = validated_path;
361 else if (chdir(path))
364 if (access("objects", X_OK) == 0 && access("refs", X_OK) == 0 &&
365 validate_headref("HEAD") == 0) {
367 check_repository_format();
374 static int calc_shared_perm(int mode)
378 if (shared_repository < 0)
379 tweak = -shared_repository;
381 tweak = shared_repository;
383 if (!(mode & S_IWUSR))
386 /* Copy read bits to execute bits */
387 tweak |= (tweak & 0444) >> 2;
388 if (shared_repository < 0)
389 mode = (mode & ~0777) | tweak;
397 int adjust_shared_perm(const char *path)
399 int old_mode, new_mode;
401 if (!shared_repository)
403 if (get_st_mode_bits(path, &old_mode) < 0)
406 new_mode = calc_shared_perm(old_mode);
407 if (S_ISDIR(old_mode)) {
408 /* Copy read bits to execute bits */
409 new_mode |= (new_mode & 0444) >> 2;
410 new_mode |= FORCE_DIR_SET_GID;
413 if (((old_mode ^ new_mode) & ~S_IFMT) &&
414 chmod(path, (new_mode & ~S_IFMT)) < 0)
419 static int have_same_root(const char *path1, const char *path2)
421 int is_abs1, is_abs2;
423 is_abs1 = is_absolute_path(path1);
424 is_abs2 = is_absolute_path(path2);
425 return (is_abs1 && is_abs2 && tolower(path1[0]) == tolower(path2[0])) ||
426 (!is_abs1 && !is_abs2);
430 * Give path as relative to prefix.
432 * The strbuf may or may not be used, so do not assume it contains the
435 const char *relative_path(const char *in, const char *prefix,
438 int in_len = in ? strlen(in) : 0;
439 int prefix_len = prefix ? strlen(prefix) : 0;
446 else if (!prefix_len)
449 if (have_same_root(in, prefix)) {
450 /* bypass dos_drive, for "c:" is identical to "C:" */
451 if (has_dos_drive_prefix(in)) {
459 while (i < prefix_len && j < in_len && prefix[i] == in[j]) {
460 if (is_dir_sep(prefix[i])) {
461 while (is_dir_sep(prefix[i]))
463 while (is_dir_sep(in[j]))
474 /* "prefix" seems like prefix of "in" */
477 * but "/foo" is not a prefix of "/foobar"
478 * (i.e. prefix not end with '/')
480 prefix_off < prefix_len) {
482 /* in="/a/b", prefix="/a/b" */
484 } else if (is_dir_sep(in[j])) {
485 /* in="/a/b/c", prefix="/a/b" */
486 while (is_dir_sep(in[j]))
490 /* in="/a/bbb/c", prefix="/a/b" */
494 /* "in" is short than "prefix" */
496 /* "in" not end with '/' */
498 if (is_dir_sep(prefix[i])) {
499 /* in="/a/b", prefix="/a/b/c/" */
500 while (is_dir_sep(prefix[i]))
508 if (i >= prefix_len) {
516 strbuf_grow(sb, in_len);
518 while (i < prefix_len) {
519 if (is_dir_sep(prefix[i])) {
520 strbuf_addstr(sb, "../");
521 while (is_dir_sep(prefix[i]))
527 if (!is_dir_sep(prefix[prefix_len - 1]))
528 strbuf_addstr(sb, "../");
530 strbuf_addstr(sb, in);
536 * A simpler implementation of relative_path
538 * Get relative path by removing "prefix" from "in". This function
539 * first appears in v1.5.6-1-g044bbbc, and makes git_dir shorter
540 * to increase performance when traversing the path to work_tree.
542 const char *remove_leading_path(const char *in, const char *prefix)
544 static char buf[PATH_MAX + 1];
547 if (!prefix || !prefix[0])
550 if (is_dir_sep(prefix[i])) {
551 if (!is_dir_sep(in[j]))
553 while (is_dir_sep(prefix[i]))
555 while (is_dir_sep(in[j]))
558 } else if (in[j] != prefix[i]) {
565 /* "/foo" is a prefix of "/foo" */
567 /* "/foo" is not a prefix of "/foobar" */
568 !is_dir_sep(prefix[i-1]) && !is_dir_sep(in[j])
571 while (is_dir_sep(in[j]))
581 * It is okay if dst == src, but they should not overlap otherwise.
583 * Performs the following normalizations on src, storing the result in dst:
584 * - Ensures that components are separated by '/' (Windows only)
585 * - Squashes sequences of '/'.
586 * - Removes "." components.
587 * - Removes ".." components, and the components the precede them.
588 * Returns failure (non-zero) if a ".." component appears as first path
589 * component anytime during the normalization. Otherwise, returns success (0).
591 * Note that this function is purely textual. It does not follow symlinks,
592 * verify the existence of the path, or make any system calls.
594 * prefix_len != NULL is for a specific case of prefix_pathspec():
595 * assume that src == dst and src[0..prefix_len-1] is already
596 * normalized, any time "../" eats up to the prefix_len part,
597 * prefix_len is reduced. In the end prefix_len is the remaining
598 * prefix that has not been overridden by user pathspec.
600 int normalize_path_copy_len(char *dst, const char *src, int *prefix_len)
604 if (has_dos_drive_prefix(src)) {
610 if (is_dir_sep(*src)) {
612 while (is_dir_sep(*src))
620 * A path component that begins with . could be
622 * (1) "." and ends -- ignore and terminate.
623 * (2) "./" -- ignore them, eat slash and continue.
624 * (3) ".." and ends -- strip one and terminate.
625 * (4) "../" -- strip one, eat slash and continue.
631 } else if (is_dir_sep(src[1])) {
634 while (is_dir_sep(*src))
637 } else if (src[1] == '.') {
642 } else if (is_dir_sep(src[2])) {
645 while (is_dir_sep(*src))
652 /* copy up to the next '/', and eat all '/' */
653 while ((c = *src++) != '\0' && !is_dir_sep(c))
657 while (is_dir_sep(c))
666 * dst0..dst is prefix portion, and dst[-1] is '/';
669 dst--; /* go to trailing '/' */
672 /* Windows: dst[-1] cannot be backslash anymore */
673 while (dst0 < dst && dst[-1] != '/')
675 if (prefix_len && *prefix_len > dst - dst0)
676 *prefix_len = dst - dst0;
682 int normalize_path_copy(char *dst, const char *src)
684 return normalize_path_copy_len(dst, src, NULL);
688 * path = Canonical absolute path
689 * prefixes = string_list containing normalized, absolute paths without
690 * trailing slashes (except for the root directory, which is denoted by "/").
692 * Determines, for each path in prefixes, whether the "prefix"
693 * is an ancestor directory of path. Returns the length of the longest
694 * ancestor directory, excluding any trailing slashes, or -1 if no prefix
695 * is an ancestor. (Note that this means 0 is returned if prefixes is
696 * ["/"].) "/foo" is not considered an ancestor of "/foobar". Directories
697 * are not considered to be their own ancestors. path must be in a
698 * canonical form: empty components, or "." or ".." components are not
701 int longest_ancestor_length(const char *path, struct string_list *prefixes)
705 if (!strcmp(path, "/"))
708 for (i = 0; i < prefixes->nr; i++) {
709 const char *ceil = prefixes->items[i].string;
710 int len = strlen(ceil);
712 if (len == 1 && ceil[0] == '/')
713 len = 0; /* root matches anything, with length 0 */
714 else if (!strncmp(path, ceil, len) && path[len] == '/')
715 ; /* match of length len */
717 continue; /* no match */
726 /* strip arbitrary amount of directory separators at end of path */
727 static inline int chomp_trailing_dir_sep(const char *path, int len)
729 while (len && is_dir_sep(path[len - 1]))
735 * If path ends with suffix (complete path components), returns the
736 * part before suffix (sans trailing directory separators).
737 * Otherwise returns NULL.
739 char *strip_path_suffix(const char *path, const char *suffix)
741 int path_len = strlen(path), suffix_len = strlen(suffix);
747 if (is_dir_sep(path[path_len - 1])) {
748 if (!is_dir_sep(suffix[suffix_len - 1]))
750 path_len = chomp_trailing_dir_sep(path, path_len);
751 suffix_len = chomp_trailing_dir_sep(suffix, suffix_len);
753 else if (path[--path_len] != suffix[--suffix_len])
757 if (path_len && !is_dir_sep(path[path_len - 1]))
759 return xstrndup(path, chomp_trailing_dir_sep(path, path_len));
762 int daemon_avoid_alias(const char *p)
767 * This resurrects the belts and suspenders paranoia check by HPA
768 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
769 * does not do getcwd() based path canonicalization.
771 * sl becomes true immediately after seeing '/' and continues to
772 * be true as long as dots continue after that without intervening
775 if (!p || (*p != '/' && *p != '~'))
785 else if (ch == '/') {
787 /* reject //, /./ and /../ */
792 if (0 < ndot && ndot < 3)
793 /* reject /.$ and /..$ */
802 else if (ch == '/') {