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 pathname[PATH_MAX];
17 static char bad_path[] = "/bad-path/";
19 static char *cleanup_path(char *path)
22 if (!memcmp(path, "./", 2)) {
30 char *mkpath(const char *fmt, ...)
36 len = vsnprintf(pathname, PATH_MAX, fmt, args);
40 return cleanup_path(pathname);
43 char *git_path(const char *fmt, ...)
45 const char *git_dir = get_git_dir();
49 len = strlen(git_dir);
50 if (len > PATH_MAX-100)
52 memcpy(pathname, git_dir, len);
53 if (len && git_dir[len-1] != '/')
54 pathname[len++] = '/';
56 len += vsnprintf(pathname + len, PATH_MAX - len, fmt, args);
60 return cleanup_path(pathname);
64 /* git_mkstemp() - create tmp file honoring TMPDIR variable */
65 int git_mkstemp(char *path, size_t len, const char *template)
67 char *env, *pch = path;
69 if ((env = getenv("TMPDIR")) == NULL) {
74 size_t n = snprintf(pch, len, "%s/", env);
80 safe_strncpy(pch, template, len);
86 char *safe_strncpy(char *dest, const char *src, size_t n)
88 strncpy(dest, src, n);
94 static char *current_dir()
96 return getcwd(pathname, sizeof(pathname));
99 /* Take a raw path from is_git_repo() and canonicalize it using Linus'
100 * idea of a blind chdir() and getcwd(). */
101 static const char *canonical_path(char *path, int strict)
105 if(strict && *dir != '/')
108 if(*dir == '~') { /* user-relative path */
110 char *slash = strchr(dir, '/');
113 /* '~/' and '~' (no slash) means users own home-dir */
114 if(!*dir || *dir == '/')
115 pw = getpwuid(getuid());
126 /* make sure we got something back that we can chdir() to */
127 if(!pw || chdir(pw->pw_dir) < 0)
130 if(!slash || !slash[1]) /* no path following username */
131 return current_dir();
136 /* ~foo/path/to/repo is now path/to/repo and we're in foo's homedir */
140 return current_dir();
143 char *enter_repo(char *path, int strict)
148 if(!canonical_path(path, strict)) {
149 if(strict || !canonical_path(mkpath("%s.git", path), strict))
153 /* This is perfectly safe, and people tend to think of the directory
154 * where they ran git-init-db as their repository, so humour them. */
157 if(access("objects", X_OK) == 0 && access("refs", X_OK) == 0) {
159 return current_dir();