codemod 2.0.0-alpha.2 → 2.0.0-alpha.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/testing/index.mjs CHANGED
@@ -8,631 +8,638 @@
8
8
  // (`codemod workflow harness`), in the engine's own sandboxed runtime.
9
9
  // Failures are `AssertionError`s with `actual` and `expected`, which every
10
10
  // runner knows how to show.
11
-
11
+ /**
12
+ * Run workflows from any test runner and compare the files they leave.
13
+ *
14
+ * ```ts
15
+ * import { test } from "node:test";
16
+ * import { runWorkflow, fixtures, assertTree } from "codemod/testing";
17
+ *
18
+ * for (const fixture of fixtures("tests")) {
19
+ * test(fixture.name, async () => {
20
+ * const run = await runWorkflow("workflow.ts", { target: fixture.input, params: fixture.params });
21
+ * assertTree(run, fixture.expected);
22
+ * });
23
+ * }
24
+ * ```
25
+ *
26
+ * Each run copies its target into a temporary directory first, so fixtures
27
+ * are never changed. Paths are resolved against the current directory;
28
+ * pass `new URL("./workflow.ts", import.meta.url)` to resolve against the
29
+ * test file instead.
30
+ *
31
+ * TypeScript workflows run in the test's own process, so breakpoints,
32
+ * coverage and mocks work in the workflow's code. `host: "quickjs"` runs them
33
+ * with the codemod CLI instead, in the sandboxed runtime `codemod run` uses.
34
+ *
35
+ * @module
36
+ */
12
37
  import { spawn } from "node:child_process";
13
38
  import { AssertionError } from "node:assert";
14
- import {
15
- cpSync,
16
- existsSync,
17
- mkdirSync,
18
- mkdtempSync,
19
- readdirSync,
20
- readFileSync,
21
- rmSync,
22
- statSync,
23
- writeFileSync,
24
- } from "node:fs";
39
+ import { cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync, } from "node:fs";
25
40
  import { createRequire } from "node:module";
26
41
  import { tmpdir } from "node:os";
27
42
  import { basename, dirname, extname, join, relative, resolve, sep } from "node:path";
28
43
  import { fileURLToPath } from "node:url";
29
-
30
44
  const require = createRequire(import.meta.url);
31
-
32
45
  // ------------------------------------------------------------ running ---
33
-
34
46
  /**
35
- * Run a workflow on a copy of `target` and return what happened.
36
- * Resolves for every outcome (check `run.status`); rejects only when the
37
- * workflow cannot be run at all (it does not build, the CLI is missing) or
38
- * an `until` / `given` label matches no step.
47
+ * Run a workflow (a workflow file, a package directory, or the workflow
48
+ * module itself, with `options.path`) on a copy of `options.target`. Resolves for every outcome; check `run.status`, or use
49
+ * `assertTree`, which fails when the run did not succeed. Rejects when the
50
+ * workflow cannot run at all (for example it does not build), or when an
51
+ * `until` or `given` label matches no step.
39
52
  */
40
53
  export async function runWorkflow(workflow, options) {
41
- if (!options || options.target === undefined) {
42
- throw new TypeError("runWorkflow(workflow, { target }): target is required");
43
- }
44
- const dir = mkdtempSync(join(tmpdir(), "codemod-test-"));
45
- try {
46
- materialize(options.target, dir);
47
- const before = readTree(dir);
48
- const result = (await inProcess(workflow, options))
49
- ? await runInProcess(workflow, options, dir)
50
- : await harness(
51
- {
52
- workflow: toPath(workflow),
53
- workflowName: options.workflowName,
54
+ if (!options || options.target === undefined) {
55
+ throw new TypeError("runWorkflow(workflow, { target }): target is required");
56
+ }
57
+ const dir = mkdtempSync(join(tmpdir(), "codemod-test-"));
58
+ try {
59
+ materialize(options.target, dir);
60
+ const before = readTree(dir);
61
+ const result = (await inProcess(workflow, options))
62
+ ? await runInProcess(workflow, options, dir)
63
+ : await harness({
64
+ workflow: toPath(workflow),
65
+ workflowName: options.workflowName,
66
+ target: dir,
67
+ params: options.params ?? {},
68
+ until: options.until,
69
+ given: options.given ?? {},
70
+ approve: options.approve ?? true,
71
+ capabilities: options.capabilities ?? [],
72
+ }, options.signal);
73
+ const files = readTree(dir);
74
+ checkLabels(result, options);
75
+ return new Run(result, dir, before, files);
76
+ }
77
+ finally {
78
+ if (!options.keep)
79
+ rmSync(dir, { recursive: true, force: true });
80
+ }
81
+ }
82
+ /** Whether this run goes to `codemod/host` rather than the CLI. */
83
+ async function inProcess(workflow, options) {
84
+ const host = options.host ?? "node";
85
+ if (host === "quickjs")
86
+ return false;
87
+ if (host !== "node")
88
+ throw new TypeError(`host must be "node" or "quickjs", not ${host}`);
89
+ if (!isPath(workflow))
90
+ return true;
91
+ const { addon } = await import("../runtime/addon.mjs");
92
+ let path;
93
+ try {
94
+ path = addon().resolveWorkflow(toPath(workflow), options.workflowName ?? null);
95
+ }
96
+ catch (error) {
97
+ // Without the addon, fall back to the CLI unless Node was asked for.
98
+ if (options.host === undefined && /native addon/.test(messageOf(error)))
99
+ return false;
100
+ throw new Error(`cannot run ${toPath(workflow)}: ${messageOf(error)}`);
101
+ }
102
+ // YAML workflows run in the engine.
103
+ return /\.m?[jt]s$/.test(path);
104
+ }
105
+ async function runInProcess(workflow, options, dir) {
106
+ const { runWorkflow: run } = await import("../runtime/host.mjs");
107
+ let report;
108
+ try {
109
+ // The host calls the module's default export with the run's input.
110
+ report = await run(isPath(workflow) ? toPath(workflow) : workflow, {
54
111
  target: dir,
55
112
  params: options.params ?? {},
56
113
  until: options.until,
57
- given: options.given ?? {},
114
+ given: options.until !== undefined || options.given ? (options.given ?? {}) : undefined,
58
115
  approve: options.approve ?? true,
59
116
  capabilities: options.capabilities ?? [],
60
- },
61
- options.signal,
62
- );
63
- const files = readTree(dir);
64
- checkLabels(result, options);
65
- return new WorkflowRun(result, dir, before, files);
66
- } finally {
67
- if (!options.keep) rmSync(dir, { recursive: true, force: true });
68
- }
69
- }
70
-
71
- /** Whether this run goes to `codemod/host` rather than the CLI. */
72
- async function inProcess(workflow, options) {
73
- const host = options.host ?? "node";
74
- if (host === "quickjs") return false;
75
- if (host !== "node") throw new TypeError(`host must be "node" or "quickjs", not ${host}`);
76
- if (workflow && typeof workflow === "object" && !isUrl(workflow)) return true;
77
- const { addon } = await import("../runtime/addon.mjs");
78
- let path;
79
- try {
80
- path = addon().resolveWorkflow(toPath(workflow), options.workflowName ?? null);
81
- } catch (error) {
82
- // Without the addon, fall back to the CLI unless Node was asked for.
83
- if (options.host === undefined && /native addon/.test(error.message)) return false;
84
- throw new Error(`cannot run ${toPath(workflow)}: ${error.message}`);
85
- }
86
- // YAML workflows run in the engine.
87
- return /\.m?[jt]s$/.test(path);
88
- }
89
-
90
- async function runInProcess(workflow, options, dir) {
91
- const { runWorkflow: run } = await import("../runtime/host.mjs");
92
- let report;
93
- try {
94
- report = await run(isPath(workflow) ? toPath(workflow) : workflow, {
95
- target: dir,
96
- params: options.params ?? {},
97
- until: options.until,
98
- given: options.until !== undefined || options.given ? (options.given ?? {}) : undefined,
99
- approve: options.approve ?? true,
100
- capabilities: options.capabilities ?? [],
101
- workflowName: options.workflowName,
102
- path: options.path === undefined ? undefined : toPath(options.path),
103
- signal: options.signal,
104
- captureConsole: true,
105
- });
106
- } catch (error) {
107
- throw new Error(`cannot run ${describeWorkflow(workflow, options)}: ${error.message}`, {
108
- cause: error,
109
- });
110
- }
111
- return { ...report, logs: logsOf(report.events) };
117
+ workflowName: options.workflowName,
118
+ path: options.path === undefined ? undefined : toPath(options.path),
119
+ signal: options.signal,
120
+ captureConsole: true,
121
+ });
122
+ }
123
+ catch (error) {
124
+ throw new Error(`cannot run ${describeWorkflow(workflow, options)}: ${messageOf(error)}`, {
125
+ cause: error,
126
+ });
127
+ }
128
+ return { ...report, steps: [...report.steps], logs: logsOf(report.events) };
112
129
  }
