]>
Commit | Line | Data |
---|---|---|
26c8a533 LT |
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. | |
5 | * | |
6 | * It's obviously not thread-safe. Sue me. But it's quite | |
7 | * useful for doing things like | |
8 | * | |
9 | * f = open(mkpath("%s/%s.git", base, name), O_RDONLY); | |
10 | * | |
11 | * which is what it's designed for. | |
12 | */ | |
13 | #include "cache.h" | |
14 | ||
15 | static char pathname[PATH_MAX]; | |
16 | static char bad_path[] = "/bad-path/"; | |
17 | ||
18 | static char *cleanup_path(char *path) | |
19 | { | |
20 | /* Clean it up */ | |
21 | if (!memcmp(path, "./", 2)) { | |
22 | path += 2; | |
23 | while (*path == '/') | |
24 | path++; | |
25 | } | |
26 | return path; | |
27 | } | |
28 | ||
29 | char *mkpath(const char *fmt, ...) | |
30 | { | |
31 | va_list args; | |
32 | unsigned len; | |
33 | ||
34 | va_start(args, fmt); | |
35 | len = vsnprintf(pathname, PATH_MAX, fmt, args); | |
36 | va_end(args); | |
37 | if (len >= PATH_MAX) | |
38 | return bad_path; | |
39 | return cleanup_path(pathname); | |
40 | } | |
41 | ||
42 | char *git_path(const char *fmt, ...) | |
43 | { | |
c7c81b3a | 44 | const char *git_dir; |
26c8a533 LT |
45 | va_list args; |
46 | unsigned len; | |
47 | ||
c7c81b3a JR |
48 | git_dir = gitenv(GIT_DIR_ENVIRONMENT); |
49 | if (!git_dir) git_dir = DEFAULT_GIT_DIR_ENVIRONMENT; | |
26c8a533 LT |
50 | len = strlen(git_dir); |
51 | if (len > PATH_MAX-100) | |
52 | return bad_path; | |
53 | memcpy(pathname, git_dir, len); | |
54 | if (len && git_dir[len-1] != '/') | |
55 | pathname[len++] = '/'; | |
56 | va_start(args, fmt); | |
57 | len += vsnprintf(pathname + len, PATH_MAX - len, fmt, args); | |
58 | va_end(args); | |
59 | if (len >= PATH_MAX) | |
60 | return bad_path; | |
61 | return cleanup_path(pathname); | |
62 | } | |
f2db68ed HE |
63 | |
64 | ||
65 | /* git_mkstemp() - create tmp file honoring TMPDIR variable */ | |
66 | int git_mkstemp(char *path, size_t len, const char *template) | |
67 | { | |
68 | char *env, *pch = path; | |
69 | ||
70 | if ((env = getenv("TMPDIR")) == NULL) { | |
71 | strcpy(pch, "/tmp/"); | |
72 | len -= 5; | |
35c3c629 HE |
73 | pch += 5; |
74 | } else { | |
75 | size_t n = snprintf(pch, len, "%s/", env); | |
76 | ||
77 | len -= n; | |
78 | pch += n; | |
79 | } | |
f2db68ed HE |
80 | |
81 | safe_strncpy(pch, template, len); | |
82 | ||
83 | return mkstemp(path); | |
84 | } | |
85 | ||
86 | ||
87 | char *safe_strncpy(char *dest, const char *src, size_t n) | |
88 | { | |
89 | strncpy(dest, src, n); | |
90 | dest[n - 1] = '\0'; | |
91 | ||
92 | return dest; | |
93 | } |