Open History to see the last commit
1import * as Effect from "effect/Effect"
2import * as ChildProcess from "effect/process/ChildProcess"
3import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"
4import * as Stream from "effect/Stream"
5import { NpmPromoteError } from "./NpmPromoteError.ts"
6
7/**
8 * Runs a command and returns its stdout. A non-zero exit code fails with the
9 * command's combined output.
10 */
11export const run = (
12 command: string,
13 args: ReadonlyArray<string>,
14 options?: { readonly cwd?: string | undefined }
15): Effect.Effect<string, NpmPromoteError, ChildProcessSpawner.ChildProcessSpawner> => {
16 const display = `${command} ${args.join(" ")}`
17 return Effect.gen(function*() {
18 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner
19 const handle = yield* spawner.spawn(ChildProcess.make(command, args, { cwd: options?.cwd }))
20 const [stdout, stderr, exitCode] = yield* Effect.all([
21 Stream.mkString(Stream.decodeText(handle.stdout)),
22 Stream.mkString(Stream.decodeText(handle.stderr)),
23 handle.exitCode
24 ], { concurrency: "unbounded" })
25 if (exitCode !== ChildProcessSpawner.ExitCode(0)) {
26 return yield* new NpmPromoteError({ message: `Command failed (${display}):\n${stderr}\n${stdout}`.trim() })
27 }
28 return stdout
29 }).pipe(
30 Effect.scoped,
31 Effect.catchTag(
32 "PlatformError",
33 (cause) => Effect.fail(new NpmPromoteError({ message: `Could not run command (${display})`, cause }))
34 )
35 )
36}