codemod 2.0.0-alpha.2 → 2.0.0-alpha.3

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,641 @@
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
+ metrics;
165
+ constructor(result, dir, before, files) {
166
+ this.status = result.status;
167
+ this.output = result.output;
168
+ this.error = result.error;
169
+ this.awaiting = result.awaiting;
170
+ this.stoppedAt = result.stoppedAt;
171
+ this.dir = dir;
172
+ this.files = Object.freeze(files);
173
+ this.changes = Object.freeze(changes(before, files));
174
+ this.steps = Object.freeze(result.steps.map((step) => Object.freeze(step)));
175
+ this.logs = Object.freeze(result.logs.map((log) => Object.freeze(log)));
176
+ this.metrics = result.metrics;
177
+ Object.defineProperty(this, "before", { value: before, enumerable: false });
178
+ }
179
+ /** Whether the run finished, or stopped at its `until` step. */
180
+ get ok() {
181
+ return this.status === "succeeded" || this.status === "stopped";
182
+ }
183
+ /** The first step with this label. Throws when there is none. */
184
+ step(label) {
185
+ const found = this.steps.find((step) => step.label === label);
186
+ if (!found) {
187
+ throw new Error(`no step is labeled ${JSON.stringify(label)}; the run's steps are: ${labels(this.steps)}`);
188
+ }
189
+ return found;
190
+ }
191
+ /** A unified diff of every file the run changed. */
192
+ diff() {
193
+ return Object.keys(this.changes)
194
+ .sort()
195
+ .map((path) => unifiedDiff(path, this.before[path] ?? "", this.changes[path] ?? ""))
196
+ .join("");
197
+ }
198
+ }
173
199
  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
-
200
+ const ran = result.steps;
201
+ if (options.until !== undefined && result.status === "succeeded") {
202
+ throw new Error(`until: no step is labeled ${JSON.stringify(options.until)}; the run's steps are: ${labels(ran)}`);
203
+ }
204
+ if (result.status !== "succeeded")
205
+ return;
206
+ const unused = Object.keys(options.given ?? {}).filter((label) => !ran.some((step) => step.given && step.label === label));
207
+ if (unused.length) {
208
+ throw new Error(`given: no step is labeled ${unused.map((l) => JSON.stringify(l)).join(", ")}; the run's steps are: ${labels(ran)}`);
209
+ }
210
+ }
191
211
  function labels(steps) {
192
- return steps.length ? steps.map((step) => JSON.stringify(step.label)).join(", ") : "(none)";
212
+ return steps.length ? steps.map((step) => JSON.stringify(step.label)).join(", ") : "(none)";
193
213
  }
194
-
195
214
  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: {},