113
-
114
130
  function describeWorkflow(workflow, options) {
115
- if (isPath(workflow)) return toPath(workflow);
116
- return options.path === undefined ? "the workflow" : toPath(options.path);
131
+ if (isPath(workflow))
132
+ return toPath(workflow);
133
+ return options.path === undefined ? "the workflow" : toPath(options.path);
134
+ }
135
+ function messageOf(error) {
136
+ return error instanceof Error ? error.message : String(error);
117
137
  }
118
-
119
138
  /** Log lines from the engine's events, with the label of the step that wrote each. */
120
139
  function logsOf(events) {
121
- const labels = new Map();
122
- const lines = [];
123
- for (const event of events) {
124
- if (event.event === "step_started") labels.set(event.position, event.label);
125
- else if (event.event === "step_log") {
126
- lines.push({ step: labels.get(event.position) ?? null, line: event.line });
127
- } else if (event.event === "run_log") lines.push({ step: null, line: event.line });
128
- }
129
- return lines;
130
- }
131
-
132
- class WorkflowRun {
133
- constructor(result, dir, before, files) {
134
- this.status = result.status;
135
- this.output = result.output;
136
- this.error = result.error;
137
- this.awaiting = result.awaiting;
138
- this.stoppedAt = result.stoppedAt;
139
- this.dir = dir;
140
- this.files = Object.freeze(files);
141
- this.changes = Object.freeze(changes(before, files));
142
- this.steps = Object.freeze(result.steps.map((step) => Object.freeze(step)));
143
- this.logs = Object.freeze(result.logs.map((log) => Object.freeze(log)));
144
- this.metrics = result.metrics;
145
- Object.defineProperty(this, "before", { value: before, enumerable: false });
146
- }
147
-
148
- /** Whether the run finished, or stopped at its `until` step. */
149
- get ok() {
150
- return this.status === "succeeded" || this.status === "stopped";
151
- }
152
-
153
- /** The first step with this label. Throws when there is none. */
154
- step(label) {
155
- const found = this.steps.find((step) => step.label === label);
156
- if (!found) {
157
- throw new Error(
158
- `no step is labeled ${JSON.stringify(label)}; the run's steps are: ${labels(this.steps)}`,
159
- );
140
+ const labels = new Map();
141
+ const lines = [];
142
+ for (const event of events) {
143
+ if (event.event === "step_started")
144
+ labels.set(event.position, String(event.label));
145
+ else if (event.event === "step_log") {
146
+ lines.push({ step: labels.get(event.position) ?? null, line: String(event.line) });
147
+ }
148
+ else if (event.event === "run_log")
149
+ lines.push({ step: null, line: String(event.line) });
160
150
  }
161
- return found;
162
- }
163
-
164
- /** A unified diff of every file the run changed. */
165
- diff() {
166
- return Object.keys(this.changes)
167
- .sort()
168
- .map((path) => unifiedDiff(path, this.before[path] ?? "", this.changes[path] ?? ""))
169
- .join("");
170
- }
171
- }
172
-
151
+ return lines;
152
+ }
153
+ class Run {
154
+ status;
155
+ output;
156
+ error;
157
+ awaiting;
158
+ stoppedAt;
159
+ dir;
160
+ files;
161
+ changes;
162
+ steps;
163
+ logs;
164
+ constructor(result, dir, before, files) {
165
+ this.status = result.status;
166
+ this.output = result.output;
167
+ this.error = result.error;
168
+ this.awaiting = result.awaiting;
169
+ this.stoppedAt = result.stoppedAt;
170
+ this.dir = dir;
171
+ this.files = Object.freeze(files);
172
+ this.changes = Object.freeze(changes(before, files));
173
+ this.steps = Object.freeze(result.steps.map((step) => Object.freeze(step)));
174
+ this.logs = Object.freeze(result.logs.map((log) => Object.freeze(log)));
175
+ Object.defineProperty(this, "before", { value: before, enumerable: false });
176
+ }
177
+ /** Whether the run finished, or stopped at its `until` step. */
178
+ get ok() {
179
+ return this.status === "succeeded" || this.status === "stopped";
180
+ }
181
+ /** The first step with this label. Throws when there is none. */
182
+ step(label) {
183
+ const found = this.steps.find((step) => step.label === label);
184
+ if (!found) {
185
+ throw new Error(`no step is labeled ${JSON.stringify(label)}; the run's steps are: ${labels(this.steps)}`);
186
+ }
187
+ return found;
188
+ }
189
+ /** A unified diff of every file the run changed. */
190
+ diff() {
191
+ return Object.keys(this.changes)
192
+ .sort()
193
+ .map((path) => unifiedDiff(path, this.before[path] ?? "", this.changes[path] ?? ""))
194
+ .join("");
195
+ }
196
+ }
173
197
  function checkLabels(result, options) {
174
- const ran = result.steps;
175
- if (options.until !== undefined && result.status === "succeeded") {
176
- throw new Error(
177
- `until: no step is labeled ${JSON.stringify(options.until)}; the run's steps are: ${labels(ran)}`,
178
- );
179
- }
180
- if (result.status !== "succeeded") return;
181
- const unused = Object.keys(options.given ?? {}).filter(
182
- (label) => !ran.some((step) => step.given && step.label === label),
183
- );
184
- if (unused.length) {
185
- throw new Error(
186
- `given: no step is labeled ${unused.map((l) => JSON.stringify(l)).join(", ")}; the run's steps are: ${labels(ran)}`,
187
- );
188
- }
189
- }
190
-
198
+ const ran = result.steps;
199
+ if (options.until !== undefined && result.status === "succeeded") {
200
+ throw new Error(`until: no step is labeled ${JSON.stringify(options.until)}; the run's steps are: ${labels(ran)}`);
201
+ }
202
+ if (result.status !== "succeeded")
203
+ return;
204
+ const unused = Object.keys(options.given ?? {}).filter((label) => !ran.some((step) => step.given && step.label === label));
205
+ if (unused.length) {
206
+ throw new Error(`given: no step is labeled ${unused.map((l) => JSON.stringify(l)).join(", ")}; the run's steps are: ${labels(ran)}`);
207
+ }
208
+ }
191
209
  function labels(steps) {
192
- return steps.length ? steps.map((step) => JSON.stringify(step.label)).join(", ") : "(none)";
210
+ return steps.length ? steps.map((step) => JSON.stringify(step.label)).join(", ") : "(none)";
193
211
  }
