diff options
author | kotontrion <[email protected]> | 2024-10-29 13:50:41 +0100 |
---|---|---|
committer | kotontrion <[email protected]> | 2024-10-29 13:50:41 +0100 |
commit | 57f20666e716fde56579b8aa638eed1264f793de (patch) | |
tree | 59b2ebbd770c80049cea4df82109d28f617675fe /lang/gjs/src/process.ts | |
parent | 4d9ae88b0bab75779876d465f986791d052414ca (diff) | |
parent | 7e484188e7492ac7945c854bcc3f26cec1863c91 (diff) |
Merge branch 'main' into feat/cava
Diffstat (limited to 'lang/gjs/src/process.ts')
-rw-r--r-- | lang/gjs/src/process.ts | 70 |
1 files changed, 70 insertions, 0 deletions
diff --git a/lang/gjs/src/process.ts b/lang/gjs/src/process.ts new file mode 100644 index 0000000..c41adc1 --- /dev/null +++ b/lang/gjs/src/process.ts @@ -0,0 +1,70 @@ +import Astal from "gi://AstalIO" + +type Args = { + cmd: string | string[] + out?: (stdout: string) => void + err?: (stderr: string) => void +} + +export const { Process } = Astal + +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 = printerr, +) { + const args = Array.isArray(argsOrCmd) || typeof argsOrCmd === "string" + const { cmd, err, out } = { + cmd: args ? argsOrCmd : argsOrCmd.cmd, + err: args ? onErr : argsOrCmd.err || onErr, + out: args ? onOut : argsOrCmd.out || onOut, + } + + 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 +} + +/** @throws {GLib.Error} Throws stderr */ +export function exec(cmd: string | string[]) { + return Array.isArray(cmd) + ? Astal.Process.execv(cmd) + : Astal.Process.exec(cmd) +} + +export function execAsync(cmd: string | string[]): Promise<string> { + return new Promise((resolve, reject) => { + if (Array.isArray(cmd)) { + Astal.Process.exec_asyncv(cmd, (_, res) => { + try { + resolve(Astal.Process.exec_asyncv_finish(res)) + } + catch (error) { + reject(error) + } + }) + } + else { + Astal.Process.exec_async(cmd, (_, res) => { + try { + resolve(Astal.Process.exec_finish(res)) + } + catch (error) { + reject(error) + } + }) + } + }) +} |