2 * Utilities for paths and pathnames
5 #include "repository.h"
7 #include "string-list.h"
10 #include "submodule-config.h"
13 #include "object-store.h"
16 static int get_st_mode_bits(const char *path, int *mode)
19 if (lstat(path, &st) < 0)
25 static char bad_path[] = "/bad-path/";
27 static struct strbuf *get_pathname(void)
29 static struct strbuf pathname_array[4] = {
30 STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
33 struct strbuf *sb = &pathname_array[index];
34 index = (index + 1) % ARRAY_SIZE(pathname_array);
39 static const char *cleanup_path(const char *path)
42 if (skip_prefix(path, "./", &path)) {
49 static void strbuf_cleanup_path(struct strbuf *sb)
51 const char *path = cleanup_path(sb->buf);
53 strbuf_remove(sb, 0, path - sb->buf);
56 char *mksnpath(char *buf, size_t n, const char *fmt, ...)
62 len = vsnprintf(buf, n, fmt, args);
65 strlcpy(buf, bad_path, n);
68 return (char *)cleanup_path(buf);
71 static int dir_prefix(const char *buf, const char *dir)
73 int len = strlen(dir);
74 return !strncmp(buf, dir, len) &&
75 (is_dir_sep(buf[len]) || buf[len] == '\0');
78 /* $buf =~ m|$dir/+$file| but without regex */
79 static int is_dir_file(const char *buf, const char *dir, const char *file)
81 int len = strlen(dir);
82 if (strncmp(buf, dir, len) || !is_dir_sep(buf[len]))
84 while (is_dir_sep(buf[len]))
86 return !strcmp(buf + len, file);
89 static void replace_dir(struct strbuf *buf, int len, const char *newdir)
91 int newlen = strlen(newdir);
92 int need_sep = (buf->buf[len] && !is_dir_sep(buf->buf[len])) &&
93 !is_dir_sep(newdir[newlen - 1]);
95 len--; /* keep one char, to be replaced with '/' */
96 strbuf_splice(buf, 0, len, newdir, newlen);
98 buf->buf[newlen] = '/';
102 /* Not considered garbage for report_linked_checkout_garbage */
103 unsigned ignore_garbage:1;
105 /* Not common even though its parent is */
110 static struct common_dir common_list[] = {
111 { 0, 1, 0, "branches" },
112 { 0, 1, 0, "common" },
113 { 0, 1, 0, "hooks" },
115 { 0, 0, 1, "info/sparse-checkout" },
117 { 1, 1, 1, "logs/HEAD" },
118 { 0, 1, 1, "logs/refs/bisect" },
119 { 0, 1, 1, "logs/refs/rewritten" },
120 { 0, 1, 1, "logs/refs/worktree" },
121 { 0, 1, 0, "lost-found" },
122 { 0, 1, 0, "objects" },
124 { 0, 1, 1, "refs/bisect" },
125 { 0, 1, 1, "refs/rewritten" },
126 { 0, 1, 1, "refs/worktree" },
127 { 0, 1, 0, "remotes" },
128 { 0, 1, 0, "worktrees" },
129 { 0, 1, 0, "rr-cache" },
131 { 0, 0, 0, "config" },
132 { 1, 0, 0, "gc.pid" },
133 { 0, 0, 0, "packed-refs" },
134 { 0, 0, 0, "shallow" },
139 * A compressed trie. A trie node consists of zero or more characters that
140 * are common to all elements with this prefix, optionally followed by some
141 * children. If value is not NULL, the trie node is a terminal node.
143 * For example, consider the following set of strings:
149 * The trie would look like:
150 * root: len = 0, children a and d non-NULL, value = NULL.
151 * a: len = 2, contents = bc, value = (data for "abc")
152 * d: len = 2, contents = ef, children i non-NULL, value = (data for "def")
153 * i: len = 3, contents = nit, children e and i non-NULL, value = NULL
154 * e: len = 0, children all NULL, value = (data for "definite")
155 * i: len = 2, contents = on, children all NULL,
156 * value = (data for "definition")
159 struct trie *children[256];
165 static struct trie *make_trie_node(const char *key, void *value)
167 struct trie *new_node = xcalloc(1, sizeof(*new_node));
168 new_node->len = strlen(key);
170 new_node->contents = xmalloc(new_node->len);
171 memcpy(new_node->contents, key, new_node->len);
173 new_node->value = value;
178 * Add a key/value pair to a trie. The key is assumed to be \0-terminated.
179 * If there was an existing value for this key, return it.
181 static void *add_to_trie(struct trie *root, const char *key, void *value)
188 /* we have reached the end of the key */
194 for (i = 0; i < root->len; i++) {
195 if (root->contents[i] == key[i])
199 * Split this node: child will contain this node's
202 child = xmalloc(sizeof(*child));
203 memcpy(child->children, root->children, sizeof(root->children));
205 child->len = root->len - i - 1;
207 child->contents = xstrndup(root->contents + i + 1,
210 child->value = root->value;
214 memset(root->children, 0, sizeof(root->children));
215 root->children[(unsigned char)root->contents[i]] = child;
217 /* This is the newly-added child. */
218 root->children[(unsigned char)key[i]] =
219 make_trie_node(key + i + 1, value);
223 /* We have matched the entire compressed section */
225 child = root->children[(unsigned char)key[root->len]];
227 return add_to_trie(child, key + root->len + 1, value);
229 child = make_trie_node(key + root->len + 1, value);
230 root->children[(unsigned char)key[root->len]] = child;
240 typedef int (*match_fn)(const char *unmatched, void *data, void *baton);
243 * Search a trie for some key. Find the longest /-or-\0-terminated
244 * prefix of the key for which the trie contains a value. Call fn
245 * with the unmatched portion of the key and the found value, and
246 * return its return value. If there is no such prefix, return -1.
248 * The key is partially normalized: consecutive slashes are skipped.
250 * For example, consider the trie containing only [refs,
251 * refs/worktree] (both with values).
253 * | key | unmatched | val from node | return value |
254 * |-----------------|------------|---------------|--------------|
255 * | a | not called | n/a | -1 |
256 * | refs | \0 | refs | as per fn |
257 * | refs/ | / | refs | as per fn |
258 * | refs/w | /w | refs | as per fn |
259 * | refs/worktree | \0 | refs/worktree | as per fn |
260 * | refs/worktree/ | / | refs/worktree | as per fn |
261 * | refs/worktree/a | /a | refs/worktree | as per fn |
262 * |-----------------|------------|---------------|--------------|
265 static int trie_find(struct trie *root, const char *key, match_fn fn,
273 /* we have reached the end of the key */
274 if (root->value && !root->len)
275 return fn(key, root->value, baton);
280 for (i = 0; i < root->len; i++) {
281 /* Partial path normalization: skip consecutive slashes. */
282 if (key[i] == '/' && key[i+1] == '/') {
286 if (root->contents[i] != key[i])
290 /* Matched the entire compressed section */
294 return fn(key, root->value, baton);
296 /* Partial path normalization: skip consecutive slashes */
297 while (key[0] == '/' && key[1] == '/')
300 child = root->children[(unsigned char)*key];
302 result = trie_find(child, key + 1, fn, baton);
306 if (result >= 0 || (*key != '/' && *key != 0))
309 return fn(key, root->value, baton);
314 static struct trie common_trie;
315 static int common_trie_done_setup;
317 static void init_common_trie(void)
319 struct common_dir *p;
321 if (common_trie_done_setup)
324 for (p = common_list; p->dirname; p++)
325 add_to_trie(&common_trie, p->dirname, p);
327 common_trie_done_setup = 1;
331 * Helper function for update_common_dir: returns 1 if the dir
334 static int check_common(const char *unmatched, void *value, void *baton)
336 struct common_dir *dir = value;
341 if (dir->is_dir && (unmatched[0] == 0 || unmatched[0] == '/'))
342 return !dir->exclude;
344 if (!dir->is_dir && unmatched[0] == 0)
345 return !dir->exclude;
350 static void update_common_dir(struct strbuf *buf, int git_dir_len,
351 const char *common_dir)
353 char *base = buf->buf + git_dir_len;
354 int has_lock_suffix = strbuf_strip_suffix(buf, LOCK_SUFFIX);
357 if (trie_find(&common_trie, base, check_common, NULL) > 0)
358 replace_dir(buf, git_dir_len, common_dir);
361 strbuf_addstr(buf, LOCK_SUFFIX);
364 void report_linked_checkout_garbage(void)
366 struct strbuf sb = STRBUF_INIT;
367 const struct common_dir *p;
370 if (!the_repository->different_commondir)
372 strbuf_addf(&sb, "%s/", get_git_dir());
374 for (p = common_list; p->dirname; p++) {
375 const char *path = p->dirname;
376 if (p->ignore_garbage)
378 strbuf_setlen(&sb, len);
379 strbuf_addstr(&sb, path);
380 if (file_exists(sb.buf))
381 report_garbage(PACKDIR_FILE_GARBAGE, sb.buf);
386 static void adjust_git_path(const struct repository *repo,
387 struct strbuf *buf, int git_dir_len)
389 const char *base = buf->buf + git_dir_len;
390 if (is_dir_file(base, "info", "grafts"))
391 strbuf_splice(buf, 0, buf->len,
392 repo->graft_file, strlen(repo->graft_file));
393 else if (!strcmp(base, "index"))
394 strbuf_splice(buf, 0, buf->len,
395 repo->index_file, strlen(repo->index_file));
396 else if (dir_prefix(base, "objects"))
397 replace_dir(buf, git_dir_len + 7, repo->objects->odb->path);
398 else if (git_hooks_path && dir_prefix(base, "hooks"))
399 replace_dir(buf, git_dir_len + 5, git_hooks_path);
400 else if (repo->different_commondir)
401 update_common_dir(buf, git_dir_len, repo->commondir);
404 static void strbuf_worktree_gitdir(struct strbuf *buf,
405 const struct repository *repo,
406 const struct worktree *wt)
409 strbuf_addstr(buf, repo->gitdir);
411 strbuf_addstr(buf, repo->commondir);
413 strbuf_git_common_path(buf, repo, "worktrees/%s", wt->id);
416 static void do_git_path(const struct repository *repo,
417 const struct worktree *wt, struct strbuf *buf,
418 const char *fmt, va_list args)
421 strbuf_worktree_gitdir(buf, repo, wt);
422 if (buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
423 strbuf_addch(buf, '/');
424 gitdir_len = buf->len;
425 strbuf_vaddf(buf, fmt, args);
427 adjust_git_path(repo, buf, gitdir_len);
428 strbuf_cleanup_path(buf);
431 char *repo_git_path(const struct repository *repo,
432 const char *fmt, ...)
434 struct strbuf path = STRBUF_INIT;
437 do_git_path(repo, NULL, &path, fmt, args);
439 return strbuf_detach(&path, NULL);
442 void strbuf_repo_git_path(struct strbuf *sb,
443 const struct repository *repo,
444 const char *fmt, ...)
448 do_git_path(repo, NULL, sb, fmt, args);
452 char *git_path_buf(struct strbuf *buf, const char *fmt, ...)
457 do_git_path(the_repository, NULL, buf, fmt, args);
462 void strbuf_git_path(struct strbuf *sb, const char *fmt, ...)
466 do_git_path(the_repository, NULL, sb, fmt, args);
470 const char *git_path(const char *fmt, ...)
472 struct strbuf *pathname = get_pathname();
475 do_git_path(the_repository, NULL, pathname, fmt, args);
477 return pathname->buf;
480 char *git_pathdup(const char *fmt, ...)
482 struct strbuf path = STRBUF_INIT;
485 do_git_path(the_repository, NULL, &path, fmt, args);
487 return strbuf_detach(&path, NULL);
490 char *mkpathdup(const char *fmt, ...)
492 struct strbuf sb = STRBUF_INIT;
495 strbuf_vaddf(&sb, fmt, args);
497 strbuf_cleanup_path(&sb);
498 return strbuf_detach(&sb, NULL);
501 const char *mkpath(const char *fmt, ...)
504 struct strbuf *pathname = get_pathname();
506 strbuf_vaddf(pathname, fmt, args);
508 return cleanup_path(pathname->buf);
511 const char *worktree_git_path(const struct worktree *wt, const char *fmt, ...)
513 struct strbuf *pathname = get_pathname();
516 do_git_path(the_repository, wt, pathname, fmt, args);
518 return pathname->buf;
521 static void do_worktree_path(const struct repository *repo,
523 const char *fmt, va_list args)
525 strbuf_addstr(buf, repo->worktree);
526 if(buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
527 strbuf_addch(buf, '/');
529 strbuf_vaddf(buf, fmt, args);
530 strbuf_cleanup_path(buf);
533 char *repo_worktree_path(const struct repository *repo, const char *fmt, ...)
535 struct strbuf path = STRBUF_INIT;
542 do_worktree_path(repo, &path, fmt, args);
545 return strbuf_detach(&path, NULL);
548 void strbuf_repo_worktree_path(struct strbuf *sb,
549 const struct repository *repo,
550 const char *fmt, ...)
558 do_worktree_path(repo, sb, fmt, args);
562 /* Returns 0 on success, negative on failure. */
563 static int do_submodule_path(struct strbuf *buf, const char *path,
564 const char *fmt, va_list args)
566 struct strbuf git_submodule_common_dir = STRBUF_INIT;
567 struct strbuf git_submodule_dir = STRBUF_INIT;
570 ret = submodule_to_gitdir(&git_submodule_dir, path);
574 strbuf_complete(&git_submodule_dir, '/');
575 strbuf_addbuf(buf, &git_submodule_dir);
576 strbuf_vaddf(buf, fmt, args);
578 if (get_common_dir_noenv(&git_submodule_common_dir, git_submodule_dir.buf))
579 update_common_dir(buf, git_submodule_dir.len, git_submodule_common_dir.buf);
581 strbuf_cleanup_path(buf);
584 strbuf_release(&git_submodule_dir);
585 strbuf_release(&git_submodule_common_dir);
589 char *git_pathdup_submodule(const char *path, const char *fmt, ...)
593 struct strbuf buf = STRBUF_INIT;
595 err = do_submodule_path(&buf, path, fmt, args);
598 strbuf_release(&buf);
601 return strbuf_detach(&buf, NULL);
604 int strbuf_git_path_submodule(struct strbuf *buf, const char *path,
605 const char *fmt, ...)
610 err = do_submodule_path(buf, path, fmt, args);
616 static void do_git_common_path(const struct repository *repo,
621 strbuf_addstr(buf, repo->commondir);
622 if (buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
623 strbuf_addch(buf, '/');
624 strbuf_vaddf(buf, fmt, args);
625 strbuf_cleanup_path(buf);
628 const char *git_common_path(const char *fmt, ...)
630 struct strbuf *pathname = get_pathname();
633 do_git_common_path(the_repository, pathname, fmt, args);
635 return pathname->buf;
638 void strbuf_git_common_path(struct strbuf *sb,
639 const struct repository *repo,
640 const char *fmt, ...)
644 do_git_common_path(repo, sb, fmt, args);
648 int validate_headref(const char *path)
653 struct object_id oid;
657 if (lstat(path, &st) < 0)
660 /* Make sure it is a "refs/.." symlink */
661 if (S_ISLNK(st.st_mode)) {
662 len = readlink(path, buffer, sizeof(buffer)-1);
663 if (len >= 5 && !memcmp("refs/", buffer, 5))
669 * Anything else, just open it and try to see if it is a symbolic ref.
671 fd = open(path, O_RDONLY);
674 len = read_in_full(fd, buffer, sizeof(buffer)-1);
682 * Is it a symbolic ref?
684 if (skip_prefix(buffer, "ref:", &refname)) {
685 while (isspace(*refname))
687 if (starts_with(refname, "refs/"))
692 * Is this a detached HEAD?
694 if (!get_oid_hex(buffer, &oid))
700 static struct passwd *getpw_str(const char *username, size_t len)
703 char *username_z = xmemdupz(username, len);
704 pw = getpwnam(username_z);
710 * Return a string with ~ and ~user expanded via getpw*. If buf != NULL,
711 * then it is a newly allocated string. Returns NULL on getpw failure or
714 * If real_home is true, real_path($HOME) is used in the expansion.
716 char *expand_user_path(const char *path, int real_home)
718 struct strbuf user_path = STRBUF_INIT;
719 const char *to_copy = path;
723 if (path[0] == '~') {
724 const char *first_slash = strchrnul(path, '/');
725 const char *username = path + 1;
726 size_t username_len = first_slash - username;
727 if (username_len == 0) {
728 const char *home = getenv("HOME");
732 strbuf_add_real_path(&user_path, home);
734 strbuf_addstr(&user_path, home);
735 #ifdef GIT_WINDOWS_NATIVE
736 convert_slashes(user_path.buf);
739 struct passwd *pw = getpw_str(username, username_len);
742 strbuf_addstr(&user_path, pw->pw_dir);
744 to_copy = first_slash;
746 strbuf_addstr(&user_path, to_copy);
747 return strbuf_detach(&user_path, NULL);
749 strbuf_release(&user_path);
754 * First, one directory to try is determined by the following algorithm.
756 * (0) If "strict" is given, the path is used as given and no DWIM is
758 * (1) "~/path" to mean path under the running user's home directory;
759 * (2) "~user/path" to mean path under named user's home directory;
760 * (3) "relative/path" to mean cwd relative directory; or
761 * (4) "/absolute/path" to mean absolute directory.
763 * Unless "strict" is given, we check "%s/.git", "%s", "%s.git/.git", "%s.git"
764 * in this order. We select the first one that is a valid git repository, and
765 * chdir() to it. If none match, or we fail to chdir, we return NULL.
767 * If all goes well, we return the directory we used to chdir() (but
768 * before ~user is expanded), avoiding getcwd() resolving symbolic
769 * links. User relative paths are also returned as they are given,
770 * except DWIM suffixing.
772 const char *enter_repo(const char *path, int strict)
774 static struct strbuf validated_path = STRBUF_INIT;
775 static struct strbuf used_path = STRBUF_INIT;
781 static const char *suffix[] = {
782 "/.git", "", ".git/.git", ".git", NULL,
785 int len = strlen(path);
787 while ((1 < len) && (path[len-1] == '/'))
791 * We can handle arbitrary-sized buffers, but this remains as a
792 * sanity check on untrusted input.
797 strbuf_reset(&used_path);
798 strbuf_reset(&validated_path);
799 strbuf_add(&used_path, path, len);
800 strbuf_add(&validated_path, path, len);
802 if (used_path.buf[0] == '~') {
803 char *newpath = expand_user_path(used_path.buf, 0);
806 strbuf_attach(&used_path, newpath, strlen(newpath),
809 for (i = 0; suffix[i]; i++) {
811 size_t baselen = used_path.len;
812 strbuf_addstr(&used_path, suffix[i]);
813 if (!stat(used_path.buf, &st) &&
814 (S_ISREG(st.st_mode) ||
815 (S_ISDIR(st.st_mode) && is_git_directory(used_path.buf)))) {
816 strbuf_addstr(&validated_path, suffix[i]);
819 strbuf_setlen(&used_path, baselen);
823 gitfile = read_gitfile(used_path.buf);
825 strbuf_reset(&used_path);
826 strbuf_addstr(&used_path, gitfile);
828 if (chdir(used_path.buf))
830 path = validated_path.buf;
833 const char *gitfile = read_gitfile(path);
840 if (is_git_directory(".")) {
842 check_repository_format();
849 static int calc_shared_perm(int mode)
853 if (get_shared_repository() < 0)
854 tweak = -get_shared_repository();
856 tweak = get_shared_repository();
858 if (!(mode & S_IWUSR))
861 /* Copy read bits to execute bits */
862 tweak |= (tweak & 0444) >> 2;
863 if (get_shared_repository() < 0)
864 mode = (mode & ~0777) | tweak;
872 int adjust_shared_perm(const char *path)
874 int old_mode, new_mode;
876 if (!get_shared_repository())
878 if (get_st_mode_bits(path, &old_mode) < 0)
881 new_mode = calc_shared_perm(old_mode);
882 if (S_ISDIR(old_mode)) {
883 /* Copy read bits to execute bits */
884 new_mode |= (new_mode & 0444) >> 2;
885 new_mode |= FORCE_DIR_SET_GID;
888 if (((old_mode ^ new_mode) & ~S_IFMT) &&
889 chmod(path, (new_mode & ~S_IFMT)) < 0)
894 void safe_create_dir(const char *dir, int share)
896 if (mkdir(dir, 0777) < 0) {
897 if (errno != EEXIST) {
902 else if (share && adjust_shared_perm(dir))
903 die(_("Could not make %s writable by group"), dir);
906 static int have_same_root(const char *path1, const char *path2)
908 int is_abs1, is_abs2;
910 is_abs1 = is_absolute_path(path1);
911 is_abs2 = is_absolute_path(path2);
912 return (is_abs1 && is_abs2 && tolower(path1[0]) == tolower(path2[0])) ||
913 (!is_abs1 && !is_abs2);
917 * Give path as relative to prefix.
919 * The strbuf may or may not be used, so do not assume it contains the
922 const char *relative_path(const char *in, const char *prefix,
925 int in_len = in ? strlen(in) : 0;
926 int prefix_len = prefix ? strlen(prefix) : 0;
933 else if (!prefix_len)
936 if (have_same_root(in, prefix))
937 /* bypass dos_drive, for "c:" is identical to "C:" */
938 i = j = has_dos_drive_prefix(in);
943 while (i < prefix_len && j < in_len && prefix[i] == in[j]) {
944 if (is_dir_sep(prefix[i])) {
945 while (is_dir_sep(prefix[i]))
947 while (is_dir_sep(in[j]))
958 /* "prefix" seems like prefix of "in" */
961 * but "/foo" is not a prefix of "/foobar"
962 * (i.e. prefix not end with '/')
964 prefix_off < prefix_len) {
966 /* in="/a/b", prefix="/a/b" */
968 } else if (is_dir_sep(in[j])) {
969 /* in="/a/b/c", prefix="/a/b" */
970 while (is_dir_sep(in[j]))
974 /* in="/a/bbb/c", prefix="/a/b" */
978 /* "in" is short than "prefix" */
980 /* "in" not end with '/' */
982 if (is_dir_sep(prefix[i])) {
983 /* in="/a/b", prefix="/a/b/c/" */
984 while (is_dir_sep(prefix[i]))
992 if (i >= prefix_len) {
1000 strbuf_grow(sb, in_len);
1002 while (i < prefix_len) {
1003 if (is_dir_sep(prefix[i])) {
1004 strbuf_addstr(sb, "../");
1005 while (is_dir_sep(prefix[i]))
1011 if (!is_dir_sep(prefix[prefix_len - 1]))
1012 strbuf_addstr(sb, "../");
1014 strbuf_addstr(sb, in);
1020 * A simpler implementation of relative_path
1022 * Get relative path by removing "prefix" from "in". This function
1023 * first appears in v1.5.6-1-g044bbbc, and makes git_dir shorter
1024 * to increase performance when traversing the path to work_tree.
1026 const char *remove_leading_path(const char *in, const char *prefix)
1028 static struct strbuf buf = STRBUF_INIT;
1031 if (!prefix || !prefix[0])
1034 if (is_dir_sep(prefix[i])) {
1035 if (!is_dir_sep(in[j]))
1037 while (is_dir_sep(prefix[i]))
1039 while (is_dir_sep(in[j]))
1042 } else if (in[j] != prefix[i]) {
1049 /* "/foo" is a prefix of "/foo" */
1051 /* "/foo" is not a prefix of "/foobar" */
1052 !is_dir_sep(prefix[i-1]) && !is_dir_sep(in[j])
1055 while (is_dir_sep(in[j]))
1060 strbuf_addstr(&buf, ".");
1062 strbuf_addstr(&buf, in + j);
1067 * It is okay if dst == src, but they should not overlap otherwise.
1069 * Performs the following normalizations on src, storing the result in dst:
1070 * - Ensures that components are separated by '/' (Windows only)
1071 * - Squashes sequences of '/' except "//server/share" on Windows
1072 * - Removes "." components.
1073 * - Removes ".." components, and the components the precede them.
1074 * Returns failure (non-zero) if a ".." component appears as first path
1075 * component anytime during the normalization. Otherwise, returns success (0).
1077 * Note that this function is purely textual. It does not follow symlinks,
1078 * verify the existence of the path, or make any system calls.
1080 * prefix_len != NULL is for a specific case of prefix_pathspec():
1081 * assume that src == dst and src[0..prefix_len-1] is already
1082 * normalized, any time "../" eats up to the prefix_len part,
1083 * prefix_len is reduced. In the end prefix_len is the remaining
1084 * prefix that has not been overridden by user pathspec.
1086 * NEEDSWORK: This function doesn't perform normalization w.r.t. trailing '/'.
1087 * For everything but the root folder itself, the normalized path should not
1088 * end with a '/', then the callers need to be fixed up accordingly.
1091 int normalize_path_copy_len(char *dst, const char *src, int *prefix_len)
1097 * Copy initial part of absolute path: "/", "C:/", "//server/share/".
1099 end = src + offset_1st_component(src);
1108 while (is_dir_sep(*src))
1115 * A path component that begins with . could be
1117 * (1) "." and ends -- ignore and terminate.
1118 * (2) "./" -- ignore them, eat slash and continue.
1119 * (3) ".." and ends -- strip one and terminate.
1120 * (4) "../" -- strip one, eat slash and continue.
1126 } else if (is_dir_sep(src[1])) {
1129 while (is_dir_sep(*src))
1132 } else if (src[1] == '.') {
1137 } else if (is_dir_sep(src[2])) {
1140 while (is_dir_sep(*src))
1147 /* copy up to the next '/', and eat all '/' */
1148 while ((c = *src++) != '\0' && !is_dir_sep(c))
1150 if (is_dir_sep(c)) {
1152 while (is_dir_sep(c))
1161 * dst0..dst is prefix portion, and dst[-1] is '/';
1164 dst--; /* go to trailing '/' */
1167 /* Windows: dst[-1] cannot be backslash anymore */
1168 while (dst0 < dst && dst[-1] != '/')
1170 if (prefix_len && *prefix_len > dst - dst0)
1171 *prefix_len = dst - dst0;
1177 int normalize_path_copy(char *dst, const char *src)
1179 return normalize_path_copy_len(dst, src, NULL);
1183 * path = Canonical absolute path
1184 * prefixes = string_list containing normalized, absolute paths without
1185 * trailing slashes (except for the root directory, which is denoted by "/").
1187 * Determines, for each path in prefixes, whether the "prefix"
1188 * is an ancestor directory of path. Returns the length of the longest
1189 * ancestor directory, excluding any trailing slashes, or -1 if no prefix
1190 * is an ancestor. (Note that this means 0 is returned if prefixes is
1191 * ["/"].) "/foo" is not considered an ancestor of "/foobar". Directories
1192 * are not considered to be their own ancestors. path must be in a
1193 * canonical form: empty components, or "." or ".." components are not
1196 int longest_ancestor_length(const char *path, struct string_list *prefixes)
1198 int i, max_len = -1;
1200 if (!strcmp(path, "/"))
1203 for (i = 0; i < prefixes->nr; i++) {
1204 const char *ceil = prefixes->items[i].string;
1205 int len = strlen(ceil);
1207 if (len == 1 && ceil[0] == '/')
1208 len = 0; /* root matches anything, with length 0 */
1209 else if (!strncmp(path, ceil, len) && path[len] == '/')
1210 ; /* match of length len */
1212 continue; /* no match */
1221 /* strip arbitrary amount of directory separators at end of path */
1222 static inline int chomp_trailing_dir_sep(const char *path, int len)
1224 while (len && is_dir_sep(path[len - 1]))
1230 * If path ends with suffix (complete path components), returns the
1231 * part before suffix (sans trailing directory separators).
1232 * Otherwise returns NULL.
1234 char *strip_path_suffix(const char *path, const char *suffix)
1236 int path_len = strlen(path), suffix_len = strlen(suffix);
1238 while (suffix_len) {
1242 if (is_dir_sep(path[path_len - 1])) {
1243 if (!is_dir_sep(suffix[suffix_len - 1]))
1245 path_len = chomp_trailing_dir_sep(path, path_len);
1246 suffix_len = chomp_trailing_dir_sep(suffix, suffix_len);
1248 else if (path[--path_len] != suffix[--suffix_len])
1252 if (path_len && !is_dir_sep(path[path_len - 1]))
1254 return xstrndup(path, chomp_trailing_dir_sep(path, path_len));
1257 int daemon_avoid_alias(const char *p)
1262 * This resurrects the belts and suspenders paranoia check by HPA
1263 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
1264 * does not do getcwd() based path canonicalization.
1266 * sl becomes true immediately after seeing '/' and continues to
1267 * be true as long as dots continue after that without intervening
1268 * non-dot character.
1270 if (!p || (*p != '/' && *p != '~'))
1280 else if (ch == '/') {
1282 /* reject //, /./ and /../ */
1287 if (0 < ndot && ndot < 3)
1288 /* reject /.$ and /..$ */
1297 else if (ch == '/') {
1304 static int only_spaces_and_periods(const char *path, size_t len, size_t skip)
1312 if (c != ' ' && c != '.')
1318 int is_ntfs_dotgit(const char *name)
1322 for (len = 0; ; len++)
1323 if (!name[len] || name[len] == '\\' || is_dir_sep(name[len])) {
1324 if (only_spaces_and_periods(name, len, 4) &&
1325 !strncasecmp(name, ".git", 4))
1327 if (only_spaces_and_periods(name, len, 5) &&
1328 !strncasecmp(name, "git~1", 5))
1330 if (name[len] != '\\')
1337 static int is_ntfs_dot_generic(const char *name,
1338 const char *dotgit_name,
1340 const char *dotgit_ntfs_shortname_prefix)
1345 if ((name[0] == '.' && !strncasecmp(name + 1, dotgit_name, len))) {
1347 only_spaces_and_periods:
1352 if (c != ' ' && c != '.')
1358 * Is it a regular NTFS short name, i.e. shortened to 6 characters,
1359 * followed by ~1, ... ~4?
1361 if (!strncasecmp(name, dotgit_name, 6) && name[6] == '~' &&
1362 name[7] >= '1' && name[7] <= '4') {
1364 goto only_spaces_and_periods;
1368 * Is it a fall-back NTFS short name (for details, see
1369 * https://en.wikipedia.org/wiki/8.3_filename?
1371 for (i = 0, saw_tilde = 0; i < 8; i++)
1372 if (name[i] == '\0')
1374 else if (saw_tilde) {
1375 if (name[i] < '0' || name[i] > '9')
1377 } else if (name[i] == '~') {
1378 if (name[++i] < '1' || name[i] > '9')
1383 else if (name[i] & 0x80) {
1385 * We know our needles contain only ASCII, so we clamp
1386 * here to make the results of tolower() sane.
1389 } else if (tolower(name[i]) != dotgit_ntfs_shortname_prefix[i])
1392 goto only_spaces_and_periods;
1396 * Inline helper to make sure compiler resolves strlen() on literals at
1399 static inline int is_ntfs_dot_str(const char *name, const char *dotgit_name,
1400 const char *dotgit_ntfs_shortname_prefix)
1402 return is_ntfs_dot_generic(name, dotgit_name, strlen(dotgit_name),
1403 dotgit_ntfs_shortname_prefix);
1406 int is_ntfs_dotgitmodules(const char *name)
1408 return is_ntfs_dot_str(name, "gitmodules", "gi7eba");
1411 int is_ntfs_dotgitignore(const char *name)
1413 return is_ntfs_dot_str(name, "gitignore", "gi250a");
1416 int is_ntfs_dotgitattributes(const char *name)
1418 return is_ntfs_dot_str(name, "gitattributes", "gi7d29");
1421 int looks_like_command_line_option(const char *str)
1423 return str && str[0] == '-';
1426 char *xdg_config_home(const char *filename)
1428 const char *home, *config_home;
1431 config_home = getenv("XDG_CONFIG_HOME");
1432 if (config_home && *config_home)
1433 return mkpathdup("%s/git/%s", config_home, filename);
1435 home = getenv("HOME");
1437 return mkpathdup("%s/.config/git/%s", home, filename);
1441 char *xdg_cache_home(const char *filename)
1443 const char *home, *cache_home;
1446 cache_home = getenv("XDG_CACHE_HOME");
1447 if (cache_home && *cache_home)
1448 return mkpathdup("%s/git/%s", cache_home, filename);
1450 home = getenv("HOME");
1452 return mkpathdup("%s/.cache/git/%s", home, filename);
1456 REPO_GIT_PATH_FUNC(cherry_pick_head, "CHERRY_PICK_HEAD")
1457 REPO_GIT_PATH_FUNC(revert_head, "REVERT_HEAD")
1458 REPO_GIT_PATH_FUNC(squash_msg, "SQUASH_MSG")
1459 REPO_GIT_PATH_FUNC(merge_msg, "MERGE_MSG")
1460 REPO_GIT_PATH_FUNC(merge_rr, "MERGE_RR")
1461 REPO_GIT_PATH_FUNC(merge_mode, "MERGE_MODE")
1462 REPO_GIT_PATH_FUNC(merge_head, "MERGE_HEAD")
1463 REPO_GIT_PATH_FUNC(fetch_head, "FETCH_HEAD")
1464 REPO_GIT_PATH_FUNC(shallow, "shallow")