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 /* Belongs to the common dir, though it may contain paths that don't */
106 unsigned is_common:1;
110 static struct common_dir common_list[] = {
111 { 0, 1, 1, "branches" },
112 { 0, 1, 1, "common" },
113 { 0, 1, 1, "hooks" },
115 { 0, 0, 0, "info/sparse-checkout" },
117 { 1, 0, 0, "logs/HEAD" },
118 { 0, 1, 0, "logs/refs/bisect" },
119 { 0, 1, 0, "logs/refs/rewritten" },
120 { 0, 1, 0, "logs/refs/worktree" },
121 { 0, 1, 1, "lost-found" },
122 { 0, 1, 1, "objects" },
124 { 0, 1, 0, "refs/bisect" },
125 { 0, 1, 0, "refs/rewritten" },
126 { 0, 1, 0, "refs/worktree" },
127 { 0, 1, 1, "remotes" },
128 { 0, 1, 1, "worktrees" },
129 { 0, 1, 1, "rr-cache" },
131 { 0, 0, 1, "config" },
132 { 1, 0, 1, "gc.pid" },
133 { 0, 0, 1, "packed-refs" },
134 { 0, 0, 1, "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 *value, 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. If there is
245 * no such prefix, return -1. Otherwise call fn with the unmatched
246 * portion of the key and the found value. If fn returns 0 or
247 * positive, then return its return value. If fn returns negative,
248 * then call fn with the next-longest /-terminated prefix of the key
249 * (i.e. a parent directory) for which the trie contains a value, and
250 * handle its return value the same way. If there is no shorter
251 * /-terminated prefix with a value left, then return the negative
252 * return value of the most recent fn invocation.
254 * The key is partially normalized: consecutive slashes are skipped.
256 * For example, consider the trie containing only [logs,
257 * logs/refs/bisect], both with values, but not logs/refs.
259 * | key | unmatched | prefix to node | return value |
260 * |--------------------|----------------|------------------|--------------|
261 * | a | not called | n/a | -1 |
262 * | logstore | not called | n/a | -1 |
263 * | logs | \0 | logs | as per fn |
264 * | logs/ | / | logs | as per fn |
265 * | logs/refs | /refs | logs | as per fn |
266 * | logs/refs/ | /refs/ | logs | as per fn |
267 * | logs/refs/b | /refs/b | logs | as per fn |
268 * | logs/refs/bisected | /refs/bisected | logs | as per fn |
269 * | logs/refs/bisect | \0 | logs/refs/bisect | as per fn |
270 * | logs/refs/bisect/ | / | logs/refs/bisect | as per fn |
271 * | logs/refs/bisect/a | /a | logs/refs/bisect | as per fn |
272 * | (If fn in the previous line returns -1, then fn is called once more:) |
273 * | logs/refs/bisect/a | /refs/bisect/a | logs | as per fn |
274 * |--------------------|----------------|------------------|--------------|
276 static int trie_find(struct trie *root, const char *key, match_fn fn,
284 /* we have reached the end of the key */
285 if (root->value && !root->len)
286 return fn(key, root->value, baton);
291 for (i = 0; i < root->len; i++) {
292 /* Partial path normalization: skip consecutive slashes. */
293 if (key[i] == '/' && key[i+1] == '/') {
297 if (root->contents[i] != key[i])
301 /* Matched the entire compressed section */
306 return fn(key, root->value, baton);
311 /* Partial path normalization: skip consecutive slashes */
312 while (key[0] == '/' && key[1] == '/')
315 child = root->children[(unsigned char)*key];
317 result = trie_find(child, key + 1, fn, baton);
321 if (result >= 0 || (*key != '/' && *key != 0))
324 return fn(key, root->value, baton);
329 static struct trie common_trie;
330 static int common_trie_done_setup;
332 static void init_common_trie(void)
334 struct common_dir *p;
336 if (common_trie_done_setup)
339 for (p = common_list; p->path; p++)
340 add_to_trie(&common_trie, p->path, p);
342 common_trie_done_setup = 1;
346 * Helper function for update_common_dir: returns 1 if the dir
349 static int check_common(const char *unmatched, void *value, void *baton)
351 struct common_dir *dir = value;
353 if (dir->is_dir && (unmatched[0] == 0 || unmatched[0] == '/'))
354 return dir->is_common;
356 if (!dir->is_dir && unmatched[0] == 0)
357 return dir->is_common;
362 static void update_common_dir(struct strbuf *buf, int git_dir_len,
363 const char *common_dir)
365 char *base = buf->buf + git_dir_len;
366 int has_lock_suffix = strbuf_strip_suffix(buf, LOCK_SUFFIX);
369 if (trie_find(&common_trie, base, check_common, NULL) > 0)
370 replace_dir(buf, git_dir_len, common_dir);
373 strbuf_addstr(buf, LOCK_SUFFIX);
376 void report_linked_checkout_garbage(void)
378 struct strbuf sb = STRBUF_INIT;
379 const struct common_dir *p;
382 if (!the_repository->different_commondir)
384 strbuf_addf(&sb, "%s/", get_git_dir());
386 for (p = common_list; p->path; p++) {
387 const char *path = p->path;
388 if (p->ignore_garbage)
390 strbuf_setlen(&sb, len);
391 strbuf_addstr(&sb, path);
392 if (file_exists(sb.buf))
393 report_garbage(PACKDIR_FILE_GARBAGE, sb.buf);
398 static void adjust_git_path(const struct repository *repo,
399 struct strbuf *buf, int git_dir_len)
401 const char *base = buf->buf + git_dir_len;
402 if (is_dir_file(base, "info", "grafts"))
403 strbuf_splice(buf, 0, buf->len,
404 repo->graft_file, strlen(repo->graft_file));
405 else if (!strcmp(base, "index"))
406 strbuf_splice(buf, 0, buf->len,
407 repo->index_file, strlen(repo->index_file));
408 else if (dir_prefix(base, "objects"))
409 replace_dir(buf, git_dir_len + 7, repo->objects->odb->path);
410 else if (git_hooks_path && dir_prefix(base, "hooks"))
411 replace_dir(buf, git_dir_len + 5, git_hooks_path);
412 else if (repo->different_commondir)
413 update_common_dir(buf, git_dir_len, repo->commondir);
416 static void strbuf_worktree_gitdir(struct strbuf *buf,
417 const struct repository *repo,
418 const struct worktree *wt)
421 strbuf_addstr(buf, repo->gitdir);
423 strbuf_addstr(buf, repo->commondir);
425 strbuf_git_common_path(buf, repo, "worktrees/%s", wt->id);
428 static void do_git_path(const struct repository *repo,
429 const struct worktree *wt, struct strbuf *buf,
430 const char *fmt, va_list args)
433 strbuf_worktree_gitdir(buf, repo, wt);
434 if (buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
435 strbuf_addch(buf, '/');
436 gitdir_len = buf->len;
437 strbuf_vaddf(buf, fmt, args);
439 adjust_git_path(repo, buf, gitdir_len);
440 strbuf_cleanup_path(buf);
443 char *repo_git_path(const struct repository *repo,
444 const char *fmt, ...)
446 struct strbuf path = STRBUF_INIT;
449 do_git_path(repo, NULL, &path, fmt, args);
451 return strbuf_detach(&path, NULL);
454 void strbuf_repo_git_path(struct strbuf *sb,
455 const struct repository *repo,
456 const char *fmt, ...)
460 do_git_path(repo, NULL, sb, fmt, args);
464 char *git_path_buf(struct strbuf *buf, const char *fmt, ...)
469 do_git_path(the_repository, NULL, buf, fmt, args);
474 void strbuf_git_path(struct strbuf *sb, const char *fmt, ...)
478 do_git_path(the_repository, NULL, sb, fmt, args);
482 const char *git_path(const char *fmt, ...)
484 struct strbuf *pathname = get_pathname();
487 do_git_path(the_repository, NULL, pathname, fmt, args);
489 return pathname->buf;
492 char *git_pathdup(const char *fmt, ...)
494 struct strbuf path = STRBUF_INIT;
497 do_git_path(the_repository, NULL, &path, fmt, args);
499 return strbuf_detach(&path, NULL);
502 char *mkpathdup(const char *fmt, ...)
504 struct strbuf sb = STRBUF_INIT;
507 strbuf_vaddf(&sb, fmt, args);
509 strbuf_cleanup_path(&sb);
510 return strbuf_detach(&sb, NULL);
513 const char *mkpath(const char *fmt, ...)
516 struct strbuf *pathname = get_pathname();
518 strbuf_vaddf(pathname, fmt, args);
520 return cleanup_path(pathname->buf);
523 const char *worktree_git_path(const struct worktree *wt, const char *fmt, ...)
525 struct strbuf *pathname = get_pathname();
528 do_git_path(the_repository, wt, pathname, fmt, args);
530 return pathname->buf;
533 static void do_worktree_path(const struct repository *repo,
535 const char *fmt, va_list args)
537 strbuf_addstr(buf, repo->worktree);
538 if(buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
539 strbuf_addch(buf, '/');
541 strbuf_vaddf(buf, fmt, args);
542 strbuf_cleanup_path(buf);
545 char *repo_worktree_path(const struct repository *repo, const char *fmt, ...)
547 struct strbuf path = STRBUF_INIT;
554 do_worktree_path(repo, &path, fmt, args);
557 return strbuf_detach(&path, NULL);
560 void strbuf_repo_worktree_path(struct strbuf *sb,
561 const struct repository *repo,
562 const char *fmt, ...)
570 do_worktree_path(repo, sb, fmt, args);
574 /* Returns 0 on success, negative on failure. */
575 static int do_submodule_path(struct strbuf *buf, const char *path,
576 const char *fmt, va_list args)
578 struct strbuf git_submodule_common_dir = STRBUF_INIT;
579 struct strbuf git_submodule_dir = STRBUF_INIT;
582 ret = submodule_to_gitdir(&git_submodule_dir, path);
586 strbuf_complete(&git_submodule_dir, '/');
587 strbuf_addbuf(buf, &git_submodule_dir);
588 strbuf_vaddf(buf, fmt, args);
590 if (get_common_dir_noenv(&git_submodule_common_dir, git_submodule_dir.buf))
591 update_common_dir(buf, git_submodule_dir.len, git_submodule_common_dir.buf);
593 strbuf_cleanup_path(buf);
596 strbuf_release(&git_submodule_dir);
597 strbuf_release(&git_submodule_common_dir);
601 char *git_pathdup_submodule(const char *path, const char *fmt, ...)
605 struct strbuf buf = STRBUF_INIT;
607 err = do_submodule_path(&buf, path, fmt, args);
610 strbuf_release(&buf);
613 return strbuf_detach(&buf, NULL);
616 int strbuf_git_path_submodule(struct strbuf *buf, const char *path,
617 const char *fmt, ...)
622 err = do_submodule_path(buf, path, fmt, args);
628 static void do_git_common_path(const struct repository *repo,
633 strbuf_addstr(buf, repo->commondir);
634 if (buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
635 strbuf_addch(buf, '/');
636 strbuf_vaddf(buf, fmt, args);
637 strbuf_cleanup_path(buf);
640 const char *git_common_path(const char *fmt, ...)
642 struct strbuf *pathname = get_pathname();
645 do_git_common_path(the_repository, pathname, fmt, args);
647 return pathname->buf;
650 void strbuf_git_common_path(struct strbuf *sb,
651 const struct repository *repo,
652 const char *fmt, ...)
656 do_git_common_path(repo, sb, fmt, args);
660 int validate_headref(const char *path)
665 struct object_id oid;
669 if (lstat(path, &st) < 0)
672 /* Make sure it is a "refs/.." symlink */
673 if (S_ISLNK(st.st_mode)) {
674 len = readlink(path, buffer, sizeof(buffer)-1);
675 if (len >= 5 && !memcmp("refs/", buffer, 5))
681 * Anything else, just open it and try to see if it is a symbolic ref.
683 fd = open(path, O_RDONLY);
686 len = read_in_full(fd, buffer, sizeof(buffer)-1);
694 * Is it a symbolic ref?
696 if (skip_prefix(buffer, "ref:", &refname)) {
697 while (isspace(*refname))
699 if (starts_with(refname, "refs/"))
704 * Is this a detached HEAD?
706 if (!get_oid_hex(buffer, &oid))
712 static struct passwd *getpw_str(const char *username, size_t len)
715 char *username_z = xmemdupz(username, len);
716 pw = getpwnam(username_z);
722 * Return a string with ~ and ~user expanded via getpw*. If buf != NULL,
723 * then it is a newly allocated string. Returns NULL on getpw failure or
726 * If real_home is true, real_path($HOME) is used in the expansion.
728 char *expand_user_path(const char *path, int real_home)
730 struct strbuf user_path = STRBUF_INIT;
731 const char *to_copy = path;
735 if (path[0] == '~') {
736 const char *first_slash = strchrnul(path, '/');
737 const char *username = path + 1;
738 size_t username_len = first_slash - username;
739 if (username_len == 0) {
740 const char *home = getenv("HOME");
744 strbuf_add_real_path(&user_path, home);
746 strbuf_addstr(&user_path, home);
747 #ifdef GIT_WINDOWS_NATIVE
748 convert_slashes(user_path.buf);
751 struct passwd *pw = getpw_str(username, username_len);
754 strbuf_addstr(&user_path, pw->pw_dir);
756 to_copy = first_slash;
758 strbuf_addstr(&user_path, to_copy);
759 return strbuf_detach(&user_path, NULL);
761 strbuf_release(&user_path);
766 * First, one directory to try is determined by the following algorithm.
768 * (0) If "strict" is given, the path is used as given and no DWIM is
770 * (1) "~/path" to mean path under the running user's home directory;
771 * (2) "~user/path" to mean path under named user's home directory;
772 * (3) "relative/path" to mean cwd relative directory; or
773 * (4) "/absolute/path" to mean absolute directory.
775 * Unless "strict" is given, we check "%s/.git", "%s", "%s.git/.git", "%s.git"
776 * in this order. We select the first one that is a valid git repository, and
777 * chdir() to it. If none match, or we fail to chdir, we return NULL.
779 * If all goes well, we return the directory we used to chdir() (but
780 * before ~user is expanded), avoiding getcwd() resolving symbolic
781 * links. User relative paths are also returned as they are given,
782 * except DWIM suffixing.
784 const char *enter_repo(const char *path, int strict)
786 static struct strbuf validated_path = STRBUF_INIT;
787 static struct strbuf used_path = STRBUF_INIT;
793 static const char *suffix[] = {
794 "/.git", "", ".git/.git", ".git", NULL,
797 int len = strlen(path);
799 while ((1 < len) && (path[len-1] == '/'))
803 * We can handle arbitrary-sized buffers, but this remains as a
804 * sanity check on untrusted input.
809 strbuf_reset(&used_path);
810 strbuf_reset(&validated_path);
811 strbuf_add(&used_path, path, len);
812 strbuf_add(&validated_path, path, len);
814 if (used_path.buf[0] == '~') {
815 char *newpath = expand_user_path(used_path.buf, 0);
818 strbuf_attach(&used_path, newpath, strlen(newpath),
821 for (i = 0; suffix[i]; i++) {
823 size_t baselen = used_path.len;
824 strbuf_addstr(&used_path, suffix[i]);
825 if (!stat(used_path.buf, &st) &&
826 (S_ISREG(st.st_mode) ||
827 (S_ISDIR(st.st_mode) && is_git_directory(used_path.buf)))) {
828 strbuf_addstr(&validated_path, suffix[i]);
831 strbuf_setlen(&used_path, baselen);
835 gitfile = read_gitfile(used_path.buf);
837 strbuf_reset(&used_path);
838 strbuf_addstr(&used_path, gitfile);
840 if (chdir(used_path.buf))
842 path = validated_path.buf;
845 const char *gitfile = read_gitfile(path);
852 if (is_git_directory(".")) {
854 check_repository_format();
861 static int calc_shared_perm(int mode)
865 if (get_shared_repository() < 0)
866 tweak = -get_shared_repository();
868 tweak = get_shared_repository();
870 if (!(mode & S_IWUSR))
873 /* Copy read bits to execute bits */
874 tweak |= (tweak & 0444) >> 2;
875 if (get_shared_repository() < 0)
876 mode = (mode & ~0777) | tweak;
884 int adjust_shared_perm(const char *path)
886 int old_mode, new_mode;
888 if (!get_shared_repository())
890 if (get_st_mode_bits(path, &old_mode) < 0)
893 new_mode = calc_shared_perm(old_mode);
894 if (S_ISDIR(old_mode)) {
895 /* Copy read bits to execute bits */
896 new_mode |= (new_mode & 0444) >> 2;
897 new_mode |= FORCE_DIR_SET_GID;
900 if (((old_mode ^ new_mode) & ~S_IFMT) &&
901 chmod(path, (new_mode & ~S_IFMT)) < 0)
906 void safe_create_dir(const char *dir, int share)
908 if (mkdir(dir, 0777) < 0) {
909 if (errno != EEXIST) {
914 else if (share && adjust_shared_perm(dir))
915 die(_("Could not make %s writable by group"), dir);
918 static int have_same_root(const char *path1, const char *path2)
920 int is_abs1, is_abs2;
922 is_abs1 = is_absolute_path(path1);
923 is_abs2 = is_absolute_path(path2);
924 return (is_abs1 && is_abs2 && tolower(path1[0]) == tolower(path2[0])) ||
925 (!is_abs1 && !is_abs2);
929 * Give path as relative to prefix.
931 * The strbuf may or may not be used, so do not assume it contains the
934 const char *relative_path(const char *in, const char *prefix,
937 int in_len = in ? strlen(in) : 0;
938 int prefix_len = prefix ? strlen(prefix) : 0;
945 else if (!prefix_len)
948 if (have_same_root(in, prefix))
949 /* bypass dos_drive, for "c:" is identical to "C:" */
950 i = j = has_dos_drive_prefix(in);
955 while (i < prefix_len && j < in_len && prefix[i] == in[j]) {
956 if (is_dir_sep(prefix[i])) {
957 while (is_dir_sep(prefix[i]))
959 while (is_dir_sep(in[j]))
970 /* "prefix" seems like prefix of "in" */
973 * but "/foo" is not a prefix of "/foobar"
974 * (i.e. prefix not end with '/')
976 prefix_off < prefix_len) {
978 /* in="/a/b", prefix="/a/b" */
980 } else if (is_dir_sep(in[j])) {
981 /* in="/a/b/c", prefix="/a/b" */
982 while (is_dir_sep(in[j]))
986 /* in="/a/bbb/c", prefix="/a/b" */
990 /* "in" is short than "prefix" */
992 /* "in" not end with '/' */
994 if (is_dir_sep(prefix[i])) {
995 /* in="/a/b", prefix="/a/b/c/" */
996 while (is_dir_sep(prefix[i]))
1004 if (i >= prefix_len) {
1012 strbuf_grow(sb, in_len);
1014 while (i < prefix_len) {
1015 if (is_dir_sep(prefix[i])) {
1016 strbuf_addstr(sb, "../");
1017 while (is_dir_sep(prefix[i]))
1023 if (!is_dir_sep(prefix[prefix_len - 1]))
1024 strbuf_addstr(sb, "../");
1026 strbuf_addstr(sb, in);
1032 * A simpler implementation of relative_path
1034 * Get relative path by removing "prefix" from "in". This function
1035 * first appears in v1.5.6-1-g044bbbc, and makes git_dir shorter
1036 * to increase performance when traversing the path to work_tree.
1038 const char *remove_leading_path(const char *in, const char *prefix)
1040 static struct strbuf buf = STRBUF_INIT;
1043 if (!prefix || !prefix[0])
1046 if (is_dir_sep(prefix[i])) {
1047 if (!is_dir_sep(in[j]))
1049 while (is_dir_sep(prefix[i]))
1051 while (is_dir_sep(in[j]))
1054 } else if (in[j] != prefix[i]) {
1061 /* "/foo" is a prefix of "/foo" */
1063 /* "/foo" is not a prefix of "/foobar" */
1064 !is_dir_sep(prefix[i-1]) && !is_dir_sep(in[j])
1067 while (is_dir_sep(in[j]))
1072 strbuf_addstr(&buf, ".");
1074 strbuf_addstr(&buf, in + j);
1079 * It is okay if dst == src, but they should not overlap otherwise.
1081 * Performs the following normalizations on src, storing the result in dst:
1082 * - Ensures that components are separated by '/' (Windows only)
1083 * - Squashes sequences of '/' except "//server/share" on Windows
1084 * - Removes "." components.
1085 * - Removes ".." components, and the components the precede them.
1086 * Returns failure (non-zero) if a ".." component appears as first path
1087 * component anytime during the normalization. Otherwise, returns success (0).
1089 * Note that this function is purely textual. It does not follow symlinks,
1090 * verify the existence of the path, or make any system calls.
1092 * prefix_len != NULL is for a specific case of prefix_pathspec():
1093 * assume that src == dst and src[0..prefix_len-1] is already
1094 * normalized, any time "../" eats up to the prefix_len part,
1095 * prefix_len is reduced. In the end prefix_len is the remaining
1096 * prefix that has not been overridden by user pathspec.
1098 * NEEDSWORK: This function doesn't perform normalization w.r.t. trailing '/'.
1099 * For everything but the root folder itself, the normalized path should not
1100 * end with a '/', then the callers need to be fixed up accordingly.
1103 int normalize_path_copy_len(char *dst, const char *src, int *prefix_len)
1109 * Copy initial part of absolute path: "/", "C:/", "//server/share/".
1111 end = src + offset_1st_component(src);
1120 while (is_dir_sep(*src))
1127 * A path component that begins with . could be
1129 * (1) "." and ends -- ignore and terminate.
1130 * (2) "./" -- ignore them, eat slash and continue.
1131 * (3) ".." and ends -- strip one and terminate.
1132 * (4) "../" -- strip one, eat slash and continue.
1138 } else if (is_dir_sep(src[1])) {
1141 while (is_dir_sep(*src))
1144 } else if (src[1] == '.') {
1149 } else if (is_dir_sep(src[2])) {
1152 while (is_dir_sep(*src))
1159 /* copy up to the next '/', and eat all '/' */
1160 while ((c = *src++) != '\0' && !is_dir_sep(c))
1162 if (is_dir_sep(c)) {
1164 while (is_dir_sep(c))
1173 * dst0..dst is prefix portion, and dst[-1] is '/';
1176 dst--; /* go to trailing '/' */
1179 /* Windows: dst[-1] cannot be backslash anymore */
1180 while (dst0 < dst && dst[-1] != '/')
1182 if (prefix_len && *prefix_len > dst - dst0)
1183 *prefix_len = dst - dst0;
1189 int normalize_path_copy(char *dst, const char *src)
1191 return normalize_path_copy_len(dst, src, NULL);
1195 * path = Canonical absolute path
1196 * prefixes = string_list containing normalized, absolute paths without
1197 * trailing slashes (except for the root directory, which is denoted by "/").
1199 * Determines, for each path in prefixes, whether the "prefix"
1200 * is an ancestor directory of path. Returns the length of the longest
1201 * ancestor directory, excluding any trailing slashes, or -1 if no prefix
1202 * is an ancestor. (Note that this means 0 is returned if prefixes is
1203 * ["/"].) "/foo" is not considered an ancestor of "/foobar". Directories
1204 * are not considered to be their own ancestors. path must be in a
1205 * canonical form: empty components, or "." or ".." components are not
1208 int longest_ancestor_length(const char *path, struct string_list *prefixes)
1210 int i, max_len = -1;
1212 if (!strcmp(path, "/"))
1215 for (i = 0; i < prefixes->nr; i++) {
1216 const char *ceil = prefixes->items[i].string;
1217 int len = strlen(ceil);
1219 if (len == 1 && ceil[0] == '/')
1220 len = 0; /* root matches anything, with length 0 */
1221 else if (!strncmp(path, ceil, len) && path[len] == '/')
1222 ; /* match of length len */
1224 continue; /* no match */
1233 /* strip arbitrary amount of directory separators at end of path */
1234 static inline int chomp_trailing_dir_sep(const char *path, int len)
1236 while (len && is_dir_sep(path[len - 1]))
1242 * If path ends with suffix (complete path components), returns the offset of
1243 * the last character in the path before the suffix (sans trailing directory
1244 * separators), and -1 otherwise.
1246 static ssize_t stripped_path_suffix_offset(const char *path, const char *suffix)
1248 int path_len = strlen(path), suffix_len = strlen(suffix);
1250 while (suffix_len) {
1254 if (is_dir_sep(path[path_len - 1])) {
1255 if (!is_dir_sep(suffix[suffix_len - 1]))
1257 path_len = chomp_trailing_dir_sep(path, path_len);
1258 suffix_len = chomp_trailing_dir_sep(suffix, suffix_len);
1260 else if (path[--path_len] != suffix[--suffix_len])
1264 if (path_len && !is_dir_sep(path[path_len - 1]))
1266 return chomp_trailing_dir_sep(path, path_len);
1270 * Returns true if the path ends with components, considering only complete path
1271 * components, and false otherwise.
1273 int ends_with_path_components(const char *path, const char *components)
1275 return stripped_path_suffix_offset(path, components) != -1;
1279 * If path ends with suffix (complete path components), returns the
1280 * part before suffix (sans trailing directory separators).
1281 * Otherwise returns NULL.
1283 char *strip_path_suffix(const char *path, const char *suffix)
1285 ssize_t offset = stripped_path_suffix_offset(path, suffix);
1287 return offset == -1 ? NULL : xstrndup(path, offset);
1290 int daemon_avoid_alias(const char *p)
1295 * This resurrects the belts and suspenders paranoia check by HPA
1296 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
1297 * does not do getcwd() based path canonicalization.
1299 * sl becomes true immediately after seeing '/' and continues to
1300 * be true as long as dots continue after that without intervening
1301 * non-dot character.
1303 if (!p || (*p != '/' && *p != '~'))
1313 else if (ch == '/') {
1315 /* reject //, /./ and /../ */
1320 if (0 < ndot && ndot < 3)
1321 /* reject /.$ and /..$ */
1330 else if (ch == '/') {
1337 static int only_spaces_and_periods(const char *path, size_t len, size_t skip)
1345 if (c != ' ' && c != '.')
1351 int is_ntfs_dotgit(const char *name)
1355 for (len = 0; ; len++)
1356 if (!name[len] || name[len] == '\\' || is_dir_sep(name[len])) {
1357 if (only_spaces_and_periods(name, len, 4) &&
1358 !strncasecmp(name, ".git", 4))
1360 if (only_spaces_and_periods(name, len, 5) &&
1361 !strncasecmp(name, "git~1", 5))
1363 if (name[len] != '\\')
1370 static int is_ntfs_dot_generic(const char *name,
1371 const char *dotgit_name,
1373 const char *dotgit_ntfs_shortname_prefix)
1378 if ((name[0] == '.' && !strncasecmp(name + 1, dotgit_name, len))) {
1380 only_spaces_and_periods:
1385 if (c != ' ' && c != '.')
1391 * Is it a regular NTFS short name, i.e. shortened to 6 characters,
1392 * followed by ~1, ... ~4?
1394 if (!strncasecmp(name, dotgit_name, 6) && name[6] == '~' &&
1395 name[7] >= '1' && name[7] <= '4') {
1397 goto only_spaces_and_periods;
1401 * Is it a fall-back NTFS short name (for details, see
1402 * https://en.wikipedia.org/wiki/8.3_filename?
1404 for (i = 0, saw_tilde = 0; i < 8; i++)
1405 if (name[i] == '\0')
1407 else if (saw_tilde) {
1408 if (name[i] < '0' || name[i] > '9')
1410 } else if (name[i] == '~') {
1411 if (name[++i] < '1' || name[i] > '9')
1416 else if (name[i] & 0x80) {
1418 * We know our needles contain only ASCII, so we clamp
1419 * here to make the results of tolower() sane.
1422 } else if (tolower(name[i]) != dotgit_ntfs_shortname_prefix[i])
1425 goto only_spaces_and_periods;
1429 * Inline helper to make sure compiler resolves strlen() on literals at
1432 static inline int is_ntfs_dot_str(const char *name, const char *dotgit_name,
1433 const char *dotgit_ntfs_shortname_prefix)
1435 return is_ntfs_dot_generic(name, dotgit_name, strlen(dotgit_name),
1436 dotgit_ntfs_shortname_prefix);
1439 int is_ntfs_dotgitmodules(const char *name)
1441 return is_ntfs_dot_str(name, "gitmodules", "gi7eba");
1444 int is_ntfs_dotgitignore(const char *name)
1446 return is_ntfs_dot_str(name, "gitignore", "gi250a");
1449 int is_ntfs_dotgitattributes(const char *name)
1451 return is_ntfs_dot_str(name, "gitattributes", "gi7d29");
1454 int looks_like_command_line_option(const char *str)
1456 return str && str[0] == '-';
1459 char *xdg_config_home(const char *filename)
1461 const char *home, *config_home;
1464 config_home = getenv("XDG_CONFIG_HOME");
1465 if (config_home && *config_home)
1466 return mkpathdup("%s/git/%s", config_home, filename);
1468 home = getenv("HOME");
1470 return mkpathdup("%s/.config/git/%s", home, filename);
1474 char *xdg_cache_home(const char *filename)
1476 const char *home, *cache_home;
1479 cache_home = getenv("XDG_CACHE_HOME");
1480 if (cache_home && *cache_home)
1481 return mkpathdup("%s/git/%s", cache_home, filename);
1483 home = getenv("HOME");
1485 return mkpathdup("%s/.cache/git/%s", home, filename);
1489 REPO_GIT_PATH_FUNC(cherry_pick_head, "CHERRY_PICK_HEAD")
1490 REPO_GIT_PATH_FUNC(revert_head, "REVERT_HEAD")
1491 REPO_GIT_PATH_FUNC(squash_msg, "SQUASH_MSG")
1492 REPO_GIT_PATH_FUNC(merge_msg, "MERGE_MSG")
1493 REPO_GIT_PATH_FUNC(merge_rr, "MERGE_RR")
1494 REPO_GIT_PATH_FUNC(merge_mode, "MERGE_MODE")
1495 REPO_GIT_PATH_FUNC(merge_head, "MERGE_HEAD")
1496 REPO_GIT_PATH_FUNC(fetch_head, "FETCH_HEAD")
1497 REPO_GIT_PATH_FUNC(shallow, "shallow")