194
-
195
212
  function harness(spec, signal) {
196
- const binary = codemodBinary();
197
- return new Promise((resolvePromise, reject) => {
198
- const child = spawn(binary, ["workflow", "harness"], {
199
- stdio: ["pipe", "pipe", "pipe"],
200
- env: { ...process.env, NO_COLOR: "1", DISABLE_ANALYTICS: "true" },
201
- signal,
202
- });
203
- let stdout = "";
204
- let stderr = "";
205
- child.stdout.setEncoding("utf8").on("data", (chunk) => (stdout += chunk));
206
- child.stderr.setEncoding("utf8").on("data", (chunk) => (stderr += chunk));
207
- child.on("error", (error) => {
208
- // Aborting stops the CLI; the run then ended as canceled, as it does
209
- // when Node.js runs the workflow.
210
- if (signal?.aborted) {
211
- resolvePromise({
212
- status: "canceled",
213
- output: null,
214
- error: null,
215
- awaiting: null,
216
- stoppedAt: null,
217
- steps: [],
218
- logs: [],
219
- metrics: {},
213
+ const binary = codemodBinary();
214
+ return new Promise((resolvePromise, reject) => {
215
+ const child = spawn(binary, ["workflow", "harness"], {
216
+ stdio: ["pipe", "pipe", "pipe"],
217
+ env: { ...process.env, NO_COLOR: "1", DISABLE_ANALYTICS: "true" },
218
+ // Stopping a process takes a real signal.
219
+ signal: signal,
220
220
  });
221
- } else {
222
- reject(error);
223
- }
224
- });
225
- child.on("close", (code) => {
226
- const line = stdout.trim().split("\n").pop();
227
- if (code === 0 && line) {
228
- try {
229
- resolvePromise(JSON.parse(line));
230
- return;
231
- } catch {
232
- // fall through to the error below
233
- }
234
- }
235
- const detail = (stderr.trim() || stdout.trim() || `exit code ${code}`).replace(
236
- /^Error:\s*/,
237
- "",
238
- );
239
- reject(new Error(`cannot run ${spec.workflow}: ${detail}`));
221
+ let stdout = "";
222
+ let stderr = "";
223
+ child.stdout.setEncoding("utf8").on("data", (chunk) => (stdout += chunk));
224
+ child.stderr.setEncoding("utf8").on("data", (chunk) => (stderr += chunk));
225
+ child.on("error", (error) => {
226
+ // Aborting stops the CLI; the run then ended as canceled, as it does
227
+ // when Node.js runs the workflow.
228
+ if (signal?.aborted) {
229
+ resolvePromise({
230
+ status: "canceled",
231
+ output: null,
232
+ error: null,
233
+ awaiting: null,
234
+ stoppedAt: null,
235
+ steps: [],
236
+ logs: [],
237
+ });
238
+ }
239
+ else {
240
+ reject(error);
241
+ }
242
+ });
243
+ child.on("close", (code) => {
244
+ const line = stdout.trim().split("\n").pop();
245
+ if (code === 0 && line) {
246
+ try {
247
+ resolvePromise(JSON.parse(line));
248
+ return;
249
+ }
250
+ catch {
251
+ // fall through to the error below
252
+ }
253
+ }
254
+ const detail = (stderr.trim() || stdout.trim() || `exit code ${code}`).replace(/^Error:\s*/, "");
255
+ reject(new Error(`cannot run ${spec.workflow}: ${detail}`));
256
+ });
257
+ child.stdin.end(JSON.stringify(spec));
240
258
  });
241
- child.stdin.end(JSON.stringify(spec));
242
- });
243
259
  }
244
-
245
260
  let binaryPath;
246
-
247
261
  /** The codemod CLI binary: `CODEMOD_BINARY`, or the one this package installed. */
248
262
  function codemodBinary() {
249
- if (process.env.CODEMOD_BINARY) return process.env.CODEMOD_BINARY;
250
- if (binaryPath) return binaryPath;
251
- const { findBinaryPath } = require("../codemod");
252
- const found = findBinaryPath();
253
- if (!found.binaryPath) {
254
- throw new Error(
255
- `cannot find the codemod binary${found.pkgName ? ` (expected the ${found.pkgName} package)` : ""}; reinstall codemod with optional dependencies, or set CODEMOD_BINARY`,
256
- );
257
- }
258
- binaryPath = found.binaryPath;
259
- return binaryPath;
260
- }
261
-
263
+ if (process.env.CODEMOD_BINARY)
264
+ return process.env.CODEMOD_BINARY;
265
+ if (binaryPath)
266
+ return binaryPath;
267
+ const { findBinaryPath } = require("../codemod");
268
+ const found = findBinaryPath();
269
+ if (!found.binaryPath) {
270
+ throw new Error(`cannot find the codemod binary${found.pkgName ? ` (expected the ${found.pkgName} package)` : ""}; reinstall codemod with optional dependencies, or set CODEMOD_BINARY`);
271
+ }
272
+ binaryPath = found.binaryPath;
273
+ return binaryPath;
274
+ }
262
275
  // ------------------------------------------------------------ fixtures ---
263
-
264
276
  /**
265
- * The fixtures in `dir`: each subdirectory with `input/` and `expected/`, or
266
- * `input.<ext>` and `expected.<ext>`, and optionally `params.json`. Groups of
277
+ * The fixtures in a directory: each subdirectory with `input/` and
278
+ * `expected/` directories, or `input.<ext>` and `expected.<ext>` files (the
279
+ * layouts `codemod jssg test` reads), and optionally `params.json`. Groups of
267
280
  * fixtures may be nested.
268
281
  */
269
282
  export function fixtures(dir) {
270
- const root = toPath(dir);
271
- if (!existsSync(root) || !statSync(root).isDirectory()) {
272
- throw new Error(`no fixtures directory at ${root}`);
273
- }
274
- const found = [];
275
- // The fixtures directory may itself hold `input/` and `expected/`.
276
- if (isDir(join(root, "input"))) {
277
- found.push(
278
- fixture(basename(root), root, join(root, "input"), join(root, "expected"), readParams(root)),
279
- );
280
- }
281
- collect(root, root, found);
282
- return found;
283
- }
284
-
283
+ const root = toPath(dir);
284
+ if (!existsSync(root) || !statSync(root).isDirectory()) {
285
+ throw new Error(`no fixtures directory at ${root}`);
286
+ }
287
+ const found = [];
288
+ // The fixtures directory may itself hold `input/` and `expected/`.
289
+ if (isDir(join(root, "input"))) {
290
+ found.push(fixture(basename(root), root, join(root, "input"), join(root, "expected"), readParams(root)));
291
+ }
292
+ collect(root, root, found);
293
+ return found;
294
+ }
285
295
  function isDir(path) {
286
- return existsSync(path) && statSync(path).isDirectory();
296
+ return existsSync(path) && statSync(path).isDirectory();
287
297
  }
288
-
289
298
  function collect(root, dir, found) {
290
- // A fixture's own input/ and expected/ are not fixtures.
291
- const own = isDir(join(dir, "input")) ? new Set(["input", "expected"]) : new Set();
292
- const subdirs = readdirSync(dir, { withFileTypes: true })
293
- .filter((entry) => entry.isDirectory() && !own.has(entry.name))
294
- .map((entry) => join(dir, entry.name))
295
- .sort();
296
- for (const sub of subdirs) {
297
- const name = relative(root, sub).split(sep).join("/");
298
- const params = readParams(sub);
299
- if (isDir(join(sub, "input"))) {
300
- found.push(fixture(name, sub, join(sub, "input"), join(sub, "expected"), params));
301
- continue;
302
- }
303
- const inputs = readdirSync(sub).filter(
304
- (file) => basename(file, extname(file)) === "input" && statSync(join(sub, file)).isFile(),
305
- );
306
- if (inputs.length > 1) {
307
- throw new Error(
308
- `${sub} has more than one input file; use input/ and expected/ directories instead`,
309
- );
310
- }
311
- if (inputs.length === 1) {
312
- const input = join(sub, inputs[0]);
313
- found.push(fixture(name, sub, input, join(sub, `expected${extname(input)}`), params));
314
- continue;
315
- }
316
- collect(root, sub, found);
317
- }
318
- }
319
-
299
+ // A fixture's own input/ and expected/ are not fixtures.
300
+ const own = new Set(isDir(join(dir, "input")) ? ["input", "expected"] : []);
301
+ const subdirs = readdirSync(dir, { withFileTypes: true })
302
+ .filter((entry) => entry.isDirectory() && !own.has(entry.name))
303
+ .map((entry) => join(dir, entry.name))
304
+ .sort();
305
+ for (const sub of subdirs) {
306
+ const name = relative(root, sub).split(sep).join("/");
307
+ const params = readParams(sub);
308
+ if (isDir(join(sub, "input"))) {
309
+ found.push(fixture(name, sub, join(sub, "input"), join(sub, "expected"), params));
310
+ continue;
311
+ }
312
+ const [inputFile, ...more] = readdirSync(sub).filter((file) => basename(file, extname(file)) === "input" && statSync(join(sub, file)).isFile());
313
+ if (more.length) {
314
+ throw new Error(`${sub} has more than one input file; use input/ and expected/ directories instead`);
315
+ }
316
+ if (inputFile !== undefined) {
317
+ const input = join(sub, inputFile);
318
+ found.push(fixture(name, sub, input, join(sub, `expected${extname(input)}`), params));
319
+ continue;
320
+ }
321
+ collect(root, sub, found);
322
+ }
323
+ }
320
324
  function fixture(name, dir, input, expected, params) {
321
- return Object.freeze({ name, dir, input, expected, params });
325
+ return Object.freeze({ name, dir, input, expected, params });
322
326
  }
323
-
324
327
  function readParams(dir) {
325
- const path = join(dir, "params.json");
326
- if (!existsSync(path)) return {};
327
- const params = JSON.parse(readFileSync(path, "utf8"));
328
- if (!params || typeof params !== "object" || Array.isArray(params)) {
329
- throw new Error(`${path} must hold a JSON object`);
330
- }
331
- return params;
332
- }
333
-
328
+ const path = join(dir, "params.json");
329
+ if (!existsSync(path))
330
+ return {};
331
+ const params = JSON.parse(readFileSync(path, "utf8"));
332
+ if (!params || typeof params !== "object" || Array.isArray(params)) {
333
+ throw new Error(`${path} must hold a JSON object`);
334
+ }
335
+ return params;
336
+ }
334
337
  // ----------------------------------------------------------- assertions ---
