-
-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathhelpers.js
More file actions
261 lines (236 loc) · 6.85 KB
/
helpers.js
File metadata and controls
261 lines (236 loc) · 6.85 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
const util = require("node:util");
const exec = util.promisify(require("node:child_process").exec);
const fs = require("node:fs/promises");
const path = require("node:path");
/*
* This file uses JsDoc syntax.
* Documentation for type helpers like @param: https://jsdoc.app/tags-type
* Documentation for types in braces:
* https://github.com/google/closure-compiler/wiki/Types-in-the-Closure-Type-System
*/
/**
* As for jest.test but skips running if the ALLOW_UNSAFE env var is set.
* @param {string} name
* @param {function({ fail: function }): void | function(): PromiseLike.<unknown>} fn
* @param {number} [timeout]
*/
function testUnsafe(name, fn, timeout) {
if (process.env.ALLOW_UNSAFE) {
return test(name, fn, timeout);
} else {
return test.skip(name, fn, timeout);
}
}
/**
* Global timeout in ms, set by TIMEOUT env var.
* This is used in TestContext to limit `exec`.
* @returns {number}
*/
function getTimeout() {
// parseInt returns NaN if it fails
// TIMEOUT <= 0 will be ignored too
return Number.parseInt(process.env.TIMEOUT) || 25000;
}
/**
* The version string for system emacs, e.g. "30.0.50".
* You can compare lexicographically, e.g. if ((await emacsVersion()) > "27") { ... }
* @returns {Promise.<string>} emacs version string.
*/
async function emacsVersion() {
const text = await exec("emacs --version");
const version = text.stdout.match("Emacs ([^ ]+)")?.[1];
if (!version) {
throw Error("Couldn't extract Emacs version. Text was:\n" + text);
}
return version;
}
/**
* Remove all ansi codes from string.
* @returns {string}
*/
async function stripAnsi(s) {
return s.replace(/\u001b[^m]*?m/g, "");
}
/** Provides transformations on output of node.exec(). */
class CommandOutput {
constructor(output, cwd) {
this.stderr = output.stderr;
this.stdout = output.stdout;
this.cwd = cwd;
this.cwdAbsolute = path.resolve(cwd || ".");
}
/**
* Both stdout and stderr concatenated as a string.
* @returns {string}
*/
combined() {
return this.stdout + "\n" + this.stderr;
}
/**
* Output as a plain object.
* @returns {{ sdout: string, stderr: string }}
*/
raw() {
return {
stderr: this.stderr,
stdout: this.stdout,
};
}
/**
* Output with no color.
* @returns {{ sdout: string, stderr: string }}
*/
rawNoColor() {
return {
stderr: stripAnsi(this.stderr),
stdout: stripAnsi(this.stdout),
};
}
/**
* Attempt to make `s` safe for snapshotting by replacing local data.
* @param {string} s
* @returns {string}
*/
sanitizeString(s) {
let working = s;
// windows paths
if (this.cwdAbsolute.startsWith(":", 1)) {
// cwdAbsolute is a windows path e.g. C:\foo\bar
// Eask outputs windows paths like d:/a/cli/Eask
let cwdTranslated = this.cwdAbsolute.replaceAll("\\", "/");
// lowercase the drive letter
cwdTranslated =
cwdTranslated[0].toLowerCase() + cwdTranslated.substring(1);
working = working.replaceAll(cwdTranslated, "~");
}
// replace absolute path
working = working.replaceAll(this.cwdAbsolute, "~");
// replace relative path
working = working.replaceAll(this.cwd, "~");
return working;
}
/**
* Create a copy of this object with output safe for snapshotting.
* @param {...function(string):string[]} sanitizeFns functions to apply to the output.
* These apply after the default sanitize functions.
* @returns {CommandOutput}
*/
sanitized(...sanitizeFns) {
let sani = (s) =>
sanitizeFns.reduce((s1, f) => f.call({}, s1), this.sanitizeString(s));
return new CommandOutput({
stdout: sani(this.stdout),
stderr: sani(this.stderr),
}, this.cwd,);
}
}
class TestContext {
/**
* @param {string} cwd Current Working Directory, used for all commands.
*/
constructor(cwd) {
this.cwd = cwd;
this.easkCommand = process.env.EASK_COMMAND || "eask";
this.controller = new AbortController();
}
/**
* Runs command with "eask" prefix.
* See https://nodejs.org/docs/latest-v20.x/api/child_process.html#child_processexeccommand-options-callback
* for additional config options.
* @param {string} command
* @param {any} config
* @returns {Promise.<CommandOutput>}
*/
runEask(command, config, safe = false) {
return this.run(this.easkCommand + " " + command, config, safe);
}
/**
* Runs a command in the context's directory.
* Prefer using Node APIs for commands like copy, delete etc.
* See https://nodejs.org/docs/latest-v20.x/api/child_process.html#child_processexeccommand-options-callback
* for additional config options.
* @param {string} command
* @param {any} config
* @returns {Promise.<CommandOutput>}
*/
run(command, config, safe = false) {
return exec(command, {
cwd: this.cwd,
signal: this.controller.signal,
timeout: getTimeout(),
...config,
})
.then((obj) => {
if (process.env.DEBUG) {
console.log(
`--> ${command}\n` +
(obj.stdout ? obj.stdout : "") +
(obj.stderr ? obj.stderr : ""),
);
}
return new CommandOutput(obj, this.cwd);
})
.catch((err) => {
if (safe)
return this.errorToCommandOutput(err);
if (!err.code)
err.message += "\nexec: TIMEOUT";
throw err;
});
}
/**
* Abort any processes created using `runEask` or `run`.
* @returns {void}
*/
cleanUp() {
this.controller.abort();
}
/**
* Test if a file exists using a path relative to this context's directory.
* Throws if file does not exist, to provide an explanation when used with
* expect().
* @param {string} relativePath
* @returns {Promise.<boolean>}
*/
fileExists(relativePath) {
const fullPath = path.resolve(this.cwd, relativePath);
return fs
.stat(fullPath)
.then((_) => true)
.catch((_) => {
throw Error("File does not exist, or is not readable: " + fullPath);
});
}
/**
* Get file contents as a string, relative to the context's directory.
* @param {string} relativePath
* @returns {Promise.<string>}
*/
fileContents(relativePath) {
const fullPath = path.resolve(this.cwd, relativePath);
return fs.readFile(fullPath);
}
/**
* Removes files or directories under the context's directory.
* Errors are silently ignored.
* @param {...string} filesOrDirs files or directories to remove
* @returns {Promise.<void>}
*/
async removeFiles(...filesOrDirs) {
for (let f of filesOrDirs) {
await fs
.rm(path.join(this.cwd, f), { recursive: true, retries: 1 })
.catch(() => {}); // ignore "does not exist errors"
}
}
errorToCommandOutput(e) {
return new CommandOutput(e, this.cwd);
}
}
module.exports = {
testUnsafe,
emacsVersion,
TestContext,
getTimeout,
CommandOutput,
};