for_each_object: mark unused callback parameters
[git/gitster.git] / path.c
blob0b641233e32248d00b4fd03d1db009d7012b3606
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"
14 #include "lockfile.h"
15 #include "exec-cmd.h"
17 static int get_st_mode_bits(const char *path, int *mode)
19 struct stat st;
20 if (lstat(path, &st) < 0)
21 return -1;
22 *mode = st.st_mode;
23 return 0;
26 static char bad_path[] = "/bad-path/";
28 static struct strbuf *get_pathname(void)
30 static struct strbuf pathname_array[4] = {
31 STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
33 static int index;
34 struct strbuf *sb = &pathname_array[index];
35 index = (index + 1) % ARRAY_SIZE(pathname_array);
36 strbuf_reset(sb);
37 return sb;
40 static const char *cleanup_path(const char *path)
42 /* Clean it up */
43 if (skip_prefix(path, "./", &path)) {
44 while (*path == '/')
45 path++;
47 return path;
50 static void strbuf_cleanup_path(struct strbuf *sb)
52 const char *path = cleanup_path(sb->buf);
53 if (path > sb->buf)
54 strbuf_remove(sb, 0, path - sb->buf);
57 char *mksnpath(char *buf, size_t n, const char *fmt, ...)
59 va_list args;
60 unsigned len;
62 va_start(args, fmt);
63 len = vsnprintf(buf, n, fmt, args);
64 va_end(args);
65 if (len >= n) {
66 strlcpy(buf, bad_path, n);
67 return buf;
69 return (char *)cleanup_path(buf);
72 static int dir_prefix(const char *buf, const char *dir)
74 int len = strlen(dir);
75 return !strncmp(buf, dir, len) &&
76 (is_dir_sep(buf[len]) || buf[len] == '\0');
79 /* $buf =~ m|$dir/+$file| but without regex */
80 static int is_dir_file(const char *buf, const char *dir, const char *file)
82 int len = strlen(dir);
83 if (strncmp(buf, dir, len) || !is_dir_sep(buf[len]))
84 return 0;
85 while (is_dir_sep(buf[len]))
86 len++;
87 return !strcmp(buf + len, file);
90 static void replace_dir(struct strbuf *buf, int len, const char *newdir)
92 int newlen = strlen(newdir);
93 int need_sep = (buf->buf[len] && !is_dir_sep(buf->buf[len])) &&
94 !is_dir_sep(newdir[newlen - 1]);
95 if (need_sep)
96 len--; /* keep one char, to be replaced with '/' */
97 strbuf_splice(buf, 0, len, newdir, newlen);
98 if (need_sep)
99 buf->buf[newlen] = '/';
102 struct common_dir {
103 /* Not considered garbage for report_linked_checkout_garbage */
104 unsigned ignore_garbage:1;
105 unsigned is_dir:1;
106 /* Belongs to the common dir, though it may contain paths that don't */
107 unsigned is_common:1;
108 const char *path;
111 static struct common_dir common_list[] = {
112 { 0, 1, 1, "branches" },
113 { 0, 1, 1, "common" },
114 { 0, 1, 1, "hooks" },
115 { 0, 1, 1, "info" },
116 { 0, 0, 0, "info/sparse-checkout" },
117 { 1, 1, 1, "logs" },
118 { 1, 0, 0, "logs/HEAD" },
119 { 0, 1, 0, "logs/refs/bisect" },
120 { 0, 1, 0, "logs/refs/rewritten" },
121 { 0, 1, 0, "logs/refs/worktree" },
122 { 0, 1, 1, "lost-found" },
123 { 0, 1, 1, "objects" },
124 { 0, 1, 1, "refs" },
125 { 0, 1, 0, "refs/bisect" },
126 { 0, 1, 0, "refs/rewritten" },
127 { 0, 1, 0, "refs/worktree" },
128 { 0, 1, 1, "remotes" },
129 { 0, 1, 1, "worktrees" },
130 { 0, 1, 1, "rr-cache" },
131 { 0, 1, 1, "svn" },
132 { 0, 0, 1, "config" },
133 { 1, 0, 1, "gc.pid" },
134 { 0, 0, 1, "packed-refs" },
135 { 0, 0, 1, "shallow" },
136 { 0, 0, 0, NULL }
140 * A compressed trie. A trie node consists of zero or more characters that
141 * are common to all elements with this prefix, optionally followed by some
142 * children. If value is not NULL, the trie node is a terminal node.
144 * For example, consider the following set of strings:
145 * abc
146 * def
147 * definite
148 * definition
150 * The trie would look like:
151 * root: len = 0, children a and d non-NULL, value = NULL.
152 * a: len = 2, contents = bc, value = (data for "abc")
153 * d: len = 2, contents = ef, children i non-NULL, value = (data for "def")
154 * i: len = 3, contents = nit, children e and i non-NULL, value = NULL
155 * e: len = 0, children all NULL, value = (data for "definite")
156 * i: len = 2, contents = on, children all NULL,
157 * value = (data for "definition")
159 struct trie {
160 struct trie *children[256];
161 int len;
162 char *contents;
163 void *value;
166 static struct trie *make_trie_node(const char *key, void *value)
168 struct trie *new_node = xcalloc(1, sizeof(*new_node));
169 new_node->len = strlen(key);
170 if (new_node->len) {
171 new_node->contents = xmalloc(new_node->len);
172 memcpy(new_node->contents, key, new_node->len);
174 new_node->value = value;
175 return new_node;
179 * Add a key/value pair to a trie. The key is assumed to be \0-terminated.
180 * If there was an existing value for this key, return it.
182 static void *add_to_trie(struct trie *root, const char *key, void *value)
184 struct trie *child;
185 void *old;
186 int i;
188 if (!*key) {
189 /* we have reached the end of the key */
190 old = root->value;
191 root->value = value;
192 return old;
195 for (i = 0; i < root->len; i++) {
196 if (root->contents[i] == key[i])
197 continue;
200 * Split this node: child will contain this node's
201 * existing children.
203 child = xmalloc(sizeof(*child));
204 memcpy(child->children, root->children, sizeof(root->children));
206 child->len = root->len - i - 1;
207 if (child->len) {
208 child->contents = xstrndup(root->contents + i + 1,
209 child->len);
211 child->value = root->value;
212 root->value = NULL;
213 root->len = i;
215 memset(root->children, 0, sizeof(root->children));
216 root->children[(unsigned char)root->contents[i]] = child;
218 /* This is the newly-added child. */
219 root->children[(unsigned char)key[i]] =
220 make_trie_node(key + i + 1, value);
221 return NULL;
224 /* We have matched the entire compressed section */
225 if (key[i]) {
226 child = root->children[(unsigned char)key[root->len]];
227 if (child) {
228 return add_to_trie(child, key + root->len + 1, value);
229 } else {
230 child = make_trie_node(key + root->len + 1, value);
231 root->children[(unsigned char)key[root->len]] = child;
232 return NULL;
236 old = root->value;
237 root->value = value;
238 return old;
241 typedef int (*match_fn)(const char *unmatched, void *value, void *baton);
244 * Search a trie for some key. Find the longest /-or-\0-terminated
245 * prefix of the key for which the trie contains a value. If there is
246 * no such prefix, return -1. Otherwise call fn with the unmatched
247 * portion of the key and the found value. If fn returns 0 or
248 * positive, then return its return value. If fn returns negative,
249 * then call fn with the next-longest /-terminated prefix of the key
250 * (i.e. a parent directory) for which the trie contains a value, and
251 * handle its return value the same way. If there is no shorter
252 * /-terminated prefix with a value left, then return the negative
253 * return value of the most recent fn invocation.
255 * The key is partially normalized: consecutive slashes are skipped.
257 * For example, consider the trie containing only [logs,
258 * logs/refs/bisect], both with values, but not logs/refs.
260 * | key | unmatched | prefix to node | return value |
261 * |--------------------|----------------|------------------|--------------|
262 * | a | not called | n/a | -1 |
263 * | logstore | not called | n/a | -1 |
264 * | logs | \0 | logs | as per fn |
265 * | logs/ | / | logs | as per fn |
266 * | logs/refs | /refs | logs | as per fn |
267 * | logs/refs/ | /refs/ | logs | as per fn |
268 * | logs/refs/b | /refs/b | logs | as per fn |
269 * | logs/refs/bisected | /refs/bisected | logs | as per fn |
270 * | logs/refs/bisect | \0 | logs/refs/bisect | as per fn |
271 * | logs/refs/bisect/ | / | logs/refs/bisect | as per fn |
272 * | logs/refs/bisect/a | /a | logs/refs/bisect | as per fn |
273 * | (If fn in the previous line returns -1, then fn is called once more:) |
274 * | logs/refs/bisect/a | /refs/bisect/a | logs | as per fn |
275 * |--------------------|----------------|------------------|--------------|
277 static int trie_find(struct trie *root, const char *key, match_fn fn,
278 void *baton)
280 int i;
281 int result;
282 struct trie *child;
284 if (!*key) {
285 /* we have reached the end of the key */
286 if (root->value && !root->len)
287 return fn(key, root->value, baton);
288 else
289 return -1;
292 for (i = 0; i < root->len; i++) {
293 /* Partial path normalization: skip consecutive slashes. */
294 if (key[i] == '/' && key[i+1] == '/') {
295 key++;
296 continue;
298 if (root->contents[i] != key[i])
299 return -1;
302 /* Matched the entire compressed section */
303 key += i;
304 if (!*key) {
305 /* End of key */
306 if (root->value)
307 return fn(key, root->value, baton);
308 else
309 return -1;
312 /* Partial path normalization: skip consecutive slashes */
313 while (key[0] == '/' && key[1] == '/')
314 key++;
316 child = root->children[(unsigned char)*key];
317 if (child)
318 result = trie_find(child, key + 1, fn, baton);
319 else
320 result = -1;
322 if (result >= 0 || (*key != '/' && *key != 0))
323 return result;
324 if (root->value)
325 return fn(key, root->value, baton);
326 else
327 return -1;
330 static struct trie common_trie;
331 static int common_trie_done_setup;
333 static void init_common_trie(void)
335 struct common_dir *p;
337 if (common_trie_done_setup)
338 return;
340 for (p = common_list; p->path; p++)
341 add_to_trie(&common_trie, p->path, p);
343 common_trie_done_setup = 1;
347 * Helper function for update_common_dir: returns 1 if the dir
348 * prefix is common.
350 static int check_common(const char *unmatched, void *value,
351 void *baton UNUSED)
353 struct common_dir *dir = value;
355 if (dir->is_dir && (unmatched[0] == 0 || unmatched[0] == '/'))
356 return dir->is_common;
358 if (!dir->is_dir && unmatched[0] == 0)
359 return dir->is_common;
361 return 0;
364 static void update_common_dir(struct strbuf *buf, int git_dir_len,
365 const char *common_dir)
367 char *base = buf->buf + git_dir_len;
368 int has_lock_suffix = strbuf_strip_suffix(buf, LOCK_SUFFIX);
370 init_common_trie();
371 if (trie_find(&common_trie, base, check_common, NULL) > 0)
372 replace_dir(buf, git_dir_len, common_dir);
374 if (has_lock_suffix)
375 strbuf_addstr(buf, LOCK_SUFFIX);
378 void report_linked_checkout_garbage(void)
380 struct strbuf sb = STRBUF_INIT;
381 const struct common_dir *p;
382 int len;
384 if (!the_repository->different_commondir)
385 return;
386 strbuf_addf(&sb, "%s/", get_git_dir());
387 len = sb.len;
388 for (p = common_list; p->path; p++) {
389 const char *path = p->path;
390 if (p->ignore_garbage)
391 continue;
392 strbuf_setlen(&sb, len);
393 strbuf_addstr(&sb, path);
394 if (file_exists(sb.buf))
395 report_garbage(PACKDIR_FILE_GARBAGE, sb.buf);
397 strbuf_release(&sb);
400 static void adjust_git_path(const struct repository *repo,
401 struct strbuf *buf, int git_dir_len)
403 const char *base = buf->buf + git_dir_len;
404 if (is_dir_file(base, "info", "grafts"))
405 strbuf_splice(buf, 0, buf->len,
406 repo->graft_file, strlen(repo->graft_file));
407 else if (!strcmp(base, "index"))
408 strbuf_splice(buf, 0, buf->len,
409 repo->index_file, strlen(repo->index_file));
410 else if (dir_prefix(base, "objects"))
411 replace_dir(buf, git_dir_len + 7, repo->objects->odb->path);
412 else if (git_hooks_path && dir_prefix(base, "hooks"))
413 replace_dir(buf, git_dir_len + 5, git_hooks_path);
414 else if (repo->different_commondir)
415 update_common_dir(buf, git_dir_len, repo->commondir);
418 static void strbuf_worktree_gitdir(struct strbuf *buf,
419 const struct repository *repo,
420 const struct worktree *wt)
422 if (!wt)
423 strbuf_addstr(buf, repo->gitdir);
424 else if (!wt->id)
425 strbuf_addstr(buf, repo->commondir);
426 else
427 strbuf_git_common_path(buf, repo, "worktrees/%s", wt->id);
430 static void do_git_path(const struct repository *repo,
431 const struct worktree *wt, struct strbuf *buf,
432 const char *fmt, va_list args)
434 int gitdir_len;
435 strbuf_worktree_gitdir(buf, repo, wt);
436 if (buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
437 strbuf_addch(buf, '/');
438 gitdir_len = buf->len;
439 strbuf_vaddf(buf, fmt, args);
440 if (!wt)
441 adjust_git_path(repo, buf, gitdir_len);
442 strbuf_cleanup_path(buf);
445 char *repo_git_path(const struct repository *repo,
446 const char *fmt, ...)
448 struct strbuf path = STRBUF_INIT;
449 va_list args;
450 va_start(args, fmt);
451 do_git_path(repo, NULL, &path, fmt, args);
452 va_end(args);
453 return strbuf_detach(&path, NULL);
456 void strbuf_repo_git_path(struct strbuf *sb,
457 const struct repository *repo,
458 const char *fmt, ...)
460 va_list args;
461 va_start(args, fmt);
462 do_git_path(repo, NULL, sb, fmt, args);
463 va_end(args);
466 char *git_path_buf(struct strbuf *buf, const char *fmt, ...)
468 va_list args;
469 strbuf_reset(buf);
470 va_start(args, fmt);
471 do_git_path(the_repository, NULL, buf, fmt, args);
472 va_end(args);
473 return buf->buf;
476 void strbuf_git_path(struct strbuf *sb, const char *fmt, ...)
478 va_list args;
479 va_start(args, fmt);
480 do_git_path(the_repository, NULL, sb, fmt, args);
481 va_end(args);
484 const char *git_path(const char *fmt, ...)
486 struct strbuf *pathname = get_pathname();
487 va_list args;
488 va_start(args, fmt);
489 do_git_path(the_repository, NULL, pathname, fmt, args);
490 va_end(args);
491 return pathname->buf;
494 char *git_pathdup(const char *fmt, ...)
496 struct strbuf path = STRBUF_INIT;
497 va_list args;
498 va_start(args, fmt);
499 do_git_path(the_repository, NULL, &path, fmt, args);
500 va_end(args);
501 return strbuf_detach(&path, NULL);
504 char *mkpathdup(const char *fmt, ...)
506 struct strbuf sb = STRBUF_INIT;
507 va_list args;
508 va_start(args, fmt);
509 strbuf_vaddf(&sb, fmt, args);
510 va_end(args);
511 strbuf_cleanup_path(&sb);
512 return strbuf_detach(&sb, NULL);
515 const char *mkpath(const char *fmt, ...)
517 va_list args;
518 struct strbuf *pathname = get_pathname();
519 va_start(args, fmt);
520 strbuf_vaddf(pathname, fmt, args);
521 va_end(args);
522 return cleanup_path(pathname->buf);
525 const char *worktree_git_path(const struct worktree *wt, const char *fmt, ...)
527 struct strbuf *pathname = get_pathname();
528 va_list args;
529 va_start(args, fmt);
530 do_git_path(the_repository, wt, pathname, fmt, args);
531 va_end(args);
532 return pathname->buf;
535 static void do_worktree_path(const struct repository *repo,
536 struct strbuf *buf,
537 const char *fmt, va_list args)
539 strbuf_addstr(buf, repo->worktree);
540 if(buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
541 strbuf_addch(buf, '/');
543 strbuf_vaddf(buf, fmt, args);
544 strbuf_cleanup_path(buf);
547 char *repo_worktree_path(const struct repository *repo, const char *fmt, ...)
549 struct strbuf path = STRBUF_INIT;
550 va_list args;
552 if (!repo->worktree)
553 return NULL;
555 va_start(args, fmt);
556 do_worktree_path(repo, &path, fmt, args);
557 va_end(args);
559 return strbuf_detach(&path, NULL);
562 void strbuf_repo_worktree_path(struct strbuf *sb,
563 const struct repository *repo,
564 const char *fmt, ...)
566 va_list args;
568 if (!repo->worktree)
569 return;
571 va_start(args, fmt);
572 do_worktree_path(repo, sb, fmt, args);
573 va_end(args);
576 /* Returns 0 on success, negative on failure. */
577 static int do_submodule_path(struct strbuf *buf, const char *path,
578 const char *fmt, va_list args)
580 struct strbuf git_submodule_common_dir = STRBUF_INIT;
581 struct strbuf git_submodule_dir = STRBUF_INIT;
582 int ret;
584 ret = submodule_to_gitdir(&git_submodule_dir, path);
585 if (ret)
586 goto cleanup;
588 strbuf_complete(&git_submodule_dir, '/');
589 strbuf_addbuf(buf, &git_submodule_dir);
590 strbuf_vaddf(buf, fmt, args);
592 if (get_common_dir_noenv(&git_submodule_common_dir, git_submodule_dir.buf))
593 update_common_dir(buf, git_submodule_dir.len, git_submodule_common_dir.buf);
595 strbuf_cleanup_path(buf);
597 cleanup:
598 strbuf_release(&git_submodule_dir);
599 strbuf_release(&git_submodule_common_dir);
600 return ret;
603 char *git_pathdup_submodule(const char *path, const char *fmt, ...)
605 int err;
606 va_list args;
607 struct strbuf buf = STRBUF_INIT;
608 va_start(args, fmt);
609 err = do_submodule_path(&buf, path, fmt, args);
610 va_end(args);
611 if (err) {
612 strbuf_release(&buf);
613 return NULL;
615 return strbuf_detach(&buf, NULL);
618 int strbuf_git_path_submodule(struct strbuf *buf, const char *path,
619 const char *fmt, ...)
621 int err;
622 va_list args;
623 va_start(args, fmt);
624 err = do_submodule_path(buf, path, fmt, args);
625 va_end(args);
627 return err;
630 static void do_git_common_path(const struct repository *repo,
631 struct strbuf *buf,
632 const char *fmt,
633 va_list args)
635 strbuf_addstr(buf, repo->commondir);
636 if (buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
637 strbuf_addch(buf, '/');
638 strbuf_vaddf(buf, fmt, args);
639 strbuf_cleanup_path(buf);
642 const char *git_common_path(const char *fmt, ...)
644 struct strbuf *pathname = get_pathname();
645 va_list args;
646 va_start(args, fmt);
647 do_git_common_path(the_repository, pathname, fmt, args);
648 va_end(args);
649 return pathname->buf;
652 void strbuf_git_common_path(struct strbuf *sb,
653 const struct repository *repo,
654 const char *fmt, ...)
656 va_list args;
657 va_start(args, fmt);
658 do_git_common_path(repo, sb, fmt, args);
659 va_end(args);
662 int validate_headref(const char *path)
664 struct stat st;
665 char buffer[256];
666 const char *refname;
667 struct object_id oid;
668 int fd;
669 ssize_t len;
671 if (lstat(path, &st) < 0)
672 return -1;
674 /* Make sure it is a "refs/.." symlink */
675 if (S_ISLNK(st.st_mode)) {
676 len = readlink(path, buffer, sizeof(buffer)-1);
677 if (len >= 5 && !memcmp("refs/", buffer, 5))
678 return 0;
679 return -1;
683 * Anything else, just open it and try to see if it is a symbolic ref.
685 fd = open(path, O_RDONLY);
686 if (fd < 0)
687 return -1;
688 len = read_in_full(fd, buffer, sizeof(buffer)-1);
689 close(fd);
691 if (len < 0)
692 return -1;
693 buffer[len] = '\0';
696 * Is it a symbolic ref?
698 if (skip_prefix(buffer, "ref:", &refname)) {
699 while (isspace(*refname))
700 refname++;
701 if (starts_with(refname, "refs/"))
702 return 0;
706 * Is this a detached HEAD?
708 if (!get_oid_hex(buffer, &oid))
709 return 0;
711 return -1;
714 static struct passwd *getpw_str(const char *username, size_t len)
716 struct passwd *pw;
717 char *username_z = xmemdupz(username, len);
718 pw = getpwnam(username_z);
719 free(username_z);
720 return pw;
724 * Return a string with ~ and ~user expanded via getpw*. Returns NULL on getpw
725 * failure or if path is NULL.
727 * If real_home is true, strbuf_realpath($HOME) is used in the `~/` expansion.
729 * If the path starts with `%(prefix)/`, the remainder is interpreted as
730 * relative to where Git is installed, and expanded to the absolute path.
732 char *interpolate_path(const char *path, int real_home)
734 struct strbuf user_path = STRBUF_INIT;
735 const char *to_copy = path;
737 if (!path)
738 goto return_null;
740 if (skip_prefix(path, "%(prefix)/", &path))
741 return system_path(path);
743 if (path[0] == '~') {
744 const char *first_slash = strchrnul(path, '/');
745 const char *username = path + 1;
746 size_t username_len = first_slash - username;
747 if (username_len == 0) {
748 const char *home = getenv("HOME");
749 if (!home)
750 goto return_null;
751 if (real_home)
752 strbuf_add_real_path(&user_path, home);
753 else
754 strbuf_addstr(&user_path, home);
755 #ifdef GIT_WINDOWS_NATIVE
756 convert_slashes(user_path.buf);
757 #endif
758 } else {
759 struct passwd *pw = getpw_str(username, username_len);
760 if (!pw)
761 goto return_null;
762 strbuf_addstr(&user_path, pw->pw_dir);
764 to_copy = first_slash;
766 strbuf_addstr(&user_path, to_copy);
767 return strbuf_detach(&user_path, NULL);
768 return_null:
769 strbuf_release(&user_path);
770 return NULL;
774 * First, one directory to try is determined by the following algorithm.
776 * (0) If "strict" is given, the path is used as given and no DWIM is
777 * done. Otherwise:
778 * (1) "~/path" to mean path under the running user's home directory;
779 * (2) "~user/path" to mean path under named user's home directory;
780 * (3) "relative/path" to mean cwd relative directory; or
781 * (4) "/absolute/path" to mean absolute directory.
783 * Unless "strict" is given, we check "%s/.git", "%s", "%s.git/.git", "%s.git"
784 * in this order. We select the first one that is a valid git repository, and
785 * chdir() to it. If none match, or we fail to chdir, we return NULL.
787 * If all goes well, we return the directory we used to chdir() (but
788 * before ~user is expanded), avoiding getcwd() resolving symbolic
789 * links. User relative paths are also returned as they are given,
790 * except DWIM suffixing.
792 const char *enter_repo(const char *path, int strict)
794 static struct strbuf validated_path = STRBUF_INIT;
795 static struct strbuf used_path = STRBUF_INIT;
797 if (!path)
798 return NULL;
800 if (!strict) {
801 static const char *suffix[] = {
802 "/.git", "", ".git/.git", ".git", NULL,
804 const char *gitfile;
805 int len = strlen(path);
806 int i;
807 while ((1 < len) && (path[len-1] == '/'))
808 len--;
811 * We can handle arbitrary-sized buffers, but this remains as a
812 * sanity check on untrusted input.
814 if (PATH_MAX <= len)
815 return NULL;
817 strbuf_reset(&used_path);
818 strbuf_reset(&validated_path);
819 strbuf_add(&used_path, path, len);
820 strbuf_add(&validated_path, path, len);
822 if (used_path.buf[0] == '~') {
823 char *newpath = interpolate_path(used_path.buf, 0);
824 if (!newpath)
825 return NULL;
826 strbuf_attach(&used_path, newpath, strlen(newpath),
827 strlen(newpath));
829 for (i = 0; suffix[i]; i++) {
830 struct stat st;
831 size_t baselen = used_path.len;
832 strbuf_addstr(&used_path, suffix[i]);
833 if (!stat(used_path.buf, &st) &&
834 (S_ISREG(st.st_mode) ||
835 (S_ISDIR(st.st_mode) && is_git_directory(used_path.buf)))) {
836 strbuf_addstr(&validated_path, suffix[i]);
837 break;
839 strbuf_setlen(&used_path, baselen);
841 if (!suffix[i])
842 return NULL;
843 gitfile = read_gitfile(used_path.buf);
844 if (gitfile) {
845 strbuf_reset(&used_path);
846 strbuf_addstr(&used_path, gitfile);
848 if (chdir(used_path.buf))
849 return NULL;
850 path = validated_path.buf;
852 else {
853 const char *gitfile = read_gitfile(path);
854 if (gitfile)
855 path = gitfile;
856 if (chdir(path))
857 return NULL;
860 if (is_git_directory(".")) {
861 set_git_dir(".", 0);
862 check_repository_format(NULL);
863 return path;
866 return NULL;
869 static int calc_shared_perm(int mode)
871 int tweak;
873 if (get_shared_repository() < 0)
874 tweak = -get_shared_repository();
875 else
876 tweak = get_shared_repository();
878 if (!(mode & S_IWUSR))
879 tweak &= ~0222;
880 if (mode & S_IXUSR)
881 /* Copy read bits to execute bits */
882 tweak |= (tweak & 0444) >> 2;
883 if (get_shared_repository() < 0)
884 mode = (mode & ~0777) | tweak;
885 else
886 mode |= tweak;
888 return mode;
892 int adjust_shared_perm(const char *path)
894 int old_mode, new_mode;
896 if (!get_shared_repository())
897 return 0;
898 if (get_st_mode_bits(path, &old_mode) < 0)
899 return -1;
901 new_mode = calc_shared_perm(old_mode);
902 if (S_ISDIR(old_mode)) {
903 /* Copy read bits to execute bits */
904 new_mode |= (new_mode & 0444) >> 2;
907 * g+s matters only if any extra access is granted
908 * based on group membership.
910 if (FORCE_DIR_SET_GID && (new_mode & 060))
911 new_mode |= FORCE_DIR_SET_GID;
914 if (((old_mode ^ new_mode) & ~S_IFMT) &&
915 chmod(path, (new_mode & ~S_IFMT)) < 0)
916 return -2;
917 return 0;
920 void safe_create_dir(const char *dir, int share)
922 if (mkdir(dir, 0777) < 0) {
923 if (errno != EEXIST) {
924 perror(dir);
925 exit(1);
928 else if (share && adjust_shared_perm(dir))
929 die(_("Could not make %s writable by group"), dir);
932 static int have_same_root(const char *path1, const char *path2)
934 int is_abs1, is_abs2;
936 is_abs1 = is_absolute_path(path1);
937 is_abs2 = is_absolute_path(path2);
938 return (is_abs1 && is_abs2 && tolower(path1[0]) == tolower(path2[0])) ||
939 (!is_abs1 && !is_abs2);
943 * Give path as relative to prefix.
945 * The strbuf may or may not be used, so do not assume it contains the
946 * returned path.
948 const char *relative_path(const char *in, const char *prefix,
949 struct strbuf *sb)
951 int in_len = in ? strlen(in) : 0;
952 int prefix_len = prefix ? strlen(prefix) : 0;
953 int in_off = 0;
954 int prefix_off = 0;
955 int i = 0, j = 0;
957 if (!in_len)
958 return "./";
959 else if (!prefix_len)
960 return in;
962 if (have_same_root(in, prefix))
963 /* bypass dos_drive, for "c:" is identical to "C:" */
964 i = j = has_dos_drive_prefix(in);
965 else {
966 return in;
969 while (i < prefix_len && j < in_len && prefix[i] == in[j]) {
970 if (is_dir_sep(prefix[i])) {
971 while (is_dir_sep(prefix[i]))
972 i++;
973 while (is_dir_sep(in[j]))
974 j++;
975 prefix_off = i;
976 in_off = j;
977 } else {
978 i++;
979 j++;
983 if (
984 /* "prefix" seems like prefix of "in" */
985 i >= prefix_len &&
987 * but "/foo" is not a prefix of "/foobar"
988 * (i.e. prefix not end with '/')
990 prefix_off < prefix_len) {
991 if (j >= in_len) {
992 /* in="/a/b", prefix="/a/b" */
993 in_off = in_len;
994 } else if (is_dir_sep(in[j])) {
995 /* in="/a/b/c", prefix="/a/b" */
996 while (is_dir_sep(in[j]))
997 j++;
998 in_off = j;
999 } else {
1000 /* in="/a/bbb/c", prefix="/a/b" */
1001 i = prefix_off;
1003 } else if (
1004 /* "in" is short than "prefix" */
1005 j >= in_len &&
1006 /* "in" not end with '/' */
1007 in_off < in_len) {
1008 if (is_dir_sep(prefix[i])) {
1009 /* in="/a/b", prefix="/a/b/c/" */
1010 while (is_dir_sep(prefix[i]))
1011 i++;
1012 in_off = in_len;
1015 in += in_off;
1016 in_len -= in_off;
1018 if (i >= prefix_len) {
1019 if (!in_len)
1020 return "./";
1021 else
1022 return in;
1025 strbuf_reset(sb);
1026 strbuf_grow(sb, in_len);
1028 while (i < prefix_len) {
1029 if (is_dir_sep(prefix[i])) {
1030 strbuf_addstr(sb, "../");
1031 while (is_dir_sep(prefix[i]))
1032 i++;
1033 continue;
1035 i++;
1037 if (!is_dir_sep(prefix[prefix_len - 1]))
1038 strbuf_addstr(sb, "../");
1040 strbuf_addstr(sb, in);
1042 return sb->buf;
1046 * A simpler implementation of relative_path
1048 * Get relative path by removing "prefix" from "in". This function
1049 * first appears in v1.5.6-1-g044bbbc, and makes git_dir shorter
1050 * to increase performance when traversing the path to work_tree.
1052 const char *remove_leading_path(const char *in, const char *prefix)
1054 static struct strbuf buf = STRBUF_INIT;
1055 int i = 0, j = 0;
1057 if (!prefix || !prefix[0])
1058 return in;
1059 while (prefix[i]) {
1060 if (is_dir_sep(prefix[i])) {
1061 if (!is_dir_sep(in[j]))
1062 return in;
1063 while (is_dir_sep(prefix[i]))
1064 i++;
1065 while (is_dir_sep(in[j]))
1066 j++;
1067 continue;
1068 } else if (in[j] != prefix[i]) {
1069 return in;
1071 i++;
1072 j++;
1074 if (
1075 /* "/foo" is a prefix of "/foo" */
1076 in[j] &&
1077 /* "/foo" is not a prefix of "/foobar" */
1078 !is_dir_sep(prefix[i-1]) && !is_dir_sep(in[j])
1080 return in;
1081 while (is_dir_sep(in[j]))
1082 j++;
1084 strbuf_reset(&buf);
1085 if (!in[j])
1086 strbuf_addstr(&buf, ".");
1087 else
1088 strbuf_addstr(&buf, in + j);
1089 return buf.buf;
1093 * It is okay if dst == src, but they should not overlap otherwise.
1094 * The "dst" buffer must be at least as long as "src"; normalizing may shrink
1095 * the size of the path, but will never grow it.
1097 * Performs the following normalizations on src, storing the result in dst:
1098 * - Ensures that components are separated by '/' (Windows only)
1099 * - Squashes sequences of '/' except "//server/share" on Windows
1100 * - Removes "." components.
1101 * - Removes ".." components, and the components the precede them.
1102 * Returns failure (non-zero) if a ".." component appears as first path
1103 * component anytime during the normalization. Otherwise, returns success (0).
1105 * Note that this function is purely textual. It does not follow symlinks,
1106 * verify the existence of the path, or make any system calls.
1108 * prefix_len != NULL is for a specific case of prefix_pathspec():
1109 * assume that src == dst and src[0..prefix_len-1] is already
1110 * normalized, any time "../" eats up to the prefix_len part,
1111 * prefix_len is reduced. In the end prefix_len is the remaining
1112 * prefix that has not been overridden by user pathspec.
1114 * NEEDSWORK: This function doesn't perform normalization w.r.t. trailing '/'.
1115 * For everything but the root folder itself, the normalized path should not
1116 * end with a '/', then the callers need to be fixed up accordingly.
1119 int normalize_path_copy_len(char *dst, const char *src, int *prefix_len)
1121 char *dst0;
1122 const char *end;
1125 * Copy initial part of absolute path: "/", "C:/", "//server/share/".
1127 end = src + offset_1st_component(src);
1128 while (src < end) {
1129 char c = *src++;
1130 if (is_dir_sep(c))
1131 c = '/';
1132 *dst++ = c;
1134 dst0 = dst;
1136 while (is_dir_sep(*src))
1137 src++;
1139 for (;;) {
1140 char c = *src;
1143 * A path component that begins with . could be
1144 * special:
1145 * (1) "." and ends -- ignore and terminate.
1146 * (2) "./" -- ignore them, eat slash and continue.
1147 * (3) ".." and ends -- strip one and terminate.
1148 * (4) "../" -- strip one, eat slash and continue.
1150 if (c == '.') {
1151 if (!src[1]) {
1152 /* (1) */
1153 src++;
1154 } else if (is_dir_sep(src[1])) {
1155 /* (2) */
1156 src += 2;
1157 while (is_dir_sep(*src))
1158 src++;
1159 continue;
1160 } else if (src[1] == '.') {
1161 if (!src[2]) {
1162 /* (3) */
1163 src += 2;
1164 goto up_one;
1165 } else if (is_dir_sep(src[2])) {
1166 /* (4) */
1167 src += 3;
1168 while (is_dir_sep(*src))
1169 src++;
1170 goto up_one;
1175 /* copy up to the next '/', and eat all '/' */
1176 while ((c = *src++) != '\0' && !is_dir_sep(c))
1177 *dst++ = c;
1178 if (is_dir_sep(c)) {
1179 *dst++ = '/';
1180 while (is_dir_sep(c))
1181 c = *src++;
1182 src--;
1183 } else if (!c)
1184 break;
1185 continue;
1187 up_one:
1189 * dst0..dst is prefix portion, and dst[-1] is '/';
1190 * go up one level.
1192 dst--; /* go to trailing '/' */
1193 if (dst <= dst0)
1194 return -1;
1195 /* Windows: dst[-1] cannot be backslash anymore */
1196 while (dst0 < dst && dst[-1] != '/')
1197 dst--;
1198 if (prefix_len && *prefix_len > dst - dst0)
1199 *prefix_len = dst - dst0;
1201 *dst = '\0';
1202 return 0;
1205 int normalize_path_copy(char *dst, const char *src)
1207 return normalize_path_copy_len(dst, src, NULL);
1211 * path = Canonical absolute path
1212 * prefixes = string_list containing normalized, absolute paths without
1213 * trailing slashes (except for the root directory, which is denoted by "/").
1215 * Determines, for each path in prefixes, whether the "prefix"
1216 * is an ancestor directory of path. Returns the length of the longest
1217 * ancestor directory, excluding any trailing slashes, or -1 if no prefix
1218 * is an ancestor. (Note that this means 0 is returned if prefixes is
1219 * ["/"].) "/foo" is not considered an ancestor of "/foobar". Directories
1220 * are not considered to be their own ancestors. path must be in a
1221 * canonical form: empty components, or "." or ".." components are not
1222 * allowed.
1224 int longest_ancestor_length(const char *path, struct string_list *prefixes)
1226 int i, max_len = -1;
1228 if (!strcmp(path, "/"))
1229 return -1;
1231 for (i = 0; i < prefixes->nr; i++) {
1232 const char *ceil = prefixes->items[i].string;
1233 int len = strlen(ceil);
1236 * For root directories (`/`, `C:/`, `//server/share/`)
1237 * adjust the length to exclude the trailing slash.
1239 if (len > 0 && ceil[len - 1] == '/')
1240 len--;
1242 if (strncmp(path, ceil, len) ||
1243 path[len] != '/' || !path[len + 1])
1244 continue; /* no match */
1246 if (len > max_len)
1247 max_len = len;
1250 return max_len;
1253 /* strip arbitrary amount of directory separators at end of path */
1254 static inline int chomp_trailing_dir_sep(const char *path, int len)
1256 while (len && is_dir_sep(path[len - 1]))
1257 len--;
1258 return len;
1262 * If path ends with suffix (complete path components), returns the offset of
1263 * the last character in the path before the suffix (sans trailing directory
1264 * separators), and -1 otherwise.
1266 static ssize_t stripped_path_suffix_offset(const char *path, const char *suffix)
1268 int path_len = strlen(path), suffix_len = strlen(suffix);
1270 while (suffix_len) {
1271 if (!path_len)
1272 return -1;
1274 if (is_dir_sep(path[path_len - 1])) {
1275 if (!is_dir_sep(suffix[suffix_len - 1]))
1276 return -1;
1277 path_len = chomp_trailing_dir_sep(path, path_len);
1278 suffix_len = chomp_trailing_dir_sep(suffix, suffix_len);
1280 else if (path[--path_len] != suffix[--suffix_len])
1281 return -1;
1284 if (path_len && !is_dir_sep(path[path_len - 1]))
1285 return -1;
1286 return chomp_trailing_dir_sep(path, path_len);
1290 * Returns true if the path ends with components, considering only complete path
1291 * components, and false otherwise.
1293 int ends_with_path_components(const char *path, const char *components)
1295 return stripped_path_suffix_offset(path, components) != -1;
1299 * If path ends with suffix (complete path components), returns the
1300 * part before suffix (sans trailing directory separators).
1301 * Otherwise returns NULL.
1303 char *strip_path_suffix(const char *path, const char *suffix)
1305 ssize_t offset = stripped_path_suffix_offset(path, suffix);
1307 return offset == -1 ? NULL : xstrndup(path, offset);
1310 int daemon_avoid_alias(const char *p)
1312 int sl, ndot;
1315 * This resurrects the belts and suspenders paranoia check by HPA
1316 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
1317 * does not do getcwd() based path canonicalization.
1319 * sl becomes true immediately after seeing '/' and continues to
1320 * be true as long as dots continue after that without intervening
1321 * non-dot character.
1323 if (!p || (*p != '/' && *p != '~'))
1324 return -1;
1325 sl = 1; ndot = 0;
1326 p++;
1328 while (1) {
1329 char ch = *p++;
1330 if (sl) {
1331 if (ch == '.')
1332 ndot++;
1333 else if (ch == '/') {
1334 if (ndot < 3)
1335 /* reject //, /./ and /../ */
1336 return -1;
1337 ndot = 0;
1339 else if (ch == 0) {
1340 if (0 < ndot && ndot < 3)
1341 /* reject /.$ and /..$ */
1342 return -1;
1343 return 0;
1345 else
1346 sl = ndot = 0;
1348 else if (ch == 0)
1349 return 0;
1350 else if (ch == '/') {
1351 sl = 1;
1352 ndot = 0;
1358 * On NTFS, we need to be careful to disallow certain synonyms of the `.git/`
1359 * directory:
1361 * - For historical reasons, file names that end in spaces or periods are
1362 * automatically trimmed. Therefore, `.git . . ./` is a valid way to refer
1363 * to `.git/`.
1365 * - For other historical reasons, file names that do not conform to the 8.3
1366 * format (up to eight characters for the basename, three for the file
1367 * extension, certain characters not allowed such as `+`, etc) are associated
1368 * with a so-called "short name", at least on the `C:` drive by default.
1369 * Which means that `git~1/` is a valid way to refer to `.git/`.
1371 * Note: Technically, `.git/` could receive the short name `git~2` if the
1372 * short name `git~1` were already used. In Git, however, we guarantee that
1373 * `.git` is the first item in a directory, therefore it will be associated
1374 * with the short name `git~1` (unless short names are disabled).
1376 * - For yet other historical reasons, NTFS supports so-called "Alternate Data
1377 * Streams", i.e. metadata associated with a given file, referred to via
1378 * `<filename>:<stream-name>:<stream-type>`. There exists a default stream
1379 * type for directories, allowing `.git/` to be accessed via
1380 * `.git::$INDEX_ALLOCATION/`.
1382 * When this function returns 1, it indicates that the specified file/directory
1383 * name refers to a `.git` file or directory, or to any of these synonyms, and
1384 * Git should therefore not track it.
1386 * For performance reasons, _all_ Alternate Data Streams of `.git/` are
1387 * forbidden, not just `::$INDEX_ALLOCATION`.
1389 * This function is intended to be used by `git fsck` even on platforms where
1390 * the backslash is a regular filename character, therefore it needs to handle
1391 * backlash characters in the provided `name` specially: they are interpreted
1392 * as directory separators.
1394 int is_ntfs_dotgit(const char *name)
1396 char c;
1399 * Note that when we don't find `.git` or `git~1` we end up with `name`
1400 * advanced partway through the string. That's okay, though, as we
1401 * return immediately in those cases, without looking at `name` any
1402 * further.
1404 c = *(name++);
1405 if (c == '.') {
1406 /* .git */
1407 if (((c = *(name++)) != 'g' && c != 'G') ||
1408 ((c = *(name++)) != 'i' && c != 'I') ||
1409 ((c = *(name++)) != 't' && c != 'T'))
1410 return 0;
1411 } else if (c == 'g' || c == 'G') {
1412 /* git ~1 */
1413 if (((c = *(name++)) != 'i' && c != 'I') ||
1414 ((c = *(name++)) != 't' && c != 'T') ||
1415 *(name++) != '~' ||
1416 *(name++) != '1')
1417 return 0;
1418 } else
1419 return 0;
1421 for (;;) {
1422 c = *(name++);
1423 if (!c || is_xplatform_dir_sep(c) || c == ':')
1424 return 1;
1425 if (c != '.' && c != ' ')
1426 return 0;
1430 static int is_ntfs_dot_generic(const char *name,
1431 const char *dotgit_name,
1432 size_t len,
1433 const char *dotgit_ntfs_shortname_prefix)
1435 int saw_tilde;
1436 size_t i;
1438 if ((name[0] == '.' && !strncasecmp(name + 1, dotgit_name, len))) {
1439 i = len + 1;
1440 only_spaces_and_periods:
1441 for (;;) {
1442 char c = name[i++];
1443 if (!c || c == ':')
1444 return 1;
1445 if (c != ' ' && c != '.')
1446 return 0;
1451 * Is it a regular NTFS short name, i.e. shortened to 6 characters,
1452 * followed by ~1, ... ~4?
1454 if (!strncasecmp(name, dotgit_name, 6) && name[6] == '~' &&
1455 name[7] >= '1' && name[7] <= '4') {
1456 i = 8;
1457 goto only_spaces_and_periods;
1461 * Is it a fall-back NTFS short name (for details, see
1462 * https://en.wikipedia.org/wiki/8.3_filename?
1464 for (i = 0, saw_tilde = 0; i < 8; i++)
1465 if (name[i] == '\0')
1466 return 0;
1467 else if (saw_tilde) {
1468 if (name[i] < '0' || name[i] > '9')
1469 return 0;
1470 } else if (name[i] == '~') {
1471 if (name[++i] < '1' || name[i] > '9')
1472 return 0;
1473 saw_tilde = 1;
1474 } else if (i >= 6)
1475 return 0;
1476 else if (name[i] & 0x80) {
1478 * We know our needles contain only ASCII, so we clamp
1479 * here to make the results of tolower() sane.
1481 return 0;
1482 } else if (tolower(name[i]) != dotgit_ntfs_shortname_prefix[i])
1483 return 0;
1485 goto only_spaces_and_periods;
1489 * Inline helper to make sure compiler resolves strlen() on literals at
1490 * compile time.
1492 static inline int is_ntfs_dot_str(const char *name, const char *dotgit_name,
1493 const char *dotgit_ntfs_shortname_prefix)
1495 return is_ntfs_dot_generic(name, dotgit_name, strlen(dotgit_name),
1496 dotgit_ntfs_shortname_prefix);
1499 int is_ntfs_dotgitmodules(const char *name)
1501 return is_ntfs_dot_str(name, "gitmodules", "gi7eba");
1504 int is_ntfs_dotgitignore(const char *name)
1506 return is_ntfs_dot_str(name, "gitignore", "gi250a");
1509 int is_ntfs_dotgitattributes(const char *name)
1511 return is_ntfs_dot_str(name, "gitattributes", "gi7d29");
1514 int is_ntfs_dotmailmap(const char *name)
1516 return is_ntfs_dot_str(name, "mailmap", "maba30");
1519 int looks_like_command_line_option(const char *str)
1521 return str && str[0] == '-';
1524 char *xdg_config_home_for(const char *subdir, const char *filename)
1526 const char *home, *config_home;
1528 assert(subdir);
1529 assert(filename);
1530 config_home = getenv("XDG_CONFIG_HOME");
1531 if (config_home && *config_home)
1532 return mkpathdup("%s/%s/%s", config_home, subdir, filename);
1534 home = getenv("HOME");
1535 if (home)
1536 return mkpathdup("%s/.config/%s/%s", home, subdir, filename);
1538 return NULL;
1541 char *xdg_config_home(const char *filename)
1543 return xdg_config_home_for("git", filename);
1546 char *xdg_cache_home(const char *filename)
1548 const char *home, *cache_home;
1550 assert(filename);
1551 cache_home = getenv("XDG_CACHE_HOME");
1552 if (cache_home && *cache_home)
1553 return mkpathdup("%s/git/%s", cache_home, filename);
1555 home = getenv("HOME");
1556 if (home)
1557 return mkpathdup("%s/.cache/git/%s", home, filename);
1558 return NULL;
1561 REPO_GIT_PATH_FUNC(squash_msg, "SQUASH_MSG")
1562 REPO_GIT_PATH_FUNC(merge_msg, "MERGE_MSG")
1563 REPO_GIT_PATH_FUNC(merge_rr, "MERGE_RR")
1564 REPO_GIT_PATH_FUNC(merge_mode, "MERGE_MODE")
1565 REPO_GIT_PATH_FUNC(merge_head, "MERGE_HEAD")
1566 REPO_GIT_PATH_FUNC(merge_autostash, "MERGE_AUTOSTASH")
1567 REPO_GIT_PATH_FUNC(auto_merge, "AUTO_MERGE")
1568 REPO_GIT_PATH_FUNC(fetch_head, "FETCH_HEAD")
1569 REPO_GIT_PATH_FUNC(shallow, "shallow")