Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import {
3 DEFAULT_SERVER_SETTINGS,
4 GitCommandError,
5 type ServerSettings,
6 type ServerSettingsPatch,
7 VcsProcessExitError,
8 VcsProcessSpawnError,
9} from "@t3tools/contracts";
10import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
11import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
12import * as Context from "effect/Context";
13import * as Effect from "effect/Effect";
14import * as Layer from "effect/Layer";
15import * as ChildProcess from "effect/process/ChildProcess";
16import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
17import * as Ref from "effect/Ref";
18import * as Stream from "effect/Stream";
19
20export interface TestSourceControlHostOptions {
21 readonly settings?: ServerSettings;
22 readonly process?: Partial<SourceControlHost.SourceControlHost["Service"]["process"]>;
23 readonly git?: Partial<SourceControlHost.SourceControlHost["Service"]["git"]>;
24}
25
26export class TestSourceControlHostSettings extends Context.Service<
27 TestSourceControlHostSettings,
28 { readonly update: (patch: ServerSettingsPatch) => Effect.Effect<void> }
29>()("@t3tools/source-control-testing/TestSourceControlHost/TestSourceControlHostSettings") {}
30
31type Git = SourceControlHost.SourceControlHost["Service"]["git"];
32
33const unexpectedGit = (operation: string) => () =>
34 Effect.die(`Unexpected git ${operation} in a test that supplied none.`);
35
36const failingGit: Git = {
37 execute: unexpectedGit("execute"),
38 resolveCommit: unexpectedGit("resolveCommit"),
39 remotes: unexpectedGit("remotes"),
40 readConfigValue: unexpectedGit("readConfigValue"),
41 resolvePrimaryRemoteName: unexpectedGit("resolvePrimaryRemoteName"),
42 ensureRemote: unexpectedGit("ensureRemote"),
43 listLocalBranchNames: unexpectedGit("listLocalBranchNames"),
44 fetchRemoteBranch: unexpectedGit("fetchRemoteBranch"),
45 fetchRemoteTrackingBranch: unexpectedGit("fetchRemoteTrackingBranch"),
46 setBranchUpstream: unexpectedGit("setBranchUpstream"),
47 createBranch: unexpectedGit("createBranch"),
48 writeConfigValue: unexpectedGit("writeConfigValue"),
49 switchRef: unexpectedGit("switchRef"),
50};
51
52export const layer = (
53 options: TestSourceControlHostOptions = {},
54): Layer.Layer<SourceControlHost.SourceControlHost | TestSourceControlHostSettings> =>
55 Layer.effectContext(
56 Effect.gen(function* () {
57 const settings = yield* Ref.make(options.settings ?? DEFAULT_SERVER_SETTINGS);
58 const host = SourceControlHost.SourceControlHost.of({
59 settings: { get: Ref.get(settings) },
60 process: {
61 run:
62 options.process?.run ??
63 ((input) => Effect.die(`Unexpected ${input.command} run in ${input.operation}.`)),
64 },
65 git: { ...failingGit, ...options.git },
66 });
67 return Context.make(SourceControlHost.SourceControlHost, host).pipe(
68 Context.add(TestSourceControlHostSettings, {
69 update: (patch) =>
70 Ref.update(settings, (current) => applyServerSettingsPatch(current, patch)),
71 }),
72 );
73 }),
74 );
75
76export const processOutput = (
77 stdout: string,
78 options?: {
79 readonly stderr?: string;
80 readonly exitCode?: ChildProcessSpawner.ExitCode;
81 },
82): SourceControlHost.SourceControlProcessOutput => ({
83 exitCode: options?.exitCode ?? ChildProcessSpawner.ExitCode(0),
84 stdout,
85 stderr: options?.stderr ?? "",
86 stdoutTruncated: false,
87 stderrTruncated: false,
88});
89
90const TRUNCATION_MARKER = "\n\n[truncated]";
91const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
92
93const collectText = <E>(stream: Stream.Stream<Uint8Array, E>, maxBytes: number, marker: string) =>
94 Stream.runCollect(stream).pipe(
95 Effect.map((chunks) => {
96 const bytes = Buffer.concat(Array.from(chunks));
97 const truncated = bytes.byteLength > maxBytes;
98 const text = bytes.subarray(0, maxBytes).toString("utf8");
99 return { text: truncated ? `${text}${marker}` : text, truncated };
100 }),
101 );
102
103/**
104 * Runs commands for real, the way the server's host does in the parts a forge reads: output is
105 * capped and marked, and a non-zero exit fails unless allowed. It has none of the server's
106 * timeouts, concurrency limits, generic failure classification, or retries.
107 */
108const runForReal = (
109 spawner: ChildProcessSpawner.ChildProcessSpawner["Service"],
110 input: SourceControlHost.SourceControlProcessInput,
111): Effect.Effect<
112 SourceControlHost.SourceControlProcessOutput,
113 VcsProcessSpawnError | VcsProcessExitError
114> => {
115 const context = {
116 operation: input.operation,
117 command: input.command,
118 cwd: input.cwd,
119 argumentCount: input.args.length,
120 };
121 const maxBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
122 const marker = input.appendTruncationMarker ? TRUNCATION_MARKER : "";
123 return Effect.gen(function* () {
124 const child = yield* spawner.spawn(
125 ChildProcess.make(input.command, input.args, {
126 cwd: input.spawnCwd ?? input.cwd,
127 ...(input.env === undefined ? {} : { env: input.env, extendEnv: true }),
128 }),
129 );
130 const [stdout, stderr] = yield* Effect.all(
131 [
132 collectText(
133 input.onStdoutChunk === undefined
134 ? child.stdout
135 : child.stdout.pipe(
136 Stream.tap((chunk) => Effect.sync(() => input.onStdoutChunk?.(chunk))),
137 ),
138 maxBytes,
139 marker,
140 ),
141 collectText(child.stderr, maxBytes, marker),
142 input.stdin === undefined
143 ? Effect.void
144 : Stream.run(Stream.encodeText(Stream.make(input.stdin)), child.stdin),
145 ],
146 { concurrency: "unbounded" },
147 );
148 const exitCode = yield* child.exitCode;
149 if (exitCode !== 0 && !input.allowNonZeroExit) {
150 return yield* VcsProcessExitError.fromProcessExit(
151 context,
152 { exitCode, stderr: stderr.text, stderrTruncated: stderr.truncated },
153 input.classifyFailure?.(stderr.text) ?? "command-failed",
154 input.notFoundDetail === undefined ? undefined : { notFoundDetail: input.notFoundDetail },
155 );
156 }
157 return {
158 exitCode,
159 stdout: stdout.text,
160 stderr: stderr.text,
161 stdoutTruncated: stdout.truncated,
162 stderrTruncated: stderr.truncated,
163 };
164 }).pipe(
165 Effect.scoped,
166 Effect.catchTags({
167 PlatformError: (cause) => Effect.fail(new VcsProcessSpawnError({ ...context, cause })),
168 }),
169 );
170};
171
172/**
173 * `layer` whose `process.run` and `git.execute` spawn real processes, for a forge test that needs
174 * a real repository. Every other git operation still dies unless supplied.
175 */
176export const layerWithRealGit = (
177 options: TestSourceControlHostOptions = {},
178): Layer.Layer<SourceControlHost.SourceControlHost | TestSourceControlHostSettings> =>
179 Layer.unwrap(
180 Effect.gen(function* () {
181 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
182 const run = (input: SourceControlHost.SourceControlProcessInput) =>
183 runForReal(spawner, input);
184 return layer({
185 ...options,
186 process: { run, ...options.process },
187 git: {
188 execute: (input) =>
189 run({ ...input, command: "git" }).pipe(
190 Effect.mapError(
191 (cause) =>
192 new GitCommandError({
193 operation: input.operation,
194 command: "git",
195 cwd: input.cwd,
196 argumentCount: input.args.length,
197 ...(cause._tag === "VcsProcessExitError" ? { exitCode: cause.exitCode } : {}),
198 detail: cause.message,
199 cause,
200 }),
201 ),
202 ),
203 ...options.git,
204 },
205 });
206 }),
207 ).pipe(Layer.provide(NodeServices.layer));