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.
15 static char bad_path[] = "/bad-path/";
17 static char *get_pathname(void)
19 static char pathname_array[4][PATH_MAX];
21 return pathname_array[3 & ++index];
24 static char *cleanup_path(char *path)
27 if (!memcmp(path, "./", 2)) {
35 char *mksnpath(char *buf, size_t n, const char *fmt, ...)
41 len = vsnprintf(buf, n, fmt, args);
44 strlcpy(buf, bad_path, n);
47 return cleanup_path(buf);
50 static char *git_vsnpath(char *buf, size_t n, const char *fmt, va_list args)
52 const char *git_dir = get_git_dir();
55 len = strlen(git_dir);
58 memcpy(buf, git_dir, len);
59 if (len && !is_dir_sep(git_dir[len-1]))
61 len += vsnprintf(buf + len, n - len, fmt, args);
64 return cleanup_path(buf);
66 strlcpy(buf, bad_path, n);
70 char *git_snpath(char *buf, size_t n, const char *fmt, ...)
74 (void)git_vsnpath(buf, n, fmt, args);
79 char *git_pathdup(const char *fmt, ...)
84 (void)git_vsnpath(path, sizeof(path), fmt, args);
89 char *mkpath(const char *fmt, ...)
93 char *pathname = get_pathname();
96 len = vsnprintf(pathname, PATH_MAX, fmt, args);
100 return cleanup_path(pathname);
103 char *git_path(const char *fmt, ...)
105 const char *git_dir = get_git_dir();
106 char *pathname = get_pathname();
110 len = strlen(git_dir);
111 if (len > PATH_MAX-100)
113 memcpy(pathname, git_dir, len);
114 if (len && git_dir[len-1] != '/')
115 pathname[len++] = '/';
117 len += vsnprintf(pathname + len, PATH_MAX - len, fmt, args);
121 return cleanup_path(pathname);
125 /* git_mkstemp() - create tmp file honoring TMPDIR variable */
126 int git_mkstemp(char *path, size_t len, const char *template)
131 tmp = getenv("TMPDIR");
134 n = snprintf(path, len, "%s/%s", tmp, template);
136 errno = ENAMETOOLONG;
139 return mkstemp(path);
142 /* git_mkstemps() - create tmp file with suffix honoring TMPDIR variable. */
143 int git_mkstemps(char *path, size_t len, const char *template, int suffix_len)
148 tmp = getenv("TMPDIR");
151 n = snprintf(path, len, "%s/%s", tmp, template);
153 errno = ENAMETOOLONG;
156 return mkstemps(path, suffix_len);
159 int validate_headref(const char *path)
162 char *buf, buffer[256];
163 unsigned char sha1[20];
167 if (lstat(path, &st) < 0)
170 /* Make sure it is a "refs/.." symlink */
171 if (S_ISLNK(st.st_mode)) {
172 len = readlink(path, buffer, sizeof(buffer)-1);
173 if (len >= 5 && !memcmp("refs/", buffer, 5))
179 * Anything else, just open it and try to see if it is a symbolic ref.
181 fd = open(path, O_RDONLY);
184 len = read_in_full(fd, buffer, sizeof(buffer)-1);
188 * Is it a symbolic ref?
192 if (!memcmp("ref:", buffer, 4)) {
195 while (len && isspace(*buf))
197 if (len >= 5 && !memcmp("refs/", buf, 5))
202 * Is this a detached HEAD?
204 if (!get_sha1_hex(buffer, sha1))
210 static char *user_path(char *buf, char *path, int sz)
216 if (!path || path[0] != '~')
219 slash = strchr(path, '/');
220 if (path[0] == '/' || !path[0]) {
221 pw = getpwuid(getuid());
232 if (!pw || !pw->pw_dir || sz <= strlen(pw->pw_dir))
234 baselen = strlen(pw->pw_dir);
235 memcpy(buf, pw->pw_dir, baselen);
236 while ((1 < baselen) && (buf[baselen-1] == '/')) {
240 if (slash && slash[1]) {
242 if (sz <= baselen + len)
244 memcpy(buf + baselen, slash, len + 1);
250 * First, one directory to try is determined by the following algorithm.
252 * (0) If "strict" is given, the path is used as given and no DWIM is
254 * (1) "~/path" to mean path under the running user's home directory;
255 * (2) "~user/path" to mean path under named user's home directory;
256 * (3) "relative/path" to mean cwd relative directory; or
257 * (4) "/absolute/path" to mean absolute directory.
259 * Unless "strict" is given, we try access() for existence of "%s.git/.git",
260 * "%s/.git", "%s.git", "%s" in this order. The first one that exists is
263 * Second, we try chdir() to that. Upon failure, we return NULL.
265 * Then, we try if the current directory is a valid git repository.
266 * Upon failure, we return NULL.
268 * If all goes well, we return the directory we used to chdir() (but
269 * before ~user is expanded), avoiding getcwd() resolving symbolic
270 * links. User relative paths are also returned as they are given,
271 * except DWIM suffixing.
273 char *enter_repo(char *path, int strict)
275 static char used_path[PATH_MAX];
276 static char validated_path[PATH_MAX];
282 static const char *suffix[] = {
283 ".git/.git", "/.git", ".git", "", NULL,
285 int len = strlen(path);
287 while ((1 < len) && (path[len-1] == '/')) {
293 if (path[0] == '~') {
294 if (!user_path(used_path, path, PATH_MAX))
296 strcpy(validated_path, path);
299 else if (PATH_MAX - 10 < len)
302 path = strcpy(used_path, path);
303 strcpy(validated_path, path);
306 for (i = 0; suffix[i]; i++) {
307 strcpy(path + len, suffix[i]);
308 if (!access(path, F_OK)) {
309 strcat(validated_path, suffix[i]);
313 if (!suffix[i] || chdir(path))
315 path = validated_path;
317 else if (chdir(path))
320 if (access("objects", X_OK) == 0 && access("refs", X_OK) == 0 &&
321 validate_headref("HEAD") == 0) {
322 setenv(GIT_DIR_ENVIRONMENT, ".", 1);
323 check_repository_format();
330 int set_shared_perm(const char *path, int mode)
333 int tweak, shared, orig_mode;
335 if (!shared_repository) {
337 return chmod(path, mode & ~S_IFMT);
341 if (lstat(path, &st) < 0)
347 if (shared_repository < 0)
348 shared = -shared_repository;
350 shared = shared_repository;
353 if (!(mode & S_IWUSR))
356 /* Copy read bits to execute bits */
357 tweak |= (tweak & 0444) >> 2;
358 if (shared_repository < 0)
359 mode = (mode & ~0777) | tweak;
364 /* Copy read bits to execute bits */
365 mode |= (shared & 0444) >> 2;
366 mode |= FORCE_DIR_SET_GID;
369 if (((shared_repository < 0
370 ? (orig_mode & (FORCE_DIR_SET_GID | 0777))
371 : (orig_mode & mode)) != mode) &&
372 chmod(path, (mode & ~S_IFMT)) < 0)
377 const char *make_relative_path(const char *abs, const char *base)
379 static char buf[PATH_MAX + 1];
383 baselen = strlen(base);
384 if (prefixcmp(abs, base))
386 if (abs[baselen] == '/')
388 else if (base[baselen - 1] != '/')
390 strcpy(buf, abs + baselen);
395 * It is okay if dst == src, but they should not overlap otherwise.
397 * Performs the following normalizations on src, storing the result in dst:
398 * - Ensures that components are separated by '/' (Windows only)
399 * - Squashes sequences of '/'.
400 * - Removes "." components.
401 * - Removes ".." components, and the components the precede them.
402 * Returns failure (non-zero) if a ".." component appears as first path
403 * component anytime during the normalization. Otherwise, returns success (0).
405 * Note that this function is purely textual. It does not follow symlinks,
406 * verify the existence of the path, or make any system calls.
408 int normalize_path_copy(char *dst, const char *src)
412 if (has_dos_drive_prefix(src)) {
418 if (is_dir_sep(*src)) {
420 while (is_dir_sep(*src))
428 * A path component that begins with . could be
430 * (1) "." and ends -- ignore and terminate.
431 * (2) "./" -- ignore them, eat slash and continue.
432 * (3) ".." and ends -- strip one and terminate.
433 * (4) "../" -- strip one, eat slash and continue.
439 } else if (is_dir_sep(src[1])) {
442 while (is_dir_sep(*src))
445 } else if (src[1] == '.') {
450 } else if (is_dir_sep(src[2])) {
453 while (is_dir_sep(*src))
460 /* copy up to the next '/', and eat all '/' */
461 while ((c = *src++) != '\0' && !is_dir_sep(c))
465 while (is_dir_sep(c))
474 * dst0..dst is prefix portion, and dst[-1] is '/';
477 dst--; /* go to trailing '/' */
480 /* Windows: dst[-1] cannot be backslash anymore */
481 while (dst0 < dst && dst[-1] != '/')
489 * path = Canonical absolute path
490 * prefix_list = Colon-separated list of absolute paths
492 * Determines, for each path in prefix_list, whether the "prefix" really
493 * is an ancestor directory of path. Returns the length of the longest
494 * ancestor directory, excluding any trailing slashes, or -1 if no prefix
495 * is an ancestor. (Note that this means 0 is returned if prefix_list is
496 * "/".) "/foo" is not considered an ancestor of "/foobar". Directories
497 * are not considered to be their own ancestors. path must be in a
498 * canonical form: empty components, or "." or ".." components are not
499 * allowed. prefix_list may be null, which is like "".
501 int longest_ancestor_length(const char *path, const char *prefix_list)
503 char buf[PATH_MAX+1];
504 const char *ceil, *colon;
505 int len, max_len = -1;
507 if (prefix_list == NULL || !strcmp(path, "/"))
510 for (colon = ceil = prefix_list; *colon; ceil = colon+1) {
511 for (colon = ceil; *colon && *colon != PATH_SEP; colon++);
513 if (len == 0 || len > PATH_MAX || !is_absolute_path(ceil))
515 strlcpy(buf, ceil, len+1);
516 if (normalize_path_copy(buf, buf) < 0)
519 if (len > 0 && buf[len-1] == '/')
522 if (!strncmp(path, buf, len) &&
532 /* strip arbitrary amount of directory separators at end of path */
533 static inline int chomp_trailing_dir_sep(const char *path, int len)
535 while (len && is_dir_sep(path[len - 1]))
541 * If path ends with suffix (complete path components), returns the
542 * part before suffix (sans trailing directory separators).
543 * Otherwise returns NULL.
545 char *strip_path_suffix(const char *path, const char *suffix)
547 int path_len = strlen(path), suffix_len = strlen(suffix);
553 if (is_dir_sep(path[path_len - 1])) {
554 if (!is_dir_sep(suffix[suffix_len - 1]))
556 path_len = chomp_trailing_dir_sep(path, path_len);
557 suffix_len = chomp_trailing_dir_sep(suffix, suffix_len);
559 else if (path[--path_len] != suffix[--suffix_len])
563 if (path_len && !is_dir_sep(path[path_len - 1]))
565 return xstrndup(path, chomp_trailing_dir_sep(path, path_len));