2 * Utilities for paths and pathnames
5 #include "repository.h"
7 #include "string-list.h"
10 #include "submodule-config.h"
12 static int get_st_mode_bits(const char *path, int *mode)
15 if (lstat(path, &st) < 0)
21 static char bad_path[] = "/bad-path/";
23 static struct strbuf *get_pathname(void)
25 static struct strbuf pathname_array[4] = {
26 STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
29 struct strbuf *sb = &pathname_array[index];
30 index = (index + 1) % ARRAY_SIZE(pathname_array);
35 static char *cleanup_path(char *path)
38 if (!memcmp(path, "./", 2)) {
46 static void strbuf_cleanup_path(struct strbuf *sb)
48 char *path = cleanup_path(sb->buf);
50 strbuf_remove(sb, 0, path - sb->buf);
53 char *mksnpath(char *buf, size_t n, const char *fmt, ...)
59 len = vsnprintf(buf, n, fmt, args);
62 strlcpy(buf, bad_path, n);
65 return cleanup_path(buf);
68 static int dir_prefix(const char *buf, const char *dir)
70 int len = strlen(dir);
71 return !strncmp(buf, dir, len) &&
72 (is_dir_sep(buf[len]) || buf[len] == '\0');
75 /* $buf =~ m|$dir/+$file| but without regex */
76 static int is_dir_file(const char *buf, const char *dir, const char *file)
78 int len = strlen(dir);
79 if (strncmp(buf, dir, len) || !is_dir_sep(buf[len]))
81 while (is_dir_sep(buf[len]))
83 return !strcmp(buf + len, file);
86 static void replace_dir(struct strbuf *buf, int len, const char *newdir)
88 int newlen = strlen(newdir);
89 int need_sep = (buf->buf[len] && !is_dir_sep(buf->buf[len])) &&
90 !is_dir_sep(newdir[newlen - 1]);
92 len--; /* keep one char, to be replaced with '/' */
93 strbuf_splice(buf, 0, len, newdir, newlen);
95 buf->buf[newlen] = '/';
99 /* Not considered garbage for report_linked_checkout_garbage */
100 unsigned ignore_garbage:1;
102 /* Not common even though its parent is */
107 static struct common_dir common_list[] = {
108 { 0, 1, 0, "branches" },
109 { 0, 1, 0, "hooks" },
111 { 0, 0, 1, "info/sparse-checkout" },
113 { 1, 1, 1, "logs/HEAD" },
114 { 0, 1, 1, "logs/refs/bisect" },
115 { 0, 1, 0, "lost-found" },
116 { 0, 1, 0, "objects" },
118 { 0, 1, 1, "refs/bisect" },
119 { 0, 1, 0, "remotes" },
120 { 0, 1, 0, "worktrees" },
121 { 0, 1, 0, "rr-cache" },
123 { 0, 0, 0, "config" },
124 { 1, 0, 0, "gc.pid" },
125 { 0, 0, 0, "packed-refs" },
126 { 0, 0, 0, "shallow" },
131 * A compressed trie. A trie node consists of zero or more characters that
132 * are common to all elements with this prefix, optionally followed by some
133 * children. If value is not NULL, the trie node is a terminal node.
135 * For example, consider the following set of strings:
141 * The trie would look like:
142 * root: len = 0, children a and d non-NULL, value = NULL.
143 * a: len = 2, contents = bc, value = (data for "abc")
144 * d: len = 2, contents = ef, children i non-NULL, value = (data for "def")
145 * i: len = 3, contents = nit, children e and i non-NULL, value = NULL
146 * e: len = 0, children all NULL, value = (data for "definite")
147 * i: len = 2, contents = on, children all NULL,
148 * value = (data for "definition")
151 struct trie *children[256];
157 static struct trie *make_trie_node(const char *key, void *value)
159 struct trie *new_node = xcalloc(1, sizeof(*new_node));
160 new_node->len = strlen(key);
162 new_node->contents = xmalloc(new_node->len);
163 memcpy(new_node->contents, key, new_node->len);
165 new_node->value = value;
170 * Add a key/value pair to a trie. The key is assumed to be \0-terminated.
171 * If there was an existing value for this key, return it.
173 static void *add_to_trie(struct trie *root, const char *key, void *value)
180 /* we have reached the end of the key */
186 for (i = 0; i < root->len; i++) {
187 if (root->contents[i] == key[i])
191 * Split this node: child will contain this node's
194 child = malloc(sizeof(*child));
195 memcpy(child->children, root->children, sizeof(root->children));
197 child->len = root->len - i - 1;
199 child->contents = xstrndup(root->contents + i + 1,
202 child->value = root->value;
206 memset(root->children, 0, sizeof(root->children));
207 root->children[(unsigned char)root->contents[i]] = child;
209 /* This is the newly-added child. */
210 root->children[(unsigned char)key[i]] =
211 make_trie_node(key + i + 1, value);
215 /* We have matched the entire compressed section */
217 child = root->children[(unsigned char)key[root->len]];
219 return add_to_trie(child, key + root->len + 1, value);
221 child = make_trie_node(key + root->len + 1, value);
222 root->children[(unsigned char)key[root->len]] = child;
232 typedef int (*match_fn)(const char *unmatched, void *data, void *baton);
235 * Search a trie for some key. Find the longest /-or-\0-terminated
236 * prefix of the key for which the trie contains a value. Call fn
237 * with the unmatched portion of the key and the found value, and
238 * return its return value. If there is no such prefix, return -1.
240 * The key is partially normalized: consecutive slashes are skipped.
242 * For example, consider the trie containing only [refs,
243 * refs/worktree] (both with values).
245 * | key | unmatched | val from node | return value |
246 * |-----------------|------------|---------------|--------------|
247 * | a | not called | n/a | -1 |
248 * | refs | \0 | refs | as per fn |
249 * | refs/ | / | refs | as per fn |
250 * | refs/w | /w | refs | as per fn |
251 * | refs/worktree | \0 | refs/worktree | as per fn |
252 * | refs/worktree/ | / | refs/worktree | as per fn |
253 * | refs/worktree/a | /a | refs/worktree | as per fn |
254 * |-----------------|------------|---------------|--------------|
257 static int trie_find(struct trie *root, const char *key, match_fn fn,
265 /* we have reached the end of the key */
266 if (root->value && !root->len)
267 return fn(key, root->value, baton);
272 for (i = 0; i < root->len; i++) {
273 /* Partial path normalization: skip consecutive slashes. */
274 if (key[i] == '/' && key[i+1] == '/') {
278 if (root->contents[i] != key[i])
282 /* Matched the entire compressed section */
286 return fn(key, root->value, baton);
288 /* Partial path normalization: skip consecutive slashes */
289 while (key[0] == '/' && key[1] == '/')
292 child = root->children[(unsigned char)*key];
294 result = trie_find(child, key + 1, fn, baton);
298 if (result >= 0 || (*key != '/' && *key != 0))
301 return fn(key, root->value, baton);
306 static struct trie common_trie;
307 static int common_trie_done_setup;
309 static void init_common_trie(void)
311 struct common_dir *p;
313 if (common_trie_done_setup)
316 for (p = common_list; p->dirname; p++)
317 add_to_trie(&common_trie, p->dirname, p);
319 common_trie_done_setup = 1;
323 * Helper function for update_common_dir: returns 1 if the dir
326 static int check_common(const char *unmatched, void *value, void *baton)
328 struct common_dir *dir = value;
333 if (dir->is_dir && (unmatched[0] == 0 || unmatched[0] == '/'))
334 return !dir->exclude;
336 if (!dir->is_dir && unmatched[0] == 0)
337 return !dir->exclude;
342 static void update_common_dir(struct strbuf *buf, int git_dir_len,
343 const char *common_dir)
345 char *base = buf->buf + git_dir_len;
348 common_dir = get_git_common_dir();
349 if (trie_find(&common_trie, base, check_common, NULL) > 0)
350 replace_dir(buf, git_dir_len, common_dir);
353 void report_linked_checkout_garbage(void)
355 struct strbuf sb = STRBUF_INIT;
356 const struct common_dir *p;
359 if (!the_repository->different_commondir)
361 strbuf_addf(&sb, "%s/", get_git_dir());
363 for (p = common_list; p->dirname; p++) {
364 const char *path = p->dirname;
365 if (p->ignore_garbage)
367 strbuf_setlen(&sb, len);
368 strbuf_addstr(&sb, path);
369 if (file_exists(sb.buf))
370 report_garbage(PACKDIR_FILE_GARBAGE, sb.buf);
375 static void adjust_git_path(struct strbuf *buf, int git_dir_len)
377 const char *base = buf->buf + git_dir_len;
378 if (is_dir_file(base, "info", "grafts"))
379 strbuf_splice(buf, 0, buf->len,
380 get_graft_file(), strlen(get_graft_file()));
381 else if (!strcmp(base, "index"))
382 strbuf_splice(buf, 0, buf->len,
383 get_index_file(), strlen(get_index_file()));
384 else if (dir_prefix(base, "objects"))
385 replace_dir(buf, git_dir_len + 7, get_object_directory());
386 else if (git_hooks_path && dir_prefix(base, "hooks"))
387 replace_dir(buf, git_dir_len + 5, git_hooks_path);
388 else if (the_repository->different_commondir)
389 update_common_dir(buf, git_dir_len, NULL);
392 static void do_git_path(const struct worktree *wt, struct strbuf *buf,
393 const char *fmt, va_list args)
396 strbuf_addstr(buf, get_worktree_git_dir(wt));
397 if (buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
398 strbuf_addch(buf, '/');
399 gitdir_len = buf->len;
400 strbuf_vaddf(buf, fmt, args);
401 adjust_git_path(buf, gitdir_len);
402 strbuf_cleanup_path(buf);
405 char *git_path_buf(struct strbuf *buf, const char *fmt, ...)
410 do_git_path(NULL, buf, fmt, args);
415 void strbuf_git_path(struct strbuf *sb, const char *fmt, ...)
419 do_git_path(NULL, sb, fmt, args);
423 const char *git_path(const char *fmt, ...)
425 struct strbuf *pathname = get_pathname();
428 do_git_path(NULL, pathname, fmt, args);
430 return pathname->buf;
433 char *git_pathdup(const char *fmt, ...)
435 struct strbuf path = STRBUF_INIT;
438 do_git_path(NULL, &path, fmt, args);
440 return strbuf_detach(&path, NULL);
443 char *mkpathdup(const char *fmt, ...)
445 struct strbuf sb = STRBUF_INIT;
448 strbuf_vaddf(&sb, fmt, args);
450 strbuf_cleanup_path(&sb);
451 return strbuf_detach(&sb, NULL);
454 const char *mkpath(const char *fmt, ...)
457 struct strbuf *pathname = get_pathname();
459 strbuf_vaddf(pathname, fmt, args);
461 return cleanup_path(pathname->buf);
464 const char *worktree_git_path(const struct worktree *wt, const char *fmt, ...)
466 struct strbuf *pathname = get_pathname();
469 do_git_path(wt, pathname, fmt, args);
471 return pathname->buf;
474 /* Returns 0 on success, negative on failure. */
475 static int do_submodule_path(struct strbuf *buf, const char *path,
476 const char *fmt, va_list args)
478 struct strbuf git_submodule_common_dir = STRBUF_INIT;
479 struct strbuf git_submodule_dir = STRBUF_INIT;
482 ret = submodule_to_gitdir(&git_submodule_dir, path);
486 strbuf_complete(&git_submodule_dir, '/');
487 strbuf_addbuf(buf, &git_submodule_dir);
488 strbuf_vaddf(buf, fmt, args);
490 if (get_common_dir_noenv(&git_submodule_common_dir, git_submodule_dir.buf))
491 update_common_dir(buf, git_submodule_dir.len, git_submodule_common_dir.buf);
493 strbuf_cleanup_path(buf);
496 strbuf_release(&git_submodule_dir);
497 strbuf_release(&git_submodule_common_dir);
501 char *git_pathdup_submodule(const char *path, const char *fmt, ...)
505 struct strbuf buf = STRBUF_INIT;
507 err = do_submodule_path(&buf, path, fmt, args);
510 strbuf_release(&buf);
513 return strbuf_detach(&buf, NULL);
516 int strbuf_git_path_submodule(struct strbuf *buf, const char *path,
517 const char *fmt, ...)
522 err = do_submodule_path(buf, path, fmt, args);
528 static void do_git_common_path(struct strbuf *buf,
532 strbuf_addstr(buf, get_git_common_dir());
533 if (buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
534 strbuf_addch(buf, '/');
535 strbuf_vaddf(buf, fmt, args);
536 strbuf_cleanup_path(buf);
539 const char *git_common_path(const char *fmt, ...)
541 struct strbuf *pathname = get_pathname();
544 do_git_common_path(pathname, fmt, args);
546 return pathname->buf;
549 void strbuf_git_common_path(struct strbuf *sb, const char *fmt, ...)
553 do_git_common_path(sb, fmt, args);
557 int validate_headref(const char *path)
560 char *buf, buffer[256];
561 unsigned char sha1[20];
565 if (lstat(path, &st) < 0)
568 /* Make sure it is a "refs/.." symlink */
569 if (S_ISLNK(st.st_mode)) {
570 len = readlink(path, buffer, sizeof(buffer)-1);
571 if (len >= 5 && !memcmp("refs/", buffer, 5))
577 * Anything else, just open it and try to see if it is a symbolic ref.
579 fd = open(path, O_RDONLY);
582 len = read_in_full(fd, buffer, sizeof(buffer)-1);
586 * Is it a symbolic ref?
590 if (!memcmp("ref:", buffer, 4)) {
593 while (len && isspace(*buf))
595 if (len >= 5 && !memcmp("refs/", buf, 5))
600 * Is this a detached HEAD?
602 if (!get_sha1_hex(buffer, sha1))
608 static struct passwd *getpw_str(const char *username, size_t len)
611 char *username_z = xmemdupz(username, len);
612 pw = getpwnam(username_z);
618 * Return a string with ~ and ~user expanded via getpw*. If buf != NULL,
619 * then it is a newly allocated string. Returns NULL on getpw failure or
622 * If real_home is true, real_path($HOME) is used in the expansion.
624 char *expand_user_path(const char *path, int real_home)
626 struct strbuf user_path = STRBUF_INIT;
627 const char *to_copy = path;
631 if (path[0] == '~') {
632 const char *first_slash = strchrnul(path, '/');
633 const char *username = path + 1;
634 size_t username_len = first_slash - username;
635 if (username_len == 0) {
636 const char *home = getenv("HOME");
640 strbuf_addstr(&user_path, real_path(home));
642 strbuf_addstr(&user_path, home);
643 #ifdef GIT_WINDOWS_NATIVE
644 convert_slashes(user_path.buf);
647 struct passwd *pw = getpw_str(username, username_len);
650 strbuf_addstr(&user_path, pw->pw_dir);
652 to_copy = first_slash;
654 strbuf_addstr(&user_path, to_copy);
655 return strbuf_detach(&user_path, NULL);
657 strbuf_release(&user_path);
662 * First, one directory to try is determined by the following algorithm.
664 * (0) If "strict" is given, the path is used as given and no DWIM is
666 * (1) "~/path" to mean path under the running user's home directory;
667 * (2) "~user/path" to mean path under named user's home directory;
668 * (3) "relative/path" to mean cwd relative directory; or
669 * (4) "/absolute/path" to mean absolute directory.
671 * Unless "strict" is given, we check "%s/.git", "%s", "%s.git/.git", "%s.git"
672 * in this order. We select the first one that is a valid git repository, and
673 * chdir() to it. If none match, or we fail to chdir, we return NULL.
675 * If all goes well, we return the directory we used to chdir() (but
676 * before ~user is expanded), avoiding getcwd() resolving symbolic
677 * links. User relative paths are also returned as they are given,
678 * except DWIM suffixing.
680 const char *enter_repo(const char *path, int strict)
682 static struct strbuf validated_path = STRBUF_INIT;
683 static struct strbuf used_path = STRBUF_INIT;
689 static const char *suffix[] = {
690 "/.git", "", ".git/.git", ".git", NULL,
693 int len = strlen(path);
695 while ((1 < len) && (path[len-1] == '/'))
699 * We can handle arbitrary-sized buffers, but this remains as a
700 * sanity check on untrusted input.
705 strbuf_reset(&used_path);
706 strbuf_reset(&validated_path);
707 strbuf_add(&used_path, path, len);
708 strbuf_add(&validated_path, path, len);
710 if (used_path.buf[0] == '~') {
711 char *newpath = expand_user_path(used_path.buf, 0);
714 strbuf_attach(&used_path, newpath, strlen(newpath),
717 for (i = 0; suffix[i]; i++) {
719 size_t baselen = used_path.len;
720 strbuf_addstr(&used_path, suffix[i]);
721 if (!stat(used_path.buf, &st) &&
722 (S_ISREG(st.st_mode) ||
723 (S_ISDIR(st.st_mode) && is_git_directory(used_path.buf)))) {
724 strbuf_addstr(&validated_path, suffix[i]);
727 strbuf_setlen(&used_path, baselen);
731 gitfile = read_gitfile(used_path.buf);
733 strbuf_reset(&used_path);
734 strbuf_addstr(&used_path, gitfile);
736 if (chdir(used_path.buf))
738 path = validated_path.buf;
741 const char *gitfile = read_gitfile(path);
748 if (is_git_directory(".")) {
750 check_repository_format();
757 static int calc_shared_perm(int mode)
761 if (get_shared_repository() < 0)
762 tweak = -get_shared_repository();
764 tweak = get_shared_repository();
766 if (!(mode & S_IWUSR))
769 /* Copy read bits to execute bits */
770 tweak |= (tweak & 0444) >> 2;
771 if (get_shared_repository() < 0)
772 mode = (mode & ~0777) | tweak;
780 int adjust_shared_perm(const char *path)
782 int old_mode, new_mode;
784 if (!get_shared_repository())
786 if (get_st_mode_bits(path, &old_mode) < 0)
789 new_mode = calc_shared_perm(old_mode);
790 if (S_ISDIR(old_mode)) {
791 /* Copy read bits to execute bits */
792 new_mode |= (new_mode & 0444) >> 2;
793 new_mode |= FORCE_DIR_SET_GID;
796 if (((old_mode ^ new_mode) & ~S_IFMT) &&
797 chmod(path, (new_mode & ~S_IFMT)) < 0)
802 void safe_create_dir(const char *dir, int share)
804 if (mkdir(dir, 0777) < 0) {
805 if (errno != EEXIST) {
810 else if (share && adjust_shared_perm(dir))
811 die(_("Could not make %s writable by group"), dir);
814 static int have_same_root(const char *path1, const char *path2)
816 int is_abs1, is_abs2;
818 is_abs1 = is_absolute_path(path1);
819 is_abs2 = is_absolute_path(path2);
820 return (is_abs1 && is_abs2 && tolower(path1[0]) == tolower(path2[0])) ||
821 (!is_abs1 && !is_abs2);
825 * Give path as relative to prefix.
827 * The strbuf may or may not be used, so do not assume it contains the
830 const char *relative_path(const char *in, const char *prefix,
833 int in_len = in ? strlen(in) : 0;
834 int prefix_len = prefix ? strlen(prefix) : 0;
841 else if (!prefix_len)
844 if (have_same_root(in, prefix))
845 /* bypass dos_drive, for "c:" is identical to "C:" */
846 i = j = has_dos_drive_prefix(in);
851 while (i < prefix_len && j < in_len && prefix[i] == in[j]) {
852 if (is_dir_sep(prefix[i])) {
853 while (is_dir_sep(prefix[i]))
855 while (is_dir_sep(in[j]))
866 /* "prefix" seems like prefix of "in" */
869 * but "/foo" is not a prefix of "/foobar"
870 * (i.e. prefix not end with '/')
872 prefix_off < prefix_len) {
874 /* in="/a/b", prefix="/a/b" */
876 } else if (is_dir_sep(in[j])) {
877 /* in="/a/b/c", prefix="/a/b" */
878 while (is_dir_sep(in[j]))
882 /* in="/a/bbb/c", prefix="/a/b" */
886 /* "in" is short than "prefix" */
888 /* "in" not end with '/' */
890 if (is_dir_sep(prefix[i])) {
891 /* in="/a/b", prefix="/a/b/c/" */
892 while (is_dir_sep(prefix[i]))
900 if (i >= prefix_len) {
908 strbuf_grow(sb, in_len);
910 while (i < prefix_len) {
911 if (is_dir_sep(prefix[i])) {
912 strbuf_addstr(sb, "../");
913 while (is_dir_sep(prefix[i]))
919 if (!is_dir_sep(prefix[prefix_len - 1]))
920 strbuf_addstr(sb, "../");
922 strbuf_addstr(sb, in);
928 * A simpler implementation of relative_path
930 * Get relative path by removing "prefix" from "in". This function
931 * first appears in v1.5.6-1-g044bbbc, and makes git_dir shorter
932 * to increase performance when traversing the path to work_tree.
934 const char *remove_leading_path(const char *in, const char *prefix)
936 static struct strbuf buf = STRBUF_INIT;
939 if (!prefix || !prefix[0])
942 if (is_dir_sep(prefix[i])) {
943 if (!is_dir_sep(in[j]))
945 while (is_dir_sep(prefix[i]))
947 while (is_dir_sep(in[j]))
950 } else if (in[j] != prefix[i]) {
957 /* "/foo" is a prefix of "/foo" */
959 /* "/foo" is not a prefix of "/foobar" */
960 !is_dir_sep(prefix[i-1]) && !is_dir_sep(in[j])
963 while (is_dir_sep(in[j]))
968 strbuf_addstr(&buf, ".");
970 strbuf_addstr(&buf, in + j);
975 * It is okay if dst == src, but they should not overlap otherwise.
977 * Performs the following normalizations on src, storing the result in dst:
978 * - Ensures that components are separated by '/' (Windows only)
979 * - Squashes sequences of '/' except "//server/share" on Windows
980 * - Removes "." components.
981 * - Removes ".." components, and the components the precede them.
982 * Returns failure (non-zero) if a ".." component appears as first path
983 * component anytime during the normalization. Otherwise, returns success (0).
985 * Note that this function is purely textual. It does not follow symlinks,
986 * verify the existence of the path, or make any system calls.
988 * prefix_len != NULL is for a specific case of prefix_pathspec():
989 * assume that src == dst and src[0..prefix_len-1] is already
990 * normalized, any time "../" eats up to the prefix_len part,
991 * prefix_len is reduced. In the end prefix_len is the remaining
992 * prefix that has not been overridden by user pathspec.
994 * NEEDSWORK: This function doesn't perform normalization w.r.t. trailing '/'.
995 * For everything but the root folder itself, the normalized path should not
996 * end with a '/', then the callers need to be fixed up accordingly.
999 int normalize_path_copy_len(char *dst, const char *src, int *prefix_len)
1005 * Copy initial part of absolute path: "/", "C:/", "//server/share/".
1007 end = src + offset_1st_component(src);
1016 while (is_dir_sep(*src))
1023 * A path component that begins with . could be
1025 * (1) "." and ends -- ignore and terminate.
1026 * (2) "./" -- ignore them, eat slash and continue.
1027 * (3) ".." and ends -- strip one and terminate.
1028 * (4) "../" -- strip one, eat slash and continue.
1034 } else if (is_dir_sep(src[1])) {
1037 while (is_dir_sep(*src))
1040 } else if (src[1] == '.') {
1045 } else if (is_dir_sep(src[2])) {
1048 while (is_dir_sep(*src))
1055 /* copy up to the next '/', and eat all '/' */
1056 while ((c = *src++) != '\0' && !is_dir_sep(c))
1058 if (is_dir_sep(c)) {
1060 while (is_dir_sep(c))
1069 * dst0..dst is prefix portion, and dst[-1] is '/';
1072 dst--; /* go to trailing '/' */
1075 /* Windows: dst[-1] cannot be backslash anymore */
1076 while (dst0 < dst && dst[-1] != '/')
1078 if (prefix_len && *prefix_len > dst - dst0)
1079 *prefix_len = dst - dst0;
1085 int normalize_path_copy(char *dst, const char *src)
1087 return normalize_path_copy_len(dst, src, NULL);
1091 * path = Canonical absolute path
1092 * prefixes = string_list containing normalized, absolute paths without
1093 * trailing slashes (except for the root directory, which is denoted by "/").
1095 * Determines, for each path in prefixes, whether the "prefix"
1096 * is an ancestor directory of path. Returns the length of the longest
1097 * ancestor directory, excluding any trailing slashes, or -1 if no prefix
1098 * is an ancestor. (Note that this means 0 is returned if prefixes is
1099 * ["/"].) "/foo" is not considered an ancestor of "/foobar". Directories
1100 * are not considered to be their own ancestors. path must be in a
1101 * canonical form: empty components, or "." or ".." components are not
1104 int longest_ancestor_length(const char *path, struct string_list *prefixes)
1106 int i, max_len = -1;
1108 if (!strcmp(path, "/"))
1111 for (i = 0; i < prefixes->nr; i++) {
1112 const char *ceil = prefixes->items[i].string;
1113 int len = strlen(ceil);
1115 if (len == 1 && ceil[0] == '/')
1116 len = 0; /* root matches anything, with length 0 */
1117 else if (!strncmp(path, ceil, len) && path[len] == '/')
1118 ; /* match of length len */
1120 continue; /* no match */
1129 /* strip arbitrary amount of directory separators at end of path */
1130 static inline int chomp_trailing_dir_sep(const char *path, int len)
1132 while (len && is_dir_sep(path[len - 1]))
1138 * If path ends with suffix (complete path components), returns the
1139 * part before suffix (sans trailing directory separators).
1140 * Otherwise returns NULL.
1142 char *strip_path_suffix(const char *path, const char *suffix)
1144 int path_len = strlen(path), suffix_len = strlen(suffix);
1146 while (suffix_len) {
1150 if (is_dir_sep(path[path_len - 1])) {
1151 if (!is_dir_sep(suffix[suffix_len - 1]))
1153 path_len = chomp_trailing_dir_sep(path, path_len);
1154 suffix_len = chomp_trailing_dir_sep(suffix, suffix_len);
1156 else if (path[--path_len] != suffix[--suffix_len])
1160 if (path_len && !is_dir_sep(path[path_len - 1]))
1162 return xstrndup(path, chomp_trailing_dir_sep(path, path_len));
1165 int daemon_avoid_alias(const char *p)
1170 * This resurrects the belts and suspenders paranoia check by HPA
1171 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
1172 * does not do getcwd() based path canonicalization.
1174 * sl becomes true immediately after seeing '/' and continues to
1175 * be true as long as dots continue after that without intervening
1176 * non-dot character.
1178 if (!p || (*p != '/' && *p != '~'))
1188 else if (ch == '/') {
1190 /* reject //, /./ and /../ */
1195 if (0 < ndot && ndot < 3)
1196 /* reject /.$ and /..$ */
1205 else if (ch == '/') {
1212 static int only_spaces_and_periods(const char *path, size_t len, size_t skip)
1220 if (c != ' ' && c != '.')
1226 int is_ntfs_dotgit(const char *name)
1230 for (len = 0; ; len++)
1231 if (!name[len] || name[len] == '\\' || is_dir_sep(name[len])) {
1232 if (only_spaces_and_periods(name, len, 4) &&
1233 !strncasecmp(name, ".git", 4))
1235 if (only_spaces_and_periods(name, len, 5) &&
1236 !strncasecmp(name, "git~1", 5))
1238 if (name[len] != '\\')
1245 char *xdg_config_home(const char *filename)
1247 const char *home, *config_home;
1250 config_home = getenv("XDG_CONFIG_HOME");
1251 if (config_home && *config_home)
1252 return mkpathdup("%s/git/%s", config_home, filename);
1254 home = getenv("HOME");
1256 return mkpathdup("%s/.config/git/%s", home, filename);
1260 char *xdg_cache_home(const char *filename)
1262 const char *home, *cache_home;
1265 cache_home = getenv("XDG_CACHE_HOME");
1266 if (cache_home && *cache_home)
1267 return mkpathdup("%s/git/%s", cache_home, filename);
1269 home = getenv("HOME");
1271 return mkpathdup("%s/.cache/git/%s", home, filename);
1275 GIT_PATH_FUNC(git_path_cherry_pick_head, "CHERRY_PICK_HEAD")
1276 GIT_PATH_FUNC(git_path_revert_head, "REVERT_HEAD")
1277 GIT_PATH_FUNC(git_path_squash_msg, "SQUASH_MSG")
1278 GIT_PATH_FUNC(git_path_merge_msg, "MERGE_MSG")
1279 GIT_PATH_FUNC(git_path_merge_rr, "MERGE_RR")
1280 GIT_PATH_FUNC(git_path_merge_mode, "MERGE_MODE")
1281 GIT_PATH_FUNC(git_path_merge_head, "MERGE_HEAD")
1282 GIT_PATH_FUNC(git_path_fetch_head, "FETCH_HEAD")
1283 GIT_PATH_FUNC(git_path_shallow, "shallow")