335
-
336
338
  /**
337
- * Assert that a run left the expected files. `actual` is a run, a directory,
338
- * or files by path; `expected` is a directory, a single file, or files by
339
- * path. With `CODEMOD_UPDATE_FIXTURES=1`, an expected directory or file is
340
- * rewritten to match instead.
339
+ * Assert that `actual` holds exactly the expected files. Throws an
340
+ * `AssertionError` with `actual` and `expected` set and a diff in the
341
+ * message.
342
+ *
343
+ * - `actual`: a run (which must have succeeded or stopped), a directory, or
344
+ * files by path.
345
+ * - `expected`: a directory, files by path, or a single file, in which case
346
+ * the run must have left exactly one file.
347
+ *
348
+ * Line endings are compared as `\n`. With `CODEMOD_UPDATE_FIXTURES=1`, an
349
+ * expected directory or file is rewritten to match `actual` instead.
341
350
  */
342
351
  export function assertTree(actual, expected, options = {}) {
343
- if (actual instanceof WorkflowRun && !actual.ok) {
344
- throw new AssertionError({
345
- message: describeFailure(actual),
346
- actual: actual.status,
347
- expected: "succeeded",
348
- operator: "assertTree",
352
+ if (actual instanceof Run && !actual.ok) {
353
+ throw new AssertionError({
354
+ message: describeFailure(actual),
355
+ actual: actual.status,
356
+ expected: "succeeded",
357
+ operator: "assertTree",
358
+ });
359
+ }
360
+ const actualTree = actual instanceof Run ? actual.files : treeOf(actual);
361
+ const expectedPath = isPath(expected) ? toPath(expected) : null;
362
+ const single = expectedPath !== null && existsSync(expectedPath) && statSync(expectedPath).isFile();
363
+ if (expectedPath !== null && updating()) {
364
+ // A file (`expected.ts`) when one exists or the name has an extension;
365
+ // otherwise a directory.
366
+ const asFile = single || (!existsSync(expectedPath) && extname(expectedPath) !== "");
367
+ if (asFile) {
368
+ writeFileSync(expectedPath, soleFile(actualTree, expectedPath)[1]);
369
+ }
370
+ else {
371
+ rmSync(expectedPath, { recursive: true, force: true });
372
+ writeTree(expectedPath, actualTree);
373
+ }
374
+ return;
375
+ }
376
+ if (expectedPath !== null && single) {
377
+ const [path, text] = soleFile(actualTree, expectedPath);
378
+ const want = normalize(readFileSync(expectedPath, "utf8"));
379
+ if (!same(text, want, options)) {
380
+ fail(`${path} differs from ${expectedPath}`, text, want, unifiedDiff(path, want, text), options);
381
+ }
382
+ return;
383
+ }
384
+ const expectedTree = treeOf(expected);
385
+ const paths = [...new Set([...Object.keys(expectedTree), ...Object.keys(actualTree)])].sort();
386
+ // What one tree has at a path that the other differs at; a file is never
387
+ // missing from both.
388
+ const differing = paths.flatMap((path) => {
389
+ const [got, want] = [actualTree[path], expectedTree[path]];
390
+ return got !== undefined && want !== undefined && same(got, want, options)
391
+ ? []
392
+ : [{ path, got, want }];
349
393
  });
350
- }
351
- const actualTree = actual instanceof WorkflowRun ? actual.files : treeOf(actual);
352
- const expectedPath = isPath(expected) ? toPath(expected) : null;
353
- const single =
354
- expectedPath !== null && existsSync(expectedPath) && statSync(expectedPath).isFile();
355
-
356
- if (expectedPath !== null && updating()) {
357
- // A file (`expected.ts`) when one exists or the name has an extension;
358
- // otherwise a directory.
359
- const asFile = single || (!existsSync(expectedPath) && extname(expectedPath) !== "");
360
- if (asFile) {
361
- writeFileSync(expectedPath, soleFile(actualTree, expectedPath)[1]);
362
- } else {
363
- rmSync(expectedPath, { recursive: true, force: true });
364
- writeTree(expectedPath, actualTree);
365
- }
366
- return;
367
- }
368
-
369
- if (single) {
370
- const [path, text] = soleFile(actualTree, expectedPath);
371
- const want = normalize(readFileSync(expectedPath, "utf8"));
372
- if (!same(text, want, options)) {
373
- fail(
374
- `${path} differs from ${expectedPath}`,
375
- text,
376
- want,
377
- unifiedDiff(path, want, text),
378
- options,
379
- );
380
- }
381
- return;
382
- }
383
-
384
- const expectedTree = treeOf(expected);
385
- const paths = [...new Set([...Object.keys(expectedTree), ...Object.keys(actualTree)])].sort();
386
- const differing = paths.filter(
387
- (path) =>
388
- !(path in expectedTree) ||
389
- !(path in actualTree) ||
390
- !same(actualTree[path], expectedTree[path], options),
391
- );
392
- if (!differing.length) return;
393
-
394
- const report = differing.map((path) => {
395
- if (!(path in actualTree)) return `missing ${path}\n`;
396
- if (!(path in expectedTree)) return `unexpected ${path}\n`;
397
- return unifiedDiff(path, expectedTree[path], actualTree[path]);
398
- });
399
- const only = differing.length === 1 && differing[0] in actualTree && differing[0] in expectedTree;
400
- const title = only
401
- ? `${differing[0]} differs from the expected output`
402
- : `${differing.length} ${differing.length === 1 ? "file differs" : "files differ"} from the expected output`;
403
- if (only) {
404
- fail(title, actualTree[differing[0]], expectedTree[differing[0]], report.join(""), options);
405
- }
406
- fail(
407
- title,
408
- render(actualTree, differing),
409
- render(expectedTree, differing),
410
- report.join(""),
411
- options,
412
- );
413
- }
414
-
394
+ const [first, ...rest] = differing;
395
+ if (!first)
396
+ return;
397
+ const report = differing
398
+ .map(({ path, got, want }) => {
399
+ if (got === undefined)
400
+ return `missing ${path}\n`;
401
+ if (want === undefined)
402
+ return `unexpected ${path}\n`;
403
+ return unifiedDiff(path, want, got);
404
+ })
405
+ .join("");
406
+ if (!rest.length && first.got !== undefined && first.want !== undefined) {
407
+ fail(`${first.path} differs from the expected output`, first.got, first.want, report, options);
408
+ }
409
+ const changed = differing.map(({ path }) => path);
410
+ fail(`${differing.length} ${differing.length === 1 ? "file differs" : "files differ"} from the expected output`, render(actualTree, changed), render(expectedTree, changed), report, options);
411
+ }
415
412
  function fail(title, actual, expected, diff, options) {
416
- const message = options.message ? `${options.message}\n${title}` : title;
417
- throw new AssertionError({
418
- message: `${message}\n\n${diff.trimEnd()}\n${updateHint()}`,
419
- actual,
420
- expected,
421
- operator: "assertTree",
422
- });
423
- }
424
-
413
+ const message = options.message ? `${options.message}\n${title}` : title;
414
+ throw new AssertionError({
415
+ message: `${message}\n\n${diff.trimEnd()}\n${updateHint()}`,
416
+ actual,
417
+ expected,
418
+ operator: "assertTree",
419
+ });
420
+ }
425
421
  function describeFailure(run) {
426
- const what = {
427
- failed: `the run failed: ${run.error}`,
428
- canceled: "the run was canceled",
429
- "awaiting-approval": `the run is waiting for an approval: ${run.awaiting}`,
430
- }[run.status];
431
- const logs = run.logs.length
432
- ? `\n\nlogs:\n${run.logs.map((log) => ` ${log.step ? `[${log.step}] ` : ""}${log.line}`).join("\n")}`
433
- : "";
434
- return `${what ?? `the run ended as ${run.status}`}${logs}`;
435
- }
436
-
422
+ const what = run.status === "failed"
423
+ ? `the run failed: ${run.error}`
424
+ : run.status === "canceled"
425
+ ? "the run was canceled"
426
+ : run.status === "awaiting-approval"
427
+ ? `the run is waiting for an approval: ${run.awaiting}`
428
+ : `the run ended as ${run.status}`;
429
+ const logs = run.logs.length
430
+ ? `\n\nlogs:\n${run.logs.map((log) => ` ${log.step ? `[${log.step}] ` : ""}${log.line}`).join("\n")}`
431
+ : "";
432
+ return `${what}${logs}`;
433
+ }
437
434
  function updateHint() {
438
- return "(set CODEMOD_UPDATE_FIXTURES=1 to update expected files from the run)";
435
+ return "(set CODEMOD_UPDATE_FIXTURES=1 to update expected files from the run)";
439
436
  }
