@zuke-build/cli 0.0.0-stage → 2.6.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.
Files changed (68) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +343 -2
  3. package/mod.d.ts +99 -0
  4. package/mod.js +893 -0
  5. package/package.json +35 -4
  6. package/src/binary_launcher.d.ts +49 -0
  7. package/src/binary_launcher.js +327 -0
  8. package/src/binary_pin.d.ts +47 -0
  9. package/src/binary_pin.js +117 -0
  10. package/src/build_file.d.ts +25 -0
  11. package/src/build_file.js +65 -0
  12. package/src/cache.d.ts +23 -0
  13. package/src/cache.js +26 -0
  14. package/src/deno_isolated.d.ts +14 -0
  15. package/src/deno_isolated.js +70 -0
  16. package/src/deno_path.d.ts +115 -0
  17. package/src/deno_path.js +205 -0
  18. package/src/deno_pin.d.ts +37 -0
  19. package/src/deno_pin.js +32 -0
  20. package/src/dependencies.d.ts +48 -0
  21. package/src/dependencies.js +80 -0
  22. package/src/dispatch.d.ts +220 -0
  23. package/src/dispatch.js +538 -0
  24. package/src/embedded_engine.d.ts +28 -0
  25. package/src/embedded_engine.js +21 -0
  26. package/src/engine_pin.d.ts +56 -0
  27. package/src/engine_pin.js +196 -0
  28. package/src/fs.d.ts +14 -0
  29. package/src/fs.js +25 -0
  30. package/src/import.d.ts +132 -0
  31. package/src/import.js +289 -0
  32. package/src/install_source.d.ts +79 -0
  33. package/src/install_source.js +104 -0
  34. package/src/launcher.d.ts +37 -0
  35. package/src/launcher.js +464 -0
  36. package/src/mcp_config.d.ts +63 -0
  37. package/src/mcp_config.js +86 -0
  38. package/src/output.d.ts +38 -0
  39. package/src/output.js +43 -0
  40. package/src/paint.d.ts +42 -0
  41. package/src/paint.js +38 -0
  42. package/src/project.d.ts +69 -0
  43. package/src/project.js +132 -0
  44. package/src/pyproject.d.ts +30 -0
  45. package/src/pyproject.js +156 -0
  46. package/src/python_build.d.ts +27 -0
  47. package/src/python_build.js +197 -0
  48. package/src/records.d.ts +9 -0
  49. package/src/records.js +13 -0
  50. package/src/relock.d.ts +11 -0
  51. package/src/relock.js +182 -0
  52. package/src/setup.d.ts +251 -0
  53. package/src/setup.js +601 -0
  54. package/src/star.d.ts +44 -0
  55. package/src/star.js +100 -0
  56. package/src/starter.d.ts +55 -0
  57. package/src/starter.js +126 -0
  58. package/src/toml.d.ts +32 -0
  59. package/src/toml.js +354 -0
  60. package/src/translate.d.ts +69 -0
  61. package/src/translate.js +198 -0
  62. package/src/upgrade.d.ts +113 -0
  63. package/src/upgrade.js +344 -0
  64. package/src/version.d.ts +11 -0
  65. package/src/version.js +13 -0
  66. package/src/version_report.d.ts +55 -0
  67. package/src/version_report.js +187 -0
  68. package/zuke.js +8 -0
