@zuke-build/cli 2.13.0 → 2.14.0
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/package.json +1 -1
- package/src/import.d.ts +46 -19
- package/src/import.js +166 -41
- package/src/import_style.d.ts +17 -0
- package/src/import_style.js +58 -0
- package/src/import_wrappers.d.ts +47 -0
- package/src/import_wrappers.js +147 -0
- package/src/python_build.js +5 -4
- package/src/sequence.d.ts +46 -0
- package/src/sequence.js +57 -0
- package/src/translate.d.ts +25 -1
- package/src/translate.js +60 -11
- package/src/version.js +1 -1
package/package.json
CHANGED
package/src/import.d.ts
CHANGED
|
@@ -4,11 +4,16 @@
|
|
|
4
4
|
* task table — and scaffold an equivalent build, so migrating to Zuke starts
|
|
5
5
|
* from a working translation instead of a blank page.
|
|
6
6
|
*
|
|
7
|
-
* Each discovered task becomes a `target()`. A command
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
7
|
+
* Each discovered task becomes a `target()`. A command whose tool has a typed
|
|
8
|
+
* wrapper becomes that wrapper's task (`eslint src` is `EslintTasks.lint`, see
|
|
9
|
+
* `./import_wrappers.ts`), and any other command maps to
|
|
10
|
+
* {@link https://jsr.io/@zuke/cmd CmdTasks.exec} (typed, injection-safe). A
|
|
11
|
+
* `package.json` script's tools resolve as `npm run` resolves them,
|
|
12
|
+
* `node_modules/.bin` first and then `PATH`. An `&&` chain becomes sequential
|
|
13
|
+
* steps; a script's leading `npm run x` delegations become a `dependsOn` that
|
|
14
|
+
* keeps their order (through `extraEdges()`, see `./sequence.ts`); and a
|
|
15
|
+
* command too shell-specific to translate faithfully (pipes, redirects,
|
|
16
|
+
* substitutions, env assignments, comments) is preserved verbatim behind a
|
|
12
17
|
* `// TODO` so the file still compiles and the few tricky scripts are flagged.
|
|
13
18
|
*
|
|
14
19
|
* A `pyproject.toml` (the first of `[tool.poe.tasks]`, `[tool.pdm.scripts]`,
|
|
@@ -25,6 +30,7 @@
|
|
|
25
30
|
import type { ProjectRuntime } from "./runtime_field.ts";
|
|
26
31
|
import type { BinaryPin } from "./binary_pin.ts";
|
|
27
32
|
import { type McpSetupOptions, type ScaffoldImports, type SetupHost, type SetupResult } from "./setup.ts";
|
|
33
|
+
import { type Resolution } from "./import_wrappers.ts";
|
|
28
34
|
/** A task discovered in an existing project, before identifier normalisation. */
|
|
29
35
|
export interface RawTask {
|
|
30
36
|
/** The task's original name (a `package.json` script key, a Makefile target). */
|
|
@@ -33,12 +39,22 @@ export interface RawTask {
|
|
|
33
39
|
readonly command: string;
|
|
34
40
|
/** Names of other tasks this one depends on / delegates to. */
|
|
35
41
|
readonly deps: readonly string[];
|
|
42
|
+
/**
|
|
43
|
+
* Whether {@link RawTask.deps} must run one after another in the order
|
|
44
|
+
* listed, as the `npm run a && npm run b` chain they came from did. A
|
|
45
|
+
* Makefile's prerequisites carry no such promise (`make -j` runs them at
|
|
46
|
+
* once), so theirs is `false`.
|
|
47
|
+
*/
|
|
48
|
+
readonly sequential: boolean;
|
|
36
49
|
}
|
|
37
50
|
/**
|
|
38
51
|
* Parse the `scripts` block of a `package.json` document into tasks, in
|
|
39
|
-
* declaration order.
|
|
40
|
-
*
|
|
41
|
-
*
|
|
52
|
+
* declaration order. The delegations a script opens with (`npm run lint &&
|
|
53
|
+
* pnpm test && …`) become its dependencies, which run before the rest and in
|
|
54
|
+
* the order listed ({@link RawTask.sequential}). Once the chain has run a
|
|
55
|
+
* command of its own, a later delegation stays a command — a dependency would
|
|
56
|
+
* run it before that command, not after it — as does one naming the script
|
|
57
|
+
* itself or one it already delegated to.
|
|
42
58
|
*/
|
|
43
59
|
export declare function parsePackageJson(text: string): RawTask[];
|
|
44
60
|
/**
|
|
@@ -48,19 +64,30 @@ export declare function parsePackageJson(text: string): RawTask[];
|
|
|
48
64
|
* skipped.
|
|
49
65
|
*/
|
|
50
66
|
export declare function parseMakefile(text: string): RawTask[];
|
|
67
|
+
/** A name a generated build imports, and the package it comes from. */
|
|
68
|
+
export interface ImportedName {
|
|
69
|
+
/** The bare specifier (`@zuke/eslint`). */
|
|
70
|
+
readonly specifier: string;
|
|
71
|
+
/** The exported name (`EslintTasks`). */
|
|
72
|
+
readonly name: string;
|
|
73
|
+
}
|
|
51
74
|
/** One statement in a generated target body. */
|
|
52
|
-
interface BodyItem {
|
|
53
|
-
/** The code — a
|
|
75
|
+
export interface BodyItem {
|
|
76
|
+
/** The code — a task call, or a `// TODO` comment. */
|
|
54
77
|
readonly code: string;
|
|
55
|
-
/** Whether this is a runnable
|
|
78
|
+
/** Whether this is a runnable call (vs. a comment placeholder). */
|
|
56
79
|
readonly runnable: boolean;
|
|
80
|
+
/** The names its code imports. */
|
|
81
|
+
readonly uses: readonly ImportedName[];
|
|
57
82
|
}
|
|
58
83
|
/**
|
|
59
84
|
* Translate a shell command into target-body statements: each `&&`-separated
|
|
60
|
-
* segment becomes a `CmdTasks.exec(...)` call
|
|
61
|
-
*
|
|
85
|
+
* segment becomes a typed wrapper's task or a `CmdTasks.exec(...)` call whose
|
|
86
|
+
* tool resolves as `resolution` says (`"node_modules"` for a `package.json`
|
|
87
|
+
* script, as `npm run` finds it; `"path"` for a Makefile), or a `// TODO`
|
|
88
|
+
* comment preserving the raw text when it is too shell-specific to translate.
|
|
62
89
|
*/
|
|
63
|
-
export declare function translateCommand(command: string): BodyItem[];
|
|
90
|
+
export declare function translateCommand(command: string, resolution: Resolution): BodyItem[];
|
|
64
91
|
/**
|
|
65
92
|
* Turn a task name into a valid, camelCase JavaScript identifier for a target
|
|
66
93
|
* field — `build:prod` → `buildProd`, `test-watch` → `testWatch`. Falls back to
|
|
@@ -73,17 +100,18 @@ export interface GeneratedBuild {
|
|
|
73
100
|
readonly source: string;
|
|
74
101
|
/**
|
|
75
102
|
* The `deno.json` `imports` entries {@link GeneratedBuild.source} resolves
|
|
76
|
-
* through — always `@zuke/core`, plus `@zuke/cmd`
|
|
77
|
-
* command. {@link runImport} hands these to the scaffolder, which merges them
|
|
103
|
+
* through — always `@zuke/core`, plus `@zuke/cmd` and each typed wrapper's
|
|
104
|
+
* package that a translated command runs through. {@link runImport} hands these to the scaffolder, which merges them
|
|
78
105
|
* into `deno.json`.
|
|
79
106
|
*/
|
|
80
107
|
readonly imports: ScaffoldImports;
|
|
81
108
|
}
|
|
82
109
|
/**
|
|
83
|
-
* Generate a `zuke.ts` build class named `className` from imported tasks
|
|
110
|
+
* Generate a `zuke.ts` build class named `className` from imported tasks, each
|
|
111
|
+
* command's tool resolved as `resolution` says (see {@link translateCommand}).
|
|
84
112
|
* Exposed for tools and tests; {@link runImport} writes the result to disk.
|
|
85
113
|
*/
|
|
86
|
-
export declare function generateBuild(className: string, raw: readonly RawTask[]): GeneratedBuild;
|
|
114
|
+
export declare function generateBuild(className: string, raw: readonly RawTask[], resolution: Resolution): GeneratedBuild;
|
|
87
115
|
/** The kinds of project `zuke import` can read. */
|
|
88
116
|
export type ImportSource = "package.json" | "Makefile" | "pyproject.toml";
|
|
89
117
|
/** Options controlling {@link runImport}. */
|
|
@@ -135,4 +163,3 @@ export interface ImportResult extends SetupResult {
|
|
|
135
163
|
* one. Returns `source: null` when nothing was found (and writes nothing).
|
|
136
164
|
*/
|
|
137
165
|
export declare function runImport(options: ImportOptions, host: SetupHost): Promise<ImportResult>;
|
|
138
|
-
export {};
|
package/src/import.js
CHANGED
|
@@ -3,16 +3,39 @@
|
|
|
3
3
|
import { parsePyproject } from "./pyproject.js";
|
|
4
4
|
import { generatePythonBuild } from "./python_build.js";
|
|
5
5
|
import { isRecord, joinPath, runSetup, } from "./setup.js";
|
|
6
|
+
import { Build } from "@zuke/core";
|
|
6
7
|
import { STARTER_IMPORTS, zukeDependency } from "./starter.js";
|
|
7
8
|
import { literal, normalize, oneLine, order, segments, splitChain, tokenize, } from "./translate.js";
|
|
9
|
+
import { wrapperFor } from "./import_wrappers.js";
|
|
10
|
+
import { sequenceEdges } from "./sequence.js";
|
|
11
|
+
import { formatterNote } from "./import_style.js";
|
|
8
12
|
// --- package.json ---------------------------------------------------------
|
|
9
|
-
/**
|
|
10
|
-
|
|
13
|
+
/**
|
|
14
|
+
* How each package manager runs a script: the subcommands that take a script
|
|
15
|
+
* name, and whether the bare `<runner> <script>` form does too. npm runs a
|
|
16
|
+
* script only through `run` (or `run-script`) and its four lifecycle
|
|
17
|
+
* shorthands, so `npm lint` is not a delegation. pnpm and yarn run a script
|
|
18
|
+
* named bare. bun's bare form runs a file or its own commands (`bun test` is
|
|
19
|
+
* bun's test runner), so only `bun run` delegates. Deno is not a runner here:
|
|
20
|
+
* `deno task x` runs `deno.json`'s task `x` before any `package.json` script of
|
|
21
|
+
* that name, so the command stays as written.
|
|
22
|
+
*/
|
|
23
|
+
const RUNNERS = {
|
|
24
|
+
npm: { run: ["run", "run-script"], bare: false },
|
|
25
|
+
pnpm: { run: ["run"], bare: true },
|
|
26
|
+
yarn: { run: ["run"], bare: true },
|
|
27
|
+
bun: { run: ["run"], bare: false },
|
|
28
|
+
};
|
|
29
|
+
/** The scripts npm runs by name without `run`. */
|
|
30
|
+
const NPM_SHORTHANDS = ["test", "start", "stop", "restart"];
|
|
11
31
|
/**
|
|
12
32
|
* Parse the `scripts` block of a `package.json` document into tasks, in
|
|
13
|
-
* declaration order.
|
|
14
|
-
*
|
|
15
|
-
*
|
|
33
|
+
* declaration order. The delegations a script opens with (`npm run lint &&
|
|
34
|
+
* pnpm test && …`) become its dependencies, which run before the rest and in
|
|
35
|
+
* the order listed ({@link RawTask.sequential}). Once the chain has run a
|
|
36
|
+
* command of its own, a later delegation stays a command — a dependency would
|
|
37
|
+
* run it before that command, not after it — as does one naming the script
|
|
38
|
+
* itself or one it already delegated to.
|
|
16
39
|
*/
|
|
17
40
|
export function parsePackageJson(text) {
|
|
18
41
|
const parsed = JSON.parse(text);
|
|
@@ -27,25 +50,33 @@ export function parsePackageJson(text) {
|
|
|
27
50
|
const kept = [];
|
|
28
51
|
for (const segment of splitChain(value)) {
|
|
29
52
|
const target = delegatedScript(segment, names);
|
|
30
|
-
|
|
53
|
+
const leading = kept.length === 0 && target !== undefined &&
|
|
54
|
+
target !== name && !deps.includes(target);
|
|
55
|
+
if (leading)
|
|
31
56
|
deps.push(target);
|
|
32
57
|
else
|
|
33
58
|
kept.push(segment.trim());
|
|
34
59
|
}
|
|
35
|
-
tasks.push({ name, command: kept.join(" && "), deps });
|
|
60
|
+
tasks.push({ name, command: kept.join(" && "), deps, sequential: true });
|
|
36
61
|
}
|
|
37
62
|
return tasks;
|
|
38
63
|
}
|
|
39
64
|
/** If `segment` is a `<runner> [run] <script>` delegation, the script name. */
|
|
40
65
|
function delegatedScript(segment, scripts) {
|
|
41
66
|
const tokens = tokenize(segment.trim());
|
|
42
|
-
if (tokens === undefined)
|
|
67
|
+
if (tokens === undefined || tokens.length === 0)
|
|
43
68
|
return undefined;
|
|
44
|
-
|
|
69
|
+
const [bin, ...args] = tokens;
|
|
70
|
+
const runner = Object.hasOwn(RUNNERS, bin) ? RUNNERS[bin] : undefined;
|
|
71
|
+
if (runner === undefined)
|
|
45
72
|
return undefined;
|
|
46
|
-
const
|
|
73
|
+
const named = runner.run.includes(args[0]) ? args.slice(1) : undefined;
|
|
74
|
+
const bare = runner.bare || (bin === "npm" && NPM_SHORTHANDS.includes(args[0]))
|
|
75
|
+
? args
|
|
76
|
+
: undefined;
|
|
77
|
+
const rest = named ?? bare;
|
|
47
78
|
// A pure delegation is exactly the runner and one known script name.
|
|
48
|
-
if (rest
|
|
79
|
+
if (rest?.length === 1 && scripts.has(rest[0]))
|
|
49
80
|
return rest[0];
|
|
50
81
|
return undefined;
|
|
51
82
|
}
|
|
@@ -66,6 +97,7 @@ export function parseMakefile(text) {
|
|
|
66
97
|
name: current.name,
|
|
67
98
|
command: current.recipe.join(" && "),
|
|
68
99
|
deps: current.deps,
|
|
100
|
+
sequential: false,
|
|
69
101
|
});
|
|
70
102
|
}
|
|
71
103
|
current = undefined;
|
|
@@ -100,24 +132,65 @@ export function parseMakefile(text) {
|
|
|
100
132
|
function stripRecipePrefix(recipe) {
|
|
101
133
|
return recipe.replace(/^[@-]+/, "");
|
|
102
134
|
}
|
|
135
|
+
/**
|
|
136
|
+
* The call that runs `argv` with its tool found as `resolution` says: a typed
|
|
137
|
+
* wrapper's task when one runs the command, else `CmdTasks.exec`. A setting
|
|
138
|
+
* appears only where it changes something: the wrapper's own resolution is not
|
|
139
|
+
* repeated, and a command with no arguments takes no `.args()`.
|
|
140
|
+
*/
|
|
141
|
+
function runCall(argv, resolution, stdout) {
|
|
142
|
+
const match = wrapperFor(argv);
|
|
143
|
+
const [bin, ...args] = argv;
|
|
144
|
+
const [callee, own, rest, head] = match === undefined
|
|
145
|
+
? ["CmdTasks.exec", "path", args, [literal(bin)]]
|
|
146
|
+
: [
|
|
147
|
+
`${match.row.object}.${match.row.method}`,
|
|
148
|
+
match.row.resolution,
|
|
149
|
+
match.rest,
|
|
150
|
+
[],
|
|
151
|
+
];
|
|
152
|
+
const settings = [];
|
|
153
|
+
if (own !== resolution) {
|
|
154
|
+
settings.push(resolution === "node_modules" ? "fromNodeModules()" : "fromPath()");
|
|
155
|
+
}
|
|
156
|
+
if (rest.length > 0)
|
|
157
|
+
settings.push(`args(${rest.map(literal).join(", ")})`);
|
|
158
|
+
if (stdout !== undefined) {
|
|
159
|
+
const append = stdout.append ? ", (w) => w.append()" : "";
|
|
160
|
+
settings.push(`stdoutToFile(${literal(stdout.path)}${append})`);
|
|
161
|
+
}
|
|
162
|
+
const params = settings.length === 0
|
|
163
|
+
? head
|
|
164
|
+
: [...head, `(s) => s.${settings.join(".")}`];
|
|
165
|
+
const uses = match === undefined
|
|
166
|
+
? { specifier: "@zuke/cmd", name: "CmdTasks" }
|
|
167
|
+
: { specifier: `@zuke/${match.row.pkg}`, name: match.row.object };
|
|
168
|
+
return {
|
|
169
|
+
code: `${callee}(${params.join(", ")})`,
|
|
170
|
+
runnable: true,
|
|
171
|
+
uses: [uses],
|
|
172
|
+
};
|
|
173
|
+
}
|
|
103
174
|
/**
|
|
104
175
|
* Translate a shell command into target-body statements: each `&&`-separated
|
|
105
|
-
* segment becomes a `CmdTasks.exec(...)` call
|
|
106
|
-
*
|
|
176
|
+
* segment becomes a typed wrapper's task or a `CmdTasks.exec(...)` call whose
|
|
177
|
+
* tool resolves as `resolution` says (`"node_modules"` for a `package.json`
|
|
178
|
+
* script, as `npm run` finds it; `"path"` for a Makefile), or a `// TODO`
|
|
179
|
+
* comment preserving the raw text when it is too shell-specific to translate.
|
|
107
180
|
*/
|
|
108
|
-
export function translateCommand(command) {
|
|
181
|
+
export function translateCommand(command, resolution) {
|
|
109
182
|
return segments(command).map((segment) => {
|
|
110
|
-
if ("
|
|
111
|
-
return
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
};
|
|
183
|
+
if ("argv" in segment)
|
|
184
|
+
return runCall(segment.argv, resolution);
|
|
185
|
+
if ("redirect" in segment) {
|
|
186
|
+
const { argv, path, append } = segment.redirect;
|
|
187
|
+
return runCall(argv, resolution, { path, append });
|
|
115
188
|
}
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
:
|
|
120
|
-
|
|
189
|
+
return {
|
|
190
|
+
code: `// TODO: translate this shell command: ${oneLine(segment.raw)}`,
|
|
191
|
+
runnable: false,
|
|
192
|
+
uses: [],
|
|
193
|
+
};
|
|
121
194
|
});
|
|
122
195
|
}
|
|
123
196
|
// --- identifiers ----------------------------------------------------------
|
|
@@ -151,38 +224,83 @@ function renderBody(items) {
|
|
|
151
224
|
return `${runnable ? "async " : ""}() => {\n${lines}\n }`;
|
|
152
225
|
}
|
|
153
226
|
/**
|
|
154
|
-
*
|
|
227
|
+
* The names a target field cannot take: every member a build inherits from
|
|
228
|
+
* {@link Build} (`extraEdges`, `onStart`, …, and `constructor`), since a field
|
|
229
|
+
* of that name would shadow it — or, for `extraEdges`, collide with the
|
|
230
|
+
* override the generator writes.
|
|
231
|
+
*/
|
|
232
|
+
const RESERVED = new Set(Object.getOwnPropertyNames(Build.prototype));
|
|
233
|
+
/** The import statements for `uses`: `@zuke/core` first, then by specifier. */
|
|
234
|
+
function importStatements(uses, typeOnly) {
|
|
235
|
+
const names = new Map([
|
|
236
|
+
["@zuke/core", new Set(["Build", "run", "target"])],
|
|
237
|
+
]);
|
|
238
|
+
for (const use of uses) {
|
|
239
|
+
const set = names.get(use.specifier) ?? new Set();
|
|
240
|
+
set.add(use.name);
|
|
241
|
+
names.set(use.specifier, set);
|
|
242
|
+
}
|
|
243
|
+
for (const use of typeOnly)
|
|
244
|
+
names.get(use.specifier)?.add(`type ${use.name}`);
|
|
245
|
+
const bare = (name) => name.replace(/^type /, "");
|
|
246
|
+
const specifiers = [...names.keys()].filter((s) => s !== "@zuke/core").sort();
|
|
247
|
+
return ["@zuke/core", ...specifiers].map((specifier) => {
|
|
248
|
+
const list = [...(names.get(specifier) ?? [])]
|
|
249
|
+
.sort((a, b) => bare(a) < bare(b) ? -1 : bare(a) > bare(b) ? 1 : 0);
|
|
250
|
+
return `import { ${list.join(", ")} } from "${specifier}";`;
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* Generate a `zuke.ts` build class named `className` from imported tasks, each
|
|
255
|
+
* command's tool resolved as `resolution` says (see {@link translateCommand}).
|
|
155
256
|
* Exposed for tools and tests; {@link runImport} writes the result to disk.
|
|
156
257
|
*/
|
|
157
|
-
export function generateBuild(className, raw) {
|
|
158
|
-
const { ordered, dropped } = order(normalize(raw, toIdentifier,
|
|
159
|
-
const
|
|
160
|
-
const
|
|
258
|
+
export function generateBuild(className, raw, resolution) {
|
|
259
|
+
const { ordered, dropped } = order(normalize(raw, toIdentifier, RESERVED));
|
|
260
|
+
const sequence = sequenceEdges(ordered);
|
|
261
|
+
const bodies = new Map(ordered.map((t) => [t.id, translateCommand(t.task.command, resolution)]));
|
|
262
|
+
const uses = [...bodies.values()].flatMap((b) => b.flatMap((i) => i.uses));
|
|
263
|
+
const ref = (id) => `this.${id}`;
|
|
161
264
|
const fields = ordered.map((task) => {
|
|
162
265
|
const body = bodies.get(task.id) ?? [];
|
|
163
266
|
const chain = [` ${task.id} = target()`];
|
|
164
267
|
chain.push(` .description(${literal(`imported: ${task.task.name}`)})`);
|
|
165
268
|
if (task.deps.length > 0) {
|
|
166
|
-
|
|
167
|
-
chain.push(` .dependsOn(${refs})`);
|
|
269
|
+
chain.push(` .dependsOn(${task.deps.map(ref).join(", ")})`);
|
|
168
270
|
}
|
|
169
271
|
const skipped = dropped.get(task.id);
|
|
170
272
|
if (skipped !== undefined && skipped.length > 0) {
|
|
171
|
-
chain.push(` // TODO: dependency cycle — dropped .dependsOn(${skipped.map(
|
|
273
|
+
chain.push(` // TODO: dependency cycle — dropped .dependsOn(${skipped.map(ref).join(", ")})`);
|
|
274
|
+
}
|
|
275
|
+
for (const { edge: [before, after] } of sequence.dropped.filter((d) => d.task === task.id)) {
|
|
276
|
+
chain.push(` // TODO: ordering cycle — another script runs ${after} before ` +
|
|
277
|
+
`${before}, so ${before} is not kept before ${after} here`);
|
|
172
278
|
}
|
|
173
279
|
chain.push(` .executes(${renderBody(body)});`);
|
|
174
280
|
return chain.join("\n");
|
|
175
281
|
});
|
|
282
|
+
if (sequence.kept.length > 0) {
|
|
283
|
+
const pairs = sequence.kept
|
|
284
|
+
.map(([before, after]) => ` [${ref(before)}, ${ref(after)}],`)
|
|
285
|
+
.join("\n");
|
|
286
|
+
fields.push(` /** Run each imported \`&&\` chain's scripts in the order it lists them. */
|
|
287
|
+
override extraEdges(): OrderingEdge[] {
|
|
288
|
+
return [
|
|
289
|
+
${pairs}
|
|
290
|
+
];
|
|
291
|
+
}`);
|
|
292
|
+
}
|
|
176
293
|
// Import by bare specifier and declare the `jsr:` dependency in `deno.json`,
|
|
177
294
|
// exactly as `zuke setup` scaffolds it — an inline `jsr:` specifier trips
|
|
178
295
|
// Deno's default `no-import-prefix` lint rule on the generated file. The
|
|
179
296
|
// caret-major pin lives in the map, via the one definition of it.
|
|
180
297
|
const imports = { ...STARTER_IMPORTS };
|
|
181
|
-
const
|
|
182
|
-
|
|
183
|
-
imports["@zuke/cmd"] = zukeDependency("cmd");
|
|
184
|
-
lines.push(`import { CmdTasks } from "@zuke/cmd";`);
|
|
298
|
+
for (const { specifier } of uses) {
|
|
299
|
+
imports[specifier] = zukeDependency(specifier.replace(/^@zuke\//, ""));
|
|
185
300
|
}
|
|
301
|
+
const lines = importStatements(uses, sequence.kept.length > 0
|
|
302
|
+
? [{ specifier: "@zuke/core", name: "OrderingEdge" }]
|
|
303
|
+
: []);
|
|
186
304
|
const body = fields.length > 0
|
|
187
305
|
? fields.join("\n\n")
|
|
188
306
|
: " // No tasks were found to import — add targets here.";
|
|
@@ -197,9 +315,9 @@ await run(${className});
|
|
|
197
315
|
`;
|
|
198
316
|
return { source, imports };
|
|
199
317
|
}
|
|
200
|
-
/** Translate tasks into a `zuke.ts
|
|
201
|
-
function typescript(tasks, name) {
|
|
202
|
-
const generated = generateBuild(name, tasks);
|
|
318
|
+
/** Translate tasks into a `zuke.ts`, their tools resolved as `resolution` says. */
|
|
319
|
+
function typescript(tasks, name, resolution) {
|
|
320
|
+
const generated = generateBuild(name, tasks, resolution);
|
|
203
321
|
return {
|
|
204
322
|
taskCount: tasks.length,
|
|
205
323
|
buildContent: generated.source,
|
|
@@ -212,12 +330,13 @@ const SOURCE_FILES = [
|
|
|
212
330
|
{
|
|
213
331
|
source: "package.json",
|
|
214
332
|
file: "package.json",
|
|
215
|
-
|
|
333
|
+
// `npm run` puts node_modules/.bin ahead of PATH; make does not.
|
|
334
|
+
translate: (text, name) => typescript(parsePackageJson(text), name, "node_modules"),
|
|
216
335
|
},
|
|
217
336
|
{
|
|
218
337
|
source: "Makefile",
|
|
219
338
|
file: "Makefile",
|
|
220
|
-
translate: (text, name) => typescript(parseMakefile(text), name),
|
|
339
|
+
translate: (text, name) => typescript(parseMakefile(text), name, "path"),
|
|
221
340
|
},
|
|
222
341
|
{
|
|
223
342
|
source: "pyproject.toml",
|
|
@@ -274,8 +393,14 @@ export async function runImport(options, host) {
|
|
|
274
393
|
runtime: translation.python ? undefined : options.runtime,
|
|
275
394
|
sdk: translation.python ? { pin: await options.pin() } : undefined,
|
|
276
395
|
}, host);
|
|
396
|
+
// The build file is scaffolded first; only a file import wrote is news.
|
|
397
|
+
const [written] = setup.files;
|
|
398
|
+
const note = translation.python || written.status === "skipped"
|
|
399
|
+
? undefined
|
|
400
|
+
: await formatterNote(options.dir, written.path, host);
|
|
277
401
|
return {
|
|
278
402
|
...setup,
|
|
403
|
+
notes: note === undefined ? setup.notes : [...setup.notes, note],
|
|
279
404
|
source: candidate.source,
|
|
280
405
|
taskCount: translation.taskCount,
|
|
281
406
|
};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The note `zuke import` prints when the project formats or lints its code
|
|
3
|
+
* with a tool of its own. The generated build file follows Zuke's layout, not
|
|
4
|
+
* the project's, so the project's own `prettier --check .` or `eslint` flags it
|
|
5
|
+
* on the first run. Import does not run the tool itself: that would execute
|
|
6
|
+
* whatever the project installed while scaffolding, so it names the command
|
|
7
|
+
* instead.
|
|
8
|
+
*
|
|
9
|
+
* @module
|
|
10
|
+
*/
|
|
11
|
+
import { type SetupHost } from "./setup.ts";
|
|
12
|
+
/**
|
|
13
|
+
* The note for `file`, the build file import just wrote into `dir`, or
|
|
14
|
+
* `undefined` when the project's `package.json` declares none of the tools
|
|
15
|
+
* above (or is missing or unreadable, which leaves nothing to say).
|
|
16
|
+
*/
|
|
17
|
+
export declare function formatterNote(dir: string, file: string, host: SetupHost): Promise<string | undefined>;
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// Copyright (c) 2026 the Zuke contributors
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
/**
|
|
4
|
+
* The note `zuke import` prints when the project formats or lints its code
|
|
5
|
+
* with a tool of its own. The generated build file follows Zuke's layout, not
|
|
6
|
+
* the project's, so the project's own `prettier --check .` or `eslint` flags it
|
|
7
|
+
* on the first run. Import does not run the tool itself: that would execute
|
|
8
|
+
* whatever the project installed while scaffolding, so it names the command
|
|
9
|
+
* instead.
|
|
10
|
+
*
|
|
11
|
+
* @module
|
|
12
|
+
*/
|
|
13
|
+
import { isRecord, joinPath } from "./setup.js";
|
|
14
|
+
/** A formatter or linter, by the package that installs it, and how it fixes one file. */
|
|
15
|
+
const TOOLS = [
|
|
16
|
+
{ pkg: "prettier", fix: (file) => `npx prettier --write ${file}` },
|
|
17
|
+
{ pkg: "@biomejs/biome", fix: (file) => `npx biome check --write ${file}` },
|
|
18
|
+
{ pkg: "dprint", fix: (file) => `npx dprint fmt ${file}` },
|
|
19
|
+
{ pkg: "eslint", fix: (file) => `npx eslint --fix ${file}` },
|
|
20
|
+
{ pkg: "oxlint", fix: (file) => `npx oxlint --fix ${file}` },
|
|
21
|
+
];
|
|
22
|
+
/**
|
|
23
|
+
* The note for `file`, the build file import just wrote into `dir`, or
|
|
24
|
+
* `undefined` when the project's `package.json` declares none of the tools
|
|
25
|
+
* above (or is missing or unreadable, which leaves nothing to say).
|
|
26
|
+
*/
|
|
27
|
+
export async function formatterNote(dir, file, host) {
|
|
28
|
+
const path = joinPath(dir, "package.json");
|
|
29
|
+
if (!(await host.exists(path)) || await host.isSymlink(path)) {
|
|
30
|
+
return undefined;
|
|
31
|
+
}
|
|
32
|
+
let parsed;
|
|
33
|
+
try {
|
|
34
|
+
parsed = JSON.parse(await host.readText(path));
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return undefined;
|
|
38
|
+
}
|
|
39
|
+
if (!isRecord(parsed))
|
|
40
|
+
return undefined;
|
|
41
|
+
const manifest = parsed;
|
|
42
|
+
const declared = (field) => {
|
|
43
|
+
const deps = manifest[field];
|
|
44
|
+
return isRecord(deps) ? Object.keys(deps) : [];
|
|
45
|
+
};
|
|
46
|
+
const names = new Set([
|
|
47
|
+
...declared("dependencies"),
|
|
48
|
+
...declared("devDependencies"),
|
|
49
|
+
]);
|
|
50
|
+
const fixes = TOOLS.filter((t) => names.has(t.pkg)).map((t) => t.fix(file));
|
|
51
|
+
if (fixes.length === 0)
|
|
52
|
+
return undefined;
|
|
53
|
+
return `${file} is generated in Zuke's layout, not this project's style, ` +
|
|
54
|
+
`so the project's own format and lint checks may flag it. Run ` +
|
|
55
|
+
`${fixes.map((f) => `\`${f}\``).join(", then ")} before committing it ` +
|
|
56
|
+
"(they load the project's own config and plugins, so only in a " +
|
|
57
|
+
"repository you trust).";
|
|
58
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The typed wrappers `zuke import` emits in place of `CmdTasks.exec`: which
|
|
3
|
+
* `@zuke/<tool>` task runs a command, so an imported `eslint src` becomes
|
|
4
|
+
* `EslintTasks.lint((s) => s.args("src"))` instead of a generic exec that
|
|
5
|
+
* discards the wrapper's typed flags and tool resolution.
|
|
6
|
+
*
|
|
7
|
+
* A row maps a binary and the subcommand words after it to the task whose
|
|
8
|
+
* settings, left unconfigured, build exactly that argv: `[bin, ...sub]`. The
|
|
9
|
+
* rest of the command rides `.args(...)`, which a wrapper appends after its own
|
|
10
|
+
* arguments, so the translated task spawns the very argv the script did.
|
|
11
|
+
* `tests/import_wrappers_test.ts` checks every row against the real package,
|
|
12
|
+
* argv and resolution mode alike, so a row cannot drift from its wrapper.
|
|
13
|
+
*
|
|
14
|
+
* @module
|
|
15
|
+
*/
|
|
16
|
+
/** Where a wrapper finds its binary when a call does not say. */
|
|
17
|
+
export type Resolution = "node_modules" | "path";
|
|
18
|
+
/** One typed task that runs a command, and how its wrapper resolves the tool. */
|
|
19
|
+
export interface WrapperRow {
|
|
20
|
+
/** The binary, as a script names it (`eslint`, `git`). */
|
|
21
|
+
readonly bin: string;
|
|
22
|
+
/** The subcommand words the task itself supplies (`["run"]` for `vitest run`). */
|
|
23
|
+
readonly sub: readonly string[];
|
|
24
|
+
/** The package's name after `@zuke/` (`eslint`). */
|
|
25
|
+
readonly pkg: string;
|
|
26
|
+
/** The exported `*Tasks` object (`EslintTasks`). */
|
|
27
|
+
readonly object: string;
|
|
28
|
+
/** The task method on it (`lint`). */
|
|
29
|
+
readonly method: string;
|
|
30
|
+
/** The wrapper's own default resolution mode. */
|
|
31
|
+
readonly resolution: Resolution;
|
|
32
|
+
}
|
|
33
|
+
/** Every command a typed wrapper runs as-is; see the module docs. */
|
|
34
|
+
export declare const WRAPPERS: readonly WrapperRow[];
|
|
35
|
+
/** A command matched to a typed task: the row, and the argv left for `.args(...)`. */
|
|
36
|
+
export interface WrapperMatch {
|
|
37
|
+
/** The task that runs the command. */
|
|
38
|
+
readonly row: WrapperRow;
|
|
39
|
+
/** The arguments after the binary and its subcommand words. */
|
|
40
|
+
readonly rest: readonly string[];
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* The typed task that runs `argv`, or `undefined` when no wrapper does. The row
|
|
44
|
+
* with the longest matching subcommand wins, so `tsc --build x` is
|
|
45
|
+
* `TscTasks.build` while `tsc -p x` is `TscTasks.tsc`.
|
|
46
|
+
*/
|
|
47
|
+
export declare function wrapperFor(argv: readonly string[]): WrapperMatch | undefined;
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
// Copyright (c) 2026 the Zuke contributors
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
/** A row for each listed subcommand of one wrapper (`""` for the bare binary). */
|
|
4
|
+
function rows(bin, pkg, object, resolution, methods) {
|
|
5
|
+
return Object.entries(methods).map(([sub, method]) => ({
|
|
6
|
+
bin,
|
|
7
|
+
sub: sub === "" ? [] : sub.split(" "),
|
|
8
|
+
pkg,
|
|
9
|
+
object,
|
|
10
|
+
method,
|
|
11
|
+
resolution,
|
|
12
|
+
}));
|
|
13
|
+
}
|
|
14
|
+
/** The subcommands Terraform and OpenTofu share, and their task names. */
|
|
15
|
+
const IAC_METHODS = {
|
|
16
|
+
init: "init",
|
|
17
|
+
validate: "validate",
|
|
18
|
+
plan: "plan",
|
|
19
|
+
apply: "apply",
|
|
20
|
+
destroy: "destroy",
|
|
21
|
+
fmt: "fmt",
|
|
22
|
+
output: "output",
|
|
23
|
+
};
|
|
24
|
+
/** Every command a typed wrapper runs as-is; see the module docs. */
|
|
25
|
+
export const WRAPPERS = [
|
|
26
|
+
// Tools whose wrapper resolves through node_modules/.bin.
|
|
27
|
+
...rows("eslint", "eslint", "EslintTasks", "node_modules", { "": "lint" }),
|
|
28
|
+
...rows("biome", "biome", "BiomeTasks", "node_modules", {
|
|
29
|
+
check: "check",
|
|
30
|
+
format: "format",
|
|
31
|
+
lint: "lint",
|
|
32
|
+
ci: "ci",
|
|
33
|
+
}),
|
|
34
|
+
...rows("cspell", "cspell", "CspellTasks", "node_modules", { lint: "lint" }),
|
|
35
|
+
...rows("dprint", "dprint", "DprintTasks", "node_modules", {
|
|
36
|
+
fmt: "fmt",
|
|
37
|
+
check: "check",
|
|
38
|
+
}),
|
|
39
|
+
...rows("oxlint", "oxlint", "OxlintTasks", "node_modules", { "": "lint" }),
|
|
40
|
+
...rows("knip", "knip", "KnipTasks", "node_modules", { "": "run" }),
|
|
41
|
+
...rows("dpdm", "dpdm", "DpdmTasks", "node_modules", { "": "analyze" }),
|
|
42
|
+
...rows("lint-staged", "lint-staged", "LintStagedTasks", "node_modules", {
|
|
43
|
+
"": "run",
|
|
44
|
+
}),
|
|
45
|
+
...rows("tsc", "tsc", "TscTasks", "node_modules", {
|
|
46
|
+
"": "tsc",
|
|
47
|
+
"--build": "build",
|
|
48
|
+
}),
|
|
49
|
+
...rows("tsc-alias", "tsc-alias", "TscAliasTasks", "node_modules", {
|
|
50
|
+
"": "run",
|
|
51
|
+
}),
|
|
52
|
+
...rows("tsup", "tsup", "TsupTasks", "node_modules", { "": "build" }),
|
|
53
|
+
...rows("tsdown", "tsdown", "TsdownTasks", "node_modules", {
|
|
54
|
+
"": "build",
|
|
55
|
+
migrate: "migrate",
|
|
56
|
+
}),
|
|
57
|
+
...rows("vite", "vite", "ViteTasks", "node_modules", {
|
|
58
|
+
dev: "dev",
|
|
59
|
+
build: "build",
|
|
60
|
+
preview: "preview",
|
|
61
|
+
}),
|
|
62
|
+
...rows("storybook", "storybook", "StorybookTasks", "node_modules", {
|
|
63
|
+
dev: "dev",
|
|
64
|
+
build: "build",
|
|
65
|
+
}),
|
|
66
|
+
...rows("nest", "nest", "NestTasks", "node_modules", {
|
|
67
|
+
build: "build",
|
|
68
|
+
start: "start",
|
|
69
|
+
info: "info",
|
|
70
|
+
}),
|
|
71
|
+
...rows("jest", "jest", "JestTasks", "node_modules", { "": "run" }),
|
|
72
|
+
...rows("vitest", "vitest", "VitestTasks", "node_modules", { run: "run" }),
|
|
73
|
+
...rows("playwright", "playwright", "PlaywrightTasks", "node_modules", {
|
|
74
|
+
test: "test",
|
|
75
|
+
install: "install",
|
|
76
|
+
"show-report": "showReport",
|
|
77
|
+
codegen: "codegen",
|
|
78
|
+
}),
|
|
79
|
+
...rows("cypress", "cypress", "CypressTasks", "node_modules", {
|
|
80
|
+
run: "run",
|
|
81
|
+
open: "open",
|
|
82
|
+
install: "install",
|
|
83
|
+
verify: "verify",
|
|
84
|
+
info: "info",
|
|
85
|
+
}),
|
|
86
|
+
...rows("husky", "husky", "HuskyTasks", "node_modules", {
|
|
87
|
+
"": "install",
|
|
88
|
+
init: "init",
|
|
89
|
+
}),
|
|
90
|
+
...rows("openapi-ts", "openapi-ts", "OpenapiTsTasks", "node_modules", {
|
|
91
|
+
"": "generate",
|
|
92
|
+
}),
|
|
93
|
+
...rows("orval", "orval", "OrvalTasks", "node_modules", { "": "generate" }),
|
|
94
|
+
...rows("redocly", "redocly", "RedoclyTasks", "node_modules", {
|
|
95
|
+
lint: "lint",
|
|
96
|
+
bundle: "bundle",
|
|
97
|
+
}),
|
|
98
|
+
...rows("release-please", "release-please", "ReleasePleaseTasks", "node_modules", { "release-pr": "releasePr", "github-release": "githubRelease" }),
|
|
99
|
+
// Tools whose wrapper resolves on PATH: the native ones.
|
|
100
|
+
...rows("git", "git", "GitTasks", "path", {
|
|
101
|
+
"": "run",
|
|
102
|
+
init: "init",
|
|
103
|
+
add: "add",
|
|
104
|
+
commit: "commit",
|
|
105
|
+
status: "status",
|
|
106
|
+
branch: "branch",
|
|
107
|
+
tag: "tag",
|
|
108
|
+
push: "push",
|
|
109
|
+
pull: "pull",
|
|
110
|
+
fetch: "fetch",
|
|
111
|
+
remote: "remote",
|
|
112
|
+
"ls-remote": "lsRemote",
|
|
113
|
+
log: "log",
|
|
114
|
+
show: "show",
|
|
115
|
+
diff: "diff",
|
|
116
|
+
"ls-files": "lsFiles",
|
|
117
|
+
"rev-parse": "revParse",
|
|
118
|
+
describe: "describe",
|
|
119
|
+
reset: "reset",
|
|
120
|
+
apply: "apply",
|
|
121
|
+
"for-each-ref": "forEachRef",
|
|
122
|
+
"show-ref": "showRef",
|
|
123
|
+
shortlog: "shortlog",
|
|
124
|
+
}),
|
|
125
|
+
...rows("terraform", "terraform", "TerraformTasks", "path", IAC_METHODS),
|
|
126
|
+
...rows("tofu", "tofu", "TofuTasks", "path", IAC_METHODS),
|
|
127
|
+
];
|
|
128
|
+
/**
|
|
129
|
+
* The typed task that runs `argv`, or `undefined` when no wrapper does. The row
|
|
130
|
+
* with the longest matching subcommand wins, so `tsc --build x` is
|
|
131
|
+
* `TscTasks.build` while `tsc -p x` is `TscTasks.tsc`.
|
|
132
|
+
*/
|
|
133
|
+
export function wrapperFor(argv) {
|
|
134
|
+
const [bin, ...args] = argv;
|
|
135
|
+
let best;
|
|
136
|
+
for (const row of WRAPPERS) {
|
|
137
|
+
if (row.bin !== bin)
|
|
138
|
+
continue;
|
|
139
|
+
if (!row.sub.every((word, i) => args[i] === word))
|
|
140
|
+
continue;
|
|
141
|
+
if (best === undefined || row.sub.length > best.sub.length)
|
|
142
|
+
best = row;
|
|
143
|
+
}
|
|
144
|
+
return best === undefined
|
|
145
|
+
? undefined
|
|
146
|
+
: { row: best, rest: args.slice(best.sub.length) };
|
|
147
|
+
}
|
package/src/python_build.js
CHANGED
|
@@ -145,11 +145,12 @@ function bodyLines(steps) {
|
|
|
145
145
|
run(step.argv);
|
|
146
146
|
else {
|
|
147
147
|
for (const segment of segments(step.command)) {
|
|
148
|
-
if ("
|
|
149
|
-
todo(`translate this shell command: ${segment.raw}`);
|
|
150
|
-
}
|
|
151
|
-
else
|
|
148
|
+
if ("argv" in segment)
|
|
152
149
|
run(segment.argv);
|
|
150
|
+
else {
|
|
151
|
+
const raw = "raw" in segment ? segment.raw : segment.redirect.raw;
|
|
152
|
+
todo(`translate this shell command: ${raw}`);
|
|
153
|
+
}
|
|
153
154
|
}
|
|
154
155
|
}
|
|
155
156
|
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Keep an imported `&&` chain's order. `npm run a && npm run b` runs `a` —
|
|
3
|
+
* with everything `a` runs first — and only then `b`, with everything `b` runs
|
|
4
|
+
* first. A target's dependencies carry no order among themselves, so the
|
|
5
|
+
* executor may run `b` first, or run both at once. For each task whose
|
|
6
|
+
* dependencies came from such a chain, this yields the soft ordering edges the
|
|
7
|
+
* generated build returns from `extraEdges()`: `a` before `b`, and before each
|
|
8
|
+
* of `b`'s own dependencies that `a` does not itself need (so `npm run clean &&
|
|
9
|
+
* npm run compile` cannot have `compile`'s code generator run before `clean`).
|
|
10
|
+
*
|
|
11
|
+
* An edge that would close a cycle — `b` must already run before `a`, through
|
|
12
|
+
* the hard dependencies or an edge already kept (two scripts chaining the same
|
|
13
|
+
* pair in opposite orders cannot both hold) — is dropped and reported. An edge
|
|
14
|
+
* the graph already implies is left out, since it adds nothing.
|
|
15
|
+
*
|
|
16
|
+
* Two limits remain, both noted in the docs. A dependency the shell would run
|
|
17
|
+
* twice (once under `a`, again under `b`) runs once. And a soft edge orders the
|
|
18
|
+
* pair in every run that includes both, not only in the script that asked.
|
|
19
|
+
*
|
|
20
|
+
* @module
|
|
21
|
+
*/
|
|
22
|
+
import type { Named } from "./translate.ts";
|
|
23
|
+
/** A soft ordering edge between two target ids: the first runs before the second. */
|
|
24
|
+
export type Edge = readonly [before: string, after: string];
|
|
25
|
+
/** An edge {@link sequenceEdges} could not keep, and the task whose chain asked for it. */
|
|
26
|
+
export interface DroppedEdge {
|
|
27
|
+
/** The edge that would have closed a cycle. */
|
|
28
|
+
readonly edge: Edge;
|
|
29
|
+
/** The id of the task whose `&&` chain implied it. */
|
|
30
|
+
readonly task: string;
|
|
31
|
+
}
|
|
32
|
+
/** The ordering edges an import keeps, and the ones it had to drop. */
|
|
33
|
+
export interface SequenceEdges {
|
|
34
|
+
/** The edges to emit, in a deterministic order. */
|
|
35
|
+
readonly kept: readonly Edge[];
|
|
36
|
+
/** The edges that would have closed a cycle. */
|
|
37
|
+
readonly dropped: readonly DroppedEdge[];
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* The soft edges that make each sequential task's dependencies run in the order
|
|
41
|
+
* listed. `tasks` is the declaration order from `order()`: every dependency id
|
|
42
|
+
* names a task in it.
|
|
43
|
+
*/
|
|
44
|
+
export declare function sequenceEdges<T extends {
|
|
45
|
+
readonly sequential: boolean;
|
|
46
|
+
}>(tasks: readonly Named<T>[]): SequenceEdges;
|
package/src/sequence.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// Copyright (c) 2026 the Zuke contributors
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
/**
|
|
4
|
+
* The soft edges that make each sequential task's dependencies run in the order
|
|
5
|
+
* listed. `tasks` is the declaration order from `order()`: every dependency id
|
|
6
|
+
* names a task in it.
|
|
7
|
+
*/
|
|
8
|
+
export function sequenceEdges(tasks) {
|
|
9
|
+
// "Runs before" successors: a hard dependency runs before its dependent.
|
|
10
|
+
const next = new Map(tasks.map((t) => [t.id, []]));
|
|
11
|
+
const prev = new Map(tasks.map((t) => [t.id, []]));
|
|
12
|
+
const link = (before, after) => {
|
|
13
|
+
next.get(before)?.push(after);
|
|
14
|
+
prev.get(after)?.push(before);
|
|
15
|
+
};
|
|
16
|
+
for (const task of tasks) {
|
|
17
|
+
for (const dep of task.deps)
|
|
18
|
+
link(dep, task.id);
|
|
19
|
+
}
|
|
20
|
+
/** `from` and every id reachable from it along `edges`. */
|
|
21
|
+
const closure = (from, edges) => {
|
|
22
|
+
const seen = new Set();
|
|
23
|
+
const stack = [from];
|
|
24
|
+
for (let id = stack.pop(); id !== undefined; id = stack.pop()) {
|
|
25
|
+
if (seen.has(id))
|
|
26
|
+
continue;
|
|
27
|
+
seen.add(id);
|
|
28
|
+
stack.push(...(edges.get(id) ?? []));
|
|
29
|
+
}
|
|
30
|
+
return seen;
|
|
31
|
+
};
|
|
32
|
+
const kept = [];
|
|
33
|
+
const dropped = [];
|
|
34
|
+
for (const task of tasks) {
|
|
35
|
+
if (!task.task.sequential)
|
|
36
|
+
continue;
|
|
37
|
+
for (let i = 1; i < task.deps.length; i++) {
|
|
38
|
+
const before = task.deps[i - 1];
|
|
39
|
+
const after = task.deps[i];
|
|
40
|
+
const needed = closure(before, prev); // `before` and what it runs first
|
|
41
|
+
if (needed.has(after)) {
|
|
42
|
+
dropped.push({ edge: [before, after], task: task.id });
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
// `after` and what it runs first, less what `before` needs anyway — so
|
|
46
|
+
// no edge here can close a cycle — and less what already follows it.
|
|
47
|
+
const follows = closure(before, next);
|
|
48
|
+
for (const id of closure(after, prev)) {
|
|
49
|
+
if (needed.has(id) || follows.has(id))
|
|
50
|
+
continue;
|
|
51
|
+
link(before, id);
|
|
52
|
+
kept.push([before, id]);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return { kept, dropped };
|
|
57
|
+
}
|
package/src/translate.d.ts
CHANGED
|
@@ -1,9 +1,33 @@
|
|
|
1
|
-
/**
|
|
1
|
+
/**
|
|
2
|
+
* One `&&`-separated segment of a command: argv to run, argv whose stdout the
|
|
3
|
+
* shell sends to a file, or text to keep verbatim.
|
|
4
|
+
*/
|
|
2
5
|
export type Segment = {
|
|
3
6
|
readonly argv: readonly string[];
|
|
7
|
+
} | {
|
|
8
|
+
readonly redirect: Redirect;
|
|
4
9
|
} | {
|
|
5
10
|
readonly raw: string;
|
|
6
11
|
};
|
|
12
|
+
/** A segment of the form `cmd args > file`, or `>> file` to append. */
|
|
13
|
+
export interface Redirect {
|
|
14
|
+
/** The command, as argv. */
|
|
15
|
+
readonly argv: readonly string[];
|
|
16
|
+
/** The file its stdout goes to, as written. */
|
|
17
|
+
readonly path: string;
|
|
18
|
+
/** Whether stdout is added to the file (`>>`) rather than replacing it. */
|
|
19
|
+
readonly append: boolean;
|
|
20
|
+
/** The segment as written, for a generator that cannot express it. */
|
|
21
|
+
readonly raw: string;
|
|
22
|
+
}
|
|
23
|
+
/** Whether `segment` uses a shell feature a single argv cannot faithfully express. */
|
|
24
|
+
export declare function needsShell(segment: string): boolean;
|
|
25
|
+
/**
|
|
26
|
+
* The indexes in `segment` of every occurrence of `char` outside quotes. Inside
|
|
27
|
+
* double quotes a backslash escapes the next character, so an escaped quote
|
|
28
|
+
* does not end the quoted run; inside single quotes nothing is escaped.
|
|
29
|
+
*/
|
|
30
|
+
export declare function unquotedIndexes(segment: string, char: string): number[];
|
|
7
31
|
/**
|
|
8
32
|
* Split a shell command into its `&&`-separated segments, each one argv
|
|
9
33
|
* (never empty: a segment is non-blank and holds no backslash), or the raw
|
package/src/translate.js
CHANGED
|
@@ -11,8 +11,8 @@
|
|
|
11
11
|
* @module
|
|
12
12
|
*/
|
|
13
13
|
import { splitShellArgs } from "@zuke/core/shell";
|
|
14
|
-
/**
|
|
15
|
-
function needsShell(segment) {
|
|
14
|
+
/** Whether `segment` uses a shell feature a single argv cannot faithfully express. */
|
|
15
|
+
export function needsShell(segment) {
|
|
16
16
|
// pipe, redirect, subst, env expand, and a newline (a second command)
|
|
17
17
|
if (/[|<>;`$\n\r]/.test(segment))
|
|
18
18
|
return true;
|
|
@@ -20,6 +20,10 @@ function needsShell(segment) {
|
|
|
20
20
|
return true; // background job
|
|
21
21
|
if (hasUnquotedBackslash(segment))
|
|
22
22
|
return true; // escape or Windows separator?
|
|
23
|
+
// A `#` opening a word starts a comment: the shell ignores the rest.
|
|
24
|
+
if (unquotedIndexes(segment, "#").some((i) => i === 0 || /\s/.test(segment[i - 1]))) {
|
|
25
|
+
return true;
|
|
26
|
+
}
|
|
23
27
|
const first = segment.trim().split(/\s+/)[0] ?? "";
|
|
24
28
|
return /^[A-Za-z_][A-Za-z0-9_]*=/.test(first); // leading VAR=value assignment
|
|
25
29
|
}
|
|
@@ -33,24 +37,30 @@ function needsShell(segment) {
|
|
|
33
37
|
* unambiguous and stays translatable.
|
|
34
38
|
*/
|
|
35
39
|
function hasUnquotedBackslash(segment) {
|
|
40
|
+
return unquotedIndexes(segment, "\\").length > 0;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* The indexes in `segment` of every occurrence of `char` outside quotes. Inside
|
|
44
|
+
* double quotes a backslash escapes the next character, so an escaped quote
|
|
45
|
+
* does not end the quoted run; inside single quotes nothing is escaped.
|
|
46
|
+
*/
|
|
47
|
+
export function unquotedIndexes(segment, char) {
|
|
48
|
+
const at = [];
|
|
36
49
|
let quote;
|
|
37
50
|
for (let i = 0; i < segment.length; i++) {
|
|
38
51
|
const ch = segment[i];
|
|
39
52
|
if (quote !== undefined) {
|
|
40
|
-
// Inside double quotes a backslash escapes the next character, so skip it
|
|
41
|
-
// and keep tracking the quote state accurately.
|
|
42
53
|
if (quote === '"' && ch === "\\")
|
|
43
54
|
i++;
|
|
44
55
|
else if (ch === quote)
|
|
45
56
|
quote = undefined;
|
|
46
|
-
continue;
|
|
47
57
|
}
|
|
48
|
-
if (ch === '"' || ch === "'")
|
|
58
|
+
else if (ch === '"' || ch === "'")
|
|
49
59
|
quote = ch;
|
|
50
|
-
else if (ch ===
|
|
51
|
-
|
|
60
|
+
else if (ch === char)
|
|
61
|
+
at.push(i);
|
|
52
62
|
}
|
|
53
|
-
return
|
|
63
|
+
return at;
|
|
54
64
|
}
|
|
55
65
|
/**
|
|
56
66
|
* Split a shell command into its `&&`-separated segments, each one argv
|
|
@@ -64,11 +74,50 @@ export function segments(command) {
|
|
|
64
74
|
const segment = raw.trim();
|
|
65
75
|
if (segment === "")
|
|
66
76
|
continue;
|
|
67
|
-
|
|
68
|
-
out.push(argv === undefined ? { raw: segment } : { argv });
|
|
77
|
+
out.push(parseSegment(segment));
|
|
69
78
|
}
|
|
70
79
|
return out;
|
|
71
80
|
}
|
|
81
|
+
/** One non-blank segment, as {@link segments} classifies it. */
|
|
82
|
+
function parseSegment(segment) {
|
|
83
|
+
if (!needsShell(segment)) {
|
|
84
|
+
const argv = tokenize(segment);
|
|
85
|
+
return argv === undefined ? { raw: segment } : { argv };
|
|
86
|
+
}
|
|
87
|
+
const redirect = redirected(segment);
|
|
88
|
+
return redirect === undefined ? { raw: segment } : { redirect };
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* `segment` as a command whose stdout goes to a file, or `undefined` unless
|
|
92
|
+
* that is all the shell does with it: exactly one unquoted `>` or `>>`, after
|
|
93
|
+
* whitespace (so neither `2>` nor `&>`), followed by a single plain word that
|
|
94
|
+
* is the last thing on the line, with a command before it that needs no shell
|
|
95
|
+
* itself. A target the shell would expand (`$`, `~`, a glob), an fd target
|
|
96
|
+
* (`>&2`), a clobber (`>|`) or a parenthesis anywhere (a subshell to `sh`)
|
|
97
|
+
* leaves the segment verbatim.
|
|
98
|
+
*/
|
|
99
|
+
function redirected(segment) {
|
|
100
|
+
const at = unquotedIndexes(segment, ">");
|
|
101
|
+
const append = at.length === 2 && at[1] === at[0] + 1;
|
|
102
|
+
if (at.length !== 1 && !append)
|
|
103
|
+
return undefined;
|
|
104
|
+
const start = at[0];
|
|
105
|
+
if (start === 0 || !/\s/.test(segment[start - 1]))
|
|
106
|
+
return undefined;
|
|
107
|
+
const command = segment.slice(0, start);
|
|
108
|
+
const target = segment.slice(at[at.length - 1] + 1);
|
|
109
|
+
if (needsShell(command) || needsShell(target))
|
|
110
|
+
return undefined;
|
|
111
|
+
if (/[~*?[{&]/.test(target) || /[()]/.test(segment))
|
|
112
|
+
return undefined;
|
|
113
|
+
const argv = tokenize(command);
|
|
114
|
+
const path = tokenize(target);
|
|
115
|
+
if (argv === undefined)
|
|
116
|
+
return undefined;
|
|
117
|
+
if (path === undefined || path.length !== 1)
|
|
118
|
+
return undefined;
|
|
119
|
+
return { argv, path: path[0], append, raw: segment };
|
|
120
|
+
}
|
|
72
121
|
/** Split a command on top-level `&&`, ignoring `&&` inside quotes. */
|
|
73
122
|
export function splitChain(command) {
|
|
74
123
|
const parts = [];
|
package/src/version.js
CHANGED