Open History to see the last commit
1/**
2 * Git process helpers - Effect-native git execution with typed errors.
3 *
4 * Centralizes child-process git invocation for server modules. This module
5 * only executes git commands and reports structured failures.
6 *
7 * @module GitServiceLive
8 */
9import { Effect, Layer, Option, Schema, Stream } from "effect";
10import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
11import { GitCommandError } from "../Errors.ts";
12import {
13 ExecuteGitInput,
14 ExecuteGitResult,
15 GitService,
16 GitServiceShape,
17} from "../Services/GitService.ts";
18
19const DEFAULT_TIMEOUT_MS = 30_000;
20const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
21
22function quoteGitCommand(args: ReadonlyArray<string>): string {
23 return `git ${args.join(" ")}`;
24}
25
26function toGitCommandError(
27 input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
28 detail: string,
29) {
30 return (cause: unknown) =>
31 Schema.is(GitCommandError)(cause)
32 ? cause
33 : new GitCommandError({
34 operation: input.operation,
35 command: quoteGitCommand(input.args),
36 cwd: input.cwd,
37 detail: `${cause instanceof Error && cause.message.length > 0 ? cause.message : "Unknown error"} - ${detail}`,
38 ...(cause !== undefined ? { cause } : {}),
39 });
40}
41
42const collectOutput = Effect.fn(function* <E>(
43 input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
44 stream: Stream.Stream<Uint8Array, E>,
45 maxOutputBytes: number,
46): Effect.fn.Return<string, GitCommandError> {
47 const decoder = new TextDecoder();
48 let bytes = 0;
49 let text = "";
50
51 yield* Stream.runForEach(stream, (chunk) =>
52 Effect.gen(function* () {
53 bytes += chunk.byteLength;
54 if (bytes > maxOutputBytes) {
55 return yield* new GitCommandError({
56 operation: input.operation,
57 command: quoteGitCommand(input.args),
58 cwd: input.cwd,
59 detail: `${quoteGitCommand(input.args)} output exceeded ${maxOutputBytes} bytes and was truncated.`,
60 });
61 }
62 text += decoder.decode(chunk, { stream: true });
63 }),
64 ).pipe(Effect.mapError(toGitCommandError(input, "output stream failed.")));
65
66 text += decoder.decode();
67 return text;
68});
69
70const makeGitService = Effect.gen(function* () {
71 const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
72
73 const execute: GitServiceShape["execute"] = Effect.fnUntraced(function* (input) {
74 const commandInput = {
75 ...input,
76 args: [...input.args],
77 } as const;
78 const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
79 const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
80
81 const commandEffect = Effect.gen(function* () {
82 const child = yield* commandSpawner
83 .spawn(
84 ChildProcess.make("git", commandInput.args, {
85 cwd: commandInput.cwd,
86 ...(input.env ? { env: input.env } : {}),
87 }),
88 )
89 .pipe(Effect.mapError(toGitCommandError(commandInput, "failed to spawn.")));
90
91 const [stdout, stderr, exitCode] = yield* Effect.all(
92 [
93 collectOutput(commandInput, child.stdout, maxOutputBytes),
94 collectOutput(commandInput, child.stderr, maxOutputBytes),
95 child.exitCode.pipe(
96 Effect.map((value) => Number(value)),
97 Effect.mapError(toGitCommandError(commandInput, "failed to report exit code.")),
98 ),
99 ],
100 { concurrency: "unbounded" },
101 );
102
103 if (!input.allowNonZeroExit && exitCode !== 0) {
104 const trimmedStderr = stderr.trim();
105 return yield* new GitCommandError({
106 operation: commandInput.operation,
107 command: quoteGitCommand(commandInput.args),
108 cwd: commandInput.cwd,
109 detail:
110 trimmedStderr.length > 0
111 ? `${quoteGitCommand(commandInput.args)} failed: ${trimmedStderr}`
112 : `${quoteGitCommand(commandInput.args)} failed with code ${exitCode}.`,
113 });
114 }
115
116 return { code: exitCode, stdout, stderr } satisfies ExecuteGitResult;
117 });
118
119 return yield* commandEffect.pipe(
120 Effect.scoped,
121 Effect.timeoutOption(timeoutMs),
122 Effect.flatMap((result) =>
123 Option.match(result, {
124 onNone: () =>
125 Effect.fail(
126 new GitCommandError({
127 operation: commandInput.operation,
128 command: quoteGitCommand(commandInput.args),
129 cwd: commandInput.cwd,
130 detail: `${quoteGitCommand(commandInput.args)} timed out.`,
131 }),
132 ),
133 onSome: Effect.succeed,
134 }),
135 ),
136 );
137 });
138
139 return {
140 execute,
141 } satisfies GitServiceShape;
142});
143
144export const GitServiceLive = Layer.effect(GitService, makeGitService);