-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.ts
103 lines (80 loc) · 2.09 KB
/
mod.ts
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import { green, red } from "./deps.ts";
export interface Options {
debug?: boolean;
flags?: Record<
string,
string | number | boolean | Array<string | number | boolean>
>;
json?: boolean;
}
export async function gh(cmd: string, options: Options = {}): Promise<unknown> {
const exec = await execPath();
if (options.debug) {
console.log(`${green("exec:")} ${exec}`);
}
const flags = Object.entries((options.flags || {})).map(([key, val]) => {
let flag = key;
if (!flag.startsWith("-") || !flag.startsWith("--")) {
flag = flag.length === 1 ? `-${flag}` : `--${flag}`;
}
if (typeof val === "boolean") {
return flag;
}
if (Array.isArray(val)) {
return `${flag} ${val.join(" ")}`;
}
return `${flag} ${val.toString()}`;
});
if (options.debug) {
console.log(
`${green("exec:")} gh ${[exec, ...cmd.split(" "), ...flags].join(" ")}`,
);
}
const p = Deno.run({
cmd: [exec, ...cmd.split(" "), ...flags],
stdout: "piped",
stderr: "piped",
env: {
PAGER: "",
},
});
const [status, stdout, stderr] = await Promise.all([
p.status(),
p.output(),
p.stderrOutput(),
]);
if (options.debug) {
console.log(`${green("status:")} ${status.code}`);
}
if (status.code !== 0) {
const error = new TextDecoder().decode(stderr);
if (options.debug) {
console.error(`${red("error:")} ${error}`);
}
throw new Error(error);
}
if (!options.json) {
return stdout;
}
if (options.debug) {
console.log(`${green("exec:")} attempting to parse JSON`);
}
return JSON.parse(new TextDecoder().decode(stdout));
}
async function execPath(): Promise<string> {
const p = Deno.run({
cmd: ["which", "gh"],
stdout: "piped",
stderr: "piped",
});
const [status, stdout, stderr] = await Promise.all([
p.status(),
p.output(),
p.stderrOutput(),
]);
if (status.code !== 0) {
const error = new TextDecoder().decode(stderr);
throw new Error(`Failed to find gh executable: ${error}`);
}
return new TextDecoder().decode(stdout).trimEnd();
}