summaryrefslogtreecommitdiff
path: root/u/process/run.ts
blob: e3c4c3d5ef883368f1bdc9d15aeb3d390bcceaf8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import {
    Either,
    type IEither,
    type ITraceable,
    LogLevel,
    type LogTraceSupplier,
    TraceUtil,
} from '@emprespresso/pengueno';
import { promisify } from 'node:util';
import { exec as execCallback } from 'node:child_process';
const exec = promisify(execCallback);

export type Command = string[] | string;
export type StdStreams = { stdout: string; stderr: string };

export const getStdout = (
    c: ITraceable<Command, LogTraceSupplier>,
    options: { env?: Record<string, string>; clearEnv?: boolean } = {},
): Promise<IEither<Error, string>> =>
    c
        .bimap(TraceUtil.withFunctionTrace(getStdout))
        .bimap((tCmd) => {
            const cmd = tCmd.get();
            tCmd.trace.trace(`Command = ${cmd} :> im gonna run this command! `);

            const _exec = typeof cmd === 'string' ? cmd : cmd.join(' ');
            const env = options.clearEnv ? options.env : { ...process.env, ...options.env };

            const p: Promise<IEither<Error, StdStreams>> = Either.fromFailableAsync(exec(_exec, { env }));
            return [p, `Command = ${_exec}`];
        })
        .map(
            TraceUtil.promiseify(
                (tEitherProcess): IEither<Error, string> =>
                    tEitherProcess.get().fold(({ isLeft, value }) => {
                        if (isLeft) {
                            return Either.left(value);
                        }
                        if (value.stderr) {
                            tEitherProcess.trace.addTrace(LogLevel.DEBUG).trace(`StdErr = ${value.stderr}`);
                        }
                        return Either.right(value.stdout);
                    }),
            ),
        )
        .get();