summaryrefslogtreecommitdiff
path: root/u/process/run.ts
blob: 7a74c3ef050fe7186eb02d23f55ea5d6d844221d (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
65
66
67
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,
      });
    })
    .map((tCmd) =>
      Either.fromFailableAsync<Error, Deno.CommandOutput>(() =>
        tCmd.get().output(),
      ),
    )
    .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): IEither<Error, string> => {
              const { code, stdoutText, stderrText } = decodedOutput;
              if (stderrText) {
                tEitherOut.trace
                  .addTrace(LogLevel.DEBUG)
                  .trace(`stderr: ${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();