summaryrefslogtreecommitdiff
path: root/lang/gjs/src/process.ts
blob: dd4a6ae06de993bd7869e6e402fcaa4ebdfe67a5 (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
68
import Astal from "gi://AstalIO"

type Args = {
    cmd: string | string[]
    out?: (stdout: string) => void
    err?: (stderr: string) => void
}

export type Process = Astal.Process
export const Process = Astal.Process

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)
                }
            })
        }
    })
}