blob: 2c895471d901411a6b3409fab287271c451c6167 [file] [log] [blame]
Linus Torvalds26c8a532005-07-08 16:20:59 -07001/*
Torsten Bögershausen3a429d32013-03-30 10:53:32 +01002 * Utilities for paths and pathnames
Linus Torvalds26c8a532005-07-08 16:20:59 -07003 */
4#include "cache.h"
Brandon Williamsc14c2342017-06-22 11:43:33 -07005#include "repository.h"
Matthieu Moy395de252009-11-17 18:24:25 +01006#include "strbuf.h"
Michael Haggertya5ccdbe2012-10-28 17:16:23 +01007#include "string-list.h"
Nguyễn Thái Ngọc Duy77a6d842014-11-30 15:24:54 +07008#include "dir.h"
Nguyễn Thái Ngọc Duy2e641d52016-04-22 20:01:29 +07009#include "worktree.h"
Jacob Keller99b43a62016-08-31 16:27:22 -070010#include "submodule-config.h"
Brandon Williamse7d72d02017-06-22 11:43:35 -070011#include "path.h"
Jonathan Tan0abe14f2017-08-18 15:20:26 -070012#include "packfile.h"
Stefan Beller90c62152018-03-23 18:20:55 +010013#include "object-store.h"
Johannes Schindelin76a53d62019-10-28 12:57:18 +000014#include "lockfile.h"
Johannes Schindeline394a162021-07-24 22:06:53 +000015#include "exec-cmd.h"
Linus Torvalds26c8a532005-07-08 16:20:59 -070016
Ramsay Jonesf66450a2013-06-22 20:42:47 +010017static int get_st_mode_bits(const char *path, int *mode)
Torsten Bögershausen0117c2f2013-03-23 13:40:29 +010018{
19 struct stat st;
20 if (lstat(path, &st) < 0)
21 return -1;
22 *mode = st.st_mode;
23 return 0;
24}
Torsten Bögershausen0117c2f2013-03-23 13:40:29 +010025
Linus Torvalds26c8a532005-07-08 16:20:59 -070026static char bad_path[] = "/bad-path/";
27
Nguyễn Thái Ngọc Duy4ef9caf2014-11-30 15:24:26 +070028static struct strbuf *get_pathname(void)
Linus Torvaldse7676d22006-09-11 12:03:15 -070029{
Nguyễn Thái Ngọc Duy4ef9caf2014-11-30 15:24:26 +070030 static struct strbuf pathname_array[4] = {
31 STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
32 };
Linus Torvaldse7676d22006-09-11 12:03:15 -070033 static int index;
René Scharfebb847352016-10-23 19:57:30 +020034 struct strbuf *sb = &pathname_array[index];
35 index = (index + 1) % ARRAY_SIZE(pathname_array);
Nguyễn Thái Ngọc Duy4ef9caf2014-11-30 15:24:26 +070036 strbuf_reset(sb);
37 return sb;
Linus Torvaldse7676d22006-09-11 12:03:15 -070038}
39
Jeff King82627152017-10-03 19:30:40 -040040static const char *cleanup_path(const char *path)
Linus Torvalds26c8a532005-07-08 16:20:59 -070041{
42 /* Clean it up */
Jeff King82627152017-10-03 19:30:40 -040043 if (skip_prefix(path, "./", &path)) {
Linus Torvalds26c8a532005-07-08 16:20:59 -070044 while (*path == '/')
45 path++;
46 }
47 return path;
48}
49
Nguyễn Thái Ngọc Duy4ef9caf2014-11-30 15:24:26 +070050static void strbuf_cleanup_path(struct strbuf *sb)
51{
Jeff King82627152017-10-03 19:30:40 -040052 const char *path = cleanup_path(sb->buf);
Nguyễn Thái Ngọc Duy4ef9caf2014-11-30 15:24:26 +070053 if (path > sb->buf)
54 strbuf_remove(sb, 0, path - sb->buf);
55}
56
Alex Riesen108bebe2008-10-26 22:59:13 +010057char *mksnpath(char *buf, size_t n, const char *fmt, ...)
58{
59 va_list args;
60 unsigned len;
61
62 va_start(args, fmt);
63 len = vsnprintf(buf, n, fmt, args);
64 va_end(args);
65 if (len >= n) {
Daniel Lowe9db56f72008-11-10 16:07:52 -050066 strlcpy(buf, bad_path, n);
Alex Riesen108bebe2008-10-26 22:59:13 +010067 return buf;
68 }
Jeff King82627152017-10-03 19:30:40 -040069 return (char *)cleanup_path(buf);
Alex Riesen108bebe2008-10-26 22:59:13 +010070}
71
Nguyễn Thái Ngọc Duy557bd832014-11-30 15:24:31 +070072static int dir_prefix(const char *buf, const char *dir)
Alex Riesenfe2d7772008-10-27 10:22:21 +010073{
Nguyễn Thái Ngọc Duy557bd832014-11-30 15:24:31 +070074 int len = strlen(dir);
75 return !strncmp(buf, dir, len) &&
76 (is_dir_sep(buf[len]) || buf[len] == '\0');
Alex Riesenfe2d7772008-10-27 10:22:21 +010077}
78
Nguyễn Thái Ngọc Duy557bd832014-11-30 15:24:31 +070079/* $buf =~ m|$dir/+$file| but without regex */
80static int is_dir_file(const char *buf, const char *dir, const char *file)
Alex Riesenaba13e72008-10-27 11:17:51 +010081{
Nguyễn Thái Ngọc Duy557bd832014-11-30 15:24:31 +070082 int len = strlen(dir);
83 if (strncmp(buf, dir, len) || !is_dir_sep(buf[len]))
84 return 0;
85 while (is_dir_sep(buf[len]))
86 len++;
87 return !strcmp(buf + len, file);
88}
89
90static void replace_dir(struct strbuf *buf, int len, const char *newdir)
91{
92 int newlen = strlen(newdir);
93 int need_sep = (buf->buf[len] && !is_dir_sep(buf->buf[len])) &&
94 !is_dir_sep(newdir[newlen - 1]);
95 if (need_sep)
96 len--; /* keep one char, to be replaced with '/' */
97 strbuf_splice(buf, 0, len, newdir, newlen);
98 if (need_sep)
99 buf->buf[newlen] = '/';
100}
101
David Turner07015302015-08-31 22:13:09 -0400102struct common_dir {
103 /* Not considered garbage for report_linked_checkout_garbage */
104 unsigned ignore_garbage:1;
105 unsigned is_dir:1;
SZEDER Gáborc72fc402019-10-21 18:00:42 +0200106 /* Belongs to the common dir, though it may contain paths that don't */
107 unsigned is_common:1;
108 const char *path;
David Turner07015302015-08-31 22:13:09 -0400109};
110
111static struct common_dir common_list[] = {
SZEDER Gáborc72fc402019-10-21 18:00:42 +0200112 { 0, 1, 1, "branches" },
113 { 0, 1, 1, "common" },
114 { 0, 1, 1, "hooks" },
115 { 0, 1, 1, "info" },
116 { 0, 0, 0, "info/sparse-checkout" },
117 { 1, 1, 1, "logs" },
118 { 1, 0, 0, "logs/HEAD" },
119 { 0, 1, 0, "logs/refs/bisect" },
120 { 0, 1, 0, "logs/refs/rewritten" },
121 { 0, 1, 0, "logs/refs/worktree" },
122 { 0, 1, 1, "lost-found" },
123 { 0, 1, 1, "objects" },
124 { 0, 1, 1, "refs" },
125 { 0, 1, 0, "refs/bisect" },
126 { 0, 1, 0, "refs/rewritten" },
127 { 0, 1, 0, "refs/worktree" },
128 { 0, 1, 1, "remotes" },
129 { 0, 1, 1, "worktrees" },
130 { 0, 1, 1, "rr-cache" },
131 { 0, 1, 1, "svn" },
132 { 0, 0, 1, "config" },
133 { 1, 0, 1, "gc.pid" },
134 { 0, 0, 1, "packed-refs" },
135 { 0, 0, 1, "shallow" },
David Turner07015302015-08-31 22:13:09 -0400136 { 0, 0, 0, NULL }
Nguyễn Thái Ngọc Duyc7b3a3d2014-11-30 15:24:36 +0700137};
138
David Turner4e09cf22015-08-31 22:13:10 -0400139/*
140 * A compressed trie. A trie node consists of zero or more characters that
141 * are common to all elements with this prefix, optionally followed by some
142 * children. If value is not NULL, the trie node is a terminal node.
143 *
144 * For example, consider the following set of strings:
145 * abc
146 * def
147 * definite
148 * definition
149 *
Li Peng832c0e52016-05-06 20:36:46 +0800150 * The trie would look like:
David Turner4e09cf22015-08-31 22:13:10 -0400151 * root: len = 0, children a and d non-NULL, value = NULL.
152 * a: len = 2, contents = bc, value = (data for "abc")
153 * d: len = 2, contents = ef, children i non-NULL, value = (data for "def")
154 * i: len = 3, contents = nit, children e and i non-NULL, value = NULL
155 * e: len = 0, children all NULL, value = (data for "definite")
156 * i: len = 2, contents = on, children all NULL,
157 * value = (data for "definition")
158 */
159struct trie {
160 struct trie *children[256];
161 int len;
162 char *contents;
163 void *value;
164};
165
166static struct trie *make_trie_node(const char *key, void *value)
167{
168 struct trie *new_node = xcalloc(1, sizeof(*new_node));
169 new_node->len = strlen(key);
170 if (new_node->len) {
171 new_node->contents = xmalloc(new_node->len);
172 memcpy(new_node->contents, key, new_node->len);
173 }
174 new_node->value = value;
175 return new_node;
176}
177
178/*
179 * Add a key/value pair to a trie. The key is assumed to be \0-terminated.
180 * If there was an existing value for this key, return it.
181 */
182static void *add_to_trie(struct trie *root, const char *key, void *value)
183{
184 struct trie *child;
185 void *old;
186 int i;
187
188 if (!*key) {
189 /* we have reached the end of the key */
190 old = root->value;
191 root->value = value;
192 return old;
193 }
194
195 for (i = 0; i < root->len; i++) {
196 if (root->contents[i] == key[i])
197 continue;
198
199 /*
200 * Split this node: child will contain this node's
201 * existing children.
202 */
Andrey Okoshkin55d7d152017-10-24 18:15:05 +0300203 child = xmalloc(sizeof(*child));
David Turner4e09cf22015-08-31 22:13:10 -0400204 memcpy(child->children, root->children, sizeof(root->children));
205
206 child->len = root->len - i - 1;
207 if (child->len) {
208 child->contents = xstrndup(root->contents + i + 1,
209 child->len);
210 }
211 child->value = root->value;
212 root->value = NULL;
213 root->len = i;
214
215 memset(root->children, 0, sizeof(root->children));
216 root->children[(unsigned char)root->contents[i]] = child;
217
218 /* This is the newly-added child. */
219 root->children[(unsigned char)key[i]] =
220 make_trie_node(key + i + 1, value);
221 return NULL;
222 }
223
224 /* We have matched the entire compressed section */
225 if (key[i]) {
226 child = root->children[(unsigned char)key[root->len]];
227 if (child) {
228 return add_to_trie(child, key + root->len + 1, value);
229 } else {
230 child = make_trie_node(key + root->len + 1, value);
231 root->children[(unsigned char)key[root->len]] = child;
232 return NULL;
233 }
234 }
235
236 old = root->value;
237 root->value = value;
238 return old;
239}
240
SZEDER Gábor7cb8c922019-10-21 18:00:40 +0200241typedef int (*match_fn)(const char *unmatched, void *value, void *baton);
David Turner4e09cf22015-08-31 22:13:10 -0400242
243/*
244 * Search a trie for some key. Find the longest /-or-\0-terminated
SZEDER Gábor7cb8c922019-10-21 18:00:40 +0200245 * prefix of the key for which the trie contains a value. If there is
246 * no such prefix, return -1. Otherwise call fn with the unmatched
247 * portion of the key and the found value. If fn returns 0 or
248 * positive, then return its return value. If fn returns negative,
249 * then call fn with the next-longest /-terminated prefix of the key
250 * (i.e. a parent directory) for which the trie contains a value, and
251 * handle its return value the same way. If there is no shorter
252 * /-terminated prefix with a value left, then return the negative
253 * return value of the most recent fn invocation.
David Turner4e09cf22015-08-31 22:13:10 -0400254 *
255 * The key is partially normalized: consecutive slashes are skipped.
256 *
SZEDER Gábor7cb8c922019-10-21 18:00:40 +0200257 * For example, consider the trie containing only [logs,
258 * logs/refs/bisect], both with values, but not logs/refs.
David Turner4e09cf22015-08-31 22:13:10 -0400259 *
SZEDER Gábor7cb8c922019-10-21 18:00:40 +0200260 * | key | unmatched | prefix to node | return value |
261 * |--------------------|----------------|------------------|--------------|
262 * | a | not called | n/a | -1 |
263 * | logstore | not called | n/a | -1 |
264 * | logs | \0 | logs | as per fn |
265 * | logs/ | / | logs | as per fn |
266 * | logs/refs | /refs | logs | as per fn |
267 * | logs/refs/ | /refs/ | logs | as per fn |
268 * | logs/refs/b | /refs/b | logs | as per fn |
269 * | logs/refs/bisected | /refs/bisected | logs | as per fn |
270 * | logs/refs/bisect | \0 | logs/refs/bisect | as per fn |
271 * | logs/refs/bisect/ | / | logs/refs/bisect | as per fn |
272 * | logs/refs/bisect/a | /a | logs/refs/bisect | as per fn |
273 * | (If fn in the previous line returns -1, then fn is called once more:) |
274 * | logs/refs/bisect/a | /refs/bisect/a | logs | as per fn |
275 * |--------------------|----------------|------------------|--------------|
David Turner4e09cf22015-08-31 22:13:10 -0400276 */
277static int trie_find(struct trie *root, const char *key, match_fn fn,
278 void *baton)
279{
280 int i;
281 int result;
282 struct trie *child;
283
284 if (!*key) {
285 /* we have reached the end of the key */
286 if (root->value && !root->len)
287 return fn(key, root->value, baton);
288 else
289 return -1;
290 }
291
292 for (i = 0; i < root->len; i++) {
293 /* Partial path normalization: skip consecutive slashes. */
294 if (key[i] == '/' && key[i+1] == '/') {
295 key++;
296 continue;
297 }
298 if (root->contents[i] != key[i])
299 return -1;
300 }
301
302 /* Matched the entire compressed section */
303 key += i;
SZEDER Gáborf45f88b2019-10-21 18:00:43 +0200304 if (!*key) {
David Turner4e09cf22015-08-31 22:13:10 -0400305 /* End of key */
SZEDER Gáborf45f88b2019-10-21 18:00:43 +0200306 if (root->value)
307 return fn(key, root->value, baton);
308 else
309 return -1;
310 }
David Turner4e09cf22015-08-31 22:13:10 -0400311
312 /* Partial path normalization: skip consecutive slashes */
313 while (key[0] == '/' && key[1] == '/')
314 key++;
315
316 child = root->children[(unsigned char)*key];
317 if (child)
318 result = trie_find(child, key + 1, fn, baton);
319 else
320 result = -1;
321
322 if (result >= 0 || (*key != '/' && *key != 0))
323 return result;
324 if (root->value)
325 return fn(key, root->value, baton);
326 else
327 return -1;
328}
329
330static struct trie common_trie;
331static int common_trie_done_setup;
332
333static void init_common_trie(void)
334{
335 struct common_dir *p;
336
337 if (common_trie_done_setup)
338 return;
339
SZEDER Gáborc72fc402019-10-21 18:00:42 +0200340 for (p = common_list; p->path; p++)
341 add_to_trie(&common_trie, p->path, p);
David Turner4e09cf22015-08-31 22:13:10 -0400342
343 common_trie_done_setup = 1;
344}
345
346/*
347 * Helper function for update_common_dir: returns 1 if the dir
348 * prefix is common.
349 */
350static int check_common(const char *unmatched, void *value, void *baton)
351{
352 struct common_dir *dir = value;
353
David Turner4e09cf22015-08-31 22:13:10 -0400354 if (dir->is_dir && (unmatched[0] == 0 || unmatched[0] == '/'))
SZEDER Gáborc72fc402019-10-21 18:00:42 +0200355 return dir->is_common;
David Turner4e09cf22015-08-31 22:13:10 -0400356
357 if (!dir->is_dir && unmatched[0] == 0)
SZEDER Gáborc72fc402019-10-21 18:00:42 +0200358 return dir->is_common;
David Turner4e09cf22015-08-31 22:13:10 -0400359
360 return 0;
361}
362
Junio C Hamano1c630ba2015-10-15 15:43:31 -0700363static void update_common_dir(struct strbuf *buf, int git_dir_len,
364 const char *common_dir)
Nguyễn Thái Ngọc Duyc7b3a3d2014-11-30 15:24:36 +0700365{
366 char *base = buf->buf + git_dir_len;
Johannes Schindelin76a53d62019-10-28 12:57:18 +0000367 int has_lock_suffix = strbuf_strip_suffix(buf, LOCK_SUFFIX);
368
David Turner4e09cf22015-08-31 22:13:10 -0400369 init_common_trie();
370 if (trie_find(&common_trie, base, check_common, NULL) > 0)
Junio C Hamano1c630ba2015-10-15 15:43:31 -0700371 replace_dir(buf, git_dir_len, common_dir);
Johannes Schindelin76a53d62019-10-28 12:57:18 +0000372
373 if (has_lock_suffix)
374 strbuf_addstr(buf, LOCK_SUFFIX);
Nguyễn Thái Ngọc Duyc7b3a3d2014-11-30 15:24:36 +0700375}
376
Nguyễn Thái Ngọc Duy77a6d842014-11-30 15:24:54 +0700377void report_linked_checkout_garbage(void)
378{
379 struct strbuf sb = STRBUF_INIT;
David Turner07015302015-08-31 22:13:09 -0400380 const struct common_dir *p;
Nguyễn Thái Ngọc Duy77a6d842014-11-30 15:24:54 +0700381 int len;
382
Brandon Williamsc14c2342017-06-22 11:43:33 -0700383 if (!the_repository->different_commondir)
Nguyễn Thái Ngọc Duy77a6d842014-11-30 15:24:54 +0700384 return;
385 strbuf_addf(&sb, "%s/", get_git_dir());
386 len = sb.len;
SZEDER Gáborc72fc402019-10-21 18:00:42 +0200387 for (p = common_list; p->path; p++) {
388 const char *path = p->path;
David Turner07015302015-08-31 22:13:09 -0400389 if (p->ignore_garbage)
Nguyễn Thái Ngọc Duy77a6d842014-11-30 15:24:54 +0700390 continue;
391 strbuf_setlen(&sb, len);
392 strbuf_addstr(&sb, path);
393 if (file_exists(sb.buf))
Junio C Hamano0a489b02015-08-13 13:02:52 -0500394 report_garbage(PACKDIR_FILE_GARBAGE, sb.buf);
Nguyễn Thái Ngọc Duy77a6d842014-11-30 15:24:54 +0700395 }
396 strbuf_release(&sb);
397}
398
Brandon Williamsf9a8a472017-06-22 11:43:38 -0700399static void adjust_git_path(const struct repository *repo,
400 struct strbuf *buf, int git_dir_len)
Nguyễn Thái Ngọc Duy557bd832014-11-30 15:24:31 +0700401{
402 const char *base = buf->buf + git_dir_len;
Brandon Williamsc14c2342017-06-22 11:43:33 -0700403 if (is_dir_file(base, "info", "grafts"))
Nguyễn Thái Ngọc Duy557bd832014-11-30 15:24:31 +0700404 strbuf_splice(buf, 0, buf->len,
Brandon Williamsf9a8a472017-06-22 11:43:38 -0700405 repo->graft_file, strlen(repo->graft_file));
Brandon Williamsc14c2342017-06-22 11:43:33 -0700406 else if (!strcmp(base, "index"))
Nguyễn Thái Ngọc Duy557bd832014-11-30 15:24:31 +0700407 strbuf_splice(buf, 0, buf->len,
Brandon Williamsf9a8a472017-06-22 11:43:38 -0700408 repo->index_file, strlen(repo->index_file));
Brandon Williamsc14c2342017-06-22 11:43:33 -0700409 else if (dir_prefix(base, "objects"))
Jeff Kingf0eaf632018-11-12 09:50:39 -0500410 replace_dir(buf, git_dir_len + 7, repo->objects->odb->path);
Johannes Schindelin9445b492016-08-16 15:14:27 +0200411 else if (git_hooks_path && dir_prefix(base, "hooks"))
412 replace_dir(buf, git_dir_len + 5, git_hooks_path);
Brandon Williamsf9a8a472017-06-22 11:43:38 -0700413 else if (repo->different_commondir)
414 update_common_dir(buf, git_dir_len, repo->commondir);
Nguyễn Thái Ngọc Duy557bd832014-11-30 15:24:31 +0700415}
416
Brandon Williamsf9a8a472017-06-22 11:43:38 -0700417static void strbuf_worktree_gitdir(struct strbuf *buf,
418 const struct repository *repo,
419 const struct worktree *wt)
420{
421 if (!wt)
422 strbuf_addstr(buf, repo->gitdir);
423 else if (!wt->id)
424 strbuf_addstr(buf, repo->commondir);
425 else
426 strbuf_git_common_path(buf, repo, "worktrees/%s", wt->id);
427}
428
429static void do_git_path(const struct repository *repo,
430 const struct worktree *wt, struct strbuf *buf,
Nguyễn Thái Ngọc Duy2e641d52016-04-22 20:01:29 +0700431 const char *fmt, va_list args)
Linus Torvaldse7676d22006-09-11 12:03:15 -0700432{
Nguyễn Thái Ngọc Duy557bd832014-11-30 15:24:31 +0700433 int gitdir_len;
Brandon Williamsf9a8a472017-06-22 11:43:38 -0700434 strbuf_worktree_gitdir(buf, repo, wt);
Nguyễn Thái Ngọc Duy4ef9caf2014-11-30 15:24:26 +0700435 if (buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
436 strbuf_addch(buf, '/');
Nguyễn Thái Ngọc Duy557bd832014-11-30 15:24:31 +0700437 gitdir_len = buf->len;
Nguyễn Thái Ngọc Duy4ef9caf2014-11-30 15:24:26 +0700438 strbuf_vaddf(buf, fmt, args);
Brandon Williams54310732017-06-22 11:43:39 -0700439 if (!wt)
440 adjust_git_path(repo, buf, gitdir_len);
Nguyễn Thái Ngọc Duy4ef9caf2014-11-30 15:24:26 +0700441 strbuf_cleanup_path(buf);
Linus Torvalds26c8a532005-07-08 16:20:59 -0700442}
443
Brandon Williams3181d862017-06-22 11:43:40 -0700444char *repo_git_path(const struct repository *repo,
445 const char *fmt, ...)
446{
447 struct strbuf path = STRBUF_INIT;
448 va_list args;
449 va_start(args, fmt);
450 do_git_path(repo, NULL, &path, fmt, args);
451 va_end(args);
452 return strbuf_detach(&path, NULL);
453}
454
455void strbuf_repo_git_path(struct strbuf *sb,
456 const struct repository *repo,
457 const char *fmt, ...)
458{
459 va_list args;
460 va_start(args, fmt);
461 do_git_path(repo, NULL, sb, fmt, args);
462 va_end(args);
463}
464
Jeff Kingbb3788c2015-09-24 17:05:40 -0400465char *git_path_buf(struct strbuf *buf, const char *fmt, ...)
466{
467 va_list args;
468 strbuf_reset(buf);
469 va_start(args, fmt);
Brandon Williamsf9a8a472017-06-22 11:43:38 -0700470 do_git_path(the_repository, NULL, buf, fmt, args);
Jeff Kingbb3788c2015-09-24 17:05:40 -0400471 va_end(args);
472 return buf->buf;
473}
474
Nguyễn Thái Ngọc Duy1a83c242014-11-30 15:24:28 +0700475void strbuf_git_path(struct strbuf *sb, const char *fmt, ...)
Alex Riesenaba13e72008-10-27 11:17:51 +0100476{
477 va_list args;
478 va_start(args, fmt);
Brandon Williamsf9a8a472017-06-22 11:43:38 -0700479 do_git_path(the_repository, NULL, sb, fmt, args);
Alex Riesenaba13e72008-10-27 11:17:51 +0100480 va_end(args);
Alex Riesenaba13e72008-10-27 11:17:51 +0100481}
482
Nguyễn Thái Ngọc Duy57a23b72014-11-30 15:24:30 +0700483const char *git_path(const char *fmt, ...)
484{
485 struct strbuf *pathname = get_pathname();
486 va_list args;
487 va_start(args, fmt);
Brandon Williamsf9a8a472017-06-22 11:43:38 -0700488 do_git_path(the_repository, NULL, pathname, fmt, args);
Nguyễn Thái Ngọc Duy57a23b72014-11-30 15:24:30 +0700489 va_end(args);
490 return pathname->buf;
Alex Riesenaba13e72008-10-27 11:17:51 +0100491}
492
493char *git_pathdup(const char *fmt, ...)
494{
Nguyễn Thái Ngọc Duy4ef9caf2014-11-30 15:24:26 +0700495 struct strbuf path = STRBUF_INIT;
Alex Riesenaba13e72008-10-27 11:17:51 +0100496 va_list args;
497 va_start(args, fmt);
Brandon Williamsf9a8a472017-06-22 11:43:38 -0700498 do_git_path(the_repository, NULL, &path, fmt, args);
Alex Riesenaba13e72008-10-27 11:17:51 +0100499 va_end(args);
Nguyễn Thái Ngọc Duy4ef9caf2014-11-30 15:24:26 +0700500 return strbuf_detach(&path, NULL);
Alex Riesenaba13e72008-10-27 11:17:51 +0100501}
502
Huynh Khoi Nguyen Nguyen21cf3222012-06-22 11:03:23 +0200503char *mkpathdup(const char *fmt, ...)
504{
Huynh Khoi Nguyen Nguyen21cf3222012-06-22 11:03:23 +0200505 struct strbuf sb = STRBUF_INIT;
506 va_list args;
Huynh Khoi Nguyen Nguyen21cf3222012-06-22 11:03:23 +0200507 va_start(args, fmt);
508 strbuf_vaddf(&sb, fmt, args);
509 va_end(args);
Nguyễn Thái Ngọc Duy4ef9caf2014-11-30 15:24:26 +0700510 strbuf_cleanup_path(&sb);
511 return strbuf_detach(&sb, NULL);
Huynh Khoi Nguyen Nguyen21cf3222012-06-22 11:03:23 +0200512}
513
Nguyễn Thái Ngọc Duydcf69262014-11-30 15:24:27 +0700514const char *mkpath(const char *fmt, ...)
Linus Torvalds26c8a532005-07-08 16:20:59 -0700515{
516 va_list args;
Nguyễn Thái Ngọc Duy4ef9caf2014-11-30 15:24:26 +0700517 struct strbuf *pathname = get_pathname();
Linus Torvalds26c8a532005-07-08 16:20:59 -0700518 va_start(args, fmt);
Nguyễn Thái Ngọc Duy4ef9caf2014-11-30 15:24:26 +0700519 strbuf_vaddf(pathname, fmt, args);
Linus Torvalds26c8a532005-07-08 16:20:59 -0700520 va_end(args);
Nguyễn Thái Ngọc Duy4ef9caf2014-11-30 15:24:26 +0700521 return cleanup_path(pathname->buf);
Linus Torvalds26c8a532005-07-08 16:20:59 -0700522}
Holger Eitzenbergerf2db68e2005-08-04 22:43:03 +0200523
Nguyễn Thái Ngọc Duy2e641d52016-04-22 20:01:29 +0700524const char *worktree_git_path(const struct worktree *wt, const char *fmt, ...)
525{
526 struct strbuf *pathname = get_pathname();
527 va_list args;
528 va_start(args, fmt);
Brandon Williamsf9a8a472017-06-22 11:43:38 -0700529 do_git_path(the_repository, wt, pathname, fmt, args);
Nguyễn Thái Ngọc Duy2e641d52016-04-22 20:01:29 +0700530 va_end(args);
531 return pathname->buf;
532}
533
Brandon Williamsb42b0c02017-06-22 11:43:41 -0700534static void do_worktree_path(const struct repository *repo,
535 struct strbuf *buf,
536 const char *fmt, va_list args)
537{
538 strbuf_addstr(buf, repo->worktree);
539 if(buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
540 strbuf_addch(buf, '/');
541
542 strbuf_vaddf(buf, fmt, args);
543 strbuf_cleanup_path(buf);
544}
545
546char *repo_worktree_path(const struct repository *repo, const char *fmt, ...)
547{
548 struct strbuf path = STRBUF_INIT;
549 va_list args;
550
551 if (!repo->worktree)
552 return NULL;
553
554 va_start(args, fmt);
555 do_worktree_path(repo, &path, fmt, args);
556 va_end(args);
557
558 return strbuf_detach(&path, NULL);
559}
560
561void strbuf_repo_worktree_path(struct strbuf *sb,
562 const struct repository *repo,
563 const char *fmt, ...)
564{
565 va_list args;
566
567 if (!repo->worktree)
568 return;
569
570 va_start(args, fmt);
571 do_worktree_path(repo, sb, fmt, args);
572 va_end(args);
573}
574
Jacob Keller99b43a62016-08-31 16:27:22 -0700575/* Returns 0 on success, negative on failure. */
Jacob Keller99b43a62016-08-31 16:27:22 -0700576static int do_submodule_path(struct strbuf *buf, const char *path,
577 const char *fmt, va_list args)
Heiko Voigt0bad6112010-07-07 15:39:11 +0200578{
Max Kirillov11f9dd72015-09-14 01:17:42 +0300579 struct strbuf git_submodule_common_dir = STRBUF_INIT;
580 struct strbuf git_submodule_dir = STRBUF_INIT;
Nguyễn Thái Ngọc Duybbbb7de2017-03-26 09:42:30 +0700581 int ret;
Heiko Voigt0bad6112010-07-07 15:39:11 +0200582
Nguyễn Thái Ngọc Duybbbb7de2017-03-26 09:42:30 +0700583 ret = submodule_to_gitdir(&git_submodule_dir, path);
584 if (ret)
585 goto cleanup;
Heiko Voigt0bad6112010-07-07 15:39:11 +0200586
Nguyễn Thái Ngọc Duybbbb7de2017-03-26 09:42:30 +0700587 strbuf_complete(&git_submodule_dir, '/');
588 strbuf_addbuf(buf, &git_submodule_dir);
Nguyễn Thái Ngọc Duy4ef9caf2014-11-30 15:24:26 +0700589 strbuf_vaddf(buf, fmt, args);
Max Kirillov11f9dd72015-09-14 01:17:42 +0300590
591 if (get_common_dir_noenv(&git_submodule_common_dir, git_submodule_dir.buf))
592 update_common_dir(buf, git_submodule_dir.len, git_submodule_common_dir.buf);
593
Nguyễn Thái Ngọc Duy4ef9caf2014-11-30 15:24:26 +0700594 strbuf_cleanup_path(buf);
Max Kirillov11f9dd72015-09-14 01:17:42 +0300595
Jacob Keller99b43a62016-08-31 16:27:22 -0700596cleanup:
Max Kirillov11f9dd72015-09-14 01:17:42 +0300597 strbuf_release(&git_submodule_dir);
598 strbuf_release(&git_submodule_common_dir);
Nguyễn Thái Ngọc Duybbbb7de2017-03-26 09:42:30 +0700599 return ret;
Jeff Kingf5895fd2015-08-10 05:32:22 -0400600}
601
Jeff Kingf5895fd2015-08-10 05:32:22 -0400602char *git_pathdup_submodule(const char *path, const char *fmt, ...)
603{
Jacob Keller99b43a62016-08-31 16:27:22 -0700604 int err;
Jeff Kingf5895fd2015-08-10 05:32:22 -0400605 va_list args;
606 struct strbuf buf = STRBUF_INIT;
607 va_start(args, fmt);
Jacob Keller99b43a62016-08-31 16:27:22 -0700608 err = do_submodule_path(&buf, path, fmt, args);
Jeff Kingf5895fd2015-08-10 05:32:22 -0400609 va_end(args);
Jacob Keller99b43a62016-08-31 16:27:22 -0700610 if (err) {
611 strbuf_release(&buf);
612 return NULL;
613 }
Jeff Kingf5895fd2015-08-10 05:32:22 -0400614 return strbuf_detach(&buf, NULL);
615}
616
Jacob Keller99b43a62016-08-31 16:27:22 -0700617int strbuf_git_path_submodule(struct strbuf *buf, const char *path,
618 const char *fmt, ...)
Jeff Kingf5895fd2015-08-10 05:32:22 -0400619{
Jacob Keller99b43a62016-08-31 16:27:22 -0700620 int err;
Jeff Kingf5895fd2015-08-10 05:32:22 -0400621 va_list args;
622 va_start(args, fmt);
Jacob Keller99b43a62016-08-31 16:27:22 -0700623 err = do_submodule_path(buf, path, fmt, args);
Jeff Kingf5895fd2015-08-10 05:32:22 -0400624 va_end(args);
Jacob Keller99b43a62016-08-31 16:27:22 -0700625
626 return err;
Jeff Kingf5895fd2015-08-10 05:32:22 -0400627}
628
Brandon Williamsb3371722017-06-22 11:43:37 -0700629static void do_git_common_path(const struct repository *repo,
630 struct strbuf *buf,
Nguyễn Thái Ngọc Duy15cdfea2016-04-22 20:01:25 +0700631 const char *fmt,
632 va_list args)
633{
Brandon Williamsb3371722017-06-22 11:43:37 -0700634 strbuf_addstr(buf, repo->commondir);
Nguyễn Thái Ngọc Duy15cdfea2016-04-22 20:01:25 +0700635 if (buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
636 strbuf_addch(buf, '/');
637 strbuf_vaddf(buf, fmt, args);
638 strbuf_cleanup_path(buf);
639}
640
641const char *git_common_path(const char *fmt, ...)
642{
643 struct strbuf *pathname = get_pathname();
644 va_list args;
645 va_start(args, fmt);
Brandon Williamsb3371722017-06-22 11:43:37 -0700646 do_git_common_path(the_repository, pathname, fmt, args);
Nguyễn Thái Ngọc Duy15cdfea2016-04-22 20:01:25 +0700647 va_end(args);
648 return pathname->buf;
649}
650
Brandon Williamsb3371722017-06-22 11:43:37 -0700651void strbuf_git_common_path(struct strbuf *sb,
652 const struct repository *repo,
653 const char *fmt, ...)
Nguyễn Thái Ngọc Duy15cdfea2016-04-22 20:01:25 +0700654{
655 va_list args;
656 va_start(args, fmt);
Brandon Williamsb3371722017-06-22 11:43:37 -0700657 do_git_common_path(repo, sb, fmt, args);
Nguyễn Thái Ngọc Duy15cdfea2016-04-22 20:01:25 +0700658 va_end(args);
659}
660
Junio C Hamanoc847f532007-01-01 23:31:08 -0800661int validate_headref(const char *path)
Junio C Hamano0870ca72005-11-18 14:59:34 -0800662{
663 struct stat st;
Jeff King7eb4b9d2017-09-27 02:17:26 -0400664 char buffer[256];
665 const char *refname;
Jeff King0bca1652017-09-27 02:17:36 -0400666 struct object_id oid;
Heikki Orsila0104ca02008-04-27 21:21:58 +0300667 int fd;
668 ssize_t len;
Junio C Hamano0870ca72005-11-18 14:59:34 -0800669
670 if (lstat(path, &st) < 0)
671 return -1;
672
673 /* Make sure it is a "refs/.." symlink */
674 if (S_ISLNK(st.st_mode)) {
675 len = readlink(path, buffer, sizeof(buffer)-1);
Junio C Hamano222b1672009-02-12 13:02:09 -0800676 if (len >= 5 && !memcmp("refs/", buffer, 5))
Junio C Hamano0870ca72005-11-18 14:59:34 -0800677 return 0;
678 return -1;
679 }
680
681 /*
682 * Anything else, just open it and try to see if it is a symbolic ref.
683 */
684 fd = open(path, O_RDONLY);
685 if (fd < 0)
686 return -1;
Andy Whitcroft93d26e42007-01-08 15:58:08 +0000687 len = read_in_full(fd, buffer, sizeof(buffer)-1);
Junio C Hamano0870ca72005-11-18 14:59:34 -0800688 close(fd);
689
Jeff King6e68c912017-09-27 02:17:23 -0400690 if (len < 0)
691 return -1;
692 buffer[len] = '\0';
693
Junio C Hamano0870ca72005-11-18 14:59:34 -0800694 /*
695 * Is it a symbolic ref?
696 */
Jeff King7eb4b9d2017-09-27 02:17:26 -0400697 if (skip_prefix(buffer, "ref:", &refname)) {
698 while (isspace(*refname))
699 refname++;
700 if (starts_with(refname, "refs/"))
Junio C Hamanoc847f532007-01-01 23:31:08 -0800701 return 0;
702 }
703
704 /*
705 * Is this a detached HEAD?
706 */
Jeff King0bca1652017-09-27 02:17:36 -0400707 if (!get_oid_hex(buffer, &oid))
Junio C Hamano0870ca72005-11-18 14:59:34 -0800708 return 0;
Junio C Hamanoc847f532007-01-01 23:31:08 -0800709
Junio C Hamano0870ca72005-11-18 14:59:34 -0800710 return -1;
711}
712
Matthieu Moy395de252009-11-17 18:24:25 +0100713static struct passwd *getpw_str(const char *username, size_t len)
Andreas Ericsson54f4b872005-11-17 20:37:14 +0100714{
Junio C Hamanod79374c2005-12-03 01:45:57 -0800715 struct passwd *pw;
René Scharfe5c0b13f2014-07-19 17:35:34 +0200716 char *username_z = xmemdupz(username, len);
Matthieu Moy395de252009-11-17 18:24:25 +0100717 pw = getpwnam(username_z);
718 free(username_z);
719 return pw;
720}
Andreas Ericsson54f4b872005-11-17 20:37:14 +0100721
Matthieu Moy395de252009-11-17 18:24:25 +0100722/*
Johannes Schindelin789f6f22021-07-24 22:06:50 +0000723 * Return a string with ~ and ~user expanded via getpw*. Returns NULL on getpw
724 * failure or if path is NULL.
Nguyễn Thái Ngọc Duy4aad2f12017-04-05 17:24:38 +0700725 *
Johannes Schindelin644e6b22021-07-24 22:06:51 +0000726 * If real_home is true, strbuf_realpath($HOME) is used in the `~/` expansion.
Johannes Schindeline394a162021-07-24 22:06:53 +0000727 *
728 * If the path starts with `%(prefix)/`, the remainder is interpreted as
729 * relative to where Git is installed, and expanded to the absolute path.
Matthieu Moy395de252009-11-17 18:24:25 +0100730 */
Johannes Schindelina03b0972021-07-24 22:06:52 +0000731char *interpolate_path(const char *path, int real_home)
Matthieu Moy395de252009-11-17 18:24:25 +0100732{
733 struct strbuf user_path = STRBUF_INIT;
Matthieu Moy395de252009-11-17 18:24:25 +0100734 const char *to_copy = path;
735
736 if (path == NULL)
737 goto return_null;
Johannes Schindeline394a162021-07-24 22:06:53 +0000738
739 if (skip_prefix(path, "%(prefix)/", &path))
740 return system_path(path);
741
Matthieu Moy395de252009-11-17 18:24:25 +0100742 if (path[0] == '~') {
Jeff King53ec5512014-01-27 20:36:12 -0500743 const char *first_slash = strchrnul(path, '/');
Matthieu Moy395de252009-11-17 18:24:25 +0100744 const char *username = path + 1;
745 size_t username_len = first_slash - username;
Matthieu Moydf2a79f2009-11-19 16:21:15 +0100746 if (username_len == 0) {
747 const char *home = getenv("HOME");
Jonathan Nieder79bf1492010-07-26 10:06:51 -0500748 if (!home)
749 goto return_null;
Nguyễn Thái Ngọc Duy4aad2f12017-04-05 17:24:38 +0700750 if (real_home)
René Scharfefa2bb342017-10-01 16:44:06 +0200751 strbuf_add_real_path(&user_path, home);
Nguyễn Thái Ngọc Duy4aad2f12017-04-05 17:24:38 +0700752 else
753 strbuf_addstr(&user_path, home);
Johannes Schindelin5ca6b7b2016-03-23 11:55:00 +0100754#ifdef GIT_WINDOWS_NATIVE
755 convert_slashes(user_path.buf);
756#endif
Matthieu Moydf2a79f2009-11-19 16:21:15 +0100757 } else {
758 struct passwd *pw = getpw_str(username, username_len);
759 if (!pw)
760 goto return_null;
René Scharfecedc61a2014-07-17 01:38:18 +0200761 strbuf_addstr(&user_path, pw->pw_dir);
Junio C Hamanod79374c2005-12-03 01:45:57 -0800762 }
Matthieu Moy395de252009-11-17 18:24:25 +0100763 to_copy = first_slash;
Junio C Hamano0870ca72005-11-18 14:59:34 -0800764 }
René Scharfecedc61a2014-07-17 01:38:18 +0200765 strbuf_addstr(&user_path, to_copy);
Matthieu Moy395de252009-11-17 18:24:25 +0100766 return strbuf_detach(&user_path, NULL);
767return_null:
768 strbuf_release(&user_path);
769 return NULL;
Junio C Hamanod79374c2005-12-03 01:45:57 -0800770}
Andreas Ericsson54f4b872005-11-17 20:37:14 +0100771
Junio C Hamanod79374c2005-12-03 01:45:57 -0800772/*
773 * First, one directory to try is determined by the following algorithm.
774 *
775 * (0) If "strict" is given, the path is used as given and no DWIM is
776 * done. Otherwise:
777 * (1) "~/path" to mean path under the running user's home directory;
778 * (2) "~user/path" to mean path under named user's home directory;
779 * (3) "relative/path" to mean cwd relative directory; or
780 * (4) "/absolute/path" to mean absolute directory.
781 *
Paul Tanc8c3f1d2015-03-31 21:39:27 +0800782 * Unless "strict" is given, we check "%s/.git", "%s", "%s.git/.git", "%s.git"
783 * in this order. We select the first one that is a valid git repository, and
784 * chdir() to it. If none match, or we fail to chdir, we return NULL.
Junio C Hamanod79374c2005-12-03 01:45:57 -0800785 *
786 * If all goes well, we return the directory we used to chdir() (but
787 * before ~user is expanded), avoiding getcwd() resolving symbolic
788 * links. User relative paths are also returned as they are given,
789 * except DWIM suffixing.
790 */
Erik Faye-Lund1c64b482011-10-04 16:02:00 -0400791const char *enter_repo(const char *path, int strict)
Junio C Hamanod79374c2005-12-03 01:45:57 -0800792{
Jeff Kinge9ba6782015-09-24 17:07:45 -0400793 static struct strbuf validated_path = STRBUF_INIT;
794 static struct strbuf used_path = STRBUF_INIT;
Junio C Hamanod79374c2005-12-03 01:45:57 -0800795
796 if (!path)
797 return NULL;
798
799 if (!strict) {
800 static const char *suffix[] = {
Jeff Kingb3256eb2012-02-02 16:59:13 -0500801 "/.git", "", ".git/.git", ".git", NULL,
Junio C Hamanod79374c2005-12-03 01:45:57 -0800802 };
Phil Hord03106762011-10-04 16:05:17 -0400803 const char *gitfile;
Junio C Hamanod79374c2005-12-03 01:45:57 -0800804 int len = strlen(path);
805 int i;
Erik Faye-Lund1c64b482011-10-04 16:02:00 -0400806 while ((1 < len) && (path[len-1] == '/'))
Junio C Hamanod79374c2005-12-03 01:45:57 -0800807 len--;
Erik Faye-Lund1c64b482011-10-04 16:02:00 -0400808
Jeff Kinge9ba6782015-09-24 17:07:45 -0400809 /*
810 * We can handle arbitrary-sized buffers, but this remains as a
811 * sanity check on untrusted input.
812 */
Junio C Hamanod79374c2005-12-03 01:45:57 -0800813 if (PATH_MAX <= len)
814 return NULL;
Erik Faye-Lund1c64b482011-10-04 16:02:00 -0400815
Jeff Kinge9ba6782015-09-24 17:07:45 -0400816 strbuf_reset(&used_path);
817 strbuf_reset(&validated_path);
818 strbuf_add(&used_path, path, len);
819 strbuf_add(&validated_path, path, len);
820
821 if (used_path.buf[0] == '~') {
Johannes Schindelina03b0972021-07-24 22:06:52 +0000822 char *newpath = interpolate_path(used_path.buf, 0);
Jeff Kinge9ba6782015-09-24 17:07:45 -0400823 if (!newpath)
Junio C Hamanod79374c2005-12-03 01:45:57 -0800824 return NULL;
Jeff Kinge9ba6782015-09-24 17:07:45 -0400825 strbuf_attach(&used_path, newpath, strlen(newpath),
826 strlen(newpath));
Junio C Hamanod79374c2005-12-03 01:45:57 -0800827 }
Junio C Hamanod79374c2005-12-03 01:45:57 -0800828 for (i = 0; suffix[i]; i++) {
Jeff Kingb3256eb2012-02-02 16:59:13 -0500829 struct stat st;
Jeff Kinge9ba6782015-09-24 17:07:45 -0400830 size_t baselen = used_path.len;
831 strbuf_addstr(&used_path, suffix[i]);
832 if (!stat(used_path.buf, &st) &&
Jeff Kingb3256eb2012-02-02 16:59:13 -0500833 (S_ISREG(st.st_mode) ||
Jeff Kinge9ba6782015-09-24 17:07:45 -0400834 (S_ISDIR(st.st_mode) && is_git_directory(used_path.buf)))) {
835 strbuf_addstr(&validated_path, suffix[i]);
Junio C Hamanod79374c2005-12-03 01:45:57 -0800836 break;
837 }
Jeff Kinge9ba6782015-09-24 17:07:45 -0400838 strbuf_setlen(&used_path, baselen);
Junio C Hamanod79374c2005-12-03 01:45:57 -0800839 }
Phil Hord03106762011-10-04 16:05:17 -0400840 if (!suffix[i])
841 return NULL;
Junio C Hamano78891792015-10-20 15:24:00 -0700842 gitfile = read_gitfile(used_path.buf);
Jeff Kinge9ba6782015-09-24 17:07:45 -0400843 if (gitfile) {
844 strbuf_reset(&used_path);
845 strbuf_addstr(&used_path, gitfile);
846 }
847 if (chdir(used_path.buf))
Junio C Hamanod79374c2005-12-03 01:45:57 -0800848 return NULL;
Jeff Kinge9ba6782015-09-24 17:07:45 -0400849 path = validated_path.buf;
Junio C Hamanod79374c2005-12-03 01:45:57 -0800850 }
Nguyễn Thái Ngọc Duy1f5fbe12015-09-28 20:06:14 +0700851 else {
852 const char *gitfile = read_gitfile(path);
853 if (gitfile)
854 path = gitfile;
855 if (chdir(path))
856 return NULL;
857 }
Junio C Hamanod79374c2005-12-03 01:45:57 -0800858
Nguyễn Thái Ngọc Duy0f64cc42015-09-28 20:06:13 +0700859 if (is_git_directory(".")) {
Alexandr Miloslavskiy0915a5b2020-03-06 19:03:13 +0000860 set_git_dir(".", 0);
brian m. carlsoncfe39172020-02-22 20:17:37 +0000861 check_repository_format(NULL);
Junio C Hamanod79374c2005-12-03 01:45:57 -0800862 return path;
Andreas Ericsson54f4b872005-11-17 20:37:14 +0100863 }
864
865 return NULL;
866}
Junio C Hamano138086a2006-06-09 22:07:23 -0700867
Torsten Bögershausencbe43b82013-03-30 10:53:47 +0100868static int calc_shared_perm(int mode)
Junio C Hamano138086a2006-06-09 22:07:23 -0700869{
Torsten Bögershausencbe43b82013-03-30 10:53:47 +0100870 int tweak;
Junio C Hamano138086a2006-06-09 22:07:23 -0700871
Jeff King7875acb2016-03-11 17:36:49 -0500872 if (get_shared_repository() < 0)
873 tweak = -get_shared_repository();
Junio C Hamano5a688fe2009-03-25 16:19:36 -0700874 else
Jeff King7875acb2016-03-11 17:36:49 -0500875 tweak = get_shared_repository();
Junio C Hamano94df2502006-06-09 23:09:49 -0700876
Junio C Hamano5a688fe2009-03-25 16:19:36 -0700877 if (!(mode & S_IWUSR))
878 tweak &= ~0222;
879 if (mode & S_IXUSR)
880 /* Copy read bits to execute bits */
881 tweak |= (tweak & 0444) >> 2;
Jeff King7875acb2016-03-11 17:36:49 -0500882 if (get_shared_repository() < 0)
Junio C Hamano5a688fe2009-03-25 16:19:36 -0700883 mode = (mode & ~0777) | tweak;
884 else
Petr Baudis8c6202d2008-07-12 03:15:03 +0200885 mode |= tweak;
Junio C Hamano94df2502006-06-09 23:09:49 -0700886
Torsten Bögershausencbe43b82013-03-30 10:53:47 +0100887 return mode;
888}
889
890
891int adjust_shared_perm(const char *path)
892{
893 int old_mode, new_mode;
894
Jeff King7875acb2016-03-11 17:36:49 -0500895 if (!get_shared_repository())
Torsten Bögershausencbe43b82013-03-30 10:53:47 +0100896 return 0;
897 if (get_st_mode_bits(path, &old_mode) < 0)
898 return -1;
899
900 new_mode = calc_shared_perm(old_mode);
901 if (S_ISDIR(old_mode)) {
Heikki Orsila06cbe852008-04-16 11:34:24 +0300902 /* Copy read bits to execute bits */
Torsten Bögershausencbe43b82013-03-30 10:53:47 +0100903 new_mode |= (new_mode & 0444) >> 2;
904 new_mode |= FORCE_DIR_SET_GID;
Heikki Orsila06cbe852008-04-16 11:34:24 +0300905 }
906
Torsten Bögershausencbe43b82013-03-30 10:53:47 +0100907 if (((old_mode ^ new_mode) & ~S_IFMT) &&
908 chmod(path, (new_mode & ~S_IFMT)) < 0)
Junio C Hamano138086a2006-06-09 22:07:23 -0700909 return -2;
910 return 0;
911}
Johannes Schindeline5392c52007-08-01 01:28:59 +0100912
David Turnereb338762015-11-10 12:42:38 +0100913void safe_create_dir(const char *dir, int share)
914{
915 if (mkdir(dir, 0777) < 0) {
916 if (errno != EEXIST) {
917 perror(dir);
918 exit(1);
919 }
920 }
921 else if (share && adjust_shared_perm(dir))
922 die(_("Could not make %s writable by group"), dir);
923}
924
Jiang Xin7fbd4222013-10-14 10:29:39 +0800925static int have_same_root(const char *path1, const char *path2)
926{
927 int is_abs1, is_abs2;
928
929 is_abs1 = is_absolute_path(path1);
930 is_abs2 = is_absolute_path(path2);
931 return (is_abs1 && is_abs2 && tolower(path1[0]) == tolower(path2[0])) ||
932 (!is_abs1 && !is_abs2);
933}
934
Jiang Xine02ca722013-06-25 23:53:43 +0800935/*
936 * Give path as relative to prefix.
937 *
938 * The strbuf may or may not be used, so do not assume it contains the
939 * returned path.
940 */
941const char *relative_path(const char *in, const char *prefix,
942 struct strbuf *sb)
Linus Torvalds044bbbc2008-06-19 12:34:06 -0700943{
Jiang Xine02ca722013-06-25 23:53:43 +0800944 int in_len = in ? strlen(in) : 0;
945 int prefix_len = prefix ? strlen(prefix) : 0;
946 int in_off = 0;
947 int prefix_off = 0;
Junio C Hamano288123f2010-01-21 19:05:19 -0800948 int i = 0, j = 0;
949
Jiang Xine02ca722013-06-25 23:53:43 +0800950 if (!in_len)
951 return "./";
952 else if (!prefix_len)
953 return in;
954
Johannes Schindelin2f36eed2016-01-12 08:57:22 +0100955 if (have_same_root(in, prefix))
Jiang Xin7fbd4222013-10-14 10:29:39 +0800956 /* bypass dos_drive, for "c:" is identical to "C:" */
Johannes Schindelin2f36eed2016-01-12 08:57:22 +0100957 i = j = has_dos_drive_prefix(in);
958 else {
Jiang Xin7fbd4222013-10-14 10:29:39 +0800959 return in;
960 }
961
Jiang Xine02ca722013-06-25 23:53:43 +0800962 while (i < prefix_len && j < in_len && prefix[i] == in[j]) {
963 if (is_dir_sep(prefix[i])) {
964 while (is_dir_sep(prefix[i]))
Junio C Hamano288123f2010-01-21 19:05:19 -0800965 i++;
Jiang Xine02ca722013-06-25 23:53:43 +0800966 while (is_dir_sep(in[j]))
Junio C Hamano288123f2010-01-21 19:05:19 -0800967 j++;
Jiang Xine02ca722013-06-25 23:53:43 +0800968 prefix_off = i;
969 in_off = j;
970 } else {
971 i++;
972 j++;
973 }
974 }
975
976 if (
977 /* "prefix" seems like prefix of "in" */
978 i >= prefix_len &&
979 /*
980 * but "/foo" is not a prefix of "/foobar"
981 * (i.e. prefix not end with '/')
982 */
983 prefix_off < prefix_len) {
984 if (j >= in_len) {
985 /* in="/a/b", prefix="/a/b" */
986 in_off = in_len;
987 } else if (is_dir_sep(in[j])) {
988 /* in="/a/b/c", prefix="/a/b" */
989 while (is_dir_sep(in[j]))
990 j++;
991 in_off = j;
992 } else {
993 /* in="/a/bbb/c", prefix="/a/b" */
994 i = prefix_off;
995 }
996 } else if (
997 /* "in" is short than "prefix" */
998 j >= in_len &&
999 /* "in" not end with '/' */
1000 in_off < in_len) {
1001 if (is_dir_sep(prefix[i])) {
1002 /* in="/a/b", prefix="/a/b/c/" */
1003 while (is_dir_sep(prefix[i]))
1004 i++;
1005 in_off = in_len;
1006 }
1007 }
1008 in += in_off;
1009 in_len -= in_off;
1010
1011 if (i >= prefix_len) {
1012 if (!in_len)
1013 return "./";
1014 else
1015 return in;
1016 }
1017
1018 strbuf_reset(sb);
1019 strbuf_grow(sb, in_len);
1020
1021 while (i < prefix_len) {
1022 if (is_dir_sep(prefix[i])) {
1023 strbuf_addstr(sb, "../");
1024 while (is_dir_sep(prefix[i]))
1025 i++;
Junio C Hamano288123f2010-01-21 19:05:19 -08001026 continue;
Junio C Hamano288123f2010-01-21 19:05:19 -08001027 }
1028 i++;
Junio C Hamano288123f2010-01-21 19:05:19 -08001029 }
Jiang Xine02ca722013-06-25 23:53:43 +08001030 if (!is_dir_sep(prefix[prefix_len - 1]))
1031 strbuf_addstr(sb, "../");
1032
1033 strbuf_addstr(sb, in);
1034
1035 return sb->buf;
Linus Torvalds044bbbc2008-06-19 12:34:06 -07001036}
David Reissae299be2008-05-19 23:48:54 -07001037
1038/*
Jiang Xin41894ae2013-10-14 10:29:40 +08001039 * A simpler implementation of relative_path
1040 *
1041 * Get relative path by removing "prefix" from "in". This function
1042 * first appears in v1.5.6-1-g044bbbc, and makes git_dir shorter
1043 * to increase performance when traversing the path to work_tree.
1044 */
1045const char *remove_leading_path(const char *in, const char *prefix)
1046{
Jeff King46357682015-09-24 17:07:47 -04001047 static struct strbuf buf = STRBUF_INIT;
Jiang Xin41894ae2013-10-14 10:29:40 +08001048 int i = 0, j = 0;
1049
1050 if (!prefix || !prefix[0])
1051 return in;
1052 while (prefix[i]) {
1053 if (is_dir_sep(prefix[i])) {
1054 if (!is_dir_sep(in[j]))
1055 return in;
1056 while (is_dir_sep(prefix[i]))
1057 i++;
1058 while (is_dir_sep(in[j]))
1059 j++;
1060 continue;
1061 } else if (in[j] != prefix[i]) {
1062 return in;
1063 }
1064 i++;
1065 j++;
1066 }
1067 if (
1068 /* "/foo" is a prefix of "/foo" */
1069 in[j] &&
1070 /* "/foo" is not a prefix of "/foobar" */
1071 !is_dir_sep(prefix[i-1]) && !is_dir_sep(in[j])
1072 )
1073 return in;
1074 while (is_dir_sep(in[j]))
1075 j++;
Jeff King46357682015-09-24 17:07:47 -04001076
1077 strbuf_reset(&buf);
Jiang Xin41894ae2013-10-14 10:29:40 +08001078 if (!in[j])
Jeff King46357682015-09-24 17:07:47 -04001079 strbuf_addstr(&buf, ".");
Jiang Xin41894ae2013-10-14 10:29:40 +08001080 else
Jeff King46357682015-09-24 17:07:47 -04001081 strbuf_addstr(&buf, in + j);
1082 return buf.buf;
Jiang Xin41894ae2013-10-14 10:29:40 +08001083}
1084
1085/*
Johannes Sixtf2a782b2009-02-07 16:08:31 +01001086 * It is okay if dst == src, but they should not overlap otherwise.
Jeff King9734b742020-01-30 04:52:19 -05001087 * The "dst" buffer must be at least as long as "src"; normalizing may shrink
1088 * the size of the path, but will never grow it.
David Reissae299be2008-05-19 23:48:54 -07001089 *
Johannes Sixtf2a782b2009-02-07 16:08:31 +01001090 * Performs the following normalizations on src, storing the result in dst:
1091 * - Ensures that components are separated by '/' (Windows only)
Johannes Sixt7814fbe2016-12-14 20:37:38 +01001092 * - Squashes sequences of '/' except "//server/share" on Windows
David Reissae299be2008-05-19 23:48:54 -07001093 * - Removes "." components.
1094 * - Removes ".." components, and the components the precede them.
Johannes Sixtf2a782b2009-02-07 16:08:31 +01001095 * Returns failure (non-zero) if a ".." component appears as first path
1096 * component anytime during the normalization. Otherwise, returns success (0).
David Reissae299be2008-05-19 23:48:54 -07001097 *
1098 * Note that this function is purely textual. It does not follow symlinks,
1099 * verify the existence of the path, or make any system calls.
Nguyễn Thái Ngọc Duy645a29c2013-07-14 15:36:03 +07001100 *
1101 * prefix_len != NULL is for a specific case of prefix_pathspec():
1102 * assume that src == dst and src[0..prefix_len-1] is already
1103 * normalized, any time "../" eats up to the prefix_len part,
1104 * prefix_len is reduced. In the end prefix_len is the remaining
1105 * prefix that has not been overridden by user pathspec.
Ray Donnellyb2a71232015-10-01 20:04:17 +01001106 *
1107 * NEEDSWORK: This function doesn't perform normalization w.r.t. trailing '/'.
1108 * For everything but the root folder itself, the normalized path should not
1109 * end with a '/', then the callers need to be fixed up accordingly.
1110 *
David Reissae299be2008-05-19 23:48:54 -07001111 */
Nguyễn Thái Ngọc Duy645a29c2013-07-14 15:36:03 +07001112int normalize_path_copy_len(char *dst, const char *src, int *prefix_len)
David Reissae299be2008-05-19 23:48:54 -07001113{
Johannes Sixtf3cad0a2009-02-07 16:08:28 +01001114 char *dst0;
Johannes Sixt7814fbe2016-12-14 20:37:38 +01001115 const char *end;
David Reissae299be2008-05-19 23:48:54 -07001116
Johannes Sixt7814fbe2016-12-14 20:37:38 +01001117 /*
1118 * Copy initial part of absolute path: "/", "C:/", "//server/share/".
1119 */
1120 end = src + offset_1st_component(src);
1121 while (src < end) {
1122 char c = *src++;
1123 if (is_dir_sep(c))
1124 c = '/';
1125 *dst++ = c;
1126 }
Johannes Sixtf3cad0a2009-02-07 16:08:28 +01001127 dst0 = dst;
David Reissae299be2008-05-19 23:48:54 -07001128
Johannes Sixt7814fbe2016-12-14 20:37:38 +01001129 while (is_dir_sep(*src))
1130 src++;
David Reissae299be2008-05-19 23:48:54 -07001131
Johannes Sixtf3cad0a2009-02-07 16:08:28 +01001132 for (;;) {
1133 char c = *src;
David Reissae299be2008-05-19 23:48:54 -07001134
Johannes Sixtf3cad0a2009-02-07 16:08:28 +01001135 /*
1136 * A path component that begins with . could be
1137 * special:
1138 * (1) "." and ends -- ignore and terminate.
1139 * (2) "./" -- ignore them, eat slash and continue.
1140 * (3) ".." and ends -- strip one and terminate.
1141 * (4) "../" -- strip one, eat slash and continue.
1142 */
1143 if (c == '.') {
1144 if (!src[1]) {
1145 /* (1) */
1146 src++;
1147 } else if (is_dir_sep(src[1])) {
1148 /* (2) */
1149 src += 2;
1150 while (is_dir_sep(*src))
1151 src++;
1152 continue;
1153 } else if (src[1] == '.') {
1154 if (!src[2]) {
1155 /* (3) */
1156 src += 2;
1157 goto up_one;
1158 } else if (is_dir_sep(src[2])) {
1159 /* (4) */
1160 src += 3;
1161 while (is_dir_sep(*src))
1162 src++;
1163 goto up_one;
1164 }
1165 }
1166 }
1167
1168 /* copy up to the next '/', and eat all '/' */
1169 while ((c = *src++) != '\0' && !is_dir_sep(c))
1170 *dst++ = c;
1171 if (is_dir_sep(c)) {
1172 *dst++ = '/';
1173 while (is_dir_sep(c))
1174 c = *src++;
1175 src--;
1176 } else if (!c)
1177 break;
1178 continue;
1179
1180 up_one:
1181 /*
1182 * dst0..dst is prefix portion, and dst[-1] is '/';
1183 * go up one level.
1184 */
Johannes Sixtf42302b2009-02-07 16:08:30 +01001185 dst--; /* go to trailing '/' */
1186 if (dst <= dst0)
Johannes Sixtf3cad0a2009-02-07 16:08:28 +01001187 return -1;
Johannes Sixtf42302b2009-02-07 16:08:30 +01001188 /* Windows: dst[-1] cannot be backslash anymore */
1189 while (dst0 < dst && dst[-1] != '/')
1190 dst--;
Nguyễn Thái Ngọc Duy645a29c2013-07-14 15:36:03 +07001191 if (prefix_len && *prefix_len > dst - dst0)
1192 *prefix_len = dst - dst0;
Johannes Sixtf3cad0a2009-02-07 16:08:28 +01001193 }
David Reissae299be2008-05-19 23:48:54 -07001194 *dst = '\0';
Johannes Sixtf3cad0a2009-02-07 16:08:28 +01001195 return 0;
David Reissae299be2008-05-19 23:48:54 -07001196}
David Reiss0454dd92008-05-19 23:49:26 -07001197
Nguyễn Thái Ngọc Duy645a29c2013-07-14 15:36:03 +07001198int normalize_path_copy(char *dst, const char *src)
1199{
1200 return normalize_path_copy_len(dst, src, NULL);
1201}
1202
David Reiss0454dd92008-05-19 23:49:26 -07001203/*
1204 * path = Canonical absolute path
Michael Haggerty9e2326c2012-10-28 17:16:25 +01001205 * prefixes = string_list containing normalized, absolute paths without
1206 * trailing slashes (except for the root directory, which is denoted by "/").
David Reiss0454dd92008-05-19 23:49:26 -07001207 *
Michael Haggerty9e2326c2012-10-28 17:16:25 +01001208 * Determines, for each path in prefixes, whether the "prefix"
David Reiss0454dd92008-05-19 23:49:26 -07001209 * is an ancestor directory of path. Returns the length of the longest
1210 * ancestor directory, excluding any trailing slashes, or -1 if no prefix
Michael Haggerty31171d92012-10-28 17:16:24 +01001211 * is an ancestor. (Note that this means 0 is returned if prefixes is
1212 * ["/"].) "/foo" is not considered an ancestor of "/foobar". Directories
David Reiss0454dd92008-05-19 23:49:26 -07001213 * are not considered to be their own ancestors. path must be in a
1214 * canonical form: empty components, or "." or ".." components are not
Michael Haggerty9e2326c2012-10-28 17:16:25 +01001215 * allowed.
David Reiss0454dd92008-05-19 23:49:26 -07001216 */
Michael Haggerty31171d92012-10-28 17:16:24 +01001217int longest_ancestor_length(const char *path, struct string_list *prefixes)
David Reiss0454dd92008-05-19 23:49:26 -07001218{
Michael Haggertya5ccdbe2012-10-28 17:16:23 +01001219 int i, max_len = -1;
David Reiss0454dd92008-05-19 23:49:26 -07001220
Michael Haggerty31171d92012-10-28 17:16:24 +01001221 if (!strcmp(path, "/"))
David Reiss0454dd92008-05-19 23:49:26 -07001222 return -1;
1223
Michael Haggerty31171d92012-10-28 17:16:24 +01001224 for (i = 0; i < prefixes->nr; i++) {
1225 const char *ceil = prefixes->items[i].string;
Michael Haggertya5ccdbe2012-10-28 17:16:23 +01001226 int len = strlen(ceil);
1227
Michael Haggerty9e2326c2012-10-28 17:16:25 +01001228 if (len == 1 && ceil[0] == '/')
1229 len = 0; /* root matches anything, with length 0 */
1230 else if (!strncmp(path, ceil, len) && path[len] == '/')
1231 ; /* match of length len */
1232 else
1233 continue; /* no match */
David Reiss0454dd92008-05-19 23:49:26 -07001234
Michael Haggerty9e2326c2012-10-28 17:16:25 +01001235 if (len > max_len)
David Reiss0454dd92008-05-19 23:49:26 -07001236 max_len = len;
David Reiss0454dd92008-05-19 23:49:26 -07001237 }
1238
1239 return max_len;
1240}
Johannes Schindelin4fcc86b2009-02-19 20:10:49 +01001241
1242/* strip arbitrary amount of directory separators at end of path */
1243static inline int chomp_trailing_dir_sep(const char *path, int len)
1244{
1245 while (len && is_dir_sep(path[len - 1]))
1246 len--;
1247 return len;
1248}
1249
1250/*
brian m. carlsonce17feb2019-08-25 23:33:39 +00001251 * If path ends with suffix (complete path components), returns the offset of
1252 * the last character in the path before the suffix (sans trailing directory
1253 * separators), and -1 otherwise.
1254 */
1255static ssize_t stripped_path_suffix_offset(const char *path, const char *suffix)
1256{
1257 int path_len = strlen(path), suffix_len = strlen(suffix);
1258
1259 while (suffix_len) {
1260 if (!path_len)
1261 return -1;
1262
1263 if (is_dir_sep(path[path_len - 1])) {
1264 if (!is_dir_sep(suffix[suffix_len - 1]))
1265 return -1;
1266 path_len = chomp_trailing_dir_sep(path, path_len);
1267 suffix_len = chomp_trailing_dir_sep(suffix, suffix_len);
1268 }
1269 else if (path[--path_len] != suffix[--suffix_len])
1270 return -1;
1271 }
1272
1273 if (path_len && !is_dir_sep(path[path_len - 1]))
1274 return -1;
1275 return chomp_trailing_dir_sep(path, path_len);
1276}
1277
1278/*
1279 * Returns true if the path ends with components, considering only complete path
1280 * components, and false otherwise.
1281 */
1282int ends_with_path_components(const char *path, const char *components)
1283{
1284 return stripped_path_suffix_offset(path, components) != -1;
1285}
1286
1287/*
Johannes Schindelin4fcc86b2009-02-19 20:10:49 +01001288 * If path ends with suffix (complete path components), returns the
1289 * part before suffix (sans trailing directory separators).
1290 * Otherwise returns NULL.
1291 */
1292char *strip_path_suffix(const char *path, const char *suffix)
1293{
brian m. carlsonce17feb2019-08-25 23:33:39 +00001294 ssize_t offset = stripped_path_suffix_offset(path, suffix);
Johannes Schindelin4fcc86b2009-02-19 20:10:49 +01001295
brian m. carlsonce17feb2019-08-25 23:33:39 +00001296 return offset == -1 ? NULL : xstrndup(path, offset);
Johannes Schindelin4fcc86b2009-02-19 20:10:49 +01001297}
Shawn O. Pearce34b6cb82009-11-09 11:26:43 -08001298
1299int daemon_avoid_alias(const char *p)
1300{
1301 int sl, ndot;
1302
1303 /*
1304 * This resurrects the belts and suspenders paranoia check by HPA
1305 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
Junio C Hamano9517e6b2010-02-03 21:23:18 -08001306 * does not do getcwd() based path canonicalization.
Shawn O. Pearce34b6cb82009-11-09 11:26:43 -08001307 *
1308 * sl becomes true immediately after seeing '/' and continues to
1309 * be true as long as dots continue after that without intervening
1310 * non-dot character.
1311 */
1312 if (!p || (*p != '/' && *p != '~'))
1313 return -1;
1314 sl = 1; ndot = 0;
1315 p++;
1316
1317 while (1) {
1318 char ch = *p++;
1319 if (sl) {
1320 if (ch == '.')
1321 ndot++;
1322 else if (ch == '/') {
1323 if (ndot < 3)
1324 /* reject //, /./ and /../ */
1325 return -1;
1326 ndot = 0;
1327 }
1328 else if (ch == 0) {
1329 if (0 < ndot && ndot < 3)
1330 /* reject /.$ and /..$ */
1331 return -1;
1332 return 0;
1333 }
1334 else
1335 sl = ndot = 0;
1336 }
1337 else if (ch == 0)
1338 return 0;
1339 else if (ch == '/') {
1340 sl = 1;
1341 ndot = 0;
1342 }
1343 }
1344}
Nguyễn Thái Ngọc Duy4bb43de2010-02-16 12:22:08 +07001345
Johannes Schindelin525e7fb2019-09-16 20:44:31 +02001346/*
1347 * On NTFS, we need to be careful to disallow certain synonyms of the `.git/`
1348 * directory:
1349 *
1350 * - For historical reasons, file names that end in spaces or periods are
1351 * automatically trimmed. Therefore, `.git . . ./` is a valid way to refer
1352 * to `.git/`.
1353 *
1354 * - For other historical reasons, file names that do not conform to the 8.3
1355 * format (up to eight characters for the basename, three for the file
1356 * extension, certain characters not allowed such as `+`, etc) are associated
1357 * with a so-called "short name", at least on the `C:` drive by default.
1358 * Which means that `git~1/` is a valid way to refer to `.git/`.
1359 *
1360 * Note: Technically, `.git/` could receive the short name `git~2` if the
1361 * short name `git~1` were already used. In Git, however, we guarantee that
1362 * `.git` is the first item in a directory, therefore it will be associated
1363 * with the short name `git~1` (unless short names are disabled).
1364 *
Johannes Schindelin7c3745f2019-08-28 12:22:17 +02001365 * - For yet other historical reasons, NTFS supports so-called "Alternate Data
1366 * Streams", i.e. metadata associated with a given file, referred to via
1367 * `<filename>:<stream-name>:<stream-type>`. There exists a default stream
1368 * type for directories, allowing `.git/` to be accessed via
1369 * `.git::$INDEX_ALLOCATION/`.
1370 *
Johannes Schindelin525e7fb2019-09-16 20:44:31 +02001371 * When this function returns 1, it indicates that the specified file/directory
1372 * name refers to a `.git` file or directory, or to any of these synonyms, and
1373 * Git should therefore not track it.
1374 *
Johannes Schindelin7c3745f2019-08-28 12:22:17 +02001375 * For performance reasons, _all_ Alternate Data Streams of `.git/` are
1376 * forbidden, not just `::$INDEX_ALLOCATION`.
1377 *
Johannes Schindelin525e7fb2019-09-16 20:44:31 +02001378 * This function is intended to be used by `git fsck` even on platforms where
1379 * the backslash is a regular filename character, therefore it needs to handle
1380 * backlash characters in the provided `name` specially: they are interpreted
1381 * as directory separators.
1382 */
Johannes Schindelin1d1d69b2014-12-16 23:31:03 +01001383int is_ntfs_dotgit(const char *name)
1384{
Johannes Schindelin3a85dc72019-09-06 21:09:35 +02001385 char c;
Johannes Schindelin1d1d69b2014-12-16 23:31:03 +01001386
Johannes Schindelin3a85dc72019-09-06 21:09:35 +02001387 /*
1388 * Note that when we don't find `.git` or `git~1` we end up with `name`
1389 * advanced partway through the string. That's okay, though, as we
1390 * return immediately in those cases, without looking at `name` any
1391 * further.
1392 */
1393 c = *(name++);
1394 if (c == '.') {
1395 /* .git */
1396 if (((c = *(name++)) != 'g' && c != 'G') ||
1397 ((c = *(name++)) != 'i' && c != 'I') ||
1398 ((c = *(name++)) != 't' && c != 'T'))
Johannes Schindelin288a74b2019-09-23 08:58:11 +02001399 return 0;
Johannes Schindelin3a85dc72019-09-06 21:09:35 +02001400 } else if (c == 'g' || c == 'G') {
1401 /* git ~1 */
1402 if (((c = *(name++)) != 'i' && c != 'I') ||
1403 ((c = *(name++)) != 't' && c != 'T') ||
1404 *(name++) != '~' ||
1405 *(name++) != '1')
1406 return 0;
1407 } else
1408 return 0;
1409
1410 for (;;) {
1411 c = *(name++);
1412 if (!c || c == '\\' || c == '/' || c == ':')
1413 return 1;
1414 if (c != '.' && c != ' ')
1415 return 0;
1416 }
Johannes Schindelin1d1d69b2014-12-16 23:31:03 +01001417}
Paul Tanea192892015-04-21 12:06:27 +08001418
Johannes Schindeline7cb0b42018-05-11 16:03:54 +02001419static int is_ntfs_dot_generic(const char *name,
1420 const char *dotgit_name,
1421 size_t len,
1422 const char *dotgit_ntfs_shortname_prefix)
1423{
1424 int saw_tilde;
1425 size_t i;
1426
1427 if ((name[0] == '.' && !strncasecmp(name + 1, dotgit_name, len))) {
1428 i = len + 1;
1429only_spaces_and_periods:
1430 for (;;) {
1431 char c = name[i++];
Johannes Schindelin91bd4652019-08-28 12:22:17 +02001432 if (!c || c == ':')
Johannes Schindeline7cb0b42018-05-11 16:03:54 +02001433 return 1;
1434 if (c != ' ' && c != '.')
1435 return 0;
1436 }
1437 }
1438
1439 /*
1440 * Is it a regular NTFS short name, i.e. shortened to 6 characters,
1441 * followed by ~1, ... ~4?
1442 */
1443 if (!strncasecmp(name, dotgit_name, 6) && name[6] == '~' &&
1444 name[7] >= '1' && name[7] <= '4') {
1445 i = 8;
1446 goto only_spaces_and_periods;
1447 }
1448
1449 /*
1450 * Is it a fall-back NTFS short name (for details, see
1451 * https://en.wikipedia.org/wiki/8.3_filename?
1452 */
1453 for (i = 0, saw_tilde = 0; i < 8; i++)
1454 if (name[i] == '\0')
1455 return 0;
1456 else if (saw_tilde) {
1457 if (name[i] < '0' || name[i] > '9')
1458 return 0;
1459 } else if (name[i] == '~') {
1460 if (name[++i] < '1' || name[i] > '9')
1461 return 0;
1462 saw_tilde = 1;
1463 } else if (i >= 6)
1464 return 0;
Torsten Bögershausen30634772018-10-25 18:13:08 +02001465 else if (name[i] & 0x80) {
Johannes Schindeline7cb0b42018-05-11 16:03:54 +02001466 /*
1467 * We know our needles contain only ASCII, so we clamp
1468 * here to make the results of tolower() sane.
1469 */
1470 return 0;
1471 } else if (tolower(name[i]) != dotgit_ntfs_shortname_prefix[i])
1472 return 0;
1473
1474 goto only_spaces_and_periods;
1475}
1476
1477/*
1478 * Inline helper to make sure compiler resolves strlen() on literals at
1479 * compile time.
1480 */
1481static inline int is_ntfs_dot_str(const char *name, const char *dotgit_name,
1482 const char *dotgit_ntfs_shortname_prefix)
1483{
1484 return is_ntfs_dot_generic(name, dotgit_name, strlen(dotgit_name),
1485 dotgit_ntfs_shortname_prefix);
1486}
1487
1488int is_ntfs_dotgitmodules(const char *name)
1489{
1490 return is_ntfs_dot_str(name, "gitmodules", "gi7eba");
1491}
1492
1493int is_ntfs_dotgitignore(const char *name)
1494{
1495 return is_ntfs_dot_str(name, "gitignore", "gi250a");
1496}
1497
1498int is_ntfs_dotgitattributes(const char *name)
1499{
1500 return is_ntfs_dot_str(name, "gitattributes", "gi7d29");
1501}
1502
Jeff King801ed012021-05-03 16:43:22 -04001503int is_ntfs_dotmailmap(const char *name)
1504{
1505 return is_ntfs_dot_str(name, "mailmap", "maba30");
1506}
1507
Jeff King2491f772017-07-28 15:25:45 -04001508int looks_like_command_line_option(const char *str)
1509{
1510 return str && str[0] == '-';
1511}
1512
Lénaïc Huardcb7db5b2021-09-04 22:54:58 +02001513char *xdg_config_home_for(const char *subdir, const char *filename)
Paul Tanea192892015-04-21 12:06:27 +08001514{
1515 const char *home, *config_home;
1516
Lénaïc Huardcb7db5b2021-09-04 22:54:58 +02001517 assert(subdir);
Paul Tanea192892015-04-21 12:06:27 +08001518 assert(filename);
1519 config_home = getenv("XDG_CONFIG_HOME");
1520 if (config_home && *config_home)
Lénaïc Huardcb7db5b2021-09-04 22:54:58 +02001521 return mkpathdup("%s/%s/%s", config_home, subdir, filename);
Paul Tanea192892015-04-21 12:06:27 +08001522
1523 home = getenv("HOME");
1524 if (home)
Lénaïc Huardcb7db5b2021-09-04 22:54:58 +02001525 return mkpathdup("%s/.config/%s/%s", home, subdir, filename);
1526
Paul Tanea192892015-04-21 12:06:27 +08001527 return NULL;
1528}
Jeff Kingf9327292015-08-10 05:38:57 -04001529
Lénaïc Huardcb7db5b2021-09-04 22:54:58 +02001530char *xdg_config_home(const char *filename)
1531{
1532 return xdg_config_home_for("git", filename);
1533}
1534
Devin Lehmachere7f136b2017-03-13 16:43:54 -04001535char *xdg_cache_home(const char *filename)
1536{
1537 const char *home, *cache_home;
1538
1539 assert(filename);
1540 cache_home = getenv("XDG_CACHE_HOME");
1541 if (cache_home && *cache_home)
1542 return mkpathdup("%s/git/%s", cache_home, filename);
1543
1544 home = getenv("HOME");
1545 if (home)
1546 return mkpathdup("%s/.cache/git/%s", home, filename);
1547 return NULL;
1548}
1549
Stefan Beller102de882018-05-17 15:51:51 -07001550REPO_GIT_PATH_FUNC(squash_msg, "SQUASH_MSG")
1551REPO_GIT_PATH_FUNC(merge_msg, "MERGE_MSG")
1552REPO_GIT_PATH_FUNC(merge_rr, "MERGE_RR")
1553REPO_GIT_PATH_FUNC(merge_mode, "MERGE_MODE")
1554REPO_GIT_PATH_FUNC(merge_head, "MERGE_HEAD")
Denton Liua03b5552020-04-07 10:28:07 -04001555REPO_GIT_PATH_FUNC(merge_autostash, "MERGE_AUTOSTASH")
Elijah Newren52918282021-03-20 00:03:52 +00001556REPO_GIT_PATH_FUNC(auto_merge, "AUTO_MERGE")
Stefan Beller102de882018-05-17 15:51:51 -07001557REPO_GIT_PATH_FUNC(fetch_head, "FETCH_HEAD")
1558REPO_GIT_PATH_FUNC(shallow, "shallow")