215
+ const binary = codemodBinary();
216
+ return new Promise((resolvePromise, reject) => {
217
+ const child = spawn(binary, ["workflow", "harness"], {
218
+ stdio: ["pipe", "pipe", "pipe"],
219
+ env: { ...process.env, NO_COLOR: "1", DISABLE_ANALYTICS: "true" },
220
+ // Stopping a process takes a real signal.
221
+ signal: signal,
220
222
  });
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}`));
223
+ let stdout = "";
224
+ let stderr = "";
225
+ child.stdout.setEncoding("utf8").on("data", (chunk) => (stdout += chunk));
226
+ child.stderr.setEncoding("utf8").on("data", (chunk) => (stderr += chunk));
227
+ child.on("error", (error) => {
228
+ // Aborting stops the CLI; the run then ended as canceled, as it does
229
+ // when Node.js runs the workflow.
230
+ if (signal?.aborted) {
231
+ resolvePromise({
232
+ status: "canceled",
233
+ output: null,
234
+ error: null,
235
+ awaiting: null,
236
+ stoppedAt: null,
237
+ steps: [],
238
+ logs: [],
239
+ metrics: {},
240
+ });
241
+ }
242
+ else {
243
+ reject(error);
244
+ }
245
+ });
246
+ child.on("close", (code) => {
247
+ const line = stdout.trim().split("\n").pop();
248
+ if (code === 0 && line) {
249
+ try {
250
+ resolvePromise(JSON.parse(line));
251
+ return;
252
+ }
253
+ catch {
254
+ // fall through to the error below
255
+ }
256
+ }
257
+ const detail = (stderr.trim() || stdout.trim() || `exit code ${code}`).replace(/^Error:\s*/, "");
258
+ reject(new Error(`cannot run ${spec.workflow}: ${detail}`));
259
+ });
260
+ child.stdin.end(JSON.stringify(spec));
240
261
  });
241
- child.stdin.end(JSON.stringify(spec));
242
- });
243
262
  }
244
-
245
263
  let binaryPath;
246
-
247
264
  /** The codemod CLI binary: `CODEMOD_BINARY`, or the one this package installed. */
248
265
  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
-
266
+ if (process.env.CODEMOD_BINARY)
267
+ return process.env.CODEMOD_BINARY;
268
+ if (binaryPath)
269
+ return binaryPath;
270
+ const { findBinaryPath } = require("../codemod");
271
+ const found = findBinaryPath();
272
+ if (!found.binaryPath) {
273
+ throw new Error(`cannot find the codemod binary${found.pkgName ? ` (expected the ${found.pkgName} package)` : ""}; reinstall codemod with optional dependencies, or set CODEMOD_BINARY`);
274
+ }
275
+ binaryPath = found.binaryPath;
276
+ return binaryPath;
277
+ }
262
278
  // ------------------------------------------------------------ fixtures ---
263
-
264
279
  /**
265
- * The fixtures in `dir`: each subdirectory with `input/` and `expected/`, or
266
- * `input.<ext>` and `expected.<ext>`, and optionally `params.json`. Groups of
280
+ * The fixtures in a directory: each subdirectory with `input/` and
281
+ * `expected/` directories, or `input.<ext>` and `expected.<ext>` files (the
282
+ * layouts `codemod jssg test` reads), and optionally `params.json`. Groups of
267
283
  * fixtures may be nested.
268
284
  */
269
285
  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
-
286
+ const root = toPath(dir);
287
+ if (!existsSync(root) || !statSync(root).isDirectory()) {
288
+ throw new Error(`no fixtures directory at ${root}`);
289
+ }
290
+ const found = [];
291
+ // The fixtures directory may itself hold `input/` and `expected/`.
292
+ if (isDir(join(root, "input"))) {
293
+ found.push(fixture(basename(root), root, join(root, "input"), join(root, "expected"), readParams(root)));
294
+ }
295
+ collect(root, root, found);
296
+ return found;
297
+ }
285
298
  function isDir(path) {
286
- return existsSync(path) && statSync(path).isDirectory();
299
+ return existsSync(path) && statSync(path).isDirectory();
287
300
  }
288
-
289
301
  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
-
302
+ // A fixture's own input/ and expected/ are not fixtures.
303
+ const own = new Set(isDir(join(dir, "input")) ? ["input", "expected"] : []);
304
+ const subdirs = readdirSync(dir, { withFileTypes: true })
305
+ .filter((entry) => entry.isDirectory() && !own.has(entry.name))
306
+ .map((entry) => join(dir, entry.name))
307
+ .sort();
308
+ for (const sub of subdirs) {
309
+ const name = relative(root, sub).split(sep).join("/");
310
+ const params = readParams(sub);
311
+ if (isDir(join(sub, "input"))) {
312
+ found.push(fixture(name, sub, join(sub, "input"), join(sub, "expected"), params));
313
+ continue;
314
+ }
315
+ const [inputFile, ...more] = readdirSync(sub).filter((file) => basename(file, extname(file)) === "input" && statSync(join(sub, file)).isFile());
316
+ if (more.length) {
317
+ throw new Error(`${sub} has more than one input file; use input/ and expected/ directories instead`);
318
+ }
319
+ if (inputFile !== undefined) {
320
+ const input = join(sub, inputFile);
321
+ found.push(fixture(name, sub, input, join(sub, `expected${extname(input)}`), params));
322
+ continue;
323
+ }
324
+ collect(root, sub, found);
325
+ }
326
+ }
320
327
  function fixture(name, dir, input, expected, params) {
321
- return Object.freeze({ name, dir, input, expected, params });
328
+ return Object.freeze({ name, dir, input, expected, params });
322
329
  }
323
-
324
330
  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
-
331
+ const path = join(dir, "params.json");
332
+ if (!existsSync(path))
333
+ return {};
334
+ const params = JSON.parse(readFileSync(path, "utf8"));
335
+ if (!params || typeof params !== "object" || Array.isArray(params)) {
336
+ throw new Error(`${path} must hold a JSON object`);
337
+ }
338
+ return params;
339
+ }
334
340
  // ----------------------------------------------------------- assertions ---
335
-
336
341
  /**
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.
342
+ * Assert that `actual` holds exactly the expected files. Throws an
343
+ * `AssertionError` with `actual` and `expected` set and a diff in the
344
+ * message.
345
+ *
346
+ * - `actual`: a run (which must have succeeded or stopped), a directory, or
347
+ * files by path.
348
+ * - `expected`: a directory, files by path, or a single file, in which case
349
+ * the run must have left exactly one file.
350
+ *
351
+ * Line endings are compared as `\n`. With `CODEMOD_UPDATE_FIXTURES=1`, an
352
+ * expected directory or file is rewritten to match `actual` instead.
341
353
  */
342
354
  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",
355
+ if (actual instanceof Run && !actual.ok) {
356
+ throw new AssertionError({
357
+ message: describeFailure(actual),
358
+ actual: actual.status,
359
+ expected: "succeeded",
360
+ operator: "assertTree",
361
+ });
362
+ }
363
+ const actualTree = actual instanceof Run ? actual.files : treeOf(actual);
364
+ const expectedPath = isPath(expected) ? toPath(expected) : null;
365
+ const single = expectedPath !== null && existsSync(expectedPath) && statSync(expectedPath).isFile();
366
+ if (expectedPath !== null && updating()) {
367
+ // A file (`expected.ts`) when one exists or the name has an extension;
368
+ // otherwise a directory.
369
+ const asFile = single || (!existsSync(expectedPath) && extname(expectedPath) !== "");
370
+ if (asFile) {
371
+ writeFileSync(expectedPath, soleFile(actualTree, expectedPath)[1]);
372
+ }
373
+ else {
374
+ rmSync(expectedPath, { recursive: true, force: true });
375
+ writeTree(expectedPath, actualTree);
376
+ }
377
+ return;
378
+ }
379
+ if (expectedPath !== null && single) {
380
+ const [path, text] = soleFile(actualTree, expectedPath);
381
+ const want = normalize(readFileSync(expectedPath, "utf8"));
382
+ if (!same(text, want, options)) {
383
+ fail(`${path} differs from ${expectedPath}`, text, want, unifiedDiff(path, want, text), options);
384
+ }
385
+ return;
386
+ }
387
+ const expectedTree = treeOf(expected);
388
+ const paths = [...new Set([...Object.keys(expectedTree), ...Object.keys(actualTree)])].sort();
389
+ // What one tree has at a path that the other differs at; a file is never
390
+ // missing from both.
391
+ const differing = paths.flatMap((path) => {
392
+ const [got, want] = [actualTree[path], expectedTree[path]];
393
+ return got !== undefined && want !== undefined && same(got, want, options)
394
+ ? []
395
+ : [{ path, got, want }];
349
396
  });
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
-
397
+ const [first, ...rest] = differing;
398
+ if (!first)
399
+ return;
400
+ const report = differing
401
+ .map(({ path, got, want }) => {
402
+ if (got === undefined)
403
+ return `missing ${path}\n`;
404
+ if (want === undefined)
405
+ return `unexpected ${path}\n`;
406
+ return unifiedDiff(path, want, got);
407
+ })
408
+ .join("");
409
+ if (!rest.length && first.got !== undefined && first.want !== undefined) {
410
+ fail(`${first.path} differs from the expected output`, first.got, first.want, report, options);
411
+ }
412
+ const changed = differing.map(({ path }) => path);
413
+ fail(`${differing.length} ${differing.length === 1 ? "file differs" : "files differ"} from the expected output`, render(actualTree, changed), render(expectedTree, changed), report, options);
414
+ }
415
415
  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
-
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
+ }
425
424
  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
-
425
+ const what = run.status === "failed"
426
+ ? `the run failed: ${run.error}`
427
+ : run.status === "canceled"
428
+ ? "the run was canceled"
429
+ : run.status === "awaiting-approval"
430
+ ? `the run is waiting for an approval: ${run.awaiting}`
431
+ : `the run ended as ${run.status}`;
432
+ const logs = run.logs.length
433
+ ? `\n\nlogs:\n${run.logs.map((log) => ` ${log.step ? `[${log.step}] ` : ""}${log.line}`).join("\n")}`
434
+ : "";
435
+ return `${what}${logs}`;
436
+ }
437
437
  function updateHint() {
438
- return "(set CODEMOD_UPDATE_FIXTURES=1 to update expected files from the run)";
438
+ return "(set CODEMOD_UPDATE_FIXTURES=1 to update expected files from the run)";
439
439
  }
440
-
441
440
  function updating() {
442
- const value = process.env.CODEMOD_UPDATE_FIXTURES;
443
- return value === "1" || value === "true";
441
+ const value = process.env.CODEMOD_UPDATE_FIXTURES;
442
+ return value === "1" || value === "true";
444
443
  }
445
-
446
444
  function same(a, b, options) {
447
- if (options.ignoreWhitespace) return squash(a) === squash(b);
448
- return a === b;
445
+ if (options.ignoreWhitespace)
446
+ return squash(a) === squash(b);
447
+ return a === b;
449
448
  }
450
-
451
449
  function squash(text) {
452
- return text
453
- .split("\n")
454
- .map((line) => line.trimEnd())
455
- .join("\n")
456
- .trimEnd();
450
+ return text
451
+ .split("\n")
452
+ .map((line) => line.trimEnd())
453
+ .join("\n")
454
+ .trimEnd();
457
455
  }
458
-
459
456
  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
-
457
+ const [only, ...others] = Object.entries(tree);
458
+ if (only && !others.length)
459
+ return only;
460
+ throw new AssertionError({
461
+ 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`,
462
+ actual: Object.keys(tree),
463
+ expected: [basename(expectedPath)],
464
+ operator: "assertTree",
465
+ });
466
+ }
470
467
  function render(tree, paths) {
471
- return paths
472
- .map((path) => (path in tree ? `// ${path}\n${tree[path]}` : `// ${path} (no file)\n`))
473
- .join("\n");
468
+ return paths
469
+ .map((path) => (path in tree ? `// ${path}\n${tree[path]}` : `// ${path} (no file)\n`))
470
+ .join("\n");
474
471
  }
