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