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