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/README.md +0 -1
- package/package.json +14 -12
- package/register.d.mts +2 -11
- package/register.mjs +53 -46
- package/runtime/addon.d.mts +114 -0
- package/runtime/addon.mjs +36 -40
- package/runtime/ast-grep.d.mts +20 -0
- package/runtime/ast-grep.mjs +50 -61
- package/runtime/context.d.mts +49 -0
- package/runtime/context.mjs +35 -53
- package/runtime/hooks.d.mts +2 -0
- package/runtime/hooks.mjs +4 -6
- package/runtime/host.d.mts +82 -81
- package/runtime/host.mjs +383 -323
- package/runtime/llm.d.mts +2 -0
- package/runtime/llm.mjs +1 -7
- package/runtime/metrics.d.mts +9 -0
- package/runtime/metrics.mjs +31 -34
- package/runtime/modules.d.mts +3 -0
- package/runtime/modules.mjs +8 -10
- package/runtime/orchestrator-version.d.mts +2 -0
- package/runtime/orchestrator-version.mjs +3 -0
- package/runtime/orchestrator.d.mts +261 -0
- package/runtime/orchestrator.mjs +829 -607
- package/runtime/runtime.d.mts +15 -0
- package/runtime/runtime.mjs +18 -26
- package/runtime/workflow.d.mts +19 -0
- package/runtime/workflow.mjs +83 -92
- package/testing/index.d.mts +109 -155
- package/testing/index.mjs +555 -545
- package/types/langs/package.json +3 -0
- package/types/modules/workflow.d.ts +180 -15
- package/vite.d.mts +4 -21
- package/vite.mjs +23 -17
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
|
|
36
|
-
* Resolves for every outcome
|
|
37
|
-
*
|
|
38
|
-
*
|
|
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
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
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
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
|
|
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
|
-
|
|
116
|
-
|
|
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
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
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
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
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
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
)
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
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
|
-
|
|
212
|
+
return steps.length ? steps.map((step) => JSON.stringify(step.label)).join(", ") : "(none)";
|
|
193
213
|
}
|
|
194
|
-
|
|
195
214
|
function harness(spec, signal) {
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
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
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
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
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
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
|
|
266
|
-
* `input.<ext>` and `expected.<ext
|
|
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
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
);
|
|
280
|
-
|
|
281
|
-
|
|
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
|
-
|
|
299
|
+
return existsSync(path) && statSync(path).isDirectory();
|
|
287
300
|
}
|
|
288
|
-
|
|
289
301
|
function collect(root, dir, found) {
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
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
|
-
|
|
328
|
+
return Object.freeze({ name, dir, input, expected, params });
|
|
322
329
|
}
|
|
323
|
-
|
|
324
330
|
function readParams(dir) {
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
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
|
|
338
|
-
*
|
|
339
|
-
*
|
|
340
|
-
*
|
|
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
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
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
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
}
|
|
366
|
-
|
|
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
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
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
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
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
|
-
|
|
438
|
+
return "(set CODEMOD_UPDATE_FIXTURES=1 to update expected files from the run)";
|
|
439
439
|
}
|
|
440
|
-
|
|
441
440
|
function updating() {
|
|
442
|
-
|
|
443
|
-
|
|
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
|
-
|
|
448
|
-
|
|
445
|
+
if (options.ignoreWhitespace)
|
|
446
|
+
return squash(a) === squash(b);
|
|
447
|
+
return a === b;
|
|
449
448
|
}
|
|
450
|
-
|
|
451
449
|
function squash(text) {
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
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
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
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
|
-
|
|
472
|
-
|
|
473
|
-
|
|
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
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
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
|
-
|
|
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
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
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
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
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
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
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
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
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
|
-
|
|
539
|
+
return text.replace(/\r\n/g, "\n");
|
|
539
540
|
}
|
|
540
|
-
|
|
541
541
|
function toPath(value) {
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
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
|
-
|
|
552
|
+
return value !== null && typeof value === "object" && typeof value.href === "string";
|
|
551
553
|
}
|
|
552
|
-
|
|
553
554
|
function isPath(value) {
|
|
554
|
-
|
|
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
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
let
|
|
591
|
-
for (
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
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
|
-
|
|
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
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
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
|
}
|