blob: 7c1cd8182a81b9e8892960707cff8a0f7ff174cb [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 */
Elijah Newren61a7b982023-03-21 06:26:06 +00004#include "git-compat-util.h"
Elijah Newren0b027f62023-03-21 06:25:58 +00005#include "abspath.h"
Elijah Newren32a8f512023-03-21 06:26:03 +00006#include "environment.h"
Elijah Newrenf394e092023-03-21 06:25:54 +00007#include "gettext.h"
Elijah Newren41771fa2023-02-24 00:09:27 +00008#include "hex.h"
Brandon Williamsc14c2342017-06-22 11:43:33 -07009#include "repository.h"
Matthieu Moy395de252009-11-17 18:24:25 +010010#include "strbuf.h"
Michael Haggertya5ccdbe2012-10-28 17:16:23 +010011#include "string-list.h"
Nguyễn Thái Ngọc Duy77a6d842014-11-30 15:24:54 +070012#include "dir.h"
Nguyễn Thái Ngọc Duy2e641d52016-04-22 20:01:29 +070013#include "worktree.h"
Elijah Newrene38da482023-03-21 06:26:05 +000014#include "setup.h"
Jacob Keller99b43a62016-08-31 16:27:22 -070015#include "submodule-config.h"
Brandon Williamse7d72d02017-06-22 11:43:35 -070016#include "path.h"
Jonathan Tan0abe14f2017-08-18 15:20:26 -070017#include "packfile.h"
Stefan Beller90c62152018-03-23 18:20:55 +010018#include "object-store.h"
Johannes Schindelin76a53d62019-10-28 12:57:18 +000019#include "lockfile.h"
Johannes Schindeline394a162021-07-24 22:06:53 +000020#include "exec-cmd.h"
Elijah Newren65156bb2023-04-11 00:42:02 -070021#include "wrapper.h"
Linus Torvalds26c8a532005-07-08 16:20:59 -070022
Ramsay Jonesf66450a2013-06-22 20:42:47 +010023static int get_st_mode_bits(const char *path, int *mode)
Torsten Bögershausen0117c2f2013-03-23 13:40:29 +010024{
25 struct stat st;
26 if (lstat(path, &st) < 0)
27 return -1;
28 *mode = st.st_mode;
29 return 0;
30}
Torsten Bögershausen0117c2f2013-03-23 13:40:29 +010031
Linus Torvalds26c8a532005-07-08 16:20:59 -070032static char bad_path[] = "/bad-path/";
33
Nguyễn Thái Ngọc Duy4ef9caf2014-11-30 15:24:26 +070034static struct strbuf *get_pathname(void)
Linus Torvaldse7676d22006-09-11 12:03:15 -070035{
Nguyễn Thái Ngọc Duy4ef9caf2014-11-30 15:24:26 +070036 static struct strbuf pathname_array[4] = {
37 STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
38 };
Linus Torvaldse7676d22006-09-11 12:03:15 -070039 static int index;
René Scharfebb847352016-10-23 19:57:30 +020040 struct strbuf *sb = &pathname_array[index];
41 index = (index + 1) % ARRAY_SIZE(pathname_array);
Nguyễn Thái Ngọc Duy4ef9caf2014-11-30 15:24:26 +070042 strbuf_reset(sb);
43 return sb;
Linus Torvaldse7676d22006-09-11 12:03:15 -070044}
45
Jeff King82627152017-10-03 19:30:40 -040046static const char *cleanup_path(const char *path)
Linus Torvalds26c8a532005-07-08 16:20:59 -070047{
48 /* Clean it up */
Jeff King82627152017-10-03 19:30:40 -040049 if (skip_prefix(path, "./", &path)) {
Linus Torvalds26c8a532005-07-08 16:20:59 -070050 while (*path == '/')
51 path++;
52 }
53 return path;
54}
55
Nguyễn Thái Ngọc Duy4ef9caf2014-11-30 15:24:26 +070056static void strbuf_cleanup_path(struct strbuf *sb)
57{
Jeff King82627152017-10-03 19:30:40 -040058 const char *path = cleanup_path(sb->buf);
Nguyễn Thái Ngọc Duy4ef9caf2014-11-30 15:24:26 +070059 if (path > sb->buf)
60 strbuf_remove(sb, 0, path - sb->buf);
61}
62
Alex Riesen108bebe2008-10-26 22:59:13 +010063char *mksnpath(char *buf, size_t n, const char *fmt, ...)
64{
65 va_list args;
66 unsigned len;
67
68 va_start(args, fmt);
69 len = vsnprintf(buf, n, fmt, args);
70 va_end(args);
71 if (len >= n) {
Daniel Lowe9db56f72008-11-10 16:07:52 -050072 strlcpy(buf, bad_path, n);
Alex Riesen108bebe2008-10-26 22:59:13 +010073 return buf;
74 }
Jeff King82627152017-10-03 19:30:40 -040075 return (char *)cleanup_path(buf);
Alex Riesen108bebe2008-10-26 22:59:13 +010076}
77
Nguyễn Thái Ngọc Duy557bd832014-11-30 15:24:31 +070078static int dir_prefix(const char *buf, const char *dir)
Alex Riesenfe2d7772008-10-27 10:22:21 +010079{
Nguyễn Thái Ngọc Duy557bd832014-11-30 15:24:31 +070080 int len = strlen(dir);
81 return !strncmp(buf, dir, len) &&
82 (is_dir_sep(buf[len]) || buf[len] == '\0');
Alex Riesenfe2d7772008-10-27 10:22:21 +010083}
84
Nguyễn Thái Ngọc Duy557bd832014-11-30 15:24:31 +070085/* $buf =~ m|$dir/+$file| but without regex */
86static int is_dir_file(const char *buf, const char *dir, const char *file)
Alex Riesenaba13e72008-10-27 11:17:51 +010087{
Nguyễn Thái Ngọc Duy557bd832014-11-30 15:24:31 +070088 int len = strlen(dir);
89 if (strncmp(buf, dir, len) || !is_dir_sep(buf[len]))
90 return 0;
91 while (is_dir_sep(buf[len]))
92 len++;
93 return !strcmp(buf + len, file);
94}
95
96static void replace_dir(struct strbuf *buf, int len, const char *newdir)
97{
98 int newlen = strlen(newdir);
99 int need_sep = (buf->buf[len] && !is_dir_sep(buf->buf[len])) &&
100 !is_dir_sep(newdir[newlen - 1]);
101 if (need_sep)
102 len--; /* keep one char, to be replaced with '/' */
103 strbuf_splice(buf, 0, len, newdir, newlen);
104 if (need_sep)
105 buf->buf[newlen] = '/';
106}
107
David Turner07015302015-08-31 22:13:09 -0400108struct common_dir {
109 /* Not considered garbage for report_linked_checkout_garbage */
110 unsigned ignore_garbage:1;
111 unsigned is_dir:1;
SZEDER Gáborc72fc402019-10-21 18:00:42 +0200112 /* Belongs to the common dir, though it may contain paths that don't */
113 unsigned is_common:1;
114 const char *path;
David Turner07015302015-08-31 22:13:09 -0400115};
116
117static struct common_dir common_list[] = {
SZEDER Gáborc72fc402019-10-21 18:00:42 +0200118 { 0, 1, 1, "branches" },
119 { 0, 1, 1, "common" },
120 { 0, 1, 1, "hooks" },
121 { 0, 1, 1, "info" },
122 { 0, 0, 0, "info/sparse-checkout" },
123 { 1, 1, 1, "logs" },
124 { 1, 0, 0, "logs/HEAD" },
125 { 0, 1, 0, "logs/refs/bisect" },
126 { 0, 1, 0, "logs/refs/rewritten" },
127 { 0, 1, 0, "logs/refs/worktree" },
128 { 0, 1, 1, "lost-found" },
129 { 0, 1, 1, "objects" },
130 { 0, 1, 1, "refs" },
131 { 0, 1, 0, "refs/bisect" },
132 { 0, 1, 0, "refs/rewritten" },
133 { 0, 1, 0, "refs/worktree" },
134 { 0, 1, 1, "remotes" },
135 { 0, 1, 1, "worktrees" },
136 { 0, 1, 1, "rr-cache" },
137 { 0, 1, 1, "svn" },
138 { 0, 0, 1, "config" },
139 { 1, 0, 1, "gc.pid" },
140 { 0, 0, 1, "packed-refs" },
141 { 0, 0, 1, "shallow" },
David Turner07015302015-08-31 22:13:09 -0400142 { 0, 0, 0, NULL }
Nguyễn Thái Ngọc Duyc7b3a3d2014-11-30 15:24:36 +0700143};
144
David Turner4e09cf22015-08-31 22:13:10 -0400145/*
146 * A compressed trie. A trie node consists of zero or more characters that
147 * are common to all elements with this prefix, optionally followed by some
148 * children. If value is not NULL, the trie node is a terminal node.
149 *
150 * For example, consider the following set of strings:
151 * abc
152 * def
153 * definite
154 * definition
155 *
Li Peng832c0e52016-05-06 20:36:46 +0800156 * The trie would look like:
David Turner4e09cf22015-08-31 22:13:10 -0400157 * root: len = 0, children a and d non-NULL, value = NULL.
158 * a: len = 2, contents = bc, value = (data for "abc")
159 * d: len = 2, contents = ef, children i non-NULL, value = (data for "def")
160 * i: len = 3, contents = nit, children e and i non-NULL, value = NULL
161 * e: len = 0, children all NULL, value = (data for "definite")
162 * i: len = 2, contents = on, children all NULL,
163 * value = (data for "definition")
164 */
165struct trie {
166 struct trie *children[256];
167 int len;
168 char *contents;
169 void *value;
170};
171
172static struct trie *make_trie_node(const char *key, void *value)
173{
174 struct trie *new_node = xcalloc(1, sizeof(*new_node));
175 new_node->len = strlen(key);
176 if (new_node->len) {
177 new_node->contents = xmalloc(new_node->len);
178 memcpy(new_node->contents, key, new_node->len);
179 }
180 new_node->value = value;
181 return new_node;
182}
183
184/*
185 * Add a key/value pair to a trie. The key is assumed to be \0-terminated.
186 * If there was an existing value for this key, return it.
187 */
188static void *add_to_trie(struct trie *root, const char *key, void *value)
189{
190 struct trie *child;
191 void *old;
192 int i;
193
194 if (!*key) {
195 /* we have reached the end of the key */
196 old = root->value;
197 root->value = value;
198 return old;
199 }
200
201 for (i = 0; i < root->len; i++) {
202 if (root->contents[i] == key[i])
203 continue;
204
205 /*
206 * Split this node: child will contain this node's
207 * existing children.
208 */
Andrey Okoshkin55d7d152017-10-24 18:15:05 +0300209 child = xmalloc(sizeof(*child));
David Turner4e09cf22015-08-31 22:13:10 -0400210 memcpy(child->children, root->children, sizeof(root->children));
211
212 child->len = root->len - i - 1;
213 if (child->len) {
214 child->contents = xstrndup(root->contents + i + 1,
215 child->len);
216 }
217 child->value = root->value;
218 root->value = NULL;
219 root->len = i;
220
221 memset(root->children, 0, sizeof(root->children));
222 root->children[(unsigned char)root->contents[i]] = child;
223
224 /* This is the newly-added child. */
225 root->children[(unsigned char)key[i]] =
226 make_trie_node(key + i + 1, value);
227 return NULL;
228 }
229
230 /* We have matched the entire compressed section */
231 if (key[i]) {
232 child = root->children[(unsigned char)key[root->len]];
233 if (child) {
234 return add_to_trie(child, key + root->len + 1, value);
235 } else {
236 child = make_trie_node(key + root->len + 1, value);
237 root->children[(unsigned char)key[root->len]] = child;
238 return NULL;
239 }
240 }
241
242 old = root->value;
243 root->value = value;
244 return old;
245}
246
SZEDER Gábor7cb8c922019-10-21 18:00:40 +0200247typedef int (*match_fn)(const char *unmatched, void *value, void *baton);
David Turner4e09cf22015-08-31 22:13:10 -0400248
249/*
250 * Search a trie for some key. Find the longest /-or-\0-terminated
SZEDER Gábor7cb8c922019-10-21 18:00:40 +0200251 * prefix of the key for which the trie contains a value. If there is
252 * no such prefix, return -1. Otherwise call fn with the unmatched
253 * portion of the key and the found value. If fn returns 0 or
254 * positive, then return its return value. If fn returns negative,
255 * then call fn with the next-longest /-terminated prefix of the key
256 * (i.e. a parent directory) for which the trie contains a value, and
257 * handle its return value the same way. If there is no shorter
258 * /-terminated prefix with a value left, then return the negative
259 * return value of the most recent fn invocation.
David Turner4e09cf22015-08-31 22:13:10 -0400260 *
261 * The key is partially normalized: consecutive slashes are skipped.
262 *
SZEDER Gábor7cb8c922019-10-21 18:00:40 +0200263 * For example, consider the trie containing only [logs,
264 * logs/refs/bisect], both with values, but not logs/refs.
David Turner4e09cf22015-08-31 22:13:10 -0400265 *
SZEDER Gábor7cb8c922019-10-21 18:00:40 +0200266 * | key | unmatched | prefix to node | return value |
267 * |--------------------|----------------|------------------|--------------|
268 * | a | not called | n/a | -1 |
269 * | logstore | not called | n/a | -1 |
270 * | logs | \0 | logs | as per fn |
271 * | logs/ | / | logs | as per fn |
272 * | logs/refs | /refs | logs | as per fn |
273 * | logs/refs/ | /refs/ | logs | as per fn |
274 * | logs/refs/b | /refs/b | logs | as per fn |
275 * | logs/refs/bisected | /refs/bisected | logs | as per fn |
276 * | logs/refs/bisect | \0 | logs/refs/bisect | as per fn |
277 * | logs/refs/bisect/ | / | logs/refs/bisect | as per fn |
278 * | logs/refs/bisect/a | /a | logs/refs/bisect | as per fn |
279 * | (If fn in the previous line returns -1, then fn is called once more:) |
280 * | logs/refs/bisect/a | /refs/bisect/a | logs | as per fn |
281 * |--------------------|----------------|------------------|--------------|
David Turner4e09cf22015-08-31 22:13:10 -0400282 */
283static int trie_find(struct trie *root, const char *key, match_fn fn,
284 void *baton)
285{
286 int i;
287 int result;
288 struct trie *child;
289
290 if (!*key) {
291 /* we have reached the end of the key */
292 if (root->value && !root->len)
293 return fn(key, root->value, baton);
294 else
295 return -1;
296 }
297
298 for (i = 0; i < root->len; i++) {
299 /* Partial path normalization: skip consecutive slashes. */
300 if (key[i] == '/' && key[i+1] == '/') {
301 key++;
302 continue;
303 }
304 if (root->contents[i] != key[i])
305 return -1;
306 }
307
308 /* Matched the entire compressed section */
309 key += i;
SZEDER Gáborf45f88b2019-10-21 18:00:43 +0200310 if (!*key) {
David Turner4e09cf22015-08-31 22:13:10 -0400311 /* End of key */
SZEDER Gáborf45f88b2019-10-21 18:00:43 +0200312 if (root->value)
313 return fn(key, root->value, baton);
314 else
315 return -1;
316 }
David Turner4e09cf22015-08-31 22:13:10 -0400317
318 /* Partial path normalization: skip consecutive slashes */
319 while (key[0] == '/' && key[1] == '/')
320 key++;
321
322 child = root->children[(unsigned char)*key];
323 if (child)
324 result = trie_find(child, key + 1, fn, baton);
325 else
326 result = -1;
327
328 if (result >= 0 || (*key != '/' && *key != 0))
329 return result;
330 if (root->value)
331 return fn(key, root->value, baton);
332 else
333 return -1;
334}
335
336static struct trie common_trie;
337static int common_trie_done_setup;
338
339static void init_common_trie(void)
340{
341 struct common_dir *p;
342
343 if (common_trie_done_setup)
344 return;
345
SZEDER Gáborc72fc402019-10-21 18:00:42 +0200346 for (p = common_list; p->path; p++)
347 add_to_trie(&common_trie, p->path, p);
David Turner4e09cf22015-08-31 22:13:10 -0400348
349 common_trie_done_setup = 1;
350}
351
352/*
353 * Helper function for update_common_dir: returns 1 if the dir
354 * prefix is common.
355 */
Jeff Kingd3dcfa02023-02-24 01:39:15 -0500356static int check_common(const char *unmatched, void *value,
357 void *baton UNUSED)
David Turner4e09cf22015-08-31 22:13:10 -0400358{
359 struct common_dir *dir = value;
360
David Turner4e09cf22015-08-31 22:13:10 -0400361 if (dir->is_dir && (unmatched[0] == 0 || unmatched[0] == '/'))
SZEDER Gáborc72fc402019-10-21 18:00:42 +0200362 return dir->is_common;
David Turner4e09cf22015-08-31 22:13:10 -0400363
364 if (!dir->is_dir && unmatched[0] == 0)
SZEDER Gáborc72fc402019-10-21 18:00:42 +0200365 return dir->is_common;
David Turner4e09cf22015-08-31 22:13:10 -0400366
367 return 0;
368}
369
Junio C Hamano1c630ba2015-10-15 15:43:31 -0700370static void update_common_dir(struct strbuf *buf, int git_dir_len,
371 const char *common_dir)
Nguyễn Thái Ngọc Duyc7b3a3d2014-11-30 15:24:36 +0700372{
373 char *base = buf->buf + git_dir_len;
Johannes Schindelin76a53d62019-10-28 12:57:18 +0000374 int has_lock_suffix = strbuf_strip_suffix(buf, LOCK_SUFFIX);
375
David Turner4e09cf22015-08-31 22:13:10 -0400376 init_common_trie();
377 if (trie_find(&common_trie, base, check_common, NULL) > 0)
Junio C Hamano1c630ba2015-10-15 15:43:31 -0700378 replace_dir(buf, git_dir_len, common_dir);
Johannes Schindelin76a53d62019-10-28 12:57:18 +0000379
380 if (has_lock_suffix)
381 strbuf_addstr(buf, LOCK_SUFFIX);
Nguyễn Thái Ngọc Duyc7b3a3d2014-11-30 15:24:36 +0700382}
383
Nguyễn Thái Ngọc Duy77a6d842014-11-30 15:24:54 +0700384void report_linked_checkout_garbage(void)
385{
386 struct strbuf sb = STRBUF_INIT;
David Turner07015302015-08-31 22:13:09 -0400387 const struct common_dir *p;
Nguyễn Thái Ngọc Duy77a6d842014-11-30 15:24:54 +0700388 int len;
389
Brandon Williamsc14c2342017-06-22 11:43:33 -0700390 if (!the_repository->different_commondir)
Nguyễn Thái Ngọc Duy77a6d842014-11-30 15:24:54 +0700391 return;
392 strbuf_addf(&sb, "%s/", get_git_dir());
393 len = sb.len;
SZEDER Gáborc72fc402019-10-21 18:00:42 +0200394 for (p = common_list; p->path; p++) {
395 const char *path = p->path;
David Turner07015302015-08-31 22:13:09 -0400396 if (p->ignore_garbage)
Nguyễn Thái Ngọc Duy77a6d842014-11-30 15:24:54 +0700397 continue;
398 strbuf_setlen(&sb, len);
399 strbuf_addstr(&sb, path);
400 if (file_exists(sb.buf))
Junio C Hamano0a489b02015-08-13 13:02:52 -0500401 report_garbage(PACKDIR_FILE_GARBAGE, sb.buf);
Nguyễn Thái Ngọc Duy77a6d842014-11-30 15:24:54 +0700402 }
403 strbuf_release(&sb);
404}
405
Brandon Williamsf9a8a472017-06-22 11:43:38 -0700406static void adjust_git_path(const struct repository *repo,
407 struct strbuf *buf, int git_dir_len)
Nguyễn Thái Ngọc Duy557bd832014-11-30 15:24:31 +0700408{
409 const char *base = buf->buf + git_dir_len;
Brandon Williamsc14c2342017-06-22 11:43:33 -0700410 if (is_dir_file(base, "info", "grafts"))
Nguyễn Thái Ngọc Duy557bd832014-11-30 15:24:31 +0700411 strbuf_splice(buf, 0, buf->len,
Brandon Williamsf9a8a472017-06-22 11:43:38 -0700412 repo->graft_file, strlen(repo->graft_file));
Brandon Williamsc14c2342017-06-22 11:43:33 -0700413 else if (!strcmp(base, "index"))
Nguyễn Thái Ngọc Duy557bd832014-11-30 15:24:31 +0700414 strbuf_splice(buf, 0, buf->len,
Brandon Williamsf9a8a472017-06-22 11:43:38 -0700415 repo->index_file, strlen(repo->index_file));
Brandon Williamsc14c2342017-06-22 11:43:33 -0700416 else if (dir_prefix(base, "objects"))
Jeff Kingf0eaf632018-11-12 09:50:39 -0500417 replace_dir(buf, git_dir_len + 7, repo->objects->odb->path);
Johannes Schindelin9445b492016-08-16 15:14:27 +0200418 else if (git_hooks_path && dir_prefix(base, "hooks"))
419 replace_dir(buf, git_dir_len + 5, git_hooks_path);
Brandon Williamsf9a8a472017-06-22 11:43:38 -0700420 else if (repo->different_commondir)
421 update_common_dir(buf, git_dir_len, repo->commondir);
Nguyễn Thái Ngọc Duy557bd832014-11-30 15:24:31 +0700422}
423
Brandon Williamsf9a8a472017-06-22 11:43:38 -0700424static void strbuf_worktree_gitdir(struct strbuf *buf,
425 const struct repository *repo,
426 const struct worktree *wt)
427{
428 if (!wt)
429 strbuf_addstr(buf, repo->gitdir);
430 else if (!wt->id)
431 strbuf_addstr(buf, repo->commondir);
432 else
433 strbuf_git_common_path(buf, repo, "worktrees/%s", wt->id);
434}
435
436static void do_git_path(const struct repository *repo,
437 const struct worktree *wt, struct strbuf *buf,
Nguyễn Thái Ngọc Duy2e641d52016-04-22 20:01:29 +0700438 const char *fmt, va_list args)
Linus Torvaldse7676d22006-09-11 12:03:15 -0700439{
Nguyễn Thái Ngọc Duy557bd832014-11-30 15:24:31 +0700440 int gitdir_len;
Brandon Williamsf9a8a472017-06-22 11:43:38 -0700441 strbuf_worktree_gitdir(buf, repo, wt);
Nguyễn Thái Ngọc Duy4ef9caf2014-11-30 15:24:26 +0700442 if (buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
443 strbuf_addch(buf, '/');
Nguyễn Thái Ngọc Duy557bd832014-11-30 15:24:31 +0700444 gitdir_len = buf->len;
Nguyễn Thái Ngọc Duy4ef9caf2014-11-30 15:24:26 +0700445 strbuf_vaddf(buf, fmt, args);
Brandon Williams54310732017-06-22 11:43:39 -0700446 if (!wt)
447 adjust_git_path(repo, buf, gitdir_len);
Nguyễn Thái Ngọc Duy4ef9caf2014-11-30 15:24:26 +0700448 strbuf_cleanup_path(buf);
Linus Torvalds26c8a532005-07-08 16:20:59 -0700449}
450
Brandon Williams3181d862017-06-22 11:43:40 -0700451char *repo_git_path(const struct repository *repo,
452 const char *fmt, ...)
453{
454 struct strbuf path = STRBUF_INIT;
455 va_list args;
456 va_start(args, fmt);
457 do_git_path(repo, NULL, &path, fmt, args);
458 va_end(args);
459 return strbuf_detach(&path, NULL);
460}
461
462void strbuf_repo_git_path(struct strbuf *sb,
463 const struct repository *repo,
464 const char *fmt, ...)
465{
466 va_list args;
467 va_start(args, fmt);
468 do_git_path(repo, NULL, sb, fmt, args);
469 va_end(args);
470}
471
Jeff Kingbb3788c2015-09-24 17:05:40 -0400472char *git_path_buf(struct strbuf *buf, const char *fmt, ...)
473{
474 va_list args;
475 strbuf_reset(buf);
476 va_start(args, fmt);
Brandon Williamsf9a8a472017-06-22 11:43:38 -0700477 do_git_path(the_repository, NULL, buf, fmt, args);
Jeff Kingbb3788c2015-09-24 17:05:40 -0400478 va_end(args);
479 return buf->buf;
480}
481
Nguyễn Thái Ngọc Duy1a83c242014-11-30 15:24:28 +0700482void strbuf_git_path(struct strbuf *sb, const char *fmt, ...)
Alex Riesenaba13e72008-10-27 11:17:51 +0100483{
484 va_list args;
485 va_start(args, fmt);
Brandon Williamsf9a8a472017-06-22 11:43:38 -0700486 do_git_path(the_repository, NULL, sb, fmt, args);
Alex Riesenaba13e72008-10-27 11:17:51 +0100487 va_end(args);
Alex Riesenaba13e72008-10-27 11:17:51 +0100488}
489
Nguyễn Thái Ngọc Duy57a23b72014-11-30 15:24:30 +0700490const char *git_path(const char *fmt, ...)
491{
492 struct strbuf *pathname = get_pathname();
493 va_list args;
494 va_start(args, fmt);
Brandon Williamsf9a8a472017-06-22 11:43:38 -0700495 do_git_path(the_repository, NULL, pathname, fmt, args);
Nguyễn Thái Ngọc Duy57a23b72014-11-30 15:24:30 +0700496 va_end(args);
497 return pathname->buf;
Alex Riesenaba13e72008-10-27 11:17:51 +0100498}
499
500char *git_pathdup(const char *fmt, ...)
501{
Nguyễn Thái Ngọc Duy4ef9caf2014-11-30 15:24:26 +0700502 struct strbuf path = STRBUF_INIT;
Alex Riesenaba13e72008-10-27 11:17:51 +0100503 va_list args;
504 va_start(args, fmt);
Brandon Williamsf9a8a472017-06-22 11:43:38 -0700505 do_git_path(the_repository, NULL, &path, fmt, args);
Alex Riesenaba13e72008-10-27 11:17:51 +0100506 va_end(args);
Nguyễn Thái Ngọc Duy4ef9caf2014-11-30 15:24:26 +0700507 return strbuf_detach(&path, NULL);
Alex Riesenaba13e72008-10-27 11:17:51 +0100508}
509
Huynh Khoi Nguyen Nguyen21cf3222012-06-22 11:03:23 +0200510char *mkpathdup(const char *fmt, ...)
511{
Huynh Khoi Nguyen Nguyen21cf3222012-06-22 11:03:23 +0200512 struct strbuf sb = STRBUF_INIT;
513 va_list args;
Huynh Khoi Nguyen Nguyen21cf3222012-06-22 11:03:23 +0200514 va_start(args, fmt);
515 strbuf_vaddf(&sb, fmt, args);
516 va_end(args);
Nguyễn Thái Ngọc Duy4ef9caf2014-11-30 15:24:26 +0700517 strbuf_cleanup_path(&sb);
518 return strbuf_detach(&sb, NULL);
Huynh Khoi Nguyen Nguyen21cf3222012-06-22 11:03:23 +0200519}
520
Nguyễn Thái Ngọc Duydcf69262014-11-30 15:24:27 +0700521const char *mkpath(const char *fmt, ...)
Linus Torvalds26c8a532005-07-08 16:20:59 -0700522{
523 va_list args;
Nguyễn Thái Ngọc Duy4ef9caf2014-11-30 15:24:26 +0700524 struct strbuf *pathname = get_pathname();
Linus Torvalds26c8a532005-07-08 16:20:59 -0700525 va_start(args, fmt);
Nguyễn Thái Ngọc Duy4ef9caf2014-11-30 15:24:26 +0700526 strbuf_vaddf(pathname, fmt, args);
Linus Torvalds26c8a532005-07-08 16:20:59 -0700527 va_end(args);
Nguyễn Thái Ngọc Duy4ef9caf2014-11-30 15:24:26 +0700528 return cleanup_path(pathname->buf);
Linus Torvalds26c8a532005-07-08 16:20:59 -0700529}
Holger Eitzenbergerf2db68e2005-08-04 22:43:03 +0200530
Nguyễn Thái Ngọc Duy2e641d52016-04-22 20:01:29 +0700531const char *worktree_git_path(const struct worktree *wt, const char *fmt, ...)
532{
533 struct strbuf *pathname = get_pathname();
534 va_list args;
535 va_start(args, fmt);
Brandon Williamsf9a8a472017-06-22 11:43:38 -0700536 do_git_path(the_repository, wt, pathname, fmt, args);
Nguyễn Thái Ngọc Duy2e641d52016-04-22 20:01:29 +0700537 va_end(args);
538 return pathname->buf;
539}
540
Brandon Williamsb42b0c02017-06-22 11:43:41 -0700541static void do_worktree_path(const struct repository *repo,
542 struct strbuf *buf,
543 const char *fmt, va_list args)
544{
545 strbuf_addstr(buf, repo->worktree);
546 if(buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
547 strbuf_addch(buf, '/');
548
549 strbuf_vaddf(buf, fmt, args);
550 strbuf_cleanup_path(buf);
551}
552
553char *repo_worktree_path(const struct repository *repo, const char *fmt, ...)
554{
555 struct strbuf path = STRBUF_INIT;
556 va_list args;
557
558 if (!repo->worktree)
559 return NULL;
560
561 va_start(args, fmt);
562 do_worktree_path(repo, &path, fmt, args);
563 va_end(args);
564
565 return strbuf_detach(&path, NULL);
566}
567
568void strbuf_repo_worktree_path(struct strbuf *sb,
569 const struct repository *repo,
570 const char *fmt, ...)
571{
572 va_list args;
573
574 if (!repo->worktree)
575 return;
576
577 va_start(args, fmt);
578 do_worktree_path(repo, sb, fmt, args);
579 va_end(args);
580}
581
Jacob Keller99b43a62016-08-31 16:27:22 -0700582/* Returns 0 on success, negative on failure. */
Jacob Keller99b43a62016-08-31 16:27:22 -0700583static int do_submodule_path(struct strbuf *buf, const char *path,
584 const char *fmt, va_list args)
Heiko Voigt0bad6112010-07-07 15:39:11 +0200585{
Max Kirillov11f9dd72015-09-14 01:17:42 +0300586 struct strbuf git_submodule_common_dir = STRBUF_INIT;
587 struct strbuf git_submodule_dir = STRBUF_INIT;
Nguyễn Thái Ngọc Duybbbb7de2017-03-26 09:42:30 +0700588 int ret;
Heiko Voigt0bad6112010-07-07 15:39:11 +0200589
Nguyễn Thái Ngọc Duybbbb7de2017-03-26 09:42:30 +0700590 ret = submodule_to_gitdir(&git_submodule_dir, path);
591 if (ret)
592 goto cleanup;
Heiko Voigt0bad6112010-07-07 15:39:11 +0200593
Nguyễn Thái Ngọc Duybbbb7de2017-03-26 09:42:30 +0700594 strbuf_complete(&git_submodule_dir, '/');
595 strbuf_addbuf(buf, &git_submodule_dir);
Nguyễn Thái Ngọc Duy4ef9caf2014-11-30 15:24:26 +0700596 strbuf_vaddf(buf, fmt, args);
Max Kirillov11f9dd72015-09-14 01:17:42 +0300597
598 if (get_common_dir_noenv(&git_submodule_common_dir, git_submodule_dir.buf))
599 update_common_dir(buf, git_submodule_dir.len, git_submodule_common_dir.buf);
600
Nguyễn Thái Ngọc Duy4ef9caf2014-11-30 15:24:26 +0700601 strbuf_cleanup_path(buf);
Max Kirillov11f9dd72015-09-14 01:17:42 +0300602
Jacob Keller99b43a62016-08-31 16:27:22 -0700603cleanup:
Max Kirillov11f9dd72015-09-14 01:17:42 +0300604 strbuf_release(&git_submodule_dir);
605 strbuf_release(&git_submodule_common_dir);
Nguyễn Thái Ngọc Duybbbb7de2017-03-26 09:42:30 +0700606 return ret;
Jeff Kingf5895fd2015-08-10 05:32:22 -0400607}
608
Jeff Kingf5895fd2015-08-10 05:32:22 -0400609char *git_pathdup_submodule(const char *path, const char *fmt, ...)
610{
Jacob Keller99b43a62016-08-31 16:27:22 -0700611 int err;
Jeff Kingf5895fd2015-08-10 05:32:22 -0400612 va_list args;
613 struct strbuf buf = STRBUF_INIT;
614 va_start(args, fmt);
Jacob Keller99b43a62016-08-31 16:27:22 -0700615 err = do_submodule_path(&buf, path, fmt, args);
Jeff Kingf5895fd2015-08-10 05:32:22 -0400616 va_end(args);
Jacob Keller99b43a62016-08-31 16:27:22 -0700617 if (err) {
618 strbuf_release(&buf);
619 return NULL;
620 }
Jeff Kingf5895fd2015-08-10 05:32:22 -0400621 return strbuf_detach(&buf, NULL);
622}
623
Jacob Keller99b43a62016-08-31 16:27:22 -0700624int strbuf_git_path_submodule(struct strbuf *buf, const char *path,
625 const char *fmt, ...)
Jeff Kingf5895fd2015-08-10 05:32:22 -0400626{
Jacob Keller99b43a62016-08-31 16:27:22 -0700627 int err;
Jeff Kingf5895fd2015-08-10 05:32:22 -0400628 va_list args;
629 va_start(args, fmt);
Jacob Keller99b43a62016-08-31 16:27:22 -0700630 err = do_submodule_path(buf, path, fmt, args);
Jeff Kingf5895fd2015-08-10 05:32:22 -0400631 va_end(args);
Jacob Keller99b43a62016-08-31 16:27:22 -0700632
633 return err;
Jeff Kingf5895fd2015-08-10 05:32:22 -0400634}
635
Brandon Williamsb3371722017-06-22 11:43:37 -0700636static void do_git_common_path(const struct repository *repo,
637 struct strbuf *buf,
Nguyễn Thái Ngọc Duy15cdfea2016-04-22 20:01:25 +0700638 const char *fmt,
639 va_list args)
640{
Brandon Williamsb3371722017-06-22 11:43:37 -0700641 strbuf_addstr(buf, repo->commondir);
Nguyễn Thái Ngọc Duy15cdfea2016-04-22 20:01:25 +0700642 if (buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
643 strbuf_addch(buf, '/');
644 strbuf_vaddf(buf, fmt, args);
645 strbuf_cleanup_path(buf);
646}
647
648const char *git_common_path(const char *fmt, ...)
649{
650 struct strbuf *pathname = get_pathname();
651 va_list args;
652 va_start(args, fmt);
Brandon Williamsb3371722017-06-22 11:43:37 -0700653 do_git_common_path(the_repository, pathname, fmt, args);
Nguyễn Thái Ngọc Duy15cdfea2016-04-22 20:01:25 +0700654 va_end(args);
655 return pathname->buf;
656}
657
Brandon Williamsb3371722017-06-22 11:43:37 -0700658void strbuf_git_common_path(struct strbuf *sb,
659 const struct repository *repo,
660 const char *fmt, ...)
Nguyễn Thái Ngọc Duy15cdfea2016-04-22 20:01:25 +0700661{
662 va_list args;
663 va_start(args, fmt);
Brandon Williamsb3371722017-06-22 11:43:37 -0700664 do_git_common_path(repo, sb, fmt, args);
Nguyễn Thái Ngọc Duy15cdfea2016-04-22 20:01:25 +0700665 va_end(args);
666}
667
Junio C Hamanoc847f532007-01-01 23:31:08 -0800668int validate_headref(const char *path)
Junio C Hamano0870ca72005-11-18 14:59:34 -0800669{
670 struct stat st;
Jeff King7eb4b9d2017-09-27 02:17:26 -0400671 char buffer[256];
672 const char *refname;
Jeff King0bca1652017-09-27 02:17:36 -0400673 struct object_id oid;
Heikki Orsila0104ca02008-04-27 21:21:58 +0300674 int fd;
675 ssize_t len;
Junio C Hamano0870ca72005-11-18 14:59:34 -0800676
677 if (lstat(path, &st) < 0)
678 return -1;
679
680 /* Make sure it is a "refs/.." symlink */
681 if (S_ISLNK(st.st_mode)) {
682 len = readlink(path, buffer, sizeof(buffer)-1);
Junio C Hamano222b1672009-02-12 13:02:09 -0800683 if (len >= 5 && !memcmp("refs/", buffer, 5))
Junio C Hamano0870ca72005-11-18 14:59:34 -0800684 return 0;
685 return -1;
686 }
687
688 /*
689 * Anything else, just open it and try to see if it is a symbolic ref.
690 */
691 fd = open(path, O_RDONLY);
692 if (fd < 0)
693 return -1;
Andy Whitcroft93d26e42007-01-08 15:58:08 +0000694 len = read_in_full(fd, buffer, sizeof(buffer)-1);
Junio C Hamano0870ca72005-11-18 14:59:34 -0800695 close(fd);
696
Jeff King6e68c912017-09-27 02:17:23 -0400697 if (len < 0)
698 return -1;
699 buffer[len] = '\0';
700
Junio C Hamano0870ca72005-11-18 14:59:34 -0800701 /*
702 * Is it a symbolic ref?
703 */
Jeff King7eb4b9d2017-09-27 02:17:26 -0400704 if (skip_prefix(buffer, "ref:", &refname)) {
705 while (isspace(*refname))
706 refname++;
707 if (starts_with(refname, "refs/"))
Junio C Hamanoc847f532007-01-01 23:31:08 -0800708 return 0;
709 }
710
711 /*
712 * Is this a detached HEAD?
713 */
Jeff King0bca1652017-09-27 02:17:36 -0400714 if (!get_oid_hex(buffer, &oid))
Junio C Hamano0870ca72005-11-18 14:59:34 -0800715 return 0;
Junio C Hamanoc847f532007-01-01 23:31:08 -0800716
Junio C Hamano0870ca72005-11-18 14:59:34 -0800717 return -1;
718}
719
Matthieu Moy395de252009-11-17 18:24:25 +0100720static struct passwd *getpw_str(const char *username, size_t len)
Andreas Ericsson54f4b872005-11-17 20:37:14 +0100721{
Junio C Hamanod79374c2005-12-03 01:45:57 -0800722 struct passwd *pw;
René Scharfe5c0b13f2014-07-19 17:35:34 +0200723 char *username_z = xmemdupz(username, len);
Matthieu Moy395de252009-11-17 18:24:25 +0100724 pw = getpwnam(username_z);
725 free(username_z);
726 return pw;
727}
Andreas Ericsson54f4b872005-11-17 20:37:14 +0100728
Matthieu Moy395de252009-11-17 18:24:25 +0100729/*
Johannes Schindelin789f6f22021-07-24 22:06:50 +0000730 * Return a string with ~ and ~user expanded via getpw*. Returns NULL on getpw
731 * failure or if path is NULL.
Nguyễn Thái Ngọc Duy4aad2f12017-04-05 17:24:38 +0700732 *
Johannes Schindelin644e6b22021-07-24 22:06:51 +0000733 * If real_home is true, strbuf_realpath($HOME) is used in the `~/` expansion.
Johannes Schindeline394a162021-07-24 22:06:53 +0000734 *
735 * If the path starts with `%(prefix)/`, the remainder is interpreted as
736 * relative to where Git is installed, and expanded to the absolute path.
Matthieu Moy395de252009-11-17 18:24:25 +0100737 */
Johannes Schindelina03b0972021-07-24 22:06:52 +0000738char *interpolate_path(const char *path, int real_home)
Matthieu Moy395de252009-11-17 18:24:25 +0100739{
740 struct strbuf user_path = STRBUF_INIT;
Matthieu Moy395de252009-11-17 18:24:25 +0100741 const char *to_copy = path;
742
Junio C Hamanoafe8a902022-05-02 09:50:37 -0700743 if (!path)
Matthieu Moy395de252009-11-17 18:24:25 +0100744 goto return_null;
Johannes Schindeline394a162021-07-24 22:06:53 +0000745
746 if (skip_prefix(path, "%(prefix)/", &path))
747 return system_path(path);
748
Matthieu Moy395de252009-11-17 18:24:25 +0100749 if (path[0] == '~') {
Jeff King53ec5512014-01-27 20:36:12 -0500750 const char *first_slash = strchrnul(path, '/');
Matthieu Moy395de252009-11-17 18:24:25 +0100751 const char *username = path + 1;
752 size_t username_len = first_slash - username;
Matthieu Moydf2a79f2009-11-19 16:21:15 +0100753 if (username_len == 0) {
754 const char *home = getenv("HOME");
Jonathan Nieder79bf1492010-07-26 10:06:51 -0500755 if (!home)
756 goto return_null;
Nguyễn Thái Ngọc Duy4aad2f12017-04-05 17:24:38 +0700757 if (real_home)
René Scharfefa2bb342017-10-01 16:44:06 +0200758 strbuf_add_real_path(&user_path, home);
Nguyễn Thái Ngọc Duy4aad2f12017-04-05 17:24:38 +0700759 else
760 strbuf_addstr(&user_path, home);
Johannes Schindelin5ca6b7b2016-03-23 11:55:00 +0100761#ifdef GIT_WINDOWS_NATIVE
762 convert_slashes(user_path.buf);
763#endif
Matthieu Moydf2a79f2009-11-19 16:21:15 +0100764 } else {
765 struct passwd *pw = getpw_str(username, username_len);
766 if (!pw)
767 goto return_null;
René Scharfecedc61a2014-07-17 01:38:18 +0200768 strbuf_addstr(&user_path, pw->pw_dir);
Junio C Hamanod79374c2005-12-03 01:45:57 -0800769 }
Matthieu Moy395de252009-11-17 18:24:25 +0100770 to_copy = first_slash;
Junio C Hamano0870ca72005-11-18 14:59:34 -0800771 }
René Scharfecedc61a2014-07-17 01:38:18 +0200772 strbuf_addstr(&user_path, to_copy);
Matthieu Moy395de252009-11-17 18:24:25 +0100773 return strbuf_detach(&user_path, NULL);
774return_null:
775 strbuf_release(&user_path);
776 return NULL;
Junio C Hamanod79374c2005-12-03 01:45:57 -0800777}
Andreas Ericsson54f4b872005-11-17 20:37:14 +0100778
Junio C Hamanod79374c2005-12-03 01:45:57 -0800779/*
780 * First, one directory to try is determined by the following algorithm.
781 *
782 * (0) If "strict" is given, the path is used as given and no DWIM is
783 * done. Otherwise:
784 * (1) "~/path" to mean path under the running user's home directory;
785 * (2) "~user/path" to mean path under named user's home directory;
786 * (3) "relative/path" to mean cwd relative directory; or
787 * (4) "/absolute/path" to mean absolute directory.
788 *
Paul Tanc8c3f1d2015-03-31 21:39:27 +0800789 * Unless "strict" is given, we check "%s/.git", "%s", "%s.git/.git", "%s.git"
790 * in this order. We select the first one that is a valid git repository, and
791 * chdir() to it. If none match, or we fail to chdir, we return NULL.
Junio C Hamanod79374c2005-12-03 01:45:57 -0800792 *
793 * If all goes well, we return the directory we used to chdir() (but
794 * before ~user is expanded), avoiding getcwd() resolving symbolic
795 * links. User relative paths are also returned as they are given,
796 * except DWIM suffixing.
797 */
Erik Faye-Lund1c64b482011-10-04 16:02:00 -0400798const char *enter_repo(const char *path, int strict)
Junio C Hamanod79374c2005-12-03 01:45:57 -0800799{
Jeff Kinge9ba6782015-09-24 17:07:45 -0400800 static struct strbuf validated_path = STRBUF_INIT;
801 static struct strbuf used_path = STRBUF_INIT;
Junio C Hamanod79374c2005-12-03 01:45:57 -0800802
803 if (!path)
804 return NULL;
805
806 if (!strict) {
807 static const char *suffix[] = {
Jeff Kingb3256eb2012-02-02 16:59:13 -0500808 "/.git", "", ".git/.git", ".git", NULL,
Junio C Hamanod79374c2005-12-03 01:45:57 -0800809 };
Phil Hord03106762011-10-04 16:05:17 -0400810 const char *gitfile;
Junio C Hamanod79374c2005-12-03 01:45:57 -0800811 int len = strlen(path);
812 int i;
Erik Faye-Lund1c64b482011-10-04 16:02:00 -0400813 while ((1 < len) && (path[len-1] == '/'))
Junio C Hamanod79374c2005-12-03 01:45:57 -0800814 len--;
Erik Faye-Lund1c64b482011-10-04 16:02:00 -0400815
Jeff Kinge9ba6782015-09-24 17:07:45 -0400816 /*
817 * We can handle arbitrary-sized buffers, but this remains as a
818 * sanity check on untrusted input.
819 */
Junio C Hamanod79374c2005-12-03 01:45:57 -0800820 if (PATH_MAX <= len)
821 return NULL;
Erik Faye-Lund1c64b482011-10-04 16:02:00 -0400822
Jeff Kinge9ba6782015-09-24 17:07:45 -0400823 strbuf_reset(&used_path);
824 strbuf_reset(&validated_path);
825 strbuf_add(&used_path, path, len);
826 strbuf_add(&validated_path, path, len);
827
828 if (used_path.buf[0] == '~') {
Johannes Schindelina03b0972021-07-24 22:06:52 +0000829 char *newpath = interpolate_path(used_path.buf, 0);
Jeff Kinge9ba6782015-09-24 17:07:45 -0400830 if (!newpath)
Junio C Hamanod79374c2005-12-03 01:45:57 -0800831 return NULL;
Jeff Kinge9ba6782015-09-24 17:07:45 -0400832 strbuf_attach(&used_path, newpath, strlen(newpath),
833 strlen(newpath));
Junio C Hamanod79374c2005-12-03 01:45:57 -0800834 }
Junio C Hamanod79374c2005-12-03 01:45:57 -0800835 for (i = 0; suffix[i]; i++) {
Jeff Kingb3256eb2012-02-02 16:59:13 -0500836 struct stat st;
Jeff Kinge9ba6782015-09-24 17:07:45 -0400837 size_t baselen = used_path.len;
838 strbuf_addstr(&used_path, suffix[i]);
839 if (!stat(used_path.buf, &st) &&
Jeff Kingb3256eb2012-02-02 16:59:13 -0500840 (S_ISREG(st.st_mode) ||
Jeff Kinge9ba6782015-09-24 17:07:45 -0400841 (S_ISDIR(st.st_mode) && is_git_directory(used_path.buf)))) {
842 strbuf_addstr(&validated_path, suffix[i]);
Junio C Hamanod79374c2005-12-03 01:45:57 -0800843 break;
844 }
Jeff Kinge9ba6782015-09-24 17:07:45 -0400845 strbuf_setlen(&used_path, baselen);
Junio C Hamanod79374c2005-12-03 01:45:57 -0800846 }
Phil Hord03106762011-10-04 16:05:17 -0400847 if (!suffix[i])
848 return NULL;
Junio C Hamano78891792015-10-20 15:24:00 -0700849 gitfile = read_gitfile(used_path.buf);
Jeff Kinge9ba6782015-09-24 17:07:45 -0400850 if (gitfile) {
851 strbuf_reset(&used_path);
852 strbuf_addstr(&used_path, gitfile);
853 }
854 if (chdir(used_path.buf))
Junio C Hamanod79374c2005-12-03 01:45:57 -0800855 return NULL;
Jeff Kinge9ba6782015-09-24 17:07:45 -0400856 path = validated_path.buf;
Junio C Hamanod79374c2005-12-03 01:45:57 -0800857 }
Nguyễn Thái Ngọc Duy1f5fbe12015-09-28 20:06:14 +0700858 else {
859 const char *gitfile = read_gitfile(path);
860 if (gitfile)
861 path = gitfile;
862 if (chdir(path))
863 return NULL;
864 }
Junio C Hamanod79374c2005-12-03 01:45:57 -0800865
Nguyễn Thái Ngọc Duy0f64cc42015-09-28 20:06:13 +0700866 if (is_git_directory(".")) {
Alexandr Miloslavskiy0915a5b2020-03-06 19:03:13 +0000867 set_git_dir(".", 0);
brian m. carlsoncfe39172020-02-22 20:17:37 +0000868 check_repository_format(NULL);
Junio C Hamanod79374c2005-12-03 01:45:57 -0800869 return path;
Andreas Ericsson54f4b872005-11-17 20:37:14 +0100870 }
871
872 return NULL;
873}
Junio C Hamano138086a2006-06-09 22:07:23 -0700874
Torsten Bögershausencbe43b82013-03-30 10:53:47 +0100875static int calc_shared_perm(int mode)
Junio C Hamano138086a2006-06-09 22:07:23 -0700876{
Torsten Bögershausencbe43b82013-03-30 10:53:47 +0100877 int tweak;
Junio C Hamano138086a2006-06-09 22:07:23 -0700878
Jeff King7875acb2016-03-11 17:36:49 -0500879 if (get_shared_repository() < 0)
880 tweak = -get_shared_repository();
Junio C Hamano5a688fe2009-03-25 16:19:36 -0700881 else
Jeff King7875acb2016-03-11 17:36:49 -0500882 tweak = get_shared_repository();
Junio C Hamano94df2502006-06-09 23:09:49 -0700883
Junio C Hamano5a688fe2009-03-25 16:19:36 -0700884 if (!(mode & S_IWUSR))
885 tweak &= ~0222;
886 if (mode & S_IXUSR)
887 /* Copy read bits to execute bits */
888 tweak |= (tweak & 0444) >> 2;
Jeff King7875acb2016-03-11 17:36:49 -0500889 if (get_shared_repository() < 0)
Junio C Hamano5a688fe2009-03-25 16:19:36 -0700890 mode = (mode & ~0777) | tweak;
891 else
Petr Baudis8c6202d2008-07-12 03:15:03 +0200892 mode |= tweak;
Junio C Hamano94df2502006-06-09 23:09:49 -0700893
Torsten Bögershausencbe43b82013-03-30 10:53:47 +0100894 return mode;
895}
896
897
898int adjust_shared_perm(const char *path)
899{
900 int old_mode, new_mode;
901
Jeff King7875acb2016-03-11 17:36:49 -0500902 if (!get_shared_repository())
Torsten Bögershausencbe43b82013-03-30 10:53:47 +0100903 return 0;
904 if (get_st_mode_bits(path, &old_mode) < 0)
905 return -1;
906
907 new_mode = calc_shared_perm(old_mode);
908 if (S_ISDIR(old_mode)) {
Heikki Orsila06cbe852008-04-16 11:34:24 +0300909 /* Copy read bits to execute bits */
Torsten Bögershausencbe43b82013-03-30 10:53:47 +0100910 new_mode |= (new_mode & 0444) >> 2;
Junio C Hamano671bbf72022-10-28 14:16:09 -0700911
912 /*
913 * g+s matters only if any extra access is granted
914 * based on group membership.
915 */
916 if (FORCE_DIR_SET_GID && (new_mode & 060))
917 new_mode |= FORCE_DIR_SET_GID;
Heikki Orsila06cbe852008-04-16 11:34:24 +0300918 }
919
Torsten Bögershausencbe43b82013-03-30 10:53:47 +0100920 if (((old_mode ^ new_mode) & ~S_IFMT) &&
921 chmod(path, (new_mode & ~S_IFMT)) < 0)
Junio C Hamano138086a2006-06-09 22:07:23 -0700922 return -2;
923 return 0;
924}
Johannes Schindeline5392c52007-08-01 01:28:59 +0100925
David Turnereb338762015-11-10 12:42:38 +0100926void safe_create_dir(const char *dir, int share)
927{
928 if (mkdir(dir, 0777) < 0) {
929 if (errno != EEXIST) {
930 perror(dir);
931 exit(1);
932 }
933 }
934 else if (share && adjust_shared_perm(dir))
935 die(_("Could not make %s writable by group"), dir);
936}
937
Jiang Xin7fbd4222013-10-14 10:29:39 +0800938static int have_same_root(const char *path1, const char *path2)
939{
940 int is_abs1, is_abs2;
941
942 is_abs1 = is_absolute_path(path1);
943 is_abs2 = is_absolute_path(path2);
944 return (is_abs1 && is_abs2 && tolower(path1[0]) == tolower(path2[0])) ||
945 (!is_abs1 && !is_abs2);
946}
947
Jiang Xine02ca722013-06-25 23:53:43 +0800948/*
949 * Give path as relative to prefix.
950 *
951 * The strbuf may or may not be used, so do not assume it contains the
952 * returned path.
953 */
954const char *relative_path(const char *in, const char *prefix,
955 struct strbuf *sb)
Linus Torvalds044bbbc2008-06-19 12:34:06 -0700956{
Jiang Xine02ca722013-06-25 23:53:43 +0800957 int in_len = in ? strlen(in) : 0;
958 int prefix_len = prefix ? strlen(prefix) : 0;
959 int in_off = 0;
960 int prefix_off = 0;
Junio C Hamano288123f2010-01-21 19:05:19 -0800961 int i = 0, j = 0;
962
Jiang Xine02ca722013-06-25 23:53:43 +0800963 if (!in_len)
964 return "./";
965 else if (!prefix_len)
966 return in;
967
Johannes Schindelin2f36eed2016-01-12 08:57:22 +0100968 if (have_same_root(in, prefix))
Jiang Xin7fbd4222013-10-14 10:29:39 +0800969 /* bypass dos_drive, for "c:" is identical to "C:" */
Johannes Schindelin2f36eed2016-01-12 08:57:22 +0100970 i = j = has_dos_drive_prefix(in);
971 else {
Jiang Xin7fbd4222013-10-14 10:29:39 +0800972 return in;
973 }
974
Jiang Xine02ca722013-06-25 23:53:43 +0800975 while (i < prefix_len && j < in_len && prefix[i] == in[j]) {
976 if (is_dir_sep(prefix[i])) {
977 while (is_dir_sep(prefix[i]))
Junio C Hamano288123f2010-01-21 19:05:19 -0800978 i++;
Jiang Xine02ca722013-06-25 23:53:43 +0800979 while (is_dir_sep(in[j]))
Junio C Hamano288123f2010-01-21 19:05:19 -0800980 j++;
Jiang Xine02ca722013-06-25 23:53:43 +0800981 prefix_off = i;
982 in_off = j;
983 } else {
984 i++;
985 j++;
986 }
987 }
988
989 if (
990 /* "prefix" seems like prefix of "in" */
991 i >= prefix_len &&
992 /*
993 * but "/foo" is not a prefix of "/foobar"
994 * (i.e. prefix not end with '/')
995 */
996 prefix_off < prefix_len) {
997 if (j >= in_len) {
998 /* in="/a/b", prefix="/a/b" */
999 in_off = in_len;
1000 } else if (is_dir_sep(in[j])) {
1001 /* in="/a/b/c", prefix="/a/b" */
1002 while (is_dir_sep(in[j]))
1003 j++;
1004 in_off = j;
1005 } else {
1006 /* in="/a/bbb/c", prefix="/a/b" */
1007 i = prefix_off;
1008 }
1009 } else if (
1010 /* "in" is short than "prefix" */
1011 j >= in_len &&
1012 /* "in" not end with '/' */
1013 in_off < in_len) {
1014 if (is_dir_sep(prefix[i])) {
1015 /* in="/a/b", prefix="/a/b/c/" */
1016 while (is_dir_sep(prefix[i]))
1017 i++;
1018 in_off = in_len;
1019 }
1020 }
1021 in += in_off;
1022 in_len -= in_off;
1023
1024 if (i >= prefix_len) {
1025 if (!in_len)
1026 return "./";
1027 else
1028 return in;
1029 }
1030
1031 strbuf_reset(sb);
1032 strbuf_grow(sb, in_len);
1033
1034 while (i < prefix_len) {
1035 if (is_dir_sep(prefix[i])) {
1036 strbuf_addstr(sb, "../");
1037 while (is_dir_sep(prefix[i]))
1038 i++;
Junio C Hamano288123f2010-01-21 19:05:19 -08001039 continue;
Junio C Hamano288123f2010-01-21 19:05:19 -08001040 }
1041 i++;
Junio C Hamano288123f2010-01-21 19:05:19 -08001042 }
Jiang Xine02ca722013-06-25 23:53:43 +08001043 if (!is_dir_sep(prefix[prefix_len - 1]))
1044 strbuf_addstr(sb, "../");
1045
1046 strbuf_addstr(sb, in);
1047
1048 return sb->buf;
Linus Torvalds044bbbc2008-06-19 12:34:06 -07001049}
David Reissae299be2008-05-19 23:48:54 -07001050
1051/*
Jiang Xin41894ae2013-10-14 10:29:40 +08001052 * A simpler implementation of relative_path
1053 *
1054 * Get relative path by removing "prefix" from "in". This function
1055 * first appears in v1.5.6-1-g044bbbc, and makes git_dir shorter
1056 * to increase performance when traversing the path to work_tree.
1057 */
1058const char *remove_leading_path(const char *in, const char *prefix)
1059{
Jeff King46357682015-09-24 17:07:47 -04001060 static struct strbuf buf = STRBUF_INIT;
Jiang Xin41894ae2013-10-14 10:29:40 +08001061 int i = 0, j = 0;
1062
1063 if (!prefix || !prefix[0])
1064 return in;
1065 while (prefix[i]) {
1066 if (is_dir_sep(prefix[i])) {
1067 if (!is_dir_sep(in[j]))
1068 return in;
1069 while (is_dir_sep(prefix[i]))
1070 i++;
1071 while (is_dir_sep(in[j]))
1072 j++;
1073 continue;
1074 } else if (in[j] != prefix[i]) {
1075 return in;
1076 }
1077 i++;
1078 j++;
1079 }
1080 if (
1081 /* "/foo" is a prefix of "/foo" */
1082 in[j] &&
1083 /* "/foo" is not a prefix of "/foobar" */
1084 !is_dir_sep(prefix[i-1]) && !is_dir_sep(in[j])
1085 )
1086 return in;
1087 while (is_dir_sep(in[j]))
1088 j++;
Jeff King46357682015-09-24 17:07:47 -04001089
1090 strbuf_reset(&buf);
Jiang Xin41894ae2013-10-14 10:29:40 +08001091 if (!in[j])
Jeff King46357682015-09-24 17:07:47 -04001092 strbuf_addstr(&buf, ".");
Jiang Xin41894ae2013-10-14 10:29:40 +08001093 else
Jeff King46357682015-09-24 17:07:47 -04001094 strbuf_addstr(&buf, in + j);
1095 return buf.buf;
Jiang Xin41894ae2013-10-14 10:29:40 +08001096}
1097
1098/*
Johannes Sixtf2a782b2009-02-07 16:08:31 +01001099 * It is okay if dst == src, but they should not overlap otherwise.
Jeff King9734b742020-01-30 04:52:19 -05001100 * The "dst" buffer must be at least as long as "src"; normalizing may shrink
1101 * the size of the path, but will never grow it.
David Reissae299be2008-05-19 23:48:54 -07001102 *
Johannes Sixtf2a782b2009-02-07 16:08:31 +01001103 * Performs the following normalizations on src, storing the result in dst:
1104 * - Ensures that components are separated by '/' (Windows only)
Johannes Sixt7814fbe2016-12-14 20:37:38 +01001105 * - Squashes sequences of '/' except "//server/share" on Windows
David Reissae299be2008-05-19 23:48:54 -07001106 * - Removes "." components.
1107 * - Removes ".." components, and the components the precede them.
Johannes Sixtf2a782b2009-02-07 16:08:31 +01001108 * Returns failure (non-zero) if a ".." component appears as first path
1109 * component anytime during the normalization. Otherwise, returns success (0).
David Reissae299be2008-05-19 23:48:54 -07001110 *
1111 * Note that this function is purely textual. It does not follow symlinks,
1112 * verify the existence of the path, or make any system calls.
Nguyễn Thái Ngọc Duy645a29c2013-07-14 15:36:03 +07001113 *
1114 * prefix_len != NULL is for a specific case of prefix_pathspec():
1115 * assume that src == dst and src[0..prefix_len-1] is already
1116 * normalized, any time "../" eats up to the prefix_len part,
1117 * prefix_len is reduced. In the end prefix_len is the remaining
1118 * prefix that has not been overridden by user pathspec.
Ray Donnellyb2a71232015-10-01 20:04:17 +01001119 *
1120 * NEEDSWORK: This function doesn't perform normalization w.r.t. trailing '/'.
1121 * For everything but the root folder itself, the normalized path should not
1122 * end with a '/', then the callers need to be fixed up accordingly.
1123 *
David Reissae299be2008-05-19 23:48:54 -07001124 */
Nguyễn Thái Ngọc Duy645a29c2013-07-14 15:36:03 +07001125int normalize_path_copy_len(char *dst, const char *src, int *prefix_len)
David Reissae299be2008-05-19 23:48:54 -07001126{
Johannes Sixtf3cad0a2009-02-07 16:08:28 +01001127 char *dst0;
Johannes Sixt7814fbe2016-12-14 20:37:38 +01001128 const char *end;
David Reissae299be2008-05-19 23:48:54 -07001129
Johannes Sixt7814fbe2016-12-14 20:37:38 +01001130 /*
1131 * Copy initial part of absolute path: "/", "C:/", "//server/share/".
1132 */
1133 end = src + offset_1st_component(src);
1134 while (src < end) {
1135 char c = *src++;
1136 if (is_dir_sep(c))
1137 c = '/';
1138 *dst++ = c;
1139 }
Johannes Sixtf3cad0a2009-02-07 16:08:28 +01001140 dst0 = dst;
David Reissae299be2008-05-19 23:48:54 -07001141
Johannes Sixt7814fbe2016-12-14 20:37:38 +01001142 while (is_dir_sep(*src))
1143 src++;
David Reissae299be2008-05-19 23:48:54 -07001144
Johannes Sixtf3cad0a2009-02-07 16:08:28 +01001145 for (;;) {
1146 char c = *src;
David Reissae299be2008-05-19 23:48:54 -07001147
Johannes Sixtf3cad0a2009-02-07 16:08:28 +01001148 /*
1149 * A path component that begins with . could be
1150 * special:
1151 * (1) "." and ends -- ignore and terminate.
1152 * (2) "./" -- ignore them, eat slash and continue.
1153 * (3) ".." and ends -- strip one and terminate.
1154 * (4) "../" -- strip one, eat slash and continue.
1155 */
1156 if (c == '.') {
1157 if (!src[1]) {
1158 /* (1) */
1159 src++;
1160 } else if (is_dir_sep(src[1])) {
1161 /* (2) */
1162 src += 2;
1163 while (is_dir_sep(*src))
1164 src++;
1165 continue;
1166 } else if (src[1] == '.') {
1167 if (!src[2]) {
1168 /* (3) */
1169 src += 2;
1170 goto up_one;
1171 } else if (is_dir_sep(src[2])) {
1172 /* (4) */
1173 src += 3;
1174 while (is_dir_sep(*src))
1175 src++;
1176 goto up_one;
1177 }
1178 }
1179 }
1180
1181 /* copy up to the next '/', and eat all '/' */
1182 while ((c = *src++) != '\0' && !is_dir_sep(c))
1183 *dst++ = c;
1184 if (is_dir_sep(c)) {
1185 *dst++ = '/';
1186 while (is_dir_sep(c))
1187 c = *src++;
1188 src--;
1189 } else if (!c)
1190 break;
1191 continue;
1192
1193 up_one:
1194 /*
1195 * dst0..dst is prefix portion, and dst[-1] is '/';
1196 * go up one level.
1197 */
Johannes Sixtf42302b2009-02-07 16:08:30 +01001198 dst--; /* go to trailing '/' */
1199 if (dst <= dst0)
Johannes Sixtf3cad0a2009-02-07 16:08:28 +01001200 return -1;
Johannes Sixtf42302b2009-02-07 16:08:30 +01001201 /* Windows: dst[-1] cannot be backslash anymore */
1202 while (dst0 < dst && dst[-1] != '/')
1203 dst--;
Nguyễn Thái Ngọc Duy645a29c2013-07-14 15:36:03 +07001204 if (prefix_len && *prefix_len > dst - dst0)
1205 *prefix_len = dst - dst0;
Johannes Sixtf3cad0a2009-02-07 16:08:28 +01001206 }
David Reissae299be2008-05-19 23:48:54 -07001207 *dst = '\0';
Johannes Sixtf3cad0a2009-02-07 16:08:28 +01001208 return 0;
David Reissae299be2008-05-19 23:48:54 -07001209}
David Reiss0454dd92008-05-19 23:49:26 -07001210
Nguyễn Thái Ngọc Duy645a29c2013-07-14 15:36:03 +07001211int normalize_path_copy(char *dst, const char *src)
1212{
1213 return normalize_path_copy_len(dst, src, NULL);
1214}
1215
David Reiss0454dd92008-05-19 23:49:26 -07001216/*
1217 * path = Canonical absolute path
Michael Haggerty9e2326c2012-10-28 17:16:25 +01001218 * prefixes = string_list containing normalized, absolute paths without
1219 * trailing slashes (except for the root directory, which is denoted by "/").
David Reiss0454dd92008-05-19 23:49:26 -07001220 *
Michael Haggerty9e2326c2012-10-28 17:16:25 +01001221 * Determines, for each path in prefixes, whether the "prefix"
David Reiss0454dd92008-05-19 23:49:26 -07001222 * is an ancestor directory of path. Returns the length of the longest
1223 * ancestor directory, excluding any trailing slashes, or -1 if no prefix
Michael Haggerty31171d92012-10-28 17:16:24 +01001224 * is an ancestor. (Note that this means 0 is returned if prefixes is
1225 * ["/"].) "/foo" is not considered an ancestor of "/foobar". Directories
David Reiss0454dd92008-05-19 23:49:26 -07001226 * are not considered to be their own ancestors. path must be in a
1227 * canonical form: empty components, or "." or ".." components are not
Michael Haggerty9e2326c2012-10-28 17:16:25 +01001228 * allowed.
David Reiss0454dd92008-05-19 23:49:26 -07001229 */
Michael Haggerty31171d92012-10-28 17:16:24 +01001230int longest_ancestor_length(const char *path, struct string_list *prefixes)
David Reiss0454dd92008-05-19 23:49:26 -07001231{
Michael Haggertya5ccdbe2012-10-28 17:16:23 +01001232 int i, max_len = -1;
David Reiss0454dd92008-05-19 23:49:26 -07001233
Michael Haggerty31171d92012-10-28 17:16:24 +01001234 if (!strcmp(path, "/"))
David Reiss0454dd92008-05-19 23:49:26 -07001235 return -1;
1236
Michael Haggerty31171d92012-10-28 17:16:24 +01001237 for (i = 0; i < prefixes->nr; i++) {
1238 const char *ceil = prefixes->items[i].string;
Michael Haggertya5ccdbe2012-10-28 17:16:23 +01001239 int len = strlen(ceil);
1240
Johannes Schindelinfdcad5a2022-03-23 23:00:41 +01001241 /*
1242 * For root directories (`/`, `C:/`, `//server/share/`)
1243 * adjust the length to exclude the trailing slash.
1244 */
1245 if (len > 0 && ceil[len - 1] == '/')
1246 len--;
1247
1248 if (strncmp(path, ceil, len) ||
1249 path[len] != '/' || !path[len + 1])
Michael Haggerty9e2326c2012-10-28 17:16:25 +01001250 continue; /* no match */
David Reiss0454dd92008-05-19 23:49:26 -07001251
Michael Haggerty9e2326c2012-10-28 17:16:25 +01001252 if (len > max_len)
David Reiss0454dd92008-05-19 23:49:26 -07001253 max_len = len;
David Reiss0454dd92008-05-19 23:49:26 -07001254 }
1255
1256 return max_len;
1257}
Johannes Schindelin4fcc86b2009-02-19 20:10:49 +01001258
1259/* strip arbitrary amount of directory separators at end of path */
1260static inline int chomp_trailing_dir_sep(const char *path, int len)
1261{
1262 while (len && is_dir_sep(path[len - 1]))
1263 len--;
1264 return len;
1265}
1266
1267/*
brian m. carlsonce17feb2019-08-25 23:33:39 +00001268 * If path ends with suffix (complete path components), returns the offset of
1269 * the last character in the path before the suffix (sans trailing directory
1270 * separators), and -1 otherwise.
1271 */
1272static ssize_t stripped_path_suffix_offset(const char *path, const char *suffix)
1273{
1274 int path_len = strlen(path), suffix_len = strlen(suffix);
1275
1276 while (suffix_len) {
1277 if (!path_len)
1278 return -1;
1279
1280 if (is_dir_sep(path[path_len - 1])) {
1281 if (!is_dir_sep(suffix[suffix_len - 1]))
1282 return -1;
1283 path_len = chomp_trailing_dir_sep(path, path_len);
1284 suffix_len = chomp_trailing_dir_sep(suffix, suffix_len);
1285 }
1286 else if (path[--path_len] != suffix[--suffix_len])
1287 return -1;
1288 }
1289
1290 if (path_len && !is_dir_sep(path[path_len - 1]))
1291 return -1;
1292 return chomp_trailing_dir_sep(path, path_len);
1293}
1294
1295/*
1296 * Returns true if the path ends with components, considering only complete path
1297 * components, and false otherwise.
1298 */
1299int ends_with_path_components(const char *path, const char *components)
1300{
1301 return stripped_path_suffix_offset(path, components) != -1;
1302}
1303
1304/*
Johannes Schindelin4fcc86b2009-02-19 20:10:49 +01001305 * If path ends with suffix (complete path components), returns the
1306 * part before suffix (sans trailing directory separators).
1307 * Otherwise returns NULL.
1308 */
1309char *strip_path_suffix(const char *path, const char *suffix)
1310{
brian m. carlsonce17feb2019-08-25 23:33:39 +00001311 ssize_t offset = stripped_path_suffix_offset(path, suffix);
Johannes Schindelin4fcc86b2009-02-19 20:10:49 +01001312
brian m. carlsonce17feb2019-08-25 23:33:39 +00001313 return offset == -1 ? NULL : xstrndup(path, offset);
Johannes Schindelin4fcc86b2009-02-19 20:10:49 +01001314}
Shawn O. Pearce34b6cb82009-11-09 11:26:43 -08001315
1316int daemon_avoid_alias(const char *p)
1317{
1318 int sl, ndot;
1319
1320 /*
1321 * This resurrects the belts and suspenders paranoia check by HPA
1322 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
Junio C Hamano9517e6b2010-02-03 21:23:18 -08001323 * does not do getcwd() based path canonicalization.
Shawn O. Pearce34b6cb82009-11-09 11:26:43 -08001324 *
1325 * sl becomes true immediately after seeing '/' and continues to
1326 * be true as long as dots continue after that without intervening
1327 * non-dot character.
1328 */
1329 if (!p || (*p != '/' && *p != '~'))
1330 return -1;
1331 sl = 1; ndot = 0;
1332 p++;
1333
1334 while (1) {
1335 char ch = *p++;
1336 if (sl) {
1337 if (ch == '.')
1338 ndot++;
1339 else if (ch == '/') {
1340 if (ndot < 3)
1341 /* reject //, /./ and /../ */
1342 return -1;
1343 ndot = 0;
1344 }
1345 else if (ch == 0) {
1346 if (0 < ndot && ndot < 3)
1347 /* reject /.$ and /..$ */
1348 return -1;
1349 return 0;
1350 }
1351 else
1352 sl = ndot = 0;
1353 }
1354 else if (ch == 0)
1355 return 0;
1356 else if (ch == '/') {
1357 sl = 1;
1358 ndot = 0;
1359 }
1360 }
1361}
Nguyễn Thái Ngọc Duy4bb43de2010-02-16 12:22:08 +07001362
Johannes Schindelin525e7fb2019-09-16 20:44:31 +02001363/*
1364 * On NTFS, we need to be careful to disallow certain synonyms of the `.git/`
1365 * directory:
1366 *
1367 * - For historical reasons, file names that end in spaces or periods are
1368 * automatically trimmed. Therefore, `.git . . ./` is a valid way to refer
1369 * to `.git/`.
1370 *
1371 * - For other historical reasons, file names that do not conform to the 8.3
1372 * format (up to eight characters for the basename, three for the file
1373 * extension, certain characters not allowed such as `+`, etc) are associated
1374 * with a so-called "short name", at least on the `C:` drive by default.
1375 * Which means that `git~1/` is a valid way to refer to `.git/`.
1376 *
1377 * Note: Technically, `.git/` could receive the short name `git~2` if the
1378 * short name `git~1` were already used. In Git, however, we guarantee that
1379 * `.git` is the first item in a directory, therefore it will be associated
1380 * with the short name `git~1` (unless short names are disabled).
1381 *
Johannes Schindelin7c3745f2019-08-28 12:22:17 +02001382 * - For yet other historical reasons, NTFS supports so-called "Alternate Data
1383 * Streams", i.e. metadata associated with a given file, referred to via
1384 * `<filename>:<stream-name>:<stream-type>`. There exists a default stream
1385 * type for directories, allowing `.git/` to be accessed via
1386 * `.git::$INDEX_ALLOCATION/`.
1387 *
Johannes Schindelin525e7fb2019-09-16 20:44:31 +02001388 * When this function returns 1, it indicates that the specified file/directory
1389 * name refers to a `.git` file or directory, or to any of these synonyms, and
1390 * Git should therefore not track it.
1391 *
Johannes Schindelin7c3745f2019-08-28 12:22:17 +02001392 * For performance reasons, _all_ Alternate Data Streams of `.git/` are
1393 * forbidden, not just `::$INDEX_ALLOCATION`.
1394 *
Johannes Schindelin525e7fb2019-09-16 20:44:31 +02001395 * This function is intended to be used by `git fsck` even on platforms where
1396 * the backslash is a regular filename character, therefore it needs to handle
1397 * backlash characters in the provided `name` specially: they are interpreted
1398 * as directory separators.
1399 */
Johannes Schindelin1d1d69b2014-12-16 23:31:03 +01001400int is_ntfs_dotgit(const char *name)
1401{
Johannes Schindelin3a85dc72019-09-06 21:09:35 +02001402 char c;
Johannes Schindelin1d1d69b2014-12-16 23:31:03 +01001403
Johannes Schindelin3a85dc72019-09-06 21:09:35 +02001404 /*
1405 * Note that when we don't find `.git` or `git~1` we end up with `name`
1406 * advanced partway through the string. That's okay, though, as we
1407 * return immediately in those cases, without looking at `name` any
1408 * further.
1409 */
1410 c = *(name++);
1411 if (c == '.') {
1412 /* .git */
1413 if (((c = *(name++)) != 'g' && c != 'G') ||
1414 ((c = *(name++)) != 'i' && c != 'I') ||
1415 ((c = *(name++)) != 't' && c != 'T'))
Johannes Schindelin288a74b2019-09-23 08:58:11 +02001416 return 0;
Johannes Schindelin3a85dc72019-09-06 21:09:35 +02001417 } else if (c == 'g' || c == 'G') {
1418 /* git ~1 */
1419 if (((c = *(name++)) != 'i' && c != 'I') ||
1420 ((c = *(name++)) != 't' && c != 'T') ||
1421 *(name++) != '~' ||
1422 *(name++) != '1')
1423 return 0;
1424 } else
1425 return 0;
1426
1427 for (;;) {
1428 c = *(name++);
Ævar Arnfjörð Bjarmason9fd512c2022-05-16 20:10:59 +00001429 if (!c || is_xplatform_dir_sep(c) || c == ':')
Johannes Schindelin3a85dc72019-09-06 21:09:35 +02001430 return 1;
1431 if (c != '.' && c != ' ')
1432 return 0;
1433 }
Johannes Schindelin1d1d69b2014-12-16 23:31:03 +01001434}
Paul Tanea192892015-04-21 12:06:27 +08001435
Johannes Schindeline7cb0b42018-05-11 16:03:54 +02001436static int is_ntfs_dot_generic(const char *name,
1437 const char *dotgit_name,
1438 size_t len,
1439 const char *dotgit_ntfs_shortname_prefix)
1440{
1441 int saw_tilde;
1442 size_t i;
1443
1444 if ((name[0] == '.' && !strncasecmp(name + 1, dotgit_name, len))) {
1445 i = len + 1;
1446only_spaces_and_periods:
1447 for (;;) {
1448 char c = name[i++];
Johannes Schindelin91bd4652019-08-28 12:22:17 +02001449 if (!c || c == ':')
Johannes Schindeline7cb0b42018-05-11 16:03:54 +02001450 return 1;
1451 if (c != ' ' && c != '.')
1452 return 0;
1453 }
1454 }
1455
1456 /*
1457 * Is it a regular NTFS short name, i.e. shortened to 6 characters,
1458 * followed by ~1, ... ~4?
1459 */
1460 if (!strncasecmp(name, dotgit_name, 6) && name[6] == '~' &&
1461 name[7] >= '1' && name[7] <= '4') {
1462 i = 8;
1463 goto only_spaces_and_periods;
1464 }
1465
1466 /*
1467 * Is it a fall-back NTFS short name (for details, see
1468 * https://en.wikipedia.org/wiki/8.3_filename?
1469 */
1470 for (i = 0, saw_tilde = 0; i < 8; i++)
1471 if (name[i] == '\0')
1472 return 0;
1473 else if (saw_tilde) {
1474 if (name[i] < '0' || name[i] > '9')
1475 return 0;
1476 } else if (name[i] == '~') {
1477 if (name[++i] < '1' || name[i] > '9')
1478 return 0;
1479 saw_tilde = 1;
1480 } else if (i >= 6)
1481 return 0;
Torsten Bögershausen30634772018-10-25 18:13:08 +02001482 else if (name[i] & 0x80) {
Johannes Schindeline7cb0b42018-05-11 16:03:54 +02001483 /*
1484 * We know our needles contain only ASCII, so we clamp
1485 * here to make the results of tolower() sane.
1486 */
1487 return 0;
1488 } else if (tolower(name[i]) != dotgit_ntfs_shortname_prefix[i])
1489 return 0;
1490
1491 goto only_spaces_and_periods;
1492}
1493
1494/*
1495 * Inline helper to make sure compiler resolves strlen() on literals at
1496 * compile time.
1497 */
1498static inline int is_ntfs_dot_str(const char *name, const char *dotgit_name,
1499 const char *dotgit_ntfs_shortname_prefix)
1500{
1501 return is_ntfs_dot_generic(name, dotgit_name, strlen(dotgit_name),
1502 dotgit_ntfs_shortname_prefix);
1503}
1504
1505int is_ntfs_dotgitmodules(const char *name)
1506{
1507 return is_ntfs_dot_str(name, "gitmodules", "gi7eba");
1508}
1509
1510int is_ntfs_dotgitignore(const char *name)
1511{
1512 return is_ntfs_dot_str(name, "gitignore", "gi250a");
1513}
1514
1515int is_ntfs_dotgitattributes(const char *name)
1516{
1517 return is_ntfs_dot_str(name, "gitattributes", "gi7d29");
1518}
1519
Jeff King801ed012021-05-03 16:43:22 -04001520int is_ntfs_dotmailmap(const char *name)
1521{
1522 return is_ntfs_dot_str(name, "mailmap", "maba30");
1523}
1524
Jeff King2491f772017-07-28 15:25:45 -04001525int looks_like_command_line_option(const char *str)
1526{
1527 return str && str[0] == '-';
1528}
1529
Lénaïc Huardcb7db5b2021-09-04 22:54:58 +02001530char *xdg_config_home_for(const char *subdir, const char *filename)
Paul Tanea192892015-04-21 12:06:27 +08001531{
1532 const char *home, *config_home;
1533
Lénaïc Huardcb7db5b2021-09-04 22:54:58 +02001534 assert(subdir);
Paul Tanea192892015-04-21 12:06:27 +08001535 assert(filename);
1536 config_home = getenv("XDG_CONFIG_HOME");
1537 if (config_home && *config_home)
Lénaïc Huardcb7db5b2021-09-04 22:54:58 +02001538 return mkpathdup("%s/%s/%s", config_home, subdir, filename);
Paul Tanea192892015-04-21 12:06:27 +08001539
1540 home = getenv("HOME");
1541 if (home)
Lénaïc Huardcb7db5b2021-09-04 22:54:58 +02001542 return mkpathdup("%s/.config/%s/%s", home, subdir, filename);
1543
Paul Tanea192892015-04-21 12:06:27 +08001544 return NULL;
1545}
Jeff Kingf9327292015-08-10 05:38:57 -04001546
Lénaïc Huardcb7db5b2021-09-04 22:54:58 +02001547char *xdg_config_home(const char *filename)
1548{
1549 return xdg_config_home_for("git", filename);
1550}
1551
Devin Lehmachere7f136b2017-03-13 16:43:54 -04001552char *xdg_cache_home(const char *filename)
1553{
1554 const char *home, *cache_home;
1555
1556 assert(filename);
1557 cache_home = getenv("XDG_CACHE_HOME");
1558 if (cache_home && *cache_home)
1559 return mkpathdup("%s/git/%s", cache_home, filename);
1560
1561 home = getenv("HOME");
1562 if (home)
1563 return mkpathdup("%s/.cache/git/%s", home, filename);
1564 return NULL;
1565}
1566
Stefan Beller102de882018-05-17 15:51:51 -07001567REPO_GIT_PATH_FUNC(squash_msg, "SQUASH_MSG")
1568REPO_GIT_PATH_FUNC(merge_msg, "MERGE_MSG")
1569REPO_GIT_PATH_FUNC(merge_rr, "MERGE_RR")
1570REPO_GIT_PATH_FUNC(merge_mode, "MERGE_MODE")
1571REPO_GIT_PATH_FUNC(merge_head, "MERGE_HEAD")
Denton Liua03b5552020-04-07 10:28:07 -04001572REPO_GIT_PATH_FUNC(merge_autostash, "MERGE_AUTOSTASH")
Elijah Newren52918282021-03-20 00:03:52 +00001573REPO_GIT_PATH_FUNC(auto_merge, "AUTO_MERGE")
Stefan Beller102de882018-05-17 15:51:51 -07001574REPO_GIT_PATH_FUNC(fetch_head, "FETCH_HEAD")
1575REPO_GIT_PATH_FUNC(shallow, "shallow")