440
-
441
437
  function updating() {
442
- const value = process.env.CODEMOD_UPDATE_FIXTURES;
443
- return value === "1" || value === "true";
438
+ const value = process.env.CODEMOD_UPDATE_FIXTURES;
439
+ return value === "1" || value === "true";
444
440
  }
445
-
446
441
  function same(a, b, options) {
447
- if (options.ignoreWhitespace) return squash(a) === squash(b);
448
- return a === b;
442
+ if (options.ignoreWhitespace)
443
+ return squash(a) === squash(b);
444
+ return a === b;
449
445
  }
450
-
451
446
  function squash(text) {
452
- return text
453
- .split("\n")
454
- .map((line) => line.trimEnd())
455
- .join("\n")
456
- .trimEnd();
447
+ return text
448
+ .split("\n")
449
+ .map((line) => line.trimEnd())
450
+ .join("\n")
451
+ .trimEnd();
457
452
  }
458
-
459
453
  function soleFile(tree, expectedPath) {
460
- const entries = Object.entries(tree);
461
- if (entries.length === 1) return entries[0];
462
- throw new AssertionError({
463
- message: `${expectedPath} is one file, but the run left ${entries.length} (${Object.keys(tree).join(", ") || "none"}); compare against a directory to test more than one file`,
464
- actual: Object.keys(tree),
465
- expected: [basename(expectedPath)],
466
- operator: "assertTree",
467
- });
468
- }
469
-
454
+ const [only, ...others] = Object.entries(tree);
455
+ if (only && !others.length)
456
+ return only;
457
+ throw new AssertionError({
458
+ message: `${expectedPath} is one file, but the run left ${Object.keys(tree).length} (${Object.keys(tree).join(", ") || "none"}); compare against a directory to test more than one file`,
459
+ actual: Object.keys(tree),
460
+ expected: [basename(expectedPath)],
461
+ operator: "assertTree",
462
+ });
463
+ }
470
464
  function render(tree, paths) {
471
- return paths
472
- .map((path) => (path in tree ? `// ${path}\n${tree[path]}` : `// ${path} (no file)\n`))
473
- .join("\n");
465
+ return paths
466
+ .map((path) => (path in tree ? `// ${path}\n${tree[path]}` : `// ${path} (no file)\n`))
467
+ .join("\n");
474
468
  }
