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