]> git.ipfire.org Git - thirdparty/git.git/blob - path.c
path.c: mark 'logs/HEAD' in 'common_list' as file
[thirdparty/git.git] / path.c
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
15 static int get_st_mode_bits(const char *path, int *mode)
16 {
17 struct stat st;
18 if (lstat(path, &st) < 0)
19 return -1;
20 *mode = st.st_mode;
21 return 0;
22 }
23
24 static char bad_path[] = "/bad-path/";
25
26 static struct strbuf *get_pathname(void)
27 {
28 static struct strbuf pathname_array[4] = {
29 STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
30 };
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;
36 }
37
38 static const char *cleanup_path(const char *path)
39 {
40 /* Clean it up */
41 if (skip_prefix(path, "./", &path)) {
42 while (*path == '/')
43 path++;
44 }
45 return path;
46 }
47
48 static void strbuf_cleanup_path(struct strbuf *sb)
49 {
50 const char *path = cleanup_path(sb->buf);
51 if (path > sb->buf)
52 strbuf_remove(sb, 0, path - sb->buf);
53 }
54
55 char *mksnpath(char *buf, size_t n, const char *fmt, ...)
56 {
57 va_list args;
58 unsigned len;
59
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;
66 }
67 return (char *)cleanup_path(buf);
68 }
69
70 static int dir_prefix(const char *buf, const char *dir)
71 {
72 int len = strlen(dir);
73 return !strncmp(buf, dir, len) &&
74 (is_dir_sep(buf[len]) || buf[len] == '\0');
75 }
76
77 /* $buf =~ m|$dir/+$file| but without regex */
78 static int is_dir_file(const char *buf, const char *dir, const char *file)
79 {
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);
86 }
87
88 static void replace_dir(struct strbuf *buf, int len, const char *newdir)
89 {
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] = '/';
98 }
99
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;
107 };
108
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, 0, 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 }
135 };
136
137 /*
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.
141 *
142 * For example, consider the following set of strings:
143 * abc
144 * def
145 * definite
146 * definition
147 *
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")
156 */
157 struct trie {
158 struct trie *children[256];
159 int len;
160 char *contents;
161 void *value;
162 };
163
164 static struct trie *make_trie_node(const char *key, void *value)
165 {
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);
171 }
172 new_node->value = value;
173 return new_node;
174 }
175
176 /*
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.
179 */
180 static void *add_to_trie(struct trie *root, const char *key, void *value)
181 {
182 struct trie *child;
183 void *old;
184 int i;
185
186 if (!*key) {
187 /* we have reached the end of the key */
188 old = root->value;
189 root->value = value;
190 return old;
191 }
192
193 for (i = 0; i < root->len; i++) {
194 if (root->contents[i] == key[i])
195 continue;
196
197 /*
198 * Split this node: child will contain this node's
199 * existing children.
200 */
201 child = xmalloc(sizeof(*child));
202 memcpy(child->children, root->children, sizeof(root->children));
203
204 child->len = root->len - i - 1;
205 if (child->len) {
206 child->contents = xstrndup(root->contents + i + 1,
207 child->len);
208 }
209 child->value = root->value;
210 root->value = NULL;
211 root->len = i;
212
213 memset(root->children, 0, sizeof(root->children));
214 root->children[(unsigned char)root->contents[i]] = child;
215
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;
220 }
221
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;
231 }
232 }
233
234 old = root->value;
235 root->value = value;
236 return old;
237 }
238
239 typedef int (*match_fn)(const char *unmatched, void *value, void *baton);
240
241 /*
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. If there is
244 * no such prefix, return -1. Otherwise call fn with the unmatched
245 * portion of the key and the found value. If fn returns 0 or
246 * positive, then return its return value. If fn returns negative,
247 * then call fn with the next-longest /-terminated prefix of the key
248 * (i.e. a parent directory) for which the trie contains a value, and
249 * handle its return value the same way. If there is no shorter
250 * /-terminated prefix with a value left, then return the negative
251 * return value of the most recent fn invocation.
252 *
253 * The key is partially normalized: consecutive slashes are skipped.
254 *
255 * For example, consider the trie containing only [logs,
256 * logs/refs/bisect], both with values, but not logs/refs.
257 *
258 * | key | unmatched | prefix to node | return value |
259 * |--------------------|----------------|------------------|--------------|
260 * | a | not called | n/a | -1 |
261 * | logstore | not called | n/a | -1 |
262 * | logs | \0 | logs | as per fn |
263 * | logs/ | / | logs | as per fn |
264 * | logs/refs | /refs | logs | as per fn |
265 * | logs/refs/ | /refs/ | logs | as per fn |
266 * | logs/refs/b | /refs/b | logs | as per fn |
267 * | logs/refs/bisected | /refs/bisected | logs | as per fn |
268 * | logs/refs/bisect | \0 | logs/refs/bisect | as per fn |
269 * | logs/refs/bisect/ | / | logs/refs/bisect | as per fn |
270 * | logs/refs/bisect/a | /a | logs/refs/bisect | as per fn |
271 * | (If fn in the previous line returns -1, then fn is called once more:) |
272 * | logs/refs/bisect/a | /refs/bisect/a | logs | as per fn |
273 * |--------------------|----------------|------------------|--------------|
274 */
275 static int trie_find(struct trie *root, const char *key, match_fn fn,
276 void *baton)
277 {
278 int i;
279 int result;
280 struct trie *child;
281
282 if (!*key) {
283 /* we have reached the end of the key */
284 if (root->value && !root->len)
285 return fn(key, root->value, baton);
286 else
287 return -1;
288 }
289
290 for (i = 0; i < root->len; i++) {
291 /* Partial path normalization: skip consecutive slashes. */
292 if (key[i] == '/' && key[i+1] == '/') {
293 key++;
294 continue;
295 }
296 if (root->contents[i] != key[i])
297 return -1;
298 }
299
300 /* Matched the entire compressed section */
301 key += i;
302 if (!*key)
303 /* End of key */
304 return fn(key, root->value, baton);
305
306 /* Partial path normalization: skip consecutive slashes */
307 while (key[0] == '/' && key[1] == '/')
308 key++;
309
310 child = root->children[(unsigned char)*key];
311 if (child)
312 result = trie_find(child, key + 1, fn, baton);
313 else
314 result = -1;
315
316 if (result >= 0 || (*key != '/' && *key != 0))
317 return result;
318 if (root->value)
319 return fn(key, root->value, baton);
320 else
321 return -1;
322 }
323
324 static struct trie common_trie;
325 static int common_trie_done_setup;
326
327 static void init_common_trie(void)
328 {
329 struct common_dir *p;
330
331 if (common_trie_done_setup)
332 return;
333
334 for (p = common_list; p->dirname; p++)
335 add_to_trie(&common_trie, p->dirname, p);
336
337 common_trie_done_setup = 1;
338 }
339
340 /*
341 * Helper function for update_common_dir: returns 1 if the dir
342 * prefix is common.
343 */
344 static int check_common(const char *unmatched, void *value, void *baton)
345 {
346 struct common_dir *dir = value;
347
348 if (!dir)
349 return 0;
350
351 if (dir->is_dir && (unmatched[0] == 0 || unmatched[0] == '/'))
352 return !dir->exclude;
353
354 if (!dir->is_dir && unmatched[0] == 0)
355 return !dir->exclude;
356
357 return 0;
358 }
359
360 static void update_common_dir(struct strbuf *buf, int git_dir_len,
361 const char *common_dir)
362 {
363 char *base = buf->buf + git_dir_len;
364 init_common_trie();
365 if (trie_find(&common_trie, base, check_common, NULL) > 0)
366 replace_dir(buf, git_dir_len, common_dir);
367 }
368
369 void report_linked_checkout_garbage(void)
370 {
371 struct strbuf sb = STRBUF_INIT;
372 const struct common_dir *p;
373 int len;
374
375 if (!the_repository->different_commondir)
376 return;
377 strbuf_addf(&sb, "%s/", get_git_dir());
378 len = sb.len;
379 for (p = common_list; p->dirname; p++) {
380 const char *path = p->dirname;
381 if (p->ignore_garbage)
382 continue;
383 strbuf_setlen(&sb, len);
384 strbuf_addstr(&sb, path);
385 if (file_exists(sb.buf))
386 report_garbage(PACKDIR_FILE_GARBAGE, sb.buf);
387 }
388 strbuf_release(&sb);
389 }
390
391 static void adjust_git_path(const struct repository *repo,
392 struct strbuf *buf, int git_dir_len)
393 {
394 const char *base = buf->buf + git_dir_len;
395 if (is_dir_file(base, "info", "grafts"))
396 strbuf_splice(buf, 0, buf->len,
397 repo->graft_file, strlen(repo->graft_file));
398 else if (!strcmp(base, "index"))
399 strbuf_splice(buf, 0, buf->len,
400 repo->index_file, strlen(repo->index_file));
401 else if (dir_prefix(base, "objects"))
402 replace_dir(buf, git_dir_len + 7, repo->objects->odb->path);
403 else if (git_hooks_path && dir_prefix(base, "hooks"))
404 replace_dir(buf, git_dir_len + 5, git_hooks_path);
405 else if (repo->different_commondir)
406 update_common_dir(buf, git_dir_len, repo->commondir);
407 }
408
409 static void strbuf_worktree_gitdir(struct strbuf *buf,
410 const struct repository *repo,
411 const struct worktree *wt)
412 {
413 if (!wt)
414 strbuf_addstr(buf, repo->gitdir);
415 else if (!wt->id)
416 strbuf_addstr(buf, repo->commondir);
417 else
418 strbuf_git_common_path(buf, repo, "worktrees/%s", wt->id);
419 }
420
421 static void do_git_path(const struct repository *repo,
422 const struct worktree *wt, struct strbuf *buf,
423 const char *fmt, va_list args)
424 {
425 int gitdir_len;
426 strbuf_worktree_gitdir(buf, repo, wt);
427 if (buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
428 strbuf_addch(buf, '/');
429 gitdir_len = buf->len;
430 strbuf_vaddf(buf, fmt, args);
431 if (!wt)
432 adjust_git_path(repo, buf, gitdir_len);
433 strbuf_cleanup_path(buf);
434 }
435
436 char *repo_git_path(const struct repository *repo,
437 const char *fmt, ...)
438 {
439 struct strbuf path = STRBUF_INIT;
440 va_list args;
441 va_start(args, fmt);
442 do_git_path(repo, NULL, &path, fmt, args);
443 va_end(args);
444 return strbuf_detach(&path, NULL);
445 }
446
447 void strbuf_repo_git_path(struct strbuf *sb,
448 const struct repository *repo,
449 const char *fmt, ...)
450 {
451 va_list args;
452 va_start(args, fmt);
453 do_git_path(repo, NULL, sb, fmt, args);
454 va_end(args);
455 }
456
457 char *git_path_buf(struct strbuf *buf, const char *fmt, ...)
458 {
459 va_list args;
460 strbuf_reset(buf);
461 va_start(args, fmt);
462 do_git_path(the_repository, NULL, buf, fmt, args);
463 va_end(args);
464 return buf->buf;
465 }
466
467 void strbuf_git_path(struct strbuf *sb, const char *fmt, ...)
468 {
469 va_list args;
470 va_start(args, fmt);
471 do_git_path(the_repository, NULL, sb, fmt, args);
472 va_end(args);
473 }
474
475 const char *git_path(const char *fmt, ...)
476 {
477 struct strbuf *pathname = get_pathname();
478 va_list args;
479 va_start(args, fmt);
480 do_git_path(the_repository, NULL, pathname, fmt, args);
481 va_end(args);
482 return pathname->buf;
483 }
484
485 char *git_pathdup(const char *fmt, ...)
486 {
487 struct strbuf path = STRBUF_INIT;
488 va_list args;
489 va_start(args, fmt);
490 do_git_path(the_repository, NULL, &path, fmt, args);
491 va_end(args);
492 return strbuf_detach(&path, NULL);
493 }
494
495 char *mkpathdup(const char *fmt, ...)
496 {
497 struct strbuf sb = STRBUF_INIT;
498 va_list args;
499 va_start(args, fmt);
500 strbuf_vaddf(&sb, fmt, args);
501 va_end(args);
502 strbuf_cleanup_path(&sb);
503 return strbuf_detach(&sb, NULL);
504 }
505
506 const char *mkpath(const char *fmt, ...)
507 {
508 va_list args;
509 struct strbuf *pathname = get_pathname();
510 va_start(args, fmt);
511 strbuf_vaddf(pathname, fmt, args);
512 va_end(args);
513 return cleanup_path(pathname->buf);
514 }
515
516 const char *worktree_git_path(const struct worktree *wt, const char *fmt, ...)
517 {
518 struct strbuf *pathname = get_pathname();
519 va_list args;
520 va_start(args, fmt);
521 do_git_path(the_repository, wt, pathname, fmt, args);
522 va_end(args);
523 return pathname->buf;
524 }
525
526 static void do_worktree_path(const struct repository *repo,
527 struct strbuf *buf,
528 const char *fmt, va_list args)
529 {
530 strbuf_addstr(buf, repo->worktree);
531 if(buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
532 strbuf_addch(buf, '/');
533
534 strbuf_vaddf(buf, fmt, args);
535 strbuf_cleanup_path(buf);
536 }
537
538 char *repo_worktree_path(const struct repository *repo, const char *fmt, ...)
539 {
540 struct strbuf path = STRBUF_INIT;
541 va_list args;
542
543 if (!repo->worktree)
544 return NULL;
545
546 va_start(args, fmt);
547 do_worktree_path(repo, &path, fmt, args);
548 va_end(args);
549
550 return strbuf_detach(&path, NULL);
551 }
552
553 void strbuf_repo_worktree_path(struct strbuf *sb,
554 const struct repository *repo,
555 const char *fmt, ...)
556 {
557 va_list args;
558
559 if (!repo->worktree)
560 return;
561
562 va_start(args, fmt);
563 do_worktree_path(repo, sb, fmt, args);
564 va_end(args);
565 }
566
567 /* Returns 0 on success, negative on failure. */
568 static int do_submodule_path(struct strbuf *buf, const char *path,
569 const char *fmt, va_list args)
570 {
571 struct strbuf git_submodule_common_dir = STRBUF_INIT;
572 struct strbuf git_submodule_dir = STRBUF_INIT;
573 int ret;
574
575 ret = submodule_to_gitdir(&git_submodule_dir, path);
576 if (ret)
577 goto cleanup;
578
579 strbuf_complete(&git_submodule_dir, '/');
580 strbuf_addbuf(buf, &git_submodule_dir);
581 strbuf_vaddf(buf, fmt, args);
582
583 if (get_common_dir_noenv(&git_submodule_common_dir, git_submodule_dir.buf))
584 update_common_dir(buf, git_submodule_dir.len, git_submodule_common_dir.buf);
585
586 strbuf_cleanup_path(buf);
587
588 cleanup:
589 strbuf_release(&git_submodule_dir);
590 strbuf_release(&git_submodule_common_dir);
591 return ret;
592 }
593
594 char *git_pathdup_submodule(const char *path, const char *fmt, ...)
595 {
596 int err;
597 va_list args;
598 struct strbuf buf = STRBUF_INIT;
599 va_start(args, fmt);
600 err = do_submodule_path(&buf, path, fmt, args);
601 va_end(args);
602 if (err) {
603 strbuf_release(&buf);
604 return NULL;
605 }
606 return strbuf_detach(&buf, NULL);
607 }
608
609 int strbuf_git_path_submodule(struct strbuf *buf, const char *path,
610 const char *fmt, ...)
611 {
612 int err;
613 va_list args;
614 va_start(args, fmt);
615 err = do_submodule_path(buf, path, fmt, args);
616 va_end(args);
617
618 return err;
619 }
620
621 static void do_git_common_path(const struct repository *repo,
622 struct strbuf *buf,
623 const char *fmt,
624 va_list args)
625 {
626 strbuf_addstr(buf, repo->commondir);
627 if (buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
628 strbuf_addch(buf, '/');
629 strbuf_vaddf(buf, fmt, args);
630 strbuf_cleanup_path(buf);
631 }
632
633 const char *git_common_path(const char *fmt, ...)
634 {
635 struct strbuf *pathname = get_pathname();
636 va_list args;
637 va_start(args, fmt);
638 do_git_common_path(the_repository, pathname, fmt, args);
639 va_end(args);
640 return pathname->buf;
641 }
642
643 void strbuf_git_common_path(struct strbuf *sb,
644 const struct repository *repo,
645 const char *fmt, ...)
646 {
647 va_list args;
648 va_start(args, fmt);
649 do_git_common_path(repo, sb, fmt, args);
650 va_end(args);
651 }
652
653 int validate_headref(const char *path)
654 {
655 struct stat st;
656 char buffer[256];
657 const char *refname;
658 struct object_id oid;
659 int fd;
660 ssize_t len;
661
662 if (lstat(path, &st) < 0)
663 return -1;
664
665 /* Make sure it is a "refs/.." symlink */
666 if (S_ISLNK(st.st_mode)) {
667 len = readlink(path, buffer, sizeof(buffer)-1);
668 if (len >= 5 && !memcmp("refs/", buffer, 5))
669 return 0;
670 return -1;
671 }
672
673 /*
674 * Anything else, just open it and try to see if it is a symbolic ref.
675 */
676 fd = open(path, O_RDONLY);
677 if (fd < 0)
678 return -1;
679 len = read_in_full(fd, buffer, sizeof(buffer)-1);
680 close(fd);
681
682 if (len < 0)
683 return -1;
684 buffer[len] = '\0';
685
686 /*
687 * Is it a symbolic ref?
688 */
689 if (skip_prefix(buffer, "ref:", &refname)) {
690 while (isspace(*refname))
691 refname++;
692 if (starts_with(refname, "refs/"))
693 return 0;
694 }
695
696 /*
697 * Is this a detached HEAD?
698 */
699 if (!get_oid_hex(buffer, &oid))
700 return 0;
701
702 return -1;
703 }
704
705 static struct passwd *getpw_str(const char *username, size_t len)
706 {
707 struct passwd *pw;
708 char *username_z = xmemdupz(username, len);
709 pw = getpwnam(username_z);
710 free(username_z);
711 return pw;
712 }
713
714 /*
715 * Return a string with ~ and ~user expanded via getpw*. If buf != NULL,
716 * then it is a newly allocated string. Returns NULL on getpw failure or
717 * if path is NULL.
718 *
719 * If real_home is true, real_path($HOME) is used in the expansion.
720 */
721 char *expand_user_path(const char *path, int real_home)
722 {
723 struct strbuf user_path = STRBUF_INIT;
724 const char *to_copy = path;
725
726 if (path == NULL)
727 goto return_null;
728 if (path[0] == '~') {
729 const char *first_slash = strchrnul(path, '/');
730 const char *username = path + 1;
731 size_t username_len = first_slash - username;
732 if (username_len == 0) {
733 const char *home = getenv("HOME");
734 if (!home)
735 goto return_null;
736 if (real_home)
737 strbuf_add_real_path(&user_path, home);
738 else
739 strbuf_addstr(&user_path, home);
740 #ifdef GIT_WINDOWS_NATIVE
741 convert_slashes(user_path.buf);
742 #endif
743 } else {
744 struct passwd *pw = getpw_str(username, username_len);
745 if (!pw)
746 goto return_null;
747 strbuf_addstr(&user_path, pw->pw_dir);
748 }
749 to_copy = first_slash;
750 }
751 strbuf_addstr(&user_path, to_copy);
752 return strbuf_detach(&user_path, NULL);
753 return_null:
754 strbuf_release(&user_path);
755 return NULL;
756 }
757
758 /*
759 * First, one directory to try is determined by the following algorithm.
760 *
761 * (0) If "strict" is given, the path is used as given and no DWIM is
762 * done. Otherwise:
763 * (1) "~/path" to mean path under the running user's home directory;
764 * (2) "~user/path" to mean path under named user's home directory;
765 * (3) "relative/path" to mean cwd relative directory; or
766 * (4) "/absolute/path" to mean absolute directory.
767 *
768 * Unless "strict" is given, we check "%s/.git", "%s", "%s.git/.git", "%s.git"
769 * in this order. We select the first one that is a valid git repository, and
770 * chdir() to it. If none match, or we fail to chdir, we return NULL.
771 *
772 * If all goes well, we return the directory we used to chdir() (but
773 * before ~user is expanded), avoiding getcwd() resolving symbolic
774 * links. User relative paths are also returned as they are given,
775 * except DWIM suffixing.
776 */
777 const char *enter_repo(const char *path, int strict)
778 {
779 static struct strbuf validated_path = STRBUF_INIT;
780 static struct strbuf used_path = STRBUF_INIT;
781
782 if (!path)
783 return NULL;
784
785 if (!strict) {
786 static const char *suffix[] = {
787 "/.git", "", ".git/.git", ".git", NULL,
788 };
789 const char *gitfile;
790 int len = strlen(path);
791 int i;
792 while ((1 < len) && (path[len-1] == '/'))
793 len--;
794
795 /*
796 * We can handle arbitrary-sized buffers, but this remains as a
797 * sanity check on untrusted input.
798 */
799 if (PATH_MAX <= len)
800 return NULL;
801
802 strbuf_reset(&used_path);
803 strbuf_reset(&validated_path);
804 strbuf_add(&used_path, path, len);
805 strbuf_add(&validated_path, path, len);
806
807 if (used_path.buf[0] == '~') {
808 char *newpath = expand_user_path(used_path.buf, 0);
809 if (!newpath)
810 return NULL;
811 strbuf_attach(&used_path, newpath, strlen(newpath),
812 strlen(newpath));
813 }
814 for (i = 0; suffix[i]; i++) {
815 struct stat st;
816 size_t baselen = used_path.len;
817 strbuf_addstr(&used_path, suffix[i]);
818 if (!stat(used_path.buf, &st) &&
819 (S_ISREG(st.st_mode) ||
820 (S_ISDIR(st.st_mode) && is_git_directory(used_path.buf)))) {
821 strbuf_addstr(&validated_path, suffix[i]);
822 break;
823 }
824 strbuf_setlen(&used_path, baselen);
825 }
826 if (!suffix[i])
827 return NULL;
828 gitfile = read_gitfile(used_path.buf);
829 if (gitfile) {
830 strbuf_reset(&used_path);
831 strbuf_addstr(&used_path, gitfile);
832 }
833 if (chdir(used_path.buf))
834 return NULL;
835 path = validated_path.buf;
836 }
837 else {
838 const char *gitfile = read_gitfile(path);
839 if (gitfile)
840 path = gitfile;
841 if (chdir(path))
842 return NULL;
843 }
844
845 if (is_git_directory(".")) {
846 set_git_dir(".");
847 check_repository_format();
848 return path;
849 }
850
851 return NULL;
852 }
853
854 static int calc_shared_perm(int mode)
855 {
856 int tweak;
857
858 if (get_shared_repository() < 0)
859 tweak = -get_shared_repository();
860 else
861 tweak = get_shared_repository();
862
863 if (!(mode & S_IWUSR))
864 tweak &= ~0222;
865 if (mode & S_IXUSR)
866 /* Copy read bits to execute bits */
867 tweak |= (tweak & 0444) >> 2;
868 if (get_shared_repository() < 0)
869 mode = (mode & ~0777) | tweak;
870 else
871 mode |= tweak;
872
873 return mode;
874 }
875
876
877 int adjust_shared_perm(const char *path)
878 {
879 int old_mode, new_mode;
880
881 if (!get_shared_repository())
882 return 0;
883 if (get_st_mode_bits(path, &old_mode) < 0)
884 return -1;
885
886 new_mode = calc_shared_perm(old_mode);
887 if (S_ISDIR(old_mode)) {
888 /* Copy read bits to execute bits */
889 new_mode |= (new_mode & 0444) >> 2;
890 new_mode |= FORCE_DIR_SET_GID;
891 }
892
893 if (((old_mode ^ new_mode) & ~S_IFMT) &&
894 chmod(path, (new_mode & ~S_IFMT)) < 0)
895 return -2;
896 return 0;
897 }
898
899 void safe_create_dir(const char *dir, int share)
900 {
901 if (mkdir(dir, 0777) < 0) {
902 if (errno != EEXIST) {
903 perror(dir);
904 exit(1);
905 }
906 }
907 else if (share && adjust_shared_perm(dir))
908 die(_("Could not make %s writable by group"), dir);
909 }
910
911 static int have_same_root(const char *path1, const char *path2)
912 {
913 int is_abs1, is_abs2;
914
915 is_abs1 = is_absolute_path(path1);
916 is_abs2 = is_absolute_path(path2);
917 return (is_abs1 && is_abs2 && tolower(path1[0]) == tolower(path2[0])) ||
918 (!is_abs1 && !is_abs2);
919 }
920
921 /*
922 * Give path as relative to prefix.
923 *
924 * The strbuf may or may not be used, so do not assume it contains the
925 * returned path.
926 */
927 const char *relative_path(const char *in, const char *prefix,
928 struct strbuf *sb)
929 {
930 int in_len = in ? strlen(in) : 0;
931 int prefix_len = prefix ? strlen(prefix) : 0;
932 int in_off = 0;
933 int prefix_off = 0;
934 int i = 0, j = 0;
935
936 if (!in_len)
937 return "./";
938 else if (!prefix_len)
939 return in;
940
941 if (have_same_root(in, prefix))
942 /* bypass dos_drive, for "c:" is identical to "C:" */
943 i = j = has_dos_drive_prefix(in);
944 else {
945 return in;
946 }
947
948 while (i < prefix_len && j < in_len && prefix[i] == in[j]) {
949 if (is_dir_sep(prefix[i])) {
950 while (is_dir_sep(prefix[i]))
951 i++;
952 while (is_dir_sep(in[j]))
953 j++;
954 prefix_off = i;
955 in_off = j;
956 } else {
957 i++;
958 j++;
959 }
960 }
961
962 if (
963 /* "prefix" seems like prefix of "in" */
964 i >= prefix_len &&
965 /*
966 * but "/foo" is not a prefix of "/foobar"
967 * (i.e. prefix not end with '/')
968 */
969 prefix_off < prefix_len) {
970 if (j >= in_len) {
971 /* in="/a/b", prefix="/a/b" */
972 in_off = in_len;
973 } else if (is_dir_sep(in[j])) {
974 /* in="/a/b/c", prefix="/a/b" */
975 while (is_dir_sep(in[j]))
976 j++;
977 in_off = j;
978 } else {
979 /* in="/a/bbb/c", prefix="/a/b" */
980 i = prefix_off;
981 }
982 } else if (
983 /* "in" is short than "prefix" */
984 j >= in_len &&
985 /* "in" not end with '/' */
986 in_off < in_len) {
987 if (is_dir_sep(prefix[i])) {
988 /* in="/a/b", prefix="/a/b/c/" */
989 while (is_dir_sep(prefix[i]))
990 i++;
991 in_off = in_len;
992 }
993 }
994 in += in_off;
995 in_len -= in_off;
996
997 if (i >= prefix_len) {
998 if (!in_len)
999 return "./";
1000 else
1001 return in;
1002 }
1003
1004 strbuf_reset(sb);
1005 strbuf_grow(sb, in_len);
1006
1007 while (i < prefix_len) {
1008 if (is_dir_sep(prefix[i])) {
1009 strbuf_addstr(sb, "../");
1010 while (is_dir_sep(prefix[i]))
1011 i++;
1012 continue;
1013 }
1014 i++;
1015 }
1016 if (!is_dir_sep(prefix[prefix_len - 1]))
1017 strbuf_addstr(sb, "../");
1018
1019 strbuf_addstr(sb, in);
1020
1021 return sb->buf;
1022 }
1023
1024 /*
1025 * A simpler implementation of relative_path
1026 *
1027 * Get relative path by removing "prefix" from "in". This function
1028 * first appears in v1.5.6-1-g044bbbc, and makes git_dir shorter
1029 * to increase performance when traversing the path to work_tree.
1030 */
1031 const char *remove_leading_path(const char *in, const char *prefix)
1032 {
1033 static struct strbuf buf = STRBUF_INIT;
1034 int i = 0, j = 0;
1035
1036 if (!prefix || !prefix[0])
1037 return in;
1038 while (prefix[i]) {
1039 if (is_dir_sep(prefix[i])) {
1040 if (!is_dir_sep(in[j]))
1041 return in;
1042 while (is_dir_sep(prefix[i]))
1043 i++;
1044 while (is_dir_sep(in[j]))
1045 j++;
1046 continue;
1047 } else if (in[j] != prefix[i]) {
1048 return in;
1049 }
1050 i++;
1051 j++;
1052 }
1053 if (
1054 /* "/foo" is a prefix of "/foo" */
1055 in[j] &&
1056 /* "/foo" is not a prefix of "/foobar" */
1057 !is_dir_sep(prefix[i-1]) && !is_dir_sep(in[j])
1058 )
1059 return in;
1060 while (is_dir_sep(in[j]))
1061 j++;
1062
1063 strbuf_reset(&buf);
1064 if (!in[j])
1065 strbuf_addstr(&buf, ".");
1066 else
1067 strbuf_addstr(&buf, in + j);
1068 return buf.buf;
1069 }
1070
1071 /*
1072 * It is okay if dst == src, but they should not overlap otherwise.
1073 *
1074 * Performs the following normalizations on src, storing the result in dst:
1075 * - Ensures that components are separated by '/' (Windows only)
1076 * - Squashes sequences of '/' except "//server/share" on Windows
1077 * - Removes "." components.
1078 * - Removes ".." components, and the components the precede them.
1079 * Returns failure (non-zero) if a ".." component appears as first path
1080 * component anytime during the normalization. Otherwise, returns success (0).
1081 *
1082 * Note that this function is purely textual. It does not follow symlinks,
1083 * verify the existence of the path, or make any system calls.
1084 *
1085 * prefix_len != NULL is for a specific case of prefix_pathspec():
1086 * assume that src == dst and src[0..prefix_len-1] is already
1087 * normalized, any time "../" eats up to the prefix_len part,
1088 * prefix_len is reduced. In the end prefix_len is the remaining
1089 * prefix that has not been overridden by user pathspec.
1090 *
1091 * NEEDSWORK: This function doesn't perform normalization w.r.t. trailing '/'.
1092 * For everything but the root folder itself, the normalized path should not
1093 * end with a '/', then the callers need to be fixed up accordingly.
1094 *
1095 */
1096 int normalize_path_copy_len(char *dst, const char *src, int *prefix_len)
1097 {
1098 char *dst0;
1099 const char *end;
1100
1101 /*
1102 * Copy initial part of absolute path: "/", "C:/", "//server/share/".
1103 */
1104 end = src + offset_1st_component(src);
1105 while (src < end) {
1106 char c = *src++;
1107 if (is_dir_sep(c))
1108 c = '/';
1109 *dst++ = c;
1110 }
1111 dst0 = dst;
1112
1113 while (is_dir_sep(*src))
1114 src++;
1115
1116 for (;;) {
1117 char c = *src;
1118
1119 /*
1120 * A path component that begins with . could be
1121 * special:
1122 * (1) "." and ends -- ignore and terminate.
1123 * (2) "./" -- ignore them, eat slash and continue.
1124 * (3) ".." and ends -- strip one and terminate.
1125 * (4) "../" -- strip one, eat slash and continue.
1126 */
1127 if (c == '.') {
1128 if (!src[1]) {
1129 /* (1) */
1130 src++;
1131 } else if (is_dir_sep(src[1])) {
1132 /* (2) */
1133 src += 2;
1134 while (is_dir_sep(*src))
1135 src++;
1136 continue;
1137 } else if (src[1] == '.') {
1138 if (!src[2]) {
1139 /* (3) */
1140 src += 2;
1141 goto up_one;
1142 } else if (is_dir_sep(src[2])) {
1143 /* (4) */
1144 src += 3;
1145 while (is_dir_sep(*src))
1146 src++;
1147 goto up_one;
1148 }
1149 }
1150 }
1151
1152 /* copy up to the next '/', and eat all '/' */
1153 while ((c = *src++) != '\0' && !is_dir_sep(c))
1154 *dst++ = c;
1155 if (is_dir_sep(c)) {
1156 *dst++ = '/';
1157 while (is_dir_sep(c))
1158 c = *src++;
1159 src--;
1160 } else if (!c)
1161 break;
1162 continue;
1163
1164 up_one:
1165 /*
1166 * dst0..dst is prefix portion, and dst[-1] is '/';
1167 * go up one level.
1168 */
1169 dst--; /* go to trailing '/' */
1170 if (dst <= dst0)
1171 return -1;
1172 /* Windows: dst[-1] cannot be backslash anymore */
1173 while (dst0 < dst && dst[-1] != '/')
1174 dst--;
1175 if (prefix_len && *prefix_len > dst - dst0)
1176 *prefix_len = dst - dst0;
1177 }
1178 *dst = '\0';
1179 return 0;
1180 }
1181
1182 int normalize_path_copy(char *dst, const char *src)
1183 {
1184 return normalize_path_copy_len(dst, src, NULL);
1185 }
1186
1187 /*
1188 * path = Canonical absolute path
1189 * prefixes = string_list containing normalized, absolute paths without
1190 * trailing slashes (except for the root directory, which is denoted by "/").
1191 *
1192 * Determines, for each path in prefixes, whether the "prefix"
1193 * is an ancestor directory of path. Returns the length of the longest
1194 * ancestor directory, excluding any trailing slashes, or -1 if no prefix
1195 * is an ancestor. (Note that this means 0 is returned if prefixes is
1196 * ["/"].) "/foo" is not considered an ancestor of "/foobar". Directories
1197 * are not considered to be their own ancestors. path must be in a
1198 * canonical form: empty components, or "." or ".." components are not
1199 * allowed.
1200 */
1201 int longest_ancestor_length(const char *path, struct string_list *prefixes)
1202 {
1203 int i, max_len = -1;
1204
1205 if (!strcmp(path, "/"))
1206 return -1;
1207
1208 for (i = 0; i < prefixes->nr; i++) {
1209 const char *ceil = prefixes->items[i].string;
1210 int len = strlen(ceil);
1211
1212 if (len == 1 && ceil[0] == '/')
1213 len = 0; /* root matches anything, with length 0 */
1214 else if (!strncmp(path, ceil, len) && path[len] == '/')
1215 ; /* match of length len */
1216 else
1217 continue; /* no match */
1218
1219 if (len > max_len)
1220 max_len = len;
1221 }
1222
1223 return max_len;
1224 }
1225
1226 /* strip arbitrary amount of directory separators at end of path */
1227 static inline int chomp_trailing_dir_sep(const char *path, int len)
1228 {
1229 while (len && is_dir_sep(path[len - 1]))
1230 len--;
1231 return len;
1232 }
1233
1234 /*
1235 * If path ends with suffix (complete path components), returns the
1236 * part before suffix (sans trailing directory separators).
1237 * Otherwise returns NULL.
1238 */
1239 char *strip_path_suffix(const char *path, const char *suffix)
1240 {
1241 int path_len = strlen(path), suffix_len = strlen(suffix);
1242
1243 while (suffix_len) {
1244 if (!path_len)
1245 return NULL;
1246
1247 if (is_dir_sep(path[path_len - 1])) {
1248 if (!is_dir_sep(suffix[suffix_len - 1]))
1249 return NULL;
1250 path_len = chomp_trailing_dir_sep(path, path_len);
1251 suffix_len = chomp_trailing_dir_sep(suffix, suffix_len);
1252 }
1253 else if (path[--path_len] != suffix[--suffix_len])
1254 return NULL;
1255 }
1256
1257 if (path_len && !is_dir_sep(path[path_len - 1]))
1258 return NULL;
1259 return xstrndup(path, chomp_trailing_dir_sep(path, path_len));
1260 }
1261
1262 int daemon_avoid_alias(const char *p)
1263 {
1264 int sl, ndot;
1265
1266 /*
1267 * This resurrects the belts and suspenders paranoia check by HPA
1268 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
1269 * does not do getcwd() based path canonicalization.
1270 *
1271 * sl becomes true immediately after seeing '/' and continues to
1272 * be true as long as dots continue after that without intervening
1273 * non-dot character.
1274 */
1275 if (!p || (*p != '/' && *p != '~'))
1276 return -1;
1277 sl = 1; ndot = 0;
1278 p++;
1279
1280 while (1) {
1281 char ch = *p++;
1282 if (sl) {
1283 if (ch == '.')
1284 ndot++;
1285 else if (ch == '/') {
1286 if (ndot < 3)
1287 /* reject //, /./ and /../ */
1288 return -1;
1289 ndot = 0;
1290 }
1291 else if (ch == 0) {
1292 if (0 < ndot && ndot < 3)
1293 /* reject /.$ and /..$ */
1294 return -1;
1295 return 0;
1296 }
1297 else
1298 sl = ndot = 0;
1299 }
1300 else if (ch == 0)
1301 return 0;
1302 else if (ch == '/') {
1303 sl = 1;
1304 ndot = 0;
1305 }
1306 }
1307 }
1308
1309 static int only_spaces_and_periods(const char *path, size_t len, size_t skip)
1310 {
1311 if (len < skip)
1312 return 0;
1313 len -= skip;
1314 path += skip;
1315 while (len-- > 0) {
1316 char c = *(path++);
1317 if (c != ' ' && c != '.')
1318 return 0;
1319 }
1320 return 1;
1321 }
1322
1323 int is_ntfs_dotgit(const char *name)
1324 {
1325 size_t len;
1326
1327 for (len = 0; ; len++)
1328 if (!name[len] || name[len] == '\\' || is_dir_sep(name[len])) {
1329 if (only_spaces_and_periods(name, len, 4) &&
1330 !strncasecmp(name, ".git", 4))
1331 return 1;
1332 if (only_spaces_and_periods(name, len, 5) &&
1333 !strncasecmp(name, "git~1", 5))
1334 return 1;
1335 if (name[len] != '\\')
1336 return 0;
1337 name += len + 1;
1338 len = -1;
1339 }
1340 }
1341
1342 static int is_ntfs_dot_generic(const char *name,
1343 const char *dotgit_name,
1344 size_t len,
1345 const char *dotgit_ntfs_shortname_prefix)
1346 {
1347 int saw_tilde;
1348 size_t i;
1349
1350 if ((name[0] == '.' && !strncasecmp(name + 1, dotgit_name, len))) {
1351 i = len + 1;
1352 only_spaces_and_periods:
1353 for (;;) {
1354 char c = name[i++];
1355 if (!c)
1356 return 1;
1357 if (c != ' ' && c != '.')
1358 return 0;
1359 }
1360 }
1361
1362 /*
1363 * Is it a regular NTFS short name, i.e. shortened to 6 characters,
1364 * followed by ~1, ... ~4?
1365 */
1366 if (!strncasecmp(name, dotgit_name, 6) && name[6] == '~' &&
1367 name[7] >= '1' && name[7] <= '4') {
1368 i = 8;
1369 goto only_spaces_and_periods;
1370 }
1371
1372 /*
1373 * Is it a fall-back NTFS short name (for details, see
1374 * https://en.wikipedia.org/wiki/8.3_filename?
1375 */
1376 for (i = 0, saw_tilde = 0; i < 8; i++)
1377 if (name[i] == '\0')
1378 return 0;
1379 else if (saw_tilde) {
1380 if (name[i] < '0' || name[i] > '9')
1381 return 0;
1382 } else if (name[i] == '~') {
1383 if (name[++i] < '1' || name[i] > '9')
1384 return 0;
1385 saw_tilde = 1;
1386 } else if (i >= 6)
1387 return 0;
1388 else if (name[i] & 0x80) {
1389 /*
1390 * We know our needles contain only ASCII, so we clamp
1391 * here to make the results of tolower() sane.
1392 */
1393 return 0;
1394 } else if (tolower(name[i]) != dotgit_ntfs_shortname_prefix[i])
1395 return 0;
1396
1397 goto only_spaces_and_periods;
1398 }
1399
1400 /*
1401 * Inline helper to make sure compiler resolves strlen() on literals at
1402 * compile time.
1403 */
1404 static inline int is_ntfs_dot_str(const char *name, const char *dotgit_name,
1405 const char *dotgit_ntfs_shortname_prefix)
1406 {
1407 return is_ntfs_dot_generic(name, dotgit_name, strlen(dotgit_name),
1408 dotgit_ntfs_shortname_prefix);
1409 }
1410
1411 int is_ntfs_dotgitmodules(const char *name)
1412 {
1413 return is_ntfs_dot_str(name, "gitmodules", "gi7eba");
1414 }
1415
1416 int is_ntfs_dotgitignore(const char *name)
1417 {
1418 return is_ntfs_dot_str(name, "gitignore", "gi250a");
1419 }
1420
1421 int is_ntfs_dotgitattributes(const char *name)
1422 {
1423 return is_ntfs_dot_str(name, "gitattributes", "gi7d29");
1424 }
1425
1426 int looks_like_command_line_option(const char *str)
1427 {
1428 return str && str[0] == '-';
1429 }
1430
1431 char *xdg_config_home(const char *filename)
1432 {
1433 const char *home, *config_home;
1434
1435 assert(filename);
1436 config_home = getenv("XDG_CONFIG_HOME");
1437 if (config_home && *config_home)
1438 return mkpathdup("%s/git/%s", config_home, filename);
1439
1440 home = getenv("HOME");
1441 if (home)
1442 return mkpathdup("%s/.config/git/%s", home, filename);
1443 return NULL;
1444 }
1445
1446 char *xdg_cache_home(const char *filename)
1447 {
1448 const char *home, *cache_home;
1449
1450 assert(filename);
1451 cache_home = getenv("XDG_CACHE_HOME");
1452 if (cache_home && *cache_home)
1453 return mkpathdup("%s/git/%s", cache_home, filename);
1454
1455 home = getenv("HOME");
1456 if (home)
1457 return mkpathdup("%s/.cache/git/%s", home, filename);
1458 return NULL;
1459 }
1460
1461 REPO_GIT_PATH_FUNC(cherry_pick_head, "CHERRY_PICK_HEAD")
1462 REPO_GIT_PATH_FUNC(revert_head, "REVERT_HEAD")
1463 REPO_GIT_PATH_FUNC(squash_msg, "SQUASH_MSG")
1464 REPO_GIT_PATH_FUNC(merge_msg, "MERGE_MSG")
1465 REPO_GIT_PATH_FUNC(merge_rr, "MERGE_RR")
1466 REPO_GIT_PATH_FUNC(merge_mode, "MERGE_MODE")
1467 REPO_GIT_PATH_FUNC(merge_head, "MERGE_HEAD")
1468 REPO_GIT_PATH_FUNC(fetch_head, "FETCH_HEAD")
1469 REPO_GIT_PATH_FUNC(shallow, "shallow")