]> git.ipfire.org Git - thirdparty/git.git/blame - path.c
environment: store worktree in the_repository
[thirdparty/git.git] / path.c
CommitLineData
26c8a533 1/*
3a429d3b 2 * Utilities for paths and pathnames
26c8a533
LT
3 */
4#include "cache.h"
c14c234f 5#include "repository.h"
395de250 6#include "strbuf.h"
a5ccdbe4 7#include "string-list.h"
77a6d840 8#include "dir.h"
2e641d58 9#include "worktree.h"
99b43a61 10#include "submodule-config.h"
26c8a533 11
f66450ae 12static int get_st_mode_bits(const char *path, int *mode)
0117c2f0
TB
13{
14 struct stat st;
15 if (lstat(path, &st) < 0)
16 return -1;
17 *mode = st.st_mode;
18 return 0;
19}
0117c2f0 20
26c8a533
LT
21static char bad_path[] = "/bad-path/";
22
4ef9caf5 23static struct strbuf *get_pathname(void)
e7676d2f 24{
4ef9caf5
NTND
25 static struct strbuf pathname_array[4] = {
26 STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
27 };
e7676d2f 28 static int index;
bb84735c
RS
29 struct strbuf *sb = &pathname_array[index];
30 index = (index + 1) % ARRAY_SIZE(pathname_array);
4ef9caf5
NTND
31 strbuf_reset(sb);
32 return sb;
e7676d2f
LT
33}
34
26c8a533
LT
35static char *cleanup_path(char *path)
36{
37 /* Clean it up */
38 if (!memcmp(path, "./", 2)) {
39 path += 2;
40 while (*path == '/')
41 path++;
42 }
43 return path;
44}
45
4ef9caf5
NTND
46static void strbuf_cleanup_path(struct strbuf *sb)
47{
48 char *path = cleanup_path(sb->buf);
49 if (path > sb->buf)
50 strbuf_remove(sb, 0, path - sb->buf);
51}
52
108bebea
AR
53char *mksnpath(char *buf, size_t n, const char *fmt, ...)
54{
55 va_list args;
56 unsigned len;
57
58 va_start(args, fmt);
59 len = vsnprintf(buf, n, fmt, args);
60 va_end(args);
61 if (len >= n) {
9db56f71 62 strlcpy(buf, bad_path, n);
108bebea
AR
63 return buf;
64 }
65 return cleanup_path(buf);
66}
67
557bd833 68static int dir_prefix(const char *buf, const char *dir)
fe2d7776 69{
557bd833
NTND
70 int len = strlen(dir);
71 return !strncmp(buf, dir, len) &&
72 (is_dir_sep(buf[len]) || buf[len] == '\0');
73}
fe2d7776 74
557bd833
NTND
75/* $buf =~ m|$dir/+$file| but without regex */
76static int is_dir_file(const char *buf, const char *dir, const char *file)
77{
78 int len = strlen(dir);
79 if (strncmp(buf, dir, len) || !is_dir_sep(buf[len]))
80 return 0;
81 while (is_dir_sep(buf[len]))
82 len++;
83 return !strcmp(buf + len, file);
84}
85
86static void replace_dir(struct strbuf *buf, int len, const char *newdir)
87{
88 int newlen = strlen(newdir);
89 int need_sep = (buf->buf[len] && !is_dir_sep(buf->buf[len])) &&
90 !is_dir_sep(newdir[newlen - 1]);
91 if (need_sep)
92 len--; /* keep one char, to be replaced with '/' */
93 strbuf_splice(buf, 0, len, newdir, newlen);
94 if (need_sep)
95 buf->buf[newlen] = '/';
96}
97
0701530c
DT
98struct common_dir {
99 /* Not considered garbage for report_linked_checkout_garbage */
100 unsigned ignore_garbage:1;
101 unsigned is_dir:1;
102 /* Not common even though its parent is */
103 unsigned exclude:1;
104 const char *dirname;
105};
106
107static struct common_dir common_list[] = {
108 { 0, 1, 0, "branches" },
109 { 0, 1, 0, "hooks" },
110 { 0, 1, 0, "info" },
111 { 0, 0, 1, "info/sparse-checkout" },
112 { 1, 1, 0, "logs" },
113 { 1, 1, 1, "logs/HEAD" },
ce414b33 114 { 0, 1, 1, "logs/refs/bisect" },
0701530c
DT
115 { 0, 1, 0, "lost-found" },
116 { 0, 1, 0, "objects" },
117 { 0, 1, 0, "refs" },
ce414b33 118 { 0, 1, 1, "refs/bisect" },
0701530c
DT
119 { 0, 1, 0, "remotes" },
120 { 0, 1, 0, "worktrees" },
121 { 0, 1, 0, "rr-cache" },
122 { 0, 1, 0, "svn" },
123 { 0, 0, 0, "config" },
124 { 1, 0, 0, "gc.pid" },
125 { 0, 0, 0, "packed-refs" },
126 { 0, 0, 0, "shallow" },
127 { 0, 0, 0, NULL }
c7b3a3d2
NTND
128};
129
4e09cf2a
DT
130/*
131 * A compressed trie. A trie node consists of zero or more characters that
132 * are common to all elements with this prefix, optionally followed by some
133 * children. If value is not NULL, the trie node is a terminal node.
134 *
135 * For example, consider the following set of strings:
136 * abc
137 * def
138 * definite
139 * definition
140 *
832c0e5e 141 * The trie would look like:
4e09cf2a
DT
142 * root: len = 0, children a and d non-NULL, value = NULL.
143 * a: len = 2, contents = bc, value = (data for "abc")
144 * d: len = 2, contents = ef, children i non-NULL, value = (data for "def")
145 * i: len = 3, contents = nit, children e and i non-NULL, value = NULL
146 * e: len = 0, children all NULL, value = (data for "definite")
147 * i: len = 2, contents = on, children all NULL,
148 * value = (data for "definition")
149 */
150struct trie {
151 struct trie *children[256];
152 int len;
153 char *contents;
154 void *value;
155};
156
157static struct trie *make_trie_node(const char *key, void *value)
c7b3a3d2 158{
4e09cf2a
DT
159 struct trie *new_node = xcalloc(1, sizeof(*new_node));
160 new_node->len = strlen(key);
161 if (new_node->len) {
162 new_node->contents = xmalloc(new_node->len);
163 memcpy(new_node->contents, key, new_node->len);
164 }
165 new_node->value = value;
166 return new_node;
167}
c7b3a3d2 168
4e09cf2a
DT
169/*
170 * Add a key/value pair to a trie. The key is assumed to be \0-terminated.
171 * If there was an existing value for this key, return it.
172 */
173static void *add_to_trie(struct trie *root, const char *key, void *value)
174{
175 struct trie *child;
176 void *old;
177 int i;
178
179 if (!*key) {
180 /* we have reached the end of the key */
181 old = root->value;
182 root->value = value;
183 return old;
184 }
185
186 for (i = 0; i < root->len; i++) {
187 if (root->contents[i] == key[i])
188 continue;
189
190 /*
191 * Split this node: child will contain this node's
192 * existing children.
193 */
194 child = malloc(sizeof(*child));
195 memcpy(child->children, root->children, sizeof(root->children));
196
197 child->len = root->len - i - 1;
198 if (child->len) {
199 child->contents = xstrndup(root->contents + i + 1,
200 child->len);
c7b3a3d2 201 }
4e09cf2a
DT
202 child->value = root->value;
203 root->value = NULL;
204 root->len = i;
205
206 memset(root->children, 0, sizeof(root->children));
207 root->children[(unsigned char)root->contents[i]] = child;
208
209 /* This is the newly-added child. */
210 root->children[(unsigned char)key[i]] =
211 make_trie_node(key + i + 1, value);
212 return NULL;
213 }
214
215 /* We have matched the entire compressed section */
216 if (key[i]) {
217 child = root->children[(unsigned char)key[root->len]];
218 if (child) {
219 return add_to_trie(child, key + root->len + 1, value);
220 } else {
221 child = make_trie_node(key + root->len + 1, value);
222 root->children[(unsigned char)key[root->len]] = child;
223 return NULL;
c7b3a3d2
NTND
224 }
225 }
4e09cf2a
DT
226
227 old = root->value;
228 root->value = value;
229 return old;
230}
231
232typedef int (*match_fn)(const char *unmatched, void *data, void *baton);
233
234/*
235 * Search a trie for some key. Find the longest /-or-\0-terminated
236 * prefix of the key for which the trie contains a value. Call fn
237 * with the unmatched portion of the key and the found value, and
238 * return its return value. If there is no such prefix, return -1.
239 *
240 * The key is partially normalized: consecutive slashes are skipped.
241 *
242 * For example, consider the trie containing only [refs,
243 * refs/worktree] (both with values).
244 *
245 * | key | unmatched | val from node | return value |
246 * |-----------------|------------|---------------|--------------|
247 * | a | not called | n/a | -1 |
248 * | refs | \0 | refs | as per fn |
249 * | refs/ | / | refs | as per fn |
250 * | refs/w | /w | refs | as per fn |
251 * | refs/worktree | \0 | refs/worktree | as per fn |
252 * | refs/worktree/ | / | refs/worktree | as per fn |
253 * | refs/worktree/a | /a | refs/worktree | as per fn |
254 * |-----------------|------------|---------------|--------------|
255 *
256 */
257static int trie_find(struct trie *root, const char *key, match_fn fn,
258 void *baton)
259{
260 int i;
261 int result;
262 struct trie *child;
263
264 if (!*key) {
265 /* we have reached the end of the key */
266 if (root->value && !root->len)
267 return fn(key, root->value, baton);
268 else
269 return -1;
270 }
271
272 for (i = 0; i < root->len; i++) {
273 /* Partial path normalization: skip consecutive slashes. */
274 if (key[i] == '/' && key[i+1] == '/') {
275 key++;
276 continue;
277 }
278 if (root->contents[i] != key[i])
279 return -1;
280 }
281
282 /* Matched the entire compressed section */
283 key += i;
284 if (!*key)
285 /* End of key */
286 return fn(key, root->value, baton);
287
288 /* Partial path normalization: skip consecutive slashes */
289 while (key[0] == '/' && key[1] == '/')
290 key++;
291
292 child = root->children[(unsigned char)*key];
293 if (child)
294 result = trie_find(child, key + 1, fn, baton);
295 else
296 result = -1;
297
298 if (result >= 0 || (*key != '/' && *key != 0))
299 return result;
300 if (root->value)
301 return fn(key, root->value, baton);
302 else
303 return -1;
304}
305
306static struct trie common_trie;
307static int common_trie_done_setup;
308
309static void init_common_trie(void)
310{
311 struct common_dir *p;
312
313 if (common_trie_done_setup)
314 return;
315
316 for (p = common_list; p->dirname; p++)
317 add_to_trie(&common_trie, p->dirname, p);
318
319 common_trie_done_setup = 1;
320}
321
322/*
323 * Helper function for update_common_dir: returns 1 if the dir
324 * prefix is common.
325 */
326static int check_common(const char *unmatched, void *value, void *baton)
327{
328 struct common_dir *dir = value;
329
330 if (!dir)
331 return 0;
332
333 if (dir->is_dir && (unmatched[0] == 0 || unmatched[0] == '/'))
334 return !dir->exclude;
335
336 if (!dir->is_dir && unmatched[0] == 0)
337 return !dir->exclude;
338
339 return 0;
340}
341
1c630bad
JH
342static void update_common_dir(struct strbuf *buf, int git_dir_len,
343 const char *common_dir)
4e09cf2a
DT
344{
345 char *base = buf->buf + git_dir_len;
346 init_common_trie();
1c630bad
JH
347 if (!common_dir)
348 common_dir = get_git_common_dir();
4e09cf2a 349 if (trie_find(&common_trie, base, check_common, NULL) > 0)
1c630bad 350 replace_dir(buf, git_dir_len, common_dir);
c7b3a3d2
NTND
351}
352
77a6d840
NTND
353void report_linked_checkout_garbage(void)
354{
355 struct strbuf sb = STRBUF_INIT;
0701530c 356 const struct common_dir *p;
77a6d840
NTND
357 int len;
358
c14c234f 359 if (!the_repository->different_commondir)
77a6d840
NTND
360 return;
361 strbuf_addf(&sb, "%s/", get_git_dir());
362 len = sb.len;
0701530c
DT
363 for (p = common_list; p->dirname; p++) {
364 const char *path = p->dirname;
365 if (p->ignore_garbage)
77a6d840
NTND
366 continue;
367 strbuf_setlen(&sb, len);
368 strbuf_addstr(&sb, path);
369 if (file_exists(sb.buf))
0a489b06 370 report_garbage(PACKDIR_FILE_GARBAGE, sb.buf);
77a6d840
NTND
371 }
372 strbuf_release(&sb);
fe2d7776
AR
373}
374
557bd833
NTND
375static void adjust_git_path(struct strbuf *buf, int git_dir_len)
376{
377 const char *base = buf->buf + git_dir_len;
c14c234f 378 if (is_dir_file(base, "info", "grafts"))
557bd833
NTND
379 strbuf_splice(buf, 0, buf->len,
380 get_graft_file(), strlen(get_graft_file()));
c14c234f 381 else if (!strcmp(base, "index"))
557bd833
NTND
382 strbuf_splice(buf, 0, buf->len,
383 get_index_file(), strlen(get_index_file()));
c14c234f 384 else if (dir_prefix(base, "objects"))
557bd833 385 replace_dir(buf, git_dir_len + 7, get_object_directory());
9445b492
JS
386 else if (git_hooks_path && dir_prefix(base, "hooks"))
387 replace_dir(buf, git_dir_len + 5, git_hooks_path);
c14c234f 388 else if (the_repository->different_commondir)
11f9dd71 389 update_common_dir(buf, git_dir_len, NULL);
557bd833
NTND
390}
391
2e641d58
NTND
392static void do_git_path(const struct worktree *wt, struct strbuf *buf,
393 const char *fmt, va_list args)
fe2d7776 394{
557bd833 395 int gitdir_len;
2e641d58 396 strbuf_addstr(buf, get_worktree_git_dir(wt));
4ef9caf5
NTND
397 if (buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
398 strbuf_addch(buf, '/');
557bd833 399 gitdir_len = buf->len;
4ef9caf5 400 strbuf_vaddf(buf, fmt, args);
557bd833 401 adjust_git_path(buf, gitdir_len);
4ef9caf5 402 strbuf_cleanup_path(buf);
fe2d7776
AR
403}
404
bb3788ce
JK
405char *git_path_buf(struct strbuf *buf, const char *fmt, ...)
406{
407 va_list args;
408 strbuf_reset(buf);
409 va_start(args, fmt);
2e641d58 410 do_git_path(NULL, buf, fmt, args);
bb3788ce
JK
411 va_end(args);
412 return buf->buf;
413}
414
1a83c240 415void strbuf_git_path(struct strbuf *sb, const char *fmt, ...)
aba13e7c
AR
416{
417 va_list args;
418 va_start(args, fmt);
2e641d58 419 do_git_path(NULL, sb, fmt, args);
aba13e7c 420 va_end(args);
aba13e7c
AR
421}
422
57a23b77 423const char *git_path(const char *fmt, ...)
aba13e7c 424{
57a23b77 425 struct strbuf *pathname = get_pathname();
aba13e7c
AR
426 va_list args;
427 va_start(args, fmt);
2e641d58 428 do_git_path(NULL, pathname, fmt, args);
aba13e7c 429 va_end(args);
57a23b77 430 return pathname->buf;
aba13e7c
AR
431}
432
aba13e7c 433char *git_pathdup(const char *fmt, ...)
21cf3227 434{
4ef9caf5 435 struct strbuf path = STRBUF_INIT;
21cf3227 436 va_list args;
21cf3227 437 va_start(args, fmt);
2e641d58 438 do_git_path(NULL, &path, fmt, args);
21cf3227 439 va_end(args);
4ef9caf5 440 return strbuf_detach(&path, NULL);
21cf3227
HKNN
441}
442
21cf3227 443char *mkpathdup(const char *fmt, ...)
26c8a533 444{
21cf3227 445 struct strbuf sb = STRBUF_INIT;
26c8a533 446 va_list args;
26c8a533 447 va_start(args, fmt);
21cf3227 448 strbuf_vaddf(&sb, fmt, args);
26c8a533 449 va_end(args);
4ef9caf5
NTND
450 strbuf_cleanup_path(&sb);
451 return strbuf_detach(&sb, NULL);
26c8a533
LT
452}
453
dcf69262 454const char *mkpath(const char *fmt, ...)
26c8a533 455{
26c8a533 456 va_list args;
4ef9caf5 457 struct strbuf *pathname = get_pathname();
26c8a533 458 va_start(args, fmt);
4ef9caf5 459 strbuf_vaddf(pathname, fmt, args);
26c8a533 460 va_end(args);
4ef9caf5 461 return cleanup_path(pathname->buf);
26c8a533 462}
f2db68ed 463
2e641d58
NTND
464const char *worktree_git_path(const struct worktree *wt, const char *fmt, ...)
465{
466 struct strbuf *pathname = get_pathname();
467 va_list args;
468 va_start(args, fmt);
469 do_git_path(wt, pathname, fmt, args);
470 va_end(args);
471 return pathname->buf;
472}
473
99b43a61 474/* Returns 0 on success, negative on failure. */
99b43a61
JK
475static int do_submodule_path(struct strbuf *buf, const char *path,
476 const char *fmt, va_list args)
0bad611b 477{
11f9dd71
MK
478 struct strbuf git_submodule_common_dir = STRBUF_INIT;
479 struct strbuf git_submodule_dir = STRBUF_INIT;
bbbb7de7 480 int ret;
0bad611b 481
bbbb7de7
NTND
482 ret = submodule_to_gitdir(&git_submodule_dir, path);
483 if (ret)
484 goto cleanup;
0bad611b 485
bbbb7de7
NTND
486 strbuf_complete(&git_submodule_dir, '/');
487 strbuf_addbuf(buf, &git_submodule_dir);
4ef9caf5 488 strbuf_vaddf(buf, fmt, args);
11f9dd71
MK
489
490 if (get_common_dir_noenv(&git_submodule_common_dir, git_submodule_dir.buf))
491 update_common_dir(buf, git_submodule_dir.len, git_submodule_common_dir.buf);
492
4ef9caf5 493 strbuf_cleanup_path(buf);
11f9dd71 494
99b43a61 495cleanup:
11f9dd71
MK
496 strbuf_release(&git_submodule_dir);
497 strbuf_release(&git_submodule_common_dir);
bbbb7de7 498 return ret;
f5895fd3
JK
499}
500
f5895fd3
JK
501char *git_pathdup_submodule(const char *path, const char *fmt, ...)
502{
99b43a61 503 int err;
f5895fd3
JK
504 va_list args;
505 struct strbuf buf = STRBUF_INIT;
506 va_start(args, fmt);
99b43a61 507 err = do_submodule_path(&buf, path, fmt, args);
f5895fd3 508 va_end(args);
99b43a61
JK
509 if (err) {
510 strbuf_release(&buf);
511 return NULL;
512 }
f5895fd3
JK
513 return strbuf_detach(&buf, NULL);
514}
515
99b43a61
JK
516int strbuf_git_path_submodule(struct strbuf *buf, const char *path,
517 const char *fmt, ...)
f5895fd3 518{
99b43a61 519 int err;
f5895fd3
JK
520 va_list args;
521 va_start(args, fmt);
99b43a61 522 err = do_submodule_path(buf, path, fmt, args);
f5895fd3 523 va_end(args);
99b43a61
JK
524
525 return err;
f5895fd3
JK
526}
527
15cdfea7
NTND
528static void do_git_common_path(struct strbuf *buf,
529 const char *fmt,
530 va_list args)
531{
532 strbuf_addstr(buf, get_git_common_dir());
533 if (buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
534 strbuf_addch(buf, '/');
535 strbuf_vaddf(buf, fmt, args);
536 strbuf_cleanup_path(buf);
537}
538
539const char *git_common_path(const char *fmt, ...)
540{
541 struct strbuf *pathname = get_pathname();
542 va_list args;
543 va_start(args, fmt);
544 do_git_common_path(pathname, fmt, args);
545 va_end(args);
546 return pathname->buf;
547}
548
549void strbuf_git_common_path(struct strbuf *sb, const char *fmt, ...)
550{
551 va_list args;
552 va_start(args, fmt);
553 do_git_common_path(sb, fmt, args);
554 va_end(args);
555}
556
c847f537 557int validate_headref(const char *path)
0870ca7f
JH
558{
559 struct stat st;
560 char *buf, buffer[256];
c847f537 561 unsigned char sha1[20];
0104ca09
HO
562 int fd;
563 ssize_t len;
0870ca7f
JH
564
565 if (lstat(path, &st) < 0)
566 return -1;
567
568 /* Make sure it is a "refs/.." symlink */
569 if (S_ISLNK(st.st_mode)) {
570 len = readlink(path, buffer, sizeof(buffer)-1);
222b1673 571 if (len >= 5 && !memcmp("refs/", buffer, 5))
0870ca7f
JH
572 return 0;
573 return -1;
574 }
575
576 /*
577 * Anything else, just open it and try to see if it is a symbolic ref.
578 */
579 fd = open(path, O_RDONLY);
580 if (fd < 0)
581 return -1;
93d26e4c 582 len = read_in_full(fd, buffer, sizeof(buffer)-1);
0870ca7f
JH
583 close(fd);
584
585 /*
586 * Is it a symbolic ref?
587 */
c847f537 588 if (len < 4)
0870ca7f 589 return -1;
c847f537
JH
590 if (!memcmp("ref:", buffer, 4)) {
591 buf = buffer + 4;
592 len -= 4;
593 while (len && isspace(*buf))
594 buf++, len--;
222b1673 595 if (len >= 5 && !memcmp("refs/", buf, 5))
c847f537
JH
596 return 0;
597 }
598
599 /*
600 * Is this a detached HEAD?
601 */
602 if (!get_sha1_hex(buffer, sha1))
0870ca7f 603 return 0;
c847f537 604
0870ca7f
JH
605 return -1;
606}
607
395de250 608static struct passwd *getpw_str(const char *username, size_t len)
54f4b874 609{
d79374c7 610 struct passwd *pw;
5c0b13f8 611 char *username_z = xmemdupz(username, len);
395de250
MM
612 pw = getpwnam(username_z);
613 free(username_z);
614 return pw;
615}
54f4b874 616
395de250
MM
617/*
618 * Return a string with ~ and ~user expanded via getpw*. If buf != NULL,
619 * then it is a newly allocated string. Returns NULL on getpw failure or
620 * if path is NULL.
4aad2f16
NTND
621 *
622 * If real_home is true, real_path($HOME) is used in the expansion.
395de250 623 */
4aad2f16 624char *expand_user_path(const char *path, int real_home)
395de250
MM
625{
626 struct strbuf user_path = STRBUF_INIT;
395de250
MM
627 const char *to_copy = path;
628
629 if (path == NULL)
630 goto return_null;
631 if (path[0] == '~') {
53ec551c 632 const char *first_slash = strchrnul(path, '/');
395de250
MM
633 const char *username = path + 1;
634 size_t username_len = first_slash - username;
df2a79f4
MM
635 if (username_len == 0) {
636 const char *home = getenv("HOME");
79bf1490
JN
637 if (!home)
638 goto return_null;
4aad2f16
NTND
639 if (real_home)
640 strbuf_addstr(&user_path, real_path(home));
641 else
642 strbuf_addstr(&user_path, home);
5ca6b7bb
JS
643#ifdef GIT_WINDOWS_NATIVE
644 convert_slashes(user_path.buf);
645#endif
df2a79f4
MM
646 } else {
647 struct passwd *pw = getpw_str(username, username_len);
648 if (!pw)
649 goto return_null;
cedc61a9 650 strbuf_addstr(&user_path, pw->pw_dir);
54f4b874 651 }
395de250 652 to_copy = first_slash;
d79374c7 653 }
cedc61a9 654 strbuf_addstr(&user_path, to_copy);
395de250
MM
655 return strbuf_detach(&user_path, NULL);
656return_null:
657 strbuf_release(&user_path);
658 return NULL;
54f4b874
AE
659}
660
d79374c7
JH
661/*
662 * First, one directory to try is determined by the following algorithm.
663 *
664 * (0) If "strict" is given, the path is used as given and no DWIM is
665 * done. Otherwise:
666 * (1) "~/path" to mean path under the running user's home directory;
667 * (2) "~user/path" to mean path under named user's home directory;
668 * (3) "relative/path" to mean cwd relative directory; or
669 * (4) "/absolute/path" to mean absolute directory.
670 *
c8c3f1d0
PT
671 * Unless "strict" is given, we check "%s/.git", "%s", "%s.git/.git", "%s.git"
672 * in this order. We select the first one that is a valid git repository, and
673 * chdir() to it. If none match, or we fail to chdir, we return NULL.
d79374c7
JH
674 *
675 * If all goes well, we return the directory we used to chdir() (but
676 * before ~user is expanded), avoiding getcwd() resolving symbolic
677 * links. User relative paths are also returned as they are given,
678 * except DWIM suffixing.
679 */
1c64b48e 680const char *enter_repo(const char *path, int strict)
54f4b874 681{
e9ba6781
JK
682 static struct strbuf validated_path = STRBUF_INIT;
683 static struct strbuf used_path = STRBUF_INIT;
d79374c7
JH
684
685 if (!path)
54f4b874
AE
686 return NULL;
687
d79374c7
JH
688 if (!strict) {
689 static const char *suffix[] = {
b3256eb8 690 "/.git", "", ".git/.git", ".git", NULL,
d79374c7 691 };
03106768 692 const char *gitfile;
d79374c7
JH
693 int len = strlen(path);
694 int i;
1c64b48e 695 while ((1 < len) && (path[len-1] == '/'))
d79374c7 696 len--;
1c64b48e 697
e9ba6781
JK
698 /*
699 * We can handle arbitrary-sized buffers, but this remains as a
700 * sanity check on untrusted input.
701 */
d79374c7 702 if (PATH_MAX <= len)
54f4b874 703 return NULL;
1c64b48e 704
e9ba6781
JK
705 strbuf_reset(&used_path);
706 strbuf_reset(&validated_path);
707 strbuf_add(&used_path, path, len);
708 strbuf_add(&validated_path, path, len);
709
710 if (used_path.buf[0] == '~') {
4aad2f16 711 char *newpath = expand_user_path(used_path.buf, 0);
e9ba6781 712 if (!newpath)
d79374c7 713 return NULL;
e9ba6781
JK
714 strbuf_attach(&used_path, newpath, strlen(newpath),
715 strlen(newpath));
d79374c7 716 }
d79374c7 717 for (i = 0; suffix[i]; i++) {
b3256eb8 718 struct stat st;
e9ba6781
JK
719 size_t baselen = used_path.len;
720 strbuf_addstr(&used_path, suffix[i]);
721 if (!stat(used_path.buf, &st) &&
b3256eb8 722 (S_ISREG(st.st_mode) ||
e9ba6781
JK
723 (S_ISDIR(st.st_mode) && is_git_directory(used_path.buf)))) {
724 strbuf_addstr(&validated_path, suffix[i]);
d79374c7
JH
725 break;
726 }
e9ba6781 727 strbuf_setlen(&used_path, baselen);
d79374c7 728 }
03106768
PH
729 if (!suffix[i])
730 return NULL;
78891795 731 gitfile = read_gitfile(used_path.buf);
e9ba6781
JK
732 if (gitfile) {
733 strbuf_reset(&used_path);
734 strbuf_addstr(&used_path, gitfile);
735 }
736 if (chdir(used_path.buf))
0870ca7f 737 return NULL;
e9ba6781 738 path = validated_path.buf;
0870ca7f 739 }
1f5fbe1f
NTND
740 else {
741 const char *gitfile = read_gitfile(path);
742 if (gitfile)
743 path = gitfile;
744 if (chdir(path))
745 return NULL;
746 }
54f4b874 747
0f64cc40 748 if (is_git_directory(".")) {
717c3972 749 set_git_dir(".");
1644162a 750 check_repository_format();
d79374c7 751 return path;
54f4b874
AE
752 }
753
754 return NULL;
755}
138086a7 756
cbe43b84 757static int calc_shared_perm(int mode)
138086a7 758{
cbe43b84 759 int tweak;
138086a7 760
7875acb6
JK
761 if (get_shared_repository() < 0)
762 tweak = -get_shared_repository();
5a688fe4 763 else
7875acb6 764 tweak = get_shared_repository();
5a688fe4
JH
765
766 if (!(mode & S_IWUSR))
767 tweak &= ~0222;
768 if (mode & S_IXUSR)
769 /* Copy read bits to execute bits */
770 tweak |= (tweak & 0444) >> 2;
7875acb6 771 if (get_shared_repository() < 0)
5a688fe4
JH
772 mode = (mode & ~0777) | tweak;
773 else
8c6202d8 774 mode |= tweak;
06cbe855 775
cbe43b84
TB
776 return mode;
777}
778
779
780int adjust_shared_perm(const char *path)
781{
782 int old_mode, new_mode;
783
7875acb6 784 if (!get_shared_repository())
cbe43b84
TB
785 return 0;
786 if (get_st_mode_bits(path, &old_mode) < 0)
787 return -1;
788
789 new_mode = calc_shared_perm(old_mode);
790 if (S_ISDIR(old_mode)) {
06cbe855 791 /* Copy read bits to execute bits */
cbe43b84
TB
792 new_mode |= (new_mode & 0444) >> 2;
793 new_mode |= FORCE_DIR_SET_GID;
06cbe855
HO
794 }
795
cbe43b84
TB
796 if (((old_mode ^ new_mode) & ~S_IFMT) &&
797 chmod(path, (new_mode & ~S_IFMT)) < 0)
138086a7
JH
798 return -2;
799 return 0;
800}
e5392c51 801
eb33876c
DT
802void safe_create_dir(const char *dir, int share)
803{
804 if (mkdir(dir, 0777) < 0) {
805 if (errno != EEXIST) {
806 perror(dir);
807 exit(1);
808 }
809 }
810 else if (share && adjust_shared_perm(dir))
811 die(_("Could not make %s writable by group"), dir);
812}
813
7fbd4221
JX
814static int have_same_root(const char *path1, const char *path2)
815{
816 int is_abs1, is_abs2;
817
818 is_abs1 = is_absolute_path(path1);
819 is_abs2 = is_absolute_path(path2);
820 return (is_abs1 && is_abs2 && tolower(path1[0]) == tolower(path2[0])) ||
821 (!is_abs1 && !is_abs2);
822}
823
e02ca72f
JX
824/*
825 * Give path as relative to prefix.
826 *
827 * The strbuf may or may not be used, so do not assume it contains the
828 * returned path.
829 */
830const char *relative_path(const char *in, const char *prefix,
831 struct strbuf *sb)
044bbbcb 832{
e02ca72f
JX
833 int in_len = in ? strlen(in) : 0;
834 int prefix_len = prefix ? strlen(prefix) : 0;
835 int in_off = 0;
836 int prefix_off = 0;
288123f0
JH
837 int i = 0, j = 0;
838
e02ca72f
JX
839 if (!in_len)
840 return "./";
841 else if (!prefix_len)
842 return in;
843
2f36eed9 844 if (have_same_root(in, prefix))
7fbd4221 845 /* bypass dos_drive, for "c:" is identical to "C:" */
2f36eed9
JS
846 i = j = has_dos_drive_prefix(in);
847 else {
7fbd4221
JX
848 return in;
849 }
850
e02ca72f
JX
851 while (i < prefix_len && j < in_len && prefix[i] == in[j]) {
852 if (is_dir_sep(prefix[i])) {
853 while (is_dir_sep(prefix[i]))
288123f0 854 i++;
e02ca72f
JX
855 while (is_dir_sep(in[j]))
856 j++;
857 prefix_off = i;
858 in_off = j;
859 } else {
860 i++;
861 j++;
862 }
863 }
864
865 if (
866 /* "prefix" seems like prefix of "in" */
867 i >= prefix_len &&
868 /*
869 * but "/foo" is not a prefix of "/foobar"
870 * (i.e. prefix not end with '/')
871 */
872 prefix_off < prefix_len) {
873 if (j >= in_len) {
874 /* in="/a/b", prefix="/a/b" */
875 in_off = in_len;
876 } else if (is_dir_sep(in[j])) {
877 /* in="/a/b/c", prefix="/a/b" */
878 while (is_dir_sep(in[j]))
288123f0 879 j++;
e02ca72f
JX
880 in_off = j;
881 } else {
882 /* in="/a/bbb/c", prefix="/a/b" */
883 i = prefix_off;
884 }
885 } else if (
886 /* "in" is short than "prefix" */
887 j >= in_len &&
888 /* "in" not end with '/' */
889 in_off < in_len) {
890 if (is_dir_sep(prefix[i])) {
891 /* in="/a/b", prefix="/a/b/c/" */
892 while (is_dir_sep(prefix[i]))
893 i++;
894 in_off = in_len;
895 }
896 }
897 in += in_off;
898 in_len -= in_off;
899
900 if (i >= prefix_len) {
901 if (!in_len)
902 return "./";
903 else
904 return in;
905 }
906
907 strbuf_reset(sb);
908 strbuf_grow(sb, in_len);
909
910 while (i < prefix_len) {
911 if (is_dir_sep(prefix[i])) {
912 strbuf_addstr(sb, "../");
913 while (is_dir_sep(prefix[i]))
914 i++;
288123f0 915 continue;
288123f0
JH
916 }
917 i++;
288123f0 918 }
e02ca72f
JX
919 if (!is_dir_sep(prefix[prefix_len - 1]))
920 strbuf_addstr(sb, "../");
921
922 strbuf_addstr(sb, in);
923
924 return sb->buf;
044bbbcb 925}
ae299be0 926
41894ae3
JX
927/*
928 * A simpler implementation of relative_path
929 *
930 * Get relative path by removing "prefix" from "in". This function
931 * first appears in v1.5.6-1-g044bbbc, and makes git_dir shorter
932 * to increase performance when traversing the path to work_tree.
933 */
934const char *remove_leading_path(const char *in, const char *prefix)
935{
46357688 936 static struct strbuf buf = STRBUF_INIT;
41894ae3
JX
937 int i = 0, j = 0;
938
939 if (!prefix || !prefix[0])
940 return in;
941 while (prefix[i]) {
942 if (is_dir_sep(prefix[i])) {
943 if (!is_dir_sep(in[j]))
944 return in;
945 while (is_dir_sep(prefix[i]))
946 i++;
947 while (is_dir_sep(in[j]))
948 j++;
949 continue;
950 } else if (in[j] != prefix[i]) {
951 return in;
952 }
953 i++;
954 j++;
955 }
956 if (
957 /* "/foo" is a prefix of "/foo" */
958 in[j] &&
959 /* "/foo" is not a prefix of "/foobar" */
960 !is_dir_sep(prefix[i-1]) && !is_dir_sep(in[j])
961 )
962 return in;
963 while (is_dir_sep(in[j]))
964 j++;
46357688
JK
965
966 strbuf_reset(&buf);
41894ae3 967 if (!in[j])
46357688 968 strbuf_addstr(&buf, ".");
41894ae3 969 else
46357688
JK
970 strbuf_addstr(&buf, in + j);
971 return buf.buf;
41894ae3
JX
972}
973
ae299be0 974/*
f2a782b8 975 * It is okay if dst == src, but they should not overlap otherwise.
ae299be0 976 *
f2a782b8
JS
977 * Performs the following normalizations on src, storing the result in dst:
978 * - Ensures that components are separated by '/' (Windows only)
7814fbe3 979 * - Squashes sequences of '/' except "//server/share" on Windows
ae299be0
DR
980 * - Removes "." components.
981 * - Removes ".." components, and the components the precede them.
f2a782b8
JS
982 * Returns failure (non-zero) if a ".." component appears as first path
983 * component anytime during the normalization. Otherwise, returns success (0).
ae299be0
DR
984 *
985 * Note that this function is purely textual. It does not follow symlinks,
986 * verify the existence of the path, or make any system calls.
645a29c4
NTND
987 *
988 * prefix_len != NULL is for a specific case of prefix_pathspec():
989 * assume that src == dst and src[0..prefix_len-1] is already
990 * normalized, any time "../" eats up to the prefix_len part,
991 * prefix_len is reduced. In the end prefix_len is the remaining
992 * prefix that has not been overridden by user pathspec.
b2a7123b
RD
993 *
994 * NEEDSWORK: This function doesn't perform normalization w.r.t. trailing '/'.
995 * For everything but the root folder itself, the normalized path should not
996 * end with a '/', then the callers need to be fixed up accordingly.
997 *
ae299be0 998 */
645a29c4 999int normalize_path_copy_len(char *dst, const char *src, int *prefix_len)
ae299be0 1000{
f3cad0ad 1001 char *dst0;
7814fbe3 1002 const char *end;
ae299be0 1003
7814fbe3
JS
1004 /*
1005 * Copy initial part of absolute path: "/", "C:/", "//server/share/".
1006 */
1007 end = src + offset_1st_component(src);
1008 while (src < end) {
1009 char c = *src++;
1010 if (is_dir_sep(c))
1011 c = '/';
1012 *dst++ = c;
1013 }
f3cad0ad 1014 dst0 = dst;
ae299be0 1015
7814fbe3
JS
1016 while (is_dir_sep(*src))
1017 src++;
f3cad0ad
JS
1018
1019 for (;;) {
1020 char c = *src;
1021
1022 /*
1023 * A path component that begins with . could be
1024 * special:
1025 * (1) "." and ends -- ignore and terminate.
1026 * (2) "./" -- ignore them, eat slash and continue.
1027 * (3) ".." and ends -- strip one and terminate.
1028 * (4) "../" -- strip one, eat slash and continue.
1029 */
1030 if (c == '.') {
1031 if (!src[1]) {
1032 /* (1) */
1033 src++;
1034 } else if (is_dir_sep(src[1])) {
1035 /* (2) */
1036 src += 2;
1037 while (is_dir_sep(*src))
1038 src++;
1039 continue;
1040 } else if (src[1] == '.') {
1041 if (!src[2]) {
1042 /* (3) */
1043 src += 2;
1044 goto up_one;
1045 } else if (is_dir_sep(src[2])) {
1046 /* (4) */
1047 src += 3;
1048 while (is_dir_sep(*src))
1049 src++;
1050 goto up_one;
1051 }
1052 }
1053 }
ae299be0 1054
f3cad0ad
JS
1055 /* copy up to the next '/', and eat all '/' */
1056 while ((c = *src++) != '\0' && !is_dir_sep(c))
1057 *dst++ = c;
1058 if (is_dir_sep(c)) {
1059 *dst++ = '/';
1060 while (is_dir_sep(c))
1061 c = *src++;
1062 src--;
1063 } else if (!c)
1064 break;
1065 continue;
1066
1067 up_one:
1068 /*
1069 * dst0..dst is prefix portion, and dst[-1] is '/';
1070 * go up one level.
1071 */
f42302b4
JS
1072 dst--; /* go to trailing '/' */
1073 if (dst <= dst0)
f3cad0ad 1074 return -1;
f42302b4
JS
1075 /* Windows: dst[-1] cannot be backslash anymore */
1076 while (dst0 < dst && dst[-1] != '/')
1077 dst--;
645a29c4
NTND
1078 if (prefix_len && *prefix_len > dst - dst0)
1079 *prefix_len = dst - dst0;
f3cad0ad 1080 }
ae299be0 1081 *dst = '\0';
f3cad0ad 1082 return 0;
ae299be0 1083}
0454dd93 1084
645a29c4
NTND
1085int normalize_path_copy(char *dst, const char *src)
1086{
1087 return normalize_path_copy_len(dst, src, NULL);
1088}
1089
0454dd93
DR
1090/*
1091 * path = Canonical absolute path
9e2326c7
MH
1092 * prefixes = string_list containing normalized, absolute paths without
1093 * trailing slashes (except for the root directory, which is denoted by "/").
0454dd93 1094 *
9e2326c7 1095 * Determines, for each path in prefixes, whether the "prefix"
0454dd93
DR
1096 * is an ancestor directory of path. Returns the length of the longest
1097 * ancestor directory, excluding any trailing slashes, or -1 if no prefix
31171d9e
MH
1098 * is an ancestor. (Note that this means 0 is returned if prefixes is
1099 * ["/"].) "/foo" is not considered an ancestor of "/foobar". Directories
0454dd93
DR
1100 * are not considered to be their own ancestors. path must be in a
1101 * canonical form: empty components, or "." or ".." components are not
9e2326c7 1102 * allowed.
0454dd93 1103 */
31171d9e 1104int longest_ancestor_length(const char *path, struct string_list *prefixes)
0454dd93 1105{
a5ccdbe4 1106 int i, max_len = -1;
0454dd93 1107
31171d9e 1108 if (!strcmp(path, "/"))
0454dd93
DR
1109 return -1;
1110
31171d9e
MH
1111 for (i = 0; i < prefixes->nr; i++) {
1112 const char *ceil = prefixes->items[i].string;
a5ccdbe4
MH
1113 int len = strlen(ceil);
1114
9e2326c7
MH
1115 if (len == 1 && ceil[0] == '/')
1116 len = 0; /* root matches anything, with length 0 */
1117 else if (!strncmp(path, ceil, len) && path[len] == '/')
1118 ; /* match of length len */
1119 else
1120 continue; /* no match */
0454dd93 1121
9e2326c7 1122 if (len > max_len)
0454dd93 1123 max_len = len;
0454dd93
DR
1124 }
1125
1126 return max_len;
1127}
4fcc86b0
JS
1128
1129/* strip arbitrary amount of directory separators at end of path */
1130static inline int chomp_trailing_dir_sep(const char *path, int len)
1131{
1132 while (len && is_dir_sep(path[len - 1]))
1133 len--;
1134 return len;
1135}
1136
1137/*
1138 * If path ends with suffix (complete path components), returns the
1139 * part before suffix (sans trailing directory separators).
1140 * Otherwise returns NULL.
1141 */
1142char *strip_path_suffix(const char *path, const char *suffix)
1143{
1144 int path_len = strlen(path), suffix_len = strlen(suffix);
1145
1146 while (suffix_len) {
1147 if (!path_len)
1148 return NULL;
1149
1150 if (is_dir_sep(path[path_len - 1])) {
1151 if (!is_dir_sep(suffix[suffix_len - 1]))
1152 return NULL;
1153 path_len = chomp_trailing_dir_sep(path, path_len);
1154 suffix_len = chomp_trailing_dir_sep(suffix, suffix_len);
1155 }
1156 else if (path[--path_len] != suffix[--suffix_len])
1157 return NULL;
1158 }
1159
1160 if (path_len && !is_dir_sep(path[path_len - 1]))
1161 return NULL;
1162 return xstrndup(path, chomp_trailing_dir_sep(path, path_len));
1163}
34b6cb8b
SP
1164
1165int daemon_avoid_alias(const char *p)
1166{
1167 int sl, ndot;
1168
1169 /*
1170 * This resurrects the belts and suspenders paranoia check by HPA
1171 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
9517e6b8 1172 * does not do getcwd() based path canonicalization.
34b6cb8b
SP
1173 *
1174 * sl becomes true immediately after seeing '/' and continues to
1175 * be true as long as dots continue after that without intervening
1176 * non-dot character.
1177 */
1178 if (!p || (*p != '/' && *p != '~'))
1179 return -1;
1180 sl = 1; ndot = 0;
1181 p++;
1182
1183 while (1) {
1184 char ch = *p++;
1185 if (sl) {
1186 if (ch == '.')
1187 ndot++;
1188 else if (ch == '/') {
1189 if (ndot < 3)
1190 /* reject //, /./ and /../ */
1191 return -1;
1192 ndot = 0;
1193 }
1194 else if (ch == 0) {
1195 if (0 < ndot && ndot < 3)
1196 /* reject /.$ and /..$ */
1197 return -1;
1198 return 0;
1199 }
1200 else
1201 sl = ndot = 0;
1202 }
1203 else if (ch == 0)
1204 return 0;
1205 else if (ch == '/') {
1206 sl = 1;
1207 ndot = 0;
1208 }
1209 }
1210}
4bb43de2 1211
1d1d69bc
JS
1212static int only_spaces_and_periods(const char *path, size_t len, size_t skip)
1213{
1214 if (len < skip)
1215 return 0;
1216 len -= skip;
1217 path += skip;
1218 while (len-- > 0) {
1219 char c = *(path++);
1220 if (c != ' ' && c != '.')
1221 return 0;
1222 }
1223 return 1;
1224}
1225
1226int is_ntfs_dotgit(const char *name)
1227{
1228 int len;
1229
1230 for (len = 0; ; len++)
1231 if (!name[len] || name[len] == '\\' || is_dir_sep(name[len])) {
1232 if (only_spaces_and_periods(name, len, 4) &&
1233 !strncasecmp(name, ".git", 4))
1234 return 1;
1235 if (only_spaces_and_periods(name, len, 5) &&
1236 !strncasecmp(name, "git~1", 5))
1237 return 1;
1238 if (name[len] != '\\')
1239 return 0;
1240 name += len + 1;
1241 len = -1;
1242 }
1243}
ea19289b
PT
1244
1245char *xdg_config_home(const char *filename)
1246{
1247 const char *home, *config_home;
1248
1249 assert(filename);
1250 config_home = getenv("XDG_CONFIG_HOME");
1251 if (config_home && *config_home)
1252 return mkpathdup("%s/git/%s", config_home, filename);
1253
1254 home = getenv("HOME");
1255 if (home)
1256 return mkpathdup("%s/.config/git/%s", home, filename);
1257 return NULL;
1258}
f932729c 1259
e7f136bf
DL
1260char *xdg_cache_home(const char *filename)
1261{
1262 const char *home, *cache_home;
1263
1264 assert(filename);
1265 cache_home = getenv("XDG_CACHE_HOME");
1266 if (cache_home && *cache_home)
1267 return mkpathdup("%s/git/%s", cache_home, filename);
1268
1269 home = getenv("HOME");
1270 if (home)
1271 return mkpathdup("%s/.cache/git/%s", home, filename);
1272 return NULL;
1273}
1274
f932729c
JK
1275GIT_PATH_FUNC(git_path_cherry_pick_head, "CHERRY_PICK_HEAD")
1276GIT_PATH_FUNC(git_path_revert_head, "REVERT_HEAD")
1277GIT_PATH_FUNC(git_path_squash_msg, "SQUASH_MSG")
1278GIT_PATH_FUNC(git_path_merge_msg, "MERGE_MSG")
1279GIT_PATH_FUNC(git_path_merge_rr, "MERGE_RR")
1280GIT_PATH_FUNC(git_path_merge_mode, "MERGE_MODE")
1281GIT_PATH_FUNC(git_path_merge_head, "MERGE_HEAD")
1282GIT_PATH_FUNC(git_path_fetch_head, "FETCH_HEAD")
1283GIT_PATH_FUNC(git_path_shallow, "shallow")