From 58fa1ab9be7ee8fd4a8e96865121a54d613978cc Mon Sep 17 00:00:00 2001 From: Aylur Date: Sat, 25 May 2024 14:44:50 +0200 Subject: separate node and gjs into its own package --- gjs/src/process.ts | 66 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 gjs/src/process.ts (limited to 'gjs/src/process.ts') diff --git a/gjs/src/process.ts b/gjs/src/process.ts new file mode 100644 index 0000000..8934efb --- /dev/null +++ b/gjs/src/process.ts @@ -0,0 +1,66 @@ +import Astal from "gi://Astal" + +type Args = { + cmd: string | string[], + out?: (stdout: string) => Out, + err?: (stderr: string) => Err, +} + +function args(argsOrCmd: Args | string | string[], onOut: O, onErr: E) { + const params = Array.isArray(argsOrCmd) || typeof argsOrCmd === "string" + return { + cmd: params ? argsOrCmd : argsOrCmd.cmd, + err: params ? onErr : argsOrCmd.err || onErr, + out: params ? onOut : argsOrCmd.out || onOut, + } +} + +export function subprocess(args: Args): Astal.Process +export function subprocess( + cmd: string | string[], + onOut?: (stdout: string) => void, + onErr?: (stderr: string) => void, +): Astal.Process +export function subprocess( + argsOrCmd: Args | string | string[], + onOut: (stdout: string) => void = print, + onErr: (stderr: string) => void = console.log, +) { + const { cmd, err, out } = args(argsOrCmd, onOut, onErr) + const proc = Array.isArray(cmd) + ? Astal.Process.subprocessv(cmd) + : Astal.Process.subprocess(cmd) + + proc.connect("stdout", (_, stdout: string) => out(stdout)) + proc.connect("stderr", (_, stderr: string) => err(stderr)) + return proc +} + +export function exec( + args: Args +): Out | Err +export function exec( + cmd: string | string[], + onOut?: (stdout: string) => Out, + onErr?: (stderr: string) => Err, +): Out | Err +export function exec( + argsOrCmd: Args | string | string[], + onOut: (stdout: string) => Out = out => out as Out, + onErr: (stderr: string) => Err = out => out as Err, +): Out | Err { + const { cmd, err, out } = args(argsOrCmd, onOut, onErr) + return Array.isArray(cmd) + ? out(Astal.Process.execv(cmd)!) as Out + : err(Astal.Process.exec(cmd)!) as Err +} + +export function execAsync(cmd: string | string[]): Promise { + const proc = Array.isArray(cmd) + ? Astal.Process.exec_asyncv(cmd) + : Astal.Process.exec_async(cmd) + return new Promise((resolve, reject) => { + proc.connect("stdout", (_, out: string) => resolve(out)) + proc.connect("stderr", (_, err: string) => reject(err)) + }) +} -- cgit v1.2.3