475
-
476
472
  // --------------------------------------------------------------- trees ---
477
-
478
473
  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);
474
+ if (isPath(value))
475
+ return readTree(toPath(value));
476
+ if (value && typeof value === "object") {
477
+ const tree = {};
478
+ for (const [path, text] of Object.entries(value)) {
479
+ if (text === null)
480
+ continue;
481
+ if (typeof text !== "string")
482
+ throw new TypeError(`file ${path} must be a string`);
483
+ tree[path.replace(/^\.\//, "")] = normalize(text);
484
+ }
485
+ return tree;
486
486
  }
487
- return tree;
488
- }
489
- throw new TypeError("expected a directory path, a URL, or files by path");
487
+ throw new TypeError("expected a directory path, a URL, or files by path");
490
488
  }
491
-
492
489
  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
-
490
+ if (isPath(target)) {
491
+ const path = toPath(target);
492
+ if (!existsSync(path))
493
+ throw new Error(`target ${path} does not exist`);
494
+ if (statSync(path).isFile())
495
+ cpSync(path, join(dir, basename(path)));
496
+ else
497
+ cpSync(path, dir, { recursive: true });
498
+ return;
499
+ }
500
+ writeTree(dir, treeOf(target));
501
+ }
503
502
  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
-
503
+ mkdirSync(dir, { recursive: true });
504
+ for (const [path, text] of Object.entries(tree)) {
505
+ const file = join(dir, path);
506
+ mkdirSync(dirname(file), { recursive: true });
507
+ writeFileSync(file, text);
508
+ }
509
+ }
512
510
  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
