summaryrefslogtreecommitdiff
path: root/u/process/run.ts
blob: 495443835ee9bd676024687e6aa96e2e01702cb6 (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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import {
  Either,
  type IEither,
  type ITraceable,
  LogLevel,
  TraceUtil,
} from "@emprespresso/pengueno";

export type Command = string[] | string;
type CommandOutputDecoded = {
  code: number;
  stdoutText: string;
  stderrText: string;
};

export const getStdout = <Trace>(
  c: ITraceable<Command, Trace>,
  options: Deno.CommandOptions = {},
): Promise<IEither<Error, string>> =>
  c.bimap(TraceUtil.withFunctionTrace(getStdout))
    .map((tCmd) => {
      const cmd = tCmd.get();
      tCmd.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((tOut) =>
      Either.fromFailableAsync<Error, Deno.CommandOutput>(tOut.get())
    )
    .map(
      TraceUtil.promiseify((tEitherOut) =>
        tEitherOut.get().flatMap(({ code, stderr, stdout }) =>
          Either
            .fromFailable<Error, CommandOutputDecoded>(() => {
              const stdoutText = new TextDecoder().decode(stdout);
              const stderrText = new TextDecoder().decode(stderr);
              return { code, stdoutText, stderrText };
            })
            .mapLeft((e) => {
              tEitherOut.trace.addTrace(LogLevel.ERROR).trace(`o.o wat ${e}`);
              return new Error(`${e}`);
            })
            .flatMap((decodedOutput): Either<Error, string> => {
              const { code, stdoutText, stderrText } = decodedOutput;
              tEitherOut.trace.addTrace(LogLevel.DEBUG).trace(
                `stderr hehehe ${stderrText}`,
              );
              if (code !== 0) {
                const msg =
                  `i weceived an exit code of ${code} i wanna zewoooo :<`;
                tEitherOut.trace.addTrace(LogLevel.ERROR).trace(msg);
                return Either.left(new Error(msg));
              }
              return Either.right(stdoutText);
            })
        )
      ),
    )
    .get();