refs: clean up common_list
[git/git.git] / path.c
CommitLineData
26c8a533 1/*
3a429d3b 2 * Utilities for paths and pathnames
26c8a533
LT
3 */
4#include "cache.h"
395de250 5#include "strbuf.h"
a5ccdbe4 6#include "string-list.h"
77a6d840 7#include "dir.h"
26c8a533 8
f66450ae 9static int get_st_mode_bits(const char *path, int *mode)
0117c2f0
TB
10{
11 struct stat st;
12 if (lstat(path, &st) < 0)
13 return -1;
14 *mode = st.st_mode;
15 return 0;
16}
0117c2f0 17
26c8a533
LT
18static char bad_path[] = "/bad-path/";
19
4ef9caf5 20static struct strbuf *get_pathname(void)
e7676d2f 21{
4ef9caf5
NTND
22 static struct strbuf pathname_array[4] = {
23 STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
24 };
e7676d2f 25 static int index;
4ef9caf5
NTND
26 struct strbuf *sb = &pathname_array[3 & ++index];
27 strbuf_reset(sb);
28 return sb;
e7676d2f
LT
29}
30
26c8a533
LT
31static char *cleanup_path(char *path)
32{
33 /* Clean it up */
34 if (!memcmp(path, "./", 2)) {
35 path += 2;
36 while (*path == '/')
37 path++;
38 }
39 return path;
40}
41
4ef9caf5
NTND
42static void strbuf_cleanup_path(struct strbuf *sb)
43{
44 char *path = cleanup_path(sb->buf);
45 if (path > sb->buf)
46 strbuf_remove(sb, 0, path - sb->buf);
47}
48
108bebea
AR
49char *mksnpath(char *buf, size_t n, const char *fmt, ...)
50{
51 va_list args;
52 unsigned len;
53
54 va_start(args, fmt);
55 len = vsnprintf(buf, n, fmt, args);
56 va_end(args);
57 if (len >= n) {
9db56f71 58 strlcpy(buf, bad_path, n);
108bebea
AR
59 return buf;
60 }
61 return cleanup_path(buf);
62}
63
557bd833 64static int dir_prefix(const char *buf, const char *dir)
fe2d7776 65{
557bd833
NTND
66 int len = strlen(dir);
67 return !strncmp(buf, dir, len) &&
68 (is_dir_sep(buf[len]) || buf[len] == '\0');
69}
fe2d7776 70
557bd833
NTND
71/* $buf =~ m|$dir/+$file| but without regex */
72static int is_dir_file(const char *buf, const char *dir, const char *file)
73{
74 int len = strlen(dir);
75 if (strncmp(buf, dir, len) || !is_dir_sep(buf[len]))
76 return 0;
77 while (is_dir_sep(buf[len]))
78 len++;
79 return !strcmp(buf + len, file);
80}
81
82static void replace_dir(struct strbuf *buf, int len, const char *newdir)
83{
84 int newlen = strlen(newdir);
85 int need_sep = (buf->buf[len] && !is_dir_sep(buf->buf[len])) &&
86 !is_dir_sep(newdir[newlen - 1]);
87 if (need_sep)
88 len--; /* keep one char, to be replaced with '/' */
89 strbuf_splice(buf, 0, len, newdir, newlen);
90 if (need_sep)
91 buf->buf[newlen] = '/';
92}
93
0701530c
DT
94struct common_dir {
95 /* Not considered garbage for report_linked_checkout_garbage */
96 unsigned ignore_garbage:1;
97 unsigned is_dir:1;
98 /* Not common even though its parent is */
99 unsigned exclude:1;
100 const char *dirname;
101};
102
103static struct common_dir common_list[] = {
104 { 0, 1, 0, "branches" },
105 { 0, 1, 0, "hooks" },
106 { 0, 1, 0, "info" },
107 { 0, 0, 1, "info/sparse-checkout" },
108 { 1, 1, 0, "logs" },
109 { 1, 1, 1, "logs/HEAD" },
110 { 0, 1, 0, "lost-found" },
111 { 0, 1, 0, "objects" },
112 { 0, 1, 0, "refs" },
113 { 0, 1, 0, "remotes" },
114 { 0, 1, 0, "worktrees" },
115 { 0, 1, 0, "rr-cache" },
116 { 0, 1, 0, "svn" },
117 { 0, 0, 0, "config" },
118 { 1, 0, 0, "gc.pid" },
119 { 0, 0, 0, "packed-refs" },
120 { 0, 0, 0, "shallow" },
121 { 0, 0, 0, NULL }
c7b3a3d2
NTND
122};
123
124static void update_common_dir(struct strbuf *buf, int git_dir_len)
125{
126 char *base = buf->buf + git_dir_len;
0701530c 127 const struct common_dir *p;
c7b3a3d2 128
6cfbdcb2
NTND
129 if (is_dir_file(base, "logs", "HEAD") ||
130 is_dir_file(base, "info", "sparse-checkout"))
c7b3a3d2 131 return; /* keep this in $GIT_DIR */
0701530c
DT
132 for (p = common_list; p->dirname; p++) {
133 const char *path = p->dirname;
134 if (p->is_dir && dir_prefix(base, path)) {
c7b3a3d2
NTND
135 replace_dir(buf, git_dir_len, get_git_common_dir());
136 return;
137 }
0701530c 138 if (!p->is_dir && !strcmp(base, path)) {
c7b3a3d2
NTND
139 replace_dir(buf, git_dir_len, get_git_common_dir());
140 return;
141 }
142 }
143}
144
77a6d840
NTND
145void report_linked_checkout_garbage(void)
146{
147 struct strbuf sb = STRBUF_INIT;
0701530c 148 const struct common_dir *p;
77a6d840
NTND
149 int len;
150
151 if (!git_common_dir_env)
152 return;
153 strbuf_addf(&sb, "%s/", get_git_dir());
154 len = sb.len;
0701530c
DT
155 for (p = common_list; p->dirname; p++) {
156 const char *path = p->dirname;
157 if (p->ignore_garbage)
77a6d840
NTND
158 continue;
159 strbuf_setlen(&sb, len);
160 strbuf_addstr(&sb, path);
161 if (file_exists(sb.buf))
162 report_garbage("unused in linked checkout", sb.buf);
163 }
164 strbuf_release(&sb);
fe2d7776
AR
165}
166
557bd833
NTND
167static void adjust_git_path(struct strbuf *buf, int git_dir_len)
168{
169 const char *base = buf->buf + git_dir_len;
170 if (git_graft_env && is_dir_file(base, "info", "grafts"))
171 strbuf_splice(buf, 0, buf->len,
172 get_graft_file(), strlen(get_graft_file()));
173 else if (git_index_env && !strcmp(base, "index"))
174 strbuf_splice(buf, 0, buf->len,
175 get_index_file(), strlen(get_index_file()));
176 else if (git_db_env && dir_prefix(base, "objects"))
177 replace_dir(buf, git_dir_len + 7, get_object_directory());
c7b3a3d2
NTND
178 else if (git_common_dir_env)
179 update_common_dir(buf, git_dir_len);
557bd833
NTND
180}
181
8afdaf39 182static void do_git_path(struct strbuf *buf, const char *fmt, va_list args)
fe2d7776 183{
557bd833
NTND
184 int gitdir_len;
185 strbuf_addstr(buf, get_git_dir());
4ef9caf5
NTND
186 if (buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
187 strbuf_addch(buf, '/');
557bd833 188 gitdir_len = buf->len;
4ef9caf5 189 strbuf_vaddf(buf, fmt, args);
557bd833 190 adjust_git_path(buf, gitdir_len);
4ef9caf5 191 strbuf_cleanup_path(buf);
fe2d7776
AR
192}
193
1a83c240 194void strbuf_git_path(struct strbuf *sb, const char *fmt, ...)
aba13e7c
AR
195{
196 va_list args;
197 va_start(args, fmt);
8afdaf39 198 do_git_path(sb, fmt, args);
aba13e7c 199 va_end(args);
aba13e7c
AR
200}
201
57a23b77 202const char *git_path(const char *fmt, ...)
aba13e7c 203{
57a23b77 204 struct strbuf *pathname = get_pathname();
aba13e7c
AR
205 va_list args;
206 va_start(args, fmt);
57a23b77 207 do_git_path(pathname, fmt, args);
aba13e7c 208 va_end(args);
57a23b77 209 return pathname->buf;
aba13e7c
AR
210}
211
aba13e7c 212char *git_pathdup(const char *fmt, ...)
21cf3227 213{
4ef9caf5 214 struct strbuf path = STRBUF_INIT;
21cf3227 215 va_list args;
21cf3227 216 va_start(args, fmt);
8afdaf39 217 do_git_path(&path, fmt, args);
21cf3227 218 va_end(args);
4ef9caf5 219 return strbuf_detach(&path, NULL);
21cf3227
HKNN
220}
221
21cf3227 222char *mkpathdup(const char *fmt, ...)
26c8a533 223{
21cf3227 224 struct strbuf sb = STRBUF_INIT;
26c8a533 225 va_list args;
26c8a533 226 va_start(args, fmt);
21cf3227 227 strbuf_vaddf(&sb, fmt, args);
26c8a533 228 va_end(args);
4ef9caf5
NTND
229 strbuf_cleanup_path(&sb);
230 return strbuf_detach(&sb, NULL);
26c8a533
LT
231}
232
dcf69262 233const char *mkpath(const char *fmt, ...)
26c8a533 234{
26c8a533 235 va_list args;
4ef9caf5 236 struct strbuf *pathname = get_pathname();
26c8a533 237 va_start(args, fmt);
4ef9caf5 238 strbuf_vaddf(pathname, fmt, args);
26c8a533 239 va_end(args);
4ef9caf5 240 return cleanup_path(pathname->buf);
26c8a533 241}
f2db68ed 242
f5895fd3
JK
243static void do_submodule_path(struct strbuf *buf, const char *path,
244 const char *fmt, va_list args)
0bad611b 245{
0bad611b 246 const char *git_dir;
0bad611b 247
4ef9caf5
NTND
248 strbuf_addstr(buf, path);
249 if (buf->len && buf->buf[buf->len - 1] != '/')
250 strbuf_addch(buf, '/');
251 strbuf_addstr(buf, ".git");
0bad611b 252
4ef9caf5 253 git_dir = read_gitfile(buf->buf);
0bad611b 254 if (git_dir) {
4ef9caf5
NTND
255 strbuf_reset(buf);
256 strbuf_addstr(buf, git_dir);
0bad611b 257 }
4ef9caf5 258 strbuf_addch(buf, '/');
0bad611b 259
4ef9caf5 260 strbuf_vaddf(buf, fmt, args);
4ef9caf5 261 strbuf_cleanup_path(buf);
f5895fd3
JK
262}
263
f5895fd3
JK
264char *git_pathdup_submodule(const char *path, const char *fmt, ...)
265{
266 va_list args;
267 struct strbuf buf = STRBUF_INIT;
268 va_start(args, fmt);
269 do_submodule_path(&buf, path, fmt, args);
270 va_end(args);
271 return strbuf_detach(&buf, NULL);
272}
273
274void strbuf_git_path_submodule(struct strbuf *buf, const char *path,
275 const char *fmt, ...)
276{
277 va_list args;
278 va_start(args, fmt);
279 do_submodule_path(buf, path, fmt, args);
280 va_end(args);
281}
282
c847f537 283int validate_headref(const char *path)
0870ca7f
JH
284{
285 struct stat st;
286 char *buf, buffer[256];
c847f537 287 unsigned char sha1[20];
0104ca09
HO
288 int fd;
289 ssize_t len;
0870ca7f
JH
290
291 if (lstat(path, &st) < 0)
292 return -1;
293
294 /* Make sure it is a "refs/.." symlink */
295 if (S_ISLNK(st.st_mode)) {
296 len = readlink(path, buffer, sizeof(buffer)-1);
222b1673 297 if (len >= 5 && !memcmp("refs/", buffer, 5))
0870ca7f
JH
298 return 0;
299 return -1;
300 }
301
302 /*
303 * Anything else, just open it and try to see if it is a symbolic ref.
304 */
305 fd = open(path, O_RDONLY);
306 if (fd < 0)
307 return -1;
93d26e4c 308 len = read_in_full(fd, buffer, sizeof(buffer)-1);
0870ca7f
JH
309 close(fd);
310
311 /*
312 * Is it a symbolic ref?
313 */
c847f537 314 if (len < 4)
0870ca7f 315 return -1;
c847f537
JH
316 if (!memcmp("ref:", buffer, 4)) {
317 buf = buffer + 4;
318 len -= 4;
319 while (len && isspace(*buf))
320 buf++, len--;
222b1673 321 if (len >= 5 && !memcmp("refs/", buf, 5))
c847f537
JH
322 return 0;
323 }
324
325 /*
326 * Is this a detached HEAD?
327 */
328 if (!get_sha1_hex(buffer, sha1))
0870ca7f 329 return 0;
c847f537 330
0870ca7f
JH
331 return -1;
332}
333
395de250 334static struct passwd *getpw_str(const char *username, size_t len)
54f4b874 335{
d79374c7 336 struct passwd *pw;
5c0b13f8 337 char *username_z = xmemdupz(username, len);
395de250
MM
338 pw = getpwnam(username_z);
339 free(username_z);
340 return pw;
341}
54f4b874 342
395de250
MM
343/*
344 * Return a string with ~ and ~user expanded via getpw*. If buf != NULL,
345 * then it is a newly allocated string. Returns NULL on getpw failure or
346 * if path is NULL.
347 */
348char *expand_user_path(const char *path)
349{
350 struct strbuf user_path = STRBUF_INIT;
395de250
MM
351 const char *to_copy = path;
352
353 if (path == NULL)
354 goto return_null;
355 if (path[0] == '~') {
53ec551c 356 const char *first_slash = strchrnul(path, '/');
395de250
MM
357 const char *username = path + 1;
358 size_t username_len = first_slash - username;
df2a79f4
MM
359 if (username_len == 0) {
360 const char *home = getenv("HOME");
79bf1490
JN
361 if (!home)
362 goto return_null;
cedc61a9 363 strbuf_addstr(&user_path, home);
df2a79f4
MM
364 } else {
365 struct passwd *pw = getpw_str(username, username_len);
366 if (!pw)
367 goto return_null;
cedc61a9 368 strbuf_addstr(&user_path, pw->pw_dir);
54f4b874 369 }
395de250 370 to_copy = first_slash;
d79374c7 371 }
cedc61a9 372 strbuf_addstr(&user_path, to_copy);
395de250
MM
373 return strbuf_detach(&user_path, NULL);
374return_null:
375 strbuf_release(&user_path);
376 return NULL;
54f4b874
AE
377}
378
d79374c7
JH
379/*
380 * First, one directory to try is determined by the following algorithm.
381 *
382 * (0) If "strict" is given, the path is used as given and no DWIM is
383 * done. Otherwise:
384 * (1) "~/path" to mean path under the running user's home directory;
385 * (2) "~user/path" to mean path under named user's home directory;
386 * (3) "relative/path" to mean cwd relative directory; or
387 * (4) "/absolute/path" to mean absolute directory.
388 *
c8c3f1d0
PT
389 * Unless "strict" is given, we check "%s/.git", "%s", "%s.git/.git", "%s.git"
390 * in this order. We select the first one that is a valid git repository, and
391 * chdir() to it. If none match, or we fail to chdir, we return NULL.
d79374c7
JH
392 *
393 * If all goes well, we return the directory we used to chdir() (but
394 * before ~user is expanded), avoiding getcwd() resolving symbolic
395 * links. User relative paths are also returned as they are given,
396 * except DWIM suffixing.
397 */
1c64b48e 398const char *enter_repo(const char *path, int strict)
54f4b874 399{
d79374c7
JH
400 static char used_path[PATH_MAX];
401 static char validated_path[PATH_MAX];
402
403 if (!path)
54f4b874
AE
404 return NULL;
405
d79374c7
JH
406 if (!strict) {
407 static const char *suffix[] = {
b3256eb8 408 "/.git", "", ".git/.git", ".git", NULL,
d79374c7 409 };
03106768 410 const char *gitfile;
d79374c7
JH
411 int len = strlen(path);
412 int i;
1c64b48e 413 while ((1 < len) && (path[len-1] == '/'))
d79374c7 414 len--;
1c64b48e 415
d79374c7 416 if (PATH_MAX <= len)
54f4b874 417 return NULL;
1c64b48e
EFL
418 strncpy(used_path, path, len); used_path[len] = 0 ;
419 strcpy(validated_path, used_path);
420
421 if (used_path[0] == '~') {
422 char *newpath = expand_user_path(used_path);
395de250
MM
423 if (!newpath || (PATH_MAX - 10 < strlen(newpath))) {
424 free(newpath);
d79374c7 425 return NULL;
395de250
MM
426 }
427 /*
428 * Copy back into the static buffer. A pity
429 * since newpath was not bounded, but other
430 * branches of the if are limited by PATH_MAX
431 * anyway.
432 */
433 strcpy(used_path, newpath); free(newpath);
d79374c7
JH
434 }
435 else if (PATH_MAX - 10 < len)
436 return NULL;
1c64b48e 437 len = strlen(used_path);
d79374c7 438 for (i = 0; suffix[i]; i++) {
b3256eb8 439 struct stat st;
1c64b48e 440 strcpy(used_path + len, suffix[i]);
b3256eb8
JK
441 if (!stat(used_path, &st) &&
442 (S_ISREG(st.st_mode) ||
443 (S_ISDIR(st.st_mode) && is_git_directory(used_path)))) {
d79374c7
JH
444 strcat(validated_path, suffix[i]);
445 break;
446 }
447 }
03106768
PH
448 if (!suffix[i])
449 return NULL;
450 gitfile = read_gitfile(used_path) ;
451 if (gitfile)
452 strcpy(used_path, gitfile);
453 if (chdir(used_path))
0870ca7f 454 return NULL;
d79374c7 455 path = validated_path;
0870ca7f 456 }
d79374c7
JH
457 else if (chdir(path))
458 return NULL;
54f4b874 459
d79374c7 460 if (access("objects", X_OK) == 0 && access("refs", X_OK) == 0 &&
c847f537 461 validate_headref("HEAD") == 0) {
717c3972 462 set_git_dir(".");
1644162a 463 check_repository_format();
d79374c7 464 return path;
54f4b874
AE
465 }
466
467 return NULL;
468}
138086a7 469
cbe43b84 470static int calc_shared_perm(int mode)
138086a7 471{
cbe43b84 472 int tweak;
138086a7 473
5a688fe4 474 if (shared_repository < 0)
cbe43b84 475 tweak = -shared_repository;
5a688fe4 476 else
cbe43b84 477 tweak = shared_repository;
5a688fe4
JH
478
479 if (!(mode & S_IWUSR))
480 tweak &= ~0222;
481 if (mode & S_IXUSR)
482 /* Copy read bits to execute bits */
483 tweak |= (tweak & 0444) >> 2;
484 if (shared_repository < 0)
485 mode = (mode & ~0777) | tweak;
486 else
8c6202d8 487 mode |= tweak;
06cbe855 488
cbe43b84
TB
489 return mode;
490}
491
492
493int adjust_shared_perm(const char *path)
494{
495 int old_mode, new_mode;
496
497 if (!shared_repository)
498 return 0;
499 if (get_st_mode_bits(path, &old_mode) < 0)
500 return -1;
501
502 new_mode = calc_shared_perm(old_mode);
503 if (S_ISDIR(old_mode)) {
06cbe855 504 /* Copy read bits to execute bits */
cbe43b84
TB
505 new_mode |= (new_mode & 0444) >> 2;
506 new_mode |= FORCE_DIR_SET_GID;
06cbe855
HO
507 }
508
cbe43b84
TB
509 if (((old_mode ^ new_mode) & ~S_IFMT) &&
510 chmod(path, (new_mode & ~S_IFMT)) < 0)
138086a7
JH
511 return -2;
512 return 0;
513}
e5392c51 514
7fbd4221
JX
515static int have_same_root(const char *path1, const char *path2)
516{
517 int is_abs1, is_abs2;
518
519 is_abs1 = is_absolute_path(path1);
520 is_abs2 = is_absolute_path(path2);
521 return (is_abs1 && is_abs2 && tolower(path1[0]) == tolower(path2[0])) ||
522 (!is_abs1 && !is_abs2);
523}
524
e02ca72f
JX
525/*
526 * Give path as relative to prefix.
527 *
528 * The strbuf may or may not be used, so do not assume it contains the
529 * returned path.
530 */
531const char *relative_path(const char *in, const char *prefix,
532 struct strbuf *sb)
044bbbcb 533{
e02ca72f
JX
534 int in_len = in ? strlen(in) : 0;
535 int prefix_len = prefix ? strlen(prefix) : 0;
536 int in_off = 0;
537 int prefix_off = 0;
288123f0
JH
538 int i = 0, j = 0;
539
e02ca72f
JX
540 if (!in_len)
541 return "./";
542 else if (!prefix_len)
543 return in;
544
7fbd4221
JX
545 if (have_same_root(in, prefix)) {
546 /* bypass dos_drive, for "c:" is identical to "C:" */
547 if (has_dos_drive_prefix(in)) {
548 i = 2;
549 j = 2;
550 }
551 } else {
552 return in;
553 }
554
e02ca72f
JX
555 while (i < prefix_len && j < in_len && prefix[i] == in[j]) {
556 if (is_dir_sep(prefix[i])) {
557 while (is_dir_sep(prefix[i]))
288123f0 558 i++;
e02ca72f
JX
559 while (is_dir_sep(in[j]))
560 j++;
561 prefix_off = i;
562 in_off = j;
563 } else {
564 i++;
565 j++;
566 }
567 }
568
569 if (
570 /* "prefix" seems like prefix of "in" */
571 i >= prefix_len &&
572 /*
573 * but "/foo" is not a prefix of "/foobar"
574 * (i.e. prefix not end with '/')
575 */
576 prefix_off < prefix_len) {
577 if (j >= in_len) {
578 /* in="/a/b", prefix="/a/b" */
579 in_off = in_len;
580 } else if (is_dir_sep(in[j])) {
581 /* in="/a/b/c", prefix="/a/b" */
582 while (is_dir_sep(in[j]))
288123f0 583 j++;
e02ca72f
JX
584 in_off = j;
585 } else {
586 /* in="/a/bbb/c", prefix="/a/b" */
587 i = prefix_off;
588 }
589 } else if (
590 /* "in" is short than "prefix" */
591 j >= in_len &&
592 /* "in" not end with '/' */
593 in_off < in_len) {
594 if (is_dir_sep(prefix[i])) {
595 /* in="/a/b", prefix="/a/b/c/" */
596 while (is_dir_sep(prefix[i]))
597 i++;
598 in_off = in_len;
599 }
600 }
601 in += in_off;
602 in_len -= in_off;
603
604 if (i >= prefix_len) {
605 if (!in_len)
606 return "./";
607 else
608 return in;
609 }
610
611 strbuf_reset(sb);
612 strbuf_grow(sb, in_len);
613
614 while (i < prefix_len) {
615 if (is_dir_sep(prefix[i])) {
616 strbuf_addstr(sb, "../");
617 while (is_dir_sep(prefix[i]))
618 i++;
288123f0 619 continue;
288123f0
JH
620 }
621 i++;
288123f0 622 }
e02ca72f
JX
623 if (!is_dir_sep(prefix[prefix_len - 1]))
624 strbuf_addstr(sb, "../");
625
626 strbuf_addstr(sb, in);
627
628 return sb->buf;
044bbbcb 629}
ae299be0 630
41894ae3
JX
631/*
632 * A simpler implementation of relative_path
633 *
634 * Get relative path by removing "prefix" from "in". This function
635 * first appears in v1.5.6-1-g044bbbc, and makes git_dir shorter
636 * to increase performance when traversing the path to work_tree.
637 */
638const char *remove_leading_path(const char *in, const char *prefix)
639{
640 static char buf[PATH_MAX + 1];
641 int i = 0, j = 0;
642
643 if (!prefix || !prefix[0])
644 return in;
645 while (prefix[i]) {
646 if (is_dir_sep(prefix[i])) {
647 if (!is_dir_sep(in[j]))
648 return in;
649 while (is_dir_sep(prefix[i]))
650 i++;
651 while (is_dir_sep(in[j]))
652 j++;
653 continue;
654 } else if (in[j] != prefix[i]) {
655 return in;
656 }
657 i++;
658 j++;
659 }
660 if (
661 /* "/foo" is a prefix of "/foo" */
662 in[j] &&
663 /* "/foo" is not a prefix of "/foobar" */
664 !is_dir_sep(prefix[i-1]) && !is_dir_sep(in[j])
665 )
666 return in;
667 while (is_dir_sep(in[j]))
668 j++;
669 if (!in[j])
670 strcpy(buf, ".");
671 else
672 strcpy(buf, in + j);
673 return buf;
674}
675
ae299be0 676/*
f2a782b8 677 * It is okay if dst == src, but they should not overlap otherwise.
ae299be0 678 *
f2a782b8
JS
679 * Performs the following normalizations on src, storing the result in dst:
680 * - Ensures that components are separated by '/' (Windows only)
681 * - Squashes sequences of '/'.
ae299be0
DR
682 * - Removes "." components.
683 * - Removes ".." components, and the components the precede them.
f2a782b8
JS
684 * Returns failure (non-zero) if a ".." component appears as first path
685 * component anytime during the normalization. Otherwise, returns success (0).
ae299be0
DR
686 *
687 * Note that this function is purely textual. It does not follow symlinks,
688 * verify the existence of the path, or make any system calls.
645a29c4
NTND
689 *
690 * prefix_len != NULL is for a specific case of prefix_pathspec():
691 * assume that src == dst and src[0..prefix_len-1] is already
692 * normalized, any time "../" eats up to the prefix_len part,
693 * prefix_len is reduced. In the end prefix_len is the remaining
694 * prefix that has not been overridden by user pathspec.
ae299be0 695 */
645a29c4 696int normalize_path_copy_len(char *dst, const char *src, int *prefix_len)
ae299be0 697{
f3cad0ad 698 char *dst0;
ae299be0 699
f3cad0ad
JS
700 if (has_dos_drive_prefix(src)) {
701 *dst++ = *src++;
702 *dst++ = *src++;
ae299be0 703 }
f3cad0ad 704 dst0 = dst;
ae299be0 705
f3cad0ad 706 if (is_dir_sep(*src)) {
ae299be0 707 *dst++ = '/';
f3cad0ad
JS
708 while (is_dir_sep(*src))
709 src++;
710 }
711
712 for (;;) {
713 char c = *src;
714
715 /*
716 * A path component that begins with . could be
717 * special:
718 * (1) "." and ends -- ignore and terminate.
719 * (2) "./" -- ignore them, eat slash and continue.
720 * (3) ".." and ends -- strip one and terminate.
721 * (4) "../" -- strip one, eat slash and continue.
722 */
723 if (c == '.') {
724 if (!src[1]) {
725 /* (1) */
726 src++;
727 } else if (is_dir_sep(src[1])) {
728 /* (2) */
729 src += 2;
730 while (is_dir_sep(*src))
731 src++;
732 continue;
733 } else if (src[1] == '.') {
734 if (!src[2]) {
735 /* (3) */
736 src += 2;
737 goto up_one;
738 } else if (is_dir_sep(src[2])) {
739 /* (4) */
740 src += 3;
741 while (is_dir_sep(*src))
742 src++;
743 goto up_one;
744 }
745 }
746 }
ae299be0 747
f3cad0ad
JS
748 /* copy up to the next '/', and eat all '/' */
749 while ((c = *src++) != '\0' && !is_dir_sep(c))
750 *dst++ = c;
751 if (is_dir_sep(c)) {
752 *dst++ = '/';
753 while (is_dir_sep(c))
754 c = *src++;
755 src--;
756 } else if (!c)
757 break;
758 continue;
759
760 up_one:
761 /*
762 * dst0..dst is prefix portion, and dst[-1] is '/';
763 * go up one level.
764 */
f42302b4
JS
765 dst--; /* go to trailing '/' */
766 if (dst <= dst0)
f3cad0ad 767 return -1;
f42302b4
JS
768 /* Windows: dst[-1] cannot be backslash anymore */
769 while (dst0 < dst && dst[-1] != '/')
770 dst--;
645a29c4
NTND
771 if (prefix_len && *prefix_len > dst - dst0)
772 *prefix_len = dst - dst0;
f3cad0ad 773 }
ae299be0 774 *dst = '\0';
f3cad0ad 775 return 0;
ae299be0 776}
0454dd93 777
645a29c4
NTND
778int normalize_path_copy(char *dst, const char *src)
779{
780 return normalize_path_copy_len(dst, src, NULL);
781}
782
0454dd93
DR
783/*
784 * path = Canonical absolute path
9e2326c7
MH
785 * prefixes = string_list containing normalized, absolute paths without
786 * trailing slashes (except for the root directory, which is denoted by "/").
0454dd93 787 *
9e2326c7 788 * Determines, for each path in prefixes, whether the "prefix"
0454dd93
DR
789 * is an ancestor directory of path. Returns the length of the longest
790 * ancestor directory, excluding any trailing slashes, or -1 if no prefix
31171d9e
MH
791 * is an ancestor. (Note that this means 0 is returned if prefixes is
792 * ["/"].) "/foo" is not considered an ancestor of "/foobar". Directories
0454dd93
DR
793 * are not considered to be their own ancestors. path must be in a
794 * canonical form: empty components, or "." or ".." components are not
9e2326c7 795 * allowed.
0454dd93 796 */
31171d9e 797int longest_ancestor_length(const char *path, struct string_list *prefixes)
0454dd93 798{
a5ccdbe4 799 int i, max_len = -1;
0454dd93 800
31171d9e 801 if (!strcmp(path, "/"))
0454dd93
DR
802 return -1;
803
31171d9e
MH
804 for (i = 0; i < prefixes->nr; i++) {
805 const char *ceil = prefixes->items[i].string;
a5ccdbe4
MH
806 int len = strlen(ceil);
807
9e2326c7
MH
808 if (len == 1 && ceil[0] == '/')
809 len = 0; /* root matches anything, with length 0 */
810 else if (!strncmp(path, ceil, len) && path[len] == '/')
811 ; /* match of length len */
812 else
813 continue; /* no match */
0454dd93 814
9e2326c7 815 if (len > max_len)
0454dd93 816 max_len = len;
0454dd93
DR
817 }
818
819 return max_len;
820}
4fcc86b0
JS
821
822/* strip arbitrary amount of directory separators at end of path */
823static inline int chomp_trailing_dir_sep(const char *path, int len)
824{
825 while (len && is_dir_sep(path[len - 1]))
826 len--;
827 return len;
828}
829
830/*
831 * If path ends with suffix (complete path components), returns the
832 * part before suffix (sans trailing directory separators).
833 * Otherwise returns NULL.
834 */
835char *strip_path_suffix(const char *path, const char *suffix)
836{
837 int path_len = strlen(path), suffix_len = strlen(suffix);
838
839 while (suffix_len) {
840 if (!path_len)
841 return NULL;
842
843 if (is_dir_sep(path[path_len - 1])) {
844 if (!is_dir_sep(suffix[suffix_len - 1]))
845 return NULL;
846 path_len = chomp_trailing_dir_sep(path, path_len);
847 suffix_len = chomp_trailing_dir_sep(suffix, suffix_len);
848 }
849 else if (path[--path_len] != suffix[--suffix_len])
850 return NULL;
851 }
852
853 if (path_len && !is_dir_sep(path[path_len - 1]))
854 return NULL;
855 return xstrndup(path, chomp_trailing_dir_sep(path, path_len));
856}
34b6cb8b
SP
857
858int daemon_avoid_alias(const char *p)
859{
860 int sl, ndot;
861
862 /*
863 * This resurrects the belts and suspenders paranoia check by HPA
864 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
9517e6b8 865 * does not do getcwd() based path canonicalization.
34b6cb8b
SP
866 *
867 * sl becomes true immediately after seeing '/' and continues to
868 * be true as long as dots continue after that without intervening
869 * non-dot character.
870 */
871 if (!p || (*p != '/' && *p != '~'))
872 return -1;
873 sl = 1; ndot = 0;
874 p++;
875
876 while (1) {
877 char ch = *p++;
878 if (sl) {
879 if (ch == '.')
880 ndot++;
881 else if (ch == '/') {
882 if (ndot < 3)
883 /* reject //, /./ and /../ */
884 return -1;
885 ndot = 0;
886 }
887 else if (ch == 0) {
888 if (0 < ndot && ndot < 3)
889 /* reject /.$ and /..$ */
890 return -1;
891 return 0;
892 }
893 else
894 sl = ndot = 0;
895 }
896 else if (ch == 0)
897 return 0;
898 else if (ch == '/') {
899 sl = 1;
900 ndot = 0;
901 }
902 }
903}
4bb43de2 904
1d1d69bc
JS
905static int only_spaces_and_periods(const char *path, size_t len, size_t skip)
906{
907 if (len < skip)
908 return 0;
909 len -= skip;
910 path += skip;
911 while (len-- > 0) {
912 char c = *(path++);
913 if (c != ' ' && c != '.')
914 return 0;
915 }
916 return 1;
917}
918
919int is_ntfs_dotgit(const char *name)
920{
921 int len;
922
923 for (len = 0; ; len++)
924 if (!name[len] || name[len] == '\\' || is_dir_sep(name[len])) {
925 if (only_spaces_and_periods(name, len, 4) &&
926 !strncasecmp(name, ".git", 4))
927 return 1;
928 if (only_spaces_and_periods(name, len, 5) &&
929 !strncasecmp(name, "git~1", 5))
930 return 1;
931 if (name[len] != '\\')
932 return 0;
933 name += len + 1;
934 len = -1;
935 }
936}
ea19289b
PT
937
938char *xdg_config_home(const char *filename)
939{
940 const char *home, *config_home;
941
942 assert(filename);
943 config_home = getenv("XDG_CONFIG_HOME");
944 if (config_home && *config_home)
945 return mkpathdup("%s/git/%s", config_home, filename);
946
947 home = getenv("HOME");
948 if (home)
949 return mkpathdup("%s/.config/git/%s", home, filename);
950 return NULL;
951}
f932729c
JK
952
953GIT_PATH_FUNC(git_path_cherry_pick_head, "CHERRY_PICK_HEAD")
954GIT_PATH_FUNC(git_path_revert_head, "REVERT_HEAD")
955GIT_PATH_FUNC(git_path_squash_msg, "SQUASH_MSG")
956GIT_PATH_FUNC(git_path_merge_msg, "MERGE_MSG")
957GIT_PATH_FUNC(git_path_merge_rr, "MERGE_RR")
958GIT_PATH_FUNC(git_path_merge_mode, "MERGE_MODE")
959GIT_PATH_FUNC(git_path_merge_head, "MERGE_HEAD")
960GIT_PATH_FUNC(git_path_fetch_head, "FETCH_HEAD")
961GIT_PATH_FUNC(git_path_shallow, "shallow")