-
511
+ const tree = {};
512
+ if (!existsSync(dir))
513
+ return tree;
514
+ const walk = (current) => {
515
+ for (const entry of readdirSync(current, { withFileTypes: true })) {
516
+ const path = join(current, entry.name);
517
+ if (entry.isDirectory())
518
+ walk(path);
519
+ else
520
+ tree[relative(dir, path).split(sep).join("/")] = normalize(readFileSync(path, "utf8"));
521
+ }
522
+ };
523
+ walk(dir);
524
+ return Object.fromEntries(Object.entries(tree).sort(([a], [b]) => (a < b ? -1 : 1)));
525
+ }
526
526
  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
-
527
+ const changed = {};
528
+ for (const [path, text] of Object.entries(after)) {
529
+ if (before[path] !== text)
530
+ changed[path] = text;
531
+ }
532
+ for (const path of Object.keys(before)) {
533
+ if (!(path in after))
534
+ changed[path] = null;
535
+ }
536
+ return changed;
537
+ }
537
538
  function normalize(text) {
538
- return text.replace(/\r\n/g, "\n");
539
+ return text.replace(/\r\n/g, "\n");
539
540
  }
540
-
541
541
  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");
542
+ if (isUrl(value))
543
+ return fileURLToPath(value.href);
544
+ if (typeof value === "string" && value.startsWith("file:"))
545
+ return fileURLToPath(value);
546
+ if (typeof value === "string")
547
+ return resolve(value);
548
+ throw new TypeError("expected a path or a file URL");
546
549
  }
