2 * I'm tired of doing "vsnprintf()" etc just to open a
3 * file, so here's a "return static buffer with printf"
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.
16 static char bad_path[] = "/bad-path/";
18 static char *get_pathname(void)
20 static char pathname_array[4][PATH_MAX];
22 return pathname_array[3 & ++index];
25 static char *cleanup_path(char *path)
28 if (!memcmp(path, "./", 2)) {
36 char *mksnpath(char *buf, size_t n, const char *fmt, ...)
42 len = vsnprintf(buf, n, fmt, args);
45 strlcpy(buf, bad_path, n);
48 return cleanup_path(buf);
51 static char *vsnpath(char *buf, size_t n, const char *fmt, va_list args)
53 const char *git_dir = get_git_dir();
56 len = strlen(git_dir);
59 memcpy(buf, git_dir, len);
60 if (len && !is_dir_sep(git_dir[len-1]))
62 len += vsnprintf(buf + len, n - len, fmt, args);
65 return cleanup_path(buf);
67 strlcpy(buf, bad_path, n);
71 char *git_snpath(char *buf, size_t n, const char *fmt, ...)
76 ret = vsnpath(buf, n, fmt, args);
81 char *git_pathdup(const char *fmt, ...)
83 char path[PATH_MAX], *ret;
86 ret = vsnpath(path, sizeof(path), fmt, args);
91 char *mkpathdup(const char *fmt, ...)
94 struct strbuf sb = STRBUF_INIT;
98 strbuf_vaddf(&sb, fmt, args);
100 path = xstrdup(cleanup_path(sb.buf));
106 char *mkpath(const char *fmt, ...)
110 char *pathname = get_pathname();
113 len = vsnprintf(pathname, PATH_MAX, fmt, args);
117 return cleanup_path(pathname);
120 char *git_path(const char *fmt, ...)
122 char *pathname = get_pathname();
127 ret = vsnpath(pathname, PATH_MAX, fmt, args);
132 void home_config_paths(char **global, char **xdg, char *file)
134 char *xdg_home = getenv("XDG_CONFIG_HOME");
135 char *home = getenv("HOME");
136 char *to_free = NULL;
143 to_free = mkpathdup("%s/.config", home);
147 *global = mkpathdup("%s/.gitconfig", home);
153 *xdg = mkpathdup("%s/git/%s", xdg_home, file);
158 char *git_path_submodule(const char *path, const char *fmt, ...)
160 char *pathname = get_pathname();
161 struct strbuf buf = STRBUF_INIT;
167 if (len > PATH_MAX-100)
170 strbuf_addstr(&buf, path);
171 if (len && path[len-1] != '/')
172 strbuf_addch(&buf, '/');
173 strbuf_addstr(&buf, ".git");
175 git_dir = read_gitfile(buf.buf);
178 strbuf_addstr(&buf, git_dir);
180 strbuf_addch(&buf, '/');
182 if (buf.len >= PATH_MAX)
184 memcpy(pathname, buf.buf, buf.len + 1);
186 strbuf_release(&buf);
187 len = strlen(pathname);
190 len += vsnprintf(pathname + len, PATH_MAX - len, fmt, args);
194 return cleanup_path(pathname);
197 int validate_headref(const char *path)
200 char *buf, buffer[256];
201 unsigned char sha1[20];
205 if (lstat(path, &st) < 0)
208 /* Make sure it is a "refs/.." symlink */
209 if (S_ISLNK(st.st_mode)) {
210 len = readlink(path, buffer, sizeof(buffer)-1);
211 if (len >= 5 && !memcmp("refs/", buffer, 5))
217 * Anything else, just open it and try to see if it is a symbolic ref.
219 fd = open(path, O_RDONLY);
222 len = read_in_full(fd, buffer, sizeof(buffer)-1);
226 * Is it a symbolic ref?
230 if (!memcmp("ref:", buffer, 4)) {
233 while (len && isspace(*buf))
235 if (len >= 5 && !memcmp("refs/", buf, 5))
240 * Is this a detached HEAD?
242 if (!get_sha1_hex(buffer, sha1))
248 static struct passwd *getpw_str(const char *username, size_t len)
251 char *username_z = xmalloc(len + 1);
252 memcpy(username_z, username, len);
253 username_z[len] = '\0';
254 pw = getpwnam(username_z);
260 * Return a string with ~ and ~user expanded via getpw*. If buf != NULL,
261 * then it is a newly allocated string. Returns NULL on getpw failure or
264 char *expand_user_path(const char *path)
266 struct strbuf user_path = STRBUF_INIT;
267 const char *first_slash = strchrnul(path, '/');
268 const char *to_copy = path;
272 if (path[0] == '~') {
273 const char *username = path + 1;
274 size_t username_len = first_slash - username;
275 if (username_len == 0) {
276 const char *home = getenv("HOME");
279 strbuf_add(&user_path, home, strlen(home));
281 struct passwd *pw = getpw_str(username, username_len);
284 strbuf_add(&user_path, pw->pw_dir, strlen(pw->pw_dir));
286 to_copy = first_slash;
288 strbuf_add(&user_path, to_copy, strlen(to_copy));
289 return strbuf_detach(&user_path, NULL);
291 strbuf_release(&user_path);
296 * First, one directory to try is determined by the following algorithm.
298 * (0) If "strict" is given, the path is used as given and no DWIM is
300 * (1) "~/path" to mean path under the running user's home directory;
301 * (2) "~user/path" to mean path under named user's home directory;
302 * (3) "relative/path" to mean cwd relative directory; or
303 * (4) "/absolute/path" to mean absolute directory.
305 * Unless "strict" is given, we try access() for existence of "%s.git/.git",
306 * "%s/.git", "%s.git", "%s" in this order. The first one that exists is
309 * Second, we try chdir() to that. Upon failure, we return NULL.
311 * Then, we try if the current directory is a valid git repository.
312 * Upon failure, we return NULL.
314 * If all goes well, we return the directory we used to chdir() (but
315 * before ~user is expanded), avoiding getcwd() resolving symbolic
316 * links. User relative paths are also returned as they are given,
317 * except DWIM suffixing.
319 const char *enter_repo(const char *path, int strict)
321 static char used_path[PATH_MAX];
322 static char validated_path[PATH_MAX];
328 static const char *suffix[] = {
329 "/.git", "", ".git/.git", ".git", NULL,
332 int len = strlen(path);
334 while ((1 < len) && (path[len-1] == '/'))
339 strncpy(used_path, path, len); used_path[len] = 0 ;
340 strcpy(validated_path, used_path);
342 if (used_path[0] == '~') {
343 char *newpath = expand_user_path(used_path);
344 if (!newpath || (PATH_MAX - 10 < strlen(newpath))) {
349 * Copy back into the static buffer. A pity
350 * since newpath was not bounded, but other
351 * branches of the if are limited by PATH_MAX
354 strcpy(used_path, newpath); free(newpath);
356 else if (PATH_MAX - 10 < len)
358 len = strlen(used_path);
359 for (i = 0; suffix[i]; i++) {
361 strcpy(used_path + len, suffix[i]);
362 if (!stat(used_path, &st) &&
363 (S_ISREG(st.st_mode) ||
364 (S_ISDIR(st.st_mode) && is_git_directory(used_path)))) {
365 strcat(validated_path, suffix[i]);
371 gitfile = read_gitfile(used_path) ;
373 strcpy(used_path, gitfile);
374 if (chdir(used_path))
376 path = validated_path;
378 else if (chdir(path))
381 if (access("objects", X_OK) == 0 && access("refs", X_OK) == 0 &&
382 validate_headref("HEAD") == 0) {
384 check_repository_format();
391 int set_shared_perm(const char *path, int mode)
394 int tweak, shared, orig_mode;
396 if (!shared_repository) {
398 return chmod(path, mode & ~S_IFMT);
402 if (lstat(path, &st) < 0)
408 if (shared_repository < 0)
409 shared = -shared_repository;
411 shared = shared_repository;
414 if (!(mode & S_IWUSR))
417 /* Copy read bits to execute bits */
418 tweak |= (tweak & 0444) >> 2;
419 if (shared_repository < 0)
420 mode = (mode & ~0777) | tweak;
425 /* Copy read bits to execute bits */
426 mode |= (shared & 0444) >> 2;
427 mode |= FORCE_DIR_SET_GID;
430 if (((shared_repository < 0
431 ? (orig_mode & (FORCE_DIR_SET_GID | 0777))
432 : (orig_mode & mode)) != mode) &&
433 chmod(path, (mode & ~S_IFMT)) < 0)
438 const char *relative_path(const char *abs, const char *base)
440 static char buf[PATH_MAX + 1];
443 if (!base || !base[0])
446 if (is_dir_sep(base[i])) {
447 if (!is_dir_sep(abs[j]))
449 while (is_dir_sep(base[i]))
451 while (is_dir_sep(abs[j]))
454 } else if (abs[j] != base[i]) {
461 /* "/foo" is a prefix of "/foo" */
463 /* "/foo" is not a prefix of "/foobar" */
464 !is_dir_sep(base[i-1]) && !is_dir_sep(abs[j])
467 while (is_dir_sep(abs[j]))
472 strcpy(buf, abs + j);
477 * It is okay if dst == src, but they should not overlap otherwise.
479 * Performs the following normalizations on src, storing the result in dst:
480 * - Ensures that components are separated by '/' (Windows only)
481 * - Squashes sequences of '/'.
482 * - Removes "." components.
483 * - Removes ".." components, and the components the precede them.
484 * Returns failure (non-zero) if a ".." component appears as first path
485 * component anytime during the normalization. Otherwise, returns success (0).
487 * Note that this function is purely textual. It does not follow symlinks,
488 * verify the existence of the path, or make any system calls.
490 int normalize_path_copy(char *dst, const char *src)
494 if (has_dos_drive_prefix(src)) {
500 if (is_dir_sep(*src)) {
502 while (is_dir_sep(*src))
510 * A path component that begins with . could be
512 * (1) "." and ends -- ignore and terminate.
513 * (2) "./" -- ignore them, eat slash and continue.
514 * (3) ".." and ends -- strip one and terminate.
515 * (4) "../" -- strip one, eat slash and continue.
521 } else if (is_dir_sep(src[1])) {
524 while (is_dir_sep(*src))
527 } else if (src[1] == '.') {
532 } else if (is_dir_sep(src[2])) {
535 while (is_dir_sep(*src))
542 /* copy up to the next '/', and eat all '/' */
543 while ((c = *src++) != '\0' && !is_dir_sep(c))
547 while (is_dir_sep(c))
556 * dst0..dst is prefix portion, and dst[-1] is '/';
559 dst--; /* go to trailing '/' */
562 /* Windows: dst[-1] cannot be backslash anymore */
563 while (dst0 < dst && dst[-1] != '/')
571 * path = Canonical absolute path
572 * prefix_list = Colon-separated list of absolute paths
574 * Determines, for each path in prefix_list, whether the "prefix" really
575 * is an ancestor directory of path. Returns the length of the longest
576 * ancestor directory, excluding any trailing slashes, or -1 if no prefix
577 * is an ancestor. (Note that this means 0 is returned if prefix_list is
578 * "/".) "/foo" is not considered an ancestor of "/foobar". Directories
579 * are not considered to be their own ancestors. path must be in a
580 * canonical form: empty components, or "." or ".." components are not
581 * allowed. prefix_list may be null, which is like "".
583 int longest_ancestor_length(const char *path, const char *prefix_list)
585 char buf[PATH_MAX+1];
586 const char *ceil, *colon;
587 int len, max_len = -1;
589 if (prefix_list == NULL || !strcmp(path, "/"))
592 for (colon = ceil = prefix_list; *colon; ceil = colon+1) {
593 for (colon = ceil; *colon && *colon != PATH_SEP; colon++);
595 if (len == 0 || len > PATH_MAX || !is_absolute_path(ceil))
597 strlcpy(buf, ceil, len+1);
598 if (normalize_path_copy(buf, buf) < 0)
601 if (len > 0 && buf[len-1] == '/')
604 if (!strncmp(path, buf, len) &&
614 /* strip arbitrary amount of directory separators at end of path */
615 static inline int chomp_trailing_dir_sep(const char *path, int len)
617 while (len && is_dir_sep(path[len - 1]))
623 * If path ends with suffix (complete path components), returns the
624 * part before suffix (sans trailing directory separators).
625 * Otherwise returns NULL.
627 char *strip_path_suffix(const char *path, const char *suffix)
629 int path_len = strlen(path), suffix_len = strlen(suffix);
635 if (is_dir_sep(path[path_len - 1])) {
636 if (!is_dir_sep(suffix[suffix_len - 1]))
638 path_len = chomp_trailing_dir_sep(path, path_len);
639 suffix_len = chomp_trailing_dir_sep(suffix, suffix_len);
641 else if (path[--path_len] != suffix[--suffix_len])
645 if (path_len && !is_dir_sep(path[path_len - 1]))
647 return xstrndup(path, chomp_trailing_dir_sep(path, path_len));
650 int daemon_avoid_alias(const char *p)
655 * This resurrects the belts and suspenders paranoia check by HPA
656 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
657 * does not do getcwd() based path canonicalization.
659 * sl becomes true immediately after seeing '/' and continues to
660 * be true as long as dots continue after that without intervening
663 if (!p || (*p != '/' && *p != '~'))
673 else if (ch == '/') {
675 /* reject //, /./ and /../ */
680 if (0 < ndot && ndot < 3)
681 /* reject /.$ and /..$ */
690 else if (ch == '/') {
697 int offset_1st_component(const char *path)
699 if (has_dos_drive_prefix(path))
700 return 2 + is_dir_sep(path[2]);
701 return is_dir_sep(path[0]);