Expand ~ and ~user in core.excludesfile, commit.template
[alt-git.git] / path.c
blob2470f78d3971acdf6a716e6d743e4fdaa1fc8a55
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.
6 * It's obviously not thread-safe. Sue me. But it's quite
7 * useful for doing things like
9 * f = open(mkpath("%s/%s.git", base, name), O_RDONLY);
11 * which is what it's designed for.
13 #include "cache.h"
14 #include "strbuf.h"
16 static char bad_path[] = "/bad-path/";
18 static char *get_pathname(void)
20 static char pathname_array[4][PATH_MAX];
21 static int index;
22 return pathname_array[3 & ++index];
25 static char *cleanup_path(char *path)
27 /* Clean it up */
28 if (!memcmp(path, "./", 2)) {
29 path += 2;
30 while (*path == '/')
31 path++;
33 return path;
36 char *mksnpath(char *buf, size_t n, const char *fmt, ...)
38 va_list args;
39 unsigned len;
41 va_start(args, fmt);
42 len = vsnprintf(buf, n, fmt, args);
43 va_end(args);
44 if (len >= n) {
45 strlcpy(buf, bad_path, n);
46 return buf;
48 return cleanup_path(buf);
51 static char *git_vsnpath(char *buf, size_t n, const char *fmt, va_list args)
53 const char *git_dir = get_git_dir();
54 size_t len;
56 len = strlen(git_dir);
57 if (n < len + 1)
58 goto bad;
59 memcpy(buf, git_dir, len);
60 if (len && !is_dir_sep(git_dir[len-1]))
61 buf[len++] = '/';
62 len += vsnprintf(buf + len, n - len, fmt, args);
63 if (len >= n)
64 goto bad;
65 return cleanup_path(buf);
66 bad:
67 strlcpy(buf, bad_path, n);
68 return buf;
71 char *git_snpath(char *buf, size_t n, const char *fmt, ...)
73 va_list args;
74 va_start(args, fmt);
75 (void)git_vsnpath(buf, n, fmt, args);
76 va_end(args);
77 return buf;
80 char *git_pathdup(const char *fmt, ...)
82 char path[PATH_MAX];
83 va_list args;
84 va_start(args, fmt);
85 (void)git_vsnpath(path, sizeof(path), fmt, args);
86 va_end(args);
87 return xstrdup(path);
90 char *mkpath(const char *fmt, ...)
92 va_list args;
93 unsigned len;
94 char *pathname = get_pathname();
96 va_start(args, fmt);
97 len = vsnprintf(pathname, PATH_MAX, fmt, args);
98 va_end(args);
99 if (len >= PATH_MAX)
100 return bad_path;
101 return cleanup_path(pathname);
104 char *git_path(const char *fmt, ...)
106 const char *git_dir = get_git_dir();
107 char *pathname = get_pathname();
108 va_list args;
109 unsigned len;
111 len = strlen(git_dir);
112 if (len > PATH_MAX-100)
113 return bad_path;
114 memcpy(pathname, git_dir, len);
115 if (len && git_dir[len-1] != '/')
116 pathname[len++] = '/';
117 va_start(args, fmt);
118 len += vsnprintf(pathname + len, PATH_MAX - len, fmt, args);
119 va_end(args);
120 if (len >= PATH_MAX)
121 return bad_path;
122 return cleanup_path(pathname);
126 /* git_mkstemp() - create tmp file honoring TMPDIR variable */
127 int git_mkstemp(char *path, size_t len, const char *template)
129 const char *tmp;
130 size_t n;
132 tmp = getenv("TMPDIR");
133 if (!tmp)
134 tmp = "/tmp";
135 n = snprintf(path, len, "%s/%s", tmp, template);
136 if (len <= n) {
137 errno = ENAMETOOLONG;
138 return -1;
140 return mkstemp(path);
143 /* git_mkstemps() - create tmp file with suffix honoring TMPDIR variable. */
144 int git_mkstemps(char *path, size_t len, const char *template, int suffix_len)
146 const char *tmp;
147 size_t n;
149 tmp = getenv("TMPDIR");
150 if (!tmp)
151 tmp = "/tmp";
152 n = snprintf(path, len, "%s/%s", tmp, template);
153 if (len <= n) {
154 errno = ENAMETOOLONG;
155 return -1;
157 return mkstemps(path, suffix_len);
160 int validate_headref(const char *path)
162 struct stat st;
163 char *buf, buffer[256];
164 unsigned char sha1[20];
165 int fd;
166 ssize_t len;
168 if (lstat(path, &st) < 0)
169 return -1;
171 /* Make sure it is a "refs/.." symlink */
172 if (S_ISLNK(st.st_mode)) {
173 len = readlink(path, buffer, sizeof(buffer)-1);
174 if (len >= 5 && !memcmp("refs/", buffer, 5))
175 return 0;
176 return -1;
180 * Anything else, just open it and try to see if it is a symbolic ref.
182 fd = open(path, O_RDONLY);
183 if (fd < 0)
184 return -1;
185 len = read_in_full(fd, buffer, sizeof(buffer)-1);
186 close(fd);
189 * Is it a symbolic ref?
191 if (len < 4)
192 return -1;
193 if (!memcmp("ref:", buffer, 4)) {
194 buf = buffer + 4;
195 len -= 4;
196 while (len && isspace(*buf))
197 buf++, len--;
198 if (len >= 5 && !memcmp("refs/", buf, 5))
199 return 0;
203 * Is this a detached HEAD?
205 if (!get_sha1_hex(buffer, sha1))
206 return 0;
208 return -1;
211 static struct passwd *getpw_str(const char *username, size_t len)
213 struct passwd *pw;
214 char *username_z = xmalloc(len + 1);
215 memcpy(username_z, username, len);
216 username_z[len] = '\0';
217 pw = getpwnam(username_z);
218 free(username_z);
219 return pw;
223 * Return a string with ~ and ~user expanded via getpw*. If buf != NULL,
224 * then it is a newly allocated string. Returns NULL on getpw failure or
225 * if path is NULL.
227 char *expand_user_path(const char *path)
229 struct strbuf user_path = STRBUF_INIT;
230 const char *first_slash = strchrnul(path, '/');
231 const char *to_copy = path;
233 if (path == NULL)
234 goto return_null;
235 if (path[0] == '~') {
236 const char *username = path + 1;
237 size_t username_len = first_slash - username;
238 struct passwd *pw = getpw_str(username, username_len);
239 if (!pw)
240 goto return_null;
241 strbuf_add(&user_path, pw->pw_dir, strlen(pw->pw_dir));
242 to_copy = first_slash;
244 strbuf_add(&user_path, to_copy, strlen(to_copy));
245 return strbuf_detach(&user_path, NULL);
246 return_null:
247 strbuf_release(&user_path);
248 return NULL;
252 * First, one directory to try is determined by the following algorithm.
254 * (0) If "strict" is given, the path is used as given and no DWIM is
255 * done. Otherwise:
256 * (1) "~/path" to mean path under the running user's home directory;
257 * (2) "~user/path" to mean path under named user's home directory;
258 * (3) "relative/path" to mean cwd relative directory; or
259 * (4) "/absolute/path" to mean absolute directory.
261 * Unless "strict" is given, we try access() for existence of "%s.git/.git",
262 * "%s/.git", "%s.git", "%s" in this order. The first one that exists is
263 * what we try.
265 * Second, we try chdir() to that. Upon failure, we return NULL.
267 * Then, we try if the current directory is a valid git repository.
268 * Upon failure, we return NULL.
270 * If all goes well, we return the directory we used to chdir() (but
271 * before ~user is expanded), avoiding getcwd() resolving symbolic
272 * links. User relative paths are also returned as they are given,
273 * except DWIM suffixing.
275 char *enter_repo(char *path, int strict)
277 static char used_path[PATH_MAX];
278 static char validated_path[PATH_MAX];
280 if (!path)
281 return NULL;
283 if (!strict) {
284 static const char *suffix[] = {
285 ".git/.git", "/.git", ".git", "", NULL,
287 int len = strlen(path);
288 int i;
289 while ((1 < len) && (path[len-1] == '/')) {
290 path[len-1] = 0;
291 len--;
293 if (PATH_MAX <= len)
294 return NULL;
295 if (path[0] == '~') {
296 char *newpath = expand_user_path(path);
297 if (!newpath || (PATH_MAX - 10 < strlen(newpath))) {
298 free(newpath);
299 return NULL;
302 * Copy back into the static buffer. A pity
303 * since newpath was not bounded, but other
304 * branches of the if are limited by PATH_MAX
305 * anyway.
307 strcpy(used_path, newpath); free(newpath);
308 strcpy(validated_path, path);
309 path = used_path;
311 else if (PATH_MAX - 10 < len)
312 return NULL;
313 else {
314 path = strcpy(used_path, path);
315 strcpy(validated_path, path);
317 len = strlen(path);
318 for (i = 0; suffix[i]; i++) {
319 strcpy(path + len, suffix[i]);
320 if (!access(path, F_OK)) {
321 strcat(validated_path, suffix[i]);
322 break;
325 if (!suffix[i] || chdir(path))
326 return NULL;
327 path = validated_path;
329 else if (chdir(path))
330 return NULL;
332 if (access("objects", X_OK) == 0 && access("refs", X_OK) == 0 &&
333 validate_headref("HEAD") == 0) {
334 setenv(GIT_DIR_ENVIRONMENT, ".", 1);
335 check_repository_format();
336 return path;
339 return NULL;
342 int set_shared_perm(const char *path, int mode)
344 struct stat st;
345 int tweak, shared, orig_mode;
347 if (!shared_repository) {
348 if (mode)
349 return chmod(path, mode & ~S_IFMT);
350 return 0;
352 if (!mode) {
353 if (lstat(path, &st) < 0)
354 return -1;
355 mode = st.st_mode;
356 orig_mode = mode;
357 } else
358 orig_mode = 0;
359 if (shared_repository < 0)
360 shared = -shared_repository;
361 else
362 shared = shared_repository;
363 tweak = shared;
365 if (!(mode & S_IWUSR))
366 tweak &= ~0222;
367 if (mode & S_IXUSR)
368 /* Copy read bits to execute bits */
369 tweak |= (tweak & 0444) >> 2;
370 if (shared_repository < 0)
371 mode = (mode & ~0777) | tweak;
372 else
373 mode |= tweak;
375 if (S_ISDIR(mode)) {
376 /* Copy read bits to execute bits */
377 mode |= (shared & 0444) >> 2;
378 mode |= FORCE_DIR_SET_GID;
381 if (((shared_repository < 0
382 ? (orig_mode & (FORCE_DIR_SET_GID | 0777))
383 : (orig_mode & mode)) != mode) &&
384 chmod(path, (mode & ~S_IFMT)) < 0)
385 return -2;
386 return 0;
389 const char *make_relative_path(const char *abs, const char *base)
391 static char buf[PATH_MAX + 1];
392 int baselen;
393 if (!base)
394 return abs;
395 baselen = strlen(base);
396 if (prefixcmp(abs, base))
397 return abs;
398 if (abs[baselen] == '/')
399 baselen++;
400 else if (base[baselen - 1] != '/')
401 return abs;
402 strcpy(buf, abs + baselen);
403 return buf;
407 * It is okay if dst == src, but they should not overlap otherwise.
409 * Performs the following normalizations on src, storing the result in dst:
410 * - Ensures that components are separated by '/' (Windows only)
411 * - Squashes sequences of '/'.
412 * - Removes "." components.
413 * - Removes ".." components, and the components the precede them.
414 * Returns failure (non-zero) if a ".." component appears as first path
415 * component anytime during the normalization. Otherwise, returns success (0).
417 * Note that this function is purely textual. It does not follow symlinks,
418 * verify the existence of the path, or make any system calls.
420 int normalize_path_copy(char *dst, const char *src)
422 char *dst0;
424 if (has_dos_drive_prefix(src)) {
425 *dst++ = *src++;
426 *dst++ = *src++;
428 dst0 = dst;
430 if (is_dir_sep(*src)) {
431 *dst++ = '/';
432 while (is_dir_sep(*src))
433 src++;
436 for (;;) {
437 char c = *src;
440 * A path component that begins with . could be
441 * special:
442 * (1) "." and ends -- ignore and terminate.
443 * (2) "./" -- ignore them, eat slash and continue.
444 * (3) ".." and ends -- strip one and terminate.
445 * (4) "../" -- strip one, eat slash and continue.
447 if (c == '.') {
448 if (!src[1]) {
449 /* (1) */
450 src++;
451 } else if (is_dir_sep(src[1])) {
452 /* (2) */
453 src += 2;
454 while (is_dir_sep(*src))
455 src++;
456 continue;
457 } else if (src[1] == '.') {
458 if (!src[2]) {
459 /* (3) */
460 src += 2;
461 goto up_one;
462 } else if (is_dir_sep(src[2])) {
463 /* (4) */
464 src += 3;
465 while (is_dir_sep(*src))
466 src++;
467 goto up_one;
472 /* copy up to the next '/', and eat all '/' */
473 while ((c = *src++) != '\0' && !is_dir_sep(c))
474 *dst++ = c;
475 if (is_dir_sep(c)) {
476 *dst++ = '/';
477 while (is_dir_sep(c))
478 c = *src++;
479 src--;
480 } else if (!c)
481 break;
482 continue;
484 up_one:
486 * dst0..dst is prefix portion, and dst[-1] is '/';
487 * go up one level.
489 dst--; /* go to trailing '/' */
490 if (dst <= dst0)
491 return -1;
492 /* Windows: dst[-1] cannot be backslash anymore */
493 while (dst0 < dst && dst[-1] != '/')
494 dst--;
496 *dst = '\0';
497 return 0;
501 * path = Canonical absolute path
502 * prefix_list = Colon-separated list of absolute paths
504 * Determines, for each path in prefix_list, whether the "prefix" really
505 * is an ancestor directory of path. Returns the length of the longest
506 * ancestor directory, excluding any trailing slashes, or -1 if no prefix
507 * is an ancestor. (Note that this means 0 is returned if prefix_list is
508 * "/".) "/foo" is not considered an ancestor of "/foobar". Directories
509 * are not considered to be their own ancestors. path must be in a
510 * canonical form: empty components, or "." or ".." components are not
511 * allowed. prefix_list may be null, which is like "".
513 int longest_ancestor_length(const char *path, const char *prefix_list)
515 char buf[PATH_MAX+1];
516 const char *ceil, *colon;
517 int len, max_len = -1;
519 if (prefix_list == NULL || !strcmp(path, "/"))
520 return -1;
522 for (colon = ceil = prefix_list; *colon; ceil = colon+1) {
523 for (colon = ceil; *colon && *colon != PATH_SEP; colon++);
524 len = colon - ceil;
525 if (len == 0 || len > PATH_MAX || !is_absolute_path(ceil))
526 continue;
527 strlcpy(buf, ceil, len+1);
528 if (normalize_path_copy(buf, buf) < 0)
529 continue;
530 len = strlen(buf);
531 if (len > 0 && buf[len-1] == '/')
532 buf[--len] = '\0';
534 if (!strncmp(path, buf, len) &&
535 path[len] == '/' &&
536 len > max_len) {
537 max_len = len;
541 return max_len;
544 /* strip arbitrary amount of directory separators at end of path */
545 static inline int chomp_trailing_dir_sep(const char *path, int len)
547 while (len && is_dir_sep(path[len - 1]))
548 len--;
549 return len;
553 * If path ends with suffix (complete path components), returns the
554 * part before suffix (sans trailing directory separators).
555 * Otherwise returns NULL.
557 char *strip_path_suffix(const char *path, const char *suffix)
559 int path_len = strlen(path), suffix_len = strlen(suffix);
561 while (suffix_len) {
562 if (!path_len)
563 return NULL;
565 if (is_dir_sep(path[path_len - 1])) {
566 if (!is_dir_sep(suffix[suffix_len - 1]))
567 return NULL;
568 path_len = chomp_trailing_dir_sep(path, path_len);
569 suffix_len = chomp_trailing_dir_sep(suffix, suffix_len);
571 else if (path[--path_len] != suffix[--suffix_len])
572 return NULL;
575 if (path_len && !is_dir_sep(path[path_len - 1]))
576 return NULL;
577 return xstrndup(path, chomp_trailing_dir_sep(path, path_len));