547
-
548
550
  // Not `instanceof URL`: test environments may have their own URL class.
549
551
  function isUrl(value) {
550
- return value !== null && typeof value === "object" && typeof value.href === "string";
552
+ return value !== null && typeof value === "object" && typeof value.href === "string";
551
553
  }
552
-
553
554
  function isPath(value) {
554
- return typeof value === "string" || isUrl(value);
555
+ return typeof value === "string" || isUrl(value);
555
556
  }
556
-
557
- // ---------------------------------------------------------------- diff ---
558
-
559
557
  /** A unified diff of two texts, by line, with three lines of context. */
560
558
  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;
559
+ const ops = diffLines(splitLines(from), splitLines(to));
560
+ const kept = (index) => ops[index]?.[0] === " ";
561
+ if (ops.every(([sign]) => sign === " "))
562
+ return "";
563
+ const hunks = [];
564
+ const context = 3;
565
+ let i = 0;
566
+ while (i < ops.length) {
567
+ if (kept(i)) {
568
+ i++;
569
+ continue;
570
+ }
571
+ const start = Math.max(0, i - context);
572
+ let end = i;
573
+ // Extend the hunk while changes are within 2 * context lines of each other.
574
+ while (end < ops.length) {
575
+ let next = end;
576
+ while (next < ops.length && kept(next))
577
+ next++;
578
+ if (next >= ops.length || next - end > context * 2)
579
+ break;
580
+ while (next < ops.length && !kept(next))
581
+ next++;
582
+ end = next;
583
+ }
584
+ end = Math.min(ops.length, end + context);
585
+ hunks.push([start, end]);
586
+ i = end;
587
+ }
588
+ let out = `--- expected/${path}\n+++ actual/${path}\n`;
589
+ for (const [start, end] of hunks) {
590
+ const before = ops.slice(0, start);
591
+ const aLine = 1 + before.filter(([sign]) => sign !== "+").length;
592
+ const bLine = 1 + before.filter(([sign]) => sign !== "-").length;
593
+ const slice = ops.slice(start, end);
594
+ const aCount = slice.filter(([sign]) => sign !== "+").length;
595
+ const bCount = slice.filter(([sign]) => sign !== "-").length;
596
+ out += `@@ -${aLine},${aCount} +${bLine},${bCount} @@\n`;
597
+ for (const [sign, line] of slice)
598
+ out += `${sign}${line}\n`;
599
+ }
600
+ return out;
609
601
  }
610
-
611
- /** Longest-common-subsequence line diff: a list of [" " | "-" | "+", line]. */
602
+ function splitLines(text) {
603
+ if (text === "")
604
+ return [];
605
+ const lines = text.split("\n");
606
+ if (lines[lines.length - 1] === "")
607
+ lines.pop();
608
+ return lines;
609
+ }
610
+ /** Longest-common-subsequence line diff. */
612
611
  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;
612
+ const n = a.length;
613
+ const m = b.length;
614
+ // lengths[i * width + j]: the longest common subsequence of a[i..] and b[j..].
615
+ const width = m + 1;
616
+ const lengths = new Uint32Array((n + 1) * width);
617
+ const length = (i, j) => lengths[i * width + j] ?? 0;
618
+ for (let i = n - 1; i >= 0; i--) {
619
+ for (let j = m - 1; j >= 0; j--) {
620
+ lengths[i * width + j] =
621
+ a[i] === b[j] ? length(i + 1, j + 1) + 1 : Math.max(length(i + 1, j), length(i, j + 1));
622
+ }
623
+ }
624
+ const ops = [];
625
+ let i = 0;
626
+ let j = 0;
627
+ while (i < n && j < m) {
628
+ const [left, right] = [a[i] ?? "", b[j] ?? ""];
629
+ if (left === right) {
630
+ ops.push([" ", left]);
631
+ i++;
632
+ j++;
633
+ }
634
+ else if (length(i + 1, j) >= length(i, j + 1)) {
635
+ ops.push(["-", left]);
636
+ i++;
637
+ }
638
+ else {
639
+ ops.push(["+", right]);
640
+ j++;
641
+ }
642
+ }
643
+ for (; i < n; i++)
644
+ ops.push(["-", a[i] ?? ""]);
645
+ for (; j < m; j++)
646
+ ops.push(["+", b[j] ?? ""]);
647
+ return ops;
638
648
  }