-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathutils.ts
More file actions
62 lines (55 loc) · 1.91 KB
/
utils.ts
File metadata and controls
62 lines (55 loc) · 1.91 KB
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
import {execFile as execFileCb} from "node:child_process";
export type Result = {stdout: string; stderr: string};
export class SubprocessError extends Error {
stdout: string;
stderr: string;
output: string;
exitCode: number | null;
constructor(message: string, stdout = "", stderr = "", exitCode: number | null = null) {
super(message);
this.name = "SubprocessError";
this.stdout = stdout;
this.stderr = stderr;
this.output = [stderr, stdout].filter(Boolean).join("\n");
this.exitCode = exitCode;
}
}
type ExecOptions = {
shell?: boolean;
stdin?: {string: string};
cwd?: string;
env?: NodeJS.ProcessEnv;
};
export const reNewline = /\r?\n/;
export function tomlGetString(content: string, section: string, key: string): string | undefined {
let inSection = false;
const keyRe = new RegExp(`^${key}\\s*=\\s*["']([^"']+)["']`);
for (const line of content.split(reNewline)) {
const trimmed = line.trim();
if (!trimmed || trimmed[0] === "#") continue;
if (trimmed[0] === "[") {
const m = /^\[([^[\]]+)\]/.exec(trimmed);
inSection = m ? m[1].trim() === section : false;
continue;
}
if (inSection) {
const m = keyRe.exec(trimmed);
if (m) return m[1];
}
}
return undefined;
}
export function exec(file: string, args: readonly string[], options?: ExecOptions): Promise<Result> {
return new Promise((resolve, reject) => {
const child = execFileCb(file, args as string[], {encoding: "utf8", shell: options?.shell, windowsHide: true, cwd: options?.cwd, env: options?.env}, (error, stdout, stderr) => {
if (error) {
reject(new SubprocessError(error.message.split(/\r?\n/)[0], stdout, stderr, typeof error.code === "number" ? error.code : null));
} else {
resolve({stdout: stdout.trimEnd(), stderr: stderr.trimEnd()});
}
});
if (options?.stdin) {
child.stdin!.end(options.stdin.string);
}
});
}