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