@@ -0,0 +1,156 @@
1
+ // Copyright (c) 2026 the Zuke contributors
2
+ // SPDX-License-Identifier: MIT
3
+ /**
4
+ * `zuke import`'s reader for a Python project: the task table of a
5
+ * `pyproject.toml`, turned into tasks the Python generator renders.
6
+ *
7
+ * The first of these tables present is read, each mapping a name to a task:
8
+ * `[tool.poe.tasks]` (poethepoet), `[tool.pdm.scripts]`,
9
+ * `[tool.hatch.envs.default.scripts]`, `[tool.taskipy.tasks]` and
10
+ * `[tool.rye.scripts]`. A task is a command string; an array of steps (hatch
11
+ * scripts, poe's sequence shorthand); or a table whose `cmd` (a string, or an
12
+ * argv array) or `shell` is the command and whose `sequence` (poe),
13
+ * `composite` (pdm) or `chain` (rye) lists steps. A step that names another
14
+ * task — and a poe `deps` entry, or a `ref` that names one — becomes a
15
+ * dependency, unless a command comes before it: a dependency would run it
16
+ * first, so it stays a `TODO` in its place. Any other step is a command. What no command expresses (a
17
+ * Python `call`/`script`, an `expr`, a `ref` with arguments, a task runner's
18
+ * `{args}` placeholder) is kept verbatim as a step the generator writes as a
19
+ * `TODO` comment. Settings such as `help` and `env` are not carried over.
20
+ *
21
+ * @module
22
+ */
23
+ import { isRecord } from "./records.js";
24
+ import { parseToml } from "./toml.js";
25
+ /** The task tables read, in the order they are looked for. */
26
+ const TABLES = [
27
+ ["tool", "poe", "tasks"],
28
+ ["tool", "pdm", "scripts"],
29
+ ["tool", "hatch", "envs", "default", "scripts"],
30
+ ["tool", "taskipy", "tasks"],
31
+ ["tool", "rye", "scripts"],
32
+ ];
33
+ /** A runner placeholder (`{args}`, `{args:tests}`, `{env:HOME}`) no argv carries. */
34
+ const PLACEHOLDER = /\{[^{}]*\}/;
35
+ /**
36
+ * Parse a `pyproject.toml` document into tasks, in declaration order, from
37
+ * the first task table it carries. No task table: no tasks.
38
+ *
39
+ * @throws {Error} naming the line, when the document is not TOML this reads.
40
+ */
41
+ export function parsePyproject(text) {
42
+ let document;
43
+ try {
44
+ document = parseToml(text);
45
+ }
46
+ catch (error) {
47
+ // parseToml throws only its own SyntaxError, which names the line.
48
+ throw new Error(`zuke import: cannot read pyproject.toml — ${error instanceof Error ? error.message : String(error)}`);
49
+ }
50
+ const table = TABLES.map((path) => lookup(document, path)).find(isRecord);
51
+ if (table === undefined)
52
+ return [];
53
+ // pdm keeps options shared by every script under `_`; it is not a task.
54
+ const entries = Object.entries(table).filter(([name]) => name !== "_");
55
+ const names = new Set(entries.map(([name]) => name));
56
+ return entries.map(([name, value]) => {
57
+ const draft = { steps: [], deps: [] };
58
+ readTask(value, names, draft);
59
+ return { name, ...draft };
60
+ });
61
+ }
62
+ /** The value at `path` under `value`, or `undefined` when any step is missing. */
63
+ function lookup(value, path) {
64
+ let current = value;
65
+ for (const key of path) {
66
+ if (!isRecord(current) || !Object.hasOwn(current, key))
67
+ return undefined;
68
+ current = current[key];
69
+ }
70
+ return current;
71
+ }
72
+ /** Read one task definition (a string, an array of steps, or a table) into `into`. */
73
+ function readTask(value, names, into) {
74
+ if (typeof value === "string")
75
+ command(value, into);
76
+ else if (Array.isArray(value))
77
+ steps(value, names, into);
78
+ else if (isRecord(value))
79
+ readTable(value, names, into);
80
+ else {
81
+ into.steps.push({
82
+ todo: `translate this task: ${JSON.stringify(value)}`,
83
+ });
84
+ }
85
+ }
86
+ /** Read a list of steps: a name of another task is a dependency. */
87
+ function steps(list, names, into) {
88
+ for (const item of list) {
89
+ if (typeof item === "string" && names.has(item))
90
+ runTask(item, into);
91
+ else
92
+ readTask(item, names, into);
93
+ }
94
+ }
95
+ /** Read a task's table form, by whichever key names its kind. */
96
+ function readTable(table, names, into) {
97
+ // poe runs a task's `deps` before it, whatever its kind.
98
+ if (Array.isArray(table.deps)) {
99
+ for (const dep of table.deps) {
100
+ if (typeof dep === "string" && names.has(dep))
101
+ dependOn(dep, into);
102
+ }
103
+ }
104
+ const { cmd, shell, ref } = table;
105
+ const list = table.sequence ?? table.composite ?? table.chain;
106
+ if (typeof cmd === "string")
107
+ command(cmd, into);
108
+ else if (isStringArray(cmd))
109
+ argv(cmd, into);
110
+ else if (typeof shell === "string")
111
+ command(shell, into);
112
+ else if (Array.isArray(list))
113
+ steps(list, names, into);
114
+ else if (typeof ref === "string" && names.has(ref))
115
+ runTask(ref, into);
116
+ else {
117
+ into.steps.push({ todo: `translate this task: ${JSON.stringify(table)}` });
118
+ }
119
+ }
120
+ /** A command line, unless it carries a placeholder only the task runner fills. */
121
+ function command(text, into) {
122
+ into.steps.push(PLACEHOLDER.test(text)
123
+ ? { todo: `translate this task runner placeholder: ${text}` }
124
+ : { command: text });
125
+ }
126
+ /** An argv, unless one of its entries carries a placeholder. */
127
+ function argv(list, into) {
128
+ into.steps.push(list.some((arg) => PLACEHOLDER.test(arg))
129
+ ? { todo: `translate this task runner placeholder: ${list.join(" ")}` }
130
+ : { argv: list });
131
+ }
132
+ /**
133
+ * Run another task at this point of the steps. Before any step it is a
134
+ * dependency, which runs first just as it would; after one, a dependency would
135
+ * run it too early, so it is kept in its place as a TODO instead.
136
+ */
137
+ function runTask(name, into) {
138
+ if (into.steps.length === 0)
139
+ dependOn(name, into);
140
+ else {
141
+ into.steps.push({
142
+ todo: `run the ${name} task here; it follows a command, so it is ` +
143
+ "not a dependency",
144
+ });
145
+ }
146
+ }
147
+ /** Record a dependency once. */
148
+ function dependOn(name, into) {
149
+ if (!into.deps.includes(name))
150
+ into.deps.push(name);
151
+ }
152
+ /** Whether `value` is a non-empty array of strings. */
153
+ function isStringArray(value) {
154
+ return Array.isArray(value) && value.length > 0 &&
155
+ value.every((v) => typeof v === "string");
156
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * `zuke import`'s Python generator: the `build.py` a `pyproject.toml`'s tasks
3
+ * translate to, in the shape of `zuke setup --sdk python`'s starter — the
4
+ * same script metadata, `from zuke import …` line, class and `run(...)` —
5
+ * with one `target()` field per task. Each task's commands run in a
6
+ * module-level `async def` body through `await ctx.sh("prog", "arg", …)`,
7
+ * split with the same rules as the TypeScript path; what cannot be translated
8
+ * is kept as a `# TODO` comment. The output is laid out as ruff formats it
9
+ * (4-space indent, double quotes, 88 columns), so a project's own formatter
10
+ * leaves it alone.
11
+ *
12
+ * @module
13
+ */
14
+ import type { PyTask } from "./pyproject.ts";
15
+ /**
16
+ * Turn a task name into a snake_case Python identifier for a target field —
17
+ * `test-watch` → `test_watch`, `buildProd` → `build_prod`, `lint:fix` →
18
+ * `lint_fix`. Falls back to `task` for an empty result and prefixes a leading
19
+ * digit. Never starts or ends with `_`, so no result is private or mangled.
20
+ */
21
+ export declare function toPythonIdentifier(name: string): string;
22
+ /**
23
+ * Generate a `build.py` whose build class is named `className` from tasks a
24
+ * `pyproject.toml` declared. Every string it emits goes through the one
25
+ * escaper (`literal`), and every comment through `oneLine`.
26
+ */
27
+ export declare function generatePythonBuild(className: string, tasks: readonly PyTask[]): string;
@@ -0,0 +1,197 @@
1
+ // Copyright (c) 2026 the Zuke contributors
2
+ // SPDX-License-Identifier: MIT
3
+ import { PYTHON_SCRIPT_METADATA } from "./starter.js";
4
+ import { literal, normalize, oneLine, order, segments } from "./translate.js";
5
+ /** The line length ruff formats to by default. */
6
+ const LINE_LENGTH = 88;
7
+ /**
8
+ * Names a target field may not take: Python's keywords, the `target` the
9
+ * class body calls (a field of that name would shadow it for every field
10
+ * below), and the attributes `zuke.Build` defines itself. A task normalising
11
+ * to one is suffixed with `_` instead.
12
+ */
13
+ const RESERVED = new Set([
14
+ // keyword.kwlist, less the capitalised three no snake_case name can be
15
+ "and",
16
+ "as",
17
+ "assert",
18
+ "async",
19
+ "await",
20
+ "break",
21
+ "class",
22
+ "continue",
23
+ "def",
24
+ "del",
25
+ "elif",
26
+ "else",
27
+ "except",
28
+ "finally",
29
+ "for",
30
+ "from",
31
+ "global",
32
+ "if",
33
+ "import",
34
+ "in",
35
+ "is",
36
+ "lambda",
37
+ "nonlocal",
38
+ "not",
39
+ "or",
40
+ "pass",
41
+ "raise",
42
+ "return",
43
+ "try",
44
+ "while",
45
+ "with",
46
+ "yield",
47
+ // the class body's own name
48
+ "target",
49
+ // zuke.Build's attributes
50
+ "deadline",
51
+ "unforceable",
52
+ "targets_",
53
+ "parameters_",
54
+ "groups_",
55
+ "ci_",
56
+ "on_start",
57
+ "on_target_start",
58
+ "on_target_end",
59
+ "on_finish",
60
+ "hooks_",
61
+ "describe",
62
+ "configure",
63
+ "target_",
64
+ "service_",
65
+ ]);
66
+ /**
67
+ * Turn a task name into a snake_case Python identifier for a target field —
68
+ * `test-watch` → `test_watch`, `buildProd` → `build_prod`, `lint:fix` →
69
+ * `lint_fix`. Falls back to `task` for an empty result and prefixes a leading
70
+ * digit. Never starts or ends with `_`, so no result is private or mangled.
71
+ */
72
+ export function toPythonIdentifier(name) {
73
+ const id = name
74
+ .replace(/([a-z0-9])([A-Z])/g, "$1_$2")
75
+ .split(/[^A-Za-z0-9]+/)
76
+ .filter((word) => word !== "")
77
+ .map((word) => word.toLowerCase())
78
+ .join("_");
79
+ if (id === "")
80
+ return "task";
81
+ return /^[0-9]/.test(id) ? `task_${id}` : id;
82
+ }
83
+ /**
84
+ * Generate a `build.py` whose build class is named `className` from tasks a
85
+ * `pyproject.toml` declared. Every string it emits goes through the one
86
+ * escaper (`literal`), and every comment through `oneLine`.
87
+ */
88
+ export function generatePythonBuild(className, tasks) {
89
+ const { ordered, dropped } = order(normalize(tasks, toPythonIdentifier, RESERVED));
90
+ const functions = [];
91
+ const fields = [];
92
+ for (const { id, task, deps } of ordered) {
93
+ const body = bodyLines(task.steps);
94
+ const fn = body.length > 0 ? `_${id}` : undefined;
95
+ if (fn !== undefined) {
96
+ const def = `async def ${fn}(ctx: Context) -> None:`;
97
+ // ruff explodes a signature that does not fit, with a trailing comma.
98
+ const head = def.length <= LINE_LENGTH
99
+ ? def
100
+ : `async def ${fn}(\n ctx: Context,\n) -> None:`;
101
+ functions.push(`${head}\n${body.join("\n")}`);
102
+ }
103
+ const calls = [
104
+ [".description", [literal(`imported: ${task.name}`)]],
105
+ ];
106
+ if (deps.length > 0)
107
+ calls.push([".depends_on", [...deps]]);
108
+ if (fn !== undefined)
109
+ calls.push([".executes", [fn]]);
110
+ const lines = [];
111
+ const skipped = dropped.get(id);
112
+ if (skipped !== undefined) {
113
+ lines.push(` # TODO: dependency cycle, dropped .depends_on(${skipped.join(", ")})`);
114
+ }
115
+ lines.push(...field(id, calls));
116
+ fields.push(lines.join("\n"));
117
+ }
118
+ const names = functions.length > 0
119
+ ? "Build, Context, run, target"
120
+ : "Build, run, target";
121
+ const members = fields.length > 0
122
+ ? fields.join("\n\n")
123
+ : " # No tasks were found to import, add targets here.";
124
+ const sections = [
125
+ `${PYTHON_SCRIPT_METADATA}"""Imported build: refine these targets into typed Zuke tasks."""\n\nfrom zuke import ${names}`,
126
+ ...functions,
127
+ `class ${className}(Build):\n """The targets imported from pyproject.toml."""\n\n${members}`,
128
+ `run(${className})\n`,
129
+ ];
130
+ return sections.join("\n\n\n");
131
+ }
132
+ /** The statements of a body, indented: `await ctx.sh(...)` and `# TODO` lines. */
133
+ function bodyLines(steps) {
134
+ const lines = [];
135
+ let runnable = false;
136
+ const run = (argv) => {
137
+ runnable = true;
138
+ lines.push(...call(4, "await ctx.sh", argv.map(literal)));
139
+ };
140
+ const todo = (text) => lines.push(` # TODO: ${oneLine(text)}`);
141
+ for (const step of steps) {
142
+ if ("todo" in step)
143
+ todo(step.todo);
144
+ else if ("argv" in step)
145
+ run(step.argv);
146
+ else {
147
+ for (const segment of segments(step.command)) {
148
+ if ("raw" in segment) {
149
+ todo(`translate this shell command: ${segment.raw}`);
150
+ }
151
+ else
152
+ run(segment.argv);
153
+ }
154
+ }
155
+ }
156
+ // A body of comments alone is not a statement Python accepts.
157
+ if (lines.length > 0 && !runnable)
158
+ lines.push(" pass");
159
+ return lines;
160
+ }
161
+ /**
162
+ * A target field, `id = target().description(...)…`, on one line when it
163
+ * fits; otherwise as ruff lays out a long method chain — wrapped in
164
+ * parentheses, one call per line — or, for a lone call, with its argument
165
+ * moved to the next line.
166
+ */
167
+ function field(id, calls) {
168
+ const chain = calls.map(([name, args]) => `${name}(${args.join(", ")})`);
169
+ const flat = ` ${id} = target()${chain.join("")}`;
170
+ if (flat.length <= LINE_LENGTH)
171
+ return [flat];
172
+ if (calls.length === 1) {
173
+ return call(4, `${id} = target()${calls[0][0]}`, calls[0][1]);
174
+ }
175
+ return [
176
+ ` ${id} = (`,
177
+ " target()",
178
+ ...calls.flatMap(([name, args]) => call(8, name, args)),
179
+ " )",
180
+ ];
181
+ }
182
+ /**
183
+ * `head(args)` at `indent` spaces, as ruff splits a call that does not fit:
184
+ * on one line; else the arguments together on the next line; else one per
185
+ * line with a trailing comma. A single argument is never exploded further.
186
+ */
187
+ function call(indent, head, args) {
188
+ const pad = " ".repeat(indent);
189
+ const flat = `${pad}${head}(${args.join(", ")})`;
190
+ if (flat.length <= LINE_LENGTH)
191
+ return [flat];
192
+ const inner = `${pad} ${args.join(", ")}`;
193
+ if (args.length === 1 || inner.length <= LINE_LENGTH) {
194
+ return [`${pad}${head}(`, inner, `${pad})`];
195
+ }
196
+ return [`${pad}${head}(`, ...args.map((a) => `${pad} ${a},`), `${pad})`];
197
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The one JSON-shape guard the scaffolder's file merges share (`deno.json`,
3
+ * `.mcp.json`). Kept apart from both so neither module has to import the
4
+ * other for it.
5
+ *
6
+ * @module
7
+ */
8
+ /** Whether `value` is a plain object (a JSON object, not an array or null). */
9
+ export declare function isRecord(value: unknown): value is Record<string, unknown>;
package/src/records.js ADDED
@@ -0,0 +1,13 @@
1
+ // Copyright (c) 2026 the Zuke contributors
2
+ // SPDX-License-Identifier: MIT
3
+ /**
4
+ * The one JSON-shape guard the scaffolder's file merges share (`deno.json`,
5
+ * `.mcp.json`). Kept apart from both so neither module has to import the
6
+ * other for it.
7
+ *
8
+ * @module
9
+ */
10
+ /** Whether `value` is a plain object (a JSON object, not an array or null). */
11
+ export function isRecord(value) {
12
+ return typeof value === "object" && value !== null && !Array.isArray(value);
13
+ }
@@ -0,0 +1,11 @@
1
+ import type { BuildProbe } from "./dispatch.ts";
2
+ import type { CliPaint } from "./paint.ts";
3
+ import { type ProjectHost } from "./project.ts";
4
+ /**
5
+ * Run `zuke relock <args>` from `cwd`, reporting through `log`, and return
6
+ * the exit code.
7
+ *
8
+ * @throws {Error} with a message for the user when the request cannot be
9
+ * carried out. `main` prints the message and exits 1.
10
+ */
11
+ export declare function runRelock(args: string[], log: (line: string) => void, host: ProjectHost, paint: CliPaint, cwd: string, probe: BuildProbe): Promise<number>;
package/src/relock.js ADDED
@@ -0,0 +1,182 @@
1
+ // Copyright (c) 2026 the Zuke contributors
2
+ // SPDX-License-Identifier: MIT
3
+ /**
4
+ * `zuke relock`: regenerate the project's lockfile from scratch.
5
+ *
6
+ * A project's own `zuke outdated --update` runs on the core the project's
7
+ * lock pins, so a core whose update path is broken cannot move the project
8
+ * off itself: core 1.66 dropped specifiers it still left in other packages'
9
+ * dependency lists, and Deno then refused the whole lock. This command
10
+ * belongs to the global CLI instead, so it works whatever core the project
11
+ * is on.
12
+ *
13
+ * The old lock is copied to a backup file beside it before anything changes,
14
+ * then emptied in place — written through, so a lock that is a symlink to a
15
+ * shared file stays one — and `deno install --entrypoint zuke.ts
16
+ * --frozen=false` resolves it afresh in the project root. A failed install
17
+ * writes the old text back; a run that dies part-way leaves the backup on
18
+ * disk, and the next `relock` refuses to start until it is dealt with.
19
+ *
20
+ * Only the entrypoints it is given are resolved: `zuke.ts`, plus any named on
21
+ * the command line. A resolution only another program needed is dropped, and
22
+ * the report names the JSR packages that went, so a shared lock is not
23
+ * narrowed silently.
24
+ *
25
+ * `--min-dep-age` passes Deno's `--minimum-dependency-age` through, under the
26
+ * name and value forms `outdated --update --min-dep-age` already takes. It
27
+ * matters on Deno 2.9, which by default skips releases from the last day or
28
+ * so: `--min-dep-age 0` resolves the newest published versions.
29
+ *
30
+ * @module
31
+ */
32
+ import { lockedJsrSpecifiers } from "@zuke/core";
33
+ import { installArgs, parseInstallFlags, projectLocation, } from "./project.js";
34
+ import { lockedCoreVersions, projectConfigText, projectLockPath, } from "./version_report.js";
35
+ /** The suffix of the backup a run keeps while the lock is being rewritten. */
36
+ const BACKUP_SUFFIX = ".relock-backup";
37
+ /** `versions` for a report line: joined, or `none` when the lock had none. */
38
+ function shown(versions) {
39
+ return versions.length > 0 ? versions.join(", ") : "none";
40
+ }
41
+ /**
42
+ * Whether release `a` is older than release `b`, comparing the numeric core
43
+ * only; `false` for anything this cannot read.
44
+ */
45
+ function olderThan(a, b) {
46
+ const parse = (v) => /^(\d+)\.(\d+)\.(\d+)/.exec(v)?.slice(1, 4);
47
+ const x = parse(a);
48
+ const y = parse(b);
49
+ if (x === undefined || y === undefined)
50
+ return false;
51
+ for (let i = 0; i < 3; i++) {
52
+ if (Number(x[i]) !== Number(y[i]))
53
+ return Number(x[i]) < Number(y[i]);
54
+ }
55
+ return false;
56
+ }
57
+ /** The emptied lock a run resolves into: `before`'s format version, no entries. */
58
+ function emptied(before) {
59
+ let version = "5";
60
+ try {
61
+ const parsed = JSON.parse(before);
62
+ if (parsed !== null && typeof parsed === "object") {
63
+ version = Reflect.get(parsed, "version") ?? version;
64
+ }
65
+ }
66
+ catch {
67
+ // An unreadable lock is still replaced; the default format is Deno 2's.
68
+ }
69
+ return `${JSON.stringify({ version }, null, 2)}\n`;
70
+ }
71
+ /** The JSR package names `lock` resolves. */
72
+ function jsrPackages(lock) {
73
+ return new Set(lockedJsrSpecifiers(lock).map((entry) => entry.name));
74
+ }
75
+ /**
76
+ * Run `zuke relock <args>` from `cwd`, reporting through `log`, and return
77
+ * the exit code.
78
+ *
79
+ * @throws {Error} with a message for the user when the request cannot be
80
+ * carried out. `main` prints the message and exits 1.
81
+ */
82
+ export async function runRelock(args, log, host, paint, cwd, probe) {
83
+ const flags = parseInstallFlags("relock", args);
84
+ const { root, build } = await projectLocation(cwd, probe, "relock");
85
+ const lockPath = projectLockPath(root, await projectConfigText((path) => host.readText(path), root));
86
+ if (lockPath === null) {
87
+ throw new Error("zuke relock: this project's deno.json disables its lock, or could " +
88
+ "not be read as JSON, so there is no lock to regenerate.");
89
+ }
90
+ // Regenerating is the point, so a lock the config freezes is not a reason
91
+ // to refuse the write.
92
+ const denoArgs = [
93
+ ...installArgs("relock", flags, host.denoVersion(), build),
94
+ "--frozen=false",
95
+ ];
96
+ const name = lockPath.startsWith(`${root}/`)
97
+ ? lockPath.slice(root.length + 1)
98
+ : lockPath;
99
+ if (flags.dryRun) {
100
+ log(`Would regenerate ${name}: deno ${denoArgs.join(" ")}`);
101
+ return 0;
102
+ }
103
+ const backup = `${lockPath}${BACKUP_SUFFIX}`;
104
+ let leftover = true;
105
+ try {
106
+ await host.readText(backup);
107
+ }
108
+ catch {
109
+ leftover = false;
110
+ }
111
+ if (leftover) {
112
+ throw new Error(`zuke relock: ${backup} is left from a relock that did not finish. ` +
113
+ `It is the lock as it was before that run: move it back over ${name} ` +
114
+ "to restore it, or delete it to keep the lock as it is, then run " +
115
+ "zuke relock again.");
116
+ }
117
+ let before;
118
+ try {
119
+ before = await host.readText(lockPath);
120
+ }
121
+ catch {
122
+ // No lock yet: there is nothing to back up or put back.
123
+ }
124
+ if (before !== undefined) {
125
+ await host.writeText(backup, before);
126
+ await host.writeText(lockPath, emptied(before));
127
+ }
128
+ const restore = async () => {
129
+ if (before !== undefined)
130
+ await host.writeText(lockPath, before);
131
+ };
132
+ log(`Regenerating ${name}…`);
133
+ let code;
134
+ try {
135
+ code = await host.deno(denoArgs, root);
136
+ }
137
+ catch (error) {
138
+ await restore();
139
+ if (before !== undefined)
140
+ await host.remove(backup);
141
+ throw error;
142
+ }
143
+ let after;
144
+ if (code === 0) {
145
+ try {
146
+ after = await host.readText(lockPath);
147
+ }
148
+ catch {
149
+ // Reported below.
150
+ }
151
+ }
152
+ if (code !== 0 || after === undefined || after === emptied(before ?? "")) {
153
+ await restore();
154
+ if (before !== undefined)
155
+ await host.remove(backup);
156
+ log(paint.fail(code !== 0
157
+ ? `zuke relock: deno install exited ${code}; ${name} is unchanged.`
158
+ : `zuke relock: deno install wrote no ${name}${before === undefined ? "" : "; the old one is restored"}. In a workspace member, Deno keeps the lock at the workspace ` +
159
+ "root: run zuke relock there."));
160
+ return code !== 0 ? code : 1;
161
+ }
162
+ if (before !== undefined)
163
+ await host.remove(backup);
164
+ const was = lockedCoreVersions(before ?? "");
165
+ const now = lockedCoreVersions(after);
166
+ log(paint.ok(`Regenerated ${name}: @zuke/core ${shown(was) === shown(now) ? shown(now) : `${shown(was)} → ${shown(now)}`}`));
167
+ if (was.length === 1 && now.length === 1 && olderThan(now[0], was[0]) &&
168
+ flags.minDepAge === undefined) {
169
+ log("Core resolved older than before: Deno's minimum dependency age " +
170
+ "skips recent releases. Run zuke relock --min-dep-age 0 to resolve " +
171
+ "the newest.");
172
+ }
173
+ const kept = jsrPackages(after);
174
+ const dropped = [...jsrPackages(before ?? "")].filter((p) => !kept.has(p));
175
+ if (dropped.length > 0) {
176
+ log(`No longer locked: ${dropped.join(", ")}. Only ${build}${flags.entrypoints.length > 0
177
+ ? ` and ${flags.entrypoints.join(", ")}`
178
+ : ""} were resolved; if another program in this project imports them, ` +
179
+ "name it: zuke relock <entrypoint>.");
180
+ }
181
+ return 0;
182
+ }