Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2import * as Deferred from "effect/Deferred";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as PlatformError from "effect/PlatformError";
6import * as Sink from "effect/Sink";
7import * as Stream from "effect/Stream";
8import { ChildProcessSpawner } from "effect/process";
9import * as HostProcess from "@t3tools/shared/HostProcess";
10import { SpawnExecutableResolution } from "@t3tools/shared/shell";
11
12import * as ProcessRunner from "./processRunner.ts";
13
14type ChildProcessCommand = {
15 readonly command: string;
16 readonly args: ReadonlyArray<string>;
17 readonly options: {
18 readonly shell?: boolean | string;
19 };
20};
21
22function asChildProcessCommand(command: unknown): ChildProcessCommand {
23 return command as ChildProcessCommand;
24}
25
26function makeHandle(input: {
27 readonly stdout?: string | Stream.Stream<Uint8Array>;
28 readonly stderr?: string | Stream.Stream<Uint8Array>;
29 readonly code?: number;
30 readonly stdin?: ChildProcessSpawner.ChildProcessHandle["stdin"];
31 readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
32}) {
33 return ChildProcessSpawner.makeHandle({
34 pid: ChildProcessSpawner.ProcessId(1),
35 exitCode: input.exitCode ?? Effect.succeed(ChildProcessSpawner.ExitCode(input.code ?? 0)),
36 isRunning: Effect.succeed(false),
37 kill: () => Effect.void,
38 unref: Effect.succeed(Effect.void),
39 stdin: input.stdin ?? Sink.drain,
40 stdout:
41 typeof input.stdout === "string"
42 ? Stream.encodeText(Stream.make(input.stdout))
43 : (input.stdout ?? Stream.empty),
44 stderr:
45 typeof input.stderr === "string"
46 ? Stream.encodeText(Stream.make(input.stderr))
47 : (input.stderr ?? Stream.empty),
48 all: Stream.empty,
49 getInputFd: () => Sink.drain,
50 getOutputFd: () => Stream.empty,
51 });
52}
53
54function makeSpawner(
55 f: (
56 command: ChildProcessCommand,
57 ) => Effect.Effect<ChildProcessSpawner.ChildProcessHandle, PlatformError.PlatformError>,
58) {
59 return ChildProcessSpawner.make((command) => f(asChildProcessCommand(command)));
60}
61
62const runWith =
63 (spawner: ChildProcessSpawner.ChildProcessSpawner["Service"]) =>
64 (input: ProcessRunner.ProcessRunInput) =>
65 Effect.service(ProcessRunner.ProcessRunner).pipe(
66 Effect.flatMap((runner) =>
67 runner.run({
68 ...input,
69 }),
70 ),
71 Effect.provide(
72 ProcessRunner.layer.pipe(
73 Layer.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner)),
74 ),
75 ),
76 );
77
78describe("runProcess", () => {
79 it.effect("resolves and escapes Windows command shims before spawning", () => {
80 const spawner = makeSpawner((command) =>
81 Effect.sync(() => {
82 expect(command.command).toBe(
83 [
84 '^"C:\\Users\\tester\\AppData\\Roaming\\npm\\az.cmd^"',
85 '^"repos^"',
86 '^"pr^"',
87 '^"list^"',
88 '^"--source-branch^"',
89 '^"feature^ ^&^ release^"',
90 ].join(" "),
91 );
92 expect(command.args).toEqual([]);
93 expect(command.options.shell).toBe(true);
94 return makeHandle({ stdout: "[]" });
95 }),
96 );
97
98 return runWith(spawner)({
99 command: "az",
100 args: ["repos", "pr", "list", "--source-branch", "feature & release"],
101 env: { AZURE_CONFIG_DIR: "C:\\Users\\tester\\.azure" },
102 }).pipe(
103 Effect.provideService(HostProcess.Platform, "win32"),
104 Effect.provideService(HostProcess.Environment, {
105 PATH: "C:\\Users\\tester\\AppData\\Roaming\\npm",
106 PATHEXT: ".COM;.EXE;.BAT;.CMD",
107 }),
108 Effect.provideService(SpawnExecutableResolution, (_command, _platform, env) =>
109 env.PATH === "C:\\Users\\tester\\AppData\\Roaming\\npm" &&
110 env.AZURE_CONFIG_DIR === "C:\\Users\\tester\\.azure"
111 ? "C:\\Users\\tester\\AppData\\Roaming\\npm\\az.cmd"
112 : undefined,
113 ),
114 Effect.map((result) => {
115 expect(result.stdout).toBe("[]");
116 }),
117 );
118 });
119
120 it.effect("types spawn failures that the platform spawner throws synchronously", () =>
121 Effect.gen(function* () {
122 // File-valued PATH entries make spawn throw ENOTDIR synchronously, arriving through Effect.callback as a defect.
123 const defect = Object.assign(new Error("spawn jj ENOTDIR"), { code: "ENOTDIR" });
124 const spawner = makeSpawner(() =>
125 Effect.callback<never, never>(() => {
126 throw defect;
127 }),
128 );
129
130 const error = yield* runWith(spawner)({
131 command: "jj",
132 args: ["--version"],
133 cwd: "/repo",
134 }).pipe(Effect.flip);
135
136 expect(error._tag).toBe("ProcessSpawnError");
137 if (error._tag !== "ProcessSpawnError") {
138 return expect.fail("Expected ProcessSpawnError");
139 }
140 expect(error).toMatchObject({ command: "jj", argumentCount: 1, cwd: "/repo" });
141 expect(error.cause).toBe(defect);
142 }),
143 );
144
145 it.effect("fails when output exceeds max buffer in default mode", () =>
146 Effect.gen(function* () {
147 const spawner = makeSpawner(() => Effect.succeed(makeHandle({ stdout: "x".repeat(2048) })));
148
149 const error = yield* runWith(spawner)({
150 command: "fake",
151 args: ["stdout-bytes", "2048"],
152 maxOutputBytes: 128,
153 }).pipe(Effect.flip);
154
155 expect(error._tag).toBe("ProcessOutputLimitError");
156 if (error._tag !== "ProcessOutputLimitError") {
157 return expect.fail("Expected ProcessOutputLimitError");
158 }
159 expect(error).toMatchObject({
160 stream: "stdout",
161 maxBytes: 128,
162 observedBytes: 2048,
163 });
164 expect(error.message).toBe(
165 "Process 'fake' stdout produced 2048 bytes, exceeding the 128 byte limit",
166 );
167 }),
168 );
169
170 it.effect("accepts output at the byte limit followed by an empty chunk", () =>
171 Effect.gen(function* () {
172 const output = new TextEncoder().encode("exactly");
173 const spawner = makeSpawner(() =>
174 Effect.succeed(
175 makeHandle({
176 stdout: Stream.make(output, new Uint8Array()),
177 }),
178 ),
179 );
180
181 const result = yield* runWith(spawner)({
182 command: "fake",
183 args: ["exact-limit"],
184 maxOutputBytes: output.byteLength,
185 });
186
187 expect(result.stdout).toBe("exactly");
188 }),
189 );
190
191 it.effect("fails fast on output limit before timeout for long-running output", () =>
192 Effect.gen(function* () {
193 const textChunk = "x".repeat(64);
194 const spawner = makeSpawner(() =>
195 Effect.succeed(
196 makeHandle({
197 stdout: Stream.fromIterable(Array.from({ length: 10 }, () => textChunk)).pipe(
198 Stream.encodeText,
199 ),
200 exitCode: Effect.never,
201 }),
202 ),
203 );
204
205 const error = yield* runWith(spawner)({
206 command: "fake",
207 args: ["spam-stdout"],
208 maxOutputBytes: 128,
209 timeout: "2 seconds",
210 }).pipe(Effect.flip);
211
212 expect(error).toBeInstanceOf(ProcessRunner.ProcessOutputLimitError);
213 }),
214 );
215
216 it.effect("truncates output when outputMode is truncate", () =>
217 Effect.gen(function* () {
218 const spawner = makeSpawner(() => Effect.succeed(makeHandle({ stdout: "x".repeat(2048) })));
219
220 const result = yield* runWith(spawner)({
221 command: "fake",
222 args: ["stdout-bytes", "2048"],
223 maxOutputBytes: 128,
224 outputMode: "truncate",
225 });
226
227 expect(result.code).toBe(0);
228 expect(result.stdout.length).toBeLessThanOrEqual(128);
229 expect(result.stdoutTruncated).toBe(true);
230 expect(result.stderrTruncated).toBe(false);
231 }),
232 );
233
234 it.effect("writes stdin before waiting for exit", () =>
235 Effect.gen(function* () {
236 const stdinWritten = yield* Deferred.make<void>();
237 const decoder = new TextDecoder();
238 const spawner = makeSpawner(() =>
239 Effect.succeed(
240 makeHandle({
241 stdout: "stdin payload",
242 stdin: Sink.forEach((chunk: Uint8Array) => {
243 const text = decoder.decode(chunk, { stream: true });
244 return text.includes("stdin payload")
245 ? Deferred.succeed(stdinWritten, undefined)
246 : Effect.void;
247 }),
248 exitCode: Deferred.await(stdinWritten).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
249 }),
250 ),
251 );
252
253 const result = yield* runWith(spawner)({
254 command: "fake",
255 args: ["stdin-echo"],
256 stdin: "stdin payload",
257 });
258
259 expect(result.stdout).toBe("stdin payload");
260 expect(result.code).toBe(0);
261 }),
262 );
263});
264
265describe("isWindowsCommandNotFound", () => {
266 it.effect("matches the localized German cmd.exe error text", () =>
267 Effect.gen(function* () {
268 const isCommandNotFound = yield* ProcessRunner.isWindowsCommandNotFound(
269 1,
270 "wird nicht als interner oder externer Befehl, betriebsfahiges Programm oder Batch-Datei erkannt",
271 ).pipe(Effect.provideService(HostProcess.Platform, "win32"));
272 expect(isCommandNotFound).toBe(true);
273 }),
274 );
275});