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