Sync with 'master'
[git.git] / path.c
blobbd6e25245d5a2b21fb64ab675bdbcdd83fb3f30b
1 /*
2 * Utilities for paths and pathnames
3 */
4 #include "git-compat-util.h"
5 #include "abspath.h"
6 #include "environment.h"
7 #include "gettext.h"
8 #include "repository.h"
9 #include "strbuf.h"
10 #include "string-list.h"
11 #include "dir.h"
12 #include "worktree.h"
13 #include "setup.h"
14 #include "submodule-config.h"
15 #include "path.h"
16 #include "packfile.h"
17 #include "object-store-ll.h"
18 #include "lockfile.h"
19 #include "exec-cmd.h"
21 static int get_st_mode_bits(const char *path, int *mode)
23 struct stat st;
24 if (lstat(path, &st) < 0)
25 return -1;
26 *mode = st.st_mode;
27 return 0;
30 static struct strbuf *get_pathname(void)
32 static struct strbuf pathname_array[4] = {
33 STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
35 static int index;
36 struct strbuf *sb = &pathname_array[index];
37 index = (index + 1) % ARRAY_SIZE(pathname_array);
38 strbuf_reset(sb);
39 return sb;
42 static const char *cleanup_path(const char *path)
44 /* Clean it up */
45 if (skip_prefix(path, "./", &path)) {
46 while (*path == '/')
47 path++;
49 return path;
52 static void strbuf_cleanup_path(struct strbuf *sb)
54 const char *path = cleanup_path(sb->buf);
55 if (path > sb->buf)
56 strbuf_remove(sb, 0, path - sb->buf);
59 static int dir_prefix(const char *buf, const char *dir)
61 int len = strlen(dir);
62 return !strncmp(buf, dir, len) &&
63 (is_dir_sep(buf[len]) || buf[len] == '\0');
66 /* $buf =~ m|$dir/+$file| but without regex */
67 static int is_dir_file(const char *buf, const char *dir, const char *file)
69 int len = strlen(dir);
70 if (strncmp(buf, dir, len) || !is_dir_sep(buf[len]))
71 return 0;
72 while (is_dir_sep(buf[len]))
73 len++;
74 return !strcmp(buf + len, file);
77 static void replace_dir(struct strbuf *buf, int len, const char *newdir)
79 int newlen = strlen(newdir);
80 int need_sep = (buf->buf[len] && !is_dir_sep(buf->buf[len])) &&
81 !is_dir_sep(newdir[newlen - 1]);
82 if (need_sep)
83 len--; /* keep one char, to be replaced with '/' */
84 strbuf_splice(buf, 0, len, newdir, newlen);
85 if (need_sep)
86 buf->buf[newlen] = '/';
89 struct common_dir {
90 /* Not considered garbage for report_linked_checkout_garbage */
91 unsigned ignore_garbage:1;
92 unsigned is_dir:1;
93 /* Belongs to the common dir, though it may contain paths that don't */
94 unsigned is_common:1;
95 const char *path;
98 static struct common_dir common_list[] = {
99 { 0, 1, 1, "branches" },
100 { 0, 1, 1, "common" },
101 { 0, 1, 1, "hooks" },
102 { 0, 1, 1, "info" },
103 { 0, 0, 0, "info/sparse-checkout" },
104 { 1, 1, 1, "logs" },
105 { 1, 0, 0, "logs/HEAD" },
106 { 0, 1, 0, "logs/refs/bisect" },
107 { 0, 1, 0, "logs/refs/rewritten" },
108 { 0, 1, 0, "logs/refs/worktree" },
109 { 0, 1, 1, "lost-found" },
110 { 0, 1, 1, "objects" },
111 { 0, 1, 1, "refs" },
112 { 0, 1, 0, "refs/bisect" },
113 { 0, 1, 0, "refs/rewritten" },
114 { 0, 1, 0, "refs/worktree" },
115 { 0, 1, 1, "remotes" },
116 { 0, 1, 1, "worktrees" },
117 { 0, 1, 1, "rr-cache" },
118 { 0, 1, 1, "svn" },
119 { 0, 0, 1, "config" },
120 { 1, 0, 1, "gc.pid" },
121 { 0, 0, 1, "packed-refs" },
122 { 0, 0, 1, "shallow" },
123 { 0, 0, 0, NULL }
127 * A compressed trie. A trie node consists of zero or more characters that
128 * are common to all elements with this prefix, optionally followed by some
129 * children. If value is not NULL, the trie node is a terminal node.
131 * For example, consider the following set of strings:
132 * abc
133 * def
134 * definite
135 * definition
137 * The trie would look like:
138 * root: len = 0, children a and d non-NULL, value = NULL.
139 * a: len = 2, contents = bc, value = (data for "abc")
140 * d: len = 2, contents = ef, children i non-NULL, value = (data for "def")
141 * i: len = 3, contents = nit, children e and i non-NULL, value = NULL
142 * e: len = 0, children all NULL, value = (data for "definite")
143 * i: len = 2, contents = on, children all NULL,
144 * value = (data for "definition")
146 struct trie {
147 struct trie *children[256];
148 int len;
149 char *contents;
150 void *value;
153 static struct trie *make_trie_node(const char *key, void *value)
155 struct trie *new_node = xcalloc(1, sizeof(*new_node));
156 new_node->len = strlen(key);
157 if (new_node->len) {
158 new_node->contents = xmalloc(new_node->len);
159 memcpy(new_node->contents, key, new_node->len);
161 new_node->value = value;
162 return new_node;
166 * Add a key/value pair to a trie. The key is assumed to be \0-terminated.
167 * If there was an existing value for this key, return it.
169 static void *add_to_trie(struct trie *root, const char *key, void *value)
171 struct trie *child;
172 void *old;
173 int i;
175 if (!*key) {
176 /* we have reached the end of the key */
177 old = root->value;
178 root->value = value;
179 return old;
182 for (i = 0; i < root->len; i++) {
183 if (root->contents[i] == key[i])
184 continue;
187 * Split this node: child will contain this node's
188 * existing children.
190 child = xmalloc(sizeof(*child));
191 memcpy(child->children, root->children, sizeof(root->children));
193 child->len = root->len - i - 1;
194 if (child->len) {
195 child->contents = xstrndup(root->contents + i + 1,
196 child->len);
198 child->value = root->value;
199 root->value = NULL;
200 root->len = i;
202 memset(root->children, 0, sizeof(root->children));
203 root->children[(unsigned char)root->contents[i]] = child;
205 /* This is the newly-added child. */
206 root->children[(unsigned char)key[i]] =
207 make_trie_node(key + i + 1, value);
208 return NULL;
211 /* We have matched the entire compressed section */
212 if (key[i]) {
213 child = root->children[(unsigned char)key[root->len]];
214 if (child) {
215 return add_to_trie(child, key + root->len + 1, value);
216 } else {
217 child = make_trie_node(key + root->len + 1, value);
218 root->children[(unsigned char)key[root->len]] = child;
219 return NULL;
223 old = root->value;
224 root->value = value;
225 return old;
228 typedef int (*match_fn)(const char *unmatched, void *value, void *baton);
231 * Search a trie for some key. Find the longest /-or-\0-terminated
232 * prefix of the key for which the trie contains a value. If there is
233 * no such prefix, return -1. Otherwise call fn with the unmatched
234 * portion of the key and the found value. If fn returns 0 or
235 * positive, then return its return value. If fn returns negative,
236 * then call fn with the next-longest /-terminated prefix of the key
237 * (i.e. a parent directory) for which the trie contains a value, and
238 * handle its return value the same way. If there is no shorter
239 * /-terminated prefix with a value left, then return the negative
240 * return value of the most recent fn invocation.
242 * The key is partially normalized: consecutive slashes are skipped.
244 * For example, consider the trie containing only [logs,
245 * logs/refs/bisect], both with values, but not logs/refs.
247 * | key | unmatched | prefix to node | return value |
248 * |--------------------|----------------|------------------|--------------|
249 * | a | not called | n/a | -1 |
250 * | logstore | not called | n/a | -1 |
251 * | logs | \0 | logs | as per fn |
252 * | logs/ | / | logs | as per fn |
253 * | logs/refs | /refs | logs | as per fn |
254 * | logs/refs/ | /refs/ | logs | as per fn |
255 * | logs/refs/b | /refs/b | logs | as per fn |
256 * | logs/refs/bisected | /refs/bisected | logs | as per fn |
257 * | logs/refs/bisect | \0 | logs/refs/bisect | as per fn |
258 * | logs/refs/bisect/ | / | logs/refs/bisect | as per fn |
259 * | logs/refs/bisect/a | /a | logs/refs/bisect | as per fn |
260 * | (If fn in the previous line returns -1, then fn is called once more:) |
261 * | logs/refs/bisect/a | /refs/bisect/a | logs | as per fn |
262 * |--------------------|----------------|------------------|--------------|
264 static int trie_find(struct trie *root, const char *key, match_fn fn,
265 void *baton)
267 int i;
268 int result;
269 struct trie *child;
271 if (!*key) {
272 /* we have reached the end of the key */
273 if (root->value && !root->len)
274 return fn(key, root->value, baton);
275 else
276 return -1;
279 for (i = 0; i < root->len; i++) {
280 /* Partial path normalization: skip consecutive slashes. */
281 if (key[i] == '/' && key[i+1] == '/') {
282 key++;
283 continue;
285 if (root->contents[i] != key[i])
286 return -1;
289 /* Matched the entire compressed section */
290 key += i;
291 if (!*key) {
292 /* End of key */
293 if (root->value)
294 return fn(key, root->value, baton);
295 else
296 return -1;
299 /* Partial path normalization: skip consecutive slashes */
300 while (key[0] == '/' && key[1] == '/')
301 key++;
303 child = root->children[(unsigned char)*key];
304 if (child)
305 result = trie_find(child, key + 1, fn, baton);
306 else
307 result = -1;
309 if (result >= 0 || (*key != '/' && *key != 0))
310 return result;
311 if (root->value)
312 return fn(key, root->value, baton);
313 else
314 return -1;
317 static struct trie common_trie;
318 static int common_trie_done_setup;
320 static void init_common_trie(void)
322 struct common_dir *p;
324 if (common_trie_done_setup)
325 return;
327 for (p = common_list; p->path; p++)
328 add_to_trie(&common_trie, p->path, p);
330 common_trie_done_setup = 1;
334 * Helper function for update_common_dir: returns 1 if the dir
335 * prefix is common.
337 static int check_common(const char *unmatched, void *value,
338 void *baton UNUSED)
340 struct common_dir *dir = value;
342 if (dir->is_dir && (unmatched[0] == 0 || unmatched[0] == '/'))
343 return dir->is_common;
345 if (!dir->is_dir && unmatched[0] == 0)
346 return dir->is_common;
348 return 0;
351 static void update_common_dir(struct strbuf *buf, int git_dir_len,
352 const char *common_dir)
354 char *base = buf->buf + git_dir_len;
355 int has_lock_suffix = strbuf_strip_suffix(buf, LOCK_SUFFIX);
357 init_common_trie();
358 if (trie_find(&common_trie, base, check_common, NULL) > 0)
359 replace_dir(buf, git_dir_len, common_dir);
361 if (has_lock_suffix)
362 strbuf_addstr(buf, LOCK_SUFFIX);
365 void report_linked_checkout_garbage(void)
367 struct strbuf sb = STRBUF_INIT;
368 const struct common_dir *p;
369 int len;
371 if (!the_repository->different_commondir)
372 return;
373 strbuf_addf(&sb, "%s/", get_git_dir());
374 len = sb.len;
375 for (p = common_list; p->path; p++) {
376 const char *path = p->path;
377 if (p->ignore_garbage)
378 continue;
379 strbuf_setlen(&sb, len);
380 strbuf_addstr(&sb, path);
381 if (file_exists(sb.buf))
382 report_garbage(PACKDIR_FILE_GARBAGE, sb.buf);
384 strbuf_release(&sb);
387 static void adjust_git_path(const struct repository *repo,
388 struct strbuf *buf, int git_dir_len)
390 const char *base = buf->buf + git_dir_len;
391 if (is_dir_file(base, "info", "grafts"))
392 strbuf_splice(buf, 0, buf->len,
393 repo->graft_file, strlen(repo->graft_file));
394 else if (!strcmp(base, "index"))
395 strbuf_splice(buf, 0, buf->len,
396 repo->index_file, strlen(repo->index_file));
397 else if (dir_prefix(base, "objects"))
398 replace_dir(buf, git_dir_len + 7, repo->objects->odb->path);
399 else if (git_hooks_path && dir_prefix(base, "hooks"))
400 replace_dir(buf, git_dir_len + 5, git_hooks_path);
401 else if (repo->different_commondir)
402 update_common_dir(buf, git_dir_len, repo->commondir);
405 static void strbuf_worktree_gitdir(struct strbuf *buf,
406 const struct repository *repo,
407 const struct worktree *wt)
409 if (!wt)
410 strbuf_addstr(buf, repo->gitdir);
411 else if (!wt->id)
412 strbuf_addstr(buf, repo->commondir);
413 else
414 strbuf_git_common_path(buf, repo, "worktrees/%s", wt->id);
417 static void do_git_path(const struct repository *repo,
418 const struct worktree *wt, struct strbuf *buf,
419 const char *fmt, va_list args)
421 int gitdir_len;
422 strbuf_worktree_gitdir(buf, repo, wt);
423 if (buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
424 strbuf_addch(buf, '/');
425 gitdir_len = buf->len;
426 strbuf_vaddf(buf, fmt, args);
427 if (!wt)
428 adjust_git_path(repo, buf, gitdir_len);
429 strbuf_cleanup_path(buf);
432 char *repo_git_path(const struct repository *repo,
433 const char *fmt, ...)
435 struct strbuf path = STRBUF_INIT;
436 va_list args;
437 va_start(args, fmt);
438 do_git_path(repo, NULL, &path, fmt, args);
439 va_end(args);
440 return strbuf_detach(&path, NULL);
443 void strbuf_repo_git_path(struct strbuf *sb,
444 const struct repository *repo,
445 const char *fmt, ...)
447 va_list args;
448 va_start(args, fmt);
449 do_git_path(repo, NULL, sb, fmt, args);
450 va_end(args);
453 char *git_path_buf(struct strbuf *buf, const char *fmt, ...)
455 va_list args;
456 strbuf_reset(buf);
457 va_start(args, fmt);
458 do_git_path(the_repository, NULL, buf, fmt, args);
459 va_end(args);
460 return buf->buf;
463 void strbuf_git_path(struct strbuf *sb, const char *fmt, ...)
465 va_list args;
466 va_start(args, fmt);
467 do_git_path(the_repository, NULL, sb, fmt, args);
468 va_end(args);
471 const char *git_path(const char *fmt, ...)
473 struct strbuf *pathname = get_pathname();
474 va_list args;
475 va_start(args, fmt);
476 do_git_path(the_repository, NULL, pathname, fmt, args);
477 va_end(args);
478 return pathname->buf;
481 char *git_pathdup(const char *fmt, ...)
483 struct strbuf path = STRBUF_INIT;
484 va_list args;
485 va_start(args, fmt);
486 do_git_path(the_repository, NULL, &path, fmt, args);
487 va_end(args);
488 return strbuf_detach(&path, NULL);
491 char *mkpathdup(const char *fmt, ...)
493 struct strbuf sb = STRBUF_INIT;
494 va_list args;
495 va_start(args, fmt);
496 strbuf_vaddf(&sb, fmt, args);
497 va_end(args);
498 strbuf_cleanup_path(&sb);
499 return strbuf_detach(&sb, NULL);
502 const char *mkpath(const char *fmt, ...)
504 va_list args;
505 struct strbuf *pathname = get_pathname();
506 va_start(args, fmt);
507 strbuf_vaddf(pathname, fmt, args);
508 va_end(args);
509 return cleanup_path(pathname->buf);
512 const char *worktree_git_path(const struct worktree *wt, const char *fmt, ...)
514 struct strbuf *pathname = get_pathname();
515 va_list args;
516 va_start(args, fmt);
517 do_git_path(the_repository, wt, pathname, fmt, args);
518 va_end(args);
519 return pathname->buf;
522 static void do_worktree_path(const struct repository *repo,
523 struct strbuf *buf,
524 const char *fmt, va_list args)
526 strbuf_addstr(buf, repo->worktree);
527 if(buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
528 strbuf_addch(buf, '/');
530 strbuf_vaddf(buf, fmt, args);
531 strbuf_cleanup_path(buf);
534 char *repo_worktree_path(const struct repository *repo, const char *fmt, ...)
536 struct strbuf path = STRBUF_INIT;
537 va_list args;
539 if (!repo->worktree)
540 return NULL;
542 va_start(args, fmt);
543 do_worktree_path(repo, &path, fmt, args);
544 va_end(args);
546 return strbuf_detach(&path, NULL);
549 void strbuf_repo_worktree_path(struct strbuf *sb,
550 const struct repository *repo,
551 const char *fmt, ...)
553 va_list args;
555 if (!repo->worktree)
556 return;
558 va_start(args, fmt);
559 do_worktree_path(repo, sb, fmt, args);
560 va_end(args);
563 /* Returns 0 on success, negative on failure. */
564 static int do_submodule_path(struct strbuf *buf, const char *path,
565 const char *fmt, va_list args)
567 struct strbuf git_submodule_common_dir = STRBUF_INIT;
568 struct strbuf git_submodule_dir = STRBUF_INIT;
569 int ret;
571 ret = submodule_to_gitdir(&git_submodule_dir, path);
572 if (ret)
573 goto cleanup;
575 strbuf_complete(&git_submodule_dir, '/');
576 strbuf_addbuf(buf, &git_submodule_dir);
577 strbuf_vaddf(buf, fmt, args);
579 if (get_common_dir_noenv(&git_submodule_common_dir, git_submodule_dir.buf))
580 update_common_dir(buf, git_submodule_dir.len, git_submodule_common_dir.buf);
582 strbuf_cleanup_path(buf);
584 cleanup:
585 strbuf_release(&git_submodule_dir);
586 strbuf_release(&git_submodule_common_dir);
587 return ret;
590 char *git_pathdup_submodule(const char *path, const char *fmt, ...)
592 int err;
593 va_list args;
594 struct strbuf buf = STRBUF_INIT;
595 va_start(args, fmt);
596 err = do_submodule_path(&buf, path, fmt, args);
597 va_end(args);
598 if (err) {
599 strbuf_release(&buf);
600 return NULL;
602 return strbuf_detach(&buf, NULL);
605 int strbuf_git_path_submodule(struct strbuf *buf, const char *path,
606 const char *fmt, ...)
608 int err;
609 va_list args;
610 va_start(args, fmt);
611 err = do_submodule_path(buf, path, fmt, args);
612 va_end(args);
614 return err;
617 static void do_git_common_path(const struct repository *repo,
618 struct strbuf *buf,
619 const char *fmt,
620 va_list args)
622 strbuf_addstr(buf, repo->commondir);
623 if (buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
624 strbuf_addch(buf, '/');
625 strbuf_vaddf(buf, fmt, args);
626 strbuf_cleanup_path(buf);
629 const char *git_common_path(const char *fmt, ...)
631 struct strbuf *pathname = get_pathname();
632 va_list args;
633 va_start(args, fmt);
634 do_git_common_path(the_repository, pathname, fmt, args);
635 va_end(args);
636 return pathname->buf;
639 void strbuf_git_common_path(struct strbuf *sb,
640 const struct repository *repo,
641 const char *fmt, ...)
643 va_list args;
644 va_start(args, fmt);
645 do_git_common_path(repo, sb, fmt, args);
646 va_end(args);
649 static struct passwd *getpw_str(const char *username, size_t len)
651 struct passwd *pw;
652 char *username_z = xmemdupz(username, len);
653 pw = getpwnam(username_z);
654 free(username_z);
655 return pw;
659 * Return a string with ~ and ~user expanded via getpw*. Returns NULL on getpw
660 * failure or if path is NULL.
662 * If real_home is true, strbuf_realpath($HOME) is used in the `~/` expansion.
664 * If the path starts with `%(prefix)/`, the remainder is interpreted as
665 * relative to where Git is installed, and expanded to the absolute path.
667 char *interpolate_path(const char *path, int real_home)
669 struct strbuf user_path = STRBUF_INIT;
670 const char *to_copy = path;
672 if (!path)
673 goto return_null;
675 if (skip_prefix(path, "%(prefix)/", &path))
676 return system_path(path);
678 if (path[0] == '~') {
679 const char *first_slash = strchrnul(path, '/');
680 const char *username = path + 1;
681 size_t username_len = first_slash - username;
682 if (username_len == 0) {
683 const char *home = getenv("HOME");
684 if (!home)
685 goto return_null;
686 if (real_home)
687 strbuf_add_real_path(&user_path, home);
688 else
689 strbuf_addstr(&user_path, home);
690 #ifdef GIT_WINDOWS_NATIVE
691 convert_slashes(user_path.buf);
692 #endif
693 } else {
694 struct passwd *pw = getpw_str(username, username_len);
695 if (!pw)
696 goto return_null;
697 strbuf_addstr(&user_path, pw->pw_dir);
699 to_copy = first_slash;
701 strbuf_addstr(&user_path, to_copy);
702 return strbuf_detach(&user_path, NULL);
703 return_null:
704 strbuf_release(&user_path);
705 return NULL;
709 * First, one directory to try is determined by the following algorithm.
711 * (0) If "strict" is given, the path is used as given and no DWIM is
712 * done. Otherwise:
713 * (1) "~/path" to mean path under the running user's home directory;
714 * (2) "~user/path" to mean path under named user's home directory;
715 * (3) "relative/path" to mean cwd relative directory; or
716 * (4) "/absolute/path" to mean absolute directory.
718 * Unless "strict" is given, we check "%s/.git", "%s", "%s.git/.git", "%s.git"
719 * in this order. We select the first one that is a valid git repository, and
720 * chdir() to it. If none match, or we fail to chdir, we return NULL.
722 * If all goes well, we return the directory we used to chdir() (but
723 * before ~user is expanded), avoiding getcwd() resolving symbolic
724 * links. User relative paths are also returned as they are given,
725 * except DWIM suffixing.
727 const char *enter_repo(const char *path, int strict)
729 static struct strbuf validated_path = STRBUF_INIT;
730 static struct strbuf used_path = STRBUF_INIT;
732 if (!path)
733 return NULL;
735 if (!strict) {
736 static const char *suffix[] = {
737 "/.git", "", ".git/.git", ".git", NULL,
739 const char *gitfile;
740 int len = strlen(path);
741 int i;
742 while ((1 < len) && (path[len-1] == '/'))
743 len--;
746 * We can handle arbitrary-sized buffers, but this remains as a
747 * sanity check on untrusted input.
749 if (PATH_MAX <= len)
750 return NULL;
752 strbuf_reset(&used_path);
753 strbuf_reset(&validated_path);
754 strbuf_add(&used_path, path, len);
755 strbuf_add(&validated_path, path, len);
757 if (used_path.buf[0] == '~') {
758 char *newpath = interpolate_path(used_path.buf, 0);
759 if (!newpath)
760 return NULL;
761 strbuf_attach(&used_path, newpath, strlen(newpath),
762 strlen(newpath));
764 for (i = 0; suffix[i]; i++) {
765 struct stat st;
766 size_t baselen = used_path.len;
767 strbuf_addstr(&used_path, suffix[i]);
768 if (!stat(used_path.buf, &st) &&
769 (S_ISREG(st.st_mode) ||
770 (S_ISDIR(st.st_mode) && is_git_directory(used_path.buf)))) {
771 strbuf_addstr(&validated_path, suffix[i]);
772 break;
774 strbuf_setlen(&used_path, baselen);
776 if (!suffix[i])
777 return NULL;
778 gitfile = read_gitfile(used_path.buf);
779 if (gitfile) {
780 strbuf_reset(&used_path);
781 strbuf_addstr(&used_path, gitfile);
783 if (chdir(used_path.buf))
784 return NULL;
785 path = validated_path.buf;
787 else {
788 const char *gitfile = read_gitfile(path);
789 if (gitfile)
790 path = gitfile;
791 if (chdir(path))
792 return NULL;
795 if (is_git_directory(".")) {
796 set_git_dir(".", 0);
797 check_repository_format(NULL);
798 return path;
801 return NULL;
804 int calc_shared_perm(int mode)
806 int tweak;
808 if (get_shared_repository() < 0)
809 tweak = -get_shared_repository();
810 else
811 tweak = get_shared_repository();
813 if (!(mode & S_IWUSR))
814 tweak &= ~0222;
815 if (mode & S_IXUSR)
816 /* Copy read bits to execute bits */
817 tweak |= (tweak & 0444) >> 2;
818 if (get_shared_repository() < 0)
819 mode = (mode & ~0777) | tweak;
820 else
821 mode |= tweak;
823 return mode;
827 int adjust_shared_perm(const char *path)
829 int old_mode, new_mode;
831 if (!get_shared_repository())
832 return 0;
833 if (get_st_mode_bits(path, &old_mode) < 0)
834 return -1;
836 new_mode = calc_shared_perm(old_mode);
837 if (S_ISDIR(old_mode)) {
838 /* Copy read bits to execute bits */
839 new_mode |= (new_mode & 0444) >> 2;
842 * g+s matters only if any extra access is granted
843 * based on group membership.
845 if (FORCE_DIR_SET_GID && (new_mode & 060))
846 new_mode |= FORCE_DIR_SET_GID;
849 if (((old_mode ^ new_mode) & ~S_IFMT) &&
850 chmod(path, (new_mode & ~S_IFMT)) < 0)
851 return -2;
852 return 0;
855 void safe_create_dir(const char *dir, int share)
857 if (mkdir(dir, 0777) < 0) {
858 if (errno != EEXIST) {
859 perror(dir);
860 exit(1);
863 else if (share && adjust_shared_perm(dir))
864 die(_("Could not make %s writable by group"), dir);
867 static int have_same_root(const char *path1, const char *path2)
869 int is_abs1, is_abs2;
871 is_abs1 = is_absolute_path(path1);
872 is_abs2 = is_absolute_path(path2);
873 return (is_abs1 && is_abs2 && tolower(path1[0]) == tolower(path2[0])) ||
874 (!is_abs1 && !is_abs2);
878 * Give path as relative to prefix.
880 * The strbuf may or may not be used, so do not assume it contains the
881 * returned path.
883 const char *relative_path(const char *in, const char *prefix,
884 struct strbuf *sb)
886 int in_len = in ? strlen(in) : 0;
887 int prefix_len = prefix ? strlen(prefix) : 0;
888 int in_off = 0;
889 int prefix_off = 0;
890 int i = 0, j = 0;
892 if (!in_len)
893 return "./";
894 else if (!prefix_len)
895 return in;
897 if (have_same_root(in, prefix))
898 /* bypass dos_drive, for "c:" is identical to "C:" */
899 i = j = has_dos_drive_prefix(in);
900 else {
901 return in;
904 while (i < prefix_len && j < in_len && prefix[i] == in[j]) {
905 if (is_dir_sep(prefix[i])) {
906 while (is_dir_sep(prefix[i]))
907 i++;
908 while (is_dir_sep(in[j]))
909 j++;
910 prefix_off = i;
911 in_off = j;
912 } else {
913 i++;
914 j++;
918 if (
919 /* "prefix" seems like prefix of "in" */
920 i >= prefix_len &&
922 * but "/foo" is not a prefix of "/foobar"
923 * (i.e. prefix not end with '/')
925 prefix_off < prefix_len) {
926 if (j >= in_len) {
927 /* in="/a/b", prefix="/a/b" */
928 in_off = in_len;
929 } else if (is_dir_sep(in[j])) {
930 /* in="/a/b/c", prefix="/a/b" */
931 while (is_dir_sep(in[j]))
932 j++;
933 in_off = j;
934 } else {
935 /* in="/a/bbb/c", prefix="/a/b" */
936 i = prefix_off;
938 } else if (
939 /* "in" is short than "prefix" */
940 j >= in_len &&
941 /* "in" not end with '/' */
942 in_off < in_len) {
943 if (is_dir_sep(prefix[i])) {
944 /* in="/a/b", prefix="/a/b/c/" */
945 while (is_dir_sep(prefix[i]))
946 i++;
947 in_off = in_len;
950 in += in_off;
951 in_len -= in_off;
953 if (i >= prefix_len) {
954 if (!in_len)
955 return "./";
956 else
957 return in;
960 strbuf_reset(sb);
961 strbuf_grow(sb, in_len);
963 while (i < prefix_len) {
964 if (is_dir_sep(prefix[i])) {
965 strbuf_addstr(sb, "../");
966 while (is_dir_sep(prefix[i]))
967 i++;
968 continue;
970 i++;
972 if (!is_dir_sep(prefix[prefix_len - 1]))
973 strbuf_addstr(sb, "../");
975 strbuf_addstr(sb, in);
977 return sb->buf;
981 * A simpler implementation of relative_path
983 * Get relative path by removing "prefix" from "in". This function
984 * first appears in v1.5.6-1-g044bbbc, and makes git_dir shorter
985 * to increase performance when traversing the path to work_tree.
987 const char *remove_leading_path(const char *in, const char *prefix)
989 static struct strbuf buf = STRBUF_INIT;
990 int i = 0, j = 0;
992 if (!prefix || !prefix[0])
993 return in;
994 while (prefix[i]) {
995 if (is_dir_sep(prefix[i])) {
996 if (!is_dir_sep(in[j]))
997 return in;
998 while (is_dir_sep(prefix[i]))
999 i++;
1000 while (is_dir_sep(in[j]))
1001 j++;
1002 continue;
1003 } else if (in[j] != prefix[i]) {
1004 return in;
1006 i++;
1007 j++;
1009 if (
1010 /* "/foo" is a prefix of "/foo" */
1011 in[j] &&
1012 /* "/foo" is not a prefix of "/foobar" */
1013 !is_dir_sep(prefix[i-1]) && !is_dir_sep(in[j])
1015 return in;
1016 while (is_dir_sep(in[j]))
1017 j++;
1019 strbuf_reset(&buf);
1020 if (!in[j])
1021 strbuf_addstr(&buf, ".");
1022 else
1023 strbuf_addstr(&buf, in + j);
1024 return buf.buf;
1028 * It is okay if dst == src, but they should not overlap otherwise.
1029 * The "dst" buffer must be at least as long as "src"; normalizing may shrink
1030 * the size of the path, but will never grow it.
1032 * Performs the following normalizations on src, storing the result in dst:
1033 * - Ensures that components are separated by '/' (Windows only)
1034 * - Squashes sequences of '/' except "//server/share" on Windows
1035 * - Removes "." components.
1036 * - Removes ".." components, and the components the precede them.
1037 * Returns failure (non-zero) if a ".." component appears as first path
1038 * component anytime during the normalization. Otherwise, returns success (0).
1040 * Note that this function is purely textual. It does not follow symlinks,
1041 * verify the existence of the path, or make any system calls.
1043 * prefix_len != NULL is for a specific case of prefix_pathspec():
1044 * assume that src == dst and src[0..prefix_len-1] is already
1045 * normalized, any time "../" eats up to the prefix_len part,
1046 * prefix_len is reduced. In the end prefix_len is the remaining
1047 * prefix that has not been overridden by user pathspec.
1049 * NEEDSWORK: This function doesn't perform normalization w.r.t. trailing '/'.
1050 * For everything but the root folder itself, the normalized path should not
1051 * end with a '/', then the callers need to be fixed up accordingly.
1054 int normalize_path_copy_len(char *dst, const char *src, int *prefix_len)
1056 char *dst0;
1057 const char *end;
1060 * Copy initial part of absolute path: "/", "C:/", "//server/share/".
1062 end = src + offset_1st_component(src);
1063 while (src < end) {
1064 char c = *src++;
1065 if (is_dir_sep(c))
1066 c = '/';
1067 *dst++ = c;
1069 dst0 = dst;
1071 while (is_dir_sep(*src))
1072 src++;
1074 for (;;) {
1075 char c = *src;
1078 * A path component that begins with . could be
1079 * special:
1080 * (1) "." and ends -- ignore and terminate.
1081 * (2) "./" -- ignore them, eat slash and continue.
1082 * (3) ".." and ends -- strip one and terminate.
1083 * (4) "../" -- strip one, eat slash and continue.
1085 if (c == '.') {
1086 if (!src[1]) {
1087 /* (1) */
1088 src++;
1089 } else if (is_dir_sep(src[1])) {
1090 /* (2) */
1091 src += 2;
1092 while (is_dir_sep(*src))
1093 src++;
1094 continue;
1095 } else if (src[1] == '.') {
1096 if (!src[2]) {
1097 /* (3) */
1098 src += 2;
1099 goto up_one;
1100 } else if (is_dir_sep(src[2])) {
1101 /* (4) */
1102 src += 3;
1103 while (is_dir_sep(*src))
1104 src++;
1105 goto up_one;
1110 /* copy up to the next '/', and eat all '/' */
1111 while ((c = *src++) != '\0' && !is_dir_sep(c))
1112 *dst++ = c;
1113 if (is_dir_sep(c)) {
1114 *dst++ = '/';
1115 while (is_dir_sep(c))
1116 c = *src++;
1117 src--;
1118 } else if (!c)
1119 break;
1120 continue;
1122 up_one:
1124 * dst0..dst is prefix portion, and dst[-1] is '/';
1125 * go up one level.
1127 dst--; /* go to trailing '/' */
1128 if (dst <= dst0)
1129 return -1;
1130 /* Windows: dst[-1] cannot be backslash anymore */
1131 while (dst0 < dst && dst[-1] != '/')
1132 dst--;
1133 if (prefix_len && *prefix_len > dst - dst0)
1134 *prefix_len = dst - dst0;
1136 *dst = '\0';
1137 return 0;
1140 int normalize_path_copy(char *dst, const char *src)
1142 return normalize_path_copy_len(dst, src, NULL);
1145 int strbuf_normalize_path(struct strbuf *src)
1147 struct strbuf dst = STRBUF_INIT;
1149 strbuf_grow(&dst, src->len);
1150 if (normalize_path_copy(dst.buf, src->buf) < 0) {
1151 strbuf_release(&dst);
1152 return -1;
1156 * normalize_path does not tell us the new length, so we have to
1157 * compute it by looking for the new NUL it placed
1159 strbuf_setlen(&dst, strlen(dst.buf));
1160 strbuf_swap(src, &dst);
1161 strbuf_release(&dst);
1162 return 0;
1166 * path = Canonical absolute path
1167 * prefixes = string_list containing normalized, absolute paths without
1168 * trailing slashes (except for the root directory, which is denoted by "/").
1170 * Determines, for each path in prefixes, whether the "prefix"
1171 * is an ancestor directory of path. Returns the length of the longest
1172 * ancestor directory, excluding any trailing slashes, or -1 if no prefix
1173 * is an ancestor. (Note that this means 0 is returned if prefixes is
1174 * ["/"].) "/foo" is not considered an ancestor of "/foobar". Directories
1175 * are not considered to be their own ancestors. path must be in a
1176 * canonical form: empty components, or "." or ".." components are not
1177 * allowed.
1179 int longest_ancestor_length(const char *path, struct string_list *prefixes)
1181 int i, max_len = -1;
1183 if (!strcmp(path, "/"))
1184 return -1;
1186 for (i = 0; i < prefixes->nr; i++) {
1187 const char *ceil = prefixes->items[i].string;
1188 int len = strlen(ceil);
1191 * For root directories (`/`, `C:/`, `//server/share/`)
1192 * adjust the length to exclude the trailing slash.
1194 if (len > 0 && ceil[len - 1] == '/')
1195 len--;
1197 if (strncmp(path, ceil, len) ||
1198 path[len] != '/' || !path[len + 1])
1199 continue; /* no match */
1201 if (len > max_len)
1202 max_len = len;
1205 return max_len;
1208 /* strip arbitrary amount of directory separators at end of path */
1209 static inline int chomp_trailing_dir_sep(const char *path, int len)
1211 while (len && is_dir_sep(path[len - 1]))
1212 len--;
1213 return len;
1217 * If path ends with suffix (complete path components), returns the offset of
1218 * the last character in the path before the suffix (sans trailing directory
1219 * separators), and -1 otherwise.
1221 static ssize_t stripped_path_suffix_offset(const char *path, const char *suffix)
1223 int path_len = strlen(path), suffix_len = strlen(suffix);
1225 while (suffix_len) {
1226 if (!path_len)
1227 return -1;
1229 if (is_dir_sep(path[path_len - 1])) {
1230 if (!is_dir_sep(suffix[suffix_len - 1]))
1231 return -1;
1232 path_len = chomp_trailing_dir_sep(path, path_len);
1233 suffix_len = chomp_trailing_dir_sep(suffix, suffix_len);
1235 else if (path[--path_len] != suffix[--suffix_len])
1236 return -1;
1239 if (path_len && !is_dir_sep(path[path_len - 1]))
1240 return -1;
1241 return chomp_trailing_dir_sep(path, path_len);
1245 * Returns true if the path ends with components, considering only complete path
1246 * components, and false otherwise.
1248 int ends_with_path_components(const char *path, const char *components)
1250 return stripped_path_suffix_offset(path, components) != -1;
1254 * If path ends with suffix (complete path components), returns the
1255 * part before suffix (sans trailing directory separators).
1256 * Otherwise returns NULL.
1258 char *strip_path_suffix(const char *path, const char *suffix)
1260 ssize_t offset = stripped_path_suffix_offset(path, suffix);
1262 return offset == -1 ? NULL : xstrndup(path, offset);
1265 int daemon_avoid_alias(const char *p)
1267 int sl, ndot;
1270 * This resurrects the belts and suspenders paranoia check by HPA
1271 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
1272 * does not do getcwd() based path canonicalization.
1274 * sl becomes true immediately after seeing '/' and continues to
1275 * be true as long as dots continue after that without intervening
1276 * non-dot character.
1278 if (!p || (*p != '/' && *p != '~'))
1279 return -1;
1280 sl = 1; ndot = 0;
1281 p++;
1283 while (1) {
1284 char ch = *p++;
1285 if (sl) {
1286 if (ch == '.')
1287 ndot++;
1288 else if (ch == '/') {
1289 if (ndot < 3)
1290 /* reject //, /./ and /../ */
1291 return -1;
1292 ndot = 0;
1294 else if (ch == 0) {
1295 if (0 < ndot && ndot < 3)
1296 /* reject /.$ and /..$ */
1297 return -1;
1298 return 0;
1300 else
1301 sl = ndot = 0;
1303 else if (ch == 0)
1304 return 0;
1305 else if (ch == '/') {
1306 sl = 1;
1307 ndot = 0;
1313 * On NTFS, we need to be careful to disallow certain synonyms of the `.git/`
1314 * directory:
1316 * - For historical reasons, file names that end in spaces or periods are
1317 * automatically trimmed. Therefore, `.git . . ./` is a valid way to refer
1318 * to `.git/`.
1320 * - For other historical reasons, file names that do not conform to the 8.3
1321 * format (up to eight characters for the basename, three for the file
1322 * extension, certain characters not allowed such as `+`, etc) are associated
1323 * with a so-called "short name", at least on the `C:` drive by default.
1324 * Which means that `git~1/` is a valid way to refer to `.git/`.
1326 * Note: Technically, `.git/` could receive the short name `git~2` if the
1327 * short name `git~1` were already used. In Git, however, we guarantee that
1328 * `.git` is the first item in a directory, therefore it will be associated
1329 * with the short name `git~1` (unless short names are disabled).
1331 * - For yet other historical reasons, NTFS supports so-called "Alternate Data
1332 * Streams", i.e. metadata associated with a given file, referred to via
1333 * `<filename>:<stream-name>:<stream-type>`. There exists a default stream
1334 * type for directories, allowing `.git/` to be accessed via
1335 * `.git::$INDEX_ALLOCATION/`.
1337 * When this function returns 1, it indicates that the specified file/directory
1338 * name refers to a `.git` file or directory, or to any of these synonyms, and
1339 * Git should therefore not track it.
1341 * For performance reasons, _all_ Alternate Data Streams of `.git/` are
1342 * forbidden, not just `::$INDEX_ALLOCATION`.
1344 * This function is intended to be used by `git fsck` even on platforms where
1345 * the backslash is a regular filename character, therefore it needs to handle
1346 * backlash characters in the provided `name` specially: they are interpreted
1347 * as directory separators.
1349 int is_ntfs_dotgit(const char *name)
1351 char c;
1354 * Note that when we don't find `.git` or `git~1` we end up with `name`
1355 * advanced partway through the string. That's okay, though, as we
1356 * return immediately in those cases, without looking at `name` any
1357 * further.
1359 c = *(name++);
1360 if (c == '.') {
1361 /* .git */
1362 if (((c = *(name++)) != 'g' && c != 'G') ||
1363 ((c = *(name++)) != 'i' && c != 'I') ||
1364 ((c = *(name++)) != 't' && c != 'T'))
1365 return 0;
1366 } else if (c == 'g' || c == 'G') {
1367 /* git ~1 */
1368 if (((c = *(name++)) != 'i' && c != 'I') ||
1369 ((c = *(name++)) != 't' && c != 'T') ||
1370 *(name++) != '~' ||
1371 *(name++) != '1')
1372 return 0;
1373 } else
1374 return 0;
1376 for (;;) {
1377 c = *(name++);
1378 if (!c || is_xplatform_dir_sep(c) || c == ':')
1379 return 1;
1380 if (c != '.' && c != ' ')
1381 return 0;
1385 static int is_ntfs_dot_generic(const char *name,
1386 const char *dotgit_name,
1387 size_t len,
1388 const char *dotgit_ntfs_shortname_prefix)
1390 int saw_tilde;
1391 size_t i;
1393 if ((name[0] == '.' && !strncasecmp(name + 1, dotgit_name, len))) {
1394 i = len + 1;
1395 only_spaces_and_periods:
1396 for (;;) {
1397 char c = name[i++];
1398 if (!c || c == ':')
1399 return 1;
1400 if (c != ' ' && c != '.')
1401 return 0;
1406 * Is it a regular NTFS short name, i.e. shortened to 6 characters,
1407 * followed by ~1, ... ~4?
1409 if (!strncasecmp(name, dotgit_name, 6) && name[6] == '~' &&
1410 name[7] >= '1' && name[7] <= '4') {
1411 i = 8;
1412 goto only_spaces_and_periods;
1416 * Is it a fall-back NTFS short name (for details, see
1417 * https://en.wikipedia.org/wiki/8.3_filename?
1419 for (i = 0, saw_tilde = 0; i < 8; i++)
1420 if (name[i] == '\0')
1421 return 0;
1422 else if (saw_tilde) {
1423 if (name[i] < '0' || name[i] > '9')
1424 return 0;
1425 } else if (name[i] == '~') {
1426 if (name[++i] < '1' || name[i] > '9')
1427 return 0;
1428 saw_tilde = 1;
1429 } else if (i >= 6)
1430 return 0;
1431 else if (name[i] & 0x80) {
1433 * We know our needles contain only ASCII, so we clamp
1434 * here to make the results of tolower() sane.
1436 return 0;
1437 } else if (tolower(name[i]) != dotgit_ntfs_shortname_prefix[i])
1438 return 0;
1440 goto only_spaces_and_periods;
1444 * Inline helper to make sure compiler resolves strlen() on literals at
1445 * compile time.
1447 static inline int is_ntfs_dot_str(const char *name, const char *dotgit_name,
1448 const char *dotgit_ntfs_shortname_prefix)
1450 return is_ntfs_dot_generic(name, dotgit_name, strlen(dotgit_name),
1451 dotgit_ntfs_shortname_prefix);
1454 int is_ntfs_dotgitmodules(const char *name)
1456 return is_ntfs_dot_str(name, "gitmodules", "gi7eba");
1459 int is_ntfs_dotgitignore(const char *name)
1461 return is_ntfs_dot_str(name, "gitignore", "gi250a");
1464 int is_ntfs_dotgitattributes(const char *name)
1466 return is_ntfs_dot_str(name, "gitattributes", "gi7d29");
1469 int is_ntfs_dotmailmap(const char *name)
1471 return is_ntfs_dot_str(name, "mailmap", "maba30");
1474 int looks_like_command_line_option(const char *str)
1476 return str && str[0] == '-';
1479 char *xdg_config_home_for(const char *subdir, const char *filename)
1481 const char *home, *config_home;
1483 assert(subdir);
1484 assert(filename);
1485 config_home = getenv("XDG_CONFIG_HOME");
1486 if (config_home && *config_home)
1487 return mkpathdup("%s/%s/%s", config_home, subdir, filename);
1489 home = getenv("HOME");
1490 if (home)
1491 return mkpathdup("%s/.config/%s/%s", home, subdir, filename);
1493 return NULL;
1496 char *xdg_config_home(const char *filename)
1498 return xdg_config_home_for("git", filename);
1501 char *xdg_cache_home(const char *filename)
1503 const char *home, *cache_home;
1505 assert(filename);
1506 cache_home = getenv("XDG_CACHE_HOME");
1507 if (cache_home && *cache_home)
1508 return mkpathdup("%s/git/%s", cache_home, filename);
1510 home = getenv("HOME");
1511 if (home)
1512 return mkpathdup("%s/.cache/git/%s", home, filename);
1513 return NULL;
1516 REPO_GIT_PATH_FUNC(squash_msg, "SQUASH_MSG")
1517 REPO_GIT_PATH_FUNC(merge_msg, "MERGE_MSG")
1518 REPO_GIT_PATH_FUNC(merge_rr, "MERGE_RR")
1519 REPO_GIT_PATH_FUNC(merge_mode, "MERGE_MODE")
1520 REPO_GIT_PATH_FUNC(merge_head, "MERGE_HEAD")
1521 REPO_GIT_PATH_FUNC(fetch_head, "FETCH_HEAD")
1522 REPO_GIT_PATH_FUNC(shallow, "shallow")