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/README.md +1 -2
- package/package.json +14 -16
- package/register.d.mts +2 -11
- package/register.mjs +53 -46
- package/runtime/addon.d.mts +119 -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 +25 -0
- package/runtime/context.mjs +10 -64
- package/runtime/hooks.d.mts +2 -0
- package/runtime/hooks.mjs +4 -6
- package/runtime/host.d.mts +81 -81
- package/runtime/host.mjs +428 -326
- package/runtime/llm.d.mts +2 -0
- package/runtime/llm.mjs +1 -7
- package/runtime/modules.d.mts +3 -0
- package/runtime/modules.mjs +7 -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 +823 -608
- package/runtime/runtime.d.mts +15 -0
- package/runtime/runtime.mjs +18 -26
- package/runtime/workflow.d.mts +24 -0
- package/runtime/workflow.mjs +42 -121
- package/testing/index.d.mts +107 -155
- package/testing/index.mjs +552 -545
- package/types/index.d.ts +0 -1
- package/types/langs/package.json +3 -0
- package/types/modules/ast-grep.d.ts +22 -1
- package/types/modules/workflow.d.ts +386 -231
- package/vite.d.mts +4 -21
- package/vite.mjs +23 -17
- package/runtime/metrics.mjs +0 -45
- package/types/metrics.d.ts +0 -5
- package/types/modules/metrics.d.ts +0 -107
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
|
|
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
|
+
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
210
|
+
return steps.length ? steps.map((step) => JSON.stringify(step.label)).join(", ") : "(none)";
|
|
193
211
|
}
|
|
194
|
-
|
|
195
212
|
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: {},
|
|
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
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
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
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
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
|
|
266
|
-
* `input.<ext>` and `expected.<ext
|
|
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
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
);
|
|
280
|
-
|
|
281
|
-
|
|
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
|
-
|
|
296
|
+
return existsSync(path) && statSync(path).isDirectory();
|
|
287
297
|
}
|
|
288
|
-
|
|
289
298
|
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
|
-
|
|
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
|
-
|
|
325
|
+
return Object.freeze({ name, dir, input, expected, params });
|
|
322
326
|
}
|
|
323
|
-
|
|
324
327
|
function readParams(dir) {
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
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
|
|
338
|
-
*
|
|
339
|
-
*
|
|
340
|
-
*
|
|
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
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
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
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
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
|
-
|
|
435
|
+
return "(set CODEMOD_UPDATE_FIXTURES=1 to update expected files from the run)";
|
|
439
436
|
}
|
|
440
|
-
|
|
441
437
|
function updating() {
|
|
442
|
-
|
|
443
|
-
|
|
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
|
-
|
|
448
|
-
|
|
442
|
+
if (options.ignoreWhitespace)
|
|
443
|
+
return squash(a) === squash(b);
|
|
444
|
+
return a === b;
|
|
449
445
|
}
|
|
450
|
-
|
|
451
446
|
function squash(text) {
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
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
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
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
|
-
|
|
472
|
-
|
|
473
|
-
|
|
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
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
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
|
-
|
|
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
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
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
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
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
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
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
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
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
|
-
|
|
536
|
+
return text.replace(/\r\n/g, "\n");
|
|
539
537
|
}
|
|
540
|
-
|
|
541
538
|
function toPath(value) {
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
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
|
-
|
|
549
|
+
return value !== null && typeof value === "object" && typeof value.href === "string";
|
|
551
550
|
}
|
|
552
|
-
|
|
553
551
|
function isPath(value) {
|
|
554
|
-
|
|
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
|
-
|
|
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;
|
|
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
|
-
|
|
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
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
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
|
}
|