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