Sync with 2.40.2
[git.git] / path.c
blob4330315cf25dead7e2ee0e942d0db92dabf7e4ff
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 "hex.h"
9 #include "repository.h"
10 #include "strbuf.h"
11 #include "string-list.h"
12 #include "dir.h"
13 #include "worktree.h"
14 #include "setup.h"
15 #include "submodule-config.h"
16 #include "path.h"
17 #include "packfile.h"
18 #include "object-store.h"
19 #include "lockfile.h"
20 #include "exec-cmd.h"
21 #include "wrapper.h"
23 static int get_st_mode_bits(const char *path, int *mode)
25 struct stat st;
26 if (lstat(path, &st) < 0)
27 return -1;
28 *mode = st.st_mode;
29 return 0;
32 static char bad_path[] = "/bad-path/";
34 static struct strbuf *get_pathname(void)
36 static struct strbuf pathname_array[4] = {
37 STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
39 static int index;
40 struct strbuf *sb = &pathname_array[index];
41 index = (index + 1) % ARRAY_SIZE(pathname_array);
42 strbuf_reset(sb);
43 return sb;
46 static const char *cleanup_path(const char *path)
48 /* Clean it up */
49 if (skip_prefix(path, "./", &path)) {
50 while (*path == '/')
51 path++;
53 return path;
56 static void strbuf_cleanup_path(struct strbuf *sb)
58 const char *path = cleanup_path(sb->buf);
59 if (path > sb->buf)
60 strbuf_remove(sb, 0, path - sb->buf);
63 char *mksnpath(char *buf, size_t n, const char *fmt, ...)
65 va_list args;
66 unsigned len;
68 va_start(args, fmt);
69 len = vsnprintf(buf, n, fmt, args);
70 va_end(args);
71 if (len >= n) {
72 strlcpy(buf, bad_path, n);
73 return buf;
75 return (char *)cleanup_path(buf);
78 static int dir_prefix(const char *buf, const char *dir)
80 int len = strlen(dir);
81 return !strncmp(buf, dir, len) &&
82 (is_dir_sep(buf[len]) || buf[len] == '\0');
85 /* $buf =~ m|$dir/+$file| but without regex */
86 static int is_dir_file(const char *buf, const char *dir, const char *file)
88 int len = strlen(dir);
89 if (strncmp(buf, dir, len) || !is_dir_sep(buf[len]))
90 return 0;
91 while (is_dir_sep(buf[len]))
92 len++;
93 return !strcmp(buf + len, file);
96 static void replace_dir(struct strbuf *buf, int len, const char *newdir)
98 int newlen = strlen(newdir);
99 int need_sep = (buf->buf[len] && !is_dir_sep(buf->buf[len])) &&
100 !is_dir_sep(newdir[newlen - 1]);
101 if (need_sep)
102 len--; /* keep one char, to be replaced with '/' */
103 strbuf_splice(buf, 0, len, newdir, newlen);
104 if (need_sep)
105 buf->buf[newlen] = '/';
108 struct common_dir {
109 /* Not considered garbage for report_linked_checkout_garbage */
110 unsigned ignore_garbage:1;
111 unsigned is_dir:1;
112 /* Belongs to the common dir, though it may contain paths that don't */
113 unsigned is_common:1;
114 const char *path;
117 static struct common_dir common_list[] = {
118 { 0, 1, 1, "branches" },
119 { 0, 1, 1, "common" },
120 { 0, 1, 1, "hooks" },
121 { 0, 1, 1, "info" },
122 { 0, 0, 0, "info/sparse-checkout" },
123 { 1, 1, 1, "logs" },
124 { 1, 0, 0, "logs/HEAD" },
125 { 0, 1, 0, "logs/refs/bisect" },
126 { 0, 1, 0, "logs/refs/rewritten" },
127 { 0, 1, 0, "logs/refs/worktree" },
128 { 0, 1, 1, "lost-found" },
129 { 0, 1, 1, "objects" },
130 { 0, 1, 1, "refs" },
131 { 0, 1, 0, "refs/bisect" },
132 { 0, 1, 0, "refs/rewritten" },
133 { 0, 1, 0, "refs/worktree" },
134 { 0, 1, 1, "remotes" },
135 { 0, 1, 1, "worktrees" },
136 { 0, 1, 1, "rr-cache" },
137 { 0, 1, 1, "svn" },
138 { 0, 0, 1, "config" },
139 { 1, 0, 1, "gc.pid" },
140 { 0, 0, 1, "packed-refs" },
141 { 0, 0, 1, "shallow" },
142 { 0, 0, 0, NULL }
146 * A compressed trie. A trie node consists of zero or more characters that
147 * are common to all elements with this prefix, optionally followed by some
148 * children. If value is not NULL, the trie node is a terminal node.
150 * For example, consider the following set of strings:
151 * abc
152 * def
153 * definite
154 * definition
156 * The trie would look like:
157 * root: len = 0, children a and d non-NULL, value = NULL.
158 * a: len = 2, contents = bc, value = (data for "abc")
159 * d: len = 2, contents = ef, children i non-NULL, value = (data for "def")
160 * i: len = 3, contents = nit, children e and i non-NULL, value = NULL
161 * e: len = 0, children all NULL, value = (data for "definite")
162 * i: len = 2, contents = on, children all NULL,
163 * value = (data for "definition")
165 struct trie {
166 struct trie *children[256];
167 int len;
168 char *contents;
169 void *value;
172 static struct trie *make_trie_node(const char *key, void *value)
174 struct trie *new_node = xcalloc(1, sizeof(*new_node));
175 new_node->len = strlen(key);
176 if (new_node->len) {
177 new_node->contents = xmalloc(new_node->len);
178 memcpy(new_node->contents, key, new_node->len);
180 new_node->value = value;
181 return new_node;
185 * Add a key/value pair to a trie. The key is assumed to be \0-terminated.
186 * If there was an existing value for this key, return it.
188 static void *add_to_trie(struct trie *root, const char *key, void *value)
190 struct trie *child;
191 void *old;
192 int i;
194 if (!*key) {
195 /* we have reached the end of the key */
196 old = root->value;
197 root->value = value;
198 return old;
201 for (i = 0; i < root->len; i++) {
202 if (root->contents[i] == key[i])
203 continue;
206 * Split this node: child will contain this node's
207 * existing children.
209 child = xmalloc(sizeof(*child));
210 memcpy(child->children, root->children, sizeof(root->children));
212 child->len = root->len - i - 1;
213 if (child->len) {
214 child->contents = xstrndup(root->contents + i + 1,
215 child->len);
217 child->value = root->value;
218 root->value = NULL;
219 root->len = i;
221 memset(root->children, 0, sizeof(root->children));
222 root->children[(unsigned char)root->contents[i]] = child;
224 /* This is the newly-added child. */
225 root->children[(unsigned char)key[i]] =
226 make_trie_node(key + i + 1, value);
227 return NULL;
230 /* We have matched the entire compressed section */
231 if (key[i]) {
232 child = root->children[(unsigned char)key[root->len]];
233 if (child) {
234 return add_to_trie(child, key + root->len + 1, value);
235 } else {
236 child = make_trie_node(key + root->len + 1, value);
237 root->children[(unsigned char)key[root->len]] = child;
238 return NULL;
242 old = root->value;
243 root->value = value;
244 return old;
247 typedef int (*match_fn)(const char *unmatched, void *value, void *baton);
250 * Search a trie for some key. Find the longest /-or-\0-terminated
251 * prefix of the key for which the trie contains a value. If there is
252 * no such prefix, return -1. Otherwise call fn with the unmatched
253 * portion of the key and the found value. If fn returns 0 or
254 * positive, then return its return value. If fn returns negative,
255 * then call fn with the next-longest /-terminated prefix of the key
256 * (i.e. a parent directory) for which the trie contains a value, and
257 * handle its return value the same way. If there is no shorter
258 * /-terminated prefix with a value left, then return the negative
259 * return value of the most recent fn invocation.
261 * The key is partially normalized: consecutive slashes are skipped.
263 * For example, consider the trie containing only [logs,
264 * logs/refs/bisect], both with values, but not logs/refs.
266 * | key | unmatched | prefix to node | return value |
267 * |--------------------|----------------|------------------|--------------|
268 * | a | not called | n/a | -1 |
269 * | logstore | not called | n/a | -1 |
270 * | logs | \0 | logs | as per fn |
271 * | logs/ | / | logs | as per fn |
272 * | logs/refs | /refs | logs | as per fn |
273 * | logs/refs/ | /refs/ | logs | as per fn |
274 * | logs/refs/b | /refs/b | logs | as per fn |
275 * | logs/refs/bisected | /refs/bisected | logs | as per fn |
276 * | logs/refs/bisect | \0 | logs/refs/bisect | as per fn |
277 * | logs/refs/bisect/ | / | logs/refs/bisect | as per fn |
278 * | logs/refs/bisect/a | /a | logs/refs/bisect | as per fn |
279 * | (If fn in the previous line returns -1, then fn is called once more:) |
280 * | logs/refs/bisect/a | /refs/bisect/a | logs | as per fn |
281 * |--------------------|----------------|------------------|--------------|
283 static int trie_find(struct trie *root, const char *key, match_fn fn,
284 void *baton)
286 int i;
287 int result;
288 struct trie *child;
290 if (!*key) {
291 /* we have reached the end of the key */
292 if (root->value && !root->len)
293 return fn(key, root->value, baton);
294 else
295 return -1;
298 for (i = 0; i < root->len; i++) {
299 /* Partial path normalization: skip consecutive slashes. */
300 if (key[i] == '/' && key[i+1] == '/') {
301 key++;
302 continue;
304 if (root->contents[i] != key[i])
305 return -1;
308 /* Matched the entire compressed section */
309 key += i;
310 if (!*key) {
311 /* End of key */
312 if (root->value)
313 return fn(key, root->value, baton);
314 else
315 return -1;
318 /* Partial path normalization: skip consecutive slashes */
319 while (key[0] == '/' && key[1] == '/')
320 key++;
322 child = root->children[(unsigned char)*key];
323 if (child)
324 result = trie_find(child, key + 1, fn, baton);
325 else
326 result = -1;
328 if (result >= 0 || (*key != '/' && *key != 0))
329 return result;
330 if (root->value)
331 return fn(key, root->value, baton);
332 else
333 return -1;
336 static struct trie common_trie;
337 static int common_trie_done_setup;
339 static void init_common_trie(void)
341 struct common_dir *p;
343 if (common_trie_done_setup)
344 return;
346 for (p = common_list; p->path; p++)
347 add_to_trie(&common_trie, p->path, p);
349 common_trie_done_setup = 1;
353 * Helper function for update_common_dir: returns 1 if the dir
354 * prefix is common.
356 static int check_common(const char *unmatched, void *value,
357 void *baton UNUSED)
359 struct common_dir *dir = value;
361 if (dir->is_dir && (unmatched[0] == 0 || unmatched[0] == '/'))
362 return dir->is_common;
364 if (!dir->is_dir && unmatched[0] == 0)
365 return dir->is_common;
367 return 0;
370 static void update_common_dir(struct strbuf *buf, int git_dir_len,
371 const char *common_dir)
373 char *base = buf->buf + git_dir_len;
374 int has_lock_suffix = strbuf_strip_suffix(buf, LOCK_SUFFIX);
376 init_common_trie();
377 if (trie_find(&common_trie, base, check_common, NULL) > 0)
378 replace_dir(buf, git_dir_len, common_dir);
380 if (has_lock_suffix)
381 strbuf_addstr(buf, LOCK_SUFFIX);
384 void report_linked_checkout_garbage(void)
386 struct strbuf sb = STRBUF_INIT;
387 const struct common_dir *p;
388 int len;
390 if (!the_repository->different_commondir)
391 return;
392 strbuf_addf(&sb, "%s/", get_git_dir());
393 len = sb.len;
394 for (p = common_list; p->path; p++) {
395 const char *path = p->path;
396 if (p->ignore_garbage)
397 continue;
398 strbuf_setlen(&sb, len);
399 strbuf_addstr(&sb, path);
400 if (file_exists(sb.buf))
401 report_garbage(PACKDIR_FILE_GARBAGE, sb.buf);
403 strbuf_release(&sb);
406 static void adjust_git_path(const struct repository *repo,
407 struct strbuf *buf, int git_dir_len)
409 const char *base = buf->buf + git_dir_len;
410 if (is_dir_file(base, "info", "grafts"))
411 strbuf_splice(buf, 0, buf->len,
412 repo->graft_file, strlen(repo->graft_file));
413 else if (!strcmp(base, "index"))
414 strbuf_splice(buf, 0, buf->len,
415 repo->index_file, strlen(repo->index_file));
416 else if (dir_prefix(base, "objects"))
417 replace_dir(buf, git_dir_len + 7, repo->objects->odb->path);
418 else if (git_hooks_path && dir_prefix(base, "hooks"))
419 replace_dir(buf, git_dir_len + 5, git_hooks_path);
420 else if (repo->different_commondir)
421 update_common_dir(buf, git_dir_len, repo->commondir);
424 static void strbuf_worktree_gitdir(struct strbuf *buf,
425 const struct repository *repo,
426 const struct worktree *wt)
428 if (!wt)
429 strbuf_addstr(buf, repo->gitdir);
430 else if (!wt->id)
431 strbuf_addstr(buf, repo->commondir);
432 else
433 strbuf_git_common_path(buf, repo, "worktrees/%s", wt->id);
436 static void do_git_path(const struct repository *repo,
437 const struct worktree *wt, struct strbuf *buf,
438 const char *fmt, va_list args)
440 int gitdir_len;
441 strbuf_worktree_gitdir(buf, repo, wt);
442 if (buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
443 strbuf_addch(buf, '/');
444 gitdir_len = buf->len;
445 strbuf_vaddf(buf, fmt, args);
446 if (!wt)
447 adjust_git_path(repo, buf, gitdir_len);
448 strbuf_cleanup_path(buf);
451 char *repo_git_path(const struct repository *repo,
452 const char *fmt, ...)
454 struct strbuf path = STRBUF_INIT;
455 va_list args;
456 va_start(args, fmt);
457 do_git_path(repo, NULL, &path, fmt, args);
458 va_end(args);
459 return strbuf_detach(&path, NULL);
462 void strbuf_repo_git_path(struct strbuf *sb,
463 const struct repository *repo,
464 const char *fmt, ...)
466 va_list args;
467 va_start(args, fmt);
468 do_git_path(repo, NULL, sb, fmt, args);
469 va_end(args);
472 char *git_path_buf(struct strbuf *buf, const char *fmt, ...)
474 va_list args;
475 strbuf_reset(buf);
476 va_start(args, fmt);
477 do_git_path(the_repository, NULL, buf, fmt, args);
478 va_end(args);
479 return buf->buf;
482 void strbuf_git_path(struct strbuf *sb, const char *fmt, ...)
484 va_list args;
485 va_start(args, fmt);
486 do_git_path(the_repository, NULL, sb, fmt, args);
487 va_end(args);
490 const char *git_path(const char *fmt, ...)
492 struct strbuf *pathname = get_pathname();
493 va_list args;
494 va_start(args, fmt);
495 do_git_path(the_repository, NULL, pathname, fmt, args);
496 va_end(args);
497 return pathname->buf;
500 char *git_pathdup(const char *fmt, ...)
502 struct strbuf path = STRBUF_INIT;
503 va_list args;
504 va_start(args, fmt);
505 do_git_path(the_repository, NULL, &path, fmt, args);
506 va_end(args);
507 return strbuf_detach(&path, NULL);
510 char *mkpathdup(const char *fmt, ...)
512 struct strbuf sb = STRBUF_INIT;
513 va_list args;
514 va_start(args, fmt);
515 strbuf_vaddf(&sb, fmt, args);
516 va_end(args);
517 strbuf_cleanup_path(&sb);
518 return strbuf_detach(&sb, NULL);
521 const char *mkpath(const char *fmt, ...)
523 va_list args;
524 struct strbuf *pathname = get_pathname();
525 va_start(args, fmt);
526 strbuf_vaddf(pathname, fmt, args);
527 va_end(args);
528 return cleanup_path(pathname->buf);
531 const char *worktree_git_path(const struct worktree *wt, const char *fmt, ...)
533 struct strbuf *pathname = get_pathname();
534 va_list args;
535 va_start(args, fmt);
536 do_git_path(the_repository, wt, pathname, fmt, args);
537 va_end(args);
538 return pathname->buf;
541 static void do_worktree_path(const struct repository *repo,
542 struct strbuf *buf,
543 const char *fmt, va_list args)
545 strbuf_addstr(buf, repo->worktree);
546 if(buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
547 strbuf_addch(buf, '/');
549 strbuf_vaddf(buf, fmt, args);
550 strbuf_cleanup_path(buf);
553 char *repo_worktree_path(const struct repository *repo, const char *fmt, ...)
555 struct strbuf path = STRBUF_INIT;
556 va_list args;
558 if (!repo->worktree)
559 return NULL;
561 va_start(args, fmt);
562 do_worktree_path(repo, &path, fmt, args);
563 va_end(args);
565 return strbuf_detach(&path, NULL);
568 void strbuf_repo_worktree_path(struct strbuf *sb,
569 const struct repository *repo,
570 const char *fmt, ...)
572 va_list args;
574 if (!repo->worktree)
575 return;
577 va_start(args, fmt);
578 do_worktree_path(repo, sb, fmt, args);
579 va_end(args);
582 /* Returns 0 on success, negative on failure. */
583 static int do_submodule_path(struct strbuf *buf, const char *path,
584 const char *fmt, va_list args)
586 struct strbuf git_submodule_common_dir = STRBUF_INIT;
587 struct strbuf git_submodule_dir = STRBUF_INIT;
588 int ret;
590 ret = submodule_to_gitdir(&git_submodule_dir, path);
591 if (ret)
592 goto cleanup;
594 strbuf_complete(&git_submodule_dir, '/');
595 strbuf_addbuf(buf, &git_submodule_dir);
596 strbuf_vaddf(buf, fmt, args);
598 if (get_common_dir_noenv(&git_submodule_common_dir, git_submodule_dir.buf))
599 update_common_dir(buf, git_submodule_dir.len, git_submodule_common_dir.buf);
601 strbuf_cleanup_path(buf);
603 cleanup:
604 strbuf_release(&git_submodule_dir);
605 strbuf_release(&git_submodule_common_dir);
606 return ret;
609 char *git_pathdup_submodule(const char *path, const char *fmt, ...)
611 int err;
612 va_list args;
613 struct strbuf buf = STRBUF_INIT;
614 va_start(args, fmt);
615 err = do_submodule_path(&buf, path, fmt, args);
616 va_end(args);
617 if (err) {
618 strbuf_release(&buf);
619 return NULL;
621 return strbuf_detach(&buf, NULL);
624 int strbuf_git_path_submodule(struct strbuf *buf, const char *path,
625 const char *fmt, ...)
627 int err;
628 va_list args;
629 va_start(args, fmt);
630 err = do_submodule_path(buf, path, fmt, args);
631 va_end(args);
633 return err;
636 static void do_git_common_path(const struct repository *repo,
637 struct strbuf *buf,
638 const char *fmt,
639 va_list args)
641 strbuf_addstr(buf, repo->commondir);
642 if (buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
643 strbuf_addch(buf, '/');
644 strbuf_vaddf(buf, fmt, args);
645 strbuf_cleanup_path(buf);
648 const char *git_common_path(const char *fmt, ...)
650 struct strbuf *pathname = get_pathname();
651 va_list args;
652 va_start(args, fmt);
653 do_git_common_path(the_repository, pathname, fmt, args);
654 va_end(args);
655 return pathname->buf;
658 void strbuf_git_common_path(struct strbuf *sb,
659 const struct repository *repo,
660 const char *fmt, ...)
662 va_list args;
663 va_start(args, fmt);
664 do_git_common_path(repo, sb, fmt, args);
665 va_end(args);
668 int validate_headref(const char *path)
670 struct stat st;
671 char buffer[256];
672 const char *refname;
673 struct object_id oid;
674 int fd;
675 ssize_t len;
677 if (lstat(path, &st) < 0)
678 return -1;
680 /* Make sure it is a "refs/.." symlink */
681 if (S_ISLNK(st.st_mode)) {
682 len = readlink(path, buffer, sizeof(buffer)-1);
683 if (len >= 5 && !memcmp("refs/", buffer, 5))
684 return 0;
685 return -1;
689 * Anything else, just open it and try to see if it is a symbolic ref.
691 fd = open(path, O_RDONLY);
692 if (fd < 0)
693 return -1;
694 len = read_in_full(fd, buffer, sizeof(buffer)-1);
695 close(fd);
697 if (len < 0)
698 return -1;
699 buffer[len] = '\0';
702 * Is it a symbolic ref?
704 if (skip_prefix(buffer, "ref:", &refname)) {
705 while (isspace(*refname))
706 refname++;
707 if (starts_with(refname, "refs/"))
708 return 0;
712 * Is this a detached HEAD?
714 if (!get_oid_hex(buffer, &oid))
715 return 0;
717 return -1;
720 static struct passwd *getpw_str(const char *username, size_t len)
722 struct passwd *pw;
723 char *username_z = xmemdupz(username, len);
724 pw = getpwnam(username_z);
725 free(username_z);
726 return pw;
730 * Return a string with ~ and ~user expanded via getpw*. Returns NULL on getpw
731 * failure or if path is NULL.
733 * If real_home is true, strbuf_realpath($HOME) is used in the `~/` expansion.
735 * If the path starts with `%(prefix)/`, the remainder is interpreted as
736 * relative to where Git is installed, and expanded to the absolute path.
738 char *interpolate_path(const char *path, int real_home)
740 struct strbuf user_path = STRBUF_INIT;
741 const char *to_copy = path;
743 if (!path)
744 goto return_null;
746 if (skip_prefix(path, "%(prefix)/", &path))
747 return system_path(path);
749 if (path[0] == '~') {
750 const char *first_slash = strchrnul(path, '/');
751 const char *username = path + 1;
752 size_t username_len = first_slash - username;
753 if (username_len == 0) {
754 const char *home = getenv("HOME");
755 if (!home)
756 goto return_null;
757 if (real_home)
758 strbuf_add_real_path(&user_path, home);
759 else
760 strbuf_addstr(&user_path, home);
761 #ifdef GIT_WINDOWS_NATIVE
762 convert_slashes(user_path.buf);
763 #endif
764 } else {
765 struct passwd *pw = getpw_str(username, username_len);
766 if (!pw)
767 goto return_null;
768 strbuf_addstr(&user_path, pw->pw_dir);
770 to_copy = first_slash;
772 strbuf_addstr(&user_path, to_copy);
773 return strbuf_detach(&user_path, NULL);
774 return_null:
775 strbuf_release(&user_path);
776 return NULL;
780 * First, one directory to try is determined by the following algorithm.
782 * (0) If "strict" is given, the path is used as given and no DWIM is
783 * done. Otherwise:
784 * (1) "~/path" to mean path under the running user's home directory;
785 * (2) "~user/path" to mean path under named user's home directory;
786 * (3) "relative/path" to mean cwd relative directory; or
787 * (4) "/absolute/path" to mean absolute directory.
789 * Unless "strict" is given, we check "%s/.git", "%s", "%s.git/.git", "%s.git"
790 * in this order. We select the first one that is a valid git repository, and
791 * chdir() to it. If none match, or we fail to chdir, we return NULL.
793 * If all goes well, we return the directory we used to chdir() (but
794 * before ~user is expanded), avoiding getcwd() resolving symbolic
795 * links. User relative paths are also returned as they are given,
796 * except DWIM suffixing.
798 const char *enter_repo(const char *path, int strict)
800 static struct strbuf validated_path = STRBUF_INIT;
801 static struct strbuf used_path = STRBUF_INIT;
803 if (!path)
804 return NULL;
806 if (!strict) {
807 static const char *suffix[] = {
808 "/.git", "", ".git/.git", ".git", NULL,
810 const char *gitfile;
811 int len = strlen(path);
812 int i;
813 while ((1 < len) && (path[len-1] == '/'))
814 len--;
817 * We can handle arbitrary-sized buffers, but this remains as a
818 * sanity check on untrusted input.
820 if (PATH_MAX <= len)
821 return NULL;
823 strbuf_reset(&used_path);
824 strbuf_reset(&validated_path);
825 strbuf_add(&used_path, path, len);
826 strbuf_add(&validated_path, path, len);
828 if (used_path.buf[0] == '~') {
829 char *newpath = interpolate_path(used_path.buf, 0);
830 if (!newpath)
831 return NULL;
832 strbuf_attach(&used_path, newpath, strlen(newpath),
833 strlen(newpath));
835 for (i = 0; suffix[i]; i++) {
836 struct stat st;
837 size_t baselen = used_path.len;
838 strbuf_addstr(&used_path, suffix[i]);
839 if (!stat(used_path.buf, &st) &&
840 (S_ISREG(st.st_mode) ||
841 (S_ISDIR(st.st_mode) && is_git_directory(used_path.buf)))) {
842 strbuf_addstr(&validated_path, suffix[i]);
843 break;
845 strbuf_setlen(&used_path, baselen);
847 if (!suffix[i])
848 return NULL;
849 gitfile = read_gitfile(used_path.buf);
850 die_upon_dubious_ownership(gitfile, NULL, used_path.buf);
851 if (gitfile) {
852 strbuf_reset(&used_path);
853 strbuf_addstr(&used_path, gitfile);
855 if (chdir(used_path.buf))
856 return NULL;
857 path = validated_path.buf;
859 else {
860 const char *gitfile = read_gitfile(path);
861 die_upon_dubious_ownership(gitfile, NULL, path);
862 if (gitfile)
863 path = gitfile;
864 if (chdir(path))
865 return NULL;
868 if (is_git_directory(".")) {
869 set_git_dir(".", 0);
870 check_repository_format(NULL);
871 return path;
874 return NULL;
877 static int calc_shared_perm(int mode)
879 int tweak;
881 if (get_shared_repository() < 0)
882 tweak = -get_shared_repository();
883 else
884 tweak = get_shared_repository();
886 if (!(mode & S_IWUSR))
887 tweak &= ~0222;
888 if (mode & S_IXUSR)
889 /* Copy read bits to execute bits */
890 tweak |= (tweak & 0444) >> 2;
891 if (get_shared_repository() < 0)
892 mode = (mode & ~0777) | tweak;
893 else
894 mode |= tweak;
896 return mode;
900 int adjust_shared_perm(const char *path)
902 int old_mode, new_mode;
904 if (!get_shared_repository())
905 return 0;
906 if (get_st_mode_bits(path, &old_mode) < 0)
907 return -1;
909 new_mode = calc_shared_perm(old_mode);
910 if (S_ISDIR(old_mode)) {
911 /* Copy read bits to execute bits */
912 new_mode |= (new_mode & 0444) >> 2;
915 * g+s matters only if any extra access is granted
916 * based on group membership.
918 if (FORCE_DIR_SET_GID && (new_mode & 060))
919 new_mode |= FORCE_DIR_SET_GID;
922 if (((old_mode ^ new_mode) & ~S_IFMT) &&
923 chmod(path, (new_mode & ~S_IFMT)) < 0)
924 return -2;
925 return 0;
928 void safe_create_dir(const char *dir, int share)
930 if (mkdir(dir, 0777) < 0) {
931 if (errno != EEXIST) {
932 perror(dir);
933 exit(1);
936 else if (share && adjust_shared_perm(dir))
937 die(_("Could not make %s writable by group"), dir);
940 static int have_same_root(const char *path1, const char *path2)
942 int is_abs1, is_abs2;
944 is_abs1 = is_absolute_path(path1);
945 is_abs2 = is_absolute_path(path2);
946 return (is_abs1 && is_abs2 && tolower(path1[0]) == tolower(path2[0])) ||
947 (!is_abs1 && !is_abs2);
951 * Give path as relative to prefix.
953 * The strbuf may or may not be used, so do not assume it contains the
954 * returned path.
956 const char *relative_path(const char *in, const char *prefix,
957 struct strbuf *sb)
959 int in_len = in ? strlen(in) : 0;
960 int prefix_len = prefix ? strlen(prefix) : 0;
961 int in_off = 0;
962 int prefix_off = 0;
963 int i = 0, j = 0;
965 if (!in_len)
966 return "./";
967 else if (!prefix_len)
968 return in;
970 if (have_same_root(in, prefix))
971 /* bypass dos_drive, for "c:" is identical to "C:" */
972 i = j = has_dos_drive_prefix(in);
973 else {
974 return in;
977 while (i < prefix_len && j < in_len && prefix[i] == in[j]) {
978 if (is_dir_sep(prefix[i])) {
979 while (is_dir_sep(prefix[i]))
980 i++;
981 while (is_dir_sep(in[j]))
982 j++;
983 prefix_off = i;
984 in_off = j;
985 } else {
986 i++;
987 j++;
991 if (
992 /* "prefix" seems like prefix of "in" */
993 i >= prefix_len &&
995 * but "/foo" is not a prefix of "/foobar"
996 * (i.e. prefix not end with '/')
998 prefix_off < prefix_len) {
999 if (j >= in_len) {
1000 /* in="/a/b", prefix="/a/b" */
1001 in_off = in_len;
1002 } else if (is_dir_sep(in[j])) {
1003 /* in="/a/b/c", prefix="/a/b" */
1004 while (is_dir_sep(in[j]))
1005 j++;
1006 in_off = j;
1007 } else {
1008 /* in="/a/bbb/c", prefix="/a/b" */
1009 i = prefix_off;
1011 } else if (
1012 /* "in" is short than "prefix" */
1013 j >= in_len &&
1014 /* "in" not end with '/' */
1015 in_off < in_len) {
1016 if (is_dir_sep(prefix[i])) {
1017 /* in="/a/b", prefix="/a/b/c/" */
1018 while (is_dir_sep(prefix[i]))
1019 i++;
1020 in_off = in_len;
1023 in += in_off;
1024 in_len -= in_off;
1026 if (i >= prefix_len) {
1027 if (!in_len)
1028 return "./";
1029 else
1030 return in;
1033 strbuf_reset(sb);
1034 strbuf_grow(sb, in_len);
1036 while (i < prefix_len) {
1037 if (is_dir_sep(prefix[i])) {
1038 strbuf_addstr(sb, "../");
1039 while (is_dir_sep(prefix[i]))
1040 i++;
1041 continue;
1043 i++;
1045 if (!is_dir_sep(prefix[prefix_len - 1]))
1046 strbuf_addstr(sb, "../");
1048 strbuf_addstr(sb, in);
1050 return sb->buf;
1054 * A simpler implementation of relative_path
1056 * Get relative path by removing "prefix" from "in". This function
1057 * first appears in v1.5.6-1-g044bbbc, and makes git_dir shorter
1058 * to increase performance when traversing the path to work_tree.
1060 const char *remove_leading_path(const char *in, const char *prefix)
1062 static struct strbuf buf = STRBUF_INIT;
1063 int i = 0, j = 0;
1065 if (!prefix || !prefix[0])
1066 return in;
1067 while (prefix[i]) {
1068 if (is_dir_sep(prefix[i])) {
1069 if (!is_dir_sep(in[j]))
1070 return in;
1071 while (is_dir_sep(prefix[i]))
1072 i++;
1073 while (is_dir_sep(in[j]))
1074 j++;
1075 continue;
1076 } else if (in[j] != prefix[i]) {
1077 return in;
1079 i++;
1080 j++;
1082 if (
1083 /* "/foo" is a prefix of "/foo" */
1084 in[j] &&
1085 /* "/foo" is not a prefix of "/foobar" */
1086 !is_dir_sep(prefix[i-1]) && !is_dir_sep(in[j])
1088 return in;
1089 while (is_dir_sep(in[j]))
1090 j++;
1092 strbuf_reset(&buf);
1093 if (!in[j])
1094 strbuf_addstr(&buf, ".");
1095 else
1096 strbuf_addstr(&buf, in + j);
1097 return buf.buf;
1101 * It is okay if dst == src, but they should not overlap otherwise.
1102 * The "dst" buffer must be at least as long as "src"; normalizing may shrink
1103 * the size of the path, but will never grow it.
1105 * Performs the following normalizations on src, storing the result in dst:
1106 * - Ensures that components are separated by '/' (Windows only)
1107 * - Squashes sequences of '/' except "//server/share" on Windows
1108 * - Removes "." components.
1109 * - Removes ".." components, and the components the precede them.
1110 * Returns failure (non-zero) if a ".." component appears as first path
1111 * component anytime during the normalization. Otherwise, returns success (0).
1113 * Note that this function is purely textual. It does not follow symlinks,
1114 * verify the existence of the path, or make any system calls.
1116 * prefix_len != NULL is for a specific case of prefix_pathspec():
1117 * assume that src == dst and src[0..prefix_len-1] is already
1118 * normalized, any time "../" eats up to the prefix_len part,
1119 * prefix_len is reduced. In the end prefix_len is the remaining
1120 * prefix that has not been overridden by user pathspec.
1122 * NEEDSWORK: This function doesn't perform normalization w.r.t. trailing '/'.
1123 * For everything but the root folder itself, the normalized path should not
1124 * end with a '/', then the callers need to be fixed up accordingly.
1127 int normalize_path_copy_len(char *dst, const char *src, int *prefix_len)
1129 char *dst0;
1130 const char *end;
1133 * Copy initial part of absolute path: "/", "C:/", "//server/share/".
1135 end = src + offset_1st_component(src);
1136 while (src < end) {
1137 char c = *src++;
1138 if (is_dir_sep(c))
1139 c = '/';
1140 *dst++ = c;
1142 dst0 = dst;
1144 while (is_dir_sep(*src))
1145 src++;
1147 for (;;) {
1148 char c = *src;
1151 * A path component that begins with . could be
1152 * special:
1153 * (1) "." and ends -- ignore and terminate.
1154 * (2) "./" -- ignore them, eat slash and continue.
1155 * (3) ".." and ends -- strip one and terminate.
1156 * (4) "../" -- strip one, eat slash and continue.
1158 if (c == '.') {
1159 if (!src[1]) {
1160 /* (1) */
1161 src++;
1162 } else if (is_dir_sep(src[1])) {
1163 /* (2) */
1164 src += 2;
1165 while (is_dir_sep(*src))
1166 src++;
1167 continue;
1168 } else if (src[1] == '.') {
1169 if (!src[2]) {
1170 /* (3) */
1171 src += 2;
1172 goto up_one;
1173 } else if (is_dir_sep(src[2])) {
1174 /* (4) */
1175 src += 3;
1176 while (is_dir_sep(*src))
1177 src++;
1178 goto up_one;
1183 /* copy up to the next '/', and eat all '/' */
1184 while ((c = *src++) != '\0' && !is_dir_sep(c))
1185 *dst++ = c;
1186 if (is_dir_sep(c)) {
1187 *dst++ = '/';
1188 while (is_dir_sep(c))
1189 c = *src++;
1190 src--;
1191 } else if (!c)
1192 break;
1193 continue;
1195 up_one:
1197 * dst0..dst is prefix portion, and dst[-1] is '/';
1198 * go up one level.
1200 dst--; /* go to trailing '/' */
1201 if (dst <= dst0)
1202 return -1;
1203 /* Windows: dst[-1] cannot be backslash anymore */
1204 while (dst0 < dst && dst[-1] != '/')
1205 dst--;
1206 if (prefix_len && *prefix_len > dst - dst0)
1207 *prefix_len = dst - dst0;
1209 *dst = '\0';
1210 return 0;
1213 int normalize_path_copy(char *dst, const char *src)
1215 return normalize_path_copy_len(dst, src, NULL);
1219 * path = Canonical absolute path
1220 * prefixes = string_list containing normalized, absolute paths without
1221 * trailing slashes (except for the root directory, which is denoted by "/").
1223 * Determines, for each path in prefixes, whether the "prefix"
1224 * is an ancestor directory of path. Returns the length of the longest
1225 * ancestor directory, excluding any trailing slashes, or -1 if no prefix
1226 * is an ancestor. (Note that this means 0 is returned if prefixes is
1227 * ["/"].) "/foo" is not considered an ancestor of "/foobar". Directories
1228 * are not considered to be their own ancestors. path must be in a
1229 * canonical form: empty components, or "." or ".." components are not
1230 * allowed.
1232 int longest_ancestor_length(const char *path, struct string_list *prefixes)
1234 int i, max_len = -1;
1236 if (!strcmp(path, "/"))
1237 return -1;
1239 for (i = 0; i < prefixes->nr; i++) {
1240 const char *ceil = prefixes->items[i].string;
1241 int len = strlen(ceil);
1244 * For root directories (`/`, `C:/`, `//server/share/`)
1245 * adjust the length to exclude the trailing slash.
1247 if (len > 0 && ceil[len - 1] == '/')
1248 len--;
1250 if (strncmp(path, ceil, len) ||
1251 path[len] != '/' || !path[len + 1])
1252 continue; /* no match */
1254 if (len > max_len)
1255 max_len = len;
1258 return max_len;
1261 /* strip arbitrary amount of directory separators at end of path */
1262 static inline int chomp_trailing_dir_sep(const char *path, int len)
1264 while (len && is_dir_sep(path[len - 1]))
1265 len--;
1266 return len;
1270 * If path ends with suffix (complete path components), returns the offset of
1271 * the last character in the path before the suffix (sans trailing directory
1272 * separators), and -1 otherwise.
1274 static ssize_t stripped_path_suffix_offset(const char *path, const char *suffix)
1276 int path_len = strlen(path), suffix_len = strlen(suffix);
1278 while (suffix_len) {
1279 if (!path_len)
1280 return -1;
1282 if (is_dir_sep(path[path_len - 1])) {
1283 if (!is_dir_sep(suffix[suffix_len - 1]))
1284 return -1;
1285 path_len = chomp_trailing_dir_sep(path, path_len);
1286 suffix_len = chomp_trailing_dir_sep(suffix, suffix_len);
1288 else if (path[--path_len] != suffix[--suffix_len])
1289 return -1;
1292 if (path_len && !is_dir_sep(path[path_len - 1]))
1293 return -1;
1294 return chomp_trailing_dir_sep(path, path_len);
1298 * Returns true if the path ends with components, considering only complete path
1299 * components, and false otherwise.
1301 int ends_with_path_components(const char *path, const char *components)
1303 return stripped_path_suffix_offset(path, components) != -1;
1307 * If path ends with suffix (complete path components), returns the
1308 * part before suffix (sans trailing directory separators).
1309 * Otherwise returns NULL.
1311 char *strip_path_suffix(const char *path, const char *suffix)
1313 ssize_t offset = stripped_path_suffix_offset(path, suffix);
1315 return offset == -1 ? NULL : xstrndup(path, offset);
1318 int daemon_avoid_alias(const char *p)
1320 int sl, ndot;
1323 * This resurrects the belts and suspenders paranoia check by HPA
1324 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
1325 * does not do getcwd() based path canonicalization.
1327 * sl becomes true immediately after seeing '/' and continues to
1328 * be true as long as dots continue after that without intervening
1329 * non-dot character.
1331 if (!p || (*p != '/' && *p != '~'))
1332 return -1;
1333 sl = 1; ndot = 0;
1334 p++;
1336 while (1) {
1337 char ch = *p++;
1338 if (sl) {
1339 if (ch == '.')
1340 ndot++;
1341 else if (ch == '/') {
1342 if (ndot < 3)
1343 /* reject //, /./ and /../ */
1344 return -1;
1345 ndot = 0;
1347 else if (ch == 0) {
1348 if (0 < ndot && ndot < 3)
1349 /* reject /.$ and /..$ */
1350 return -1;
1351 return 0;
1353 else
1354 sl = ndot = 0;
1356 else if (ch == 0)
1357 return 0;
1358 else if (ch == '/') {
1359 sl = 1;
1360 ndot = 0;
1366 * On NTFS, we need to be careful to disallow certain synonyms of the `.git/`
1367 * directory:
1369 * - For historical reasons, file names that end in spaces or periods are
1370 * automatically trimmed. Therefore, `.git . . ./` is a valid way to refer
1371 * to `.git/`.
1373 * - For other historical reasons, file names that do not conform to the 8.3
1374 * format (up to eight characters for the basename, three for the file
1375 * extension, certain characters not allowed such as `+`, etc) are associated
1376 * with a so-called "short name", at least on the `C:` drive by default.
1377 * Which means that `git~1/` is a valid way to refer to `.git/`.
1379 * Note: Technically, `.git/` could receive the short name `git~2` if the
1380 * short name `git~1` were already used. In Git, however, we guarantee that
1381 * `.git` is the first item in a directory, therefore it will be associated
1382 * with the short name `git~1` (unless short names are disabled).
1384 * - For yet other historical reasons, NTFS supports so-called "Alternate Data
1385 * Streams", i.e. metadata associated with a given file, referred to via
1386 * `<filename>:<stream-name>:<stream-type>`. There exists a default stream
1387 * type for directories, allowing `.git/` to be accessed via
1388 * `.git::$INDEX_ALLOCATION/`.
1390 * When this function returns 1, it indicates that the specified file/directory
1391 * name refers to a `.git` file or directory, or to any of these synonyms, and
1392 * Git should therefore not track it.
1394 * For performance reasons, _all_ Alternate Data Streams of `.git/` are
1395 * forbidden, not just `::$INDEX_ALLOCATION`.
1397 * This function is intended to be used by `git fsck` even on platforms where
1398 * the backslash is a regular filename character, therefore it needs to handle
1399 * backlash characters in the provided `name` specially: they are interpreted
1400 * as directory separators.
1402 int is_ntfs_dotgit(const char *name)
1404 char c;
1407 * Note that when we don't find `.git` or `git~1` we end up with `name`
1408 * advanced partway through the string. That's okay, though, as we
1409 * return immediately in those cases, without looking at `name` any
1410 * further.
1412 c = *(name++);
1413 if (c == '.') {
1414 /* .git */
1415 if (((c = *(name++)) != 'g' && c != 'G') ||
1416 ((c = *(name++)) != 'i' && c != 'I') ||
1417 ((c = *(name++)) != 't' && c != 'T'))
1418 return 0;
1419 } else if (c == 'g' || c == 'G') {
1420 /* git ~1 */
1421 if (((c = *(name++)) != 'i' && c != 'I') ||
1422 ((c = *(name++)) != 't' && c != 'T') ||
1423 *(name++) != '~' ||
1424 *(name++) != '1')
1425 return 0;
1426 } else
1427 return 0;
1429 for (;;) {
1430 c = *(name++);
1431 if (!c || is_xplatform_dir_sep(c) || c == ':')
1432 return 1;
1433 if (c != '.' && c != ' ')
1434 return 0;
1438 static int is_ntfs_dot_generic(const char *name,
1439 const char *dotgit_name,
1440 size_t len,
1441 const char *dotgit_ntfs_shortname_prefix)
1443 int saw_tilde;
1444 size_t i;
1446 if ((name[0] == '.' && !strncasecmp(name + 1, dotgit_name, len))) {
1447 i = len + 1;
1448 only_spaces_and_periods:
1449 for (;;) {
1450 char c = name[i++];
1451 if (!c || c == ':')
1452 return 1;
1453 if (c != ' ' && c != '.')
1454 return 0;
1459 * Is it a regular NTFS short name, i.e. shortened to 6 characters,
1460 * followed by ~1, ... ~4?
1462 if (!strncasecmp(name, dotgit_name, 6) && name[6] == '~' &&
1463 name[7] >= '1' && name[7] <= '4') {
1464 i = 8;
1465 goto only_spaces_and_periods;
1469 * Is it a fall-back NTFS short name (for details, see
1470 * https://en.wikipedia.org/wiki/8.3_filename?
1472 for (i = 0, saw_tilde = 0; i < 8; i++)
1473 if (name[i] == '\0')
1474 return 0;
1475 else if (saw_tilde) {
1476 if (name[i] < '0' || name[i] > '9')
1477 return 0;
1478 } else if (name[i] == '~') {
1479 if (name[++i] < '1' || name[i] > '9')
1480 return 0;
1481 saw_tilde = 1;
1482 } else if (i >= 6)
1483 return 0;
1484 else if (name[i] & 0x80) {
1486 * We know our needles contain only ASCII, so we clamp
1487 * here to make the results of tolower() sane.
1489 return 0;
1490 } else if (tolower(name[i]) != dotgit_ntfs_shortname_prefix[i])
1491 return 0;
1493 goto only_spaces_and_periods;
1497 * Inline helper to make sure compiler resolves strlen() on literals at
1498 * compile time.
1500 static inline int is_ntfs_dot_str(const char *name, const char *dotgit_name,
1501 const char *dotgit_ntfs_shortname_prefix)
1503 return is_ntfs_dot_generic(name, dotgit_name, strlen(dotgit_name),
1504 dotgit_ntfs_shortname_prefix);
1507 int is_ntfs_dotgitmodules(const char *name)
1509 return is_ntfs_dot_str(name, "gitmodules", "gi7eba");
1512 int is_ntfs_dotgitignore(const char *name)
1514 return is_ntfs_dot_str(name, "gitignore", "gi250a");
1517 int is_ntfs_dotgitattributes(const char *name)
1519 return is_ntfs_dot_str(name, "gitattributes", "gi7d29");
1522 int is_ntfs_dotmailmap(const char *name)
1524 return is_ntfs_dot_str(name, "mailmap", "maba30");
1527 int looks_like_command_line_option(const char *str)
1529 return str && str[0] == '-';
1532 char *xdg_config_home_for(const char *subdir, const char *filename)
1534 const char *home, *config_home;
1536 assert(subdir);
1537 assert(filename);
1538 config_home = getenv("XDG_CONFIG_HOME");
1539 if (config_home && *config_home)
1540 return mkpathdup("%s/%s/%s", config_home, subdir, filename);
1542 home = getenv("HOME");
1543 if (home)
1544 return mkpathdup("%s/.config/%s/%s", home, subdir, filename);
1546 return NULL;
1549 char *xdg_config_home(const char *filename)
1551 return xdg_config_home_for("git", filename);
1554 char *xdg_cache_home(const char *filename)
1556 const char *home, *cache_home;
1558 assert(filename);
1559 cache_home = getenv("XDG_CACHE_HOME");
1560 if (cache_home && *cache_home)
1561 return mkpathdup("%s/git/%s", cache_home, filename);
1563 home = getenv("HOME");
1564 if (home)
1565 return mkpathdup("%s/.cache/git/%s", home, filename);
1566 return NULL;
1569 REPO_GIT_PATH_FUNC(squash_msg, "SQUASH_MSG")
1570 REPO_GIT_PATH_FUNC(merge_msg, "MERGE_MSG")
1571 REPO_GIT_PATH_FUNC(merge_rr, "MERGE_RR")
1572 REPO_GIT_PATH_FUNC(merge_mode, "MERGE_MODE")
1573 REPO_GIT_PATH_FUNC(merge_head, "MERGE_HEAD")
1574 REPO_GIT_PATH_FUNC(merge_autostash, "MERGE_AUTOSTASH")
1575 REPO_GIT_PATH_FUNC(auto_merge, "AUTO_MERGE")
1576 REPO_GIT_PATH_FUNC(fetch_head, "FETCH_HEAD")
1577 REPO_GIT_PATH_FUNC(shallow, "shallow")