-
Notifications
You must be signed in to change notification settings - Fork 469
Expand file tree
/
Copy pathdashboard-cli.ts
More file actions
270 lines (240 loc) · 8.5 KB
/
Copy pathdashboard-cli.ts
File metadata and controls
270 lines (240 loc) · 8.5 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
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
import { spawn, type SpawnOptions } from "node:child_process";
import { constants as fsConstants } from "node:fs";
import { access } from "node:fs/promises";
import { join } from "node:path";
const INSTALL_COMMAND = "gh extension install github/gh-aw";
const GH_INSTALL_URL = "https://cli.github.com";
type ExecError = Error & {
code?: string | number;
syscall?: string;
path?: string;
stderr?: string;
stdout?: string;
output?: string;
};
type ExecCallback = (err: ExecError | null, stdout: string, stderr: string) => void;
type ExecFileLike = (file: string, args: string[], options: ExecOptions, callback: ExecCallback) => void;
type AccessLike = typeof access;
interface ExecOptions {
env?: NodeJS.ProcessEnv;
cwd?: string;
maxBuffer?: number;
}
interface RunExecOptions {
combineIO?: boolean;
execFileFn?: ExecFileLike;
env?: NodeJS.ProcessEnv;
}
interface RunnerOptions {
getWorkspacePath: () => string;
accessFn?: AccessLike;
execFileFn?: ExecFileLike;
platform?: NodeJS.Platform;
env?: NodeJS.ProcessEnv;
/** Pre-built memoized resolver; when provided, `findDevBinary` is never called directly. */
resolveBin?: () => Promise<string | null>;
}
export interface GhAwStatus {
available: boolean;
source: "dev-binary" | "gh-extension" | "gh-not-found" | "missing" | "error";
version: string;
command: string;
installCommand: string;
installUrl?: string;
message?: string;
}
export type GhAwRunner = ((args: string[]) => Promise<string>) & {
getStatus: () => Promise<GhAwStatus>;
};
function combineOutput(stdout: string, stderr: string): string {
return [stdout, stderr].filter(Boolean).join("\n").trim();
}
function spawnExecFile(file: string, args: string[], options: ExecOptions, callback: ExecCallback): void {
const { env, cwd, maxBuffer = 10 * 1024 * 1024 } = options ?? {};
const spawnOptions: SpawnOptions = { env, cwd, stdio: ["ignore", "pipe", "pipe"], detached: true };
const proc = spawn(file, args, spawnOptions);
const stdoutChunks: Buffer[] = [];
const stderrChunks: Buffer[] = [];
let stdoutLen = 0;
let stderrLen = 0;
let overflowed = false;
proc.stdout?.on("data", (chunk: Buffer) => {
stdoutLen += chunk.length;
if (stdoutLen > maxBuffer) {
overflowed = true;
return;
}
stdoutChunks.push(chunk);
});
proc.stderr?.on("data", (chunk: Buffer) => {
stderrLen += chunk.length;
if (stderrLen > maxBuffer) {
overflowed = true;
return;
}
stderrChunks.push(chunk);
});
proc.on("error", err => callback(err as ExecError, "", ""));
proc.on("close", code => {
const stdout = Buffer.concat(stdoutChunks).toString("utf8");
const stderr = Buffer.concat(stderrChunks).toString("utf8");
if (overflowed) {
const err: ExecError = new Error("stdout/stderr maxBuffer exceeded");
err.code = "ERR_CHILD_PROCESS_STDIO_MAXBUFFER";
callback(err, stdout, stderr);
} else if (code !== 0) {
const err: ExecError = new Error(`Command failed with exit code ${code}`);
err.code = code ?? 1;
callback(err, stdout, stderr);
} else {
callback(null, stdout, stderr);
}
});
}
function execp(bin: string, args: string[], cwd: string, { combineIO = false, execFileFn = spawnExecFile, env = process.env }: RunExecOptions = {}): Promise<string> {
return new Promise((resolve, reject) => {
execFileFn(
bin,
args,
{
cwd,
env: { ...env, CI: "1", NO_COLOR: "1", GH_NO_UPDATE_NOTIFIER: "1" },
maxBuffer: 10 * 1024 * 1024,
},
(err, stdout, stderr) => {
const output = combineOutput(stdout ?? "", stderr ?? "");
if (err) {
reject(Object.assign(err, { stderr: stderr ?? "", stdout: stdout ?? "", output }));
return;
}
resolve(combineIO ? output : stdout);
}
);
});
}
function parseVersionFromOutput(output: string): string {
const trimmed = String(output ?? "").trim();
if (!trimmed) return "";
const match = trimmed.match(/gh(?:-aw| aw) version ([^\r\n]+)/i);
return match?.[1]?.trim() ?? "";
}
function isMissingGh(error: unknown): boolean {
const e = error as ExecError | undefined;
return e?.code === "ENOENT" && e?.syscall === "spawn" && e?.path === "gh";
}
function isMissingGhAwExtension(error: unknown): boolean {
const e = error as ExecError | undefined;
const output = String(e?.output ?? e?.stderr ?? e?.message ?? "");
return /extension not found:\s*aw/i.test(output) || /unknown command ["']aw["'] for ["']gh["']/i.test(output);
}
async function findDevBinary(cwd: string, accessFn: AccessLike = access, platform: NodeJS.Platform = process.platform): Promise<string | null> {
const devBin = join(cwd, platform === "win32" ? "gh-aw.exe" : "gh-aw");
try {
await accessFn(devBin, fsConstants.X_OK);
return devBin;
} catch {
return null;
}
}
export function createGhAwRunner({ getWorkspacePath, accessFn = access, execFileFn = spawnExecFile, platform = process.platform, env = process.env, resolveBin }: RunnerOptions): (args: string[]) => Promise<string> {
// Memoize per cwd so findDevBinary is called at most once per workspace path.
const binCache = new Map<string, Promise<string | null>>();
const _resolveBin =
resolveBin ??
(() => {
const cwd = getWorkspacePath();
if (!binCache.has(cwd)) {
binCache.set(cwd, findDevBinary(cwd, accessFn, platform));
}
return binCache.get(cwd)!;
});
function runExec(bin: string, args: string[], cwd: string, options?: RunExecOptions): Promise<string> {
return execp(bin, args, cwd, { ...options, execFileFn, env });
}
return async function runGhAw(args: string[]): Promise<string> {
const cwd = getWorkspacePath();
const devBin = await _resolveBin();
if (devBin) {
return runExec(devBin, args, cwd);
}
return runExec("gh", ["aw", ...args], cwd);
};
}
export function createGhAwRunnerWithStatus(options: RunnerOptions): GhAwRunner {
// One shared per-cwd memoized resolver so findDevBinary is called at most once,
// even across concurrent runGhAw() calls and getStatus().
const binCache = new Map<string, Promise<string | null>>();
const resolveBin = (): Promise<string | null> => {
const cwd = options.getWorkspacePath();
if (!binCache.has(cwd)) {
binCache.set(cwd, findDevBinary(cwd, options.accessFn ?? access, options.platform ?? process.platform));
}
return binCache.get(cwd)!;
};
const runGhAw = createGhAwRunner({ ...options, resolveBin }) as GhAwRunner;
const getStatus = async (): Promise<GhAwStatus> => {
const cwd = options.getWorkspacePath();
const devBin = await resolveBin();
if (devBin) {
const output = await execp(devBin, ["version"], cwd, {
combineIO: true,
execFileFn: options.execFileFn ?? spawnExecFile,
env: options.env ?? process.env,
});
return {
available: true,
source: "dev-binary",
version: parseVersionFromOutput(output) || "unknown",
command: `${devBin} version`,
installCommand: INSTALL_COMMAND,
};
}
try {
const output = await execp("gh", ["aw", "version"], cwd, {
combineIO: true,
execFileFn: options.execFileFn ?? spawnExecFile,
env: options.env ?? process.env,
});
return {
available: true,
source: "gh-extension",
version: parseVersionFromOutput(output) || "unknown",
command: "gh aw version",
installCommand: INSTALL_COMMAND,
};
} catch (error) {
if (isMissingGh(error)) {
return {
available: false,
source: "gh-not-found",
version: "",
command: "gh aw version",
installCommand: INSTALL_COMMAND,
installUrl: GH_INSTALL_URL,
message: "Install the GitHub CLI to use this dashboard.",
};
}
if (isMissingGhAwExtension(error)) {
return {
available: false,
source: "missing",
version: "",
command: "gh aw version",
installCommand: INSTALL_COMMAND,
message: "gh aw is not installed. Install the GitHub CLI extension to use the dashboard outside a local dev build.",
};
}
const e = error as ExecError | undefined;
return {
available: false,
source: "error",
version: "",
command: "gh aw version",
installCommand: INSTALL_COMMAND,
message: String(e?.output ?? e?.stderr ?? e?.message ?? "Failed to detect gh aw."),
};
}
};
runGhAw.getStatus = getStatus;
return runGhAw;
}