]> git.ipfire.org Git - thirdparty/git.git/blame - path.c
treewide: remove unnecessary cache.h inclusion from a few headers
[thirdparty/git.git] / path.c
CommitLineData
26c8a533 1/*
3a429d3b 2 * Utilities for paths and pathnames
26c8a533
LT
3 */
4#include "cache.h"
41771fa4 5#include "hex.h"
c14c234f 6#include "repository.h"
395de250 7#include "strbuf.h"
a5ccdbe4 8#include "string-list.h"
77a6d840 9#include "dir.h"
2e641d58 10#include "worktree.h"
99b43a61 11#include "submodule-config.h"
e7d72d07 12#include "path.h"
0abe14f6 13#include "packfile.h"
90c62155 14#include "object-store.h"
76a53d64 15#include "lockfile.h"
e394a160 16#include "exec-cmd.h"
26c8a533 17
f66450ae 18static int get_st_mode_bits(const char *path, int *mode)
0117c2f0
TB
19{
20 struct stat st;
21 if (lstat(path, &st) < 0)
22 return -1;
23 *mode = st.st_mode;
24 return 0;
25}
0117c2f0 26
26c8a533
LT
27static char bad_path[] = "/bad-path/";
28
4ef9caf5 29static struct strbuf *get_pathname(void)
e7676d2f 30{
4ef9caf5
NTND
31 static struct strbuf pathname_array[4] = {
32 STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
33 };
e7676d2f 34 static int index;
bb84735c
RS
35 struct strbuf *sb = &pathname_array[index];
36 index = (index + 1) % ARRAY_SIZE(pathname_array);
4ef9caf5
NTND
37 strbuf_reset(sb);
38 return sb;
e7676d2f
LT
39}
40
8262715b 41static const char *cleanup_path(const char *path)
26c8a533
LT
42{
43 /* Clean it up */
8262715b 44 if (skip_prefix(path, "./", &path)) {
26c8a533
LT
45 while (*path == '/')
46 path++;
47 }
48 return path;
49}
50
4ef9caf5
NTND
51static void strbuf_cleanup_path(struct strbuf *sb)
52{
8262715b 53 const char *path = cleanup_path(sb->buf);
4ef9caf5
NTND
54 if (path > sb->buf)
55 strbuf_remove(sb, 0, path - sb->buf);
56}
57
108bebea
AR
58char *mksnpath(char *buf, size_t n, const char *fmt, ...)
59{
60 va_list args;
61 unsigned len;
62
63 va_start(args, fmt);
64 len = vsnprintf(buf, n, fmt, args);
65 va_end(args);
66 if (len >= n) {
9db56f71 67 strlcpy(buf, bad_path, n);
108bebea
AR
68 return buf;
69 }
8262715b 70 return (char *)cleanup_path(buf);
108bebea
AR
71}
72
557bd833 73static int dir_prefix(const char *buf, const char *dir)
fe2d7776 74{
557bd833
NTND
75 int len = strlen(dir);
76 return !strncmp(buf, dir, len) &&
77 (is_dir_sep(buf[len]) || buf[len] == '\0');
78}
fe2d7776 79
557bd833
NTND
80/* $buf =~ m|$dir/+$file| but without regex */
81static int is_dir_file(const char *buf, const char *dir, const char *file)
82{
83 int len = strlen(dir);
84 if (strncmp(buf, dir, len) || !is_dir_sep(buf[len]))
85 return 0;
86 while (is_dir_sep(buf[len]))
87 len++;
88 return !strcmp(buf + len, file);
89}
90
91static void replace_dir(struct strbuf *buf, int len, const char *newdir)
92{
93 int newlen = strlen(newdir);
94 int need_sep = (buf->buf[len] && !is_dir_sep(buf->buf[len])) &&
95 !is_dir_sep(newdir[newlen - 1]);
96 if (need_sep)
97 len--; /* keep one char, to be replaced with '/' */
98 strbuf_splice(buf, 0, len, newdir, newlen);
99 if (need_sep)
100 buf->buf[newlen] = '/';
101}
102
0701530c
DT
103struct common_dir {
104 /* Not considered garbage for report_linked_checkout_garbage */
105 unsigned ignore_garbage:1;
106 unsigned is_dir:1;
c72fc40d
SG
107 /* Belongs to the common dir, though it may contain paths that don't */
108 unsigned is_common:1;
109 const char *path;
0701530c
DT
110};
111
112static struct common_dir common_list[] = {
c72fc40d
SG
113 { 0, 1, 1, "branches" },
114 { 0, 1, 1, "common" },
115 { 0, 1, 1, "hooks" },
116 { 0, 1, 1, "info" },
117 { 0, 0, 0, "info/sparse-checkout" },
118 { 1, 1, 1, "logs" },
119 { 1, 0, 0, "logs/HEAD" },
120 { 0, 1, 0, "logs/refs/bisect" },
121 { 0, 1, 0, "logs/refs/rewritten" },
122 { 0, 1, 0, "logs/refs/worktree" },
123 { 0, 1, 1, "lost-found" },
124 { 0, 1, 1, "objects" },
125 { 0, 1, 1, "refs" },
126 { 0, 1, 0, "refs/bisect" },
127 { 0, 1, 0, "refs/rewritten" },
128 { 0, 1, 0, "refs/worktree" },
129 { 0, 1, 1, "remotes" },
130 { 0, 1, 1, "worktrees" },
131 { 0, 1, 1, "rr-cache" },
132 { 0, 1, 1, "svn" },
133 { 0, 0, 1, "config" },
134 { 1, 0, 1, "gc.pid" },
135 { 0, 0, 1, "packed-refs" },
136 { 0, 0, 1, "shallow" },
0701530c 137 { 0, 0, 0, NULL }
c7b3a3d2
NTND
138};
139
4e09cf2a
DT
140/*
141 * A compressed trie. A trie node consists of zero or more characters that
142 * are common to all elements with this prefix, optionally followed by some
143 * children. If value is not NULL, the trie node is a terminal node.
144 *
145 * For example, consider the following set of strings:
146 * abc
147 * def
148 * definite
149 * definition
150 *
832c0e5e 151 * The trie would look like:
4e09cf2a
DT
152 * root: len = 0, children a and d non-NULL, value = NULL.
153 * a: len = 2, contents = bc, value = (data for "abc")
154 * d: len = 2, contents = ef, children i non-NULL, value = (data for "def")
155 * i: len = 3, contents = nit, children e and i non-NULL, value = NULL
156 * e: len = 0, children all NULL, value = (data for "definite")
157 * i: len = 2, contents = on, children all NULL,
158 * value = (data for "definition")
159 */
160struct trie {
161 struct trie *children[256];
162 int len;
163 char *contents;
164 void *value;
165};
166
167static struct trie *make_trie_node(const char *key, void *value)
c7b3a3d2 168{
4e09cf2a
DT
169 struct trie *new_node = xcalloc(1, sizeof(*new_node));
170 new_node->len = strlen(key);
171 if (new_node->len) {
172 new_node->contents = xmalloc(new_node->len);
173 memcpy(new_node->contents, key, new_node->len);
174 }
175 new_node->value = value;
176 return new_node;
177}
c7b3a3d2 178
4e09cf2a
DT
179/*
180 * Add a key/value pair to a trie. The key is assumed to be \0-terminated.
181 * If there was an existing value for this key, return it.
182 */
183static void *add_to_trie(struct trie *root, const char *key, void *value)
184{
185 struct trie *child;
186 void *old;
187 int i;
188
189 if (!*key) {
190 /* we have reached the end of the key */
191 old = root->value;
192 root->value = value;
193 return old;
194 }
195
196 for (i = 0; i < root->len; i++) {
197 if (root->contents[i] == key[i])
198 continue;
199
200 /*
201 * Split this node: child will contain this node's
202 * existing children.
203 */
55d7d158 204 child = xmalloc(sizeof(*child));
4e09cf2a
DT
205 memcpy(child->children, root->children, sizeof(root->children));
206
207 child->len = root->len - i - 1;
208 if (child->len) {
209 child->contents = xstrndup(root->contents + i + 1,
210 child->len);
c7b3a3d2 211 }
4e09cf2a
DT
212 child->value = root->value;
213 root->value = NULL;
214 root->len = i;
215
216 memset(root->children, 0, sizeof(root->children));
217 root->children[(unsigned char)root->contents[i]] = child;
218
219 /* This is the newly-added child. */
220 root->children[(unsigned char)key[i]] =
221 make_trie_node(key + i + 1, value);
222 return NULL;
223 }
224
225 /* We have matched the entire compressed section */
226 if (key[i]) {
227 child = root->children[(unsigned char)key[root->len]];
228 if (child) {
229 return add_to_trie(child, key + root->len + 1, value);
230 } else {
231 child = make_trie_node(key + root->len + 1, value);
232 root->children[(unsigned char)key[root->len]] = child;
233 return NULL;
c7b3a3d2
NTND
234 }
235 }
4e09cf2a
DT
236
237 old = root->value;
238 root->value = value;
239 return old;
240}
241
7cb8c929 242typedef int (*match_fn)(const char *unmatched, void *value, void *baton);
4e09cf2a
DT
243
244/*
245 * Search a trie for some key. Find the longest /-or-\0-terminated
7cb8c929
SG
246 * prefix of the key for which the trie contains a value. If there is
247 * no such prefix, return -1. Otherwise call fn with the unmatched
248 * portion of the key and the found value. If fn returns 0 or
249 * positive, then return its return value. If fn returns negative,
250 * then call fn with the next-longest /-terminated prefix of the key
251 * (i.e. a parent directory) for which the trie contains a value, and
252 * handle its return value the same way. If there is no shorter
253 * /-terminated prefix with a value left, then return the negative
254 * return value of the most recent fn invocation.
4e09cf2a
DT
255 *
256 * The key is partially normalized: consecutive slashes are skipped.
257 *
7cb8c929
SG
258 * For example, consider the trie containing only [logs,
259 * logs/refs/bisect], both with values, but not logs/refs.
4e09cf2a 260 *
7cb8c929
SG
261 * | key | unmatched | prefix to node | return value |
262 * |--------------------|----------------|------------------|--------------|
263 * | a | not called | n/a | -1 |
264 * | logstore | not called | n/a | -1 |
265 * | logs | \0 | logs | as per fn |
266 * | logs/ | / | logs | as per fn |
267 * | logs/refs | /refs | logs | as per fn |
268 * | logs/refs/ | /refs/ | logs | as per fn |
269 * | logs/refs/b | /refs/b | logs | as per fn |
270 * | logs/refs/bisected | /refs/bisected | logs | as per fn |
271 * | logs/refs/bisect | \0 | logs/refs/bisect | as per fn |
272 * | logs/refs/bisect/ | / | logs/refs/bisect | as per fn |
273 * | logs/refs/bisect/a | /a | logs/refs/bisect | as per fn |
274 * | (If fn in the previous line returns -1, then fn is called once more:) |
275 * | logs/refs/bisect/a | /refs/bisect/a | logs | as per fn |
276 * |--------------------|----------------|------------------|--------------|
4e09cf2a
DT
277 */
278static int trie_find(struct trie *root, const char *key, match_fn fn,
279 void *baton)
280{
281 int i;
282 int result;
283 struct trie *child;
284
285 if (!*key) {
286 /* we have reached the end of the key */
287 if (root->value && !root->len)
288 return fn(key, root->value, baton);
289 else
290 return -1;
291 }
292
293 for (i = 0; i < root->len; i++) {
294 /* Partial path normalization: skip consecutive slashes. */
295 if (key[i] == '/' && key[i+1] == '/') {
296 key++;
297 continue;
298 }
299 if (root->contents[i] != key[i])
300 return -1;
301 }
302
303 /* Matched the entire compressed section */
304 key += i;
f45f88b2 305 if (!*key) {
4e09cf2a 306 /* End of key */
f45f88b2
SG
307 if (root->value)
308 return fn(key, root->value, baton);
309 else
310 return -1;
311 }
4e09cf2a
DT
312
313 /* Partial path normalization: skip consecutive slashes */
314 while (key[0] == '/' && key[1] == '/')
315 key++;
316
317 child = root->children[(unsigned char)*key];
318 if (child)
319 result = trie_find(child, key + 1, fn, baton);
320 else
321 result = -1;
322
323 if (result >= 0 || (*key != '/' && *key != 0))
324 return result;
325 if (root->value)
326 return fn(key, root->value, baton);
327 else
328 return -1;
329}
330
331static struct trie common_trie;
332static int common_trie_done_setup;
333
334static void init_common_trie(void)
335{
336 struct common_dir *p;
337
338 if (common_trie_done_setup)
339 return;
340
c72fc40d
SG
341 for (p = common_list; p->path; p++)
342 add_to_trie(&common_trie, p->path, p);
4e09cf2a
DT
343
344 common_trie_done_setup = 1;
345}
346
347/*
348 * Helper function for update_common_dir: returns 1 if the dir
349 * prefix is common.
350 */
d3dcfa04
JK
351static int check_common(const char *unmatched, void *value,
352 void *baton UNUSED)
4e09cf2a
DT
353{
354 struct common_dir *dir = value;
355
4e09cf2a 356 if (dir->is_dir && (unmatched[0] == 0 || unmatched[0] == '/'))
c72fc40d 357 return dir->is_common;
4e09cf2a
DT
358
359 if (!dir->is_dir && unmatched[0] == 0)
c72fc40d 360 return dir->is_common;
4e09cf2a
DT
361
362 return 0;
363}
364
1c630bad
JH
365static void update_common_dir(struct strbuf *buf, int git_dir_len,
366 const char *common_dir)
4e09cf2a
DT
367{
368 char *base = buf->buf + git_dir_len;
76a53d64
JS
369 int has_lock_suffix = strbuf_strip_suffix(buf, LOCK_SUFFIX);
370
4e09cf2a
DT
371 init_common_trie();
372 if (trie_find(&common_trie, base, check_common, NULL) > 0)
1c630bad 373 replace_dir(buf, git_dir_len, common_dir);
76a53d64
JS
374
375 if (has_lock_suffix)
376 strbuf_addstr(buf, LOCK_SUFFIX);
c7b3a3d2
NTND
377}
378
77a6d840
NTND
379void report_linked_checkout_garbage(void)
380{
381 struct strbuf sb = STRBUF_INIT;
0701530c 382 const struct common_dir *p;
77a6d840
NTND
383 int len;
384
c14c234f 385 if (!the_repository->different_commondir)
77a6d840
NTND
386 return;
387 strbuf_addf(&sb, "%s/", get_git_dir());
388 len = sb.len;
c72fc40d
SG
389 for (p = common_list; p->path; p++) {
390 const char *path = p->path;
0701530c 391 if (p->ignore_garbage)
77a6d840
NTND
392 continue;
393 strbuf_setlen(&sb, len);
394 strbuf_addstr(&sb, path);
395 if (file_exists(sb.buf))
0a489b06 396 report_garbage(PACKDIR_FILE_GARBAGE, sb.buf);
77a6d840
NTND
397 }
398 strbuf_release(&sb);
fe2d7776
AR
399}
400
f9a8a47e
BW
401static void adjust_git_path(const struct repository *repo,
402 struct strbuf *buf, int git_dir_len)
557bd833
NTND
403{
404 const char *base = buf->buf + git_dir_len;
c14c234f 405 if (is_dir_file(base, "info", "grafts"))
557bd833 406 strbuf_splice(buf, 0, buf->len,
f9a8a47e 407 repo->graft_file, strlen(repo->graft_file));
c14c234f 408 else if (!strcmp(base, "index"))
557bd833 409 strbuf_splice(buf, 0, buf->len,
f9a8a47e 410 repo->index_file, strlen(repo->index_file));
c14c234f 411 else if (dir_prefix(base, "objects"))
f0eaf638 412 replace_dir(buf, git_dir_len + 7, repo->objects->odb->path);
9445b492
JS
413 else if (git_hooks_path && dir_prefix(base, "hooks"))
414 replace_dir(buf, git_dir_len + 5, git_hooks_path);
f9a8a47e
BW
415 else if (repo->different_commondir)
416 update_common_dir(buf, git_dir_len, repo->commondir);
557bd833
NTND
417}
418
f9a8a47e
BW
419static void strbuf_worktree_gitdir(struct strbuf *buf,
420 const struct repository *repo,
421 const struct worktree *wt)
422{
423 if (!wt)
424 strbuf_addstr(buf, repo->gitdir);
425 else if (!wt->id)
426 strbuf_addstr(buf, repo->commondir);
427 else
428 strbuf_git_common_path(buf, repo, "worktrees/%s", wt->id);
429}
430
431static void do_git_path(const struct repository *repo,
432 const struct worktree *wt, struct strbuf *buf,
2e641d58 433 const char *fmt, va_list args)
fe2d7776 434{
557bd833 435 int gitdir_len;
f9a8a47e 436 strbuf_worktree_gitdir(buf, repo, wt);
4ef9caf5
NTND
437 if (buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
438 strbuf_addch(buf, '/');
557bd833 439 gitdir_len = buf->len;
4ef9caf5 440 strbuf_vaddf(buf, fmt, args);
54310733
BW
441 if (!wt)
442 adjust_git_path(repo, buf, gitdir_len);
4ef9caf5 443 strbuf_cleanup_path(buf);
fe2d7776
AR
444}
445
3181d863
BW
446char *repo_git_path(const struct repository *repo,
447 const char *fmt, ...)
448{
449 struct strbuf path = STRBUF_INIT;
450 va_list args;
451 va_start(args, fmt);
452 do_git_path(repo, NULL, &path, fmt, args);
453 va_end(args);
454 return strbuf_detach(&path, NULL);
455}
456
457void strbuf_repo_git_path(struct strbuf *sb,
458 const struct repository *repo,
459 const char *fmt, ...)
460{
461 va_list args;
462 va_start(args, fmt);
463 do_git_path(repo, NULL, sb, fmt, args);
464 va_end(args);
465}
466
bb3788ce
JK
467char *git_path_buf(struct strbuf *buf, const char *fmt, ...)
468{
469 va_list args;
470 strbuf_reset(buf);
471 va_start(args, fmt);
f9a8a47e 472 do_git_path(the_repository, NULL, buf, fmt, args);
bb3788ce
JK
473 va_end(args);
474 return buf->buf;
475}
476
1a83c240 477void strbuf_git_path(struct strbuf *sb, const char *fmt, ...)
aba13e7c
AR
478{
479 va_list args;
480 va_start(args, fmt);
f9a8a47e 481 do_git_path(the_repository, NULL, sb, fmt, args);
aba13e7c 482 va_end(args);
aba13e7c
AR
483}
484
57a23b77 485const char *git_path(const char *fmt, ...)
aba13e7c 486{
57a23b77 487 struct strbuf *pathname = get_pathname();
aba13e7c
AR
488 va_list args;
489 va_start(args, fmt);
f9a8a47e 490 do_git_path(the_repository, NULL, pathname, fmt, args);
aba13e7c 491 va_end(args);
57a23b77 492 return pathname->buf;
aba13e7c
AR
493}
494
aba13e7c 495char *git_pathdup(const char *fmt, ...)
21cf3227 496{
4ef9caf5 497 struct strbuf path = STRBUF_INIT;
21cf3227 498 va_list args;
21cf3227 499 va_start(args, fmt);
f9a8a47e 500 do_git_path(the_repository, NULL, &path, fmt, args);
21cf3227 501 va_end(args);
4ef9caf5 502 return strbuf_detach(&path, NULL);
21cf3227
HKNN
503}
504
21cf3227 505char *mkpathdup(const char *fmt, ...)
26c8a533 506{
21cf3227 507 struct strbuf sb = STRBUF_INIT;
26c8a533 508 va_list args;
26c8a533 509 va_start(args, fmt);
21cf3227 510 strbuf_vaddf(&sb, fmt, args);
26c8a533 511 va_end(args);
4ef9caf5
NTND
512 strbuf_cleanup_path(&sb);
513 return strbuf_detach(&sb, NULL);
26c8a533
LT
514}
515
dcf69262 516const char *mkpath(const char *fmt, ...)
26c8a533 517{
26c8a533 518 va_list args;
4ef9caf5 519 struct strbuf *pathname = get_pathname();
26c8a533 520 va_start(args, fmt);
4ef9caf5 521 strbuf_vaddf(pathname, fmt, args);
26c8a533 522 va_end(args);
4ef9caf5 523 return cleanup_path(pathname->buf);
26c8a533 524}
f2db68ed 525
2e641d58
NTND
526const char *worktree_git_path(const struct worktree *wt, const char *fmt, ...)
527{
528 struct strbuf *pathname = get_pathname();
529 va_list args;
530 va_start(args, fmt);
f9a8a47e 531 do_git_path(the_repository, wt, pathname, fmt, args);
2e641d58
NTND
532 va_end(args);
533 return pathname->buf;
534}
535
b42b0c09
BW
536static void do_worktree_path(const struct repository *repo,
537 struct strbuf *buf,
538 const char *fmt, va_list args)
539{
540 strbuf_addstr(buf, repo->worktree);
541 if(buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
542 strbuf_addch(buf, '/');
543
544 strbuf_vaddf(buf, fmt, args);
545 strbuf_cleanup_path(buf);
546}
547
548char *repo_worktree_path(const struct repository *repo, const char *fmt, ...)
549{
550 struct strbuf path = STRBUF_INIT;
551 va_list args;
552
553 if (!repo->worktree)
554 return NULL;
555
556 va_start(args, fmt);
557 do_worktree_path(repo, &path, fmt, args);
558 va_end(args);
559
560 return strbuf_detach(&path, NULL);
561}
562
563void strbuf_repo_worktree_path(struct strbuf *sb,
564 const struct repository *repo,
565 const char *fmt, ...)
566{
567 va_list args;
568
569 if (!repo->worktree)
570 return;
571
572 va_start(args, fmt);
573 do_worktree_path(repo, sb, fmt, args);
574 va_end(args);
575}
576
99b43a61 577/* Returns 0 on success, negative on failure. */
99b43a61
JK
578static int do_submodule_path(struct strbuf *buf, const char *path,
579 const char *fmt, va_list args)
0bad611b 580{
11f9dd71
MK
581 struct strbuf git_submodule_common_dir = STRBUF_INIT;
582 struct strbuf git_submodule_dir = STRBUF_INIT;
bbbb7de7 583 int ret;
0bad611b 584
bbbb7de7
NTND
585 ret = submodule_to_gitdir(&git_submodule_dir, path);
586 if (ret)
587 goto cleanup;
0bad611b 588
bbbb7de7
NTND
589 strbuf_complete(&git_submodule_dir, '/');
590 strbuf_addbuf(buf, &git_submodule_dir);
4ef9caf5 591 strbuf_vaddf(buf, fmt, args);
11f9dd71
MK
592
593 if (get_common_dir_noenv(&git_submodule_common_dir, git_submodule_dir.buf))
594 update_common_dir(buf, git_submodule_dir.len, git_submodule_common_dir.buf);
595
4ef9caf5 596 strbuf_cleanup_path(buf);
11f9dd71 597
99b43a61 598cleanup:
11f9dd71
MK
599 strbuf_release(&git_submodule_dir);
600 strbuf_release(&git_submodule_common_dir);
bbbb7de7 601 return ret;
f5895fd3
JK
602}
603
f5895fd3
JK
604char *git_pathdup_submodule(const char *path, const char *fmt, ...)
605{
99b43a61 606 int err;
f5895fd3
JK
607 va_list args;
608 struct strbuf buf = STRBUF_INIT;
609 va_start(args, fmt);
99b43a61 610 err = do_submodule_path(&buf, path, fmt, args);
f5895fd3 611 va_end(args);
99b43a61
JK
612 if (err) {
613 strbuf_release(&buf);
614 return NULL;
615 }
f5895fd3
JK
616 return strbuf_detach(&buf, NULL);
617}
618
99b43a61
JK
619int strbuf_git_path_submodule(struct strbuf *buf, const char *path,
620 const char *fmt, ...)
f5895fd3 621{
99b43a61 622 int err;
f5895fd3
JK
623 va_list args;
624 va_start(args, fmt);
99b43a61 625 err = do_submodule_path(buf, path, fmt, args);
f5895fd3 626 va_end(args);
99b43a61
JK
627
628 return err;
f5895fd3
JK
629}
630
b337172c
BW
631static void do_git_common_path(const struct repository *repo,
632 struct strbuf *buf,
15cdfea7
NTND
633 const char *fmt,
634 va_list args)
635{
b337172c 636 strbuf_addstr(buf, repo->commondir);
15cdfea7
NTND
637 if (buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
638 strbuf_addch(buf, '/');
639 strbuf_vaddf(buf, fmt, args);
640 strbuf_cleanup_path(buf);
641}
642
643const char *git_common_path(const char *fmt, ...)
644{
645 struct strbuf *pathname = get_pathname();
646 va_list args;
647 va_start(args, fmt);
b337172c 648 do_git_common_path(the_repository, pathname, fmt, args);
15cdfea7
NTND
649 va_end(args);
650 return pathname->buf;
651}
652
b337172c
BW
653void strbuf_git_common_path(struct strbuf *sb,
654 const struct repository *repo,
655 const char *fmt, ...)
15cdfea7
NTND
656{
657 va_list args;
658 va_start(args, fmt);
b337172c 659 do_git_common_path(repo, sb, fmt, args);
15cdfea7
NTND
660 va_end(args);
661}
662
c847f537 663int validate_headref(const char *path)
0870ca7f
JH
664{
665 struct stat st;
7eb4b9d0
JK
666 char buffer[256];
667 const char *refname;
0bca165f 668 struct object_id oid;
0104ca09
HO
669 int fd;
670 ssize_t len;
0870ca7f
JH
671
672 if (lstat(path, &st) < 0)
673 return -1;
674
675 /* Make sure it is a "refs/.." symlink */
676 if (S_ISLNK(st.st_mode)) {
677 len = readlink(path, buffer, sizeof(buffer)-1);
222b1673 678 if (len >= 5 && !memcmp("refs/", buffer, 5))
0870ca7f
JH
679 return 0;
680 return -1;
681 }
682
683 /*
684 * Anything else, just open it and try to see if it is a symbolic ref.
685 */
686 fd = open(path, O_RDONLY);
687 if (fd < 0)
688 return -1;
93d26e4c 689 len = read_in_full(fd, buffer, sizeof(buffer)-1);
0870ca7f
JH
690 close(fd);
691
6e68c914
JK
692 if (len < 0)
693 return -1;
694 buffer[len] = '\0';
695
0870ca7f
JH
696 /*
697 * Is it a symbolic ref?
698 */
7eb4b9d0
JK
699 if (skip_prefix(buffer, "ref:", &refname)) {
700 while (isspace(*refname))
701 refname++;
702 if (starts_with(refname, "refs/"))
c847f537
JH
703 return 0;
704 }
705
706 /*
707 * Is this a detached HEAD?
708 */
0bca165f 709 if (!get_oid_hex(buffer, &oid))
0870ca7f 710 return 0;
c847f537 711
0870ca7f
JH
712 return -1;
713}
714
395de250 715static struct passwd *getpw_str(const char *username, size_t len)
54f4b874 716{
d79374c7 717 struct passwd *pw;
5c0b13f8 718 char *username_z = xmemdupz(username, len);
395de250
MM
719 pw = getpwnam(username_z);
720 free(username_z);
721 return pw;
722}
54f4b874 723
395de250 724/*
789f6f22
JS
725 * Return a string with ~ and ~user expanded via getpw*. Returns NULL on getpw
726 * failure or if path is NULL.
4aad2f16 727 *
644e6b2c 728 * If real_home is true, strbuf_realpath($HOME) is used in the `~/` expansion.
e394a160
JS
729 *
730 * If the path starts with `%(prefix)/`, the remainder is interpreted as
731 * relative to where Git is installed, and expanded to the absolute path.
395de250 732 */
a03b097d 733char *interpolate_path(const char *path, int real_home)
395de250
MM
734{
735 struct strbuf user_path = STRBUF_INIT;
395de250
MM
736 const char *to_copy = path;
737
afe8a907 738 if (!path)
395de250 739 goto return_null;
e394a160
JS
740
741 if (skip_prefix(path, "%(prefix)/", &path))
742 return system_path(path);
743
395de250 744 if (path[0] == '~') {
53ec551c 745 const char *first_slash = strchrnul(path, '/');
395de250
MM
746 const char *username = path + 1;
747 size_t username_len = first_slash - username;
df2a79f4
MM
748 if (username_len == 0) {
749 const char *home = getenv("HOME");
79bf1490
JN
750 if (!home)
751 goto return_null;
4aad2f16 752 if (real_home)
fa2bb344 753 strbuf_add_real_path(&user_path, home);
4aad2f16
NTND
754 else
755 strbuf_addstr(&user_path, home);
5ca6b7bb
JS
756#ifdef GIT_WINDOWS_NATIVE
757 convert_slashes(user_path.buf);
758#endif
df2a79f4
MM
759 } else {
760 struct passwd *pw = getpw_str(username, username_len);
761 if (!pw)
762 goto return_null;
cedc61a9 763 strbuf_addstr(&user_path, pw->pw_dir);
54f4b874 764 }
395de250 765 to_copy = first_slash;
d79374c7 766 }
cedc61a9 767 strbuf_addstr(&user_path, to_copy);
395de250
MM
768 return strbuf_detach(&user_path, NULL);
769return_null:
770 strbuf_release(&user_path);
771 return NULL;
54f4b874
AE
772}
773
d79374c7
JH
774/*
775 * First, one directory to try is determined by the following algorithm.
776 *
777 * (0) If "strict" is given, the path is used as given and no DWIM is
778 * done. Otherwise:
779 * (1) "~/path" to mean path under the running user's home directory;
780 * (2) "~user/path" to mean path under named user's home directory;
781 * (3) "relative/path" to mean cwd relative directory; or
782 * (4) "/absolute/path" to mean absolute directory.
783 *
c8c3f1d0
PT
784 * Unless "strict" is given, we check "%s/.git", "%s", "%s.git/.git", "%s.git"
785 * in this order. We select the first one that is a valid git repository, and
786 * chdir() to it. If none match, or we fail to chdir, we return NULL.
d79374c7
JH
787 *
788 * If all goes well, we return the directory we used to chdir() (but
789 * before ~user is expanded), avoiding getcwd() resolving symbolic
790 * links. User relative paths are also returned as they are given,
791 * except DWIM suffixing.
792 */
1c64b48e 793const char *enter_repo(const char *path, int strict)
54f4b874 794{
e9ba6781
JK
795 static struct strbuf validated_path = STRBUF_INIT;
796 static struct strbuf used_path = STRBUF_INIT;
d79374c7
JH
797
798 if (!path)
54f4b874
AE
799 return NULL;
800
d79374c7
JH
801 if (!strict) {
802 static const char *suffix[] = {
b3256eb8 803 "/.git", "", ".git/.git", ".git", NULL,
d79374c7 804 };
03106768 805 const char *gitfile;
d79374c7
JH
806 int len = strlen(path);
807 int i;
1c64b48e 808 while ((1 < len) && (path[len-1] == '/'))
d79374c7 809 len--;
1c64b48e 810
e9ba6781
JK
811 /*
812 * We can handle arbitrary-sized buffers, but this remains as a
813 * sanity check on untrusted input.
814 */
d79374c7 815 if (PATH_MAX <= len)
54f4b874 816 return NULL;
1c64b48e 817
e9ba6781
JK
818 strbuf_reset(&used_path);
819 strbuf_reset(&validated_path);
820 strbuf_add(&used_path, path, len);
821 strbuf_add(&validated_path, path, len);
822
823 if (used_path.buf[0] == '~') {
a03b097d 824 char *newpath = interpolate_path(used_path.buf, 0);
e9ba6781 825 if (!newpath)
d79374c7 826 return NULL;
e9ba6781
JK
827 strbuf_attach(&used_path, newpath, strlen(newpath),
828 strlen(newpath));
d79374c7 829 }
d79374c7 830 for (i = 0; suffix[i]; i++) {
b3256eb8 831 struct stat st;
e9ba6781
JK
832 size_t baselen = used_path.len;
833 strbuf_addstr(&used_path, suffix[i]);
834 if (!stat(used_path.buf, &st) &&
b3256eb8 835 (S_ISREG(st.st_mode) ||
e9ba6781
JK
836 (S_ISDIR(st.st_mode) && is_git_directory(used_path.buf)))) {
837 strbuf_addstr(&validated_path, suffix[i]);
d79374c7
JH
838 break;
839 }
e9ba6781 840 strbuf_setlen(&used_path, baselen);
d79374c7 841 }
03106768
PH
842 if (!suffix[i])
843 return NULL;
78891795 844 gitfile = read_gitfile(used_path.buf);
e9ba6781
JK
845 if (gitfile) {
846 strbuf_reset(&used_path);
847 strbuf_addstr(&used_path, gitfile);
848 }
849 if (chdir(used_path.buf))
0870ca7f 850 return NULL;
e9ba6781 851 path = validated_path.buf;
0870ca7f 852 }
1f5fbe1f
NTND
853 else {
854 const char *gitfile = read_gitfile(path);
855 if (gitfile)
856 path = gitfile;
857 if (chdir(path))
858 return NULL;
859 }
54f4b874 860
0f64cc40 861 if (is_git_directory(".")) {
0915a5b4 862 set_git_dir(".", 0);
cfe3917c 863 check_repository_format(NULL);
d79374c7 864 return path;
54f4b874
AE
865 }
866
867 return NULL;
868}
138086a7 869
cbe43b84 870static int calc_shared_perm(int mode)
138086a7 871{
cbe43b84 872 int tweak;
138086a7 873
7875acb6
JK
874 if (get_shared_repository() < 0)
875 tweak = -get_shared_repository();
5a688fe4 876 else
7875acb6 877 tweak = get_shared_repository();
5a688fe4
JH
878
879 if (!(mode & S_IWUSR))
880 tweak &= ~0222;
881 if (mode & S_IXUSR)
882 /* Copy read bits to execute bits */
883 tweak |= (tweak & 0444) >> 2;
7875acb6 884 if (get_shared_repository() < 0)
5a688fe4
JH
885 mode = (mode & ~0777) | tweak;
886 else
8c6202d8 887 mode |= tweak;
06cbe855 888
cbe43b84
TB
889 return mode;
890}
891
892
893int adjust_shared_perm(const char *path)
894{
895 int old_mode, new_mode;
896
7875acb6 897 if (!get_shared_repository())
cbe43b84
TB
898 return 0;
899 if (get_st_mode_bits(path, &old_mode) < 0)
900 return -1;
901
902 new_mode = calc_shared_perm(old_mode);
903 if (S_ISDIR(old_mode)) {
06cbe855 904 /* Copy read bits to execute bits */
cbe43b84 905 new_mode |= (new_mode & 0444) >> 2;
671bbf7b
JH
906
907 /*
908 * g+s matters only if any extra access is granted
909 * based on group membership.
910 */
911 if (FORCE_DIR_SET_GID && (new_mode & 060))
912 new_mode |= FORCE_DIR_SET_GID;
06cbe855
HO
913 }
914
cbe43b84
TB
915 if (((old_mode ^ new_mode) & ~S_IFMT) &&
916 chmod(path, (new_mode & ~S_IFMT)) < 0)
138086a7
JH
917 return -2;
918 return 0;
919}
e5392c51 920
eb33876c
DT
921void safe_create_dir(const char *dir, int share)
922{
923 if (mkdir(dir, 0777) < 0) {
924 if (errno != EEXIST) {
925 perror(dir);
926 exit(1);
927 }
928 }
929 else if (share && adjust_shared_perm(dir))
930 die(_("Could not make %s writable by group"), dir);
931}
932
7fbd4221
JX
933static int have_same_root(const char *path1, const char *path2)
934{
935 int is_abs1, is_abs2;
936
937 is_abs1 = is_absolute_path(path1);
938 is_abs2 = is_absolute_path(path2);
939 return (is_abs1 && is_abs2 && tolower(path1[0]) == tolower(path2[0])) ||
940 (!is_abs1 && !is_abs2);
941}
942
e02ca72f
JX
943/*
944 * Give path as relative to prefix.
945 *
946 * The strbuf may or may not be used, so do not assume it contains the
947 * returned path.
948 */
949const char *relative_path(const char *in, const char *prefix,
950 struct strbuf *sb)
044bbbcb 951{
e02ca72f
JX
952 int in_len = in ? strlen(in) : 0;
953 int prefix_len = prefix ? strlen(prefix) : 0;
954 int in_off = 0;
955 int prefix_off = 0;
288123f0
JH
956 int i = 0, j = 0;
957
e02ca72f
JX
958 if (!in_len)
959 return "./";
960 else if (!prefix_len)
961 return in;
962
2f36eed9 963 if (have_same_root(in, prefix))
7fbd4221 964 /* bypass dos_drive, for "c:" is identical to "C:" */
2f36eed9
JS
965 i = j = has_dos_drive_prefix(in);
966 else {
7fbd4221
JX
967 return in;
968 }
969
e02ca72f
JX
970 while (i < prefix_len && j < in_len && prefix[i] == in[j]) {
971 if (is_dir_sep(prefix[i])) {
972 while (is_dir_sep(prefix[i]))
288123f0 973 i++;
e02ca72f
JX
974 while (is_dir_sep(in[j]))
975 j++;
976 prefix_off = i;
977 in_off = j;
978 } else {
979 i++;
980 j++;
981 }
982 }
983
984 if (
985 /* "prefix" seems like prefix of "in" */
986 i >= prefix_len &&
987 /*
988 * but "/foo" is not a prefix of "/foobar"
989 * (i.e. prefix not end with '/')
990 */
991 prefix_off < prefix_len) {
992 if (j >= in_len) {
993 /* in="/a/b", prefix="/a/b" */
994 in_off = in_len;
995 } else if (is_dir_sep(in[j])) {
996 /* in="/a/b/c", prefix="/a/b" */
997 while (is_dir_sep(in[j]))
288123f0 998 j++;
e02ca72f
JX
999 in_off = j;
1000 } else {
1001 /* in="/a/bbb/c", prefix="/a/b" */
1002 i = prefix_off;
1003 }
1004 } else if (
1005 /* "in" is short than "prefix" */
1006 j >= in_len &&
1007 /* "in" not end with '/' */
1008 in_off < in_len) {
1009 if (is_dir_sep(prefix[i])) {
1010 /* in="/a/b", prefix="/a/b/c/" */
1011 while (is_dir_sep(prefix[i]))
1012 i++;
1013 in_off = in_len;
1014 }
1015 }
1016 in += in_off;
1017 in_len -= in_off;
1018
1019 if (i >= prefix_len) {
1020 if (!in_len)
1021 return "./";
1022 else
1023 return in;
1024 }
1025
1026 strbuf_reset(sb);
1027 strbuf_grow(sb, in_len);
1028
1029 while (i < prefix_len) {
1030 if (is_dir_sep(prefix[i])) {
1031 strbuf_addstr(sb, "../");
1032 while (is_dir_sep(prefix[i]))
1033 i++;
288123f0 1034 continue;
288123f0
JH
1035 }
1036 i++;
288123f0 1037 }
e02ca72f
JX
1038 if (!is_dir_sep(prefix[prefix_len - 1]))
1039 strbuf_addstr(sb, "../");
1040
1041 strbuf_addstr(sb, in);
1042
1043 return sb->buf;
044bbbcb 1044}
ae299be0 1045
41894ae3
JX
1046/*
1047 * A simpler implementation of relative_path
1048 *
1049 * Get relative path by removing "prefix" from "in". This function
1050 * first appears in v1.5.6-1-g044bbbc, and makes git_dir shorter
1051 * to increase performance when traversing the path to work_tree.
1052 */
1053const char *remove_leading_path(const char *in, const char *prefix)
1054{
46357688 1055 static struct strbuf buf = STRBUF_INIT;
41894ae3
JX
1056 int i = 0, j = 0;
1057
1058 if (!prefix || !prefix[0])
1059 return in;
1060 while (prefix[i]) {
1061 if (is_dir_sep(prefix[i])) {
1062 if (!is_dir_sep(in[j]))
1063 return in;
1064 while (is_dir_sep(prefix[i]))
1065 i++;
1066 while (is_dir_sep(in[j]))
1067 j++;
1068 continue;
1069 } else if (in[j] != prefix[i]) {
1070 return in;
1071 }
1072 i++;
1073 j++;
1074 }
1075 if (
1076 /* "/foo" is a prefix of "/foo" */
1077 in[j] &&
1078 /* "/foo" is not a prefix of "/foobar" */
1079 !is_dir_sep(prefix[i-1]) && !is_dir_sep(in[j])
1080 )
1081 return in;
1082 while (is_dir_sep(in[j]))
1083 j++;
46357688
JK
1084
1085 strbuf_reset(&buf);
41894ae3 1086 if (!in[j])
46357688 1087 strbuf_addstr(&buf, ".");
41894ae3 1088 else
46357688
JK
1089 strbuf_addstr(&buf, in + j);
1090 return buf.buf;
41894ae3
JX
1091}
1092
ae299be0 1093/*
f2a782b8 1094 * It is okay if dst == src, but they should not overlap otherwise.
9734b74a
JK
1095 * The "dst" buffer must be at least as long as "src"; normalizing may shrink
1096 * the size of the path, but will never grow it.
ae299be0 1097 *
f2a782b8
JS
1098 * Performs the following normalizations on src, storing the result in dst:
1099 * - Ensures that components are separated by '/' (Windows only)
7814fbe3 1100 * - Squashes sequences of '/' except "//server/share" on Windows
ae299be0
DR
1101 * - Removes "." components.
1102 * - Removes ".." components, and the components the precede them.
f2a782b8
JS
1103 * Returns failure (non-zero) if a ".." component appears as first path
1104 * component anytime during the normalization. Otherwise, returns success (0).
ae299be0
DR
1105 *
1106 * Note that this function is purely textual. It does not follow symlinks,
1107 * verify the existence of the path, or make any system calls.
645a29c4
NTND
1108 *
1109 * prefix_len != NULL is for a specific case of prefix_pathspec():
1110 * assume that src == dst and src[0..prefix_len-1] is already
1111 * normalized, any time "../" eats up to the prefix_len part,
1112 * prefix_len is reduced. In the end prefix_len is the remaining
1113 * prefix that has not been overridden by user pathspec.
b2a7123b
RD
1114 *
1115 * NEEDSWORK: This function doesn't perform normalization w.r.t. trailing '/'.
1116 * For everything but the root folder itself, the normalized path should not
1117 * end with a '/', then the callers need to be fixed up accordingly.
1118 *
ae299be0 1119 */
645a29c4 1120int normalize_path_copy_len(char *dst, const char *src, int *prefix_len)
ae299be0 1121{
f3cad0ad 1122 char *dst0;
7814fbe3 1123 const char *end;
ae299be0 1124
7814fbe3
JS
1125 /*
1126 * Copy initial part of absolute path: "/", "C:/", "//server/share/".
1127 */
1128 end = src + offset_1st_component(src);
1129 while (src < end) {
1130 char c = *src++;
1131 if (is_dir_sep(c))
1132 c = '/';
1133 *dst++ = c;
1134 }
f3cad0ad 1135 dst0 = dst;
ae299be0 1136
7814fbe3
JS
1137 while (is_dir_sep(*src))
1138 src++;
f3cad0ad
JS
1139
1140 for (;;) {
1141 char c = *src;
1142
1143 /*
1144 * A path component that begins with . could be
1145 * special:
1146 * (1) "." and ends -- ignore and terminate.
1147 * (2) "./" -- ignore them, eat slash and continue.
1148 * (3) ".." and ends -- strip one and terminate.
1149 * (4) "../" -- strip one, eat slash and continue.
1150 */
1151 if (c == '.') {
1152 if (!src[1]) {
1153 /* (1) */
1154 src++;
1155 } else if (is_dir_sep(src[1])) {
1156 /* (2) */
1157 src += 2;
1158 while (is_dir_sep(*src))
1159 src++;
1160 continue;
1161 } else if (src[1] == '.') {
1162 if (!src[2]) {
1163 /* (3) */
1164 src += 2;
1165 goto up_one;
1166 } else if (is_dir_sep(src[2])) {
1167 /* (4) */
1168 src += 3;
1169 while (is_dir_sep(*src))
1170 src++;
1171 goto up_one;
1172 }
1173 }
1174 }
ae299be0 1175
f3cad0ad
JS
1176 /* copy up to the next '/', and eat all '/' */
1177 while ((c = *src++) != '\0' && !is_dir_sep(c))
1178 *dst++ = c;
1179 if (is_dir_sep(c)) {
1180 *dst++ = '/';
1181 while (is_dir_sep(c))
1182 c = *src++;
1183 src--;
1184 } else if (!c)
1185 break;
1186 continue;
1187
1188 up_one:
1189 /*
1190 * dst0..dst is prefix portion, and dst[-1] is '/';
1191 * go up one level.
1192 */
f42302b4
JS
1193 dst--; /* go to trailing '/' */
1194 if (dst <= dst0)
f3cad0ad 1195 return -1;
f42302b4
JS
1196 /* Windows: dst[-1] cannot be backslash anymore */
1197 while (dst0 < dst && dst[-1] != '/')
1198 dst--;
645a29c4
NTND
1199 if (prefix_len && *prefix_len > dst - dst0)
1200 *prefix_len = dst - dst0;
f3cad0ad 1201 }
ae299be0 1202 *dst = '\0';
f3cad0ad 1203 return 0;
ae299be0 1204}
0454dd93 1205
645a29c4
NTND
1206int normalize_path_copy(char *dst, const char *src)
1207{
1208 return normalize_path_copy_len(dst, src, NULL);
1209}
1210
0454dd93
DR
1211/*
1212 * path = Canonical absolute path
9e2326c7
MH
1213 * prefixes = string_list containing normalized, absolute paths without
1214 * trailing slashes (except for the root directory, which is denoted by "/").
0454dd93 1215 *
9e2326c7 1216 * Determines, for each path in prefixes, whether the "prefix"
0454dd93
DR
1217 * is an ancestor directory of path. Returns the length of the longest
1218 * ancestor directory, excluding any trailing slashes, or -1 if no prefix
31171d9e
MH
1219 * is an ancestor. (Note that this means 0 is returned if prefixes is
1220 * ["/"].) "/foo" is not considered an ancestor of "/foobar". Directories
0454dd93
DR
1221 * are not considered to be their own ancestors. path must be in a
1222 * canonical form: empty components, or "." or ".." components are not
9e2326c7 1223 * allowed.
0454dd93 1224 */
31171d9e 1225int longest_ancestor_length(const char *path, struct string_list *prefixes)
0454dd93 1226{
a5ccdbe4 1227 int i, max_len = -1;
0454dd93 1228
31171d9e 1229 if (!strcmp(path, "/"))
0454dd93
DR
1230 return -1;
1231
31171d9e
MH
1232 for (i = 0; i < prefixes->nr; i++) {
1233 const char *ceil = prefixes->items[i].string;
a5ccdbe4
MH
1234 int len = strlen(ceil);
1235
fdcad5a5
JS
1236 /*
1237 * For root directories (`/`, `C:/`, `//server/share/`)
1238 * adjust the length to exclude the trailing slash.
1239 */
1240 if (len > 0 && ceil[len - 1] == '/')
1241 len--;
1242
1243 if (strncmp(path, ceil, len) ||
1244 path[len] != '/' || !path[len + 1])
9e2326c7 1245 continue; /* no match */
0454dd93 1246
9e2326c7 1247 if (len > max_len)
0454dd93 1248 max_len = len;
0454dd93
DR
1249 }
1250
1251 return max_len;
1252}
4fcc86b0
JS
1253
1254/* strip arbitrary amount of directory separators at end of path */
1255static inline int chomp_trailing_dir_sep(const char *path, int len)
1256{
1257 while (len && is_dir_sep(path[len - 1]))
1258 len--;
1259 return len;
1260}
1261
1262/*
ce17feb1 1263 * If path ends with suffix (complete path components), returns the offset of
1264 * the last character in the path before the suffix (sans trailing directory
1265 * separators), and -1 otherwise.
4fcc86b0 1266 */
ce17feb1 1267static ssize_t stripped_path_suffix_offset(const char *path, const char *suffix)
4fcc86b0
JS
1268{
1269 int path_len = strlen(path), suffix_len = strlen(suffix);
1270
1271 while (suffix_len) {
1272 if (!path_len)
ce17feb1 1273 return -1;
4fcc86b0
JS
1274
1275 if (is_dir_sep(path[path_len - 1])) {
1276 if (!is_dir_sep(suffix[suffix_len - 1]))
ce17feb1 1277 return -1;
4fcc86b0
JS
1278 path_len = chomp_trailing_dir_sep(path, path_len);
1279 suffix_len = chomp_trailing_dir_sep(suffix, suffix_len);
1280 }
1281 else if (path[--path_len] != suffix[--suffix_len])
ce17feb1 1282 return -1;
4fcc86b0
JS
1283 }
1284
1285 if (path_len && !is_dir_sep(path[path_len - 1]))
ce17feb1 1286 return -1;
1287 return chomp_trailing_dir_sep(path, path_len);
1288}
1289
1290/*
1291 * Returns true if the path ends with components, considering only complete path
1292 * components, and false otherwise.
1293 */
1294int ends_with_path_components(const char *path, const char *components)
1295{
1296 return stripped_path_suffix_offset(path, components) != -1;
1297}
1298
1299/*
1300 * If path ends with suffix (complete path components), returns the
1301 * part before suffix (sans trailing directory separators).
1302 * Otherwise returns NULL.
1303 */
1304char *strip_path_suffix(const char *path, const char *suffix)
1305{
1306 ssize_t offset = stripped_path_suffix_offset(path, suffix);
1307
1308 return offset == -1 ? NULL : xstrndup(path, offset);
4fcc86b0 1309}
34b6cb8b
SP
1310
1311int daemon_avoid_alias(const char *p)
1312{
1313 int sl, ndot;
1314
1315 /*
1316 * This resurrects the belts and suspenders paranoia check by HPA
1317 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
9517e6b8 1318 * does not do getcwd() based path canonicalization.
34b6cb8b
SP
1319 *
1320 * sl becomes true immediately after seeing '/' and continues to
1321 * be true as long as dots continue after that without intervening
1322 * non-dot character.
1323 */
1324 if (!p || (*p != '/' && *p != '~'))
1325 return -1;
1326 sl = 1; ndot = 0;
1327 p++;
1328
1329 while (1) {
1330 char ch = *p++;
1331 if (sl) {
1332 if (ch == '.')
1333 ndot++;
1334 else if (ch == '/') {
1335 if (ndot < 3)
1336 /* reject //, /./ and /../ */
1337 return -1;
1338 ndot = 0;
1339 }
1340 else if (ch == 0) {
1341 if (0 < ndot && ndot < 3)
1342 /* reject /.$ and /..$ */
1343 return -1;
1344 return 0;
1345 }
1346 else
1347 sl = ndot = 0;
1348 }
1349 else if (ch == 0)
1350 return 0;
1351 else if (ch == '/') {
1352 sl = 1;
1353 ndot = 0;
1354 }
1355 }
1356}
4bb43de2 1357
525e7fba
JS
1358/*
1359 * On NTFS, we need to be careful to disallow certain synonyms of the `.git/`
1360 * directory:
1361 *
1362 * - For historical reasons, file names that end in spaces or periods are
1363 * automatically trimmed. Therefore, `.git . . ./` is a valid way to refer
1364 * to `.git/`.
1365 *
1366 * - For other historical reasons, file names that do not conform to the 8.3
1367 * format (up to eight characters for the basename, three for the file
1368 * extension, certain characters not allowed such as `+`, etc) are associated
1369 * with a so-called "short name", at least on the `C:` drive by default.
1370 * Which means that `git~1/` is a valid way to refer to `.git/`.
1371 *
1372 * Note: Technically, `.git/` could receive the short name `git~2` if the
1373 * short name `git~1` were already used. In Git, however, we guarantee that
1374 * `.git` is the first item in a directory, therefore it will be associated
1375 * with the short name `git~1` (unless short names are disabled).
1376 *
7c3745fc
JS
1377 * - For yet other historical reasons, NTFS supports so-called "Alternate Data
1378 * Streams", i.e. metadata associated with a given file, referred to via
1379 * `<filename>:<stream-name>:<stream-type>`. There exists a default stream
1380 * type for directories, allowing `.git/` to be accessed via
1381 * `.git::$INDEX_ALLOCATION/`.
1382 *
525e7fba
JS
1383 * When this function returns 1, it indicates that the specified file/directory
1384 * name refers to a `.git` file or directory, or to any of these synonyms, and
1385 * Git should therefore not track it.
1386 *
7c3745fc
JS
1387 * For performance reasons, _all_ Alternate Data Streams of `.git/` are
1388 * forbidden, not just `::$INDEX_ALLOCATION`.
1389 *
525e7fba
JS
1390 * This function is intended to be used by `git fsck` even on platforms where
1391 * the backslash is a regular filename character, therefore it needs to handle
1392 * backlash characters in the provided `name` specially: they are interpreted
1393 * as directory separators.
1394 */
1d1d69bc 1395int is_ntfs_dotgit(const char *name)
1d1d69bc 1396{
3a85dc7d
JS
1397 char c;
1398
1399 /*
1400 * Note that when we don't find `.git` or `git~1` we end up with `name`
1401 * advanced partway through the string. That's okay, though, as we
1402 * return immediately in those cases, without looking at `name` any
1403 * further.
1404 */
1405 c = *(name++);
1406 if (c == '.') {
1407 /* .git */
1408 if (((c = *(name++)) != 'g' && c != 'G') ||
1409 ((c = *(name++)) != 'i' && c != 'I') ||
1410 ((c = *(name++)) != 't' && c != 'T'))
288a74bc 1411 return 0;
3a85dc7d
JS
1412 } else if (c == 'g' || c == 'G') {
1413 /* git ~1 */
1414 if (((c = *(name++)) != 'i' && c != 'I') ||
1415 ((c = *(name++)) != 't' && c != 'T') ||
1416 *(name++) != '~' ||
1417 *(name++) != '1')
1418 return 0;
1419 } else
1d1d69bc 1420 return 0;
3a85dc7d
JS
1421
1422 for (;;) {
1423 c = *(name++);
9fd512c8 1424 if (!c || is_xplatform_dir_sep(c) || c == ':')
3a85dc7d
JS
1425 return 1;
1426 if (c != '.' && c != ' ')
1d1d69bc
JS
1427 return 0;
1428 }
1d1d69bc 1429}
ea19289b 1430
e7cb0b44
JS
1431static int is_ntfs_dot_generic(const char *name,
1432 const char *dotgit_name,
1433 size_t len,
1434 const char *dotgit_ntfs_shortname_prefix)
1435{
1436 int saw_tilde;
1437 size_t i;
1438
1439 if ((name[0] == '.' && !strncasecmp(name + 1, dotgit_name, len))) {
1440 i = len + 1;
1441only_spaces_and_periods:
1442 for (;;) {
1443 char c = name[i++];
91bd4658 1444 if (!c || c == ':')
e7cb0b44
JS
1445 return 1;
1446 if (c != ' ' && c != '.')
1447 return 0;
1448 }
1449 }
1450
1451 /*
1452 * Is it a regular NTFS short name, i.e. shortened to 6 characters,
1453 * followed by ~1, ... ~4?
1454 */
1455 if (!strncasecmp(name, dotgit_name, 6) && name[6] == '~' &&
1456 name[7] >= '1' && name[7] <= '4') {
1457 i = 8;
1458 goto only_spaces_and_periods;
1459 }
1460
1461 /*
1462 * Is it a fall-back NTFS short name (for details, see
1463 * https://en.wikipedia.org/wiki/8.3_filename?
1464 */
1465 for (i = 0, saw_tilde = 0; i < 8; i++)
1466 if (name[i] == '\0')
1467 return 0;
1468 else if (saw_tilde) {
1469 if (name[i] < '0' || name[i] > '9')
1470 return 0;
1471 } else if (name[i] == '~') {
1472 if (name[++i] < '1' || name[i] > '9')
1473 return 0;
1474 saw_tilde = 1;
1475 } else if (i >= 6)
1476 return 0;
30634774 1477 else if (name[i] & 0x80) {
e7cb0b44
JS
1478 /*
1479 * We know our needles contain only ASCII, so we clamp
1480 * here to make the results of tolower() sane.
1481 */
1482 return 0;
1483 } else if (tolower(name[i]) != dotgit_ntfs_shortname_prefix[i])
1484 return 0;
1485
1486 goto only_spaces_and_periods;
1487}
1488
1489/*
1490 * Inline helper to make sure compiler resolves strlen() on literals at
1491 * compile time.
1492 */
1493static inline int is_ntfs_dot_str(const char *name, const char *dotgit_name,
1494 const char *dotgit_ntfs_shortname_prefix)
1495{
1496 return is_ntfs_dot_generic(name, dotgit_name, strlen(dotgit_name),
1497 dotgit_ntfs_shortname_prefix);
1498}
1499
1500int is_ntfs_dotgitmodules(const char *name)
1501{
1502 return is_ntfs_dot_str(name, "gitmodules", "gi7eba");
1503}
1504
1505int is_ntfs_dotgitignore(const char *name)
1506{
1507 return is_ntfs_dot_str(name, "gitignore", "gi250a");
1508}
1509
1510int is_ntfs_dotgitattributes(const char *name)
1511{
1512 return is_ntfs_dot_str(name, "gitattributes", "gi7d29");
1513}
1514
801ed010
JK
1515int is_ntfs_dotmailmap(const char *name)
1516{
1517 return is_ntfs_dot_str(name, "mailmap", "maba30");
1518}
1519
2491f77b
JK
1520int looks_like_command_line_option(const char *str)
1521{
1522 return str && str[0] == '-';
1523}
1524
cb7db5bb 1525char *xdg_config_home_for(const char *subdir, const char *filename)
ea19289b
PT
1526{
1527 const char *home, *config_home;
1528
cb7db5bb 1529 assert(subdir);
ea19289b
PT
1530 assert(filename);
1531 config_home = getenv("XDG_CONFIG_HOME");
1532 if (config_home && *config_home)
cb7db5bb 1533 return mkpathdup("%s/%s/%s", config_home, subdir, filename);
ea19289b
PT
1534
1535 home = getenv("HOME");
1536 if (home)
cb7db5bb
LH
1537 return mkpathdup("%s/.config/%s/%s", home, subdir, filename);
1538
ea19289b
PT
1539 return NULL;
1540}
f932729c 1541
cb7db5bb
LH
1542char *xdg_config_home(const char *filename)
1543{
1544 return xdg_config_home_for("git", filename);
1545}
1546
e7f136bf
DL
1547char *xdg_cache_home(const char *filename)
1548{
1549 const char *home, *cache_home;
1550
1551 assert(filename);
1552 cache_home = getenv("XDG_CACHE_HOME");
1553 if (cache_home && *cache_home)
1554 return mkpathdup("%s/git/%s", cache_home, filename);
1555
1556 home = getenv("HOME");
1557 if (home)
1558 return mkpathdup("%s/.cache/git/%s", home, filename);
1559 return NULL;
1560}
1561
102de880
SB
1562REPO_GIT_PATH_FUNC(squash_msg, "SQUASH_MSG")
1563REPO_GIT_PATH_FUNC(merge_msg, "MERGE_MSG")
1564REPO_GIT_PATH_FUNC(merge_rr, "MERGE_RR")
1565REPO_GIT_PATH_FUNC(merge_mode, "MERGE_MODE")
1566REPO_GIT_PATH_FUNC(merge_head, "MERGE_HEAD")
a03b5553 1567REPO_GIT_PATH_FUNC(merge_autostash, "MERGE_AUTOSTASH")
5291828d 1568REPO_GIT_PATH_FUNC(auto_merge, "AUTO_MERGE")
102de880
SB
1569REPO_GIT_PATH_FUNC(fetch_head, "FETCH_HEAD")
1570REPO_GIT_PATH_FUNC(shallow, "shallow")