This repository has been archived by the owner on Nov 24, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathcommandLineUtil.js
52 lines (43 loc) · 1.65 KB
/
commandLineUtil.js
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
import Gio from 'gi://Gio';
/**
* From https://gjs.guide/guides/gio/subprocesses.html
*/
/* Gio.Subprocess */
Gio._promisify(Gio.Subprocess.prototype, 'communicate_utf8_async');
/**
* Execute a command asynchronously and return the output from `stdout` on
* success or throw an error with output from `stderr` on failure.
*
* If given, @input will be passed to `stdin` and @cancellable can be used to
* stop the process before it finishes.
*
* @param {string[]} argv - a list of string arguments
* @param {string} [input] - Input to write to `stdin` or %null to ignore
* @param {Gio.Cancellable} [cancellable] - optional cancellable object
* @returns {Promise<string>} - The process output
*/
export async function execCommunicateAsync(argv, input = null, cancellable = null) {
let cancelId = 0;
let flags = Gio.SubprocessFlags.STDOUT_PIPE |
Gio.SubprocessFlags.STDERR_PIPE;
if (input !== null)
flags |= Gio.SubprocessFlags.STDIN_PIPE;
const proc = new Gio.Subprocess({ argv, flags });
proc.init(cancellable);
if (cancellable instanceof Gio.Cancellable)
cancelId = cancellable.connect(() => proc.force_exit());
try {
const [stdout, stderr] = await proc.communicate_utf8_async(input, null);
const status = proc.get_exit_status();
if (status !== 0) {
throw new Gio.IOErrorEnum({
code: Gio.IOErrorEnum.FAILED,
message: stderr ? stderr.trim() : `Command '${argv}' failed with exit code ${status}`,
});
}
return stdout.trim();
} finally {
if (cancelId > 0)
cancellable.disconnect(cancelId);
}
}