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