Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

GitMetadataFastPath.ts

1,444 lines57.7 KB

1// @effect-diagnostics nodeBuiltinImport:off globalDate:off globalTimers:off - plain Node on purpose: this runs before and instead of a process spawn.
2/**
3 * Answers a small set of read-only git metadata commands by reading the
4 * repository files directly, without spawning `git`.
5 *
6 * Background loops ask git the same cheap questions (toplevel, remotes, HEAD,
7 * a config value) many times a minute per project. On Windows every spawn costs
8 * a launcher, a `conhost.exe` and a slot on the session-wide win32k lock, so the
9 * volume stalls the whole desktop. Reading a few small files costs microseconds.
10 *
11 * Contract: `tryAnswerGitCommand` returns exactly what `git` would have printed,
12 * or `null`. `null` means "not sure" and the caller must spawn git. Anything
13 * unusual (unknown arguments, `GIT_*` overrides, includes, extensions, bare
14 * repositories, reftable, ambiguous names, unreadable files) returns `null`.
15 * Never guess here: a wrong answer is worse than a spawn.
16 *
17 * Whether a directory is a repository git is willing to open at all (ownership
18 * and `safe.directory`, format version, filesystem boundaries) is git's call:
19 * git is asked once per repository and the verdict is reused for a few minutes.
20 * This module only ever reads text and never runs anything a repository configures.
21 */
22import * as NodeAsyncHooks from "node:async_hooks";
23import * as NodeChildProcess from "node:child_process";
24import * as NodeFSP from "node:fs/promises";
25import * as NodeOS from "node:os";
26import * as NodePath from "node:path";
27​
28export interface GitFastPathInput {
29 readonly cwd: string;
30 readonly args: ReadonlyArray<string>;
31 readonly env?: NodeJS.ProcessEnv | undefined;
32 /** The caller's budget for the command; the answer never takes longer than this. */
33 readonly timeoutMs?: number | null | undefined;
34 /** The caller's output cap. A larger answer is left to git, which truncates or fails as asked. */
35 readonly maxOutputBytes?: number | undefined;
37​
38export interface GitFastPathAnswer {
39 readonly exitCode: number;
40 readonly stdout: string;
41 readonly stderr: string;
43​
44/** `T3CODE_GIT_FAST_PATH=0` turns the fast path off; every command spawns git again. */
45const isGitFastPathEnabled = (env: NodeJS.ProcessEnv = process.env) =>
46 env.T3CODE_GIT_FAST_PATH !== "0";
47​
48const ANSWER_TIMEOUT_MS = 2_000;
49// Attempts that ran out of budget while their reads were still pending.
50let abandonedReads = 0;
51// Same default as the process runners that would otherwise spawn git.
52const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
53​
54class Unsure extends Error {}
55/** Discovery reached the filesystem root, and git agreed: exit 128 with this stderr. */
56class NotARepository extends Error {
57 readonly stderr: string;
58 constructor(stderr: string) {
59 super("not a repository");
60 this.stderr = stderr;
61 }
63const unsure = (reason: string): never => {
64 throw new Unsure(reason);
65};
66​
67// GIT_* variables that cannot change discovery, config or ref resolution.
68const HARMLESS_GIT_ENV = new Set([
69 "GIT_TERMINAL_PROMPT",
70 "GIT_ASKPASS",
71 "GIT_EDITOR",
72 "GIT_SEQUENCE_EDITOR",
73 "GIT_PAGER",
74 "GIT_OPTIONAL_LOCKS",
75 "GIT_SSH",
76 "GIT_SSH_COMMAND",
77 "GIT_SSH_VARIANT",
78 "GIT_AUTHOR_NAME",
79 "GIT_AUTHOR_EMAIL",
80 "GIT_AUTHOR_DATE",
81 "GIT_COMMITTER_NAME",
82 "GIT_COMMITTER_EMAIL",
83 "GIT_COMMITTER_DATE",
84 "GIT_LFS_SKIP_SMUDGE",
85 "GIT_MERGE_AUTOEDIT",
86 "GIT_EXEC_PATH",
87 "GIT_INSTALL_ROOT",
88]);
89​
90function hasGitEnvOverride(env: NodeJS.ProcessEnv | undefined): boolean {
91 if (!env) return false;
92 for (const key of Object.keys(env)) {
93 if (env[key] === undefined) continue;
94 const upper = key.toUpperCase();
95 if (upper.startsWith("GIT_") && !HARMLESS_GIT_ENV.has(upper)) return true;
96 }
97 return false;
99​
100// Where git finds itself and its system/global config. The cached listing and
101// verdicts come from git run with the server's own environment.
102const GIT_LOCATION_ENV = new Set([
103 "HOME",
104 "USERPROFILE",
105 "HOMEDRIVE",
106 "HOMEPATH",
107 "XDG_CONFIG_HOME",
108 "PATH",
109]);
110​
111function movesGitOrItsConfig(env: NodeJS.ProcessEnv | undefined): boolean {
112 if (!env) return false;
113 for (const [key, value] of Object.entries(env)) {
114 // Windows environment names ignore case; `process.env` lookups there do too.
115 const name = NodePath.sep === "\\" ? key.toUpperCase() : key;
116 if (GIT_LOCATION_ENV.has(name) && value !== process.env[key]) return true;
117 }
118 return false;
120​
121/**
122 * Runs at most `max` of the given tasks at once, the rest in arrival order.
123 * Exported for tests.
124 */
125export function makeTaskLimiter(max: number) {
126 let running = 0;
127 const waiting: Array<() => void> = [];
128 return async <T>(task: () => Promise<T>): Promise<T> => {
129 // A finishing task hands its slot to the next one, so `running` stays put.
130 if (running >= max) await new Promise<void>((resolve) => waiting.push(resolve));
131 else running++;
132 try {
133 return await task();
134 } finally {
135 const next = waiting.shift();
136 if (next) next();
137 else running--;
138 }
139 };
141​
142// The git processes started here run outside the drivers' process permits. A
143// sweep over many repositories asks for one verdict each, all at once.
144const withOwnGitProcess = makeTaskLimiter(4);
145​
146const toGitPath = (value: string) => (NodePath.sep === "\\" ? value.replaceAll("\\", "/") : value);
147​
148// Symlinks are git's to follow: one inside repository metadata can point at a
149// `\\server\share` path, and touching that makes Windows authenticate to the server.
150// Directories found free of symlinks, with their ancestors, are remembered only
151// for the rest of one query: a later one checks them again, since any may have
152// been swapped for a symlink in between.
153const symlinkFreeDirs = new NodeAsyncHooks.AsyncLocalStorage<Set<string>>();
154​
155/** Runs one query with its own memory of checked directories. */
156const withFreshSymlinkChecks = <T>(work: () => Promise<T>): Promise<T> =>
157 symlinkFreeDirs.run(new Set(), work);
158​
159function isKnownSymlinkFree(dir: string): boolean {
160 const prefix = dir.endsWith(NodePath.sep) ? dir : dir + NodePath.sep;
161 for (const known of symlinkFreeDirs.getStore() ?? []) {
162 if (known === dir || known.startsWith(prefix)) return true;
163 }
164 return false;
166​
167function rememberSymlinkFree(dir: string): void {
168 symlinkFreeDirs.getStore()?.add(dir);
170​
171/** Declines when `target` or a directory above it is a symlink. */
172async function assertNoSymlinks(target: string): Promise<void> {
173 const parent = NodePath.dirname(target);
174 let parentChecked = false;
175 for (let dir = parent; !isKnownSymlinkFree(dir);) {
176 const stat = await NodeFSP.lstat(dir).catch(() => null);
177 if (stat?.isSymbolicLink()) unsure("symlink in repository path");
178 if (dir === parent) parentChecked = stat !== null;
179 const above = NodePath.dirname(dir);
180 if (above === dir) break;
181 dir = above;
182 }
183 if (parentChecked) rememberSymlinkFree(parent);
184 const stat = await NodeFSP.lstat(target).catch(() => null);
185 if (stat?.isSymbolicLink()) unsure("symlink in repository path");
187​
188async function statOrNull(target: string) {
189 await assertNoSymlinks(target);
190 try {
191 return await NodeFSP.lstat(target);
192 } catch {
193 return null;
194 }
196​
197// git bounds what it reads from a repository too (HEAD, the `.git` file). The
198// server opens folders it did not create, so a huge or special file is git's to refuse.
199const SMALL_FILE_BYTES = 4 * 1024;
200const CONFIG_FILE_BYTES = 1024 * 1024;
201const PACKED_REFS_BYTES = 32 * 1024 * 1024;
202​
203/** Text of a regular file no larger than `maxBytes`, `null` when it does not exist. */
204async function readBoundedFile(file: string, maxBytes: number): Promise<string | null> {
205 // One handle for the check and the read: a path checked first and opened later
206 // can be swapped for a FIFO or a huge file in between. O_NONBLOCK keeps the
207 // open itself from waiting on a FIFO, O_NOFOLLOW from following a swapped-in
208 // symlink; Windows has neither.
209 await assertNoSymlinks(file);
210 const handle = await NodeFSP.open(
211 file,
212 NodeFSP.constants.O_RDONLY |
213 (NodeFSP.constants.O_NONBLOCK ?? 0) |
214 (NodeFSP.constants.O_NOFOLLOW ?? 0),
215 ).catch((error: NodeJS.ErrnoException) =>
216 error.code === "ENOENT" || error.code === "ENOTDIR" ? null : unsure("unreadable file"),
217 );
218 if (handle === null) return null;
219 try {
220 const stat = await handle.stat();
221 if (!stat.isFile() || stat.size > maxBytes) unsure("not a small regular file");
222 // One spare byte shows a file that grew after the size was taken.
223 const buffer = Buffer.alloc(stat.size + 1);
224 let length = 0;
225 while (length < buffer.length) {
226 const { bytesRead } = await handle.read(buffer, length, buffer.length - length, length);
227 if (bytesRead === 0) break;
228 length += bytesRead;
229 }
230 if (length > stat.size) unsure("file grew while it was read");
231 const text = buffer.toString("utf8", 0, length);
232 // Lossy decoding or a NUL would make the answer differ from git's bytes.
233 if (text.includes("\0") || text.includes("\ufffd")) unsure("binary content");
234 return text;
235 } finally {
236 await handle.close();
237 }
239​
240/**
241 * git refuses `\\server\share` targets in `.git` files and `commondir`: touching
242 * one makes Windows authenticate to that server. Checked before any filesystem call.
243 */
244function assertLocalPath(target: string): void {
245 if (/^[\\/]{2}/.test(target)) unsure("UNC path");
247​
248// ---------------------------------------------------------------------------
249// Config parsing
250​
251export interface GitConfigEntry {
252 /** Canonical key: lowercase section and variable, subsection as written. */
253 readonly key: string;
254 readonly value: string;
256​
257/**
258 * Strict parser for git's config file syntax. Throws on anything it does not
259 * fully understand, including value-less keys, so the caller falls back to git.
260 */
261export function parseGitConfig(text: string): ReadonlyArray<GitConfigEntry> {
262 const entries: Array<GitConfigEntry> = [];
263 let section: string | null = null;
264 let index = text.charCodeAt(0) === 0xfeff ? 1 : 0;
265 const length = text.length;
266 const isSpace = (char: string) => char === " " || char === "\t" || char === "\r";
267​
268 while (index < length) {
269 const char = text[index]!;
270 if (char === "\n" || isSpace(char)) {
271 index++;
272 continue;
273 }
274 if (char === "#" || char === ";") {
275 while (index < length && text[index] !== "\n") index++;
276 continue;
277 }
278 if (char === "[") {
279 const close = text.indexOf("]", index);
280 const lineEnd = text.indexOf("\n", index);
281 if (close === -1) unsure("config: unterminated section header");
282 const header = text.slice(index + 1, close);
283 const quoted = /^([A-Za-z0-9.-]+)[ \t]+"((?:[^"\\\n]|\\.)*)"$/.exec(header);
284 if (quoted) {
285 section = `${quoted[1]!.toLowerCase()}.${quoted[2]!.replace(/\\(.)/g, "$1")}`;
286 } else if (/^[A-Za-z0-9.-]+$/.test(header)) {
287 section = header.toLowerCase();
288 } else {
289 unsure("config: unsupported section header");
290 }
291 if (lineEnd !== -1 && close > lineEnd) unsure("config: section header spans lines");
292 index = close + 1;
293 continue;
294 }
295​
296 if (section === null) unsure("config: key before any section");
297 const nameMatch = /^[A-Za-z][A-Za-z0-9-]*/.exec(text.slice(index, index + 256));
298 if (!nameMatch) unsure("config: invalid variable name");
299 const name = nameMatch![0].toLowerCase();
300 index += nameMatch![0].length;
301 while (index < length && isSpace(text[index]!)) index++;
302 if (text[index] !== "=") unsure("config: value-less key");
303 index++;
304 while (index < length && isSpace(text[index]!)) index++;
305​
306 let value = "";
307 let inQuotes = false;
308 let pendingSpace = "";
309 for (; index < length; index++) {
310 const current = text[index]!;
311 if (current === "\n") break;
312 if (current === "\r" && text[index + 1] === "\n") continue;
313 if (!inQuotes && (current === "#" || current === ";")) {
314 while (index < length && text[index] !== "\n") index++;
315 break;
316 }
317 if (!inQuotes && (current === " " || current === "\t")) {
318 pendingSpace += current;
319 continue;
320 }
321 value += pendingSpace;
322 pendingSpace = "";
323 if (current === '"') {
324 inQuotes = !inQuotes;
325 continue;
326 }
327 if (current === "\\") {
328 let next = text[++index];
329 if (next === "\r" && text[index + 1] === "\n") next = text[++index];
330 if (next === "\n") continue;
331 if (next === "n") value += "\n";
332 else if (next === "t") value += "\t";
333 else if (next === "b") value += "\b";
334 else if (next === "\\" || next === '"') value += next;
335 else unsure("config: unsupported escape");
336 continue;
337 }
338 value += current;
339 }
340 if (inQuotes) unsure("config: unterminated quote");
341 entries.push({ key: `${section}.${name}`, value });
342 }
343 return entries;
345​
346/** `Section.Sub.Name` -> `section.Sub.name`, the form git prints and compares. */
347function canonicalConfigKey(key: string): string | null {
348 const first = key.indexOf(".");
349 const last = key.lastIndexOf(".");
350 if (first <= 0 || last === key.length - 1) return null;
351 if (/[\n\0]/.test(key)) return null;
352 const section = key.slice(0, first).toLowerCase();
353 const name = key.slice(last + 1).toLowerCase();
354 if (!/^[a-z0-9-]+$/.test(section) || !/^[a-z][a-z0-9-]*$/.test(name)) return null;
355 return first === last ? `${section}.${name}` : `${section}.${key.slice(first + 1, last)}.${name}`;
357​
358const lastValue = (entries: ReadonlyArray<GitConfigEntry>, key: string) =>
359 entries.findLast((entry) => entry.key === key)?.value;
360​
361/** git's boolean: a word, or any non-zero integer (`core.bare = 2` is true). */
362const isGitTrue = (value: string | undefined) => {
363 const text = value?.trim() ?? "";
364 if (/^(true|yes|on)$/i.test(text)) return true;
365 return /^[-+]?\d+[kmg]?$/i.test(text) && Number.parseInt(text, 10) !== 0;
366};
367​
368// ---------------------------------------------------------------------------
369// System and global config
370//
371// Their locations depend on the git installation, so git lists them once and
372// the result is reused until one of the files it came from changes.
373​
374interface OuterConfig {
375 readonly entries: ReadonlyArray<GitConfigEntry>;
376 readonly files: ReadonlyArray<string>;
377 readonly fingerprint: string;
378 readonly loadedAtMs: number;
380​
381const OUTER_CONFIG_MAX_AGE_MS = 5 * 60_000;
382const OUTER_CONFIG_RETRY_MS = 30_000;
383let outerConfig: Promise<OuterConfig> | null = null;
384let outerConfigFailedAtMs: number | null = null;
385​
386function outerConfigCandidates(origins: ReadonlyArray<string>): ReadonlyArray<string> {
387 const home = NodeOS.homedir();
388 const xdg = process.env.XDG_CONFIG_HOME?.trim() || NodePath.join(home, ".config");
389 return [
390 ...new Set([
391 ...origins,
392 NodePath.join(home, ".gitconfig"),
393 NodePath.join(xdg, "git", "config"),
394 ]),
395 ];
397​
398async function fingerprintFiles(files: ReadonlyArray<string>): Promise<string> {
399 const stats = await Promise.all(files.map(statOrNull));
400 return stats.map((stat) => (stat ? `${stat.mtimeMs}:${stat.size}:${stat.ino}` : "-")).join("|");
402​
403function listOuterConfig(): Promise<string> {
404 return withOwnGitProcess(
405 () =>
406 new Promise((resolve, reject) => {
407 NodeChildProcess.execFile(
408 "git",
409 ["config", "--list", "--show-scope", "--show-origin", "-z"],
410 { cwd: NodeOS.tmpdir(), windowsHide: true, timeout: 10_000, maxBuffer: 4 * 1024 * 1024 },
411 (error, stdout) => (error ? reject(error) : resolve(stdout)),
412 );
413 }),
414 );
416​
417/** Where git looks for an `include.path` value found in `originFile`. */
418function includedConfigFile(originFile: string, value: string): string {
419 if (value === "~" || value.startsWith("~/"))
420 return NodePath.join(NodeOS.homedir(), value.slice(1));
421 // `~user/` needs the account database; `%(prefix)/` needs git's install location.
422 if (value.startsWith("~") || value.startsWith("%(")) unsure("outer config: include location");
423 return NodePath.resolve(NodePath.dirname(originFile), value);
425​
426async function loadOuterConfig(): Promise<OuterConfig> {
427 // Records: scope NUL origin NUL key LF value NUL
428 const fields = (await listOuterConfig()).split("\0");
429 const entries: Array<GitConfigEntry> = [];
430 const origins: Array<string> = [];
431 for (let index = 0; index + 2 < fields.length; index += 3) {
432 const scope = fields[index]!;
433 const origin = fields[index + 1]!;
434 const record = fields[index + 2]!;
435 if (scope !== "system" && scope !== "global") continue;
436 if (!origin.startsWith("file:")) unsure("outer config: non-file origin");
437 const originFile = NodePath.resolve(origin.slice("file:".length));
438 origins.push(originFile);
439 const separator = record.indexOf("\n");
440 if (separator === -1) unsure("outer config: value-less key");
441 const entry = { key: record.slice(0, separator), value: record.slice(separator + 1) };
442 entries.push(entry);
443 // An included file that is missing or empty lists no entries of its own, so
444 // it is watched by name: the listing is stale once it gains content.
445 if (entry.key === "include.path") origins.push(includedConfigFile(originFile, entry.value));
446 }
447 const files = outerConfigCandidates(origins);
448 return { entries, files, fingerprint: await fingerprintFiles(files), loadedAtMs: Date.now() };
450​
451/**
452 * Also the proof that git runs at all: every answer asks for it first, so a
453 * missing or broken git stays as visible as it was when each question spawned it.
454 */
455async function getOuterConfig(): Promise<ReadonlyArray<GitConfigEntry>> {
456 const pending = outerConfig;
457 const current = pending ? await pending.catch(() => null) : null;
458 if (
459 current &&
460 Date.now() - current.loadedAtMs < OUTER_CONFIG_MAX_AGE_MS &&
461 (await fingerprintFiles(current.files)) === current.fingerprint
462 ) {
463 return current.entries;
464 }
465 // Concurrent callers share one listing.
466 if (outerConfig === pending) {
467 // A listing that failed (no git, a config this reader refuses) fails again;
468 // retrying it for every command would add a spawn to each one.
469 if (
470 outerConfigFailedAtMs !== null &&
471 Date.now() - outerConfigFailedAtMs < OUTER_CONFIG_RETRY_MS
472 )
473 unsure("outer config unavailable");
474 const loading = loadOuterConfig();
475 loading.then(
476 () => (outerConfigFailedAtMs = null),
477 () => (outerConfigFailedAtMs = Date.now()),
478 );
479 outerConfig = loading;
480 }
481 return (await outerConfig!).entries;
483​
484/** Test seam: forget the cached system/global config. */
485export const resetGitFastPathCaches = () => {
486 outerConfig = null;
487 outerConfigFailedAtMs = null;
488 verdicts.clear();
489 packedRefsCache.clear();
490 revListMemo.clear();
491};
492​
493// ---------------------------------------------------------------------------
494// Repository discovery
495​
496interface Repository {
497 /** Real path of the directory that holds `.git`. */
498 readonly workTree: string;
499 readonly gitDir: string;
500 readonly commonDir: string;
501 /** `.git` is a directory (main worktree), not a `gitdir:` file. */
502 readonly dotGitIsDirectory: boolean;
503 readonly localConfig: ReadonlyArray<GitConfigEntry>;
505​
506const HEAD_CONTENT = /^(?:ref:[ \t]*refs\/\S+|[0-9a-f]{40}|[0-9a-f]{64})\s*$/;
507​
508/**
509 * git's `is_git_directory`. A directory whose HEAD is empty or garbage (an
510 * interrupted clone) is not a repository to git, which then keeps looking in the
511 * parents; callers here decline instead.
512 */
513async function looksLikeGitDir(dir: string): Promise<boolean> {
514 const [head, objects, refs, commondir] = await Promise.all([
515 statOrNull(NodePath.join(dir, "HEAD")),
516 statOrNull(NodePath.join(dir, "objects")),
517 statOrNull(NodePath.join(dir, "refs")),
518 statOrNull(NodePath.join(dir, "commondir")),
519 ]);
520 if (!head?.isFile() || !(commondir?.isFile() || (objects?.isDirectory() && refs?.isDirectory())))
521 return false;
522 const content = await readBoundedFile(NodePath.join(dir, "HEAD"), SMALL_FILE_BYTES);
523 return content !== null && HEAD_CONTENT.test(content);
525​
526const SUPPORTED_EXTENSIONS = new Set([
527 "extensions.noop",
528 "extensions.objectformat",
529 "extensions.partialclone",
530 "extensions.preciousobjects",
531 "extensions.worktreeconfig",
532]);
533​
534async function openRepository(workTree: string, gitDir: string, dotGitIsDirectory: boolean) {
535 assertLocalPath(gitDir);
536 if (!(await looksLikeGitDir(gitDir))) unsure("not a git directory");
537 let commonDir = gitDir;
538 const commonDirFile = await readBoundedFile(NodePath.join(gitDir, "commondir"), SMALL_FILE_BYTES);
539 if (commonDirFile !== null) {
540 const relative = commonDirFile.replace(/\r?\n$/, "");
541 if (relative.length === 0 || relative.includes("\n")) unsure("malformed commondir");
542 assertLocalPath(relative);
543 commonDir = NodePath.resolve(gitDir, relative);
544 assertLocalPath(commonDir);
545 const [objects, refs] = await Promise.all([
546 statOrNull(NodePath.join(commonDir, "objects")),
547 statOrNull(NodePath.join(commonDir, "refs")),
548 ]);
549 if (!objects?.isDirectory() || !refs?.isDirectory()) unsure("common dir is incomplete");
550 }
551​
552 const sharedConfig = parseGitConfig(
553 (await readBoundedFile(NodePath.join(commonDir, "config"), CONFIG_FILE_BYTES)) ??
554 unsure("no repository config"),
555 );
556 // Without a format version git ignores every extension, worktreeConfig included.
557 const versionText = lastValue(sharedConfig, "core.repositoryformatversion");
558 if (versionText === undefined && sharedConfig.some(({ key }) => key.startsWith("extensions.")))
559 unsure("extensions without a format version");
560 // extensions.worktreeConfig adds a per-worktree file that outranks the shared one.
561 const worktreeConfigFile = isGitTrue(lastValue(sharedConfig, "extensions.worktreeconfig"))
562 ? ((await readBoundedFile(NodePath.join(gitDir, "config.worktree"), CONFIG_FILE_BYTES)) ?? "")
563 : "";
564 const localConfig = [...sharedConfig, ...parseGitConfig(worktreeConfigFile)];
565 const version = Number(versionText ?? "0");
566 if (version !== 0 && version !== 1) unsure("unknown repository format");
567 for (const { key } of localConfig) {
568 if (key.startsWith("include.") || key.startsWith("includeif.")) unsure("config includes");
569 if (key.startsWith("extensions.") && !SUPPORTED_EXTENSIONS.has(key)) unsure("extension");
570 }
571 if (isGitTrue(lastValue(localConfig, "core.bare"))) unsure("bare repository");
572 if (lastValue(localConfig, "core.worktree") !== undefined) unsure("core.worktree");
573​
574 return { workTree, gitDir, commonDir, dotGitIsDirectory, localConfig } satisfies Repository;
576​
577async function discoverRepository(cwd: string): Promise<{ repo: Repository; realCwd: string }> {
578 const realCwd = await NodeFSP.realpath(cwd);
579 if (realCwd.startsWith("\\\\")) unsure("UNC path");
580 const startStat = await NodeFSP.stat(realCwd);
581 // git cannot even start in a file; walking up from it would answer for the parent repository.
582 if (!startStat.isDirectory()) unsure("cwd is not a directory");
583 rememberSymlinkFree(realCwd);
584 // Windows has no device ids worth comparing, and git for Windows does not compare them either.
585 const checkBoundaries = NodePath.sep !== "\\";
586​
587 for (let dir = realCwd; ;) {
588 const dotGit = NodePath.join(dir, ".git");
589 const dotGitStat = await statOrNull(dotGit);
590 // git walks past a `.git` directory that is not a repository (an empty one, a broken HEAD).
591 if (dotGitStat?.isDirectory() && (await looksLikeGitDir(dotGit))) {
592 return { repo: await openRepository(dir, dotGit, true), realCwd };
593 }
594 if (dotGitStat && !dotGitStat.isDirectory()) {
595 const pointer = /^gitdir: (.+?)\r?\n?$/.exec(
596 (await readBoundedFile(dotGit, SMALL_FILE_BYTES)) ?? "",
597 );
598 if (!pointer) unsure("malformed .git file");
599 assertLocalPath(pointer![1]!);
600 return {
601 repo: await openRepository(dir, NodePath.resolve(dir, pointer![1]!), false),
602 realCwd,
603 };
604 }
605 // Inside a git directory or a bare repository: git has rules this does not replicate.
606 if (await looksLikeGitDir(dir)) unsure("inside a git directory");
607​
608 const parent = NodePath.dirname(dir);
609 if (parent === dir) return notARepository(realCwd);
610 // git stops at filesystem boundaries unless told otherwise.
611 if (checkBoundaries && (await NodeFSP.stat(parent)).dev !== startStat.dev)
612 unsure("filesystem boundary");
613 dir = parent;
614 }
616​
617// ---------------------------------------------------------------------------
618// git's verdict on the repository
619//
620// Discovery above finds the files. Whether git accepts them (owner and
621// `safe.directory`, format version and extensions, filesystem boundaries) has
622// too many rules, and too much security history, to mirror here. One spawn per
623// repository per few minutes settles it, against hundreds of answered questions.
624​
625const VERDICT_MAX_AGE_MS = 5 * 60_000;
626const VERDICT_CAPACITY = 256;
627​
628interface GitVerdict {
629 readonly exitCode: number;
630 readonly stdout: string;
631 readonly stderr: string;
633​
634const verdicts = new Map<string, { readonly at: number; readonly verdict: Promise<GitVerdict> }>();
635​
636function askGit(args: ReadonlyArray<string>): Promise<GitVerdict> {
637 return withOwnGitProcess(
638 () =>
639 new Promise((resolve, reject) => {
640 NodeChildProcess.execFile(
641 "git",
642 [...args],
643 {
644 cwd: NodeOS.tmpdir(),
645 env: { ...process.env, LC_ALL: "C" },
646 windowsHide: true,
647 timeout: 10_000,
648 maxBuffer: 64 * 1024,
649 },
650 (error, stdout, stderr) =>
651 error && typeof error.code !== "number"
652 ? reject(error)
653 : resolve({
654 exitCode: typeof error?.code === "number" ? error.code : 0,
655 stdout,
656 stderr,
657 }),
658 );
659 }),
660 );
662​
663/**
664 * What git's acceptance depends on beyond the path: which directories these are
665 * and who owns them, the repository config, and the system and global config
666 * that hold `safe.directory`. A replaced repository or changed settings get a new verdict.
667 */
668async function repositoryIdentity(repo: Repository): Promise<string> {
669 const directories = await Promise.all(
670 [repo.workTree, repo.gitDir, repo.commonDir].map((dir) => NodeFSP.stat(dir)),
671 );
672 const outer = await outerConfig?.catch(() => null);
673 return [
674 ...directories.map((stat) => `${stat.dev}:${stat.ino}:${stat.uid}:${stat.birthtimeMs}`),
675 await fingerprintFiles([NodePath.join(repo.commonDir, "config")]),
676 outer?.fingerprint ?? "",
677 ].join("|");
679​
680function gitVerdict(args: ReadonlyArray<string>, identity = ""): Promise<GitVerdict> {
681 const key = [...args, identity].join("\0");
682 const known = verdicts.get(key);
683 if (known && Date.now() - known.at < VERDICT_MAX_AGE_MS) return known.verdict;
684 if (verdicts.size >= VERDICT_CAPACITY) verdicts.clear();
685 const verdict = askGit(args);
686 verdicts.set(key, { at: Date.now(), verdict });
687 // A failed spawn is not a verdict.
688 verdict.catch(() => verdicts.delete(key));
689 return verdict;
691​
692/** Declines unless git opens the same repository from the same place. */
693async function requireGitAgrees(repo: Repository, explicitGitDir: boolean): Promise<void> {
694 const identity = await repositoryIdentity(repo);
695 const verdict = explicitGitDir
696 ? await gitVerdict(["--git-dir", repo.gitDir, "rev-parse", "--git-dir"], identity)
697 : await gitVerdict(["-C", repo.workTree, "rev-parse", "--show-toplevel"], identity);
698 if (verdict.exitCode !== 0) unsure("git refuses this repository");
699 if (!explicitGitDir && verdict.stdout !== `${toGitPath(repo.workTree)}\n`)
700 unsure("git opens a different repository");
702​
703/** Discovery found no repository; answers 128 only with git's own words for it. */
704async function notARepository(cwd: string): Promise<never> {
705 const verdict = await gitVerdict(["-C", cwd, "rev-parse", "--show-toplevel"]);
706 if (verdict.exitCode !== 128 || verdict.stdout !== "") unsure("git found a repository");
707 throw new NotARepository(verdict.stderr);
709​
710// ---------------------------------------------------------------------------
711// Refs
712​
713const OBJECT_ID = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
714​
715const WINDOWS_DEVICE_NAME = /^(?:con|prn|aux|nul|com[0-9]|lpt[0-9]|conin\$|conout\$)(?:\..*)?$/i;
716​
717/** Accepts only names that are safe to join onto the git directory. */
718function isSafeRefName(ref: string): boolean {
719 if (!ref.startsWith("refs/") || ref.endsWith("/") || ref.endsWith(".")) return false;
720 // eslint-disable-next-line no-control-regex -- git's check_refname_format rejects control characters
721 if (/[\x00-\x20\x7f~^:?*[\\]|\.\.|@\{|\/\//.test(ref)) return false;
722 return ref.split("/").every(
723 (part) =>
724 part.length > 0 &&
725 !part.startsWith(".") &&
726 !part.endsWith(".lock") &&
727 // Legal to git, but Windows maps these onto other files or onto devices.
728 !part.endsWith(".") &&
729 !WINDOWS_DEVICE_NAME.test(part),
730 );
732​
733const packedRefsCache = new Map<
734 string,
735 { fingerprint: string; refs: ReadonlyMap<string, string> }
736>();
737​
738/** Packed ref name -> object id. */
739async function readPackedRefs(commonDir: string): Promise<ReadonlyMap<string, string>> {
740 const file = NodePath.join(commonDir, "packed-refs");
741 const stat = await statOrNull(file);
742 if (!stat) return new Map();
743 const fingerprint = `${stat.mtimeMs}:${stat.size}:${stat.ino}`;
744 const cached = packedRefsCache.get(file);
745 if (cached?.fingerprint === fingerprint) return cached.refs;
746​
747 const refs = new Map<string, string>();
748 const text = (await readBoundedFile(file, PACKED_REFS_BYTES)) ?? "";
749 for (const line of text.split("\n")) {
750 if (line.length === 0 || line.startsWith("#") || line.startsWith("^")) continue;
751 const space = line.indexOf(" ");
752 if (space === -1 || !OBJECT_ID.test(line.slice(0, space))) unsure("malformed packed-refs");
753 // git dies on an unsafe name here; these names reach NUL-delimited output.
754 const name = line.slice(space + 1);
755 if (!isSafeRefName(name)) unsure("unsafe packed ref name");
756 refs.set(name, line.slice(0, space));
757 }
758 // Without an inode a same-size rewrite inside one mtime tick would go unseen.
759 if (stat.ino === 0) return refs;
760 if (packedRefsCache.size >= 64) packedRefsCache.clear();
761 packedRefsCache.set(file, { fingerprint, refs });
762 return refs;
764​
765type RefState = "exists" | "missing";
766​
767/** Object id a ref points at, `null` when the ref does not exist. */
768async function refObjectId(repo: Repository, ref: string): Promise<string | null> {
769 if (!isSafeRefName(ref)) unsure("unsafe ref name");
770 // These live in each worktree's own git directory, not in the common one read below.
771 if (/^refs\/(?:bisect|worktree|rewritten)\//.test(ref)) unsure("per-worktree ref");
772 const looseFile = NodePath.join(repo.commonDir, ...ref.split("/"));
773 // A directory here means deeper refs exist (`refs/heads/a` vs `refs/heads/a/b`), not this one.
774 const loose = (await statOrNull(looseFile))?.isDirectory()
775 ? null
776 : await readBoundedFile(looseFile, SMALL_FILE_BYTES);
777 if (loose !== null) {
778 // Symbolic or damaged loose refs need git's full resolution.
779 return OBJECT_ID.test(loose.trim()) ? loose.trim() : unsure("loose ref is not an object id");
780 }
781 return (await readPackedRefs(repo.commonDir)).get(ref) ?? null;
783​
784const refState = async (repo: Repository, ref: string): Promise<RefState> =>
785 (await refObjectId(repo, ref)) === null ? "missing" : "exists";
786​
787type Head =
788 | { /** Full ref name HEAD points at. */ readonly ref: string }
789 | { /** Detached. */ readonly ref: null; readonly objectId: string };
790​
791async function readHead(repo: Repository): Promise<Head> {
792 const content = (
793 (await readBoundedFile(NodePath.join(repo.gitDir, "HEAD"), SMALL_FILE_BYTES)) ??
794 unsure("no HEAD")
795 ).trim();
796 if (OBJECT_ID.test(content)) return { ref: null, objectId: content };
797 const symbolic = /^ref: (refs\/\S+)$/.exec(content);
798 if (!symbolic || !isSafeRefName(symbolic[1]!)) unsure("unexpected HEAD");
799 return { ref: symbolic![1]! };
801​
802/** `refs/heads/x` -> `x`, only when no other ref namespace could claim `x`. */
803async function shortBranchName(repo: Repository, ref: string): Promise<string> {
804 if (!ref.startsWith("refs/heads/")) unsure("HEAD outside refs/heads");
805 const short = ref.slice("refs/heads/".length);
806 const rivals = [
807 `refs/${short}`,
808 `refs/tags/${short}`,
809 `refs/remotes/${short}`,
810 `refs/remotes/${short}/HEAD`,
811 ];
812 for (const rival of rivals) {
813 if (!isSafeRefName(rival)) unsure("unsafe rival ref");
814 if (await statOrNull(NodePath.join(repo.commonDir, ...rival.split("/"))))
815 unsure("ambiguous short name");
816 }
817 for (const dir of new Set([repo.gitDir, repo.commonDir])) {
818 if (await statOrNull(NodePath.join(dir, ...short.split("/")))) unsure("ambiguous short name");
819 }
820 const packed = await readPackedRefs(repo.commonDir);
821 if (rivals.some((rival) => packed.has(rival))) unsure("ambiguous short name");
822 return short;
824​
825// ---------------------------------------------------------------------------
826// Remotes
827​
828async function mergedConfig(repo: Repository): Promise<ReadonlyArray<GitConfigEntry>> {
829 const outer = await getOuterConfig();
830 // Conditional includes depend on the repository; the outer listing cannot show them.
831 if (outer.some(({ key }) => key.startsWith("includeif."))) unsure("conditional includes");
832 return [...outer, ...repo.localConfig];
834​
835interface Remote {
836 readonly name: string;
837 readonly urls: ReadonlyArray<string>;
838 readonly pushUrls: ReadonlyArray<string>;
840​
841async function readRemotes(repo: Repository): Promise<ReadonlyArray<Remote>> {
842 const config = await mergedConfig(repo);
843 // URL rewriting changes what git prints for every remote.
844 if (config.some(({ key }) => key.startsWith("url."))) unsure("url rewriting");
845 for (const legacy of ["remotes", "branches"]) {
846 const dir = NodePath.join(repo.commonDir, legacy);
847 await assertNoSymlinks(dir);
848 const names = await NodeFSP.readdir(dir).catch(() => []);
849 if (names.length > 0) unsure("legacy remote files");
850 }
851​
852 const remotes = new Map<string, { urls: Array<string>; pushUrls: Array<string> }>();
853 for (const { key, value } of config) {
854 const match = /^remote\.(.+)\.([a-z][a-z0-9-]*)$/.exec(key);
855 if (!match) continue;
856 const [, name, variable] = match as unknown as [string, string, string];
857 if (variable === "partialclonefilter" || variable === "vcs") unsure("remote variable");
858 const remote = remotes.get(name) ?? { urls: [], pushUrls: [] };
859 remotes.set(name, remote);
860 if (variable !== "url" && variable !== "pushurl") continue;
861 // An empty value resets the list in git; rare enough to leave to git.
862 if (value.length === 0) unsure("empty remote url");
863 (variable === "url" ? remote.urls : remote.pushUrls).push(value);
864 }
865​
866 const listed: Array<Remote> = [];
867 for (const [name, remote] of remotes) {
868 // git lists a remote for any `remote.<name>.*` key; without a url its lines differ.
869 if (remote.urls.length === 0) unsure("remote without url");
870 listed.push({ name, ...remote });
871 }
872 const byteOrder = (left: Remote, right: Remote) =>
873 Buffer.compare(Buffer.from(left.name), Buffer.from(right.name));
874 return listed.toSorted(byteOrder);
876​
877// ---------------------------------------------------------------------------
878// Commands
879​
880const ok = (stdout: string): GitFastPathAnswer => ({ exitCode: 0, stdout, stderr: "" });
881const silentFailure: GitFastPathAnswer = { exitCode: 1, stdout: "", stderr: "" };
882​
883/**
884 * git translates its messages when the locale asks for it. Error text answered
885 * here is English, so it is only given to a caller whose git would speak English.
886 */
887function gitMessagesMayBeTranslated(env: NodeJS.ProcessEnv | undefined): boolean {
888 const merged = { ...process.env, ...env };
889 const locale = merged.LC_ALL || merged.LC_MESSAGES || merged.LANG || "";
890 if (locale === "" || /^(?:C|POSIX)(?:[.@]|$)/.test(locale)) return false;
891 return !(merged.LANGUAGE || locale).split(":").every((name) => /^en(?:[_.@]|$)/.test(name));
893​
894const sameArgs = (args: ReadonlyArray<string>, expected: ReadonlyArray<string>) =>
895 args.length === expected.length && expected.every((value, index) => args[index] === value);
896​
897const REV_PARSE_FORMS: ReadonlyArray<ReadonlyArray<string>> = [
898 ["--is-inside-work-tree"],
899 ["--show-toplevel"],
900 ["--git-common-dir"],
901 ["--abbrev-ref", "HEAD"],
902 ["--abbrev-ref", "--symbolic-full-name", "@{upstream}"],
903];
904​
905async function answerRevParse(
906 cwd: string,
907 args: ReadonlyArray<string>,
908 env: NodeJS.ProcessEnv | undefined,
909) {
910 // Other forms (`--sq-quote`, `--parseopt`, ...) work outside a repository.
911 if (!REV_PARSE_FORMS.some((form) => sameArgs(args, form))) unsure("rev-parse arguments");
912 const { repo, realCwd } = await discoverRepository(cwd);
913 await requireGitAgrees(repo, false);
914 if (sameArgs(args, ["--is-inside-work-tree"])) return ok("true\n");
915 if (sameArgs(args, ["--show-toplevel"])) return ok(`${toGitPath(repo.workTree)}\n`);
916 if (sameArgs(args, ["--git-common-dir"])) {
917 // Below the worktree root git prints a relative path; leave that form to git.
918 if (realCwd !== repo.workTree) unsure("common dir from a subdirectory");
919 return ok(
920 repo.dotGitIsDirectory && repo.commonDir === repo.gitDir
921 ? ".git\n"
922 : `${toGitPath(repo.commonDir)}\n`,
923 );
924 }
925 if (sameArgs(args, ["--abbrev-ref", "HEAD"])) {
926 const head = await readHead(repo);
927 if (head.ref === null) return ok("HEAD\n");
928 // An unborn branch is an error in git, with a message worth keeping.
929 if ((await refState(repo, head.ref)) === "missing") unsure("unborn branch");
930 return ok(`${await shortBranchName(repo, head.ref)}\n`);
931 }
932 if (sameArgs(args, ["--abbrev-ref", "--symbolic-full-name", "@{upstream}"])) {
933 const head = await readHead(repo);
934 // Detached and unborn HEADs fail with messages of their own.
935 if (head.ref === null || !head.ref.startsWith("refs/heads/")) unsure("detached HEAD");
936 if ((await refState(repo, head.ref!)) === "missing") unsure("unborn branch");
937 const branch = head.ref!.slice("refs/heads/".length);
938 const upstream = await resolveUpstream(repo, await mergedConfig(repo), branch);
939 if (!upstream && gitMessagesMayBeTranslated(env)) unsure("translated error message");
940 return upstream
941 ? ok(`${upstream.short}\n`)
942 : {
943 exitCode: 128,
944 stdout: "",
945 stderr: `fatal: no upstream configured for branch '${branch}'\n`,
946 };
947 }
948 return unsure("rev-parse arguments");
950​
951async function answerSymbolicRef(repo: Repository, args: ReadonlyArray<string>) {
952 if (sameArgs(args, ["--quiet", "--short", "HEAD"])) {
953 const head = await readHead(repo);
954 if (head.ref === null) return silentFailure;
955 await refObjectId(repo, head.ref);
956 return ok(`${await shortBranchName(repo, head.ref)}\n`);
957 }
958 if (
959 args.length === 1 &&
960 /^refs\/remotes\/[^/]+\/HEAD$/.test(args[0]!) &&
961 isSafeRefName(args[0]!)
962 ) {
963 const content =
964 (await readBoundedFile(
965 NodePath.join(repo.commonDir, ...args[0]!.split("/")),
966 SMALL_FILE_BYTES,
967 )) ?? unsure("no such ref");
968 const symbolic = /^ref: (refs\/\S+)\r?\n?$/.exec(content);
969 if (!symbolic || !isSafeRefName(symbolic[1]!)) unsure("not a symbolic ref");
970 // git prints the end of a chain; `refObjectId` declines when the target is symbolic too.
971 await refObjectId(repo, symbolic![1]!);
972 return ok(`${symbolic![1]!}\n`);
973 }
974 return unsure("symbolic-ref arguments");
976​
977async function answerRemote(repo: Repository, args: ReadonlyArray<string>) {
978 const remotes = await readRemotes(repo);
979 if (args.length === 0) return ok(remotes.map(({ name }) => `${name}\n`).join(""));
980 if (sameArgs(args, ["-v"])) {
981 return ok(
982 remotes
983 .flatMap(({ name, urls, pushUrls }) => [
984 `${name}\t${urls[0]!} (fetch)\n`,
985 ...(pushUrls.length > 0 ? pushUrls : urls).map((url) => `${name}\t${url} (push)\n`),
986 ])
987 .join(""),
988 );
989 }
990 if (args.length === 2 && args[0] === "get-url") {
991 // A missing remote has a specific exit code and message; git reports it.
992 const remote = remotes.find(({ name }) => name === args[1]) ?? unsure("no such remote");
993 // So does one that only system or global config defines: `get-url` wants it in the repository.
994 if (!repo.localConfig.some(({ key }) => key.startsWith(`remote.${remote.name}.`)))
995 unsure("remote defined outside the repository");
996 return ok(`${remote.urls[0]!}\n`);
997 }
998 return unsure("remote arguments");
1000​
1001// ---------------------------------------------------------------------------
1002// for-each-ref
1003​
1004const REFNAME_FORMAT = "--format=%(refname)";
1005const UPSTREAM_FORMAT =
1006 "--format=%(refname)%00%(upstream:short)%00%(upstream:remotename)%00%(upstream:remoteref)";
1007​
1008const byteOrder = (left: string, right: string) =>
1009 Buffer.compare(Buffer.from(left), Buffer.from(right));
1010​
1011/**
1012 * Every ref whose name starts with `prefix`, loose and packed, that resolves to
1013 * an object: the refs git iterates for a pattern without wildcards.
1014 */
1015async function listBranchRefs(repo: Repository, prefix: string): Promise<ReadonlyArray<string>> {
1016 const packed = await readPackedRefs(repo.commonDir);
1017 const refs = new Set<string>();
1018 for (const ref of packed.keys()) if (ref.startsWith(prefix)) refs.add(ref);
1019​
1020 const visit = async (parent: string, keep: (name: string) => boolean): Promise<void> => {
1021 const dir = NodePath.join(repo.commonDir, ...parent.split("/"));
1022 await assertNoSymlinks(dir);
1023 const entries = await NodeFSP.readdir(dir, { withFileTypes: true }).catch(
1024 (error: NodeJS.ErrnoException) =>
1025 error.code === "ENOENT" ? [] : unsure("unreadable refs directory"),
1026 );
1027 for (const entry of entries) {
1028 if (!keep(entry.name)) continue;
1029 const child = `${parent}/${entry.name}`;
1030 if (entry.isDirectory()) {
1031 await visit(child, () => true);
1032 continue;
1034 // Lock files, odd names and non-files are git's to judge.
1035 if (!entry.isFile() || !isSafeRefName(child)) unsure("unexpected entry under refs");
1036 const content = (
1037 (await readBoundedFile(
1038 NodePath.join(repo.commonDir, ...child.split("/")),
1039 SMALL_FILE_BYTES,
1040 )) ?? unsure("ref vanished")
1041 ).trim();
1042 if (OBJECT_ID.test(content)) {
1043 refs.add(child);
1044 continue;
1046 // A symbolic ref is listed only when its target exists; git warns about the rest.
1047 const symbolic = /^ref: (refs\/\S+)$/.exec(content) ?? unsure("damaged loose ref");
1048 if ((await refState(repo, symbolic[1]!)) === "missing") unsure("dangling symbolic ref");
1049 refs.add(child);
1051 };
1052 const slash = prefix.lastIndexOf("/");
1053 const base = prefix.slice(slash + 1);
1054 await visit(prefix.slice(0, slash), (name) => name.startsWith(base));
1055 return [...refs];
1057​
1058/**
1059 * git's pattern rule for a pattern without wildcards: the whole ref or a leading
1060 * directory of it. Wildcards make git walk the whole namespace, and so does a
1061 * pattern naming no single remote; those are git's to answer.
1062 */
1063function refPatternMatcher(pattern: string): (ref: string) => boolean {
1064 if (!isSafeRefName(pattern) || pattern.includes("*")) unsure("ref pattern");
1065 if (pattern.startsWith("refs/remotes") && pattern.split("/").length < 4)
1066 unsure("every remote-tracking ref");
1067 return (ref) => ref === pattern || ref.startsWith(`${pattern}/`);
1069​
1070/** Tracking ref for `branch.<name>.merge` under the remote's fetch refspecs, or `null` when none maps it. */
1071function mapThroughFetchRefspecs(refspecs: ReadonlyArray<string>, source: string): string | null {
1072 for (const raw of refspecs) {
1073 const refspec = raw.startsWith("+") ? raw.slice(1) : raw;
1074 const colon = refspec.indexOf(":");
1075 // Negative and one-sided refspecs change the mapping in ways not modelled here.
1076 if (refspec.startsWith("^") || colon <= 0 || colon === refspec.length - 1)
1077 unsure("unsupported fetch refspec");
1078 const from = refspec.slice(0, colon);
1079 const to = refspec.slice(colon + 1);
1080 const fromStar = from.indexOf("*");
1081 const toStar = to.indexOf("*");
1082 if (fromStar === -1 && toStar === -1) {
1083 if (from === source) return to;
1084 continue;
1086 if (
1087 fromStar === -1 ||
1088 toStar === -1 ||
1089 from.includes("*", fromStar + 1) ||
1090 to.includes("*", toStar + 1)
1092 unsure("unsupported fetch refspec");
1093 const prefix = from.slice(0, fromStar);
1094 const suffix = from.slice(fromStar + 1);
1095 if (
1096 source.length >= prefix.length + suffix.length &&
1097 source.startsWith(prefix) &&
1098 source.endsWith(suffix)
1099 ) {
1100 const middle = source.slice(prefix.length, source.length - suffix.length);
1101 return `${to.slice(0, toStar)}${middle}${to.slice(toStar + 1)}`;
1104 return null;
1106​
1107/** `refs/remotes/origin/x` -> `origin/x`, only when nothing else could claim that short name. */
1108async function shortTrackingName(repo: Repository, ref: string): Promise<string> {
1109 if (!ref.startsWith("refs/remotes/")) unsure("upstream outside refs/remotes");
1110 // git shortens `refs/remotes/origin/HEAD` to `origin`, by a rule of its own.
1111 if (ref.endsWith("/HEAD")) unsure("upstream is a remote HEAD");
1112 const short = ref.slice("refs/remotes/".length);
1113 const rivals = [`refs/${short}`, `refs/tags/${short}`, `refs/heads/${short}`, `${ref}/HEAD`];
1114 const packed = await readPackedRefs(repo.commonDir);
1115 for (const rival of rivals) {
1116 if (!isSafeRefName(rival) || packed.has(rival)) unsure("ambiguous short name");
1117 if (await statOrNull(NodePath.join(repo.commonDir, ...rival.split("/"))))
1118 unsure("ambiguous short name");
1120 for (const dir of new Set([repo.gitDir, repo.commonDir])) {
1121 if (await statOrNull(NodePath.join(dir, ...short.split("/")))) unsure("ambiguous short name");
1123 return short;
1125​
1126interface Upstream {
1127 /** `origin/main` */
1128 readonly short: string;
1129 readonly remote: string;
1130 /** `refs/heads/main` on the remote. */
1131 readonly merge: string;
1133​
1134/** Configured upstream of a local branch, `null` when it has none. */
1135async function resolveUpstream(
1136 repo: Repository,
1137 config: ReadonlyArray<GitConfigEntry>,
1138 branch: string,
1139): Promise<Upstream | null> {
1140 const values = (name: string) =>
1141 config.filter(({ key }) => key === `branch.${branch}.${name}`).map(({ value }) => value);
1142 const remote = values("remote").at(-1);
1143 const merges = values("merge");
1144 if (remote === undefined && merges.length === 0) return null;
1145 // Half-configured, local (".") and multi-merge upstreams follow rules not modelled here.
1146 if (remote === undefined || remote === "." || merges.length !== 1) unsure("unusual upstream");
1147 const merge = merges[0]!;
1148 if (!isSafeRefName(merge)) unsure("unusual upstream");
1149 if (!config.some(({ key }) => key === `remote.${remote}.url`))
1150 unsure("upstream remote is not configured");
1151 const refspecs = config
1152 .filter(({ key }) => key === `remote.${remote}.fetch`)
1153 .map(({ value }) => value);
1154 const tracking =
1155 mapThroughFetchRefspecs(refspecs, merge) ?? unsure("upstream has no tracking ref");
1156 if ((await refState(repo, tracking)) === "missing") unsure("tracking ref is missing");
1157 return { short: await shortTrackingName(repo, tracking), remote: remote!, merge };
1159​
1160async function upstreamFields(
1161 repo: Repository,
1162 config: ReadonlyArray<GitConfigEntry>,
1163 ref: string,
1164): Promise<string> {
1165 const upstream = ref.startsWith("refs/heads/")
1166 ? await resolveUpstream(repo, config, ref.slice("refs/heads/".length))
1167 : null;
1168 return upstream ? `${upstream.short}\0${upstream.remote}\0${upstream.merge}` : "\0\0";
1170​
1171async function answerForEachRef(repo: Repository, args: ReadonlyArray<string>) {
1172 let rest = args;
1173 let count = Number.POSITIVE_INFINITY;
1174 if (rest[0] === "--count=1") {
1175 count = 1;
1176 rest = rest.slice(1);
1178 const [format, ...patterns] = rest;
1179 if ((format !== REFNAME_FORMAT && format !== UPSTREAM_FORMAT) || patterns.length === 0)
1180 unsure("for-each-ref arguments");
1181​
1182 for (const pattern of patterns) {
1183 if (!/^refs\/(?:heads|remotes)(?:\/|$)/.test(pattern)) unsure("for-each-ref outside branches");
1185 const matchers = patterns.map(refPatternMatcher);
1186 const listed = await Promise.all(patterns.map((pattern) => listBranchRefs(repo, pattern)));
1187 const refs = [...new Set(listed.flat())]
1188 .filter((ref) => matchers.some((matches) => matches(ref)))
1189 .toSorted(byteOrder)
1190 .slice(0, count);
1191​
1192 if (format === REFNAME_FORMAT) return ok(refs.map((ref) => `${ref}\n`).join(""));
1193 const config = await mergedConfig(repo);
1194 let stdout = "";
1195 for (const ref of refs) stdout += `${ref}\0${await upstreamFields(repo, config, ref)}\n`;
1196 return ok(stdout);
1198​
1199// ---------------------------------------------------------------------------
1200// rev-list counts
1202// Ahead/behind counts are a pure function of the two commits. Equal commits
1203// need no git at all; any other pair is answered from what git said last time
1204// for that same pair.
1205​
1206const REV_LIST_MEMO_CAPACITY = 512;
1207const revListMemo = new Map<string, string>();
1208​
1209/** A branch-like name -> object id, only when exactly one ref namespace knows it. */
1210async function resolveRevision(repo: Repository, name: string): Promise<string> {
1211 if (name === "HEAD") {
1212 const head = await readHead(repo);
1213 if (head.ref === null) return head.objectId;
1214 return (await refObjectId(repo, head.ref)) ?? unsure("unborn branch");
1216 // Anything that could be an object id or revision syntax is git's to parse.
1217 if (/^[0-9a-f]{4,64}$/i.test(name) || !isSafeRefName(`refs/heads/${name}`)) unsure("revision");
1218 const candidates = [
1219 `refs/${name}`,
1220 `refs/tags/${name}`,
1221 `refs/heads/${name}`,
1222 `refs/remotes/${name}`,
1223 `refs/remotes/${name}/HEAD`,
1224 ];
1225 for (const dir of new Set([repo.gitDir, repo.commonDir])) {
1226 if (await statOrNull(NodePath.join(dir, ...name.split("/")))) unsure("ambiguous revision");
1228 const found: Array<string> = [];
1229 for (const candidate of candidates) {
1230 const objectId = await refObjectId(repo, candidate).catch(() => unsure("ambiguous revision"));
1231 if (objectId !== null) found.push(objectId);
1233 if (found.length !== 1) unsure("ambiguous or missing revision");
1234 return found[0]!;
1236​
1237interface RevListQuery {
1238 readonly key: string;
1239 readonly left: string;
1240 readonly right: string;
1241 readonly symmetric: boolean;
1243​
1244async function revListQuery(repo: Repository, args: ReadonlyArray<string>): Promise<RevListQuery> {
1245 const symmetric = sameArgs(args.slice(0, 2), ["--left-right", "--count"]) && args.length === 3;
1246 const range = symmetric
1247 ? args[2]!
1248 : sameArgs(args.slice(0, 1), ["--count"]) && args.length === 2
1249 ? args[1]!
1250 : unsure("rev-list arguments");
1251 const separator = symmetric ? "..." : "..";
1252 const at = range.indexOf(separator);
1253 if (
1254 at <= 0 ||
1255 range.indexOf("..", at + separator.length) !== -1 ||
1256 (!symmetric && range.includes("..."))
1258 unsure("rev-list range");
1259 // Grafts, replacements and shallow boundaries change counts without changing the commits.
1260 for (const file of ["shallow", NodePath.join("info", "grafts")]) {
1261 if (await statOrNull(NodePath.join(repo.commonDir, file))) unsure("altered history");
1263 const replaceDir = NodePath.join(repo.commonDir, "refs", "replace");
1264 await assertNoSymlinks(replaceDir);
1265 const replacements = await NodeFSP.readdir(replaceDir).catch(() => []);
1266 const packed = await readPackedRefs(repo.commonDir);
1267 if (replacements.length > 0 || [...packed.keys()].some((ref) => ref.startsWith("refs/replace/")))
1268 unsure("altered history");
1269​
1270 const left = await resolveRevision(repo, range.slice(0, at));
1271 const right = await resolveRevision(repo, range.slice(at + separator.length));
1272 return { key: `${repo.commonDir}\0${separator}\0${left}\0${right}`, left, right, symmetric };
1274​
1275async function answerRevList(repo: Repository, args: ReadonlyArray<string>) {
1276 const query = await revListQuery(repo, args);
1277 if (query.left === query.right) return ok(query.symmetric ? "0\t0\n" : "0\n");
1278 return ok(revListMemo.get(query.key) ?? unsure("not seen before"));
1280​
1281async function answerConfigGet(repo: Repository, key: string) {
1282 const canonical = canonicalConfigKey(key) ?? unsure("config key");
1283 // Only keys that live in repository config in practice.
1284 if (!canonical.startsWith("branch.") && !canonical.startsWith("remote."))
1285 unsure("config section");
1286 const value = lastValue(await mergedConfig(repo), canonical);
1287 return value === undefined ? silentFailure : ok(`${value}\n`);
1289​
1290async function answer(input: GitFastPathInput): Promise<GitFastPathAnswer> {
1291 let args = input.args;
1292 let cwd = input.cwd;
1293 let explicitGitDir: string | null = null;
1294 if (args[0] === "-C" && args.length > 2) {
1295 cwd = NodePath.resolve(cwd, args[1]!);
1296 args = args.slice(2);
1298 if (args[0] === "--git-dir" && args.length > 2) {
1299 explicitGitDir = NodePath.resolve(cwd, args[1]!);
1300 args = args.slice(2);
1302 const [command, ...rest] = args;
1303​
1304 if (command === "rev-parse") {
1305 if (explicitGitDir) unsure("rev-parse with --git-dir");
1306 return answerRevParse(cwd, rest, input.env);
1308 const repoCommand =
1309 command === "symbolic-ref" ||
1310 command === "remote" ||
1311 command === "show-ref" ||
1312 command === "for-each-ref" ||
1313 command === "rev-list" ||
1314 (command === "config" && rest.length === 2 && rest[0] === "--get");
1315 if (!repoCommand) unsure("unsupported command");
1316​
1317 // With --git-dir only commands that ignore the worktree are answered.
1318 const repo = explicitGitDir
1319 ? await openRepository(explicitGitDir, explicitGitDir, false)
1320 : (
1321 await discoverRepository(cwd).catch((error: unknown) =>
1322 // `git config` works outside a repository, from system and global config alone.
1323 error instanceof NotARepository && command === "config"
1324 ? unsure("config outside a repository")
1325 : Promise.reject(error),
1327 ).repo;
1328 await requireGitAgrees(repo, explicitGitDir !== null);
1329 if (explicitGitDir && command === "symbolic-ref" && rest.includes("HEAD"))
1330 unsure("HEAD with --git-dir");
1331​
1332 if (command === "symbolic-ref") return answerSymbolicRef(repo, rest);
1333 if (command === "remote") return answerRemote(repo, rest);
1334 if (command === "config") return answerConfigGet(repo, rest[1]!);
1335 if (command === "for-each-ref") return answerForEachRef(repo, rest);
1336 if (command === "rev-list") return answerRevList(repo, rest);
1337 if (rest.length === 3 && rest[0] === "--verify" && rest[1] === "--quiet") {
1338 return (await refState(repo, rest[2]!)) === "exists" ? ok("") : silentFailure;
1340 return unsure("show-ref arguments");
1342​
1343/**
1344 * Returns git's exact output for a supported read-only command, or `null` when
1345 * the caller has to spawn git. Never throws.
1346 */
1347export async function tryAnswerGitCommand(
1348 input: GitFastPathInput,
1349): Promise<GitFastPathAnswer | null> {
1350 if (!isGitFastPathEnabled() || !isGitFastPathEnabled(input.env ?? {})) return null;
1351 if (hasGitEnvOverride(process.env) || hasGitEnvOverride(input.env)) return null;
1352 if (movesGitOrItsConfig(input.env)) return null;
1353 const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
1354 try {
1355 // Asking for the outer config first proves git runs at all, so a missing git is not papered over.
1356 const result = await withinReadBudget(input.timeoutMs, () =>
1357 withFreshSymlinkChecks(() => getOuterConfig().then(() => answer(input))),
1358 );
1359 return result !== null &&
1360 Math.max(Buffer.byteLength(result.stdout), Buffer.byteLength(result.stderr)) > maxOutputBytes
1361 ? null
1362 : result;
1363 } catch (error) {
1364 return error instanceof NotARepository && !gitMessagesMayBeTranslated(input.env)
1365 ? { exitCode: 128, stdout: "", stderr: error.stderr }
1366 : null;
1369​
1370/**
1371 * Settles with `work`'s result, or with `null` once the caller's budget or
1372 * ANSWER_TIMEOUT_MS runs out, whichever comes first. A rejection of `work`
1373 * before then is passed on.
1374 */
1375export async function withinReadBudget<T>(
1376 timeoutMs: number | null | undefined,
1377 work: () => Promise<T>,
1378): Promise<T | null> {
1379 // No budget at all: nothing may be answered, however fast the reads turn out.
1380 if (typeof timeoutMs === "number" && timeoutMs <= 0) return null;
1381 // A started read cannot be cancelled and holds one of libuv's few threads until
1382 // the disk answers. Starting more while one is stuck would pile them up and
1383 // stall every file operation in the server, so git gets every question instead.
1384 if (abandonedReads > 0) return null;
1385 let timer: NodeJS.Timeout | undefined;
1386 // Reads that take this long mean a stuck disk or share; git gets the question instead.
1387 const timedOut = new Promise<null>((resolve) => {
1388 timer = setTimeout(resolve, Math.min(ANSWER_TIMEOUT_MS, timeoutMs ?? Infinity), null);
1389 });
1390 let settled = false;
1391 const working = work().finally(() => {
1392 settled = true;
1393 });
1394 // When the timer wins, the abandoned attempt still settles; its decline is not an error.
1395 working.catch(() => undefined);
1396 try {
1397 return await Promise.race([working, timedOut]);
1398 } finally {
1399 clearTimeout(timer);
1400 if (!settled) {
1401 abandonedReads++;
1402 void working.then(
1403 () => abandonedReads--,
1404 () => abandonedReads--,
1405 );
1409​
1410/**
1411 * Identifies a command whose answer depends only on commits that can be read
1412 * from the repository files, or `null`. Take it before spawning git and hand it
1413 * to `rememberGitAnswer` with git's output, so the same question is answered
1414 * without a process until one of those commits changes.
1415 */
1416export async function gitAnswerMemoKey(input: GitFastPathInput): Promise<string | null> {
1417 if (!isGitFastPathEnabled() || !isGitFastPathEnabled(input.env ?? {})) return null;
1418 if (hasGitEnvOverride(process.env) || hasGitEnvOverride(input.env)) return null;
1419 const [command, ...rest] = input.args;
1420 if (command !== "rev-list") return null;
1421 try {
1422 // Without a key git still runs, so a stuck disk must not hold up the spawn.
1423 return await withinReadBudget(input.timeoutMs, () =>
1424 withFreshSymlinkChecks(async () => {
1425 const { repo } = await discoverRepository(input.cwd);
1426 await requireGitAgrees(repo, false);
1427 return (await revListQuery(repo, rest)).key;
1428 }),
1429 );
1430 } catch {
1431 return null;
1434​
1435/** Stores git's output for `key` if the commits behind it did not move while git ran. */
1436export async function rememberGitAnswer(
1437 input: GitFastPathInput,
1438 key: string,
1439 stdout: string,
1440): Promise<void> {
1441 if (!/^\d+(?:\t\d+)?\n$/.test(stdout) || (await gitAnswerMemoKey(input)) !== key) return;
1442 if (revListMemo.size >= REV_LIST_MEMO_CAPACITY) revListMemo.clear();
1443 revListMemo.set(key, stdout);