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.h"
22 static int get_st_mode_bits(const char *path
, int *mode
)
25 if (lstat(path
, &st
) < 0)
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 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(struct repository
*repo
,
389 struct strbuf
*buf
, int git_dir_len
)
391 const char *base
= buf
->buf
+ git_dir_len
;
393 if (is_dir_file(base
, "info", "grafts"))
394 strbuf_splice(buf
, 0, buf
->len
,
395 repo
->graft_file
, strlen(repo
->graft_file
));
396 else if (!strcmp(base
, "index"))
397 strbuf_splice(buf
, 0, buf
->len
,
398 repo
->index_file
, strlen(repo
->index_file
));
399 else if (dir_prefix(base
, "objects"))
400 replace_dir(buf
, git_dir_len
+ 7, repo
->objects
->odb
->path
);
401 else if (repo_settings_get_hooks_path(repo
) && dir_prefix(base
, "hooks"))
402 replace_dir(buf
, git_dir_len
+ 5, repo_settings_get_hooks_path(repo
));
403 else if (repo
->different_commondir
)
404 update_common_dir(buf
, git_dir_len
, repo
->commondir
);
407 static void strbuf_worktree_gitdir(struct strbuf
*buf
,
408 const struct repository
*repo
,
409 const struct worktree
*wt
)
412 strbuf_addstr(buf
, repo
->gitdir
);
414 strbuf_addstr(buf
, repo
->commondir
);
416 repo_common_path_append(repo
, buf
, "worktrees/%s", wt
->id
);
419 static void repo_git_pathv(struct repository
*repo
,
420 const struct worktree
*wt
, struct strbuf
*buf
,
421 const char *fmt
, va_list args
)
424 strbuf_worktree_gitdir(buf
, repo
, wt
);
425 if (buf
->len
&& !is_dir_sep(buf
->buf
[buf
->len
- 1]))
426 strbuf_addch(buf
, '/');
427 gitdir_len
= buf
->len
;
428 strbuf_vaddf(buf
, fmt
, args
);
430 adjust_git_path(repo
, buf
, gitdir_len
);
431 strbuf_cleanup_path(buf
);
434 char *repo_git_path(struct repository
*repo
,
435 const char *fmt
, ...)
437 struct strbuf path
= STRBUF_INIT
;
440 repo_git_pathv(repo
, NULL
, &path
, fmt
, args
);
442 return strbuf_detach(&path
, NULL
);
445 const char *repo_git_path_append(struct repository
*repo
,
447 const char *fmt
, ...)
451 repo_git_pathv(repo
, NULL
, sb
, fmt
, args
);
456 const char *repo_git_path_replace(struct repository
*repo
,
458 const char *fmt
, ...)
463 repo_git_pathv(repo
, NULL
, sb
, fmt
, args
);
468 char *mkpathdup(const char *fmt
, ...)
470 struct strbuf sb
= STRBUF_INIT
;
473 strbuf_vaddf(&sb
, fmt
, args
);
475 strbuf_cleanup_path(&sb
);
476 return strbuf_detach(&sb
, NULL
);
479 const char *mkpath(const char *fmt
, ...)
482 struct strbuf
*pathname
= get_pathname();
484 strbuf_vaddf(pathname
, fmt
, args
);
486 return cleanup_path(pathname
->buf
);
489 const char *worktree_git_path(struct repository
*r
,
490 const struct worktree
*wt
, const char *fmt
, ...)
492 struct strbuf
*pathname
= get_pathname();
495 if (wt
&& wt
->repo
!= r
)
496 BUG("worktree not connected to expected repository");
499 repo_git_pathv(r
, wt
, pathname
, fmt
, args
);
501 return pathname
->buf
;
504 static void do_worktree_path(const struct repository
*repo
,
506 const char *fmt
, va_list args
)
508 strbuf_addstr(buf
, repo
->worktree
);
509 if(buf
->len
&& !is_dir_sep(buf
->buf
[buf
->len
- 1]))
510 strbuf_addch(buf
, '/');
512 strbuf_vaddf(buf
, fmt
, args
);
513 strbuf_cleanup_path(buf
);
516 char *repo_worktree_path(const struct repository
*repo
, const char *fmt
, ...)
518 struct strbuf path
= STRBUF_INIT
;
522 do_worktree_path(repo
, &path
, fmt
, args
);
525 return strbuf_detach(&path
, NULL
);
528 const char *repo_worktree_path_append(const struct repository
*repo
,
530 const char *fmt
, ...)
538 do_worktree_path(repo
, sb
, fmt
, args
);
544 const char *repo_worktree_path_replace(const struct repository
*repo
,
546 const char *fmt
, ...)
555 do_worktree_path(repo
, sb
, fmt
, args
);
561 /* Returns 0 on success, negative on failure. */
562 static int do_submodule_path(struct repository
*repo
,
563 struct strbuf
*buf
, const char *path
,
564 const char *fmt
, va_list args
)
566 struct strbuf git_submodule_common_dir
= STRBUF_INIT
;
567 struct strbuf git_submodule_dir
= STRBUF_INIT
;
570 ret
= submodule_to_gitdir(repo
, &git_submodule_dir
, path
);
574 strbuf_complete(&git_submodule_dir
, '/');
575 strbuf_addbuf(buf
, &git_submodule_dir
);
576 strbuf_vaddf(buf
, fmt
, args
);
578 if (get_common_dir_noenv(&git_submodule_common_dir
, git_submodule_dir
.buf
))
579 update_common_dir(buf
, git_submodule_dir
.len
, git_submodule_common_dir
.buf
);
581 strbuf_cleanup_path(buf
);
584 strbuf_release(&git_submodule_dir
);
585 strbuf_release(&git_submodule_common_dir
);
589 char *repo_submodule_path(struct repository
*repo
,
590 const char *path
, const char *fmt
, ...)
594 struct strbuf buf
= STRBUF_INIT
;
596 err
= do_submodule_path(repo
, &buf
, path
, fmt
, args
);
599 strbuf_release(&buf
);
602 return strbuf_detach(&buf
, NULL
);
605 const char *repo_submodule_path_append(struct repository
*repo
,
608 const char *fmt
, ...)
613 err
= do_submodule_path(repo
, buf
, path
, fmt
, args
);
620 const char *repo_submodule_path_replace(struct repository
*repo
,
623 const char *fmt
, ...)
629 err
= do_submodule_path(repo
, buf
, path
, fmt
, args
);
636 static void repo_common_pathv(const struct repository
*repo
,
641 strbuf_addstr(sb
, repo
->commondir
);
642 if (sb
->len
&& !is_dir_sep(sb
->buf
[sb
->len
- 1]))
643 strbuf_addch(sb
, '/');
644 strbuf_vaddf(sb
, fmt
, args
);
645 strbuf_cleanup_path(sb
);
648 char *repo_common_path(const struct repository
*repo
,
649 const char *fmt
, ...)
651 struct strbuf sb
= STRBUF_INIT
;
654 repo_common_pathv(repo
, &sb
, fmt
, args
);
656 return strbuf_detach(&sb
, NULL
);
659 const char *repo_common_path_append(const struct repository
*repo
,
661 const char *fmt
, ...)
665 repo_common_pathv(repo
, sb
, fmt
, args
);
670 const char *repo_common_path_replace(const struct repository
*repo
,
672 const char *fmt
, ...)
677 repo_common_pathv(repo
, sb
, fmt
, args
);
682 static struct passwd
*getpw_str(const char *username
, size_t len
)
685 char *username_z
= xmemdupz(username
, len
);
686 pw
= getpwnam(username_z
);
692 * Return a string with ~ and ~user expanded via getpw*. Returns NULL on getpw
693 * failure or if path is NULL.
695 * If real_home is true, strbuf_realpath($HOME) is used in the `~/` expansion.
697 * If the path starts with `%(prefix)/`, the remainder is interpreted as
698 * relative to where Git is installed, and expanded to the absolute path.
700 char *interpolate_path(const char *path
, int real_home
)
702 struct strbuf user_path
= STRBUF_INIT
;
703 const char *to_copy
= path
;
708 if (skip_prefix(path
, "%(prefix)/", &path
))
709 return system_path(path
);
711 if (path
[0] == '~') {
712 const char *first_slash
= strchrnul(path
, '/');
713 const char *username
= path
+ 1;
714 size_t username_len
= first_slash
- username
;
715 if (username_len
== 0) {
716 const char *home
= getenv("HOME");
720 strbuf_add_real_path(&user_path
, home
);
722 strbuf_addstr(&user_path
, home
);
723 #ifdef GIT_WINDOWS_NATIVE
724 convert_slashes(user_path
.buf
);
727 struct passwd
*pw
= getpw_str(username
, username_len
);
730 strbuf_addstr(&user_path
, pw
->pw_dir
);
732 to_copy
= first_slash
;
734 strbuf_addstr(&user_path
, to_copy
);
735 return strbuf_detach(&user_path
, NULL
);
737 strbuf_release(&user_path
);
742 * First, one directory to try is determined by the following algorithm.
744 * (0) If "strict" is given, the path is used as given and no DWIM is
746 * (1) "~/path" to mean path under the running user's home directory;
747 * (2) "~user/path" to mean path under named user's home directory;
748 * (3) "relative/path" to mean cwd relative directory; or
749 * (4) "/absolute/path" to mean absolute directory.
751 * Unless "strict" is given, we check "%s/.git", "%s", "%s.git/.git", "%s.git"
752 * in this order. We select the first one that is a valid git repository, and
753 * chdir() to it. If none match, or we fail to chdir, we return NULL.
755 * If all goes well, we return the directory we used to chdir() (but
756 * before ~user is expanded), avoiding getcwd() resolving symbolic
757 * links. User relative paths are also returned as they are given,
758 * except DWIM suffixing.
760 const char *enter_repo(const char *path
, unsigned flags
)
762 static struct strbuf validated_path
= STRBUF_INIT
;
763 static struct strbuf used_path
= STRBUF_INIT
;
768 if (!(flags
& ENTER_REPO_STRICT
)) {
769 static const char *suffix
[] = {
770 "/.git", "", ".git/.git", ".git", NULL
,
773 int len
= strlen(path
);
775 while ((1 < len
) && (path
[len
-1] == '/'))
779 * We can handle arbitrary-sized buffers, but this remains as a
780 * sanity check on untrusted input.
785 strbuf_reset(&used_path
);
786 strbuf_reset(&validated_path
);
787 strbuf_add(&used_path
, path
, len
);
788 strbuf_add(&validated_path
, path
, len
);
790 if (used_path
.buf
[0] == '~') {
791 char *newpath
= interpolate_path(used_path
.buf
, 0);
794 strbuf_attach(&used_path
, newpath
, strlen(newpath
),
797 for (i
= 0; suffix
[i
]; i
++) {
799 size_t baselen
= used_path
.len
;
800 strbuf_addstr(&used_path
, suffix
[i
]);
801 if (!stat(used_path
.buf
, &st
) &&
802 (S_ISREG(st
.st_mode
) ||
803 (S_ISDIR(st
.st_mode
) && is_git_directory(used_path
.buf
)))) {
804 strbuf_addstr(&validated_path
, suffix
[i
]);
807 strbuf_setlen(&used_path
, baselen
);
811 gitfile
= read_gitfile(used_path
.buf
);
812 if (!(flags
& ENTER_REPO_ANY_OWNER_OK
))
813 die_upon_dubious_ownership(gitfile
, NULL
, used_path
.buf
);
815 strbuf_reset(&used_path
);
816 strbuf_addstr(&used_path
, gitfile
);
818 if (chdir(used_path
.buf
))
820 path
= validated_path
.buf
;
823 const char *gitfile
= read_gitfile(path
);
824 if (!(flags
& ENTER_REPO_ANY_OWNER_OK
))
825 die_upon_dubious_ownership(gitfile
, NULL
, path
);
832 if (is_git_directory(".")) {
834 check_repository_format(NULL
);
841 int calc_shared_perm(struct repository
*repo
,
846 if (repo_settings_get_shared_repository(repo
) < 0)
847 tweak
= -repo_settings_get_shared_repository(repo
);
849 tweak
= repo_settings_get_shared_repository(repo
);
851 if (!(mode
& S_IWUSR
))
854 /* Copy read bits to execute bits */
855 tweak
|= (tweak
& 0444) >> 2;
856 if (repo_settings_get_shared_repository(repo
) < 0)
857 mode
= (mode
& ~0777) | tweak
;
864 int adjust_shared_perm(struct repository
*repo
,
867 int old_mode
, new_mode
;
869 if (!repo_settings_get_shared_repository(repo
))
871 if (get_st_mode_bits(path
, &old_mode
) < 0)
874 new_mode
= calc_shared_perm(repo
, old_mode
);
875 if (S_ISDIR(old_mode
)) {
876 /* Copy read bits to execute bits */
877 new_mode
|= (new_mode
& 0444) >> 2;
880 * g+s matters only if any extra access is granted
881 * based on group membership.
883 if (FORCE_DIR_SET_GID
&& (new_mode
& 060))
884 new_mode
|= FORCE_DIR_SET_GID
;
887 if (((old_mode
^ new_mode
) & ~S_IFMT
) &&
888 chmod(path
, (new_mode
& ~S_IFMT
)) < 0)
893 void safe_create_dir(struct repository
*repo
, const char *dir
, int share
)
895 if (mkdir(dir
, 0777) < 0) {
896 if (errno
!= EEXIST
) {
901 else if (share
&& adjust_shared_perm(repo
, dir
))
902 die(_("Could not make %s writable by group"), dir
);
905 int safe_create_dir_in_gitdir(struct repository
*repo
, const char *path
)
907 if (mkdir(path
, 0777)) {
908 int saved_errno
= errno
;
910 struct strbuf sb
= STRBUF_INIT
;
915 * Are we looking at a path in a symlinked worktree
916 * whose original repository does not yet have it?
917 * e.g. .git/rr-cache pointing at its original
918 * repository in which the user hasn't performed any
919 * conflict resolution yet?
921 if (lstat(path
, &st
) || !S_ISLNK(st
.st_mode
) ||
922 strbuf_readlink(&sb
, path
, st
.st_size
) ||
923 !is_absolute_path(sb
.buf
) ||
924 mkdir(sb
.buf
, 0777)) {
931 return adjust_shared_perm(repo
, path
);
934 static enum scld_error
safe_create_leading_directories_1(struct repository
*repo
,
937 char *next_component
= path
+ offset_1st_component(path
);
938 enum scld_error ret
= SCLD_OK
;
940 while (ret
== SCLD_OK
&& next_component
) {
942 char *slash
= next_component
, slash_character
;
944 while (*slash
&& !is_dir_sep(*slash
))
950 next_component
= slash
+ 1;
951 while (is_dir_sep(*next_component
))
953 if (!*next_component
)
956 slash_character
= *slash
;
958 if (!stat(path
, &st
)) {
960 if (!S_ISDIR(st
.st_mode
)) {
964 } else if (mkdir(path
, 0777)) {
965 if (errno
== EEXIST
&&
966 !stat(path
, &st
) && S_ISDIR(st
.st_mode
))
967 ; /* somebody created it since we checked */
968 else if (errno
== ENOENT
)
970 * Either mkdir() failed because
971 * somebody just pruned the containing
972 * directory, or stat() failed because
973 * the file that was in our way was
974 * just removed. Either way, inform
975 * the caller that it might be worth
981 } else if (repo
&& adjust_shared_perm(repo
, path
)) {
984 *slash
= slash_character
;
989 enum scld_error
safe_create_leading_directories(struct repository
*repo
,
992 return safe_create_leading_directories_1(repo
, path
);
995 enum scld_error
safe_create_leading_directories_no_share(char *path
)
997 return safe_create_leading_directories_1(NULL
, path
);
1000 enum scld_error
safe_create_leading_directories_const(struct repository
*repo
,
1004 /* path points to cache entries, so xstrdup before messing with it */
1005 char *buf
= xstrdup(path
);
1006 enum scld_error result
= safe_create_leading_directories(repo
, buf
);
1014 int safe_create_file_with_leading_directories(struct repository
*repo
,
1019 fd
= open(path
, O_RDWR
|O_CREAT
|O_EXCL
, 0600);
1024 safe_create_leading_directories_const(repo
, path
);
1025 return open(path
, O_RDWR
|O_CREAT
|O_EXCL
, 0600);
1028 static int have_same_root(const char *path1
, const char *path2
)
1030 int is_abs1
, is_abs2
;
1032 is_abs1
= is_absolute_path(path1
);
1033 is_abs2
= is_absolute_path(path2
);
1034 return (is_abs1
&& is_abs2
&& tolower(path1
[0]) == tolower(path2
[0])) ||
1035 (!is_abs1
&& !is_abs2
);
1039 * Give path as relative to prefix.
1041 * The strbuf may or may not be used, so do not assume it contains the
1044 const char *relative_path(const char *in
, const char *prefix
,
1047 int in_len
= in
? strlen(in
) : 0;
1048 int prefix_len
= prefix
? strlen(prefix
) : 0;
1055 else if (!prefix_len
)
1058 if (have_same_root(in
, prefix
))
1059 /* bypass dos_drive, for "c:" is identical to "C:" */
1060 i
= j
= has_dos_drive_prefix(in
);
1065 while (i
< prefix_len
&& j
< in_len
&& prefix
[i
] == in
[j
]) {
1066 if (is_dir_sep(prefix
[i
])) {
1067 while (is_dir_sep(prefix
[i
]))
1069 while (is_dir_sep(in
[j
]))
1080 /* "prefix" seems like prefix of "in" */
1083 * but "/foo" is not a prefix of "/foobar"
1084 * (i.e. prefix not end with '/')
1086 prefix_off
< prefix_len
) {
1088 /* in="/a/b", prefix="/a/b" */
1090 } else if (is_dir_sep(in
[j
])) {
1091 /* in="/a/b/c", prefix="/a/b" */
1092 while (is_dir_sep(in
[j
]))
1096 /* in="/a/bbb/c", prefix="/a/b" */
1100 /* "in" is short than "prefix" */
1102 /* "in" not end with '/' */
1104 if (is_dir_sep(prefix
[i
])) {
1105 /* in="/a/b", prefix="/a/b/c/" */
1106 while (is_dir_sep(prefix
[i
]))
1114 if (i
>= prefix_len
) {
1122 strbuf_grow(sb
, in_len
);
1124 while (i
< prefix_len
) {
1125 if (is_dir_sep(prefix
[i
])) {
1126 strbuf_addstr(sb
, "../");
1127 while (is_dir_sep(prefix
[i
]))
1133 if (!is_dir_sep(prefix
[prefix_len
- 1]))
1134 strbuf_addstr(sb
, "../");
1136 strbuf_addstr(sb
, in
);
1142 * A simpler implementation of relative_path
1144 * Get relative path by removing "prefix" from "in". This function
1145 * first appears in v1.5.6-1-g044bbbc, and makes git_dir shorter
1146 * to increase performance when traversing the path to work_tree.
1148 const char *remove_leading_path(const char *in
, const char *prefix
)
1150 static struct strbuf buf
= STRBUF_INIT
;
1153 if (!prefix
|| !prefix
[0])
1156 if (is_dir_sep(prefix
[i
])) {
1157 if (!is_dir_sep(in
[j
]))
1159 while (is_dir_sep(prefix
[i
]))
1161 while (is_dir_sep(in
[j
]))
1164 } else if (in
[j
] != prefix
[i
]) {
1171 /* "/foo" is a prefix of "/foo" */
1173 /* "/foo" is not a prefix of "/foobar" */
1174 !is_dir_sep(prefix
[i
-1]) && !is_dir_sep(in
[j
])
1177 while (is_dir_sep(in
[j
]))
1182 strbuf_addstr(&buf
, ".");
1184 strbuf_addstr(&buf
, in
+ j
);
1189 * It is okay if dst == src, but they should not overlap otherwise.
1190 * The "dst" buffer must be at least as long as "src"; normalizing may shrink
1191 * the size of the path, but will never grow it.
1193 * Performs the following normalizations on src, storing the result in dst:
1194 * - Ensures that components are separated by '/' (Windows only)
1195 * - Squashes sequences of '/' except "//server/share" on Windows
1196 * - Removes "." components.
1197 * - Removes ".." components, and the components the precede them.
1198 * Returns failure (non-zero) if a ".." component appears as first path
1199 * component anytime during the normalization. Otherwise, returns success (0).
1201 * Note that this function is purely textual. It does not follow symlinks,
1202 * verify the existence of the path, or make any system calls.
1204 * prefix_len != NULL is for a specific case of prefix_pathspec():
1205 * assume that src == dst and src[0..prefix_len-1] is already
1206 * normalized, any time "../" eats up to the prefix_len part,
1207 * prefix_len is reduced. In the end prefix_len is the remaining
1208 * prefix that has not been overridden by user pathspec.
1210 * NEEDSWORK: This function doesn't perform normalization w.r.t. trailing '/'.
1211 * For everything but the root folder itself, the normalized path should not
1212 * end with a '/', then the callers need to be fixed up accordingly.
1215 int normalize_path_copy_len(char *dst
, const char *src
, int *prefix_len
)
1221 * Copy initial part of absolute path: "/", "C:/", "//server/share/".
1223 end
= src
+ offset_1st_component(src
);
1232 while (is_dir_sep(*src
))
1239 * A path component that begins with . could be
1241 * (1) "." and ends -- ignore and terminate.
1242 * (2) "./" -- ignore them, eat slash and continue.
1243 * (3) ".." and ends -- strip one and terminate.
1244 * (4) "../" -- strip one, eat slash and continue.
1250 } else if (is_dir_sep(src
[1])) {
1253 while (is_dir_sep(*src
))
1256 } else if (src
[1] == '.') {
1261 } else if (is_dir_sep(src
[2])) {
1264 while (is_dir_sep(*src
))
1271 /* copy up to the next '/', and eat all '/' */
1272 while ((c
= *src
++) != '\0' && !is_dir_sep(c
))
1274 if (is_dir_sep(c
)) {
1276 while (is_dir_sep(c
))
1285 * dst0..dst is prefix portion, and dst[-1] is '/';
1288 dst
--; /* go to trailing '/' */
1291 /* Windows: dst[-1] cannot be backslash anymore */
1292 while (dst0
< dst
&& dst
[-1] != '/')
1294 if (prefix_len
&& *prefix_len
> dst
- dst0
)
1295 *prefix_len
= dst
- dst0
;
1301 int normalize_path_copy(char *dst
, const char *src
)
1303 return normalize_path_copy_len(dst
, src
, NULL
);
1306 int strbuf_normalize_path(struct strbuf
*src
)
1308 struct strbuf dst
= STRBUF_INIT
;
1310 strbuf_grow(&dst
, src
->len
);
1311 if (normalize_path_copy(dst
.buf
, src
->buf
) < 0) {
1312 strbuf_release(&dst
);
1317 * normalize_path does not tell us the new length, so we have to
1318 * compute it by looking for the new NUL it placed
1320 strbuf_setlen(&dst
, strlen(dst
.buf
));
1321 strbuf_swap(src
, &dst
);
1322 strbuf_release(&dst
);
1327 * path = Canonical absolute path
1328 * prefixes = string_list containing normalized, absolute paths without
1329 * trailing slashes (except for the root directory, which is denoted by "/").
1331 * Determines, for each path in prefixes, whether the "prefix"
1332 * is an ancestor directory of path. Returns the length of the longest
1333 * ancestor directory, excluding any trailing slashes, or -1 if no prefix
1334 * is an ancestor. (Note that this means 0 is returned if prefixes is
1335 * ["/"].) "/foo" is not considered an ancestor of "/foobar". Directories
1336 * are not considered to be their own ancestors. path must be in a
1337 * canonical form: empty components, or "." or ".." components are not
1340 int longest_ancestor_length(const char *path
, struct string_list
*prefixes
)
1344 if (!strcmp(path
, "/"))
1347 for (size_t i
= 0; i
< prefixes
->nr
; i
++) {
1348 const char *ceil
= prefixes
->items
[i
].string
;
1349 int len
= strlen(ceil
);
1352 * For root directories (`/`, `C:/`, `//server/share/`)
1353 * adjust the length to exclude the trailing slash.
1355 if (len
> 0 && ceil
[len
- 1] == '/')
1358 if (strncmp(path
, ceil
, len
) ||
1359 path
[len
] != '/' || !path
[len
+ 1])
1360 continue; /* no match */
1369 /* strip arbitrary amount of directory separators at end of path */
1370 static inline int chomp_trailing_dir_sep(const char *path
, int len
)
1372 while (len
&& is_dir_sep(path
[len
- 1]))
1378 * If path ends with suffix (complete path components), returns the offset of
1379 * the last character in the path before the suffix (sans trailing directory
1380 * separators), and -1 otherwise.
1382 static ssize_t
stripped_path_suffix_offset(const char *path
, const char *suffix
)
1384 int path_len
= strlen(path
), suffix_len
= strlen(suffix
);
1386 while (suffix_len
) {
1390 if (is_dir_sep(path
[path_len
- 1])) {
1391 if (!is_dir_sep(suffix
[suffix_len
- 1]))
1393 path_len
= chomp_trailing_dir_sep(path
, path_len
);
1394 suffix_len
= chomp_trailing_dir_sep(suffix
, suffix_len
);
1396 else if (path
[--path_len
] != suffix
[--suffix_len
])
1400 if (path_len
&& !is_dir_sep(path
[path_len
- 1]))
1402 return chomp_trailing_dir_sep(path
, path_len
);
1406 * Returns true if the path ends with components, considering only complete path
1407 * components, and false otherwise.
1409 int ends_with_path_components(const char *path
, const char *components
)
1411 return stripped_path_suffix_offset(path
, components
) != -1;
1415 * If path ends with suffix (complete path components), returns the
1416 * part before suffix (sans trailing directory separators).
1417 * Otherwise returns NULL.
1419 char *strip_path_suffix(const char *path
, const char *suffix
)
1421 ssize_t offset
= stripped_path_suffix_offset(path
, suffix
);
1423 return offset
== -1 ? NULL
: xstrndup(path
, offset
);
1426 int daemon_avoid_alias(const char *p
)
1431 * This resurrects the belts and suspenders paranoia check by HPA
1432 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
1433 * does not do getcwd() based path canonicalization.
1435 * sl becomes true immediately after seeing '/' and continues to
1436 * be true as long as dots continue after that without intervening
1437 * non-dot character.
1439 if (!p
|| (*p
!= '/' && *p
!= '~'))
1449 else if (ch
== '/') {
1451 /* reject //, /./ and /../ */
1456 if (0 < ndot
&& ndot
< 3)
1457 /* reject /.$ and /..$ */
1466 else if (ch
== '/') {
1474 * On NTFS, we need to be careful to disallow certain synonyms of the `.git/`
1477 * - For historical reasons, file names that end in spaces or periods are
1478 * automatically trimmed. Therefore, `.git . . ./` is a valid way to refer
1481 * - For other historical reasons, file names that do not conform to the 8.3
1482 * format (up to eight characters for the basename, three for the file
1483 * extension, certain characters not allowed such as `+`, etc) are associated
1484 * with a so-called "short name", at least on the `C:` drive by default.
1485 * Which means that `git~1/` is a valid way to refer to `.git/`.
1487 * Note: Technically, `.git/` could receive the short name `git~2` if the
1488 * short name `git~1` were already used. In Git, however, we guarantee that
1489 * `.git` is the first item in a directory, therefore it will be associated
1490 * with the short name `git~1` (unless short names are disabled).
1492 * - For yet other historical reasons, NTFS supports so-called "Alternate Data
1493 * Streams", i.e. metadata associated with a given file, referred to via
1494 * `<filename>:<stream-name>:<stream-type>`. There exists a default stream
1495 * type for directories, allowing `.git/` to be accessed via
1496 * `.git::$INDEX_ALLOCATION/`.
1498 * When this function returns 1, it indicates that the specified file/directory
1499 * name refers to a `.git` file or directory, or to any of these synonyms, and
1500 * Git should therefore not track it.
1502 * For performance reasons, _all_ Alternate Data Streams of `.git/` are
1503 * forbidden, not just `::$INDEX_ALLOCATION`.
1505 * This function is intended to be used by `git fsck` even on platforms where
1506 * the backslash is a regular filename character, therefore it needs to handle
1507 * backlash characters in the provided `name` specially: they are interpreted
1508 * as directory separators.
1510 int is_ntfs_dotgit(const char *name
)
1515 * Note that when we don't find `.git` or `git~1` we end up with `name`
1516 * advanced partway through the string. That's okay, though, as we
1517 * return immediately in those cases, without looking at `name` any
1523 if (((c
= *(name
++)) != 'g' && c
!= 'G') ||
1524 ((c
= *(name
++)) != 'i' && c
!= 'I') ||
1525 ((c
= *(name
++)) != 't' && c
!= 'T'))
1527 } else if (c
== 'g' || c
== 'G') {
1529 if (((c
= *(name
++)) != 'i' && c
!= 'I') ||
1530 ((c
= *(name
++)) != 't' && c
!= 'T') ||
1539 if (!c
|| is_xplatform_dir_sep(c
) || c
== ':')
1541 if (c
!= '.' && c
!= ' ')
1546 static int is_ntfs_dot_generic(const char *name
,
1547 const char *dotgit_name
,
1549 const char *dotgit_ntfs_shortname_prefix
)
1554 if ((name
[0] == '.' && !strncasecmp(name
+ 1, dotgit_name
, len
))) {
1556 only_spaces_and_periods
:
1561 if (c
!= ' ' && c
!= '.')
1567 * Is it a regular NTFS short name, i.e. shortened to 6 characters,
1568 * followed by ~1, ... ~4?
1570 if (!strncasecmp(name
, dotgit_name
, 6) && name
[6] == '~' &&
1571 name
[7] >= '1' && name
[7] <= '4') {
1573 goto only_spaces_and_periods
;
1577 * Is it a fall-back NTFS short name (for details, see
1578 * https://en.wikipedia.org/wiki/8.3_filename?
1580 for (i
= 0, saw_tilde
= 0; i
< 8; i
++)
1581 if (name
[i
] == '\0')
1583 else if (saw_tilde
) {
1584 if (name
[i
] < '0' || name
[i
] > '9')
1586 } else if (name
[i
] == '~') {
1587 if (name
[++i
] < '1' || name
[i
] > '9')
1592 else if (name
[i
] & 0x80) {
1594 * We know our needles contain only ASCII, so we clamp
1595 * here to make the results of tolower() sane.
1598 } else if (tolower(name
[i
]) != dotgit_ntfs_shortname_prefix
[i
])
1601 goto only_spaces_and_periods
;
1605 * Inline helper to make sure compiler resolves strlen() on literals at
1608 static inline int is_ntfs_dot_str(const char *name
, const char *dotgit_name
,
1609 const char *dotgit_ntfs_shortname_prefix
)
1611 return is_ntfs_dot_generic(name
, dotgit_name
, strlen(dotgit_name
),
1612 dotgit_ntfs_shortname_prefix
);
1615 int is_ntfs_dotgitmodules(const char *name
)
1617 return is_ntfs_dot_str(name
, "gitmodules", "gi7eba");
1620 int is_ntfs_dotgitignore(const char *name
)
1622 return is_ntfs_dot_str(name
, "gitignore", "gi250a");
1625 int is_ntfs_dotgitattributes(const char *name
)
1627 return is_ntfs_dot_str(name
, "gitattributes", "gi7d29");
1630 int is_ntfs_dotmailmap(const char *name
)
1632 return is_ntfs_dot_str(name
, "mailmap", "maba30");
1635 int looks_like_command_line_option(const char *str
)
1637 return str
&& str
[0] == '-';
1640 char *xdg_config_home_for(const char *subdir
, const char *filename
)
1642 const char *home
, *config_home
;
1646 config_home
= getenv("XDG_CONFIG_HOME");
1647 if (config_home
&& *config_home
)
1648 return mkpathdup("%s/%s/%s", config_home
, subdir
, filename
);
1650 home
= getenv("HOME");
1652 return mkpathdup("%s/.config/%s/%s", home
, subdir
, filename
);
1657 char *xdg_config_home(const char *filename
)
1659 return xdg_config_home_for("git", filename
);
1662 char *xdg_cache_home(const char *filename
)
1664 const char *home
, *cache_home
;
1667 cache_home
= getenv("XDG_CACHE_HOME");
1668 if (cache_home
&& *cache_home
)
1669 return mkpathdup("%s/git/%s", cache_home
, filename
);
1671 home
= getenv("HOME");
1673 return mkpathdup("%s/.cache/git/%s", home
, filename
);
1677 REPO_GIT_PATH_FUNC(squash_msg
, "SQUASH_MSG")
1678 REPO_GIT_PATH_FUNC(merge_msg
, "MERGE_MSG")
1679 REPO_GIT_PATH_FUNC(merge_rr
, "MERGE_RR")
1680 REPO_GIT_PATH_FUNC(merge_mode
, "MERGE_MODE")
1681 REPO_GIT_PATH_FUNC(merge_head
, "MERGE_HEAD")
1682 REPO_GIT_PATH_FUNC(fetch_head
, "FETCH_HEAD")
1683 REPO_GIT_PATH_FUNC(shallow
, "shallow")