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 int validate_symref(const char *path
)
97 char *buf
, buffer
[256];
100 if (lstat(path
, &st
) < 0)
103 /* Make sure it is a "refs/.." symlink */
104 if (S_ISLNK(st
.st_mode
)) {
105 len
= readlink(path
, buffer
, sizeof(buffer
)-1);
106 if (len
>= 5 && !memcmp("refs/", buffer
, 5))
112 * Anything else, just open it and try to see if it is a symbolic ref.
114 fd
= open(path
, O_RDONLY
);
117 len
= read(fd
, buffer
, sizeof(buffer
)-1);
121 * Is it a symbolic ref?
123 if (len
< 4 || memcmp("ref:", buffer
, 4))
127 while (len
&& isspace(*buf
))
129 if (len
>= 5 && !memcmp("refs/", buf
, 5))
134 static char *current_dir(void)
136 return getcwd(pathname
, sizeof(pathname
));
139 static int user_chdir(char *path
)
143 if(*dir
== '~') { /* user-relative path */
145 char *slash
= strchr(dir
, '/');
148 /* '~/' and '~' (no slash) means users own home-dir */
149 if(!*dir
|| *dir
== '/')
150 pw
= getpwuid(getuid());
161 /* make sure we got something back that we can chdir() to */
162 if(!pw
|| chdir(pw
->pw_dir
) < 0)
165 if(!slash
|| !slash
[1]) /* no path following username */
171 /* ~foo/path/to/repo is now path/to/repo and we're in foo's homedir */
178 char *enter_repo(char *path
, int strict
)
189 ; /* happy -- no chdir */
190 else if (!user_chdir(path
))
191 ; /* happy -- as given */
192 else if (!user_chdir(mkpath("%s.git", path
)))
193 ; /* happy -- uemacs --> uemacs.git */
199 if(access("objects", X_OK
) == 0 && access("refs", X_OK
) == 0 &&
200 validate_symref("HEAD") == 0) {
202 check_repository_format();
203 return current_dir();