2 * Utilities for paths and pathnames
8 #include "repository.h"
10 #include "string-list.h"
13 #include "submodule-config.h"
16 #include "object-store.h"
20 static int get_st_mode_bits(const char *path
, int *mode
)
23 if (lstat(path
, &st
) < 0)
29 static char bad_path
[] = "/bad-path/";
31 static 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 char *mksnpath(char *buf
, size_t n
, const char *fmt
, ...)
66 len
= vsnprintf(buf
, n
, fmt
, args
);
69 strlcpy(buf
, bad_path
, n
);
72 return (char *)cleanup_path(buf
);
75 static int dir_prefix(const char *buf
, const char *dir
)
77 int len
= strlen(dir
);
78 return !strncmp(buf
, dir
, len
) &&
79 (is_dir_sep(buf
[len
]) || buf
[len
] == '\0');
82 /* $buf =~ m|$dir/+$file| but without regex */
83 static int is_dir_file(const char *buf
, const char *dir
, const char *file
)
85 int len
= strlen(dir
);
86 if (strncmp(buf
, dir
, len
) || !is_dir_sep(buf
[len
]))
88 while (is_dir_sep(buf
[len
]))
90 return !strcmp(buf
+ len
, file
);
93 static void replace_dir(struct strbuf
*buf
, int len
, const char *newdir
)
95 int newlen
= strlen(newdir
);
96 int need_sep
= (buf
->buf
[len
] && !is_dir_sep(buf
->buf
[len
])) &&
97 !is_dir_sep(newdir
[newlen
- 1]);
99 len
--; /* keep one char, to be replaced with '/' */
100 strbuf_splice(buf
, 0, len
, newdir
, newlen
);
102 buf
->buf
[newlen
] = '/';
106 /* Not considered garbage for report_linked_checkout_garbage */
107 unsigned ignore_garbage
:1;
109 /* Belongs to the common dir, though it may contain paths that don't */
110 unsigned is_common
:1;
114 static struct common_dir common_list
[] = {
115 { 0, 1, 1, "branches" },
116 { 0, 1, 1, "common" },
117 { 0, 1, 1, "hooks" },
119 { 0, 0, 0, "info/sparse-checkout" },
121 { 1, 0, 0, "logs/HEAD" },
122 { 0, 1, 0, "logs/refs/bisect" },
123 { 0, 1, 0, "logs/refs/rewritten" },
124 { 0, 1, 0, "logs/refs/worktree" },
125 { 0, 1, 1, "lost-found" },
126 { 0, 1, 1, "objects" },
128 { 0, 1, 0, "refs/bisect" },
129 { 0, 1, 0, "refs/rewritten" },
130 { 0, 1, 0, "refs/worktree" },
131 { 0, 1, 1, "remotes" },
132 { 0, 1, 1, "worktrees" },
133 { 0, 1, 1, "rr-cache" },
135 { 0, 0, 1, "config" },
136 { 1, 0, 1, "gc.pid" },
137 { 0, 0, 1, "packed-refs" },
138 { 0, 0, 1, "shallow" },
143 * A compressed trie. A trie node consists of zero or more characters that
144 * are common to all elements with this prefix, optionally followed by some
145 * children. If value is not NULL, the trie node is a terminal node.
147 * For example, consider the following set of strings:
153 * The trie would look like:
154 * root: len = 0, children a and d non-NULL, value = NULL.
155 * a: len = 2, contents = bc, value = (data for "abc")
156 * d: len = 2, contents = ef, children i non-NULL, value = (data for "def")
157 * i: len = 3, contents = nit, children e and i non-NULL, value = NULL
158 * e: len = 0, children all NULL, value = (data for "definite")
159 * i: len = 2, contents = on, children all NULL,
160 * value = (data for "definition")
163 struct trie
*children
[256];
169 static struct trie
*make_trie_node(const char *key
, void *value
)
171 struct trie
*new_node
= xcalloc(1, sizeof(*new_node
));
172 new_node
->len
= strlen(key
);
174 new_node
->contents
= xmalloc(new_node
->len
);
175 memcpy(new_node
->contents
, key
, new_node
->len
);
177 new_node
->value
= value
;
182 * Add a key/value pair to a trie. The key is assumed to be \0-terminated.
183 * If there was an existing value for this key, return it.
185 static void *add_to_trie(struct trie
*root
, const char *key
, void *value
)
192 /* we have reached the end of the key */
198 for (i
= 0; i
< root
->len
; i
++) {
199 if (root
->contents
[i
] == key
[i
])
203 * Split this node: child will contain this node's
206 child
= xmalloc(sizeof(*child
));
207 memcpy(child
->children
, root
->children
, sizeof(root
->children
));
209 child
->len
= root
->len
- i
- 1;
211 child
->contents
= xstrndup(root
->contents
+ i
+ 1,
214 child
->value
= root
->value
;
218 memset(root
->children
, 0, sizeof(root
->children
));
219 root
->children
[(unsigned char)root
->contents
[i
]] = child
;
221 /* This is the newly-added child. */
222 root
->children
[(unsigned char)key
[i
]] =
223 make_trie_node(key
+ i
+ 1, value
);
227 /* We have matched the entire compressed section */
229 child
= root
->children
[(unsigned char)key
[root
->len
]];
231 return add_to_trie(child
, key
+ root
->len
+ 1, value
);
233 child
= make_trie_node(key
+ root
->len
+ 1, value
);
234 root
->children
[(unsigned char)key
[root
->len
]] = child
;
244 typedef int (*match_fn
)(const char *unmatched
, void *value
, void *baton
);
247 * Search a trie for some key. Find the longest /-or-\0-terminated
248 * prefix of the key for which the trie contains a value. If there is
249 * no such prefix, return -1. Otherwise call fn with the unmatched
250 * portion of the key and the found value. If fn returns 0 or
251 * positive, then return its return value. If fn returns negative,
252 * then call fn with the next-longest /-terminated prefix of the key
253 * (i.e. a parent directory) for which the trie contains a value, and
254 * handle its return value the same way. If there is no shorter
255 * /-terminated prefix with a value left, then return the negative
256 * return value of the most recent fn invocation.
258 * The key is partially normalized: consecutive slashes are skipped.
260 * For example, consider the trie containing only [logs,
261 * logs/refs/bisect], both with values, but not logs/refs.
263 * | key | unmatched | prefix to node | return value |
264 * |--------------------|----------------|------------------|--------------|
265 * | a | not called | n/a | -1 |
266 * | logstore | not called | n/a | -1 |
267 * | logs | \0 | logs | as per fn |
268 * | logs/ | / | logs | as per fn |
269 * | logs/refs | /refs | logs | as per fn |
270 * | logs/refs/ | /refs/ | logs | as per fn |
271 * | logs/refs/b | /refs/b | logs | as per fn |
272 * | logs/refs/bisected | /refs/bisected | logs | as per fn |
273 * | logs/refs/bisect | \0 | logs/refs/bisect | as per fn |
274 * | logs/refs/bisect/ | / | logs/refs/bisect | as per fn |
275 * | logs/refs/bisect/a | /a | logs/refs/bisect | as per fn |
276 * | (If fn in the previous line returns -1, then fn is called once more:) |
277 * | logs/refs/bisect/a | /refs/bisect/a | logs | as per fn |
278 * |--------------------|----------------|------------------|--------------|
280 static int trie_find(struct trie
*root
, const char *key
, match_fn fn
,
288 /* we have reached the end of the key */
289 if (root
->value
&& !root
->len
)
290 return fn(key
, root
->value
, baton
);
295 for (i
= 0; i
< root
->len
; i
++) {
296 /* Partial path normalization: skip consecutive slashes. */
297 if (key
[i
] == '/' && key
[i
+1] == '/') {
301 if (root
->contents
[i
] != key
[i
])
305 /* Matched the entire compressed section */
310 return fn(key
, root
->value
, baton
);
315 /* Partial path normalization: skip consecutive slashes */
316 while (key
[0] == '/' && key
[1] == '/')
319 child
= root
->children
[(unsigned char)*key
];
321 result
= trie_find(child
, key
+ 1, fn
, baton
);
325 if (result
>= 0 || (*key
!= '/' && *key
!= 0))
328 return fn(key
, root
->value
, baton
);
333 static struct trie common_trie
;
334 static int common_trie_done_setup
;
336 static void init_common_trie(void)
338 struct common_dir
*p
;
340 if (common_trie_done_setup
)
343 for (p
= common_list
; p
->path
; p
++)
344 add_to_trie(&common_trie
, p
->path
, p
);
346 common_trie_done_setup
= 1;
350 * Helper function for update_common_dir: returns 1 if the dir
353 static int check_common(const char *unmatched
, void *value
,
356 struct common_dir
*dir
= value
;
358 if (dir
->is_dir
&& (unmatched
[0] == 0 || unmatched
[0] == '/'))
359 return dir
->is_common
;
361 if (!dir
->is_dir
&& unmatched
[0] == 0)
362 return dir
->is_common
;
367 static void update_common_dir(struct strbuf
*buf
, int git_dir_len
,
368 const char *common_dir
)
370 char *base
= buf
->buf
+ git_dir_len
;
371 int has_lock_suffix
= strbuf_strip_suffix(buf
, LOCK_SUFFIX
);
374 if (trie_find(&common_trie
, base
, check_common
, NULL
) > 0)
375 replace_dir(buf
, git_dir_len
, common_dir
);
378 strbuf_addstr(buf
, LOCK_SUFFIX
);
381 void report_linked_checkout_garbage(void)
383 struct strbuf sb
= STRBUF_INIT
;
384 const struct common_dir
*p
;
387 if (!the_repository
->different_commondir
)
389 strbuf_addf(&sb
, "%s/", get_git_dir());
391 for (p
= common_list
; p
->path
; p
++) {
392 const char *path
= p
->path
;
393 if (p
->ignore_garbage
)
395 strbuf_setlen(&sb
, len
);
396 strbuf_addstr(&sb
, path
);
397 if (file_exists(sb
.buf
))
398 report_garbage(PACKDIR_FILE_GARBAGE
, sb
.buf
);
403 static void adjust_git_path(const struct repository
*repo
,
404 struct strbuf
*buf
, int git_dir_len
)
406 const char *base
= buf
->buf
+ git_dir_len
;
407 if (is_dir_file(base
, "info", "grafts"))
408 strbuf_splice(buf
, 0, buf
->len
,
409 repo
->graft_file
, strlen(repo
->graft_file
));
410 else if (!strcmp(base
, "index"))
411 strbuf_splice(buf
, 0, buf
->len
,
412 repo
->index_file
, strlen(repo
->index_file
));
413 else if (dir_prefix(base
, "objects"))
414 replace_dir(buf
, git_dir_len
+ 7, repo
->objects
->odb
->path
);
415 else if (git_hooks_path
&& dir_prefix(base
, "hooks"))
416 replace_dir(buf
, git_dir_len
+ 5, git_hooks_path
);
417 else if (repo
->different_commondir
)
418 update_common_dir(buf
, git_dir_len
, repo
->commondir
);
421 static void strbuf_worktree_gitdir(struct strbuf
*buf
,
422 const struct repository
*repo
,
423 const struct worktree
*wt
)
426 strbuf_addstr(buf
, repo
->gitdir
);
428 strbuf_addstr(buf
, repo
->commondir
);
430 strbuf_git_common_path(buf
, repo
, "worktrees/%s", wt
->id
);
433 static void do_git_path(const struct repository
*repo
,
434 const struct worktree
*wt
, struct strbuf
*buf
,
435 const char *fmt
, va_list args
)
438 strbuf_worktree_gitdir(buf
, repo
, wt
);
439 if (buf
->len
&& !is_dir_sep(buf
->buf
[buf
->len
- 1]))
440 strbuf_addch(buf
, '/');
441 gitdir_len
= buf
->len
;
442 strbuf_vaddf(buf
, fmt
, args
);
444 adjust_git_path(repo
, buf
, gitdir_len
);
445 strbuf_cleanup_path(buf
);
448 char *repo_git_path(const struct repository
*repo
,
449 const char *fmt
, ...)
451 struct strbuf path
= STRBUF_INIT
;
454 do_git_path(repo
, NULL
, &path
, fmt
, args
);
456 return strbuf_detach(&path
, NULL
);
459 void strbuf_repo_git_path(struct strbuf
*sb
,
460 const struct repository
*repo
,
461 const char *fmt
, ...)
465 do_git_path(repo
, NULL
, sb
, fmt
, args
);
469 char *git_path_buf(struct strbuf
*buf
, const char *fmt
, ...)
474 do_git_path(the_repository
, NULL
, buf
, fmt
, args
);
479 void strbuf_git_path(struct strbuf
*sb
, const char *fmt
, ...)
483 do_git_path(the_repository
, NULL
, sb
, fmt
, args
);
487 const char *git_path(const char *fmt
, ...)
489 struct strbuf
*pathname
= get_pathname();
492 do_git_path(the_repository
, NULL
, pathname
, fmt
, args
);
494 return pathname
->buf
;
497 char *git_pathdup(const char *fmt
, ...)
499 struct strbuf path
= STRBUF_INIT
;
502 do_git_path(the_repository
, NULL
, &path
, fmt
, args
);
504 return strbuf_detach(&path
, NULL
);
507 char *mkpathdup(const char *fmt
, ...)
509 struct strbuf sb
= STRBUF_INIT
;
512 strbuf_vaddf(&sb
, fmt
, args
);
514 strbuf_cleanup_path(&sb
);
515 return strbuf_detach(&sb
, NULL
);
518 const char *mkpath(const char *fmt
, ...)
521 struct strbuf
*pathname
= get_pathname();
523 strbuf_vaddf(pathname
, fmt
, args
);
525 return cleanup_path(pathname
->buf
);
528 const char *worktree_git_path(const struct worktree
*wt
, const char *fmt
, ...)
530 struct strbuf
*pathname
= get_pathname();
533 do_git_path(the_repository
, wt
, pathname
, fmt
, args
);
535 return pathname
->buf
;
538 static void do_worktree_path(const struct repository
*repo
,
540 const char *fmt
, va_list args
)
542 strbuf_addstr(buf
, repo
->worktree
);
543 if(buf
->len
&& !is_dir_sep(buf
->buf
[buf
->len
- 1]))
544 strbuf_addch(buf
, '/');
546 strbuf_vaddf(buf
, fmt
, args
);
547 strbuf_cleanup_path(buf
);
550 char *repo_worktree_path(const struct repository
*repo
, const char *fmt
, ...)
552 struct strbuf path
= STRBUF_INIT
;
559 do_worktree_path(repo
, &path
, fmt
, args
);
562 return strbuf_detach(&path
, NULL
);
565 void strbuf_repo_worktree_path(struct strbuf
*sb
,
566 const struct repository
*repo
,
567 const char *fmt
, ...)
575 do_worktree_path(repo
, sb
, fmt
, args
);
579 /* Returns 0 on success, negative on failure. */
580 static int do_submodule_path(struct strbuf
*buf
, const char *path
,
581 const char *fmt
, va_list args
)
583 struct strbuf git_submodule_common_dir
= STRBUF_INIT
;
584 struct strbuf git_submodule_dir
= STRBUF_INIT
;
587 ret
= submodule_to_gitdir(&git_submodule_dir
, path
);
591 strbuf_complete(&git_submodule_dir
, '/');
592 strbuf_addbuf(buf
, &git_submodule_dir
);
593 strbuf_vaddf(buf
, fmt
, args
);
595 if (get_common_dir_noenv(&git_submodule_common_dir
, git_submodule_dir
.buf
))
596 update_common_dir(buf
, git_submodule_dir
.len
, git_submodule_common_dir
.buf
);
598 strbuf_cleanup_path(buf
);
601 strbuf_release(&git_submodule_dir
);
602 strbuf_release(&git_submodule_common_dir
);
606 char *git_pathdup_submodule(const char *path
, const char *fmt
, ...)
610 struct strbuf buf
= STRBUF_INIT
;
612 err
= do_submodule_path(&buf
, path
, fmt
, args
);
615 strbuf_release(&buf
);
618 return strbuf_detach(&buf
, NULL
);
621 int strbuf_git_path_submodule(struct strbuf
*buf
, const char *path
,
622 const char *fmt
, ...)
627 err
= do_submodule_path(buf
, path
, fmt
, args
);
633 static void do_git_common_path(const struct repository
*repo
,
638 strbuf_addstr(buf
, repo
->commondir
);
639 if (buf
->len
&& !is_dir_sep(buf
->buf
[buf
->len
- 1]))
640 strbuf_addch(buf
, '/');
641 strbuf_vaddf(buf
, fmt
, args
);
642 strbuf_cleanup_path(buf
);
645 const char *git_common_path(const char *fmt
, ...)
647 struct strbuf
*pathname
= get_pathname();
650 do_git_common_path(the_repository
, pathname
, fmt
, args
);
652 return pathname
->buf
;
655 void strbuf_git_common_path(struct strbuf
*sb
,
656 const struct repository
*repo
,
657 const char *fmt
, ...)
661 do_git_common_path(repo
, sb
, fmt
, args
);
665 int validate_headref(const char *path
)
670 struct object_id oid
;
674 if (lstat(path
, &st
) < 0)
677 /* Make sure it is a "refs/.." symlink */
678 if (S_ISLNK(st
.st_mode
)) {
679 len
= readlink(path
, buffer
, sizeof(buffer
)-1);
680 if (len
>= 5 && !memcmp("refs/", buffer
, 5))
686 * Anything else, just open it and try to see if it is a symbolic ref.
688 fd
= open(path
, O_RDONLY
);
691 len
= read_in_full(fd
, buffer
, sizeof(buffer
)-1);
699 * Is it a symbolic ref?
701 if (skip_prefix(buffer
, "ref:", &refname
)) {
702 while (isspace(*refname
))
704 if (starts_with(refname
, "refs/"))
709 * Is this a detached HEAD?
711 if (!get_oid_hex(buffer
, &oid
))
717 static struct passwd
*getpw_str(const char *username
, size_t len
)
720 char *username_z
= xmemdupz(username
, len
);
721 pw
= getpwnam(username_z
);
727 * Return a string with ~ and ~user expanded via getpw*. Returns NULL on getpw
728 * failure or if path is NULL.
730 * If real_home is true, strbuf_realpath($HOME) is used in the `~/` expansion.
732 * If the path starts with `%(prefix)/`, the remainder is interpreted as
733 * relative to where Git is installed, and expanded to the absolute path.
735 char *interpolate_path(const char *path
, int real_home
)
737 struct strbuf user_path
= STRBUF_INIT
;
738 const char *to_copy
= path
;
743 if (skip_prefix(path
, "%(prefix)/", &path
))
744 return system_path(path
);
746 if (path
[0] == '~') {
747 const char *first_slash
= strchrnul(path
, '/');
748 const char *username
= path
+ 1;
749 size_t username_len
= first_slash
- username
;
750 if (username_len
== 0) {
751 const char *home
= getenv("HOME");
755 strbuf_add_real_path(&user_path
, home
);
757 strbuf_addstr(&user_path
, home
);
758 #ifdef GIT_WINDOWS_NATIVE
759 convert_slashes(user_path
.buf
);
762 struct passwd
*pw
= getpw_str(username
, username_len
);
765 strbuf_addstr(&user_path
, pw
->pw_dir
);
767 to_copy
= first_slash
;
769 strbuf_addstr(&user_path
, to_copy
);
770 return strbuf_detach(&user_path
, NULL
);
772 strbuf_release(&user_path
);
777 * First, one directory to try is determined by the following algorithm.
779 * (0) If "strict" is given, the path is used as given and no DWIM is
781 * (1) "~/path" to mean path under the running user's home directory;
782 * (2) "~user/path" to mean path under named user's home directory;
783 * (3) "relative/path" to mean cwd relative directory; or
784 * (4) "/absolute/path" to mean absolute directory.
786 * Unless "strict" is given, we check "%s/.git", "%s", "%s.git/.git", "%s.git"
787 * in this order. We select the first one that is a valid git repository, and
788 * chdir() to it. If none match, or we fail to chdir, we return NULL.
790 * If all goes well, we return the directory we used to chdir() (but
791 * before ~user is expanded), avoiding getcwd() resolving symbolic
792 * links. User relative paths are also returned as they are given,
793 * except DWIM suffixing.
795 const char *enter_repo(const char *path
, int strict
)
797 static struct strbuf validated_path
= STRBUF_INIT
;
798 static struct strbuf used_path
= STRBUF_INIT
;
804 static const char *suffix
[] = {
805 "/.git", "", ".git/.git", ".git", NULL
,
808 int len
= strlen(path
);
810 while ((1 < len
) && (path
[len
-1] == '/'))
814 * We can handle arbitrary-sized buffers, but this remains as a
815 * sanity check on untrusted input.
820 strbuf_reset(&used_path
);
821 strbuf_reset(&validated_path
);
822 strbuf_add(&used_path
, path
, len
);
823 strbuf_add(&validated_path
, path
, len
);
825 if (used_path
.buf
[0] == '~') {
826 char *newpath
= interpolate_path(used_path
.buf
, 0);
829 strbuf_attach(&used_path
, newpath
, strlen(newpath
),
832 for (i
= 0; suffix
[i
]; i
++) {
834 size_t baselen
= used_path
.len
;
835 strbuf_addstr(&used_path
, suffix
[i
]);
836 if (!stat(used_path
.buf
, &st
) &&
837 (S_ISREG(st
.st_mode
) ||
838 (S_ISDIR(st
.st_mode
) && is_git_directory(used_path
.buf
)))) {
839 strbuf_addstr(&validated_path
, suffix
[i
]);
842 strbuf_setlen(&used_path
, baselen
);
846 gitfile
= read_gitfile(used_path
.buf
);
848 strbuf_reset(&used_path
);
849 strbuf_addstr(&used_path
, gitfile
);
851 if (chdir(used_path
.buf
))
853 path
= validated_path
.buf
;
856 const char *gitfile
= read_gitfile(path
);
863 if (is_git_directory(".")) {
865 check_repository_format(NULL
);
872 static int calc_shared_perm(int mode
)
876 if (get_shared_repository() < 0)
877 tweak
= -get_shared_repository();
879 tweak
= get_shared_repository();
881 if (!(mode
& S_IWUSR
))
884 /* Copy read bits to execute bits */
885 tweak
|= (tweak
& 0444) >> 2;
886 if (get_shared_repository() < 0)
887 mode
= (mode
& ~0777) | tweak
;
895 int adjust_shared_perm(const char *path
)
897 int old_mode
, new_mode
;
899 if (!get_shared_repository())
901 if (get_st_mode_bits(path
, &old_mode
) < 0)
904 new_mode
= calc_shared_perm(old_mode
);
905 if (S_ISDIR(old_mode
)) {
906 /* Copy read bits to execute bits */
907 new_mode
|= (new_mode
& 0444) >> 2;
910 * g+s matters only if any extra access is granted
911 * based on group membership.
913 if (FORCE_DIR_SET_GID
&& (new_mode
& 060))
914 new_mode
|= FORCE_DIR_SET_GID
;
917 if (((old_mode
^ new_mode
) & ~S_IFMT
) &&
918 chmod(path
, (new_mode
& ~S_IFMT
)) < 0)
923 void safe_create_dir(const char *dir
, int share
)
925 if (mkdir(dir
, 0777) < 0) {
926 if (errno
!= EEXIST
) {
931 else if (share
&& adjust_shared_perm(dir
))
932 die(_("Could not make %s writable by group"), dir
);
935 static int have_same_root(const char *path1
, const char *path2
)
937 int is_abs1
, is_abs2
;
939 is_abs1
= is_absolute_path(path1
);
940 is_abs2
= is_absolute_path(path2
);
941 return (is_abs1
&& is_abs2
&& tolower(path1
[0]) == tolower(path2
[0])) ||
942 (!is_abs1
&& !is_abs2
);
946 * Give path as relative to prefix.
948 * The strbuf may or may not be used, so do not assume it contains the
951 const char *relative_path(const char *in
, const char *prefix
,
954 int in_len
= in
? strlen(in
) : 0;
955 int prefix_len
= prefix
? strlen(prefix
) : 0;
962 else if (!prefix_len
)
965 if (have_same_root(in
, prefix
))
966 /* bypass dos_drive, for "c:" is identical to "C:" */
967 i
= j
= has_dos_drive_prefix(in
);
972 while (i
< prefix_len
&& j
< in_len
&& prefix
[i
] == in
[j
]) {
973 if (is_dir_sep(prefix
[i
])) {
974 while (is_dir_sep(prefix
[i
]))
976 while (is_dir_sep(in
[j
]))
987 /* "prefix" seems like prefix of "in" */
990 * but "/foo" is not a prefix of "/foobar"
991 * (i.e. prefix not end with '/')
993 prefix_off
< prefix_len
) {
995 /* in="/a/b", prefix="/a/b" */
997 } else if (is_dir_sep(in
[j
])) {
998 /* in="/a/b/c", prefix="/a/b" */
999 while (is_dir_sep(in
[j
]))
1003 /* in="/a/bbb/c", prefix="/a/b" */
1007 /* "in" is short than "prefix" */
1009 /* "in" not end with '/' */
1011 if (is_dir_sep(prefix
[i
])) {
1012 /* in="/a/b", prefix="/a/b/c/" */
1013 while (is_dir_sep(prefix
[i
]))
1021 if (i
>= prefix_len
) {
1029 strbuf_grow(sb
, in_len
);
1031 while (i
< prefix_len
) {
1032 if (is_dir_sep(prefix
[i
])) {
1033 strbuf_addstr(sb
, "../");
1034 while (is_dir_sep(prefix
[i
]))
1040 if (!is_dir_sep(prefix
[prefix_len
- 1]))
1041 strbuf_addstr(sb
, "../");
1043 strbuf_addstr(sb
, in
);
1049 * A simpler implementation of relative_path
1051 * Get relative path by removing "prefix" from "in". This function
1052 * first appears in v1.5.6-1-g044bbbc, and makes git_dir shorter
1053 * to increase performance when traversing the path to work_tree.
1055 const char *remove_leading_path(const char *in
, const char *prefix
)
1057 static struct strbuf buf
= STRBUF_INIT
;
1060 if (!prefix
|| !prefix
[0])
1063 if (is_dir_sep(prefix
[i
])) {
1064 if (!is_dir_sep(in
[j
]))
1066 while (is_dir_sep(prefix
[i
]))
1068 while (is_dir_sep(in
[j
]))
1071 } else if (in
[j
] != prefix
[i
]) {
1078 /* "/foo" is a prefix of "/foo" */
1080 /* "/foo" is not a prefix of "/foobar" */
1081 !is_dir_sep(prefix
[i
-1]) && !is_dir_sep(in
[j
])
1084 while (is_dir_sep(in
[j
]))
1089 strbuf_addstr(&buf
, ".");
1091 strbuf_addstr(&buf
, in
+ j
);
1096 * It is okay if dst == src, but they should not overlap otherwise.
1097 * The "dst" buffer must be at least as long as "src"; normalizing may shrink
1098 * the size of the path, but will never grow it.
1100 * Performs the following normalizations on src, storing the result in dst:
1101 * - Ensures that components are separated by '/' (Windows only)
1102 * - Squashes sequences of '/' except "//server/share" on Windows
1103 * - Removes "." components.
1104 * - Removes ".." components, and the components the precede them.
1105 * Returns failure (non-zero) if a ".." component appears as first path
1106 * component anytime during the normalization. Otherwise, returns success (0).
1108 * Note that this function is purely textual. It does not follow symlinks,
1109 * verify the existence of the path, or make any system calls.
1111 * prefix_len != NULL is for a specific case of prefix_pathspec():
1112 * assume that src == dst and src[0..prefix_len-1] is already
1113 * normalized, any time "../" eats up to the prefix_len part,
1114 * prefix_len is reduced. In the end prefix_len is the remaining
1115 * prefix that has not been overridden by user pathspec.
1117 * NEEDSWORK: This function doesn't perform normalization w.r.t. trailing '/'.
1118 * For everything but the root folder itself, the normalized path should not
1119 * end with a '/', then the callers need to be fixed up accordingly.
1122 int normalize_path_copy_len(char *dst
, const char *src
, int *prefix_len
)
1128 * Copy initial part of absolute path: "/", "C:/", "//server/share/".
1130 end
= src
+ offset_1st_component(src
);
1139 while (is_dir_sep(*src
))
1146 * A path component that begins with . could be
1148 * (1) "." and ends -- ignore and terminate.
1149 * (2) "./" -- ignore them, eat slash and continue.
1150 * (3) ".." and ends -- strip one and terminate.
1151 * (4) "../" -- strip one, eat slash and continue.
1157 } else if (is_dir_sep(src
[1])) {
1160 while (is_dir_sep(*src
))
1163 } else if (src
[1] == '.') {
1168 } else if (is_dir_sep(src
[2])) {
1171 while (is_dir_sep(*src
))
1178 /* copy up to the next '/', and eat all '/' */
1179 while ((c
= *src
++) != '\0' && !is_dir_sep(c
))
1181 if (is_dir_sep(c
)) {
1183 while (is_dir_sep(c
))
1192 * dst0..dst is prefix portion, and dst[-1] is '/';
1195 dst
--; /* go to trailing '/' */
1198 /* Windows: dst[-1] cannot be backslash anymore */
1199 while (dst0
< dst
&& dst
[-1] != '/')
1201 if (prefix_len
&& *prefix_len
> dst
- dst0
)
1202 *prefix_len
= dst
- dst0
;
1208 int normalize_path_copy(char *dst
, const char *src
)
1210 return normalize_path_copy_len(dst
, src
, NULL
);
1214 * path = Canonical absolute path
1215 * prefixes = string_list containing normalized, absolute paths without
1216 * trailing slashes (except for the root directory, which is denoted by "/").
1218 * Determines, for each path in prefixes, whether the "prefix"
1219 * is an ancestor directory of path. Returns the length of the longest
1220 * ancestor directory, excluding any trailing slashes, or -1 if no prefix
1221 * is an ancestor. (Note that this means 0 is returned if prefixes is
1222 * ["/"].) "/foo" is not considered an ancestor of "/foobar". Directories
1223 * are not considered to be their own ancestors. path must be in a
1224 * canonical form: empty components, or "." or ".." components are not
1227 int longest_ancestor_length(const char *path
, struct string_list
*prefixes
)
1229 int i
, max_len
= -1;
1231 if (!strcmp(path
, "/"))
1234 for (i
= 0; i
< prefixes
->nr
; i
++) {
1235 const char *ceil
= prefixes
->items
[i
].string
;
1236 int len
= strlen(ceil
);
1239 * For root directories (`/`, `C:/`, `//server/share/`)
1240 * adjust the length to exclude the trailing slash.
1242 if (len
> 0 && ceil
[len
- 1] == '/')
1245 if (strncmp(path
, ceil
, len
) ||
1246 path
[len
] != '/' || !path
[len
+ 1])
1247 continue; /* no match */
1256 /* strip arbitrary amount of directory separators at end of path */
1257 static inline int chomp_trailing_dir_sep(const char *path
, int len
)
1259 while (len
&& is_dir_sep(path
[len
- 1]))
1265 * If path ends with suffix (complete path components), returns the offset of
1266 * the last character in the path before the suffix (sans trailing directory
1267 * separators), and -1 otherwise.
1269 static ssize_t
stripped_path_suffix_offset(const char *path
, const char *suffix
)
1271 int path_len
= strlen(path
), suffix_len
= strlen(suffix
);
1273 while (suffix_len
) {
1277 if (is_dir_sep(path
[path_len
- 1])) {
1278 if (!is_dir_sep(suffix
[suffix_len
- 1]))
1280 path_len
= chomp_trailing_dir_sep(path
, path_len
);
1281 suffix_len
= chomp_trailing_dir_sep(suffix
, suffix_len
);
1283 else if (path
[--path_len
] != suffix
[--suffix_len
])
1287 if (path_len
&& !is_dir_sep(path
[path_len
- 1]))
1289 return chomp_trailing_dir_sep(path
, path_len
);
1293 * Returns true if the path ends with components, considering only complete path
1294 * components, and false otherwise.
1296 int ends_with_path_components(const char *path
, const char *components
)
1298 return stripped_path_suffix_offset(path
, components
) != -1;
1302 * If path ends with suffix (complete path components), returns the
1303 * part before suffix (sans trailing directory separators).
1304 * Otherwise returns NULL.
1306 char *strip_path_suffix(const char *path
, const char *suffix
)
1308 ssize_t offset
= stripped_path_suffix_offset(path
, suffix
);
1310 return offset
== -1 ? NULL
: xstrndup(path
, offset
);
1313 int daemon_avoid_alias(const char *p
)
1318 * This resurrects the belts and suspenders paranoia check by HPA
1319 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
1320 * does not do getcwd() based path canonicalization.
1322 * sl becomes true immediately after seeing '/' and continues to
1323 * be true as long as dots continue after that without intervening
1324 * non-dot character.
1326 if (!p
|| (*p
!= '/' && *p
!= '~'))
1336 else if (ch
== '/') {
1338 /* reject //, /./ and /../ */
1343 if (0 < ndot
&& ndot
< 3)
1344 /* reject /.$ and /..$ */
1353 else if (ch
== '/') {
1361 * On NTFS, we need to be careful to disallow certain synonyms of the `.git/`
1364 * - For historical reasons, file names that end in spaces or periods are
1365 * automatically trimmed. Therefore, `.git . . ./` is a valid way to refer
1368 * - For other historical reasons, file names that do not conform to the 8.3
1369 * format (up to eight characters for the basename, three for the file
1370 * extension, certain characters not allowed such as `+`, etc) are associated
1371 * with a so-called "short name", at least on the `C:` drive by default.
1372 * Which means that `git~1/` is a valid way to refer to `.git/`.
1374 * Note: Technically, `.git/` could receive the short name `git~2` if the
1375 * short name `git~1` were already used. In Git, however, we guarantee that
1376 * `.git` is the first item in a directory, therefore it will be associated
1377 * with the short name `git~1` (unless short names are disabled).
1379 * - For yet other historical reasons, NTFS supports so-called "Alternate Data
1380 * Streams", i.e. metadata associated with a given file, referred to via
1381 * `<filename>:<stream-name>:<stream-type>`. There exists a default stream
1382 * type for directories, allowing `.git/` to be accessed via
1383 * `.git::$INDEX_ALLOCATION/`.
1385 * When this function returns 1, it indicates that the specified file/directory
1386 * name refers to a `.git` file or directory, or to any of these synonyms, and
1387 * Git should therefore not track it.
1389 * For performance reasons, _all_ Alternate Data Streams of `.git/` are
1390 * forbidden, not just `::$INDEX_ALLOCATION`.
1392 * This function is intended to be used by `git fsck` even on platforms where
1393 * the backslash is a regular filename character, therefore it needs to handle
1394 * backlash characters in the provided `name` specially: they are interpreted
1395 * as directory separators.
1397 int is_ntfs_dotgit(const char *name
)
1402 * Note that when we don't find `.git` or `git~1` we end up with `name`
1403 * advanced partway through the string. That's okay, though, as we
1404 * return immediately in those cases, without looking at `name` any
1410 if (((c
= *(name
++)) != 'g' && c
!= 'G') ||
1411 ((c
= *(name
++)) != 'i' && c
!= 'I') ||
1412 ((c
= *(name
++)) != 't' && c
!= 'T'))
1414 } else if (c
== 'g' || c
== 'G') {
1416 if (((c
= *(name
++)) != 'i' && c
!= 'I') ||
1417 ((c
= *(name
++)) != 't' && c
!= 'T') ||
1426 if (!c
|| is_xplatform_dir_sep(c
) || c
== ':')
1428 if (c
!= '.' && c
!= ' ')
1433 static int is_ntfs_dot_generic(const char *name
,
1434 const char *dotgit_name
,
1436 const char *dotgit_ntfs_shortname_prefix
)
1441 if ((name
[0] == '.' && !strncasecmp(name
+ 1, dotgit_name
, len
))) {
1443 only_spaces_and_periods
:
1448 if (c
!= ' ' && c
!= '.')
1454 * Is it a regular NTFS short name, i.e. shortened to 6 characters,
1455 * followed by ~1, ... ~4?
1457 if (!strncasecmp(name
, dotgit_name
, 6) && name
[6] == '~' &&
1458 name
[7] >= '1' && name
[7] <= '4') {
1460 goto only_spaces_and_periods
;
1464 * Is it a fall-back NTFS short name (for details, see
1465 * https://en.wikipedia.org/wiki/8.3_filename?
1467 for (i
= 0, saw_tilde
= 0; i
< 8; i
++)
1468 if (name
[i
] == '\0')
1470 else if (saw_tilde
) {
1471 if (name
[i
] < '0' || name
[i
] > '9')
1473 } else if (name
[i
] == '~') {
1474 if (name
[++i
] < '1' || name
[i
] > '9')
1479 else if (name
[i
] & 0x80) {
1481 * We know our needles contain only ASCII, so we clamp
1482 * here to make the results of tolower() sane.
1485 } else if (tolower(name
[i
]) != dotgit_ntfs_shortname_prefix
[i
])
1488 goto only_spaces_and_periods
;
1492 * Inline helper to make sure compiler resolves strlen() on literals at
1495 static inline int is_ntfs_dot_str(const char *name
, const char *dotgit_name
,
1496 const char *dotgit_ntfs_shortname_prefix
)
1498 return is_ntfs_dot_generic(name
, dotgit_name
, strlen(dotgit_name
),
1499 dotgit_ntfs_shortname_prefix
);
1502 int is_ntfs_dotgitmodules(const char *name
)
1504 return is_ntfs_dot_str(name
, "gitmodules", "gi7eba");
1507 int is_ntfs_dotgitignore(const char *name
)
1509 return is_ntfs_dot_str(name
, "gitignore", "gi250a");
1512 int is_ntfs_dotgitattributes(const char *name
)
1514 return is_ntfs_dot_str(name
, "gitattributes", "gi7d29");
1517 int is_ntfs_dotmailmap(const char *name
)
1519 return is_ntfs_dot_str(name
, "mailmap", "maba30");
1522 int looks_like_command_line_option(const char *str
)
1524 return str
&& str
[0] == '-';
1527 char *xdg_config_home_for(const char *subdir
, const char *filename
)
1529 const char *home
, *config_home
;
1533 config_home
= getenv("XDG_CONFIG_HOME");
1534 if (config_home
&& *config_home
)
1535 return mkpathdup("%s/%s/%s", config_home
, subdir
, filename
);
1537 home
= getenv("HOME");
1539 return mkpathdup("%s/.config/%s/%s", home
, subdir
, filename
);
1544 char *xdg_config_home(const char *filename
)
1546 return xdg_config_home_for("git", filename
);
1549 char *xdg_cache_home(const char *filename
)
1551 const char *home
, *cache_home
;
1554 cache_home
= getenv("XDG_CACHE_HOME");
1555 if (cache_home
&& *cache_home
)
1556 return mkpathdup("%s/git/%s", cache_home
, filename
);
1558 home
= getenv("HOME");
1560 return mkpathdup("%s/.cache/git/%s", home
, filename
);
1564 REPO_GIT_PATH_FUNC(squash_msg
, "SQUASH_MSG")
1565 REPO_GIT_PATH_FUNC(merge_msg
, "MERGE_MSG")
1566 REPO_GIT_PATH_FUNC(merge_rr
, "MERGE_RR")
1567 REPO_GIT_PATH_FUNC(merge_mode
, "MERGE_MODE")
1568 REPO_GIT_PATH_FUNC(merge_head
, "MERGE_HEAD")
1569 REPO_GIT_PATH_FUNC(merge_autostash
, "MERGE_AUTOSTASH")
1570 REPO_GIT_PATH_FUNC(auto_merge
, "AUTO_MERGE")
1571 REPO_GIT_PATH_FUNC(fetch_head
, "FETCH_HEAD")
1572 REPO_GIT_PATH_FUNC(shallow
, "shallow")