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