Open History to see the last commit
1import * as Context from "effect/Context";
2import * as Duration from "effect/Duration";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Match from "effect/Match";
6import * as Schedule from "effect/Schedule";
7import * as Semaphore from "effect/Semaphore";
8import { ChildProcessSpawner } from "effect/process";
9
10import {
11 type VcsError,
12 type VcsProcessErrorContext,
13 VcsProcessExitError,
14 type VcsProcessExitFailureKind,
15 VcsProcessMissingExitCodeError,
16 VcsProcessOutputLimitError,
17 VcsProcessOutputReadError,
18 VcsProcessSpawnError,
19 VcsProcessStdinWriteError,
20 VcsProcessTimeoutError,
21} from "@t3tools/contracts";
22import * as HostProcess from "@t3tools/shared/HostProcess";
23
24import * as ProcessRunner from "../processRunner.ts";
25
26export interface VcsProcessInput {
27 readonly operation: string;
28 readonly command: string;
29 readonly args: ReadonlyArray<string>;
30 readonly cwd: string;
31 readonly spawnCwd?: string;
32 readonly stdin?: string;
33 readonly onStdoutChunk?: (chunk: Uint8Array) => void;
34 readonly env?: NodeJS.ProcessEnv;
35 readonly allowNonZeroExit?: boolean;
36 readonly timeoutMs?: number;
37 readonly maxOutputBytes?: number;
38 readonly outputMode?: ProcessRunner.ProcessRunInput["outputMode"];
39 readonly appendTruncationMarker?: boolean;
40}
41
42export interface VcsProcessOutput {
43 readonly exitCode: ChildProcessSpawner.ExitCode;
44 readonly stdout: string;
45 readonly stderr: string;
46 readonly stdoutTruncated: boolean;
47 readonly stderrTruncated: boolean;
48 readonly stdoutInvalidUtf8?: boolean;
49 readonly stderrInvalidUtf8?: boolean;
50}
51
52export class VcsProcess extends Context.Service<
53 VcsProcess,
54 {
55 readonly run: (input: VcsProcessInput) => Effect.Effect<VcsProcessOutput, VcsError>;
56 }
57>()("t3/vcs/VcsProcess") {}
58
59const DEFAULT_TIMEOUT_MS = 30_000;
60const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
61const OUTPUT_TRUNCATED_MARKER = "\n\n[truncated]";
62const VCS_PROCESS_CONCURRENCY = 8;
63const GITHUB_PROCESS_CONCURRENCY = 4;
64
65/** Shown to users when a Git command fails because another process holds the index lock. */
66export const GIT_INDEX_LOCKED_DETAIL =
67 "Git's index is locked. Wait for other Git operations to finish, then try again.";
68
69export const CHECKPOINT_CAPTURE_OPERATION = "GitVcsDriver.checkpoints.captureCheckpoint";
70
71/**
72 * Appends `key=value` to the `GIT_CONFIG_*` entries git reads as command-line
73 * config, so argv stays the same on every platform and nothing is written to
74 * the user's config. The entry goes after any inherited ones. Windows env names
75 * are case-insensitive (elsewhere git reads only `GIT_CONFIG_COUNT`), so there the
76 * count is found regardless of casing, read from
77 * the last spelling (a per-command value spread over process.env), and updated
78 * under every spelling so the child sees it whichever one Node keeps. A count
79 * git would reject is left alone so git still reports it.
80 */
81export const gitConfigEnv = (
82 env: NodeJS.ProcessEnv,
83 key: string,
84 value: string,
85 platform: NodeJS.Platform,
86): NodeJS.ProcessEnv => {
87 const countKeys = Object.keys(env).filter((name) =>
88 platform === "win32" ? name.toUpperCase() === "GIT_CONFIG_COUNT" : name === "GIT_CONFIG_COUNT",
89 );
90 const countKey = countKeys.at(-1) ?? "GIT_CONFIG_COUNT";
91 const inherited = env[countKey];
92 if (
93 inherited !== undefined &&
94 inherited !== "" &&
95 // Git parses the count with strtoul: leading whitespace, an optional sign
96 // (only -0 is non-negative), digits, and nothing after them.
97 /^[ \t\r\n\v\f]*(?:\+?\d+|-0+)/.exec(inherited)?.[0] !== inherited
98 ) {
99 return {};
100 }
101 const count = inherited === undefined || inherited === "" ? 0 : Number.parseInt(inherited, 10);
102 return {
103 ...Object.fromEntries([...countKeys, countKey].map((name) => [name, String(count + 1)])),
104 [`GIT_CONFIG_KEY_${count}`]: key,
105 [`GIT_CONFIG_VALUE_${count}`]: value,
106 };
107};
108
109/**
110 * Git otherwise opens any folder holding `HEAD`, `objects/` and `refs/` as a
111 * bare repository and applies its `config`, including commands such as
112 * `core.fsmonitor`. Files saved in a project or checked out from a clone can
113 * form one, so git started by T3 (or by gh and friends) only opens a bare
114 * repository named with `--git-dir` or `GIT_DIR`. Git before 2.38 ignores it.
115 */
116export const explicitBareRepositoryEnv = (env: NodeJS.ProcessEnv, platform: NodeJS.Platform) =>
117 gitConfigEnv(env, "safe.bareRepository", "explicit", platform);
118
119const classifyNonZeroExit = (command: string, stderr: string): VcsProcessExitFailureKind => {
120 const normalized = stderr.toLowerCase();
121
122 if (
123 normalized.includes("authentication failed") ||
124 normalized.includes("not logged in") ||
125 normalized.includes("gh auth login") ||
126 normalized.includes("glab auth login") ||
127 normalized.includes("az devops login") ||
128 normalized.includes("please run az login") ||
129 normalized.includes("no oauth token") ||
130 normalized.includes("unauthorized")
131 ) {
132 return "authentication";
133 }
134
135 if (
136 normalized.includes("api rate limit") ||
137 normalized.includes("rate limit exceeded") ||
138 normalized.includes("secondary rate limit") ||
139 normalized.includes("too many requests") ||
140 normalized.includes("http 429")
141 ) {
142 return "rate-limited";
143 }
144
145 if (
146 (command === "gh" &&
147 (normalized.includes("could not resolve to a pullrequest") ||
148 normalized.includes("repository.pullrequest") ||
149 normalized.includes("no pull requests found for branch") ||
150 normalized.includes("pull request not found"))) ||
151 (command === "glab" &&
152 (normalized.includes("merge request not found") ||
153 normalized.includes("not found") ||
154 normalized.includes("404"))) ||
155 (command === "az" &&
156 normalized.includes("pull request") &&
157 (normalized.includes("not found") || normalized.includes("does not exist")))
158 ) {
159 return "not-found";
160 }
161
162 return "command-failed";
163};
164
165// Classify before discarding stderr; keep paths and process output out of errors.
166const isTransientGitExit = (stderr: string) =>
167 /unable to create [^\n]*\.lock['"]?: file exists/i.test(stderr) ||
168 /(?:unable to stat|lstat\(|error: open\()[^\n]+: no such file or directory/i.test(stderr);
169
170// On macOS, Git's fsync uses F_FULLFSYNC; writeout-only still uses fsync(2).
171// Network mounts can reject F_FULLFSYNC. Ref writes omit errno, so retry their
172// bare write error too; explicit unrelated errors remain failures.
173// Linux writeout-only only starts writeback, so it must not use this fallback.
174const FULL_FSYNC_ARG = "core.fsyncMethod=fsync";
175const BATCH_FSYNC_ARG = "core.fsyncMethod=batch";
176const WRITEOUT_ONLY_FSYNC_ARG = "core.fsyncMethod=writeout-only";
177const canRetryFullFsync = (stderr: string) =>
178 /fsync error on [^\r\n]+: operation not supported\r?$/im.test(stderr) ||
179 /cannot update ref [^\r\n]+: couldn't write '[^\r\n]+\.lock'\r?$/im.test(stderr);
180
181export const make = Effect.gen(function* () {
182 const processRunner = yield* ProcessRunner.ProcessRunner;
183 const hostPlatform = yield* HostProcess.Platform;
184 const vcsProcesses = yield* Semaphore.make(VCS_PROCESS_CONCURRENCY);
185 const githubProcesses = yield* Semaphore.make(GITHUB_PROCESS_CONCURRENCY);
186
187 const spawn = (input: VcsProcessInput, baseError: VcsProcessErrorContext) =>
188 processRunner
189 .run({
190 command: input.command,
191 args: input.args,
192 cwd: input.cwd,
193 ...(input.spawnCwd !== undefined ? { spawnCwd: input.spawnCwd } : {}),
194 ...(input.stdin !== undefined ? { stdin: input.stdin } : {}),
195 ...(input.onStdoutChunk !== undefined ? { onStdoutChunk: input.onStdoutChunk } : {}),
196 env: {
197 ...input.env,
198 ...explicitBareRepositoryEnv({ ...process.env, ...input.env }, hostPlatform),
199 },
200 timeout: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
201 maxOutputBytes: input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES,
202 outputMode: input.outputMode ?? "truncate",
203 truncatedMarker: input.appendTruncationMarker ? OUTPUT_TRUNCATED_MARKER : "",
204 timeoutBehavior: "error",
205 })
206 .pipe(
207 Effect.mapError(
208 Match.valueTags({
209 ProcessSpawnError: (error) =>
210 VcsProcessSpawnError.fromProcessSpawnError(baseError, error),
211 ProcessOutputLimitError: (error) =>
212 new VcsProcessOutputLimitError({
213 ...baseError,
214 stream: error.stream,
215 maxBytes: error.maxBytes,
216 observedBytes: error.observedBytes,
217 }),
218 ProcessTimeoutError: (error) =>
219 VcsProcessTimeoutError.fromProcessTimeoutError(baseError, error),
220 ProcessStdinError: (error) =>
221 new VcsProcessStdinWriteError({
222 ...baseError,
223 stdinBytes: error.stdinBytes,
224 cause: error.cause,
225 }),
226 ProcessReadError: (error) =>
227 new VcsProcessOutputReadError({
228 ...baseError,
229 stream: error.stream,
230 cause: error.cause,
231 }),
232 }),
233 ),
234 );
235
236 const runUnbounded = Effect.fn("VcsProcess.runUnbounded")(function* (input: VcsProcessInput) {
237 const baseError = {
238 operation: input.operation,
239 command: input.command,
240 cwd: input.cwd,
241 argumentCount: input.args.length,
242 };
243
244 let result = yield* spawn(input, baseError);
245
246 if (
247 hostPlatform === "darwin" &&
248 input.operation === CHECKPOINT_CAPTURE_OPERATION &&
249 !input.allowNonZeroExit &&
250 result.code !== null &&
251 result.code !== 0 &&
252 input.command === "git" &&
253 (input.args.includes(FULL_FSYNC_ARG) || input.args.includes(BATCH_FSYNC_ARG)) &&
254 canRetryFullFsync(result.stderr)
255 ) {
256 result = yield* spawn(
257 {
258 ...input,
259 args: input.args.map((arg) =>
260 arg === FULL_FSYNC_ARG || arg === BATCH_FSYNC_ARG ? WRITEOUT_ONLY_FSYNC_ARG : arg,
261 ),
262 },
263 baseError,
264 );
265 }
266
267 if (result.code === null) {
268 return yield* new VcsProcessMissingExitCodeError(baseError);
269 }
270
271 if (!input.allowNonZeroExit && result.code !== 0) {
272 const failureKind = classifyNonZeroExit(input.command, result.stderr);
273 const error = VcsProcessExitError.fromProcessExit(
274 baseError,
275 {
276 exitCode: result.code,
277 stderr: result.stderr,
278 stderrTruncated: result.stderrTruncated,
279 },
280 failureKind,
281 input.command === "git" &&
282 failureKind === "command-failed" &&
283 isTransientGitExit(result.stderr),
284 );
285 if (
286 input.command === "git" &&
287 /^fatal: unable to create ['"][^\r\n]*[/\\]index\.lock['"]: file exists\.?$/im.test(
288 result.stderr,
289 )
290 ) {
291 return yield* new VcsProcessExitError({
292 ...error,
293 detail: GIT_INDEX_LOCKED_DETAIL,
294 });
295 }
296 return yield* error;
297 }
298
299 return {
300 exitCode: result.code,
301 stdout: result.stdout,
302 stderr: result.stderr,
303 stdoutTruncated: result.stdoutTruncated,
304 stderrTruncated: result.stderrTruncated,
305 stdoutInvalidUtf8: result.stdoutInvalidUtf8 ?? false,
306 stderrInvalidUtf8: result.stderrInvalidUtf8 ?? false,
307 } satisfies VcsProcessOutput;
308 });
309
310 const run = Effect.fn("VcsProcess.run")(function* (input: VcsProcessInput) {
311 const bounded = vcsProcesses.withPermits(1)(runUnbounded(input));
312 if (
313 input.command === "git" &&
314 input.operation === CHECKPOINT_CAPTURE_OPERATION &&
315 input.onStdoutChunk === undefined
316 ) {
317 return yield* bounded.pipe(
318 Effect.tapError((error) =>
319 Effect.logDebug("checkpoint Git command failed", {
320 operation: input.operation,
321 errorTag: error._tag,
322 }),
323 ),
324 Effect.retry({
325 times: 2,
326 while: (error) => error._tag === "VcsProcessExitError" && error.retryable === true,
327 schedule: Schedule.spaced(Duration.millis(75)),
328 }),
329 );
330 }
331 return yield* input.command === "gh" ? githubProcesses.withPermits(1)(bounded) : bounded;
332 });
333
334 return VcsProcess.of({ run });
335});
336
337export const layer = Layer.effect(VcsProcess, make).pipe(Layer.provide(ProcessRunner.layer));