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 do_git_path(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 void strbuf_git_path(struct strbuf *sb, const char *fmt, ...)
77 do_git_path(sb, fmt, args);
81 const char *git_path(const char *fmt, ...)
83 struct strbuf *pathname = get_pathname();
86 do_git_path(pathname, fmt, args);
91 char *git_pathdup(const char *fmt, ...)
93 struct strbuf path = STRBUF_INIT;
96 do_git_path(&path, fmt, args);
98 return strbuf_detach(&path, NULL);
101 char *mkpathdup(const char *fmt, ...)
103 struct strbuf sb = STRBUF_INIT;
106 strbuf_vaddf(&sb, fmt, args);
108 strbuf_cleanup_path(&sb);
109 return strbuf_detach(&sb, NULL);
112 const char *mkpath(const char *fmt, ...)
115 struct strbuf *pathname = get_pathname();
117 strbuf_vaddf(pathname, fmt, args);
119 return cleanup_path(pathname->buf);
122 void home_config_paths(char **global, char **xdg, char *file)
124 char *xdg_home = getenv("XDG_CONFIG_HOME");
125 char *home = getenv("HOME");
126 char *to_free = NULL;
133 to_free = mkpathdup("%s/.config", home);
137 *global = mkpathdup("%s/.gitconfig", home);
144 *xdg = mkpathdup("%s/git/%s", xdg_home, file);
150 const char *git_path_submodule(const char *path, const char *fmt, ...)
152 struct strbuf *buf = get_pathname();
156 strbuf_addstr(buf, path);
157 if (buf->len && buf->buf[buf->len - 1] != '/')
158 strbuf_addch(buf, '/');
159 strbuf_addstr(buf, ".git");
161 git_dir = read_gitfile(buf->buf);
164 strbuf_addstr(buf, git_dir);
166 strbuf_addch(buf, '/');
169 strbuf_vaddf(buf, fmt, args);
171 strbuf_cleanup_path(buf);
175 int validate_headref(const char *path)
178 char *buf, buffer[256];
179 unsigned char sha1[20];
183 if (lstat(path, &st) < 0)
186 /* Make sure it is a "refs/.." symlink */
187 if (S_ISLNK(st.st_mode)) {
188 len = readlink(path, buffer, sizeof(buffer)-1);
189 if (len >= 5 && !memcmp("refs/", buffer, 5))
195 * Anything else, just open it and try to see if it is a symbolic ref.
197 fd = open(path, O_RDONLY);
200 len = read_in_full(fd, buffer, sizeof(buffer)-1);
204 * Is it a symbolic ref?
208 if (!memcmp("ref:", buffer, 4)) {
211 while (len && isspace(*buf))
213 if (len >= 5 && !memcmp("refs/", buf, 5))
218 * Is this a detached HEAD?
220 if (!get_sha1_hex(buffer, sha1))
226 static struct passwd *getpw_str(const char *username, size_t len)
229 char *username_z = xmemdupz(username, len);
230 pw = getpwnam(username_z);
236 * Return a string with ~ and ~user expanded via getpw*. If buf != NULL,
237 * then it is a newly allocated string. Returns NULL on getpw failure or
240 char *expand_user_path(const char *path)
242 struct strbuf user_path = STRBUF_INIT;
243 const char *to_copy = path;
247 if (path[0] == '~') {
248 const char *first_slash = strchrnul(path, '/');
249 const char *username = path + 1;
250 size_t username_len = first_slash - username;
251 if (username_len == 0) {
252 const char *home = getenv("HOME");
255 strbuf_addstr(&user_path, home);
257 struct passwd *pw = getpw_str(username, username_len);
260 strbuf_addstr(&user_path, pw->pw_dir);
262 to_copy = first_slash;
264 strbuf_addstr(&user_path, to_copy);
265 return strbuf_detach(&user_path, NULL);
267 strbuf_release(&user_path);
272 * First, one directory to try is determined by the following algorithm.
274 * (0) If "strict" is given, the path is used as given and no DWIM is
276 * (1) "~/path" to mean path under the running user's home directory;
277 * (2) "~user/path" to mean path under named user's home directory;
278 * (3) "relative/path" to mean cwd relative directory; or
279 * (4) "/absolute/path" to mean absolute directory.
281 * Unless "strict" is given, we try access() for existence of "%s.git/.git",
282 * "%s/.git", "%s.git", "%s" in this order. The first one that exists is
285 * Second, we try chdir() to that. Upon failure, we return NULL.
287 * Then, we try if the current directory is a valid git repository.
288 * Upon failure, we return NULL.
290 * If all goes well, we return the directory we used to chdir() (but
291 * before ~user is expanded), avoiding getcwd() resolving symbolic
292 * links. User relative paths are also returned as they are given,
293 * except DWIM suffixing.
295 const char *enter_repo(const char *path, int strict)
297 static char used_path[PATH_MAX];
298 static char validated_path[PATH_MAX];
304 static const char *suffix[] = {
305 "/.git", "", ".git/.git", ".git", NULL,
308 int len = strlen(path);
310 while ((1 < len) && (path[len-1] == '/'))
315 strncpy(used_path, path, len); used_path[len] = 0 ;
316 strcpy(validated_path, used_path);
318 if (used_path[0] == '~') {
319 char *newpath = expand_user_path(used_path);
320 if (!newpath || (PATH_MAX - 10 < strlen(newpath))) {
325 * Copy back into the static buffer. A pity
326 * since newpath was not bounded, but other
327 * branches of the if are limited by PATH_MAX
330 strcpy(used_path, newpath); free(newpath);
332 else if (PATH_MAX - 10 < len)
334 len = strlen(used_path);
335 for (i = 0; suffix[i]; i++) {
337 strcpy(used_path + len, suffix[i]);
338 if (!stat(used_path, &st) &&
339 (S_ISREG(st.st_mode) ||
340 (S_ISDIR(st.st_mode) && is_git_directory(used_path)))) {
341 strcat(validated_path, suffix[i]);
347 gitfile = read_gitfile(used_path) ;
349 strcpy(used_path, gitfile);
350 if (chdir(used_path))
352 path = validated_path;
354 else if (chdir(path))
357 if (access("objects", X_OK) == 0 && access("refs", X_OK) == 0 &&
358 validate_headref("HEAD") == 0) {
360 check_repository_format();
367 static int calc_shared_perm(int mode)
371 if (shared_repository < 0)
372 tweak = -shared_repository;
374 tweak = shared_repository;
376 if (!(mode & S_IWUSR))
379 /* Copy read bits to execute bits */
380 tweak |= (tweak & 0444) >> 2;
381 if (shared_repository < 0)
382 mode = (mode & ~0777) | tweak;
390 int adjust_shared_perm(const char *path)
392 int old_mode, new_mode;
394 if (!shared_repository)
396 if (get_st_mode_bits(path, &old_mode) < 0)
399 new_mode = calc_shared_perm(old_mode);
400 if (S_ISDIR(old_mode)) {
401 /* Copy read bits to execute bits */
402 new_mode |= (new_mode & 0444) >> 2;
403 new_mode |= FORCE_DIR_SET_GID;
406 if (((old_mode ^ new_mode) & ~S_IFMT) &&
407 chmod(path, (new_mode & ~S_IFMT)) < 0)
412 static int have_same_root(const char *path1, const char *path2)
414 int is_abs1, is_abs2;
416 is_abs1 = is_absolute_path(path1);
417 is_abs2 = is_absolute_path(path2);
418 return (is_abs1 && is_abs2 && tolower(path1[0]) == tolower(path2[0])) ||
419 (!is_abs1 && !is_abs2);
423 * Give path as relative to prefix.
425 * The strbuf may or may not be used, so do not assume it contains the
428 const char *relative_path(const char *in, const char *prefix,
431 int in_len = in ? strlen(in) : 0;
432 int prefix_len = prefix ? strlen(prefix) : 0;
439 else if (!prefix_len)
442 if (have_same_root(in, prefix)) {
443 /* bypass dos_drive, for "c:" is identical to "C:" */
444 if (has_dos_drive_prefix(in)) {
452 while (i < prefix_len && j < in_len && prefix[i] == in[j]) {
453 if (is_dir_sep(prefix[i])) {
454 while (is_dir_sep(prefix[i]))
456 while (is_dir_sep(in[j]))
467 /* "prefix" seems like prefix of "in" */
470 * but "/foo" is not a prefix of "/foobar"
471 * (i.e. prefix not end with '/')
473 prefix_off < prefix_len) {
475 /* in="/a/b", prefix="/a/b" */
477 } else if (is_dir_sep(in[j])) {
478 /* in="/a/b/c", prefix="/a/b" */
479 while (is_dir_sep(in[j]))
483 /* in="/a/bbb/c", prefix="/a/b" */
487 /* "in" is short than "prefix" */
489 /* "in" not end with '/' */
491 if (is_dir_sep(prefix[i])) {
492 /* in="/a/b", prefix="/a/b/c/" */
493 while (is_dir_sep(prefix[i]))
501 if (i >= prefix_len) {
509 strbuf_grow(sb, in_len);
511 while (i < prefix_len) {
512 if (is_dir_sep(prefix[i])) {
513 strbuf_addstr(sb, "../");
514 while (is_dir_sep(prefix[i]))
520 if (!is_dir_sep(prefix[prefix_len - 1]))
521 strbuf_addstr(sb, "../");
523 strbuf_addstr(sb, in);
529 * A simpler implementation of relative_path
531 * Get relative path by removing "prefix" from "in". This function
532 * first appears in v1.5.6-1-g044bbbc, and makes git_dir shorter
533 * to increase performance when traversing the path to work_tree.
535 const char *remove_leading_path(const char *in, const char *prefix)
537 static char buf[PATH_MAX + 1];
540 if (!prefix || !prefix[0])
543 if (is_dir_sep(prefix[i])) {
544 if (!is_dir_sep(in[j]))
546 while (is_dir_sep(prefix[i]))
548 while (is_dir_sep(in[j]))
551 } else if (in[j] != prefix[i]) {
558 /* "/foo" is a prefix of "/foo" */
560 /* "/foo" is not a prefix of "/foobar" */
561 !is_dir_sep(prefix[i-1]) && !is_dir_sep(in[j])
564 while (is_dir_sep(in[j]))
574 * It is okay if dst == src, but they should not overlap otherwise.
576 * Performs the following normalizations on src, storing the result in dst:
577 * - Ensures that components are separated by '/' (Windows only)
578 * - Squashes sequences of '/'.
579 * - Removes "." components.
580 * - Removes ".." components, and the components the precede them.
581 * Returns failure (non-zero) if a ".." component appears as first path
582 * component anytime during the normalization. Otherwise, returns success (0).
584 * Note that this function is purely textual. It does not follow symlinks,
585 * verify the existence of the path, or make any system calls.
587 * prefix_len != NULL is for a specific case of prefix_pathspec():
588 * assume that src == dst and src[0..prefix_len-1] is already
589 * normalized, any time "../" eats up to the prefix_len part,
590 * prefix_len is reduced. In the end prefix_len is the remaining
591 * prefix that has not been overridden by user pathspec.
593 int normalize_path_copy_len(char *dst, const char *src, int *prefix_len)
597 if (has_dos_drive_prefix(src)) {
603 if (is_dir_sep(*src)) {
605 while (is_dir_sep(*src))
613 * A path component that begins with . could be
615 * (1) "." and ends -- ignore and terminate.
616 * (2) "./" -- ignore them, eat slash and continue.
617 * (3) ".." and ends -- strip one and terminate.
618 * (4) "../" -- strip one, eat slash and continue.
624 } else if (is_dir_sep(src[1])) {
627 while (is_dir_sep(*src))
630 } else if (src[1] == '.') {
635 } else if (is_dir_sep(src[2])) {
638 while (is_dir_sep(*src))
645 /* copy up to the next '/', and eat all '/' */
646 while ((c = *src++) != '\0' && !is_dir_sep(c))
650 while (is_dir_sep(c))
659 * dst0..dst is prefix portion, and dst[-1] is '/';
662 dst--; /* go to trailing '/' */
665 /* Windows: dst[-1] cannot be backslash anymore */
666 while (dst0 < dst && dst[-1] != '/')
668 if (prefix_len && *prefix_len > dst - dst0)
669 *prefix_len = dst - dst0;
675 int normalize_path_copy(char *dst, const char *src)
677 return normalize_path_copy_len(dst, src, NULL);
681 * path = Canonical absolute path
682 * prefixes = string_list containing normalized, absolute paths without
683 * trailing slashes (except for the root directory, which is denoted by "/").
685 * Determines, for each path in prefixes, whether the "prefix"
686 * is an ancestor directory of path. Returns the length of the longest
687 * ancestor directory, excluding any trailing slashes, or -1 if no prefix
688 * is an ancestor. (Note that this means 0 is returned if prefixes is
689 * ["/"].) "/foo" is not considered an ancestor of "/foobar". Directories
690 * are not considered to be their own ancestors. path must be in a
691 * canonical form: empty components, or "." or ".." components are not
694 int longest_ancestor_length(const char *path, struct string_list *prefixes)
698 if (!strcmp(path, "/"))
701 for (i = 0; i < prefixes->nr; i++) {
702 const char *ceil = prefixes->items[i].string;
703 int len = strlen(ceil);
705 if (len == 1 && ceil[0] == '/')
706 len = 0; /* root matches anything, with length 0 */
707 else if (!strncmp(path, ceil, len) && path[len] == '/')
708 ; /* match of length len */
710 continue; /* no match */
719 /* strip arbitrary amount of directory separators at end of path */
720 static inline int chomp_trailing_dir_sep(const char *path, int len)
722 while (len && is_dir_sep(path[len - 1]))
728 * If path ends with suffix (complete path components), returns the
729 * part before suffix (sans trailing directory separators).
730 * Otherwise returns NULL.
732 char *strip_path_suffix(const char *path, const char *suffix)
734 int path_len = strlen(path), suffix_len = strlen(suffix);
740 if (is_dir_sep(path[path_len - 1])) {
741 if (!is_dir_sep(suffix[suffix_len - 1]))
743 path_len = chomp_trailing_dir_sep(path, path_len);
744 suffix_len = chomp_trailing_dir_sep(suffix, suffix_len);
746 else if (path[--path_len] != suffix[--suffix_len])
750 if (path_len && !is_dir_sep(path[path_len - 1]))
752 return xstrndup(path, chomp_trailing_dir_sep(path, path_len));
755 int daemon_avoid_alias(const char *p)
760 * This resurrects the belts and suspenders paranoia check by HPA
761 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
762 * does not do getcwd() based path canonicalization.
764 * sl becomes true immediately after seeing '/' and continues to
765 * be true as long as dots continue after that without intervening
768 if (!p || (*p != '/' && *p != '~'))
778 else if (ch == '/') {
780 /* reject //, /./ and /../ */
785 if (0 < ndot && ndot < 3)
786 /* reject /.$ and /..$ */
795 else if (ch == '/') {