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