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