-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathcliUtils.ts
More file actions
243 lines (228 loc) · 6.27 KB
/
cliUtils.ts
File metadata and controls
243 lines (228 loc) · 6.27 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
import { execFile, type ExecFileException } from "node:child_process";
import * as crypto from "node:crypto";
import { createReadStream, type Stats } from "node:fs";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { promisify } from "node:util";
/**
* Custom error thrown when a binary file is locked (typically on Windows).
*/
export class FileLockError extends Error {
constructor(binPath: string) {
super(`Binary is in use: ${binPath}`);
this.name = "WindowsFileLockError";
}
}
/**
* Stat the path or undefined if the path does not exist. Throw if unable to
* stat for a reason other than the path not existing.
*/
export async function stat(binPath: string): Promise<Stats | undefined> {
try {
return await fs.stat(binPath);
} catch (error) {
if ((error as NodeJS.ErrnoException)?.code === "ENOENT") {
return undefined;
}
throw error;
}
}
// util.promisify types are dynamic so there is no concrete type we can import
// and we have to make our own.
type ExecException = ExecFileException & { stdout?: string; stderr?: string };
/**
* Return the version from the binary. Throw if unable to execute the binary or
* find the version for any reason.
*/
export async function version(binPath: string): Promise<string> {
let stdout: string;
try {
const result = await promisify(execFile)(binPath, [
"version",
"--output",
"json",
]);
stdout = result.stdout;
} catch (error) {
// It could be an old version without support for --output.
if ((error as ExecException)?.stderr?.includes("unknown flag: --output")) {
const result = await promisify(execFile)(binPath, ["version"]);
if (result.stdout?.startsWith("Coder")) {
const v = result.stdout.split(" ")[1]?.trim();
if (!v) {
throw new Error(`No version found in output: ${result.stdout}`, {
cause: error,
});
}
return v;
}
}
throw error;
}
const json = JSON.parse(stdout) as { version?: string };
if (!json.version) {
throw new Error("No version found in output: ${stdout}");
}
return json.version;
}
/**
* Run a speed test against the specified workspace and return the raw output.
* Throw if unable to execute the binary.
*/
export async function speedtest(
binPath: string,
globalFlags: string[],
workspaceName: string,
options: { signal?: AbortSignal; duration?: string },
): Promise<string> {
const args = [...globalFlags, "speedtest", workspaceName, "--output", "json"];
if (options.duration) {
args.push("-t", options.duration);
}
const result = await promisify(execFile)(binPath, args, {
signal: options.signal,
});
return result.stdout;
}
export interface RemovalResult {
fileName: string;
error: unknown;
}
/**
* Remove binaries in the same directory as the specified path that have a
* .old-* or .temp-* extension along with signatures (files ending in .asc).
* Return a list of files and the errors trying to remove them, when applicable.
*/
export async function rmOld(binPath: string): Promise<RemovalResult[]> {
const binDir = path.dirname(binPath);
try {
const files = await fs.readdir(binDir);
const results: RemovalResult[] = [];
for (const file of files) {
const fileName = path.basename(file);
if (
fileName.includes(".old-") ||
fileName.includes(".temp-") ||
fileName.endsWith(".asc") ||
fileName.endsWith(".progress.log")
) {
try {
await fs.rm(path.join(binDir, file), { force: true });
results.push({ fileName, error: undefined });
} catch (error) {
results.push({ fileName, error });
}
}
}
return results;
} catch (error) {
// If the directory does not exist, there is nothing to remove.
if ((error as NodeJS.ErrnoException)?.code === "ENOENT") {
return [];
}
throw error;
}
}
/**
* Find all .old-* binaries in the same directory as the given binary path.
* Returns paths sorted by modification time (most recent first).
*/
export async function findOldBinaries(binPath: string): Promise<string[]> {
const binDir = path.dirname(binPath);
const binName = path.basename(binPath);
try {
const files = await fs.readdir(binDir);
const oldBinaries = files
.filter((f) => f.startsWith(binName) && f.includes(".old-"))
.map((f) => path.join(binDir, f));
// Sort by modification time, most recent first
const stats = await Promise.allSettled(
oldBinaries.map(async (f) => ({
path: f,
mtime: (await fs.stat(f)).mtime,
})),
).then((result) =>
result
.filter((promise) => promise.status === "fulfilled")
.map((promise) => promise.value),
);
stats.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
return stats.map((s) => s.path);
} catch (error) {
// If directory doesn't exist, return empty array
if ((error as NodeJS.ErrnoException)?.code === "ENOENT") {
return [];
}
throw error;
}
}
export function maybeWrapFileLockError(
error: unknown,
binPath: string,
): unknown {
const code = (error as NodeJS.ErrnoException).code;
if (code === "EBUSY" || code === "EPERM") {
return new FileLockError(binPath);
}
return error;
}
/**
* Return the etag (sha1) of the path. Throw if unable to hash the file.
*/
export async function eTag(binPath: string): Promise<string> {
const hash = crypto.createHash("sha1");
const stream = createReadStream(binPath);
return new Promise((resolve, reject) => {
stream.on("end", () => {
hash.end();
resolve(hash.digest("hex"));
});
stream.on("error", (err) => {
reject(err);
});
stream.on("data", (chunk) => {
hash.update(chunk);
});
});
}
/**
* Return the binary name for the current platform.
*/
export function name(): string {
const os = goos();
const arch = goarch();
let binName = `coder-${os}-${arch}`;
// Windows binaries have an exe suffix.
if (os === "windows") {
binName += ".exe";
}
return binName;
}
/**
* Returns the Go format for the current platform.
* Coder binaries are created in Go, so we conform to that name structure.
*/
export function goos(): string {
const platform = os.platform();
switch (platform) {
case "win32":
return "windows";
default:
return platform;
}
}
/**
* Return the Go format for the current architecture.
*/
export function goarch(): string {
const arch = os.arch();
switch (arch) {
case "arm":
return "armv7";
case "x64":
return "amd64";
default:
return arch;
}
}