import { Either, type IEither, type ITraceable, LogLevel, TraceUtil, } from "@emprespresso/pengueno"; type Command = string[] | string; type CommandOutputDecoded = { code: number; stdoutText: string; stderrText: string; }; export class ProcessError extends Error {} export const getStdout = ( c: ITraceable, options: Deno.CommandOptions = {}, ): Promise> => c.bimap(TraceUtil.withFunctionTrace(getStdout)) .map(({ item: cmd, trace }) => { trace.trace(`:> im gonna run this command! ${cmd}`); const [exec, ...args] = (typeof cmd === "string") ? cmd.split(" ") : cmd; return new Deno.Command(exec, { args, stdout: "piped", stderr: "piped", ...options, }).output(); }) .map(({ item: p }) => Either.fromFailableAsync(p) ) .map( TraceUtil.promiseify(({ item: eitherOutput, trace }) => eitherOutput.flatMap(({ code, stderr, stdout }) => Either .fromFailable(() => { const stdoutText = new TextDecoder().decode(stdout); const stderrText = new TextDecoder().decode(stderr); return { code, stdoutText, stderrText }; }) .mapLeft((e) => { trace.addTrace(LogLevel.ERROR).trace(`o.o wat ${e}`); return new ProcessError(`${e}`); }) .flatMap((decodedOutput): Either => { const { code, stdoutText, stderrText } = decodedOutput; trace.addTrace(LogLevel.DEBUG).trace( `stderr hehehe ${stderrText}`, ); if (code !== 0) { const msg = `i weceived an exit code of ${code} i wanna zewoooo :<`; trace.addTrace(LogLevel.ERROR).trace(msg); return Either.left(new ProcessError(msg)); } return Either.right(stdoutText); }) ) ), ).item;