475
-
476
469
  // --------------------------------------------------------------- trees ---
477
-
478
470
  function treeOf(value) {
479
- if (isPath(value)) return readTree(toPath(value));
480
- if (value && typeof value === "object") {
481
- const tree = {};
482
- for (const [path, text] of Object.entries(value)) {
483
- if (text === null) continue;
484
- if (typeof text !== "string") throw new TypeError(`file ${path} must be a string`);
485
- tree[path.replace(/^\.\//, "")] = normalize(text);
471
+ if (isPath(value))
472
+ return readTree(toPath(value));
473
+ if (value && typeof value === "object") {
474
+ const tree = {};
475
+ for (const [path, text] of Object.entries(value)) {
476
+ if (text === null)
477
+ continue;
478
+ if (typeof text !== "string")
479
+ throw new TypeError(`file ${path} must be a string`);
480
+ tree[path.replace(/^\.\//, "")] = normalize(text);
481
+ }
482
+ return tree;
486
483
  }
487
- return tree;
488
- }
489
- throw new TypeError("expected a directory path, a URL, or files by path");
484
+ throw new TypeError("expected a directory path, a URL, or files by path");
490
485
  }
491
-
492
486
  function materialize(target, dir) {
493
- if (isPath(target)) {
494
- const path = toPath(target);
495
- if (!existsSync(path)) throw new Error(`target ${path} does not exist`);
496
- if (statSync(path).isFile()) cpSync(path, join(dir, basename(path)));
497
- else cpSync(path, dir, { recursive: true });
498
- return;
499
- }
500
- writeTree(dir, treeOf(target));
501
- }
502
-
487
+ if (isPath(target)) {
488
+ const path = toPath(target);
489
+ if (!existsSync(path))
490
+ throw new Error(`target ${path} does not exist`);
491
+ if (statSync(path).isFile())
492
+ cpSync(path, join(dir, basename(path)));
493
+ else
494
+ cpSync(path, dir, { recursive: true });
495
+ return;
496
+ }
497
+ writeTree(dir, treeOf(target));
498
+ }
503
499
  function writeTree(dir, tree) {
504
- mkdirSync(dir, { recursive: true });
505
- for (const [path, text] of Object.entries(tree)) {
506
- const file = join(dir, path);
507
- mkdirSync(dirname(file), { recursive: true });
508
- writeFileSync(file, text);
509
- }
510
- }
511
-
500
+ mkdirSync(dir, { recursive: true });
501
+ for (const [path, text] of Object.entries(tree)) {
502
+ const file = join(dir, path);
503
+ mkdirSync(dirname(file), { recursive: true });
504
+ writeFileSync(file, text);
505
+ }
506
+ }
512
507
  function readTree(dir) {
513
- const tree = {};
514
- if (!existsSync(dir)) return tree;
515
- const walk = (current) => {
516
- for (const entry of readdirSync(current, { withFileTypes: true })) {
517
- const path = join(current, entry.name);
518
- if (entry.isDirectory()) walk(path);
519
- else tree[relative(dir, path).split(sep).join("/")] = normalize(readFileSync(path, "utf8"));
520
- }
521
- };
522
- walk(dir);
523
- return Object.fromEntries(Object.entries(tree).sort(([a], [b]) => (a < b ? -1 : 1)));
524
- }
525
-
508
+ const tree = {};
509
+ if (!existsSync(dir))
510
+ return tree;
511
+ const walk = (current) => {
512
+ for (const entry of readdirSync(current, { withFileTypes: true })) {
513
+ const path = join(current, entry.name);
514
+ if (entry.isDirectory())
515
+ walk(path);
516
+ else
517
+ tree[relative(dir, path).split(sep).join("/")] = normalize(readFileSync(path, "utf8"));
518
+ }
519
+ };
520
+ walk(dir);
521
+ return Object.fromEntries(Object.entries(tree).sort(([a], [b]) => (a < b ? -1 : 1)));
522
+ }
526
523
  function changes(before, after) {
527
- const changed = {};
528
- for (const [path, text] of Object.entries(after)) {
529
- if (before[path] !== text) changed[path] = text;
530
- }
531
- for (const path of Object.keys(before)) {
532
- if (!(path in after)) changed[path] = null;
533
- }
534
- return changed;
535
- }
536
-
524
+ const changed = {};
525
+ for (const [path, text] of Object.entries(after)) {
526
+ if (before[path] !== text)
527
+ changed[path] = text;
528
+ }
529
+ for (const path of Object.keys(before)) {
530
+ if (!(path in after))
531
+ changed[path] = null;
532
+ }
533
+ return changed;
534
+ }
537
535
  function normalize(text) {
538
- return text.replace(/\r\n/g, "\n");
536
+ return text.replace(/\r\n/g, "\n");
539
537
  }
540
-
541
538
  function toPath(value) {
542
- if (isUrl(value)) return fileURLToPath(value.href);
543
- if (typeof value === "string" && value.startsWith("file:")) return fileURLToPath(value);
544
- if (typeof value === "string") return resolve(value);
545
- throw new TypeError("expected a path or a file URL");
539
+ if (isUrl(value))
540
+ return fileURLToPath(value.href);
541
+ if (typeof value === "string" && value.startsWith("file:"))
542
+ return fileURLToPath(value);
543
+ if (typeof value === "string")
544
+ return resolve(value);
545
+ throw new TypeError("expected a path or a file URL");
546
546
  }
547
-
548
547
  // Not `instanceof URL`: test environments may have their own URL class.
549
548
  function isUrl(value) {
550
- return value !== null && typeof value === "object" && typeof value.href === "string";
549
+ return value !== null && typeof value === "object" && typeof value.href === "string";
551
550
  }
552
-
553
551
  function isPath(value) {
554
- return typeof value === "string" || isUrl(value);
552
+ return typeof value === "string" || isUrl(value);
555
553
  }
556
-
557
- // ---------------------------------------------------------------- diff ---
558
-
559
554
  /** A unified diff of two texts, by line, with three lines of context. */
560
555
  function unifiedDiff(path, from, to) {
561
- const a = splitLines(from);
562
- const b = splitLines(to);
563
- const ops = diffLines(a, b);
564
- if (ops.every((op) => op[0] === " ")) return "";
565
- const hunks = [];
566
- const context = 3;
567
- let i = 0;
568
- while (i < ops.length) {
569
- if (ops[i][0] === " ") {
570
- i++;
571
- continue;
572
- }
573
- let start = Math.max(0, i - context);
574
- let end = i;
575
- // Extend the hunk while changes are within 2 * context lines of each other.
576
- while (end < ops.length) {
577
- let next = end;
578
- while (next < ops.length && ops[next][0] === " ") next++;
579
- if (next >= ops.length || next - end > context * 2) break;
580
- while (next < ops.length && ops[next][0] !== " ") next++;
581
- end = next;
582
- }
583
- end = Math.min(ops.length, end + context);
584
- hunks.push([start, end]);
585
- i = end;
586
- }
587
- let out = `--- expected/${path}\n+++ actual/${path}\n`;
588
- for (const [start, end] of hunks) {
589
- let aLine = 1;
590
- let bLine = 1;
591
- for (let k = 0; k < start; k++) {
592
- if (ops[k][0] !== "+") aLine++;
593
- if (ops[k][0] !== "-") bLine++;
594
- }
595
- const slice = ops.slice(start, end);
596
- const aCount = slice.filter((op) => op[0] !== "+").length;
597
- const bCount = slice.filter((op) => op[0] !== "-").length;
598
- out += `@@ -${aLine},${aCount} +${bLine},${bCount} @@\n`;
599
- for (const [sign, line] of slice) out += `${sign}${line}\n`;
600
- }
601
- return out;
602
- }
603
-
604
- function splitLines(text) {
605
- if (text === "") return [];
606
- const lines = text.split("\n");
607
- if (lines[lines.length - 1] === "") lines.pop();
608
- return lines;
556
+ const ops = diffLines(splitLines(from), splitLines(to));
557
+ const kept = (index) => ops[index]?.[0] === " ";
558
+ if (ops.every(([sign]) => sign === " "))
559
+ return "";
560
+ const hunks = [];
561
+ const context = 3;
562
+ let i = 0;
563
+ while (i < ops.length) {
564
+ if (kept(i)) {
565
+ i++;
566
+ continue;
567
+ }
568
+ const start = Math.max(0, i - context);
569
+ let end = i;
570
+ // Extend the hunk while changes are within 2 * context lines of each other.
571
+ while (end < ops.length) {
572
+ let next = end;
573
+ while (next < ops.length && kept(next))
574
+ next++;
575
+ if (next >= ops.length || next - end > context * 2)
576
+ break;
577
+ while (next < ops.length && !kept(next))
578
+ next++;
579
+ end = next;
580
+ }
581
+ end = Math.min(ops.length, end + context);
582
+ hunks.push([start, end]);
583
+ i = end;
584
+ }
585
+ let out = `--- expected/${path}\n+++ actual/${path}\n`;
586
+ for (const [start, end] of hunks) {
587
+ const before = ops.slice(0, start);
588
+ const aLine = 1 + before.filter(([sign]) => sign !== "+").length;
589
+ const bLine = 1 + before.filter(([sign]) => sign !== "-").length;
590
+ const slice = ops.slice(start, end);
591
+ const aCount = slice.filter(([sign]) => sign !== "+").length;
592
+ const bCount = slice.filter(([sign]) => sign !== "-").length;
593
+ out += `@@ -${aLine},${aCount} +${bLine},${bCount} @@\n`;
594
+ for (const [sign, line] of slice)
595
+ out += `${sign}${line}\n`;
596
+ }
597
+ return out;
609
598
  }
610
-
611
- /** Longest-common-subsequence line diff: a list of [" " | "-" | "+", line]. */
599
+ function splitLines(text) {
600
+ if (text === "")
601
+ return [];
602
+ const lines = text.split("\n");
603
+ if (lines[lines.length - 1] === "")
604
+ lines.pop();
605
+ return lines;
606
+ }
607
+ /** Longest-common-subsequence line diff. */
612
608
  function diffLines(a, b) {
613
- const n = a.length;
614
- const m = b.length;
615
- const table = Array.from({ length: n + 1 }, () => new Uint32Array(m + 1));
616
- for (let i = n - 1; i >= 0; i--) {
617
- for (let j = m - 1; j >= 0; j--) {
618
- table[i][j] =
619
- a[i] === b[j] ? table[i + 1][j + 1] + 1 : Math.max(table[i + 1][j], table[i][j + 1]);
620
- }
621
- }
622
- const ops = [];
623
- let i = 0;
624
- let j = 0;
625
- while (i < n && j < m) {
626
- if (a[i] === b[j]) {
627
- ops.push([" ", a[i++]]);
628
- j++;
629
- } else if (table[i + 1][j] >= table[i][j + 1]) {
630
- ops.push(["-", a[i++]]);
631
- } else {
632
- ops.push(["+", b[j++]]);
633
- }
634
- }
635
- while (i < n) ops.push(["-", a[i++]]);
636
- while (j < m) ops.push(["+", b[j++]]);
637
- return ops;
609
+ const n = a.length;
610
+ const m = b.length;
611
+ // lengths[i * width + j]: the longest common subsequence of a[i..] and b[j..].
612
+ const width = m + 1;
613
+ const lengths = new Uint32Array((n + 1) * width);
614
+ const length = (i, j) => lengths[i * width + j] ?? 0;
615
+ for (let i = n - 1; i >= 0; i--) {
616
+ for (let j = m - 1; j >= 0; j--) {
617
+ lengths[i * width + j] =
618
+ a[i] === b[j] ? length(i + 1, j + 1) + 1 : Math.max(length(i + 1, j), length(i, j + 1));
619
+ }
620
+ }
621
+ const ops = [];
622
+ let i = 0;
623
+ let j = 0;
624
+ while (i < n && j < m) {
625
+ const [left, right] = [a[i] ?? "", b[j] ?? ""];
626
+ if (left === right) {
627
+ ops.push([" ", left]);
628
+ i++;
629
+ j++;
630
+ }
631
+ else if (length(i + 1, j) >= length(i, j + 1)) {
632
+ ops.push(["-", left]);
633
+ i++;
634
+ }
635
+ else {
636
+ ops.push(["+", right]);
637
+ j++;
638
+ }
639
+ }
640
+ for (; i < n; i++)
641
+ ops.push(["-", a[i] ?? ""]);
642
+ for (; j < m; j++)
643
+ ops.push(["+", b[j] ?? ""]);
644
+ return ops;
638
645
  }