2 * Utilities for paths and pathnames
5 #include "git-compat-util.h"
7 #include "environment.h"
9 #include "repository.h"
11 #include "string-list.h"
15 #include "submodule-config.h"
18 #include "object-store-ll.h"
22 static int get_st_mode_bits(const char *path
, int *mode
)
25 if (lstat(path
, &st
) < 0)
31 struct strbuf
*get_pathname(void)
33 static struct strbuf pathname_array
[4] = {
34 STRBUF_INIT
, STRBUF_INIT
, STRBUF_INIT
, STRBUF_INIT
37 struct strbuf
*sb
= &pathname_array
[index
];
38 index
= (index
+ 1) % ARRAY_SIZE(pathname_array
);
43 static const char *cleanup_path(const char *path
)
46 if (skip_prefix(path
, "./", &path
)) {
53 static void strbuf_cleanup_path(struct strbuf
*sb
)
55 const char *path
= cleanup_path(sb
->buf
);
57 strbuf_remove(sb
, 0, path
- sb
->buf
);
60 static int dir_prefix(const char *buf
, const char *dir
)
62 int len
= strlen(dir
);
63 return !strncmp(buf
, dir
, len
) &&
64 (is_dir_sep(buf
[len
]) || buf
[len
] == '\0');
67 /* $buf =~ m|$dir/+$file| but without regex */
68 static int is_dir_file(const char *buf
, const char *dir
, const char *file
)
70 int len
= strlen(dir
);
71 if (strncmp(buf
, dir
, len
) || !is_dir_sep(buf
[len
]))
73 while (is_dir_sep(buf
[len
]))
75 return !strcmp(buf
+ len
, file
);
78 static void replace_dir(struct strbuf
*buf
, int len
, const char *newdir
)
80 int newlen
= strlen(newdir
);
81 int need_sep
= (buf
->buf
[len
] && !is_dir_sep(buf
->buf
[len
])) &&
82 !is_dir_sep(newdir
[newlen
- 1]);
84 len
--; /* keep one char, to be replaced with '/' */
85 strbuf_splice(buf
, 0, len
, newdir
, newlen
);
87 buf
->buf
[newlen
] = '/';
91 /* Not considered garbage for report_linked_checkout_garbage */
92 unsigned ignore_garbage
:1;
94 /* Belongs to the common dir, though it may contain paths that don't */
99 static struct common_dir common_list
[] = {
100 { 0, 1, 1, "branches" },
101 { 0, 1, 1, "common" },
102 { 0, 1, 1, "hooks" },
104 { 0, 0, 0, "info/sparse-checkout" },
106 { 1, 0, 0, "logs/HEAD" },
107 { 0, 1, 0, "logs/refs/bisect" },
108 { 0, 1, 0, "logs/refs/rewritten" },
109 { 0, 1, 0, "logs/refs/worktree" },
110 { 0, 1, 1, "lost-found" },
111 { 0, 1, 1, "objects" },
113 { 0, 1, 0, "refs/bisect" },
114 { 0, 1, 0, "refs/rewritten" },
115 { 0, 1, 0, "refs/worktree" },
116 { 0, 1, 1, "remotes" },
117 { 0, 1, 1, "worktrees" },
118 { 0, 1, 1, "rr-cache" },
120 { 0, 0, 1, "config" },
121 { 1, 0, 1, "gc.pid" },
122 { 0, 0, 1, "packed-refs" },
123 { 0, 0, 1, "shallow" },
128 * A compressed trie. A trie node consists of zero or more characters that
129 * are common to all elements with this prefix, optionally followed by some
130 * children. If value is not NULL, the trie node is a terminal node.
132 * For example, consider the following set of strings:
138 * The trie would look like:
139 * root: len = 0, children a and d non-NULL, value = NULL.
140 * a: len = 2, contents = bc, value = (data for "abc")
141 * d: len = 2, contents = ef, children i non-NULL, value = (data for "def")
142 * i: len = 3, contents = nit, children e and i non-NULL, value = NULL
143 * e: len = 0, children all NULL, value = (data for "definite")
144 * i: len = 2, contents = on, children all NULL,
145 * value = (data for "definition")
148 struct trie
*children
[256];
154 static struct trie
*make_trie_node(const char *key
, void *value
)
156 struct trie
*new_node
= xcalloc(1, sizeof(*new_node
));
157 new_node
->len
= strlen(key
);
159 new_node
->contents
= xmalloc(new_node
->len
);
160 memcpy(new_node
->contents
, key
, new_node
->len
);
162 new_node
->value
= value
;
167 * Add a key/value pair to a trie. The key is assumed to be \0-terminated.
168 * If there was an existing value for this key, return it.
170 static void *add_to_trie(struct trie
*root
, const char *key
, void *value
)
177 /* we have reached the end of the key */
183 for (i
= 0; i
< root
->len
; i
++) {
184 if (root
->contents
[i
] == key
[i
])
188 * Split this node: child will contain this node's
191 child
= xmalloc(sizeof(*child
));
192 memcpy(child
->children
, root
->children
, sizeof(root
->children
));
194 child
->len
= root
->len
- i
- 1;
196 child
->contents
= xstrndup(root
->contents
+ i
+ 1,
199 child
->value
= root
->value
;
203 memset(root
->children
, 0, sizeof(root
->children
));
204 root
->children
[(unsigned char)root
->contents
[i
]] = child
;
206 /* This is the newly-added child. */
207 root
->children
[(unsigned char)key
[i
]] =
208 make_trie_node(key
+ i
+ 1, value
);
212 /* We have matched the entire compressed section */
214 child
= root
->children
[(unsigned char)key
[root
->len
]];
216 return add_to_trie(child
, key
+ root
->len
+ 1, value
);
218 child
= make_trie_node(key
+ root
->len
+ 1, value
);
219 root
->children
[(unsigned char)key
[root
->len
]] = child
;
229 typedef int (*match_fn
)(const char *unmatched
, void *value
, void *baton
);
232 * Search a trie for some key. Find the longest /-or-\0-terminated
233 * prefix of the key for which the trie contains a value. If there is
234 * no such prefix, return -1. Otherwise call fn with the unmatched
235 * portion of the key and the found value. If fn returns 0 or
236 * positive, then return its return value. If fn returns negative,
237 * then call fn with the next-longest /-terminated prefix of the key
238 * (i.e. a parent directory) for which the trie contains a value, and
239 * handle its return value the same way. If there is no shorter
240 * /-terminated prefix with a value left, then return the negative
241 * return value of the most recent fn invocation.
243 * The key is partially normalized: consecutive slashes are skipped.
245 * For example, consider the trie containing only [logs,
246 * logs/refs/bisect], both with values, but not logs/refs.
248 * | key | unmatched | prefix to node | return value |
249 * |--------------------|----------------|------------------|--------------|
250 * | a | not called | n/a | -1 |
251 * | logstore | not called | n/a | -1 |
252 * | logs | \0 | logs | as per fn |
253 * | logs/ | / | logs | as per fn |
254 * | logs/refs | /refs | logs | as per fn |
255 * | logs/refs/ | /refs/ | logs | as per fn |
256 * | logs/refs/b | /refs/b | logs | as per fn |
257 * | logs/refs/bisected | /refs/bisected | logs | as per fn |
258 * | logs/refs/bisect | \0 | logs/refs/bisect | as per fn |
259 * | logs/refs/bisect/ | / | logs/refs/bisect | as per fn |
260 * | logs/refs/bisect/a | /a | logs/refs/bisect | as per fn |
261 * | (If fn in the previous line returns -1, then fn is called once more:) |
262 * | logs/refs/bisect/a | /refs/bisect/a | logs | as per fn |
263 * |--------------------|----------------|------------------|--------------|
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 */
295 return fn(key
, root
->value
, baton
);
300 /* Partial path normalization: skip consecutive slashes */
301 while (key
[0] == '/' && key
[1] == '/')
304 child
= root
->children
[(unsigned char)*key
];
306 result
= trie_find(child
, key
+ 1, fn
, baton
);
310 if (result
>= 0 || (*key
!= '/' && *key
!= 0))
313 return fn(key
, root
->value
, baton
);
318 static struct trie common_trie
;
319 static int common_trie_done_setup
;
321 static void init_common_trie(void)
323 struct common_dir
*p
;
325 if (common_trie_done_setup
)
328 for (p
= common_list
; p
->path
; p
++)
329 add_to_trie(&common_trie
, p
->path
, p
);
331 common_trie_done_setup
= 1;
335 * Helper function for update_common_dir: returns 1 if the dir
338 static int check_common(const char *unmatched
, void *value
,
341 struct common_dir
*dir
= value
;
343 if (dir
->is_dir
&& (unmatched
[0] == 0 || unmatched
[0] == '/'))
344 return dir
->is_common
;
346 if (!dir
->is_dir
&& unmatched
[0] == 0)
347 return dir
->is_common
;
352 static void update_common_dir(struct strbuf
*buf
, int git_dir_len
,
353 const char *common_dir
)
355 char *base
= buf
->buf
+ git_dir_len
;
356 int has_lock_suffix
= strbuf_strip_suffix(buf
, LOCK_SUFFIX
);
359 if (trie_find(&common_trie
, base
, check_common
, NULL
) > 0)
360 replace_dir(buf
, git_dir_len
, common_dir
);
363 strbuf_addstr(buf
, LOCK_SUFFIX
);
366 void report_linked_checkout_garbage(struct repository
*r
)
368 struct strbuf sb
= STRBUF_INIT
;
369 const struct common_dir
*p
;
372 if (!r
->different_commondir
)
374 strbuf_addf(&sb
, "%s/", r
->gitdir
);
376 for (p
= common_list
; p
->path
; p
++) {
377 const char *path
= p
->path
;
378 if (p
->ignore_garbage
)
380 strbuf_setlen(&sb
, len
);
381 strbuf_addstr(&sb
, path
);
382 if (file_exists(sb
.buf
))
383 report_garbage(PACKDIR_FILE_GARBAGE
, sb
.buf
);
388 static void adjust_git_path(const struct repository
*repo
,
389 struct strbuf
*buf
, int git_dir_len
)
391 const char *base
= buf
->buf
+ git_dir_len
;
392 if (is_dir_file(base
, "info", "grafts"))
393 strbuf_splice(buf
, 0, buf
->len
,
394 repo
->graft_file
, strlen(repo
->graft_file
));
395 else if (!strcmp(base
, "index"))
396 strbuf_splice(buf
, 0, buf
->len
,
397 repo
->index_file
, strlen(repo
->index_file
));
398 else if (dir_prefix(base
, "objects"))
399 replace_dir(buf
, git_dir_len
+ 7, repo
->objects
->odb
->path
);
400 else if (git_hooks_path
&& dir_prefix(base
, "hooks"))
401 replace_dir(buf
, git_dir_len
+ 5, git_hooks_path
);
402 else if (repo
->different_commondir
)
403 update_common_dir(buf
, git_dir_len
, repo
->commondir
);
406 static void strbuf_worktree_gitdir(struct strbuf
*buf
,
407 const struct repository
*repo
,
408 const struct worktree
*wt
)
411 strbuf_addstr(buf
, repo
->gitdir
);
413 strbuf_addstr(buf
, repo
->commondir
);
415 strbuf_git_common_path(buf
, repo
, "worktrees/%s", wt
->id
);
418 void repo_git_pathv(const struct repository
*repo
,
419 const struct worktree
*wt
, struct strbuf
*buf
,
420 const char *fmt
, va_list args
)
423 strbuf_worktree_gitdir(buf
, repo
, wt
);
424 if (buf
->len
&& !is_dir_sep(buf
->buf
[buf
->len
- 1]))
425 strbuf_addch(buf
, '/');
426 gitdir_len
= buf
->len
;
427 strbuf_vaddf(buf
, fmt
, args
);
429 adjust_git_path(repo
, buf
, gitdir_len
);
430 strbuf_cleanup_path(buf
);
433 char *repo_git_path(const struct repository
*repo
,
434 const char *fmt
, ...)
436 struct strbuf path
= STRBUF_INIT
;
439 repo_git_pathv(repo
, NULL
, &path
, fmt
, args
);
441 return strbuf_detach(&path
, NULL
);
444 void strbuf_repo_git_path(struct strbuf
*sb
,
445 const struct repository
*repo
,
446 const char *fmt
, ...)
450 repo_git_pathv(repo
, NULL
, sb
, fmt
, args
);
454 char *mkpathdup(const char *fmt
, ...)
456 struct strbuf sb
= STRBUF_INIT
;
459 strbuf_vaddf(&sb
, fmt
, args
);
461 strbuf_cleanup_path(&sb
);
462 return strbuf_detach(&sb
, NULL
);
465 const char *mkpath(const char *fmt
, ...)
468 struct strbuf
*pathname
= get_pathname();
470 strbuf_vaddf(pathname
, fmt
, args
);
472 return cleanup_path(pathname
->buf
);
475 const char *worktree_git_path(struct repository
*r
,
476 const struct worktree
*wt
, const char *fmt
, ...)
478 struct strbuf
*pathname
= get_pathname();
481 if (wt
&& wt
->repo
!= r
)
482 BUG("worktree not connected to expected repository");
485 repo_git_pathv(r
, wt
, pathname
, fmt
, args
);
487 return pathname
->buf
;
490 static void do_worktree_path(const struct repository
*repo
,
492 const char *fmt
, va_list args
)
494 strbuf_addstr(buf
, repo
->worktree
);
495 if(buf
->len
&& !is_dir_sep(buf
->buf
[buf
->len
- 1]))
496 strbuf_addch(buf
, '/');
498 strbuf_vaddf(buf
, fmt
, args
);
499 strbuf_cleanup_path(buf
);
502 char *repo_worktree_path(const struct repository
*repo
, const char *fmt
, ...)
504 struct strbuf path
= STRBUF_INIT
;
511 do_worktree_path(repo
, &path
, fmt
, args
);
514 return strbuf_detach(&path
, NULL
);
517 void strbuf_repo_worktree_path(struct strbuf
*sb
,
518 const struct repository
*repo
,
519 const char *fmt
, ...)
527 do_worktree_path(repo
, sb
, fmt
, args
);
531 /* Returns 0 on success, negative on failure. */
532 static int do_submodule_path(struct strbuf
*buf
, const char *path
,
533 const char *fmt
, va_list args
)
535 struct strbuf git_submodule_common_dir
= STRBUF_INIT
;
536 struct strbuf git_submodule_dir
= STRBUF_INIT
;
539 ret
= submodule_to_gitdir(&git_submodule_dir
, path
);
543 strbuf_complete(&git_submodule_dir
, '/');
544 strbuf_addbuf(buf
, &git_submodule_dir
);
545 strbuf_vaddf(buf
, fmt
, args
);
547 if (get_common_dir_noenv(&git_submodule_common_dir
, git_submodule_dir
.buf
))
548 update_common_dir(buf
, git_submodule_dir
.len
, git_submodule_common_dir
.buf
);
550 strbuf_cleanup_path(buf
);
553 strbuf_release(&git_submodule_dir
);
554 strbuf_release(&git_submodule_common_dir
);
558 char *git_pathdup_submodule(const char *path
, const char *fmt
, ...)
562 struct strbuf buf
= STRBUF_INIT
;
564 err
= do_submodule_path(&buf
, path
, fmt
, args
);
567 strbuf_release(&buf
);
570 return strbuf_detach(&buf
, NULL
);
573 int strbuf_git_path_submodule(struct strbuf
*buf
, const char *path
,
574 const char *fmt
, ...)
579 err
= do_submodule_path(buf
, path
, fmt
, args
);
585 void repo_common_pathv(const struct repository
*repo
,
590 strbuf_addstr(sb
, repo
->commondir
);
591 if (sb
->len
&& !is_dir_sep(sb
->buf
[sb
->len
- 1]))
592 strbuf_addch(sb
, '/');
593 strbuf_vaddf(sb
, fmt
, args
);
594 strbuf_cleanup_path(sb
);
597 void strbuf_git_common_path(struct strbuf
*sb
,
598 const struct repository
*repo
,
599 const char *fmt
, ...)
603 repo_common_pathv(repo
, sb
, fmt
, args
);
607 static struct passwd
*getpw_str(const char *username
, size_t len
)
610 char *username_z
= xmemdupz(username
, len
);
611 pw
= getpwnam(username_z
);
617 * Return a string with ~ and ~user expanded via getpw*. Returns NULL on getpw
618 * failure or if path is NULL.
620 * If real_home is true, strbuf_realpath($HOME) is used in the `~/` expansion.
622 * If the path starts with `%(prefix)/`, the remainder is interpreted as
623 * relative to where Git is installed, and expanded to the absolute path.
625 char *interpolate_path(const char *path
, int real_home
)
627 struct strbuf user_path
= STRBUF_INIT
;
628 const char *to_copy
= path
;
633 if (skip_prefix(path
, "%(prefix)/", &path
))
634 return system_path(path
);
636 if (path
[0] == '~') {
637 const char *first_slash
= strchrnul(path
, '/');
638 const char *username
= path
+ 1;
639 size_t username_len
= first_slash
- username
;
640 if (username_len
== 0) {
641 const char *home
= getenv("HOME");
645 strbuf_add_real_path(&user_path
, home
);
647 strbuf_addstr(&user_path
, home
);
648 #ifdef GIT_WINDOWS_NATIVE
649 convert_slashes(user_path
.buf
);
652 struct passwd
*pw
= getpw_str(username
, username_len
);
655 strbuf_addstr(&user_path
, pw
->pw_dir
);
657 to_copy
= first_slash
;
659 strbuf_addstr(&user_path
, to_copy
);
660 return strbuf_detach(&user_path
, NULL
);
662 strbuf_release(&user_path
);
667 * First, one directory to try is determined by the following algorithm.
669 * (0) If "strict" is given, the path is used as given and no DWIM is
671 * (1) "~/path" to mean path under the running user's home directory;
672 * (2) "~user/path" to mean path under named user's home directory;
673 * (3) "relative/path" to mean cwd relative directory; or
674 * (4) "/absolute/path" to mean absolute directory.
676 * Unless "strict" is given, we check "%s/.git", "%s", "%s.git/.git", "%s.git"
677 * in this order. We select the first one that is a valid git repository, and
678 * chdir() to it. If none match, or we fail to chdir, we return NULL.
680 * If all goes well, we return the directory we used to chdir() (but
681 * before ~user is expanded), avoiding getcwd() resolving symbolic
682 * links. User relative paths are also returned as they are given,
683 * except DWIM suffixing.
685 const char *enter_repo(const char *path
, int strict
)
687 static struct strbuf validated_path
= STRBUF_INIT
;
688 static struct strbuf used_path
= STRBUF_INIT
;
694 static const char *suffix
[] = {
695 "/.git", "", ".git/.git", ".git", NULL
,
698 int len
= strlen(path
);
700 while ((1 < len
) && (path
[len
-1] == '/'))
704 * We can handle arbitrary-sized buffers, but this remains as a
705 * sanity check on untrusted input.
710 strbuf_reset(&used_path
);
711 strbuf_reset(&validated_path
);
712 strbuf_add(&used_path
, path
, len
);
713 strbuf_add(&validated_path
, path
, len
);
715 if (used_path
.buf
[0] == '~') {
716 char *newpath
= interpolate_path(used_path
.buf
, 0);
719 strbuf_attach(&used_path
, newpath
, strlen(newpath
),
722 for (i
= 0; suffix
[i
]; i
++) {
724 size_t baselen
= used_path
.len
;
725 strbuf_addstr(&used_path
, suffix
[i
]);
726 if (!stat(used_path
.buf
, &st
) &&
727 (S_ISREG(st
.st_mode
) ||
728 (S_ISDIR(st
.st_mode
) && is_git_directory(used_path
.buf
)))) {
729 strbuf_addstr(&validated_path
, suffix
[i
]);
732 strbuf_setlen(&used_path
, baselen
);
736 gitfile
= read_gitfile(used_path
.buf
);
737 die_upon_dubious_ownership(gitfile
, NULL
, used_path
.buf
);
739 strbuf_reset(&used_path
);
740 strbuf_addstr(&used_path
, gitfile
);
742 if (chdir(used_path
.buf
))
744 path
= validated_path
.buf
;
747 const char *gitfile
= read_gitfile(path
);
748 die_upon_dubious_ownership(gitfile
, NULL
, path
);
755 if (is_git_directory(".")) {
757 check_repository_format(NULL
);
764 int calc_shared_perm(int mode
)
768 if (get_shared_repository() < 0)
769 tweak
= -get_shared_repository();
771 tweak
= get_shared_repository();
773 if (!(mode
& S_IWUSR
))
776 /* Copy read bits to execute bits */
777 tweak
|= (tweak
& 0444) >> 2;
778 if (get_shared_repository() < 0)
779 mode
= (mode
& ~0777) | tweak
;
787 int adjust_shared_perm(const char *path
)
789 int old_mode
, new_mode
;
791 if (!get_shared_repository())
793 if (get_st_mode_bits(path
, &old_mode
) < 0)
796 new_mode
= calc_shared_perm(old_mode
);
797 if (S_ISDIR(old_mode
)) {
798 /* Copy read bits to execute bits */
799 new_mode
|= (new_mode
& 0444) >> 2;
802 * g+s matters only if any extra access is granted
803 * based on group membership.
805 if (FORCE_DIR_SET_GID
&& (new_mode
& 060))
806 new_mode
|= FORCE_DIR_SET_GID
;
809 if (((old_mode
^ new_mode
) & ~S_IFMT
) &&
810 chmod(path
, (new_mode
& ~S_IFMT
)) < 0)
815 void safe_create_dir(const char *dir
, int share
)
817 if (mkdir(dir
, 0777) < 0) {
818 if (errno
!= EEXIST
) {
823 else if (share
&& adjust_shared_perm(dir
))
824 die(_("Could not make %s writable by group"), dir
);
827 static int have_same_root(const char *path1
, const char *path2
)
829 int is_abs1
, is_abs2
;
831 is_abs1
= is_absolute_path(path1
);
832 is_abs2
= is_absolute_path(path2
);
833 return (is_abs1
&& is_abs2
&& tolower(path1
[0]) == tolower(path2
[0])) ||
834 (!is_abs1
&& !is_abs2
);
838 * Give path as relative to prefix.
840 * The strbuf may or may not be used, so do not assume it contains the
843 const char *relative_path(const char *in
, const char *prefix
,
846 int in_len
= in
? strlen(in
) : 0;
847 int prefix_len
= prefix
? strlen(prefix
) : 0;
854 else if (!prefix_len
)
857 if (have_same_root(in
, prefix
))
858 /* bypass dos_drive, for "c:" is identical to "C:" */
859 i
= j
= has_dos_drive_prefix(in
);
864 while (i
< prefix_len
&& j
< in_len
&& prefix
[i
] == in
[j
]) {
865 if (is_dir_sep(prefix
[i
])) {
866 while (is_dir_sep(prefix
[i
]))
868 while (is_dir_sep(in
[j
]))
879 /* "prefix" seems like prefix of "in" */
882 * but "/foo" is not a prefix of "/foobar"
883 * (i.e. prefix not end with '/')
885 prefix_off
< prefix_len
) {
887 /* in="/a/b", prefix="/a/b" */
889 } else if (is_dir_sep(in
[j
])) {
890 /* in="/a/b/c", prefix="/a/b" */
891 while (is_dir_sep(in
[j
]))
895 /* in="/a/bbb/c", prefix="/a/b" */
899 /* "in" is short than "prefix" */
901 /* "in" not end with '/' */
903 if (is_dir_sep(prefix
[i
])) {
904 /* in="/a/b", prefix="/a/b/c/" */
905 while (is_dir_sep(prefix
[i
]))
913 if (i
>= prefix_len
) {
921 strbuf_grow(sb
, in_len
);
923 while (i
< prefix_len
) {
924 if (is_dir_sep(prefix
[i
])) {
925 strbuf_addstr(sb
, "../");
926 while (is_dir_sep(prefix
[i
]))
932 if (!is_dir_sep(prefix
[prefix_len
- 1]))
933 strbuf_addstr(sb
, "../");
935 strbuf_addstr(sb
, in
);
941 * A simpler implementation of relative_path
943 * Get relative path by removing "prefix" from "in". This function
944 * first appears in v1.5.6-1-g044bbbc, and makes git_dir shorter
945 * to increase performance when traversing the path to work_tree.
947 const char *remove_leading_path(const char *in
, const char *prefix
)
949 static struct strbuf buf
= STRBUF_INIT
;
952 if (!prefix
|| !prefix
[0])
955 if (is_dir_sep(prefix
[i
])) {
956 if (!is_dir_sep(in
[j
]))
958 while (is_dir_sep(prefix
[i
]))
960 while (is_dir_sep(in
[j
]))
963 } else if (in
[j
] != prefix
[i
]) {
970 /* "/foo" is a prefix of "/foo" */
972 /* "/foo" is not a prefix of "/foobar" */
973 !is_dir_sep(prefix
[i
-1]) && !is_dir_sep(in
[j
])
976 while (is_dir_sep(in
[j
]))
981 strbuf_addstr(&buf
, ".");
983 strbuf_addstr(&buf
, in
+ j
);
988 * It is okay if dst == src, but they should not overlap otherwise.
989 * The "dst" buffer must be at least as long as "src"; normalizing may shrink
990 * the size of the path, but will never grow it.
992 * Performs the following normalizations on src, storing the result in dst:
993 * - Ensures that components are separated by '/' (Windows only)
994 * - Squashes sequences of '/' except "//server/share" on Windows
995 * - Removes "." components.
996 * - Removes ".." components, and the components the precede them.
997 * Returns failure (non-zero) if a ".." component appears as first path
998 * component anytime during the normalization. Otherwise, returns success (0).
1000 * Note that this function is purely textual. It does not follow symlinks,
1001 * verify the existence of the path, or make any system calls.
1003 * prefix_len != NULL is for a specific case of prefix_pathspec():
1004 * assume that src == dst and src[0..prefix_len-1] is already
1005 * normalized, any time "../" eats up to the prefix_len part,
1006 * prefix_len is reduced. In the end prefix_len is the remaining
1007 * prefix that has not been overridden by user pathspec.
1009 * NEEDSWORK: This function doesn't perform normalization w.r.t. trailing '/'.
1010 * For everything but the root folder itself, the normalized path should not
1011 * end with a '/', then the callers need to be fixed up accordingly.
1014 int normalize_path_copy_len(char *dst
, const char *src
, int *prefix_len
)
1020 * Copy initial part of absolute path: "/", "C:/", "//server/share/".
1022 end
= src
+ offset_1st_component(src
);
1031 while (is_dir_sep(*src
))
1038 * A path component that begins with . could be
1040 * (1) "." and ends -- ignore and terminate.
1041 * (2) "./" -- ignore them, eat slash and continue.
1042 * (3) ".." and ends -- strip one and terminate.
1043 * (4) "../" -- strip one, eat slash and continue.
1049 } else if (is_dir_sep(src
[1])) {
1052 while (is_dir_sep(*src
))
1055 } else if (src
[1] == '.') {
1060 } else if (is_dir_sep(src
[2])) {
1063 while (is_dir_sep(*src
))
1070 /* copy up to the next '/', and eat all '/' */
1071 while ((c
= *src
++) != '\0' && !is_dir_sep(c
))
1073 if (is_dir_sep(c
)) {
1075 while (is_dir_sep(c
))
1084 * dst0..dst is prefix portion, and dst[-1] is '/';
1087 dst
--; /* go to trailing '/' */
1090 /* Windows: dst[-1] cannot be backslash anymore */
1091 while (dst0
< dst
&& dst
[-1] != '/')
1093 if (prefix_len
&& *prefix_len
> dst
- dst0
)
1094 *prefix_len
= dst
- dst0
;
1100 int normalize_path_copy(char *dst
, const char *src
)
1102 return normalize_path_copy_len(dst
, src
, NULL
);
1105 int strbuf_normalize_path(struct strbuf
*src
)
1107 struct strbuf dst
= STRBUF_INIT
;
1109 strbuf_grow(&dst
, src
->len
);
1110 if (normalize_path_copy(dst
.buf
, src
->buf
) < 0) {
1111 strbuf_release(&dst
);
1116 * normalize_path does not tell us the new length, so we have to
1117 * compute it by looking for the new NUL it placed
1119 strbuf_setlen(&dst
, strlen(dst
.buf
));
1120 strbuf_swap(src
, &dst
);
1121 strbuf_release(&dst
);
1126 * path = Canonical absolute path
1127 * prefixes = string_list containing normalized, absolute paths without
1128 * trailing slashes (except for the root directory, which is denoted by "/").
1130 * Determines, for each path in prefixes, whether the "prefix"
1131 * is an ancestor directory of path. Returns the length of the longest
1132 * ancestor directory, excluding any trailing slashes, or -1 if no prefix
1133 * is an ancestor. (Note that this means 0 is returned if prefixes is
1134 * ["/"].) "/foo" is not considered an ancestor of "/foobar". Directories
1135 * are not considered to be their own ancestors. path must be in a
1136 * canonical form: empty components, or "." or ".." components are not
1139 int longest_ancestor_length(const char *path
, struct string_list
*prefixes
)
1141 int i
, max_len
= -1;
1143 if (!strcmp(path
, "/"))
1146 for (i
= 0; i
< prefixes
->nr
; i
++) {
1147 const char *ceil
= prefixes
->items
[i
].string
;
1148 int len
= strlen(ceil
);
1151 * For root directories (`/`, `C:/`, `//server/share/`)
1152 * adjust the length to exclude the trailing slash.
1154 if (len
> 0 && ceil
[len
- 1] == '/')
1157 if (strncmp(path
, ceil
, len
) ||
1158 path
[len
] != '/' || !path
[len
+ 1])
1159 continue; /* no match */
1168 /* strip arbitrary amount of directory separators at end of path */
1169 static inline int chomp_trailing_dir_sep(const char *path
, int len
)
1171 while (len
&& is_dir_sep(path
[len
- 1]))
1177 * If path ends with suffix (complete path components), returns the offset of
1178 * the last character in the path before the suffix (sans trailing directory
1179 * separators), and -1 otherwise.
1181 static ssize_t
stripped_path_suffix_offset(const char *path
, const char *suffix
)
1183 int path_len
= strlen(path
), suffix_len
= strlen(suffix
);
1185 while (suffix_len
) {
1189 if (is_dir_sep(path
[path_len
- 1])) {
1190 if (!is_dir_sep(suffix
[suffix_len
- 1]))
1192 path_len
= chomp_trailing_dir_sep(path
, path_len
);
1193 suffix_len
= chomp_trailing_dir_sep(suffix
, suffix_len
);
1195 else if (path
[--path_len
] != suffix
[--suffix_len
])
1199 if (path_len
&& !is_dir_sep(path
[path_len
- 1]))
1201 return chomp_trailing_dir_sep(path
, path_len
);
1205 * Returns true if the path ends with components, considering only complete path
1206 * components, and false otherwise.
1208 int ends_with_path_components(const char *path
, const char *components
)
1210 return stripped_path_suffix_offset(path
, components
) != -1;
1214 * If path ends with suffix (complete path components), returns the
1215 * part before suffix (sans trailing directory separators).
1216 * Otherwise returns NULL.
1218 char *strip_path_suffix(const char *path
, const char *suffix
)
1220 ssize_t offset
= stripped_path_suffix_offset(path
, suffix
);
1222 return offset
== -1 ? NULL
: xstrndup(path
, offset
);
1225 int daemon_avoid_alias(const char *p
)
1230 * This resurrects the belts and suspenders paranoia check by HPA
1231 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
1232 * does not do getcwd() based path canonicalization.
1234 * sl becomes true immediately after seeing '/' and continues to
1235 * be true as long as dots continue after that without intervening
1236 * non-dot character.
1238 if (!p
|| (*p
!= '/' && *p
!= '~'))
1248 else if (ch
== '/') {
1250 /* reject //, /./ and /../ */
1255 if (0 < ndot
&& ndot
< 3)
1256 /* reject /.$ and /..$ */
1265 else if (ch
== '/') {
1273 * On NTFS, we need to be careful to disallow certain synonyms of the `.git/`
1276 * - For historical reasons, file names that end in spaces or periods are
1277 * automatically trimmed. Therefore, `.git . . ./` is a valid way to refer
1280 * - For other historical reasons, file names that do not conform to the 8.3
1281 * format (up to eight characters for the basename, three for the file
1282 * extension, certain characters not allowed such as `+`, etc) are associated
1283 * with a so-called "short name", at least on the `C:` drive by default.
1284 * Which means that `git~1/` is a valid way to refer to `.git/`.
1286 * Note: Technically, `.git/` could receive the short name `git~2` if the
1287 * short name `git~1` were already used. In Git, however, we guarantee that
1288 * `.git` is the first item in a directory, therefore it will be associated
1289 * with the short name `git~1` (unless short names are disabled).
1291 * - For yet other historical reasons, NTFS supports so-called "Alternate Data
1292 * Streams", i.e. metadata associated with a given file, referred to via
1293 * `<filename>:<stream-name>:<stream-type>`. There exists a default stream
1294 * type for directories, allowing `.git/` to be accessed via
1295 * `.git::$INDEX_ALLOCATION/`.
1297 * When this function returns 1, it indicates that the specified file/directory
1298 * name refers to a `.git` file or directory, or to any of these synonyms, and
1299 * Git should therefore not track it.
1301 * For performance reasons, _all_ Alternate Data Streams of `.git/` are
1302 * forbidden, not just `::$INDEX_ALLOCATION`.
1304 * This function is intended to be used by `git fsck` even on platforms where
1305 * the backslash is a regular filename character, therefore it needs to handle
1306 * backlash characters in the provided `name` specially: they are interpreted
1307 * as directory separators.
1309 int is_ntfs_dotgit(const char *name
)
1314 * Note that when we don't find `.git` or `git~1` we end up with `name`
1315 * advanced partway through the string. That's okay, though, as we
1316 * return immediately in those cases, without looking at `name` any
1322 if (((c
= *(name
++)) != 'g' && c
!= 'G') ||
1323 ((c
= *(name
++)) != 'i' && c
!= 'I') ||
1324 ((c
= *(name
++)) != 't' && c
!= 'T'))
1326 } else if (c
== 'g' || c
== 'G') {
1328 if (((c
= *(name
++)) != 'i' && c
!= 'I') ||
1329 ((c
= *(name
++)) != 't' && c
!= 'T') ||
1338 if (!c
|| is_xplatform_dir_sep(c
) || c
== ':')
1340 if (c
!= '.' && c
!= ' ')
1345 static int is_ntfs_dot_generic(const char *name
,
1346 const char *dotgit_name
,
1348 const char *dotgit_ntfs_shortname_prefix
)
1353 if ((name
[0] == '.' && !strncasecmp(name
+ 1, dotgit_name
, len
))) {
1355 only_spaces_and_periods
:
1360 if (c
!= ' ' && c
!= '.')
1366 * Is it a regular NTFS short name, i.e. shortened to 6 characters,
1367 * followed by ~1, ... ~4?
1369 if (!strncasecmp(name
, dotgit_name
, 6) && name
[6] == '~' &&
1370 name
[7] >= '1' && name
[7] <= '4') {
1372 goto only_spaces_and_periods
;
1376 * Is it a fall-back NTFS short name (for details, see
1377 * https://en.wikipedia.org/wiki/8.3_filename?
1379 for (i
= 0, saw_tilde
= 0; i
< 8; i
++)
1380 if (name
[i
] == '\0')
1382 else if (saw_tilde
) {
1383 if (name
[i
] < '0' || name
[i
] > '9')
1385 } else if (name
[i
] == '~') {
1386 if (name
[++i
] < '1' || name
[i
] > '9')
1391 else if (name
[i
] & 0x80) {
1393 * We know our needles contain only ASCII, so we clamp
1394 * here to make the results of tolower() sane.
1397 } else if (tolower(name
[i
]) != dotgit_ntfs_shortname_prefix
[i
])
1400 goto only_spaces_and_periods
;
1404 * Inline helper to make sure compiler resolves strlen() on literals at
1407 static inline int is_ntfs_dot_str(const char *name
, const char *dotgit_name
,
1408 const char *dotgit_ntfs_shortname_prefix
)
1410 return is_ntfs_dot_generic(name
, dotgit_name
, strlen(dotgit_name
),
1411 dotgit_ntfs_shortname_prefix
);
1414 int is_ntfs_dotgitmodules(const char *name
)
1416 return is_ntfs_dot_str(name
, "gitmodules", "gi7eba");
1419 int is_ntfs_dotgitignore(const char *name
)
1421 return is_ntfs_dot_str(name
, "gitignore", "gi250a");
1424 int is_ntfs_dotgitattributes(const char *name
)
1426 return is_ntfs_dot_str(name
, "gitattributes", "gi7d29");
1429 int is_ntfs_dotmailmap(const char *name
)
1431 return is_ntfs_dot_str(name
, "mailmap", "maba30");
1434 int looks_like_command_line_option(const char *str
)
1436 return str
&& str
[0] == '-';
1439 char *xdg_config_home_for(const char *subdir
, const char *filename
)
1441 const char *home
, *config_home
;
1445 config_home
= getenv("XDG_CONFIG_HOME");
1446 if (config_home
&& *config_home
)
1447 return mkpathdup("%s/%s/%s", config_home
, subdir
, filename
);
1449 home
= getenv("HOME");
1451 return mkpathdup("%s/.config/%s/%s", home
, subdir
, filename
);
1456 char *xdg_config_home(const char *filename
)
1458 return xdg_config_home_for("git", filename
);
1461 char *xdg_cache_home(const char *filename
)
1463 const char *home
, *cache_home
;
1466 cache_home
= getenv("XDG_CACHE_HOME");
1467 if (cache_home
&& *cache_home
)
1468 return mkpathdup("%s/git/%s", cache_home
, filename
);
1470 home
= getenv("HOME");
1472 return mkpathdup("%s/.cache/git/%s", home
, filename
);
1476 REPO_GIT_PATH_FUNC(squash_msg
, "SQUASH_MSG")
1477 REPO_GIT_PATH_FUNC(merge_msg
, "MERGE_MSG")
1478 REPO_GIT_PATH_FUNC(merge_rr
, "MERGE_RR")
1479 REPO_GIT_PATH_FUNC(merge_mode
, "MERGE_MODE")
1480 REPO_GIT_PATH_FUNC(merge_head
, "MERGE_HEAD")
1481 REPO_GIT_PATH_FUNC(fetch_head
, "FETCH_HEAD")
1482 REPO_GIT_PATH_FUNC(shallow
, "shallow")