bulk-checkin: fix leaking state TODO
[git/gitster.git] / path.c
blob19f7684f3876bd1d88dcd04165abbee37b0f9769
1 /*
2 * Utilities for paths and pathnames
3 */
5 #define USE_THE_REPOSITORY_VARIABLE
7 #include "git-compat-util.h"
8 #include "abspath.h"
9 #include "environment.h"
10 #include "gettext.h"
11 #include "repository.h"
12 #include "strbuf.h"
13 #include "string-list.h"
14 #include "dir.h"
15 #include "worktree.h"
16 #include "setup.h"
17 #include "submodule-config.h"
18 #include "path.h"
19 #include "packfile.h"
20 #include "object-store-ll.h"
21 #include "lockfile.h"
22 #include "exec-cmd.h"
24 static int get_st_mode_bits(const char *path, int *mode)
26 struct stat st;
27 if (lstat(path, &st) < 0)
28 return -1;
29 *mode = st.st_mode;
30 return 0;
33 static struct strbuf *get_pathname(void)
35 static struct strbuf pathname_array[4] = {
36 STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
38 static int index;
39 struct strbuf *sb = &pathname_array[index];
40 index = (index + 1) % ARRAY_SIZE(pathname_array);
41 strbuf_reset(sb);
42 return sb;
45 static const char *cleanup_path(const char *path)
47 /* Clean it up */
48 if (skip_prefix(path, "./", &path)) {
49 while (*path == '/')
50 path++;
52 return path;
55 static void strbuf_cleanup_path(struct strbuf *sb)
57 const char *path = cleanup_path(sb->buf);
58 if (path > sb->buf)
59 strbuf_remove(sb, 0, path - sb->buf);
62 static int dir_prefix(const char *buf, const char *dir)
64 int len = strlen(dir);
65 return !strncmp(buf, dir, len) &&
66 (is_dir_sep(buf[len]) || buf[len] == '\0');
69 /* $buf =~ m|$dir/+$file| but without regex */
70 static int is_dir_file(const char *buf, const char *dir, const char *file)
72 int len = strlen(dir);
73 if (strncmp(buf, dir, len) || !is_dir_sep(buf[len]))
74 return 0;
75 while (is_dir_sep(buf[len]))
76 len++;
77 return !strcmp(buf + len, file);
80 static void replace_dir(struct strbuf *buf, int len, const char *newdir)
82 int newlen = strlen(newdir);
83 int need_sep = (buf->buf[len] && !is_dir_sep(buf->buf[len])) &&
84 !is_dir_sep(newdir[newlen - 1]);
85 if (need_sep)
86 len--; /* keep one char, to be replaced with '/' */
87 strbuf_splice(buf, 0, len, newdir, newlen);
88 if (need_sep)
89 buf->buf[newlen] = '/';
92 struct common_dir {
93 /* Not considered garbage for report_linked_checkout_garbage */
94 unsigned ignore_garbage:1;
95 unsigned is_dir:1;
96 /* Belongs to the common dir, though it may contain paths that don't */
97 unsigned is_common:1;
98 const char *path;
101 static struct common_dir common_list[] = {
102 { 0, 1, 1, "branches" },
103 { 0, 1, 1, "common" },
104 { 0, 1, 1, "hooks" },
105 { 0, 1, 1, "info" },
106 { 0, 0, 0, "info/sparse-checkout" },
107 { 1, 1, 1, "logs" },
108 { 1, 0, 0, "logs/HEAD" },
109 { 0, 1, 0, "logs/refs/bisect" },
110 { 0, 1, 0, "logs/refs/rewritten" },
111 { 0, 1, 0, "logs/refs/worktree" },
112 { 0, 1, 1, "lost-found" },
113 { 0, 1, 1, "objects" },
114 { 0, 1, 1, "refs" },
115 { 0, 1, 0, "refs/bisect" },
116 { 0, 1, 0, "refs/rewritten" },
117 { 0, 1, 0, "refs/worktree" },
118 { 0, 1, 1, "remotes" },
119 { 0, 1, 1, "worktrees" },
120 { 0, 1, 1, "rr-cache" },
121 { 0, 1, 1, "svn" },
122 { 0, 0, 1, "config" },
123 { 1, 0, 1, "gc.pid" },
124 { 0, 0, 1, "packed-refs" },
125 { 0, 0, 1, "shallow" },
126 { 0, 0, 0, NULL }
130 * A compressed trie. A trie node consists of zero or more characters that
131 * are common to all elements with this prefix, optionally followed by some
132 * children. If value is not NULL, the trie node is a terminal node.
134 * For example, consider the following set of strings:
135 * abc
136 * def
137 * definite
138 * definition
140 * The trie would look like:
141 * root: len = 0, children a and d non-NULL, value = NULL.
142 * a: len = 2, contents = bc, value = (data for "abc")
143 * d: len = 2, contents = ef, children i non-NULL, value = (data for "def")
144 * i: len = 3, contents = nit, children e and i non-NULL, value = NULL
145 * e: len = 0, children all NULL, value = (data for "definite")
146 * i: len = 2, contents = on, children all NULL,
147 * value = (data for "definition")
149 struct trie {
150 struct trie *children[256];
151 int len;
152 char *contents;
153 void *value;
156 static struct trie *make_trie_node(const char *key, void *value)
158 struct trie *new_node = xcalloc(1, sizeof(*new_node));
159 new_node->len = strlen(key);
160 if (new_node->len) {
161 new_node->contents = xmalloc(new_node->len);
162 memcpy(new_node->contents, key, new_node->len);
164 new_node->value = value;
165 return new_node;
169 * Add a key/value pair to a trie. The key is assumed to be \0-terminated.
170 * If there was an existing value for this key, return it.
172 static void *add_to_trie(struct trie *root, const char *key, void *value)
174 struct trie *child;
175 void *old;
176 int i;
178 if (!*key) {
179 /* we have reached the end of the key */
180 old = root->value;
181 root->value = value;
182 return old;
185 for (i = 0; i < root->len; i++) {
186 if (root->contents[i] == key[i])
187 continue;
190 * Split this node: child will contain this node's
191 * existing children.
193 child = xmalloc(sizeof(*child));
194 memcpy(child->children, root->children, sizeof(root->children));
196 child->len = root->len - i - 1;
197 if (child->len) {
198 child->contents = xstrndup(root->contents + i + 1,
199 child->len);
201 child->value = root->value;
202 root->value = NULL;
203 root->len = i;
205 memset(root->children, 0, sizeof(root->children));
206 root->children[(unsigned char)root->contents[i]] = child;
208 /* This is the newly-added child. */
209 root->children[(unsigned char)key[i]] =
210 make_trie_node(key + i + 1, value);
211 return NULL;
214 /* We have matched the entire compressed section */
215 if (key[i]) {
216 child = root->children[(unsigned char)key[root->len]];
217 if (child) {
218 return add_to_trie(child, key + root->len + 1, value);
219 } else {
220 child = make_trie_node(key + root->len + 1, value);
221 root->children[(unsigned char)key[root->len]] = child;
222 return NULL;
226 old = root->value;
227 root->value = value;
228 return old;
231 typedef int (*match_fn)(const char *unmatched, void *value, void *baton);
234 * Search a trie for some key. Find the longest /-or-\0-terminated
235 * prefix of the key for which the trie contains a value. If there is
236 * no such prefix, return -1. Otherwise call fn with the unmatched
237 * portion of the key and the found value. If fn returns 0 or
238 * positive, then return its return value. If fn returns negative,
239 * then call fn with the next-longest /-terminated prefix of the key
240 * (i.e. a parent directory) for which the trie contains a value, and
241 * handle its return value the same way. If there is no shorter
242 * /-terminated prefix with a value left, then return the negative
243 * return value of the most recent fn invocation.
245 * The key is partially normalized: consecutive slashes are skipped.
247 * For example, consider the trie containing only [logs,
248 * logs/refs/bisect], both with values, but not logs/refs.
250 * | key | unmatched | prefix to node | return value |
251 * |--------------------|----------------|------------------|--------------|
252 * | a | not called | n/a | -1 |
253 * | logstore | not called | n/a | -1 |
254 * | logs | \0 | logs | as per fn |
255 * | logs/ | / | logs | as per fn |
256 * | logs/refs | /refs | logs | as per fn |
257 * | logs/refs/ | /refs/ | logs | as per fn |
258 * | logs/refs/b | /refs/b | logs | as per fn |
259 * | logs/refs/bisected | /refs/bisected | logs | as per fn |
260 * | logs/refs/bisect | \0 | logs/refs/bisect | as per fn |
261 * | logs/refs/bisect/ | / | logs/refs/bisect | as per fn |
262 * | logs/refs/bisect/a | /a | logs/refs/bisect | as per fn |
263 * | (If fn in the previous line returns -1, then fn is called once more:) |
264 * | logs/refs/bisect/a | /refs/bisect/a | logs | as per fn |
265 * |--------------------|----------------|------------------|--------------|
267 static int trie_find(struct trie *root, const char *key, match_fn fn,
268 void *baton)
270 int i;
271 int result;
272 struct trie *child;
274 if (!*key) {
275 /* we have reached the end of the key */
276 if (root->value && !root->len)
277 return fn(key, root->value, baton);
278 else
279 return -1;
282 for (i = 0; i < root->len; i++) {
283 /* Partial path normalization: skip consecutive slashes. */
284 if (key[i] == '/' && key[i+1] == '/') {
285 key++;
286 continue;
288 if (root->contents[i] != key[i])
289 return -1;
292 /* Matched the entire compressed section */
293 key += i;
294 if (!*key) {
295 /* End of key */
296 if (root->value)
297 return fn(key, root->value, baton);
298 else
299 return -1;
302 /* Partial path normalization: skip consecutive slashes */
303 while (key[0] == '/' && key[1] == '/')
304 key++;
306 child = root->children[(unsigned char)*key];
307 if (child)
308 result = trie_find(child, key + 1, fn, baton);
309 else
310 result = -1;
312 if (result >= 0 || (*key != '/' && *key != 0))
313 return result;
314 if (root->value)
315 return fn(key, root->value, baton);
316 else
317 return -1;
320 static struct trie common_trie;
321 static int common_trie_done_setup;
323 static void init_common_trie(void)
325 struct common_dir *p;
327 if (common_trie_done_setup)
328 return;
330 for (p = common_list; p->path; p++)
331 add_to_trie(&common_trie, p->path, p);
333 common_trie_done_setup = 1;
337 * Helper function for update_common_dir: returns 1 if the dir
338 * prefix is common.
340 static int check_common(const char *unmatched, void *value,
341 void *baton UNUSED)
343 struct common_dir *dir = value;
345 if (dir->is_dir && (unmatched[0] == 0 || unmatched[0] == '/'))
346 return dir->is_common;
348 if (!dir->is_dir && unmatched[0] == 0)
349 return dir->is_common;
351 return 0;
354 static void update_common_dir(struct strbuf *buf, int git_dir_len,
355 const char *common_dir)
357 char *base = buf->buf + git_dir_len;
358 int has_lock_suffix = strbuf_strip_suffix(buf, LOCK_SUFFIX);
360 init_common_trie();
361 if (trie_find(&common_trie, base, check_common, NULL) > 0)
362 replace_dir(buf, git_dir_len, common_dir);
364 if (has_lock_suffix)
365 strbuf_addstr(buf, LOCK_SUFFIX);
368 void report_linked_checkout_garbage(void)
370 struct strbuf sb = STRBUF_INIT;
371 const struct common_dir *p;
372 int len;
374 if (!the_repository->different_commondir)
375 return;
376 strbuf_addf(&sb, "%s/", get_git_dir());
377 len = sb.len;
378 for (p = common_list; p->path; p++) {
379 const char *path = p->path;
380 if (p->ignore_garbage)
381 continue;
382 strbuf_setlen(&sb, len);
383 strbuf_addstr(&sb, path);
384 if (file_exists(sb.buf))
385 report_garbage(PACKDIR_FILE_GARBAGE, sb.buf);
387 strbuf_release(&sb);
390 static void adjust_git_path(const struct repository *repo,
391 struct strbuf *buf, int git_dir_len)
393 const char *base = buf->buf + git_dir_len;
394 if (is_dir_file(base, "info", "grafts"))
395 strbuf_splice(buf, 0, buf->len,
396 repo->graft_file, strlen(repo->graft_file));
397 else if (!strcmp(base, "index"))
398 strbuf_splice(buf, 0, buf->len,
399 repo->index_file, strlen(repo->index_file));
400 else if (dir_prefix(base, "objects"))
401 replace_dir(buf, git_dir_len + 7, repo->objects->odb->path);
402 else if (git_hooks_path && dir_prefix(base, "hooks"))
403 replace_dir(buf, git_dir_len + 5, git_hooks_path);
404 else if (repo->different_commondir)
405 update_common_dir(buf, git_dir_len, repo->commondir);
408 static void strbuf_worktree_gitdir(struct strbuf *buf,
409 const struct repository *repo,
410 const struct worktree *wt)
412 if (!wt)
413 strbuf_addstr(buf, repo->gitdir);
414 else if (!wt->id)
415 strbuf_addstr(buf, repo->commondir);
416 else
417 strbuf_git_common_path(buf, repo, "worktrees/%s", wt->id);
420 static void do_git_path(const struct repository *repo,
421 const struct worktree *wt, struct strbuf *buf,
422 const char *fmt, va_list args)
424 int gitdir_len;
425 strbuf_worktree_gitdir(buf, repo, wt);
426 if (buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
427 strbuf_addch(buf, '/');
428 gitdir_len = buf->len;
429 strbuf_vaddf(buf, fmt, args);
430 if (!wt)
431 adjust_git_path(repo, buf, gitdir_len);
432 strbuf_cleanup_path(buf);
435 char *repo_git_path(const struct repository *repo,
436 const char *fmt, ...)
438 struct strbuf path = STRBUF_INIT;
439 va_list args;
440 va_start(args, fmt);
441 do_git_path(repo, NULL, &path, fmt, args);
442 va_end(args);
443 return strbuf_detach(&path, NULL);
446 void strbuf_repo_git_path(struct strbuf *sb,
447 const struct repository *repo,
448 const char *fmt, ...)
450 va_list args;
451 va_start(args, fmt);
452 do_git_path(repo, NULL, sb, fmt, args);
453 va_end(args);
456 char *git_path_buf(struct strbuf *buf, const char *fmt, ...)
458 va_list args;
459 strbuf_reset(buf);
460 va_start(args, fmt);
461 do_git_path(the_repository, NULL, buf, fmt, args);
462 va_end(args);
463 return buf->buf;
466 void strbuf_git_path(struct strbuf *sb, const char *fmt, ...)
468 va_list args;
469 va_start(args, fmt);
470 do_git_path(the_repository, NULL, sb, fmt, args);
471 va_end(args);
474 const char *git_path(const char *fmt, ...)
476 struct strbuf *pathname = get_pathname();
477 va_list args;
478 va_start(args, fmt);
479 do_git_path(the_repository, NULL, pathname, fmt, args);
480 va_end(args);
481 return pathname->buf;
484 char *git_pathdup(const char *fmt, ...)
486 struct strbuf path = STRBUF_INIT;
487 va_list args;
488 va_start(args, fmt);
489 do_git_path(the_repository, NULL, &path, fmt, args);
490 va_end(args);
491 return strbuf_detach(&path, NULL);
494 char *mkpathdup(const char *fmt, ...)
496 struct strbuf sb = STRBUF_INIT;
497 va_list args;
498 va_start(args, fmt);
499 strbuf_vaddf(&sb, fmt, args);
500 va_end(args);
501 strbuf_cleanup_path(&sb);
502 return strbuf_detach(&sb, NULL);
505 const char *mkpath(const char *fmt, ...)
507 va_list args;
508 struct strbuf *pathname = get_pathname();
509 va_start(args, fmt);
510 strbuf_vaddf(pathname, fmt, args);
511 va_end(args);
512 return cleanup_path(pathname->buf);
515 const char *worktree_git_path(const struct worktree *wt, const char *fmt, ...)
517 struct strbuf *pathname = get_pathname();
518 va_list args;
519 va_start(args, fmt);
520 do_git_path(the_repository, wt, pathname, fmt, args);
521 va_end(args);
522 return pathname->buf;
525 static void do_worktree_path(const struct repository *repo,
526 struct strbuf *buf,
527 const char *fmt, va_list args)
529 strbuf_addstr(buf, repo->worktree);
530 if(buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
531 strbuf_addch(buf, '/');
533 strbuf_vaddf(buf, fmt, args);
534 strbuf_cleanup_path(buf);
537 char *repo_worktree_path(const struct repository *repo, const char *fmt, ...)
539 struct strbuf path = STRBUF_INIT;
540 va_list args;
542 if (!repo->worktree)
543 return NULL;
545 va_start(args, fmt);
546 do_worktree_path(repo, &path, fmt, args);
547 va_end(args);
549 return strbuf_detach(&path, NULL);
552 void strbuf_repo_worktree_path(struct strbuf *sb,
553 const struct repository *repo,
554 const char *fmt, ...)
556 va_list args;
558 if (!repo->worktree)
559 return;
561 va_start(args, fmt);
562 do_worktree_path(repo, sb, fmt, args);
563 va_end(args);
566 /* Returns 0 on success, negative on failure. */
567 static int do_submodule_path(struct strbuf *buf, const char *path,
568 const char *fmt, va_list args)
570 struct strbuf git_submodule_common_dir = STRBUF_INIT;
571 struct strbuf git_submodule_dir = STRBUF_INIT;
572 int ret;
574 ret = submodule_to_gitdir(&git_submodule_dir, path);
575 if (ret)
576 goto cleanup;
578 strbuf_complete(&git_submodule_dir, '/');
579 strbuf_addbuf(buf, &git_submodule_dir);
580 strbuf_vaddf(buf, fmt, args);
582 if (get_common_dir_noenv(&git_submodule_common_dir, git_submodule_dir.buf))
583 update_common_dir(buf, git_submodule_dir.len, git_submodule_common_dir.buf);
585 strbuf_cleanup_path(buf);
587 cleanup:
588 strbuf_release(&git_submodule_dir);
589 strbuf_release(&git_submodule_common_dir);
590 return ret;
593 char *git_pathdup_submodule(const char *path, const char *fmt, ...)
595 int err;
596 va_list args;
597 struct strbuf buf = STRBUF_INIT;
598 va_start(args, fmt);
599 err = do_submodule_path(&buf, path, fmt, args);
600 va_end(args);
601 if (err) {
602 strbuf_release(&buf);
603 return NULL;
605 return strbuf_detach(&buf, NULL);
608 int strbuf_git_path_submodule(struct strbuf *buf, const char *path,
609 const char *fmt, ...)
611 int err;
612 va_list args;
613 va_start(args, fmt);
614 err = do_submodule_path(buf, path, fmt, args);
615 va_end(args);
617 return err;
620 static void do_git_common_path(const struct repository *repo,
621 struct strbuf *buf,
622 const char *fmt,
623 va_list args)
625 strbuf_addstr(buf, repo->commondir);
626 if (buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
627 strbuf_addch(buf, '/');
628 strbuf_vaddf(buf, fmt, args);
629 strbuf_cleanup_path(buf);
632 const char *git_common_path(const char *fmt, ...)
634 struct strbuf *pathname = get_pathname();
635 va_list args;
636 va_start(args, fmt);
637 do_git_common_path(the_repository, pathname, fmt, args);
638 va_end(args);
639 return pathname->buf;
642 void strbuf_git_common_path(struct strbuf *sb,
643 const struct repository *repo,
644 const char *fmt, ...)
646 va_list args;
647 va_start(args, fmt);
648 do_git_common_path(repo, sb, fmt, args);
649 va_end(args);
652 static struct passwd *getpw_str(const char *username, size_t len)
654 struct passwd *pw;
655 char *username_z = xmemdupz(username, len);
656 pw = getpwnam(username_z);
657 free(username_z);
658 return pw;
662 * Return a string with ~ and ~user expanded via getpw*. Returns NULL on getpw
663 * failure or if path is NULL.
665 * If real_home is true, strbuf_realpath($HOME) is used in the `~/` expansion.
667 * If the path starts with `%(prefix)/`, the remainder is interpreted as
668 * relative to where Git is installed, and expanded to the absolute path.
670 char *interpolate_path(const char *path, int real_home)
672 struct strbuf user_path = STRBUF_INIT;
673 const char *to_copy = path;
675 if (!path)
676 goto return_null;
678 if (skip_prefix(path, "%(prefix)/", &path))
679 return system_path(path);
681 if (path[0] == '~') {
682 const char *first_slash = strchrnul(path, '/');
683 const char *username = path + 1;
684 size_t username_len = first_slash - username;
685 if (username_len == 0) {
686 const char *home = getenv("HOME");
687 if (!home)
688 goto return_null;
689 if (real_home)
690 strbuf_add_real_path(&user_path, home);
691 else
692 strbuf_addstr(&user_path, home);
693 #ifdef GIT_WINDOWS_NATIVE
694 convert_slashes(user_path.buf);
695 #endif
696 } else {
697 struct passwd *pw = getpw_str(username, username_len);
698 if (!pw)
699 goto return_null;
700 strbuf_addstr(&user_path, pw->pw_dir);
702 to_copy = first_slash;
704 strbuf_addstr(&user_path, to_copy);
705 return strbuf_detach(&user_path, NULL);
706 return_null:
707 strbuf_release(&user_path);
708 return NULL;
712 * First, one directory to try is determined by the following algorithm.
714 * (0) If "strict" is given, the path is used as given and no DWIM is
715 * done. Otherwise:
716 * (1) "~/path" to mean path under the running user's home directory;
717 * (2) "~user/path" to mean path under named user's home directory;
718 * (3) "relative/path" to mean cwd relative directory; or
719 * (4) "/absolute/path" to mean absolute directory.
721 * Unless "strict" is given, we check "%s/.git", "%s", "%s.git/.git", "%s.git"
722 * in this order. We select the first one that is a valid git repository, and
723 * chdir() to it. If none match, or we fail to chdir, we return NULL.
725 * If all goes well, we return the directory we used to chdir() (but
726 * before ~user is expanded), avoiding getcwd() resolving symbolic
727 * links. User relative paths are also returned as they are given,
728 * except DWIM suffixing.
730 const char *enter_repo(const char *path, int strict)
732 static struct strbuf validated_path = STRBUF_INIT;
733 static struct strbuf used_path = STRBUF_INIT;
735 if (!path)
736 return NULL;
738 if (!strict) {
739 static const char *suffix[] = {
740 "/.git", "", ".git/.git", ".git", NULL,
742 const char *gitfile;
743 int len = strlen(path);
744 int i;
745 while ((1 < len) && (path[len-1] == '/'))
746 len--;
749 * We can handle arbitrary-sized buffers, but this remains as a
750 * sanity check on untrusted input.
752 if (PATH_MAX <= len)
753 return NULL;
755 strbuf_reset(&used_path);
756 strbuf_reset(&validated_path);
757 strbuf_add(&used_path, path, len);
758 strbuf_add(&validated_path, path, len);
760 if (used_path.buf[0] == '~') {
761 char *newpath = interpolate_path(used_path.buf, 0);
762 if (!newpath)
763 return NULL;
764 strbuf_attach(&used_path, newpath, strlen(newpath),
765 strlen(newpath));
767 for (i = 0; suffix[i]; i++) {
768 struct stat st;
769 size_t baselen = used_path.len;
770 strbuf_addstr(&used_path, suffix[i]);
771 if (!stat(used_path.buf, &st) &&
772 (S_ISREG(st.st_mode) ||
773 (S_ISDIR(st.st_mode) && is_git_directory(used_path.buf)))) {
774 strbuf_addstr(&validated_path, suffix[i]);
775 break;
777 strbuf_setlen(&used_path, baselen);
779 if (!suffix[i])
780 return NULL;
781 gitfile = read_gitfile(used_path.buf);
782 die_upon_dubious_ownership(gitfile, NULL, used_path.buf);
783 if (gitfile) {
784 strbuf_reset(&used_path);
785 strbuf_addstr(&used_path, gitfile);
787 if (chdir(used_path.buf))
788 return NULL;
789 path = validated_path.buf;
791 else {
792 const char *gitfile = read_gitfile(path);
793 die_upon_dubious_ownership(gitfile, NULL, path);
794 if (gitfile)
795 path = gitfile;
796 if (chdir(path))
797 return NULL;
800 if (is_git_directory(".")) {
801 set_git_dir(".", 0);
802 check_repository_format(NULL);
803 return path;
806 return NULL;
809 int calc_shared_perm(int mode)
811 int tweak;
813 if (get_shared_repository() < 0)
814 tweak = -get_shared_repository();
815 else
816 tweak = get_shared_repository();
818 if (!(mode & S_IWUSR))
819 tweak &= ~0222;
820 if (mode & S_IXUSR)
821 /* Copy read bits to execute bits */
822 tweak |= (tweak & 0444) >> 2;
823 if (get_shared_repository() < 0)
824 mode = (mode & ~0777) | tweak;
825 else
826 mode |= tweak;
828 return mode;
832 int adjust_shared_perm(const char *path)
834 int old_mode, new_mode;
836 if (!get_shared_repository())
837 return 0;
838 if (get_st_mode_bits(path, &old_mode) < 0)
839 return -1;
841 new_mode = calc_shared_perm(old_mode);
842 if (S_ISDIR(old_mode)) {
843 /* Copy read bits to execute bits */
844 new_mode |= (new_mode & 0444) >> 2;
847 * g+s matters only if any extra access is granted
848 * based on group membership.
850 if (FORCE_DIR_SET_GID && (new_mode & 060))
851 new_mode |= FORCE_DIR_SET_GID;
854 if (((old_mode ^ new_mode) & ~S_IFMT) &&
855 chmod(path, (new_mode & ~S_IFMT)) < 0)
856 return -2;
857 return 0;
860 void safe_create_dir(const char *dir, int share)
862 if (mkdir(dir, 0777) < 0) {
863 if (errno != EEXIST) {
864 perror(dir);
865 exit(1);
868 else if (share && adjust_shared_perm(dir))
869 die(_("Could not make %s writable by group"), dir);
872 static int have_same_root(const char *path1, const char *path2)
874 int is_abs1, is_abs2;
876 is_abs1 = is_absolute_path(path1);
877 is_abs2 = is_absolute_path(path2);
878 return (is_abs1 && is_abs2 && tolower(path1[0]) == tolower(path2[0])) ||
879 (!is_abs1 && !is_abs2);
883 * Give path as relative to prefix.
885 * The strbuf may or may not be used, so do not assume it contains the
886 * returned path.
888 const char *relative_path(const char *in, const char *prefix,
889 struct strbuf *sb)
891 int in_len = in ? strlen(in) : 0;
892 int prefix_len = prefix ? strlen(prefix) : 0;
893 int in_off = 0;
894 int prefix_off = 0;
895 int i = 0, j = 0;
897 if (!in_len)
898 return "./";
899 else if (!prefix_len)
900 return in;
902 if (have_same_root(in, prefix))
903 /* bypass dos_drive, for "c:" is identical to "C:" */
904 i = j = has_dos_drive_prefix(in);
905 else {
906 return in;
909 while (i < prefix_len && j < in_len && prefix[i] == in[j]) {
910 if (is_dir_sep(prefix[i])) {
911 while (is_dir_sep(prefix[i]))
912 i++;
913 while (is_dir_sep(in[j]))
914 j++;
915 prefix_off = i;
916 in_off = j;
917 } else {
918 i++;
919 j++;
923 if (
924 /* "prefix" seems like prefix of "in" */
925 i >= prefix_len &&
927 * but "/foo" is not a prefix of "/foobar"
928 * (i.e. prefix not end with '/')
930 prefix_off < prefix_len) {
931 if (j >= in_len) {
932 /* in="/a/b", prefix="/a/b" */
933 in_off = in_len;
934 } else if (is_dir_sep(in[j])) {
935 /* in="/a/b/c", prefix="/a/b" */
936 while (is_dir_sep(in[j]))
937 j++;
938 in_off = j;
939 } else {
940 /* in="/a/bbb/c", prefix="/a/b" */
941 i = prefix_off;
943 } else if (
944 /* "in" is short than "prefix" */
945 j >= in_len &&
946 /* "in" not end with '/' */
947 in_off < in_len) {
948 if (is_dir_sep(prefix[i])) {
949 /* in="/a/b", prefix="/a/b/c/" */
950 while (is_dir_sep(prefix[i]))
951 i++;
952 in_off = in_len;
955 in += in_off;
956 in_len -= in_off;
958 if (i >= prefix_len) {
959 if (!in_len)
960 return "./";
961 else
962 return in;
965 strbuf_reset(sb);
966 strbuf_grow(sb, in_len);
968 while (i < prefix_len) {
969 if (is_dir_sep(prefix[i])) {
970 strbuf_addstr(sb, "../");
971 while (is_dir_sep(prefix[i]))
972 i++;
973 continue;
975 i++;
977 if (!is_dir_sep(prefix[prefix_len - 1]))
978 strbuf_addstr(sb, "../");
980 strbuf_addstr(sb, in);
982 return sb->buf;
986 * A simpler implementation of relative_path
988 * Get relative path by removing "prefix" from "in". This function
989 * first appears in v1.5.6-1-g044bbbc, and makes git_dir shorter
990 * to increase performance when traversing the path to work_tree.
992 const char *remove_leading_path(const char *in, const char *prefix)
994 static struct strbuf buf = STRBUF_INIT;
995 int i = 0, j = 0;
997 if (!prefix || !prefix[0])
998 return in;
999 while (prefix[i]) {
1000 if (is_dir_sep(prefix[i])) {
1001 if (!is_dir_sep(in[j]))
1002 return in;
1003 while (is_dir_sep(prefix[i]))
1004 i++;
1005 while (is_dir_sep(in[j]))
1006 j++;
1007 continue;
1008 } else if (in[j] != prefix[i]) {
1009 return in;
1011 i++;
1012 j++;
1014 if (
1015 /* "/foo" is a prefix of "/foo" */
1016 in[j] &&
1017 /* "/foo" is not a prefix of "/foobar" */
1018 !is_dir_sep(prefix[i-1]) && !is_dir_sep(in[j])
1020 return in;
1021 while (is_dir_sep(in[j]))
1022 j++;
1024 strbuf_reset(&buf);
1025 if (!in[j])
1026 strbuf_addstr(&buf, ".");
1027 else
1028 strbuf_addstr(&buf, in + j);
1029 return buf.buf;
1033 * It is okay if dst == src, but they should not overlap otherwise.
1034 * The "dst" buffer must be at least as long as "src"; normalizing may shrink
1035 * the size of the path, but will never grow it.
1037 * Performs the following normalizations on src, storing the result in dst:
1038 * - Ensures that components are separated by '/' (Windows only)
1039 * - Squashes sequences of '/' except "//server/share" on Windows
1040 * - Removes "." components.
1041 * - Removes ".." components, and the components the precede them.
1042 * Returns failure (non-zero) if a ".." component appears as first path
1043 * component anytime during the normalization. Otherwise, returns success (0).
1045 * Note that this function is purely textual. It does not follow symlinks,
1046 * verify the existence of the path, or make any system calls.
1048 * prefix_len != NULL is for a specific case of prefix_pathspec():
1049 * assume that src == dst and src[0..prefix_len-1] is already
1050 * normalized, any time "../" eats up to the prefix_len part,
1051 * prefix_len is reduced. In the end prefix_len is the remaining
1052 * prefix that has not been overridden by user pathspec.
1054 * NEEDSWORK: This function doesn't perform normalization w.r.t. trailing '/'.
1055 * For everything but the root folder itself, the normalized path should not
1056 * end with a '/', then the callers need to be fixed up accordingly.
1059 int normalize_path_copy_len(char *dst, const char *src, int *prefix_len)
1061 char *dst0;
1062 const char *end;
1065 * Copy initial part of absolute path: "/", "C:/", "//server/share/".
1067 end = src + offset_1st_component(src);
1068 while (src < end) {
1069 char c = *src++;
1070 if (is_dir_sep(c))
1071 c = '/';
1072 *dst++ = c;
1074 dst0 = dst;
1076 while (is_dir_sep(*src))
1077 src++;
1079 for (;;) {
1080 char c = *src;
1083 * A path component that begins with . could be
1084 * special:
1085 * (1) "." and ends -- ignore and terminate.
1086 * (2) "./" -- ignore them, eat slash and continue.
1087 * (3) ".." and ends -- strip one and terminate.
1088 * (4) "../" -- strip one, eat slash and continue.
1090 if (c == '.') {
1091 if (!src[1]) {
1092 /* (1) */
1093 src++;
1094 } else if (is_dir_sep(src[1])) {
1095 /* (2) */
1096 src += 2;
1097 while (is_dir_sep(*src))
1098 src++;
1099 continue;
1100 } else if (src[1] == '.') {
1101 if (!src[2]) {
1102 /* (3) */
1103 src += 2;
1104 goto up_one;
1105 } else if (is_dir_sep(src[2])) {
1106 /* (4) */
1107 src += 3;
1108 while (is_dir_sep(*src))
1109 src++;
1110 goto up_one;
1115 /* copy up to the next '/', and eat all '/' */
1116 while ((c = *src++) != '\0' && !is_dir_sep(c))
1117 *dst++ = c;
1118 if (is_dir_sep(c)) {
1119 *dst++ = '/';
1120 while (is_dir_sep(c))
1121 c = *src++;
1122 src--;
1123 } else if (!c)
1124 break;
1125 continue;
1127 up_one:
1129 * dst0..dst is prefix portion, and dst[-1] is '/';
1130 * go up one level.
1132 dst--; /* go to trailing '/' */
1133 if (dst <= dst0)
1134 return -1;
1135 /* Windows: dst[-1] cannot be backslash anymore */
1136 while (dst0 < dst && dst[-1] != '/')
1137 dst--;
1138 if (prefix_len && *prefix_len > dst - dst0)
1139 *prefix_len = dst - dst0;
1141 *dst = '\0';
1142 return 0;
1145 int normalize_path_copy(char *dst, const char *src)
1147 return normalize_path_copy_len(dst, src, NULL);
1150 int strbuf_normalize_path(struct strbuf *src)
1152 struct strbuf dst = STRBUF_INIT;
1154 strbuf_grow(&dst, src->len);
1155 if (normalize_path_copy(dst.buf, src->buf) < 0) {
1156 strbuf_release(&dst);
1157 return -1;
1161 * normalize_path does not tell us the new length, so we have to
1162 * compute it by looking for the new NUL it placed
1164 strbuf_setlen(&dst, strlen(dst.buf));
1165 strbuf_swap(src, &dst);
1166 strbuf_release(&dst);
1167 return 0;
1171 * path = Canonical absolute path
1172 * prefixes = string_list containing normalized, absolute paths without
1173 * trailing slashes (except for the root directory, which is denoted by "/").
1175 * Determines, for each path in prefixes, whether the "prefix"
1176 * is an ancestor directory of path. Returns the length of the longest
1177 * ancestor directory, excluding any trailing slashes, or -1 if no prefix
1178 * is an ancestor. (Note that this means 0 is returned if prefixes is
1179 * ["/"].) "/foo" is not considered an ancestor of "/foobar". Directories
1180 * are not considered to be their own ancestors. path must be in a
1181 * canonical form: empty components, or "." or ".." components are not
1182 * allowed.
1184 int longest_ancestor_length(const char *path, struct string_list *prefixes)
1186 int i, max_len = -1;
1188 if (!strcmp(path, "/"))
1189 return -1;
1191 for (i = 0; i < prefixes->nr; i++) {
1192 const char *ceil = prefixes->items[i].string;
1193 int len = strlen(ceil);
1196 * For root directories (`/`, `C:/`, `//server/share/`)
1197 * adjust the length to exclude the trailing slash.
1199 if (len > 0 && ceil[len - 1] == '/')
1200 len--;
1202 if (strncmp(path, ceil, len) ||
1203 path[len] != '/' || !path[len + 1])
1204 continue; /* no match */
1206 if (len > max_len)
1207 max_len = len;
1210 return max_len;
1213 /* strip arbitrary amount of directory separators at end of path */
1214 static inline int chomp_trailing_dir_sep(const char *path, int len)
1216 while (len && is_dir_sep(path[len - 1]))
1217 len--;
1218 return len;
1222 * If path ends with suffix (complete path components), returns the offset of
1223 * the last character in the path before the suffix (sans trailing directory
1224 * separators), and -1 otherwise.
1226 static ssize_t stripped_path_suffix_offset(const char *path, const char *suffix)
1228 int path_len = strlen(path), suffix_len = strlen(suffix);
1230 while (suffix_len) {
1231 if (!path_len)
1232 return -1;
1234 if (is_dir_sep(path[path_len - 1])) {
1235 if (!is_dir_sep(suffix[suffix_len - 1]))
1236 return -1;
1237 path_len = chomp_trailing_dir_sep(path, path_len);
1238 suffix_len = chomp_trailing_dir_sep(suffix, suffix_len);
1240 else if (path[--path_len] != suffix[--suffix_len])
1241 return -1;
1244 if (path_len && !is_dir_sep(path[path_len - 1]))
1245 return -1;
1246 return chomp_trailing_dir_sep(path, path_len);
1250 * Returns true if the path ends with components, considering only complete path
1251 * components, and false otherwise.
1253 int ends_with_path_components(const char *path, const char *components)
1255 return stripped_path_suffix_offset(path, components) != -1;
1259 * If path ends with suffix (complete path components), returns the
1260 * part before suffix (sans trailing directory separators).
1261 * Otherwise returns NULL.
1263 char *strip_path_suffix(const char *path, const char *suffix)
1265 ssize_t offset = stripped_path_suffix_offset(path, suffix);
1267 return offset == -1 ? NULL : xstrndup(path, offset);
1270 int daemon_avoid_alias(const char *p)
1272 int sl, ndot;
1275 * This resurrects the belts and suspenders paranoia check by HPA
1276 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
1277 * does not do getcwd() based path canonicalization.
1279 * sl becomes true immediately after seeing '/' and continues to
1280 * be true as long as dots continue after that without intervening
1281 * non-dot character.
1283 if (!p || (*p != '/' && *p != '~'))
1284 return -1;
1285 sl = 1; ndot = 0;
1286 p++;
1288 while (1) {
1289 char ch = *p++;
1290 if (sl) {
1291 if (ch == '.')
1292 ndot++;
1293 else if (ch == '/') {
1294 if (ndot < 3)
1295 /* reject //, /./ and /../ */
1296 return -1;
1297 ndot = 0;
1299 else if (ch == 0) {
1300 if (0 < ndot && ndot < 3)
1301 /* reject /.$ and /..$ */
1302 return -1;
1303 return 0;
1305 else
1306 sl = ndot = 0;
1308 else if (ch == 0)
1309 return 0;
1310 else if (ch == '/') {
1311 sl = 1;
1312 ndot = 0;
1318 * On NTFS, we need to be careful to disallow certain synonyms of the `.git/`
1319 * directory:
1321 * - For historical reasons, file names that end in spaces or periods are
1322 * automatically trimmed. Therefore, `.git . . ./` is a valid way to refer
1323 * to `.git/`.
1325 * - For other historical reasons, file names that do not conform to the 8.3
1326 * format (up to eight characters for the basename, three for the file
1327 * extension, certain characters not allowed such as `+`, etc) are associated
1328 * with a so-called "short name", at least on the `C:` drive by default.
1329 * Which means that `git~1/` is a valid way to refer to `.git/`.
1331 * Note: Technically, `.git/` could receive the short name `git~2` if the
1332 * short name `git~1` were already used. In Git, however, we guarantee that
1333 * `.git` is the first item in a directory, therefore it will be associated
1334 * with the short name `git~1` (unless short names are disabled).
1336 * - For yet other historical reasons, NTFS supports so-called "Alternate Data
1337 * Streams", i.e. metadata associated with a given file, referred to via
1338 * `<filename>:<stream-name>:<stream-type>`. There exists a default stream
1339 * type for directories, allowing `.git/` to be accessed via
1340 * `.git::$INDEX_ALLOCATION/`.
1342 * When this function returns 1, it indicates that the specified file/directory
1343 * name refers to a `.git` file or directory, or to any of these synonyms, and
1344 * Git should therefore not track it.
1346 * For performance reasons, _all_ Alternate Data Streams of `.git/` are
1347 * forbidden, not just `::$INDEX_ALLOCATION`.
1349 * This function is intended to be used by `git fsck` even on platforms where
1350 * the backslash is a regular filename character, therefore it needs to handle
1351 * backlash characters in the provided `name` specially: they are interpreted
1352 * as directory separators.
1354 int is_ntfs_dotgit(const char *name)
1356 char c;
1359 * Note that when we don't find `.git` or `git~1` we end up with `name`
1360 * advanced partway through the string. That's okay, though, as we
1361 * return immediately in those cases, without looking at `name` any
1362 * further.
1364 c = *(name++);
1365 if (c == '.') {
1366 /* .git */
1367 if (((c = *(name++)) != 'g' && c != 'G') ||
1368 ((c = *(name++)) != 'i' && c != 'I') ||
1369 ((c = *(name++)) != 't' && c != 'T'))
1370 return 0;
1371 } else if (c == 'g' || c == 'G') {
1372 /* git ~1 */
1373 if (((c = *(name++)) != 'i' && c != 'I') ||
1374 ((c = *(name++)) != 't' && c != 'T') ||
1375 *(name++) != '~' ||
1376 *(name++) != '1')
1377 return 0;
1378 } else
1379 return 0;
1381 for (;;) {
1382 c = *(name++);
1383 if (!c || is_xplatform_dir_sep(c) || c == ':')
1384 return 1;
1385 if (c != '.' && c != ' ')
1386 return 0;
1390 static int is_ntfs_dot_generic(const char *name,
1391 const char *dotgit_name,
1392 size_t len,
1393 const char *dotgit_ntfs_shortname_prefix)
1395 int saw_tilde;
1396 size_t i;
1398 if ((name[0] == '.' && !strncasecmp(name + 1, dotgit_name, len))) {
1399 i = len + 1;
1400 only_spaces_and_periods:
1401 for (;;) {
1402 char c = name[i++];
1403 if (!c || c == ':')
1404 return 1;
1405 if (c != ' ' && c != '.')
1406 return 0;
1411 * Is it a regular NTFS short name, i.e. shortened to 6 characters,
1412 * followed by ~1, ... ~4?
1414 if (!strncasecmp(name, dotgit_name, 6) && name[6] == '~' &&
1415 name[7] >= '1' && name[7] <= '4') {
1416 i = 8;
1417 goto only_spaces_and_periods;
1421 * Is it a fall-back NTFS short name (for details, see
1422 * https://en.wikipedia.org/wiki/8.3_filename?
1424 for (i = 0, saw_tilde = 0; i < 8; i++)
1425 if (name[i] == '\0')
1426 return 0;
1427 else if (saw_tilde) {
1428 if (name[i] < '0' || name[i] > '9')
1429 return 0;
1430 } else if (name[i] == '~') {
1431 if (name[++i] < '1' || name[i] > '9')
1432 return 0;
1433 saw_tilde = 1;
1434 } else if (i >= 6)
1435 return 0;
1436 else if (name[i] & 0x80) {
1438 * We know our needles contain only ASCII, so we clamp
1439 * here to make the results of tolower() sane.
1441 return 0;
1442 } else if (tolower(name[i]) != dotgit_ntfs_shortname_prefix[i])
1443 return 0;
1445 goto only_spaces_and_periods;
1449 * Inline helper to make sure compiler resolves strlen() on literals at
1450 * compile time.
1452 static inline int is_ntfs_dot_str(const char *name, const char *dotgit_name,
1453 const char *dotgit_ntfs_shortname_prefix)
1455 return is_ntfs_dot_generic(name, dotgit_name, strlen(dotgit_name),
1456 dotgit_ntfs_shortname_prefix);
1459 int is_ntfs_dotgitmodules(const char *name)
1461 return is_ntfs_dot_str(name, "gitmodules", "gi7eba");
1464 int is_ntfs_dotgitignore(const char *name)
1466 return is_ntfs_dot_str(name, "gitignore", "gi250a");
1469 int is_ntfs_dotgitattributes(const char *name)
1471 return is_ntfs_dot_str(name, "gitattributes", "gi7d29");
1474 int is_ntfs_dotmailmap(const char *name)
1476 return is_ntfs_dot_str(name, "mailmap", "maba30");
1479 int looks_like_command_line_option(const char *str)
1481 return str && str[0] == '-';
1484 char *xdg_config_home_for(const char *subdir, const char *filename)
1486 const char *home, *config_home;
1488 assert(subdir);
1489 assert(filename);
1490 config_home = getenv("XDG_CONFIG_HOME");
1491 if (config_home && *config_home)
1492 return mkpathdup("%s/%s/%s", config_home, subdir, filename);
1494 home = getenv("HOME");
1495 if (home)
1496 return mkpathdup("%s/.config/%s/%s", home, subdir, filename);
1498 return NULL;
1501 char *xdg_config_home(const char *filename)
1503 return xdg_config_home_for("git", filename);
1506 char *xdg_cache_home(const char *filename)
1508 const char *home, *cache_home;
1510 assert(filename);
1511 cache_home = getenv("XDG_CACHE_HOME");
1512 if (cache_home && *cache_home)
1513 return mkpathdup("%s/git/%s", cache_home, filename);
1515 home = getenv("HOME");
1516 if (home)
1517 return mkpathdup("%s/.cache/git/%s", home, filename);
1518 return NULL;
1521 REPO_GIT_PATH_FUNC(squash_msg, "SQUASH_MSG")
1522 REPO_GIT_PATH_FUNC(merge_msg, "MERGE_MSG")
1523 REPO_GIT_PATH_FUNC(merge_rr, "MERGE_RR")
1524 REPO_GIT_PATH_FUNC(merge_mode, "MERGE_MODE")
1525 REPO_GIT_PATH_FUNC(merge_head, "MERGE_HEAD")
1526 REPO_GIT_PATH_FUNC(fetch_head, "FETCH_HEAD")
1527 REPO_GIT_PATH_FUNC(shallow, "shallow")