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