Open History to see the last commit
1/**
2 * Contains props, error tags, and the live service for executing commands.
3 * Shared between the `Build`, `Dev`, and `Exec` resources.
4 */
5
6import * as Context from "effect/Context";
7import * as Data from "effect/Data";
8import * as Effect from "effect/Effect";
9import { flow } from "effect/Function";
10import * as Layer from "effect/Layer";
11import * as Path from "effect/Path";
12import type { PlatformError, SystemError } from "effect/PlatformError";
13import { BadArgument } from "effect/PlatformError";
14import * as Predicate from "effect/Predicate";
15import * as Redacted from "effect/Redacted";
16import type * as Scope from "effect/Scope";
17import * as Sink from "effect/Sink";
18import * as Stream from "effect/Stream";
19import * as ChildProcess from "effect/unstable/process/ChildProcess";
20import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
21import type { ScopedPlanStatusSession } from "../Cli/Cli.ts";
22import { isNonInteractive } from "../Util/interactive.ts";
23
24/**
25 * Base properties for a command resource.
26 */
27export interface CommandProps {
28 /**
29 * The command to run.
30 */
31 command: string;
32 /**
33 * Working directory for the command. Defaults to `process.cwd()`.
34 */
35 cwd?: string;
36 /**
37 * If set to true, runs the command inside of a shell, defaulting to /bin/sh on UNIX systems and cmd.exe on Windows.
38 * It is generally discouraged to use this option, as it can lead to security vulnerabilities and is not portable.
39 * If set to a string, runs the command inside of the specified shell.
40 * @default false
41 */
42 shell?: string | boolean;
43 /**
44 * Extra environment variables passed to the command on top of `process.env`.
45 */
46 env?: Record<string, string | Redacted.Redacted<string>>;
47}
48
49export class CommandExecutor extends Context.Service<
50 CommandExecutor,
51 {
52 /**
53 * Spawns a command, returning the child process handle.
54 */
55 readonly spawn: (
56 props: CommandProps,
57 ) => Effect.Effect<
58 ChildProcessSpawner.ChildProcessHandle,
59 CommandError,
60 Scope.Scope
61 >;
62 /**
63 * Executes a command, returning the exit code, stdout, and stderr.
64 * Throws a {@link CommandError} if the command exits with a non-zero exit code.
65 */
66 readonly run: (
67 props: CommandProps,
68 session: ScopedPlanStatusSession,
69 ) => Effect.Effect<
70 { exitCode: number; stdout: string; stderr: string },
71 CommandError
72 >;
73 }
74>()("alchemy/Command/CommandExecutor") {}
75
76/**
77 * Extends Effect's `PlatformError` to include the command that failed and some command-specific error reasons.
78 */
79export class CommandError extends Data.TaggedError("CommandError")<{
80 command: string;
81 reason: SystemError | BadArgument | UnexpectedExit | OutputNotFound;
82 cause?: unknown;
83}> {
84 constructor({
85 command,
86 reason,
87 }: {
88 command: string;
89 reason: CommandError["reason"];
90 }) {
91 if ("cause" in reason) {
92 super({ command, reason, cause: reason.cause });
93 } else {
94 super({ command, reason });
95 }
96 }
97
98 override get message() {
99 return `Failed to execute command "${this.command}": ${this.reason.message}`;
100 }
101}
102
103export const isCommandError = (error: unknown): error is CommandError =>
104 Predicate.isTagged(error, "CommandError");
105
106/**
107 * Represents when a command exits unexpectedly.
108 */
109export class UnexpectedExit extends Data.TaggedError("UnexpectedExit")<{
110 exitCode: number;
111 stderr: string;
112}> {
113 override get message() {
114 return `The command exited with code ${this.exitCode}. Standard error output: ${this.stderr}`;
115 }
116}
117
118/**
119 * Represents when the output directory does not exist.
120 */
121export class OutputNotFound extends Data.TaggedError("OutputNotFound")<{
122 outdir: string;
123}> {
124 override get message() {
125 return `The output directory "${this.outdir}" does not exist.`;
126 }
127}
128
129export const CommandExecutorLive = () =>
130 Layer.effect(
131 CommandExecutor,
132 Effect.gen(function* () {
133 const path = yield* Path.Path;
134 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
135
136 /** Parses a command string into a binary and arguments, unless {@link CommandProps.shell} is true. */
137 const parseCommand = (
138 props: CommandProps,
139 ): Effect.Effect<{ bin: string; args: string[] }, CommandError> => {
140 if (props.shell) {
141 return Effect.succeed({ bin: props.command, args: [] });
142 }
143 const [bin, ...args] = props.command
144 .split(/(\s+)/)
145 .filter((part) => !!part.trim());
146 if (!bin) {
147 return Effect.fail(
148 new CommandError({
149 command: props.command,
150 reason: new BadArgument({
151 module: "Command",
152 method: "parseCommand",
153 description: "Command is empty",
154 }),
155 }),
156 );
157 }
158 return Effect.succeed({ bin, args });
159 };
160
161 /** Spawns a command, returning the child process handle. */
162 const spawn = (props: CommandProps) =>
163 parseCommand(props).pipe(
164 Effect.flatMap(({ bin, args }) =>
165 spawner.spawn(
166 ChildProcess.make(bin, args, {
167 cwd: path.resolve(props.cwd ?? process.cwd()),
168 shell: props.shell ?? false,
169 env: Object.fromEntries(
170 Object.entries(props.env ?? {}).map(([k, v]) => [
171 k,
172 Redacted.isRedacted(v) ? Redacted.value(v) : v,
173 ]),
174 ),
175 extendEnv: true,
176 stdin: isNonInteractive() ? "ignore" : "inherit",
177 stdout: "pipe",
178 stderr: "pipe",
179 detached: false,
180 }),
181 ),
182 ),
183 mapError(props.command),
184 );
185
186 /** Collects the output of a stream, tapping each line to a sink. */
187 const collect = (
188 stream: Stream.Stream<Uint8Array, PlatformError>,
189 tap: (chunk: string) => Effect.Effect<void>,
190 ) =>
191 stream.pipe(
192 Stream.decodeText,
193 Stream.tapSink(
194 Sink.make<string>()(
195 flow(Stream.splitLines, Stream.runForEach(tap)),
196 ),
197 ),
198 Stream.mkString,
199 );
200
201 /** Maps a PlatformError to a CommandError. */
202 const mapError = (command: string) =>
203 Effect.mapError((error: PlatformError | CommandError) =>
204 error._tag === "CommandError"
205 ? error
206 : new CommandError({
207 command,
208 reason: error.reason,
209 }),
210 );
211
212 return CommandExecutor.of({
213 spawn,
214 /** Executes a command, returning the exit code, stdout, and stderr. */
215 run: (props: CommandProps, session: ScopedPlanStatusSession) =>
216 spawn(props).pipe(
217 Effect.flatMap((child) =>
218 Effect.all(
219 {
220 exitCode: child.exitCode,
221 stdout: collect(child.stdout, session.note),
222 stderr: collect(child.stderr, session.note),
223 },
224 { concurrency: "unbounded" },
225 ).pipe(mapError(props.command)),
226 ),
227 Effect.tap(({ exitCode, stderr }) =>
228 exitCode !== 0
229 ? Effect.fail(
230 new CommandError({
231 command: props.command,
232 reason: new UnexpectedExit({
233 exitCode,
234 stderr,
235 }),
236 }),
237 )
238 : Effect.void,
239 ),
240 Effect.scoped,
241 ),
242 });
243 }),
244 );