summaryrefslogtreecommitdiff
path: root/lang/gjs/lib/process.ts
diff options
context:
space:
mode:
authorAylur <[email protected]>2024-10-15 01:26:32 +0200
committerAylur <[email protected]>2024-10-15 01:26:32 +0200
commit2f71cd4c08bb4514efe43533e6a5d03535204c29 (patch)
treefc991a12e159ad645187862c90f40731794d6e47 /lang/gjs/lib/process.ts
parent9fab13452a26ed55c01047d4225f699f43bba20d (diff)
refactor lua and gjs lib
Diffstat (limited to 'lang/gjs/lib/process.ts')
-rw-r--r--lang/gjs/lib/process.ts68
1 files changed, 68 insertions, 0 deletions
diff --git a/lang/gjs/lib/process.ts b/lang/gjs/lib/process.ts
new file mode 100644
index 0000000..2f7816b
--- /dev/null
+++ b/lang/gjs/lib/process.ts
@@ -0,0 +1,68 @@
+import Astal from "gi://AstalIO"
+
+type Args = {
+ cmd: string | string[]
+ out?: (stdout: string) => void
+ err?: (stderr: string) => void
+}
+
+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)
+ }
+ })
+ }
+ })
+}