t7503: add tests for pre-merge-hook
[git/mjg.git] / path.c
blob25e97b8c3f76ce9246d8d985adba9777acd5f43c
1 /*
2 * Utilities for paths and pathnames
3 */
4 #include "cache.h"
5 #include "repository.h"
6 #include "strbuf.h"
7 #include "string-list.h"
8 #include "dir.h"
9 #include "worktree.h"
10 #include "submodule-config.h"
11 #include "path.h"
12 #include "packfile.h"
13 #include "object-store.h"
15 static int get_st_mode_bits(const char *path, int *mode)
17 struct stat st;
18 if (lstat(path, &st) < 0)
19 return -1;
20 *mode = st.st_mode;
21 return 0;
24 static char bad_path[] = "/bad-path/";
26 static struct strbuf *get_pathname(void)
28 static struct strbuf pathname_array[4] = {
29 STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
31 static int index;
32 struct strbuf *sb = &pathname_array[index];
33 index = (index + 1) % ARRAY_SIZE(pathname_array);
34 strbuf_reset(sb);
35 return sb;
38 static const char *cleanup_path(const char *path)
40 /* Clean it up */
41 if (skip_prefix(path, "./", &path)) {
42 while (*path == '/')
43 path++;
45 return path;
48 static void strbuf_cleanup_path(struct strbuf *sb)
50 const char *path = cleanup_path(sb->buf);
51 if (path > sb->buf)
52 strbuf_remove(sb, 0, path - sb->buf);
55 char *mksnpath(char *buf, size_t n, const char *fmt, ...)
57 va_list args;
58 unsigned len;
60 va_start(args, fmt);
61 len = vsnprintf(buf, n, fmt, args);
62 va_end(args);
63 if (len >= n) {
64 strlcpy(buf, bad_path, n);
65 return buf;
67 return (char *)cleanup_path(buf);
70 static int dir_prefix(const char *buf, const char *dir)
72 int len = strlen(dir);
73 return !strncmp(buf, dir, len) &&
74 (is_dir_sep(buf[len]) || buf[len] == '\0');
77 /* $buf =~ m|$dir/+$file| but without regex */
78 static int is_dir_file(const char *buf, const char *dir, const char *file)
80 int len = strlen(dir);
81 if (strncmp(buf, dir, len) || !is_dir_sep(buf[len]))
82 return 0;
83 while (is_dir_sep(buf[len]))
84 len++;
85 return !strcmp(buf + len, file);
88 static void replace_dir(struct strbuf *buf, int len, const char *newdir)
90 int newlen = strlen(newdir);
91 int need_sep = (buf->buf[len] && !is_dir_sep(buf->buf[len])) &&
92 !is_dir_sep(newdir[newlen - 1]);
93 if (need_sep)
94 len--; /* keep one char, to be replaced with '/' */
95 strbuf_splice(buf, 0, len, newdir, newlen);
96 if (need_sep)
97 buf->buf[newlen] = '/';
100 struct common_dir {
101 /* Not considered garbage for report_linked_checkout_garbage */
102 unsigned ignore_garbage:1;
103 unsigned is_dir:1;
104 /* Not common even though its parent is */
105 unsigned exclude:1;
106 const char *dirname;
109 static struct common_dir common_list[] = {
110 { 0, 1, 0, "branches" },
111 { 0, 1, 0, "common" },
112 { 0, 1, 0, "hooks" },
113 { 0, 1, 0, "info" },
114 { 0, 0, 1, "info/sparse-checkout" },
115 { 1, 1, 0, "logs" },
116 { 1, 1, 1, "logs/HEAD" },
117 { 0, 1, 1, "logs/refs/bisect" },
118 { 0, 1, 1, "logs/refs/rewritten" },
119 { 0, 1, 1, "logs/refs/worktree" },
120 { 0, 1, 0, "lost-found" },
121 { 0, 1, 0, "objects" },
122 { 0, 1, 0, "refs" },
123 { 0, 1, 1, "refs/bisect" },
124 { 0, 1, 1, "refs/rewritten" },
125 { 0, 1, 1, "refs/worktree" },
126 { 0, 1, 0, "remotes" },
127 { 0, 1, 0, "worktrees" },
128 { 0, 1, 0, "rr-cache" },
129 { 0, 1, 0, "svn" },
130 { 0, 0, 0, "config" },
131 { 1, 0, 0, "gc.pid" },
132 { 0, 0, 0, "packed-refs" },
133 { 0, 0, 0, "shallow" },
134 { 0, 0, 0, NULL }
138 * A compressed trie. A trie node consists of zero or more characters that
139 * are common to all elements with this prefix, optionally followed by some
140 * children. If value is not NULL, the trie node is a terminal node.
142 * For example, consider the following set of strings:
143 * abc
144 * def
145 * definite
146 * definition
148 * The trie would look like:
149 * root: len = 0, children a and d non-NULL, value = NULL.
150 * a: len = 2, contents = bc, value = (data for "abc")
151 * d: len = 2, contents = ef, children i non-NULL, value = (data for "def")
152 * i: len = 3, contents = nit, children e and i non-NULL, value = NULL
153 * e: len = 0, children all NULL, value = (data for "definite")
154 * i: len = 2, contents = on, children all NULL,
155 * value = (data for "definition")
157 struct trie {
158 struct trie *children[256];
159 int len;
160 char *contents;
161 void *value;
164 static struct trie *make_trie_node(const char *key, void *value)
166 struct trie *new_node = xcalloc(1, sizeof(*new_node));
167 new_node->len = strlen(key);
168 if (new_node->len) {
169 new_node->contents = xmalloc(new_node->len);
170 memcpy(new_node->contents, key, new_node->len);
172 new_node->value = value;
173 return new_node;
177 * Add a key/value pair to a trie. The key is assumed to be \0-terminated.
178 * If there was an existing value for this key, return it.
180 static void *add_to_trie(struct trie *root, const char *key, void *value)
182 struct trie *child;
183 void *old;
184 int i;
186 if (!*key) {
187 /* we have reached the end of the key */
188 old = root->value;
189 root->value = value;
190 return old;
193 for (i = 0; i < root->len; i++) {
194 if (root->contents[i] == key[i])
195 continue;
198 * Split this node: child will contain this node's
199 * existing children.
201 child = xmalloc(sizeof(*child));
202 memcpy(child->children, root->children, sizeof(root->children));
204 child->len = root->len - i - 1;
205 if (child->len) {
206 child->contents = xstrndup(root->contents + i + 1,
207 child->len);
209 child->value = root->value;
210 root->value = NULL;
211 root->len = i;
213 memset(root->children, 0, sizeof(root->children));
214 root->children[(unsigned char)root->contents[i]] = child;
216 /* This is the newly-added child. */
217 root->children[(unsigned char)key[i]] =
218 make_trie_node(key + i + 1, value);
219 return NULL;
222 /* We have matched the entire compressed section */
223 if (key[i]) {
224 child = root->children[(unsigned char)key[root->len]];
225 if (child) {
226 return add_to_trie(child, key + root->len + 1, value);
227 } else {
228 child = make_trie_node(key + root->len + 1, value);
229 root->children[(unsigned char)key[root->len]] = child;
230 return NULL;
234 old = root->value;
235 root->value = value;
236 return old;
239 typedef int (*match_fn)(const char *unmatched, void *data, void *baton);
242 * Search a trie for some key. Find the longest /-or-\0-terminated
243 * prefix of the key for which the trie contains a value. Call fn
244 * with the unmatched portion of the key and the found value, and
245 * return its return value. If there is no such prefix, return -1.
247 * The key is partially normalized: consecutive slashes are skipped.
249 * For example, consider the trie containing only [refs,
250 * refs/worktree] (both with values).
252 * | key | unmatched | val from node | return value |
253 * |-----------------|------------|---------------|--------------|
254 * | a | not called | n/a | -1 |
255 * | refs | \0 | refs | as per fn |
256 * | refs/ | / | refs | as per fn |
257 * | refs/w | /w | refs | as per fn |
258 * | refs/worktree | \0 | refs/worktree | as per fn |
259 * | refs/worktree/ | / | refs/worktree | as per fn |
260 * | refs/worktree/a | /a | refs/worktree | as per fn |
261 * |-----------------|------------|---------------|--------------|
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 return fn(key, root->value, baton);
295 /* Partial path normalization: skip consecutive slashes */
296 while (key[0] == '/' && key[1] == '/')
297 key++;
299 child = root->children[(unsigned char)*key];
300 if (child)
301 result = trie_find(child, key + 1, fn, baton);
302 else
303 result = -1;
305 if (result >= 0 || (*key != '/' && *key != 0))
306 return result;
307 if (root->value)
308 return fn(key, root->value, baton);
309 else
310 return -1;
313 static struct trie common_trie;
314 static int common_trie_done_setup;
316 static void init_common_trie(void)
318 struct common_dir *p;
320 if (common_trie_done_setup)
321 return;
323 for (p = common_list; p->dirname; p++)
324 add_to_trie(&common_trie, p->dirname, p);
326 common_trie_done_setup = 1;
330 * Helper function for update_common_dir: returns 1 if the dir
331 * prefix is common.
333 static int check_common(const char *unmatched, void *value, void *baton)
335 struct common_dir *dir = value;
337 if (!dir)
338 return 0;
340 if (dir->is_dir && (unmatched[0] == 0 || unmatched[0] == '/'))
341 return !dir->exclude;
343 if (!dir->is_dir && unmatched[0] == 0)
344 return !dir->exclude;
346 return 0;
349 static void update_common_dir(struct strbuf *buf, int git_dir_len,
350 const char *common_dir)
352 char *base = buf->buf + git_dir_len;
353 init_common_trie();
354 if (trie_find(&common_trie, base, check_common, NULL) > 0)
355 replace_dir(buf, git_dir_len, common_dir);
358 void report_linked_checkout_garbage(void)
360 struct strbuf sb = STRBUF_INIT;
361 const struct common_dir *p;
362 int len;
364 if (!the_repository->different_commondir)
365 return;
366 strbuf_addf(&sb, "%s/", get_git_dir());
367 len = sb.len;
368 for (p = common_list; p->dirname; p++) {
369 const char *path = p->dirname;
370 if (p->ignore_garbage)
371 continue;
372 strbuf_setlen(&sb, len);
373 strbuf_addstr(&sb, path);
374 if (file_exists(sb.buf))
375 report_garbage(PACKDIR_FILE_GARBAGE, sb.buf);
377 strbuf_release(&sb);
380 static void adjust_git_path(const struct repository *repo,
381 struct strbuf *buf, int git_dir_len)
383 const char *base = buf->buf + git_dir_len;
384 if (is_dir_file(base, "info", "grafts"))
385 strbuf_splice(buf, 0, buf->len,
386 repo->graft_file, strlen(repo->graft_file));
387 else if (!strcmp(base, "index"))
388 strbuf_splice(buf, 0, buf->len,
389 repo->index_file, strlen(repo->index_file));
390 else if (dir_prefix(base, "objects"))
391 replace_dir(buf, git_dir_len + 7, repo->objects->odb->path);
392 else if (git_hooks_path && dir_prefix(base, "hooks"))
393 replace_dir(buf, git_dir_len + 5, git_hooks_path);
394 else if (repo->different_commondir)
395 update_common_dir(buf, git_dir_len, repo->commondir);
398 static void strbuf_worktree_gitdir(struct strbuf *buf,
399 const struct repository *repo,
400 const struct worktree *wt)
402 if (!wt)
403 strbuf_addstr(buf, repo->gitdir);
404 else if (!wt->id)
405 strbuf_addstr(buf, repo->commondir);
406 else
407 strbuf_git_common_path(buf, repo, "worktrees/%s", wt->id);
410 static void do_git_path(const struct repository *repo,
411 const struct worktree *wt, struct strbuf *buf,
412 const char *fmt, va_list args)
414 int gitdir_len;
415 strbuf_worktree_gitdir(buf, repo, wt);
416 if (buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
417 strbuf_addch(buf, '/');
418 gitdir_len = buf->len;
419 strbuf_vaddf(buf, fmt, args);
420 if (!wt)
421 adjust_git_path(repo, buf, gitdir_len);
422 strbuf_cleanup_path(buf);
425 char *repo_git_path(const struct repository *repo,
426 const char *fmt, ...)
428 struct strbuf path = STRBUF_INIT;
429 va_list args;
430 va_start(args, fmt);
431 do_git_path(repo, NULL, &path, fmt, args);
432 va_end(args);
433 return strbuf_detach(&path, NULL);
436 void strbuf_repo_git_path(struct strbuf *sb,
437 const struct repository *repo,
438 const char *fmt, ...)
440 va_list args;
441 va_start(args, fmt);
442 do_git_path(repo, NULL, sb, fmt, args);
443 va_end(args);
446 char *git_path_buf(struct strbuf *buf, const char *fmt, ...)
448 va_list args;
449 strbuf_reset(buf);
450 va_start(args, fmt);
451 do_git_path(the_repository, NULL, buf, fmt, args);
452 va_end(args);
453 return buf->buf;
456 void strbuf_git_path(struct strbuf *sb, const char *fmt, ...)
458 va_list args;
459 va_start(args, fmt);
460 do_git_path(the_repository, NULL, sb, fmt, args);
461 va_end(args);
464 const char *git_path(const char *fmt, ...)
466 struct strbuf *pathname = get_pathname();
467 va_list args;
468 va_start(args, fmt);
469 do_git_path(the_repository, NULL, pathname, fmt, args);
470 va_end(args);
471 return pathname->buf;
474 char *git_pathdup(const char *fmt, ...)
476 struct strbuf path = STRBUF_INIT;
477 va_list args;
478 va_start(args, fmt);
479 do_git_path(the_repository, NULL, &path, fmt, args);
480 va_end(args);
481 return strbuf_detach(&path, NULL);
484 char *mkpathdup(const char *fmt, ...)
486 struct strbuf sb = STRBUF_INIT;
487 va_list args;
488 va_start(args, fmt);
489 strbuf_vaddf(&sb, fmt, args);
490 va_end(args);
491 strbuf_cleanup_path(&sb);
492 return strbuf_detach(&sb, NULL);
495 const char *mkpath(const char *fmt, ...)
497 va_list args;
498 struct strbuf *pathname = get_pathname();
499 va_start(args, fmt);
500 strbuf_vaddf(pathname, fmt, args);
501 va_end(args);
502 return cleanup_path(pathname->buf);
505 const char *worktree_git_path(const struct worktree *wt, const char *fmt, ...)
507 struct strbuf *pathname = get_pathname();
508 va_list args;
509 va_start(args, fmt);
510 do_git_path(the_repository, wt, pathname, fmt, args);
511 va_end(args);
512 return pathname->buf;
515 static void do_worktree_path(const struct repository *repo,
516 struct strbuf *buf,
517 const char *fmt, va_list args)
519 strbuf_addstr(buf, repo->worktree);
520 if(buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
521 strbuf_addch(buf, '/');
523 strbuf_vaddf(buf, fmt, args);
524 strbuf_cleanup_path(buf);
527 char *repo_worktree_path(const struct repository *repo, const char *fmt, ...)
529 struct strbuf path = STRBUF_INIT;
530 va_list args;
532 if (!repo->worktree)
533 return NULL;
535 va_start(args, fmt);
536 do_worktree_path(repo, &path, fmt, args);
537 va_end(args);
539 return strbuf_detach(&path, NULL);
542 void strbuf_repo_worktree_path(struct strbuf *sb,
543 const struct repository *repo,
544 const char *fmt, ...)
546 va_list args;
548 if (!repo->worktree)
549 return;
551 va_start(args, fmt);
552 do_worktree_path(repo, sb, fmt, args);
553 va_end(args);
556 /* Returns 0 on success, negative on failure. */
557 static int do_submodule_path(struct strbuf *buf, const char *path,
558 const char *fmt, va_list args)
560 struct strbuf git_submodule_common_dir = STRBUF_INIT;
561 struct strbuf git_submodule_dir = STRBUF_INIT;
562 int ret;
564 ret = submodule_to_gitdir(&git_submodule_dir, path);
565 if (ret)
566 goto cleanup;
568 strbuf_complete(&git_submodule_dir, '/');
569 strbuf_addbuf(buf, &git_submodule_dir);
570 strbuf_vaddf(buf, fmt, args);
572 if (get_common_dir_noenv(&git_submodule_common_dir, git_submodule_dir.buf))
573 update_common_dir(buf, git_submodule_dir.len, git_submodule_common_dir.buf);
575 strbuf_cleanup_path(buf);
577 cleanup:
578 strbuf_release(&git_submodule_dir);
579 strbuf_release(&git_submodule_common_dir);
580 return ret;
583 char *git_pathdup_submodule(const char *path, const char *fmt, ...)
585 int err;
586 va_list args;
587 struct strbuf buf = STRBUF_INIT;
588 va_start(args, fmt);
589 err = do_submodule_path(&buf, path, fmt, args);
590 va_end(args);
591 if (err) {
592 strbuf_release(&buf);
593 return NULL;
595 return strbuf_detach(&buf, NULL);
598 int strbuf_git_path_submodule(struct strbuf *buf, const char *path,
599 const char *fmt, ...)
601 int err;
602 va_list args;
603 va_start(args, fmt);
604 err = do_submodule_path(buf, path, fmt, args);
605 va_end(args);
607 return err;
610 static void do_git_common_path(const struct repository *repo,
611 struct strbuf *buf,
612 const char *fmt,
613 va_list args)
615 strbuf_addstr(buf, repo->commondir);
616 if (buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
617 strbuf_addch(buf, '/');
618 strbuf_vaddf(buf, fmt, args);
619 strbuf_cleanup_path(buf);
622 const char *git_common_path(const char *fmt, ...)
624 struct strbuf *pathname = get_pathname();
625 va_list args;
626 va_start(args, fmt);
627 do_git_common_path(the_repository, pathname, fmt, args);
628 va_end(args);
629 return pathname->buf;
632 void strbuf_git_common_path(struct strbuf *sb,
633 const struct repository *repo,
634 const char *fmt, ...)
636 va_list args;
637 va_start(args, fmt);
638 do_git_common_path(repo, sb, fmt, args);
639 va_end(args);
642 int validate_headref(const char *path)
644 struct stat st;
645 char buffer[256];
646 const char *refname;
647 struct object_id oid;
648 int fd;
649 ssize_t len;
651 if (lstat(path, &st) < 0)
652 return -1;
654 /* Make sure it is a "refs/.." symlink */
655 if (S_ISLNK(st.st_mode)) {
656 len = readlink(path, buffer, sizeof(buffer)-1);
657 if (len >= 5 && !memcmp("refs/", buffer, 5))
658 return 0;
659 return -1;
663 * Anything else, just open it and try to see if it is a symbolic ref.
665 fd = open(path, O_RDONLY);
666 if (fd < 0)
667 return -1;
668 len = read_in_full(fd, buffer, sizeof(buffer)-1);
669 close(fd);
671 if (len < 0)
672 return -1;
673 buffer[len] = '\0';
676 * Is it a symbolic ref?
678 if (skip_prefix(buffer, "ref:", &refname)) {
679 while (isspace(*refname))
680 refname++;
681 if (starts_with(refname, "refs/"))
682 return 0;
686 * Is this a detached HEAD?
688 if (!get_oid_hex(buffer, &oid))
689 return 0;
691 return -1;
694 static struct passwd *getpw_str(const char *username, size_t len)
696 struct passwd *pw;
697 char *username_z = xmemdupz(username, len);
698 pw = getpwnam(username_z);
699 free(username_z);
700 return pw;
704 * Return a string with ~ and ~user expanded via getpw*. If buf != NULL,
705 * then it is a newly allocated string. Returns NULL on getpw failure or
706 * if path is NULL.
708 * If real_home is true, real_path($HOME) is used in the expansion.
710 char *expand_user_path(const char *path, int real_home)
712 struct strbuf user_path = STRBUF_INIT;
713 const char *to_copy = path;
715 if (path == NULL)
716 goto return_null;
717 if (path[0] == '~') {
718 const char *first_slash = strchrnul(path, '/');
719 const char *username = path + 1;
720 size_t username_len = first_slash - username;
721 if (username_len == 0) {
722 const char *home = getenv("HOME");
723 if (!home)
724 goto return_null;
725 if (real_home)
726 strbuf_add_real_path(&user_path, home);
727 else
728 strbuf_addstr(&user_path, home);
729 #ifdef GIT_WINDOWS_NATIVE
730 convert_slashes(user_path.buf);
731 #endif
732 } else {
733 struct passwd *pw = getpw_str(username, username_len);
734 if (!pw)
735 goto return_null;
736 strbuf_addstr(&user_path, pw->pw_dir);
738 to_copy = first_slash;
740 strbuf_addstr(&user_path, to_copy);
741 return strbuf_detach(&user_path, NULL);
742 return_null:
743 strbuf_release(&user_path);
744 return NULL;
748 * First, one directory to try is determined by the following algorithm.
750 * (0) If "strict" is given, the path is used as given and no DWIM is
751 * done. Otherwise:
752 * (1) "~/path" to mean path under the running user's home directory;
753 * (2) "~user/path" to mean path under named user's home directory;
754 * (3) "relative/path" to mean cwd relative directory; or
755 * (4) "/absolute/path" to mean absolute directory.
757 * Unless "strict" is given, we check "%s/.git", "%s", "%s.git/.git", "%s.git"
758 * in this order. We select the first one that is a valid git repository, and
759 * chdir() to it. If none match, or we fail to chdir, we return NULL.
761 * If all goes well, we return the directory we used to chdir() (but
762 * before ~user is expanded), avoiding getcwd() resolving symbolic
763 * links. User relative paths are also returned as they are given,
764 * except DWIM suffixing.
766 const char *enter_repo(const char *path, int strict)
768 static struct strbuf validated_path = STRBUF_INIT;
769 static struct strbuf used_path = STRBUF_INIT;
771 if (!path)
772 return NULL;
774 if (!strict) {
775 static const char *suffix[] = {
776 "/.git", "", ".git/.git", ".git", NULL,
778 const char *gitfile;
779 int len = strlen(path);
780 int i;
781 while ((1 < len) && (path[len-1] == '/'))
782 len--;
785 * We can handle arbitrary-sized buffers, but this remains as a
786 * sanity check on untrusted input.
788 if (PATH_MAX <= len)
789 return NULL;
791 strbuf_reset(&used_path);
792 strbuf_reset(&validated_path);
793 strbuf_add(&used_path, path, len);
794 strbuf_add(&validated_path, path, len);
796 if (used_path.buf[0] == '~') {
797 char *newpath = expand_user_path(used_path.buf, 0);
798 if (!newpath)
799 return NULL;
800 strbuf_attach(&used_path, newpath, strlen(newpath),
801 strlen(newpath));
803 for (i = 0; suffix[i]; i++) {
804 struct stat st;
805 size_t baselen = used_path.len;
806 strbuf_addstr(&used_path, suffix[i]);
807 if (!stat(used_path.buf, &st) &&
808 (S_ISREG(st.st_mode) ||
809 (S_ISDIR(st.st_mode) && is_git_directory(used_path.buf)))) {
810 strbuf_addstr(&validated_path, suffix[i]);
811 break;
813 strbuf_setlen(&used_path, baselen);
815 if (!suffix[i])
816 return NULL;
817 gitfile = read_gitfile(used_path.buf);
818 if (gitfile) {
819 strbuf_reset(&used_path);
820 strbuf_addstr(&used_path, gitfile);
822 if (chdir(used_path.buf))
823 return NULL;
824 path = validated_path.buf;
826 else {
827 const char *gitfile = read_gitfile(path);
828 if (gitfile)
829 path = gitfile;
830 if (chdir(path))
831 return NULL;
834 if (is_git_directory(".")) {
835 set_git_dir(".");
836 check_repository_format();
837 return path;
840 return NULL;
843 static int calc_shared_perm(int mode)
845 int tweak;
847 if (get_shared_repository() < 0)
848 tweak = -get_shared_repository();
849 else
850 tweak = get_shared_repository();
852 if (!(mode & S_IWUSR))
853 tweak &= ~0222;
854 if (mode & S_IXUSR)
855 /* Copy read bits to execute bits */
856 tweak |= (tweak & 0444) >> 2;
857 if (get_shared_repository() < 0)
858 mode = (mode & ~0777) | tweak;
859 else
860 mode |= tweak;
862 return mode;
866 int adjust_shared_perm(const char *path)
868 int old_mode, new_mode;
870 if (!get_shared_repository())
871 return 0;
872 if (get_st_mode_bits(path, &old_mode) < 0)
873 return -1;
875 new_mode = calc_shared_perm(old_mode);
876 if (S_ISDIR(old_mode)) {
877 /* Copy read bits to execute bits */
878 new_mode |= (new_mode & 0444) >> 2;
879 new_mode |= FORCE_DIR_SET_GID;
882 if (((old_mode ^ new_mode) & ~S_IFMT) &&
883 chmod(path, (new_mode & ~S_IFMT)) < 0)
884 return -2;
885 return 0;
888 void safe_create_dir(const char *dir, int share)
890 if (mkdir(dir, 0777) < 0) {
891 if (errno != EEXIST) {
892 perror(dir);
893 exit(1);
896 else if (share && adjust_shared_perm(dir))
897 die(_("Could not make %s writable by group"), dir);
900 static int have_same_root(const char *path1, const char *path2)
902 int is_abs1, is_abs2;
904 is_abs1 = is_absolute_path(path1);
905 is_abs2 = is_absolute_path(path2);
906 return (is_abs1 && is_abs2 && tolower(path1[0]) == tolower(path2[0])) ||
907 (!is_abs1 && !is_abs2);
911 * Give path as relative to prefix.
913 * The strbuf may or may not be used, so do not assume it contains the
914 * returned path.
916 const char *relative_path(const char *in, const char *prefix,
917 struct strbuf *sb)
919 int in_len = in ? strlen(in) : 0;
920 int prefix_len = prefix ? strlen(prefix) : 0;
921 int in_off = 0;
922 int prefix_off = 0;
923 int i = 0, j = 0;
925 if (!in_len)
926 return "./";
927 else if (!prefix_len)
928 return in;
930 if (have_same_root(in, prefix))
931 /* bypass dos_drive, for "c:" is identical to "C:" */
932 i = j = has_dos_drive_prefix(in);
933 else {
934 return in;
937 while (i < prefix_len && j < in_len && prefix[i] == in[j]) {
938 if (is_dir_sep(prefix[i])) {
939 while (is_dir_sep(prefix[i]))
940 i++;
941 while (is_dir_sep(in[j]))
942 j++;
943 prefix_off = i;
944 in_off = j;
945 } else {
946 i++;
947 j++;
951 if (
952 /* "prefix" seems like prefix of "in" */
953 i >= prefix_len &&
955 * but "/foo" is not a prefix of "/foobar"
956 * (i.e. prefix not end with '/')
958 prefix_off < prefix_len) {
959 if (j >= in_len) {
960 /* in="/a/b", prefix="/a/b" */
961 in_off = in_len;
962 } else if (is_dir_sep(in[j])) {
963 /* in="/a/b/c", prefix="/a/b" */
964 while (is_dir_sep(in[j]))
965 j++;
966 in_off = j;
967 } else {
968 /* in="/a/bbb/c", prefix="/a/b" */
969 i = prefix_off;
971 } else if (
972 /* "in" is short than "prefix" */
973 j >= in_len &&
974 /* "in" not end with '/' */
975 in_off < in_len) {
976 if (is_dir_sep(prefix[i])) {
977 /* in="/a/b", prefix="/a/b/c/" */
978 while (is_dir_sep(prefix[i]))
979 i++;
980 in_off = in_len;
983 in += in_off;
984 in_len -= in_off;
986 if (i >= prefix_len) {
987 if (!in_len)
988 return "./";
989 else
990 return in;
993 strbuf_reset(sb);
994 strbuf_grow(sb, in_len);
996 while (i < prefix_len) {
997 if (is_dir_sep(prefix[i])) {
998 strbuf_addstr(sb, "../");
999 while (is_dir_sep(prefix[i]))
1000 i++;
1001 continue;
1003 i++;
1005 if (!is_dir_sep(prefix[prefix_len - 1]))
1006 strbuf_addstr(sb, "../");
1008 strbuf_addstr(sb, in);
1010 return sb->buf;
1014 * A simpler implementation of relative_path
1016 * Get relative path by removing "prefix" from "in". This function
1017 * first appears in v1.5.6-1-g044bbbc, and makes git_dir shorter
1018 * to increase performance when traversing the path to work_tree.
1020 const char *remove_leading_path(const char *in, const char *prefix)
1022 static struct strbuf buf = STRBUF_INIT;
1023 int i = 0, j = 0;
1025 if (!prefix || !prefix[0])
1026 return in;
1027 while (prefix[i]) {
1028 if (is_dir_sep(prefix[i])) {
1029 if (!is_dir_sep(in[j]))
1030 return in;
1031 while (is_dir_sep(prefix[i]))
1032 i++;
1033 while (is_dir_sep(in[j]))
1034 j++;
1035 continue;
1036 } else if (in[j] != prefix[i]) {
1037 return in;
1039 i++;
1040 j++;
1042 if (
1043 /* "/foo" is a prefix of "/foo" */
1044 in[j] &&
1045 /* "/foo" is not a prefix of "/foobar" */
1046 !is_dir_sep(prefix[i-1]) && !is_dir_sep(in[j])
1048 return in;
1049 while (is_dir_sep(in[j]))
1050 j++;
1052 strbuf_reset(&buf);
1053 if (!in[j])
1054 strbuf_addstr(&buf, ".");
1055 else
1056 strbuf_addstr(&buf, in + j);
1057 return buf.buf;
1061 * It is okay if dst == src, but they should not overlap otherwise.
1063 * Performs the following normalizations on src, storing the result in dst:
1064 * - Ensures that components are separated by '/' (Windows only)
1065 * - Squashes sequences of '/' except "//server/share" on Windows
1066 * - Removes "." components.
1067 * - Removes ".." components, and the components the precede them.
1068 * Returns failure (non-zero) if a ".." component appears as first path
1069 * component anytime during the normalization. Otherwise, returns success (0).
1071 * Note that this function is purely textual. It does not follow symlinks,
1072 * verify the existence of the path, or make any system calls.
1074 * prefix_len != NULL is for a specific case of prefix_pathspec():
1075 * assume that src == dst and src[0..prefix_len-1] is already
1076 * normalized, any time "../" eats up to the prefix_len part,
1077 * prefix_len is reduced. In the end prefix_len is the remaining
1078 * prefix that has not been overridden by user pathspec.
1080 * NEEDSWORK: This function doesn't perform normalization w.r.t. trailing '/'.
1081 * For everything but the root folder itself, the normalized path should not
1082 * end with a '/', then the callers need to be fixed up accordingly.
1085 int normalize_path_copy_len(char *dst, const char *src, int *prefix_len)
1087 char *dst0;
1088 const char *end;
1091 * Copy initial part of absolute path: "/", "C:/", "//server/share/".
1093 end = src + offset_1st_component(src);
1094 while (src < end) {
1095 char c = *src++;
1096 if (is_dir_sep(c))
1097 c = '/';
1098 *dst++ = c;
1100 dst0 = dst;
1102 while (is_dir_sep(*src))
1103 src++;
1105 for (;;) {
1106 char c = *src;
1109 * A path component that begins with . could be
1110 * special:
1111 * (1) "." and ends -- ignore and terminate.
1112 * (2) "./" -- ignore them, eat slash and continue.
1113 * (3) ".." and ends -- strip one and terminate.
1114 * (4) "../" -- strip one, eat slash and continue.
1116 if (c == '.') {
1117 if (!src[1]) {
1118 /* (1) */
1119 src++;
1120 } else if (is_dir_sep(src[1])) {
1121 /* (2) */
1122 src += 2;
1123 while (is_dir_sep(*src))
1124 src++;
1125 continue;
1126 } else if (src[1] == '.') {
1127 if (!src[2]) {
1128 /* (3) */
1129 src += 2;
1130 goto up_one;
1131 } else if (is_dir_sep(src[2])) {
1132 /* (4) */
1133 src += 3;
1134 while (is_dir_sep(*src))
1135 src++;
1136 goto up_one;
1141 /* copy up to the next '/', and eat all '/' */
1142 while ((c = *src++) != '\0' && !is_dir_sep(c))
1143 *dst++ = c;
1144 if (is_dir_sep(c)) {
1145 *dst++ = '/';
1146 while (is_dir_sep(c))
1147 c = *src++;
1148 src--;
1149 } else if (!c)
1150 break;
1151 continue;
1153 up_one:
1155 * dst0..dst is prefix portion, and dst[-1] is '/';
1156 * go up one level.
1158 dst--; /* go to trailing '/' */
1159 if (dst <= dst0)
1160 return -1;
1161 /* Windows: dst[-1] cannot be backslash anymore */
1162 while (dst0 < dst && dst[-1] != '/')
1163 dst--;
1164 if (prefix_len && *prefix_len > dst - dst0)
1165 *prefix_len = dst - dst0;
1167 *dst = '\0';
1168 return 0;
1171 int normalize_path_copy(char *dst, const char *src)
1173 return normalize_path_copy_len(dst, src, NULL);
1177 * path = Canonical absolute path
1178 * prefixes = string_list containing normalized, absolute paths without
1179 * trailing slashes (except for the root directory, which is denoted by "/").
1181 * Determines, for each path in prefixes, whether the "prefix"
1182 * is an ancestor directory of path. Returns the length of the longest
1183 * ancestor directory, excluding any trailing slashes, or -1 if no prefix
1184 * is an ancestor. (Note that this means 0 is returned if prefixes is
1185 * ["/"].) "/foo" is not considered an ancestor of "/foobar". Directories
1186 * are not considered to be their own ancestors. path must be in a
1187 * canonical form: empty components, or "." or ".." components are not
1188 * allowed.
1190 int longest_ancestor_length(const char *path, struct string_list *prefixes)
1192 int i, max_len = -1;
1194 if (!strcmp(path, "/"))
1195 return -1;
1197 for (i = 0; i < prefixes->nr; i++) {
1198 const char *ceil = prefixes->items[i].string;
1199 int len = strlen(ceil);
1201 if (len == 1 && ceil[0] == '/')
1202 len = 0; /* root matches anything, with length 0 */
1203 else if (!strncmp(path, ceil, len) && path[len] == '/')
1204 ; /* match of length len */
1205 else
1206 continue; /* no match */
1208 if (len > max_len)
1209 max_len = len;
1212 return max_len;
1215 /* strip arbitrary amount of directory separators at end of path */
1216 static inline int chomp_trailing_dir_sep(const char *path, int len)
1218 while (len && is_dir_sep(path[len - 1]))
1219 len--;
1220 return len;
1224 * If path ends with suffix (complete path components), returns the
1225 * part before suffix (sans trailing directory separators).
1226 * Otherwise returns NULL.
1228 char *strip_path_suffix(const char *path, const char *suffix)
1230 int path_len = strlen(path), suffix_len = strlen(suffix);
1232 while (suffix_len) {
1233 if (!path_len)
1234 return NULL;
1236 if (is_dir_sep(path[path_len - 1])) {
1237 if (!is_dir_sep(suffix[suffix_len - 1]))
1238 return NULL;
1239 path_len = chomp_trailing_dir_sep(path, path_len);
1240 suffix_len = chomp_trailing_dir_sep(suffix, suffix_len);
1242 else if (path[--path_len] != suffix[--suffix_len])
1243 return NULL;
1246 if (path_len && !is_dir_sep(path[path_len - 1]))
1247 return NULL;
1248 return xstrndup(path, chomp_trailing_dir_sep(path, path_len));
1251 int daemon_avoid_alias(const char *p)
1253 int sl, ndot;
1256 * This resurrects the belts and suspenders paranoia check by HPA
1257 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
1258 * does not do getcwd() based path canonicalization.
1260 * sl becomes true immediately after seeing '/' and continues to
1261 * be true as long as dots continue after that without intervening
1262 * non-dot character.
1264 if (!p || (*p != '/' && *p != '~'))
1265 return -1;
1266 sl = 1; ndot = 0;
1267 p++;
1269 while (1) {
1270 char ch = *p++;
1271 if (sl) {
1272 if (ch == '.')
1273 ndot++;
1274 else if (ch == '/') {
1275 if (ndot < 3)
1276 /* reject //, /./ and /../ */
1277 return -1;
1278 ndot = 0;
1280 else if (ch == 0) {
1281 if (0 < ndot && ndot < 3)
1282 /* reject /.$ and /..$ */
1283 return -1;
1284 return 0;
1286 else
1287 sl = ndot = 0;
1289 else if (ch == 0)
1290 return 0;
1291 else if (ch == '/') {
1292 sl = 1;
1293 ndot = 0;
1298 static int only_spaces_and_periods(const char *path, size_t len, size_t skip)
1300 if (len < skip)
1301 return 0;
1302 len -= skip;
1303 path += skip;
1304 while (len-- > 0) {
1305 char c = *(path++);
1306 if (c != ' ' && c != '.')
1307 return 0;
1309 return 1;
1312 int is_ntfs_dotgit(const char *name)
1314 size_t len;
1316 for (len = 0; ; len++)
1317 if (!name[len] || name[len] == '\\' || is_dir_sep(name[len])) {
1318 if (only_spaces_and_periods(name, len, 4) &&
1319 !strncasecmp(name, ".git", 4))
1320 return 1;
1321 if (only_spaces_and_periods(name, len, 5) &&
1322 !strncasecmp(name, "git~1", 5))
1323 return 1;
1324 if (name[len] != '\\')
1325 return 0;
1326 name += len + 1;
1327 len = -1;
1331 static int is_ntfs_dot_generic(const char *name,
1332 const char *dotgit_name,
1333 size_t len,
1334 const char *dotgit_ntfs_shortname_prefix)
1336 int saw_tilde;
1337 size_t i;
1339 if ((name[0] == '.' && !strncasecmp(name + 1, dotgit_name, len))) {
1340 i = len + 1;
1341 only_spaces_and_periods:
1342 for (;;) {
1343 char c = name[i++];
1344 if (!c)
1345 return 1;
1346 if (c != ' ' && c != '.')
1347 return 0;
1352 * Is it a regular NTFS short name, i.e. shortened to 6 characters,
1353 * followed by ~1, ... ~4?
1355 if (!strncasecmp(name, dotgit_name, 6) && name[6] == '~' &&
1356 name[7] >= '1' && name[7] <= '4') {
1357 i = 8;
1358 goto only_spaces_and_periods;
1362 * Is it a fall-back NTFS short name (for details, see
1363 * https://en.wikipedia.org/wiki/8.3_filename?
1365 for (i = 0, saw_tilde = 0; i < 8; i++)
1366 if (name[i] == '\0')
1367 return 0;
1368 else if (saw_tilde) {
1369 if (name[i] < '0' || name[i] > '9')
1370 return 0;
1371 } else if (name[i] == '~') {
1372 if (name[++i] < '1' || name[i] > '9')
1373 return 0;
1374 saw_tilde = 1;
1375 } else if (i >= 6)
1376 return 0;
1377 else if (name[i] & 0x80) {
1379 * We know our needles contain only ASCII, so we clamp
1380 * here to make the results of tolower() sane.
1382 return 0;
1383 } else if (tolower(name[i]) != dotgit_ntfs_shortname_prefix[i])
1384 return 0;
1386 goto only_spaces_and_periods;
1390 * Inline helper to make sure compiler resolves strlen() on literals at
1391 * compile time.
1393 static inline int is_ntfs_dot_str(const char *name, const char *dotgit_name,
1394 const char *dotgit_ntfs_shortname_prefix)
1396 return is_ntfs_dot_generic(name, dotgit_name, strlen(dotgit_name),
1397 dotgit_ntfs_shortname_prefix);
1400 int is_ntfs_dotgitmodules(const char *name)
1402 return is_ntfs_dot_str(name, "gitmodules", "gi7eba");
1405 int is_ntfs_dotgitignore(const char *name)
1407 return is_ntfs_dot_str(name, "gitignore", "gi250a");
1410 int is_ntfs_dotgitattributes(const char *name)
1412 return is_ntfs_dot_str(name, "gitattributes", "gi7d29");
1415 int looks_like_command_line_option(const char *str)
1417 return str && str[0] == '-';
1420 char *xdg_config_home(const char *filename)
1422 const char *home, *config_home;
1424 assert(filename);
1425 config_home = getenv("XDG_CONFIG_HOME");
1426 if (config_home && *config_home)
1427 return mkpathdup("%s/git/%s", config_home, filename);
1429 home = getenv("HOME");
1430 if (home)
1431 return mkpathdup("%s/.config/git/%s", home, filename);
1432 return NULL;
1435 char *xdg_cache_home(const char *filename)
1437 const char *home, *cache_home;
1439 assert(filename);
1440 cache_home = getenv("XDG_CACHE_HOME");
1441 if (cache_home && *cache_home)
1442 return mkpathdup("%s/git/%s", cache_home, filename);
1444 home = getenv("HOME");
1445 if (home)
1446 return mkpathdup("%s/.cache/git/%s", home, filename);
1447 return NULL;
1450 REPO_GIT_PATH_FUNC(cherry_pick_head, "CHERRY_PICK_HEAD")
1451 REPO_GIT_PATH_FUNC(revert_head, "REVERT_HEAD")
1452 REPO_GIT_PATH_FUNC(squash_msg, "SQUASH_MSG")
1453 REPO_GIT_PATH_FUNC(merge_msg, "MERGE_MSG")
1454 REPO_GIT_PATH_FUNC(merge_rr, "MERGE_RR")
1455 REPO_GIT_PATH_FUNC(merge_mode, "MERGE_MODE")
1456 REPO_GIT_PATH_FUNC(merge_head, "MERGE_HEAD")
1457 REPO_GIT_PATH_FUNC(fetch_head, "FETCH_HEAD")
1458 REPO_GIT_PATH_FUNC(shallow, "shallow")