]> git.ipfire.org Git - thirdparty/git.git/blame - path.c
completion: support 'git config --local'
[thirdparty/git.git] / path.c
CommitLineData
26c8a533
LT
1/*
2 * I'm tired of doing "vsnprintf()" etc just to open a
3 * file, so here's a "return static buffer with printf"
4 * interface for paths.
5 *
6 * It's obviously not thread-safe. Sue me. But it's quite
7 * useful for doing things like
8 *
9 * f = open(mkpath("%s/%s.git", base, name), O_RDONLY);
10 *
11 * which is what it's designed for.
12 */
13#include "cache.h"
395de250 14#include "strbuf.h"
a5ccdbe4 15#include "string-list.h"
26c8a533 16
26c8a533
LT
17static char bad_path[] = "/bad-path/";
18
e7676d2f
LT
19static char *get_pathname(void)
20{
21 static char pathname_array[4][PATH_MAX];
22 static int index;
23 return pathname_array[3 & ++index];
24}
25
26c8a533
LT
26static char *cleanup_path(char *path)
27{
28 /* Clean it up */
29 if (!memcmp(path, "./", 2)) {
30 path += 2;
31 while (*path == '/')
32 path++;
33 }
34 return path;
35}
36
108bebea
AR
37char *mksnpath(char *buf, size_t n, const char *fmt, ...)
38{
39 va_list args;
40 unsigned len;
41
42 va_start(args, fmt);
43 len = vsnprintf(buf, n, fmt, args);
44 va_end(args);
45 if (len >= n) {
9db56f71 46 strlcpy(buf, bad_path, n);
108bebea
AR
47 return buf;
48 }
49 return cleanup_path(buf);
50}
51
5b3b8fa2 52static char *vsnpath(char *buf, size_t n, const char *fmt, va_list args)
fe2d7776
AR
53{
54 const char *git_dir = get_git_dir();
fe2d7776
AR
55 size_t len;
56
57 len = strlen(git_dir);
58 if (n < len + 1)
59 goto bad;
60 memcpy(buf, git_dir, len);
61 if (len && !is_dir_sep(git_dir[len-1]))
62 buf[len++] = '/';
fe2d7776 63 len += vsnprintf(buf + len, n - len, fmt, args);
fe2d7776
AR
64 if (len >= n)
65 goto bad;
66 return cleanup_path(buf);
67bad:
9db56f71 68 strlcpy(buf, bad_path, n);
fe2d7776
AR
69 return buf;
70}
71
aba13e7c
AR
72char *git_snpath(char *buf, size_t n, const char *fmt, ...)
73{
66a51a9a 74 char *ret;
aba13e7c
AR
75 va_list args;
76 va_start(args, fmt);
66a51a9a 77 ret = vsnpath(buf, n, fmt, args);
aba13e7c 78 va_end(args);
66a51a9a 79 return ret;
aba13e7c
AR
80}
81
82char *git_pathdup(const char *fmt, ...)
83{
66a51a9a 84 char path[PATH_MAX], *ret;
aba13e7c
AR
85 va_list args;
86 va_start(args, fmt);
66a51a9a 87 ret = vsnpath(path, sizeof(path), fmt, args);
aba13e7c 88 va_end(args);
66a51a9a 89 return xstrdup(ret);
aba13e7c
AR
90}
91
21cf3227
HKNN
92char *mkpathdup(const char *fmt, ...)
93{
94 char *path;
95 struct strbuf sb = STRBUF_INIT;
96 va_list args;
97
98 va_start(args, fmt);
99 strbuf_vaddf(&sb, fmt, args);
100 va_end(args);
101 path = xstrdup(cleanup_path(sb.buf));
102
103 strbuf_release(&sb);
104 return path;
105}
106
26c8a533
LT
107char *mkpath(const char *fmt, ...)
108{
109 va_list args;
110 unsigned len;
e7676d2f 111 char *pathname = get_pathname();
26c8a533
LT
112
113 va_start(args, fmt);
114 len = vsnprintf(pathname, PATH_MAX, fmt, args);
115 va_end(args);
116 if (len >= PATH_MAX)
117 return bad_path;
118 return cleanup_path(pathname);
119}
120
121char *git_path(const char *fmt, ...)
122{
e7676d2f 123 char *pathname = get_pathname();
26c8a533 124 va_list args;
5c44252e 125 char *ret;
26c8a533 126
26c8a533 127 va_start(args, fmt);
5c44252e 128 ret = vsnpath(pathname, PATH_MAX, fmt, args);
26c8a533 129 va_end(args);
5c44252e 130 return ret;
26c8a533 131}
f2db68ed 132
21cf3227
HKNN
133void home_config_paths(char **global, char **xdg, char *file)
134{
135 char *xdg_home = getenv("XDG_CONFIG_HOME");
136 char *home = getenv("HOME");
137 char *to_free = NULL;
138
139 if (!home) {
140 if (global)
141 *global = NULL;
142 } else {
143 if (!xdg_home) {
144 to_free = mkpathdup("%s/.config", home);
145 xdg_home = to_free;
146 }
147 if (global)
148 *global = mkpathdup("%s/.gitconfig", home);
149 }
150
151 if (!xdg_home)
152 *xdg = NULL;
153 else
154 *xdg = mkpathdup("%s/git/%s", xdg_home, file);
155
156 free(to_free);
157}
158
0bad611b
HV
159char *git_path_submodule(const char *path, const char *fmt, ...)
160{
161 char *pathname = get_pathname();
162 struct strbuf buf = STRBUF_INIT;
163 const char *git_dir;
164 va_list args;
165 unsigned len;
166
167 len = strlen(path);
168 if (len > PATH_MAX-100)
169 return bad_path;
170
171 strbuf_addstr(&buf, path);
172 if (len && path[len-1] != '/')
173 strbuf_addch(&buf, '/');
174 strbuf_addstr(&buf, ".git");
175
13d6ec91 176 git_dir = read_gitfile(buf.buf);
0bad611b
HV
177 if (git_dir) {
178 strbuf_reset(&buf);
179 strbuf_addstr(&buf, git_dir);
180 }
181 strbuf_addch(&buf, '/');
182
183 if (buf.len >= PATH_MAX)
184 return bad_path;
185 memcpy(pathname, buf.buf, buf.len + 1);
186
187 strbuf_release(&buf);
188 len = strlen(pathname);
189
190 va_start(args, fmt);
191 len += vsnprintf(pathname + len, PATH_MAX - len, fmt, args);
192 va_end(args);
193 if (len >= PATH_MAX)
194 return bad_path;
195 return cleanup_path(pathname);
196}
f2db68ed 197
c847f537 198int validate_headref(const char *path)
0870ca7f
JH
199{
200 struct stat st;
201 char *buf, buffer[256];
c847f537 202 unsigned char sha1[20];
0104ca09
HO
203 int fd;
204 ssize_t len;
0870ca7f
JH
205
206 if (lstat(path, &st) < 0)
207 return -1;
208
209 /* Make sure it is a "refs/.." symlink */
210 if (S_ISLNK(st.st_mode)) {
211 len = readlink(path, buffer, sizeof(buffer)-1);
222b1673 212 if (len >= 5 && !memcmp("refs/", buffer, 5))
0870ca7f
JH
213 return 0;
214 return -1;
215 }
216
217 /*
218 * Anything else, just open it and try to see if it is a symbolic ref.
219 */
220 fd = open(path, O_RDONLY);
221 if (fd < 0)
222 return -1;
93d26e4c 223 len = read_in_full(fd, buffer, sizeof(buffer)-1);
0870ca7f
JH
224 close(fd);
225
226 /*
227 * Is it a symbolic ref?
228 */
c847f537 229 if (len < 4)
0870ca7f 230 return -1;
c847f537
JH
231 if (!memcmp("ref:", buffer, 4)) {
232 buf = buffer + 4;
233 len -= 4;
234 while (len && isspace(*buf))
235 buf++, len--;
222b1673 236 if (len >= 5 && !memcmp("refs/", buf, 5))
c847f537
JH
237 return 0;
238 }
239
240 /*
241 * Is this a detached HEAD?
242 */
243 if (!get_sha1_hex(buffer, sha1))
0870ca7f 244 return 0;
c847f537 245
0870ca7f
JH
246 return -1;
247}
248
395de250 249static struct passwd *getpw_str(const char *username, size_t len)
54f4b874 250{
d79374c7 251 struct passwd *pw;
395de250
MM
252 char *username_z = xmalloc(len + 1);
253 memcpy(username_z, username, len);
254 username_z[len] = '\0';
255 pw = getpwnam(username_z);
256 free(username_z);
257 return pw;
258}
54f4b874 259
395de250
MM
260/*
261 * Return a string with ~ and ~user expanded via getpw*. If buf != NULL,
262 * then it is a newly allocated string. Returns NULL on getpw failure or
263 * if path is NULL.
264 */
265char *expand_user_path(const char *path)
266{
267 struct strbuf user_path = STRBUF_INIT;
268 const char *first_slash = strchrnul(path, '/');
269 const char *to_copy = path;
270
271 if (path == NULL)
272 goto return_null;
273 if (path[0] == '~') {
274 const char *username = path + 1;
275 size_t username_len = first_slash - username;
df2a79f4
MM
276 if (username_len == 0) {
277 const char *home = getenv("HOME");
79bf1490
JN
278 if (!home)
279 goto return_null;
df2a79f4
MM
280 strbuf_add(&user_path, home, strlen(home));
281 } else {
282 struct passwd *pw = getpw_str(username, username_len);
283 if (!pw)
284 goto return_null;
285 strbuf_add(&user_path, pw->pw_dir, strlen(pw->pw_dir));
54f4b874 286 }
395de250 287 to_copy = first_slash;
d79374c7 288 }
395de250
MM
289 strbuf_add(&user_path, to_copy, strlen(to_copy));
290 return strbuf_detach(&user_path, NULL);
291return_null:
292 strbuf_release(&user_path);
293 return NULL;
54f4b874
AE
294}
295
d79374c7
JH
296/*
297 * First, one directory to try is determined by the following algorithm.
298 *
299 * (0) If "strict" is given, the path is used as given and no DWIM is
300 * done. Otherwise:
301 * (1) "~/path" to mean path under the running user's home directory;
302 * (2) "~user/path" to mean path under named user's home directory;
303 * (3) "relative/path" to mean cwd relative directory; or
304 * (4) "/absolute/path" to mean absolute directory.
305 *
306 * Unless "strict" is given, we try access() for existence of "%s.git/.git",
307 * "%s/.git", "%s.git", "%s" in this order. The first one that exists is
308 * what we try.
309 *
310 * Second, we try chdir() to that. Upon failure, we return NULL.
311 *
312 * Then, we try if the current directory is a valid git repository.
313 * Upon failure, we return NULL.
314 *
315 * If all goes well, we return the directory we used to chdir() (but
316 * before ~user is expanded), avoiding getcwd() resolving symbolic
317 * links. User relative paths are also returned as they are given,
318 * except DWIM suffixing.
319 */
1c64b48e 320const char *enter_repo(const char *path, int strict)
54f4b874 321{
d79374c7
JH
322 static char used_path[PATH_MAX];
323 static char validated_path[PATH_MAX];
324
325 if (!path)
54f4b874
AE
326 return NULL;
327
d79374c7
JH
328 if (!strict) {
329 static const char *suffix[] = {
b3256eb8 330 "/.git", "", ".git/.git", ".git", NULL,
d79374c7 331 };
03106768 332 const char *gitfile;
d79374c7
JH
333 int len = strlen(path);
334 int i;
1c64b48e 335 while ((1 < len) && (path[len-1] == '/'))
d79374c7 336 len--;
1c64b48e 337
d79374c7 338 if (PATH_MAX <= len)
54f4b874 339 return NULL;
1c64b48e
EFL
340 strncpy(used_path, path, len); used_path[len] = 0 ;
341 strcpy(validated_path, used_path);
342
343 if (used_path[0] == '~') {
344 char *newpath = expand_user_path(used_path);
395de250
MM
345 if (!newpath || (PATH_MAX - 10 < strlen(newpath))) {
346 free(newpath);
d79374c7 347 return NULL;
395de250
MM
348 }
349 /*
350 * Copy back into the static buffer. A pity
351 * since newpath was not bounded, but other
352 * branches of the if are limited by PATH_MAX
353 * anyway.
354 */
355 strcpy(used_path, newpath); free(newpath);
d79374c7
JH
356 }
357 else if (PATH_MAX - 10 < len)
358 return NULL;
1c64b48e 359 len = strlen(used_path);
d79374c7 360 for (i = 0; suffix[i]; i++) {
b3256eb8 361 struct stat st;
1c64b48e 362 strcpy(used_path + len, suffix[i]);
b3256eb8
JK
363 if (!stat(used_path, &st) &&
364 (S_ISREG(st.st_mode) ||
365 (S_ISDIR(st.st_mode) && is_git_directory(used_path)))) {
d79374c7
JH
366 strcat(validated_path, suffix[i]);
367 break;
368 }
369 }
03106768
PH
370 if (!suffix[i])
371 return NULL;
372 gitfile = read_gitfile(used_path) ;
373 if (gitfile)
374 strcpy(used_path, gitfile);
375 if (chdir(used_path))
0870ca7f 376 return NULL;
d79374c7 377 path = validated_path;
0870ca7f 378 }
d79374c7
JH
379 else if (chdir(path))
380 return NULL;
54f4b874 381
d79374c7 382 if (access("objects", X_OK) == 0 && access("refs", X_OK) == 0 &&
c847f537 383 validate_headref("HEAD") == 0) {
717c3972 384 set_git_dir(".");
1644162a 385 check_repository_format();
d79374c7 386 return path;
54f4b874
AE
387 }
388
389 return NULL;
390}
138086a7 391
17e61b82 392int set_shared_perm(const char *path, int mode)
138086a7
JH
393{
394 struct stat st;
17e61b82 395 int tweak, shared, orig_mode;
138086a7 396
17e61b82
JH
397 if (!shared_repository) {
398 if (mode)
399 return chmod(path, mode & ~S_IFMT);
138086a7 400 return 0;
17e61b82
JH
401 }
402 if (!mode) {
403 if (lstat(path, &st) < 0)
404 return -1;
405 mode = st.st_mode;
406 orig_mode = mode;
407 } else
408 orig_mode = 0;
5a688fe4
JH
409 if (shared_repository < 0)
410 shared = -shared_repository;
411 else
412 shared = shared_repository;
413 tweak = shared;
414
415 if (!(mode & S_IWUSR))
416 tweak &= ~0222;
417 if (mode & S_IXUSR)
418 /* Copy read bits to execute bits */
419 tweak |= (tweak & 0444) >> 2;
420 if (shared_repository < 0)
421 mode = (mode & ~0777) | tweak;
422 else
8c6202d8 423 mode |= tweak;
06cbe855
HO
424
425 if (S_ISDIR(mode)) {
06cbe855 426 /* Copy read bits to execute bits */
5a688fe4
JH
427 mode |= (shared & 0444) >> 2;
428 mode |= FORCE_DIR_SET_GID;
06cbe855
HO
429 }
430
5a688fe4 431 if (((shared_repository < 0
17e61b82
JH
432 ? (orig_mode & (FORCE_DIR_SET_GID | 0777))
433 : (orig_mode & mode)) != mode) &&
434 chmod(path, (mode & ~S_IFMT)) < 0)
138086a7
JH
435 return -2;
436 return 0;
437}
e5392c51 438
e2a57aac 439const char *relative_path(const char *abs, const char *base)
044bbbcb
LT
440{
441 static char buf[PATH_MAX + 1];
288123f0
JH
442 int i = 0, j = 0;
443
444 if (!base || !base[0])
044bbbcb 445 return abs;
288123f0
JH
446 while (base[i]) {
447 if (is_dir_sep(base[i])) {
448 if (!is_dir_sep(abs[j]))
449 return abs;
450 while (is_dir_sep(base[i]))
451 i++;
452 while (is_dir_sep(abs[j]))
453 j++;
454 continue;
455 } else if (abs[j] != base[i]) {
456 return abs;
457 }
458 i++;
459 j++;
460 }
461 if (
462 /* "/foo" is a prefix of "/foo" */
463 abs[j] &&
464 /* "/foo" is not a prefix of "/foobar" */
465 !is_dir_sep(base[i-1]) && !is_dir_sep(abs[j])
466 )
044bbbcb 467 return abs;
288123f0
JH
468 while (is_dir_sep(abs[j]))
469 j++;
470 if (!abs[j])
471 strcpy(buf, ".");
472 else
473 strcpy(buf, abs + j);
044bbbcb
LT
474 return buf;
475}
ae299be0
DR
476
477/*
f2a782b8 478 * It is okay if dst == src, but they should not overlap otherwise.
ae299be0 479 *
f2a782b8
JS
480 * Performs the following normalizations on src, storing the result in dst:
481 * - Ensures that components are separated by '/' (Windows only)
482 * - Squashes sequences of '/'.
ae299be0
DR
483 * - Removes "." components.
484 * - Removes ".." components, and the components the precede them.
f2a782b8
JS
485 * Returns failure (non-zero) if a ".." component appears as first path
486 * component anytime during the normalization. Otherwise, returns success (0).
ae299be0
DR
487 *
488 * Note that this function is purely textual. It does not follow symlinks,
489 * verify the existence of the path, or make any system calls.
490 */
f3cad0ad 491int normalize_path_copy(char *dst, const char *src)
ae299be0 492{
f3cad0ad 493 char *dst0;
ae299be0 494
f3cad0ad
JS
495 if (has_dos_drive_prefix(src)) {
496 *dst++ = *src++;
497 *dst++ = *src++;
ae299be0 498 }
f3cad0ad 499 dst0 = dst;
ae299be0 500
f3cad0ad 501 if (is_dir_sep(*src)) {
ae299be0 502 *dst++ = '/';
f3cad0ad
JS
503 while (is_dir_sep(*src))
504 src++;
505 }
506
507 for (;;) {
508 char c = *src;
509
510 /*
511 * A path component that begins with . could be
512 * special:
513 * (1) "." and ends -- ignore and terminate.
514 * (2) "./" -- ignore them, eat slash and continue.
515 * (3) ".." and ends -- strip one and terminate.
516 * (4) "../" -- strip one, eat slash and continue.
517 */
518 if (c == '.') {
519 if (!src[1]) {
520 /* (1) */
521 src++;
522 } else if (is_dir_sep(src[1])) {
523 /* (2) */
524 src += 2;
525 while (is_dir_sep(*src))
526 src++;
527 continue;
528 } else if (src[1] == '.') {
529 if (!src[2]) {
530 /* (3) */
531 src += 2;
532 goto up_one;
533 } else if (is_dir_sep(src[2])) {
534 /* (4) */
535 src += 3;
536 while (is_dir_sep(*src))
537 src++;
538 goto up_one;
539 }
540 }
541 }
ae299be0 542
f3cad0ad
JS
543 /* copy up to the next '/', and eat all '/' */
544 while ((c = *src++) != '\0' && !is_dir_sep(c))
545 *dst++ = c;
546 if (is_dir_sep(c)) {
547 *dst++ = '/';
548 while (is_dir_sep(c))
549 c = *src++;
550 src--;
551 } else if (!c)
552 break;
553 continue;
554
555 up_one:
556 /*
557 * dst0..dst is prefix portion, and dst[-1] is '/';
558 * go up one level.
559 */
f42302b4
JS
560 dst--; /* go to trailing '/' */
561 if (dst <= dst0)
f3cad0ad 562 return -1;
f42302b4
JS
563 /* Windows: dst[-1] cannot be backslash anymore */
564 while (dst0 < dst && dst[-1] != '/')
565 dst--;
f3cad0ad 566 }
ae299be0 567 *dst = '\0';
f3cad0ad 568 return 0;
ae299be0 569}
0454dd93
DR
570
571/*
572 * path = Canonical absolute path
9e2326c7
MH
573 * prefixes = string_list containing normalized, absolute paths without
574 * trailing slashes (except for the root directory, which is denoted by "/").
0454dd93 575 *
9e2326c7 576 * Determines, for each path in prefixes, whether the "prefix"
0454dd93
DR
577 * is an ancestor directory of path. Returns the length of the longest
578 * ancestor directory, excluding any trailing slashes, or -1 if no prefix
31171d9e
MH
579 * is an ancestor. (Note that this means 0 is returned if prefixes is
580 * ["/"].) "/foo" is not considered an ancestor of "/foobar". Directories
0454dd93
DR
581 * are not considered to be their own ancestors. path must be in a
582 * canonical form: empty components, or "." or ".." components are not
9e2326c7 583 * allowed.
0454dd93 584 */
31171d9e 585int longest_ancestor_length(const char *path, struct string_list *prefixes)
0454dd93 586{
a5ccdbe4 587 int i, max_len = -1;
0454dd93 588
31171d9e 589 if (!strcmp(path, "/"))
0454dd93
DR
590 return -1;
591
31171d9e
MH
592 for (i = 0; i < prefixes->nr; i++) {
593 const char *ceil = prefixes->items[i].string;
a5ccdbe4
MH
594 int len = strlen(ceil);
595
9e2326c7
MH
596 if (len == 1 && ceil[0] == '/')
597 len = 0; /* root matches anything, with length 0 */
598 else if (!strncmp(path, ceil, len) && path[len] == '/')
599 ; /* match of length len */
600 else
601 continue; /* no match */
0454dd93 602
9e2326c7 603 if (len > max_len)
0454dd93 604 max_len = len;
0454dd93
DR
605 }
606
607 return max_len;
608}
4fcc86b0
JS
609
610/* strip arbitrary amount of directory separators at end of path */
611static inline int chomp_trailing_dir_sep(const char *path, int len)
612{
613 while (len && is_dir_sep(path[len - 1]))
614 len--;
615 return len;
616}
617
618/*
619 * If path ends with suffix (complete path components), returns the
620 * part before suffix (sans trailing directory separators).
621 * Otherwise returns NULL.
622 */
623char *strip_path_suffix(const char *path, const char *suffix)
624{
625 int path_len = strlen(path), suffix_len = strlen(suffix);
626
627 while (suffix_len) {
628 if (!path_len)
629 return NULL;
630
631 if (is_dir_sep(path[path_len - 1])) {
632 if (!is_dir_sep(suffix[suffix_len - 1]))
633 return NULL;
634 path_len = chomp_trailing_dir_sep(path, path_len);
635 suffix_len = chomp_trailing_dir_sep(suffix, suffix_len);
636 }
637 else if (path[--path_len] != suffix[--suffix_len])
638 return NULL;
639 }
640
641 if (path_len && !is_dir_sep(path[path_len - 1]))
642 return NULL;
643 return xstrndup(path, chomp_trailing_dir_sep(path, path_len));
644}
34b6cb8b
SP
645
646int daemon_avoid_alias(const char *p)
647{
648 int sl, ndot;
649
650 /*
651 * This resurrects the belts and suspenders paranoia check by HPA
652 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
9517e6b8 653 * does not do getcwd() based path canonicalization.
34b6cb8b
SP
654 *
655 * sl becomes true immediately after seeing '/' and continues to
656 * be true as long as dots continue after that without intervening
657 * non-dot character.
658 */
659 if (!p || (*p != '/' && *p != '~'))
660 return -1;
661 sl = 1; ndot = 0;
662 p++;
663
664 while (1) {
665 char ch = *p++;
666 if (sl) {
667 if (ch == '.')
668 ndot++;
669 else if (ch == '/') {
670 if (ndot < 3)
671 /* reject //, /./ and /../ */
672 return -1;
673 ndot = 0;
674 }
675 else if (ch == 0) {
676 if (0 < ndot && ndot < 3)
677 /* reject /.$ and /..$ */
678 return -1;
679 return 0;
680 }
681 else
682 sl = ndot = 0;
683 }
684 else if (ch == 0)
685 return 0;
686 else if (ch == '/') {
687 sl = 1;
688 ndot = 0;
689 }
690 }
691}
4bb43de2
NTND
692
693int offset_1st_component(const char *path)
694{
695 if (has_dos_drive_prefix(path))
696 return 2 + is_dir_sep(path[2]);
697 return is_dir_sep(path[0]);
698}