@intentius/chant 0.124.100 → 0.124.101
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/dist/action-pins.d.ts +2 -0
- package/dist/action-pins.js +3 -0
- package/dist/ci-detect.d.ts +13 -0
- package/dist/ci-detect.js +12 -0
- package/dist/ci-system.d.ts +66 -0
- package/dist/ci-system.js +61 -0
- package/dist/cli/handlers/build.js +27 -0
- package/dist/cli/handlers/release-doctor.d.ts +12 -0
- package/dist/cli/handlers/release-doctor.js +118 -0
- package/dist/cli/handlers/release-init.d.ts +10 -0
- package/dist/cli/handlers/release-init.js +342 -0
- package/dist/cli/handlers/release.d.ts +42 -1
- package/dist/cli/handlers/release.js +656 -31
- package/dist/cli/handlers/run-generate.js +11 -0
- package/dist/cli/main.d.ts +2 -0
- package/dist/cli/main.js +44 -101
- package/dist/cli/parse-args.js +48 -0
- package/dist/cli/registry.d.ts +16 -0
- package/dist/cli/release-commands/artifacts.d.ts +3 -0
- package/dist/cli/release-commands/artifacts.js +14 -0
- package/dist/cli/release-commands/candidates.d.ts +3 -0
- package/dist/cli/release-commands/candidates.js +16 -0
- package/dist/cli/release-commands/changed.d.ts +3 -0
- package/dist/cli/release-commands/changed.js +14 -0
- package/dist/cli/release-commands/compose.d.ts +3 -0
- package/dist/cli/release-commands/compose.js +16 -0
- package/dist/cli/release-commands/cut.d.ts +3 -0
- package/dist/cli/release-commands/cut.js +49 -0
- package/dist/cli/release-commands/doctor.d.ts +3 -0
- package/dist/cli/release-commands/doctor.js +14 -0
- package/dist/cli/release-commands/export.d.ts +3 -0
- package/dist/cli/release-commands/export.js +12 -0
- package/dist/cli/release-commands/images.d.ts +3 -0
- package/dist/cli/release-commands/images.js +13 -0
- package/dist/cli/release-commands/index.d.ts +8 -0
- package/dist/cli/release-commands/index.js +52 -0
- package/dist/cli/release-commands/init.d.ts +3 -0
- package/dist/cli/release-commands/init.js +16 -0
- package/dist/cli/release-commands/list.d.ts +3 -0
- package/dist/cli/release-commands/list.js +10 -0
- package/dist/cli/release-commands/next.d.ts +3 -0
- package/dist/cli/release-commands/next.js +13 -0
- package/dist/cli/release-commands/publish.d.ts +3 -0
- package/dist/cli/release-commands/publish.js +22 -0
- package/dist/cli/release-commands/stamp.d.ts +3 -0
- package/dist/cli/release-commands/stamp.js +15 -0
- package/dist/cli/release-commands/status.d.ts +3 -0
- package/dist/cli/release-commands/status.js +17 -0
- package/dist/cli/release-commands/tag.d.ts +3 -0
- package/dist/cli/release-commands/tag.js +12 -0
- package/dist/cli/release-commands/types.d.ts +20 -0
- package/dist/cli/release-commands/types.js +1 -0
- package/dist/cli/release-commands/verify.d.ts +3 -0
- package/dist/cli/release-commands/verify.js +15 -0
- package/dist/cli/release-commands/workflow.d.ts +3 -0
- package/dist/cli/release-commands/workflow.js +13 -0
- package/dist/components/cli-support.d.ts +1 -1
- package/dist/components/cli-support.js +1 -1
- package/dist/config-environments.d.ts +8 -1
- package/dist/config-environments.js +2 -0
- package/dist/config.d.ts +294 -9
- package/dist/config.js +100 -5
- package/dist/floor-table.data.js +15 -1
- package/dist/forge-remote.d.ts +13 -0
- package/dist/forge-remote.js +15 -0
- package/dist/lexicon.d.ts +41 -2
- package/dist/lifecycle/__fixtures__/publish-fakes.d.ts +62 -0
- package/dist/lifecycle/__fixtures__/publish-fakes.js +270 -3
- package/dist/lifecycle/publish-attachments.d.ts +2 -1
- package/dist/lifecycle/publish-attachments.js +19 -2
- package/dist/lifecycle/publish-cargo.d.ts +99 -0
- package/dist/lifecycle/publish-cargo.js +412 -0
- package/dist/lifecycle/publish-credentials.d.ts +1 -1
- package/dist/lifecycle/publish-credentials.js +8 -0
- package/dist/lifecycle/publish-declaration.d.ts +199 -4
- package/dist/lifecycle/publish-declaration.js +200 -9
- package/dist/lifecycle/publish-forge.d.ts +45 -2
- package/dist/lifecycle/publish-forge.js +434 -34
- package/dist/lifecycle/publish-git-ssh.d.ts +15 -0
- package/dist/lifecycle/publish-git-ssh.js +30 -4
- package/dist/lifecycle/publish-github.d.ts +40 -2
- package/dist/lifecycle/publish-github.js +100 -3
- package/dist/lifecycle/publish-homebrew.d.ts +7 -9
- package/dist/lifecycle/publish-homebrew.js +34 -197
- package/dist/lifecycle/publish-index.d.ts +141 -0
- package/dist/lifecycle/publish-index.js +719 -0
- package/dist/lifecycle/publish-marketplace.js +77 -0
- package/dist/lifecycle/publish-mcp-registry.d.ts +66 -0
- package/dist/lifecycle/publish-mcp-registry.js +306 -0
- package/dist/lifecycle/publish-npm.js +165 -2
- package/dist/lifecycle/publish-oci.d.ts +34 -1
- package/dist/lifecycle/publish-oci.js +246 -7
- package/dist/lifecycle/publish-pypi.d.ts +136 -0
- package/dist/lifecycle/publish-pypi.js +657 -0
- package/dist/lifecycle/publish-record.d.ts +6 -3
- package/dist/lifecycle/publish-record.js +6 -3
- package/dist/lifecycle/publish-signing.d.ts +147 -0
- package/dist/lifecycle/publish-signing.js +257 -0
- package/dist/lifecycle/publish-targets.d.ts +27 -1
- package/dist/lifecycle/publish-targets.js +80 -0
- package/dist/lifecycle/publish-tauri.js +43 -0
- package/dist/lifecycle/publish-train-names.d.ts +54 -0
- package/dist/lifecycle/publish-train-names.js +118 -0
- package/dist/lifecycle/publish-verify.d.ts +121 -0
- package/dist/lifecycle/publish-verify.js +130 -0
- package/dist/lifecycle/query.js +8 -0
- package/dist/lifecycle/release-artifacts.d.ts +212 -0
- package/dist/lifecycle/release-artifacts.js +571 -0
- package/dist/lifecycle/release-changelog.d.ts +13 -1
- package/dist/lifecycle/release-changelog.js +35 -2
- package/dist/lifecycle/release-cut.d.ts +58 -3
- package/dist/lifecycle/release-cut.js +132 -34
- package/dist/lifecycle/release-doctor.d.ts +113 -0
- package/dist/lifecycle/release-doctor.js +996 -0
- package/dist/lifecycle/release-green.d.ts +86 -0
- package/dist/lifecycle/release-green.js +286 -0
- package/dist/lifecycle/release-init.d.ts +255 -0
- package/dist/lifecycle/release-init.js +859 -0
- package/dist/lifecycle/release-intents.d.ts +73 -0
- package/dist/lifecycle/release-intents.js +128 -0
- package/dist/lifecycle/release-next.d.ts +111 -0
- package/dist/lifecycle/release-next.js +252 -0
- package/dist/lifecycle/release-prerelease.d.ts +19 -0
- package/dist/lifecycle/release-prerelease.js +30 -0
- package/dist/lifecycle/release-publish.d.ts +256 -10
- package/dist/lifecycle/release-publish.js +246 -34
- package/dist/lifecycle/release-status-change.d.ts +226 -0
- package/dist/lifecycle/release-status-change.js +478 -0
- package/dist/lifecycle/release-status.d.ts +11 -0
- package/dist/lifecycle/release-status.js +1 -1
- package/dist/lifecycle/release-store.d.ts +73 -2
- package/dist/lifecycle/release-store.js +32 -1
- package/dist/lifecycle/release-tag.d.ts +142 -0
- package/dist/lifecycle/release-tag.js +323 -0
- package/dist/lifecycle/release-verify.d.ts +73 -1
- package/dist/lifecycle/release-verify.js +117 -2
- package/dist/lifecycle/release-version-formats.d.ts +73 -0
- package/dist/lifecycle/release-version-formats.js +570 -0
- package/dist/lifecycle/release-version.d.ts +58 -10
- package/dist/lifecycle/release-version.js +164 -36
- package/dist/lifecycle/release-workstation.d.ts +3 -2
- package/dist/lifecycle/release-workstation.js +3 -2
- package/dist/op/generate-pipeline.js +1 -1
- package/dist/pr-forge-base.js +4 -2
- package/dist/pr-forge.d.ts +20 -2
- package/dist/pr-forge.js +46 -10
- package/dist/release-floors.d.ts +8 -1
- package/dist/release-floors.js +9 -2
- package/dist/tool-pins.d.ts +38 -0
- package/dist/tool-pins.js +54 -0
- package/dist/wave-runtime.mjs +337 -334
- package/dist/workspace/ci-forge.d.ts +17 -0
- package/dist/workspace/ci-forge.js +17 -0
- package/dist/workspace/ci-init.js +1 -1
- package/dist/workspace/composites.schema.json +1 -0
- package/dist/workspace/declaration.d.ts +8 -0
- package/dist/workspace/declaration.js +12 -0
- package/dist/workspace/declaration.schema.json +8 -0
- package/dist/workspace/environments.d.ts +2 -0
- package/dist/workspace/environments.js +1 -1
- package/dist/workspace/identity-gate-rule.d.ts +61 -5
- package/dist/workspace/identity-gate-rule.js +81 -12
- package/dist/workspace/member-pipeline.d.ts +2 -1
- package/dist/workspace/member-pipeline.js +5 -2
- package/dist/workspace/reason-codes.d.ts +2 -0
- package/dist/workspace/reason-codes.js +3 -1
- package/dist/workspace/release-changed.d.ts +75 -4
- package/dist/workspace/release-changed.js +205 -34
- package/dist/workspace/release-changed.schema.json +20 -2
- package/dist/workspace/release-steps/artifacts.d.ts +7 -0
- package/dist/workspace/release-steps/artifacts.js +45 -0
- package/dist/workspace/release-steps/builds.d.ts +12 -0
- package/dist/workspace/release-steps/builds.js +38 -0
- package/dist/workspace/release-steps/doctor.d.ts +8 -0
- package/dist/workspace/release-steps/doctor.js +14 -0
- package/dist/workspace/release-steps/goreleaser.d.ts +16 -0
- package/dist/workspace/release-steps/goreleaser.js +36 -0
- package/dist/workspace/release-steps/green.d.ts +3 -0
- package/dist/workspace/release-steps/green.js +6 -0
- package/dist/workspace/release-steps/images.d.ts +22 -0
- package/dist/workspace/release-steps/images.js +59 -0
- package/dist/workspace/release-steps/index.d.ts +9 -0
- package/dist/workspace/release-steps/index.js +46 -0
- package/dist/workspace/release-steps/pypi.d.ts +15 -0
- package/dist/workspace/release-steps/pypi.js +21 -0
- package/dist/workspace/release-steps/qemu.d.ts +21 -0
- package/dist/workspace/release-steps/qemu.js +35 -0
- package/dist/workspace/release-steps/signing.d.ts +18 -0
- package/dist/workspace/release-steps/signing.js +30 -0
- package/dist/workspace/release-steps/stamp.d.ts +3 -0
- package/dist/workspace/release-steps/stamp.js +4 -0
- package/dist/workspace/release-steps/targets.d.ts +31 -0
- package/dist/workspace/release-steps/targets.js +40 -0
- package/dist/workspace/release-steps/types.d.ts +104 -0
- package/dist/workspace/release-steps/types.js +2 -0
- package/dist/workspace/release-steps/verify.d.ts +3 -0
- package/dist/workspace/release-steps/verify.js +4 -0
- package/dist/workspace/release-toolchains.d.ts +59 -0
- package/dist/workspace/release-toolchains.js +133 -0
- package/dist/workspace/release-train-workflow.d.ts +29 -0
- package/dist/workspace/release-train-workflow.js +85 -0
- package/dist/workspace/release-train.d.ts +3 -1
- package/dist/workspace/release-train.js +20 -3
- package/dist/workspace/release-workflow.d.ts +160 -61
- package/dist/workspace/release-workflow.js +539 -193
- package/dist/workspace/releases.schema.json +70 -1
- package/dist/workspace/search-contract.d.ts +1 -1
- package/dist/workspace/security.js +9 -2
- package/dist/workspace/train-cut.d.ts +182 -0
- package/dist/workspace/train-cut.js +482 -0
- package/dist/workspace/train-prepare.d.ts +61 -0
- package/dist/workspace/train-prepare.js +267 -0
- package/dist/workspace/train-publish.d.ts +177 -0
- package/dist/workspace/train-publish.js +575 -0
- package/dist/workspace/train-range-labels.d.ts +33 -0
- package/dist/workspace/train-range-labels.js +109 -0
- package/dist/workspace/trust/seal.d.ts +13 -3
- package/dist/workspace/trust/seal.js +14 -4
- package/dist/workspace/work-cli.d.ts +3 -2
- package/dist/workspace/work-cli.js +3 -2
- package/dist/workspace/workspace-ledger.d.ts +14 -1
- package/dist/workspace/workspace-ledger.js +33 -7
- package/package.json +1 -1
|
@@ -0,0 +1,859 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `chant release init` (#5160): the first setup of `chant release` in a
|
|
3
|
+
* project that has never used chant.
|
|
4
|
+
*
|
|
5
|
+
* It reads the project ({@link detectProject}): the package.json and its
|
|
6
|
+
* npm, pnpm or yarn workspaces, go.mod, Cargo.toml, pyproject.toml,
|
|
7
|
+
* Dockerfiles, a goreleaser config, the forge `origin` names, and the tags
|
|
8
|
+
* releases were made under so far. From that it plans a `release` block
|
|
9
|
+
* ({@link planRelease}): the tag template, `legacyTags`, the green gate, the
|
|
10
|
+
* version stamping, the publish targets it can infer, and a dispatched
|
|
11
|
+
* release workflow. Then it writes that block into `chant.config.ts`
|
|
12
|
+
* ({@link insertReleaseBlock}), making a config of the block alone when
|
|
13
|
+
* there is none.
|
|
14
|
+
*
|
|
15
|
+
* Detection reads files and local git only; it never reaches a registry or
|
|
16
|
+
* the forge. Everything it can't set up from the repository, such as an npm
|
|
17
|
+
* trusted publisher, is a step printed for a person ({@link ReleaseInitPlan.registry}).
|
|
18
|
+
*/
|
|
19
|
+
import { execFileSync } from "node:child_process";
|
|
20
|
+
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
21
|
+
import { basename, join, posix, relative, sep } from "node:path";
|
|
22
|
+
import { forgeOfRemote } from "../forge-remote.js";
|
|
23
|
+
/** A refusal of `chant release init`, with its code. */
|
|
24
|
+
export class ReleaseInitError extends Error {
|
|
25
|
+
constructor(code, message, fix) {
|
|
26
|
+
super(message);
|
|
27
|
+
this.code = code;
|
|
28
|
+
this.fix = fix;
|
|
29
|
+
this.name = "ReleaseInitError";
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
const VERSION_TAG = /^(.*?)(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?)$/;
|
|
33
|
+
/** The characters a `release.tag` template may hold around its placeholder. */
|
|
34
|
+
const TEMPLATE_PREFIX = /^[A-Za-z0-9._+/-]*$/;
|
|
35
|
+
function compareVersions(a, b) {
|
|
36
|
+
const pa = a.split(/[-+]/)[0].split(".").map(Number);
|
|
37
|
+
const pb = b.split(/[-+]/)[0].split(".").map(Number);
|
|
38
|
+
for (let i = 0; i < 3; i++)
|
|
39
|
+
if (pa[i] !== pb[i])
|
|
40
|
+
return pa[i] - pb[i];
|
|
41
|
+
// A release sorts after its prereleases.
|
|
42
|
+
const ra = a.includes("-") ? 0 : 1;
|
|
43
|
+
const rb = b.includes("-") ? 0 : 1;
|
|
44
|
+
return ra - rb;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* The tag history of a list of tags: version tags grouped by their prefix,
|
|
48
|
+
* the largest group first. `ci/` and `chant/` tags are chant's own and
|
|
49
|
+
* left out.
|
|
50
|
+
*/
|
|
51
|
+
export function readTagHistory(tags) {
|
|
52
|
+
const groups = new Map();
|
|
53
|
+
for (const t of tags) {
|
|
54
|
+
if (t.startsWith("ci/") || t.startsWith("chant/"))
|
|
55
|
+
continue;
|
|
56
|
+
const m = VERSION_TAG.exec(t);
|
|
57
|
+
if (!m)
|
|
58
|
+
continue;
|
|
59
|
+
const prefix = m[1];
|
|
60
|
+
groups.set(prefix, [...(groups.get(prefix) ?? []), m[2]]);
|
|
61
|
+
}
|
|
62
|
+
const ranked = [...groups.entries()].sort((a, b) => b[1].length - a[1].length || a[0].localeCompare(b[0]));
|
|
63
|
+
if (ranked.length === 0)
|
|
64
|
+
return { prefix: null, count: 0, newest: null, others: [] };
|
|
65
|
+
const [prefix, versions] = ranked[0];
|
|
66
|
+
const newest = [...versions].sort(compareVersions).pop();
|
|
67
|
+
return { prefix, count: versions.length, newest: `${prefix}${newest}`, others: ranked.slice(1).map(([p, v]) => ({ prefix: p, count: v.length })) };
|
|
68
|
+
}
|
|
69
|
+
function readJson(file) {
|
|
70
|
+
try {
|
|
71
|
+
return JSON.parse(readFileSync(file, "utf-8"));
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
function readText(file) {
|
|
78
|
+
try {
|
|
79
|
+
return readFileSync(file, "utf-8");
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
return null;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
function isDir(p) {
|
|
86
|
+
try {
|
|
87
|
+
return statSync(p).isDirectory();
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
return false;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
function readPackage(root, dir) {
|
|
94
|
+
const pkg = readJson(join(root, dir, "package.json"));
|
|
95
|
+
if (!pkg)
|
|
96
|
+
return null;
|
|
97
|
+
const obj = (v) => (v && typeof v === "object" ? v : {});
|
|
98
|
+
const engines = obj(pkg.engines);
|
|
99
|
+
const publishConfig = obj(pkg.publishConfig);
|
|
100
|
+
return {
|
|
101
|
+
dir,
|
|
102
|
+
name: typeof pkg.name === "string" ? pkg.name : null,
|
|
103
|
+
private: pkg.private === true,
|
|
104
|
+
access: typeof publishConfig.access === "string" ? publishConfig.access : null,
|
|
105
|
+
vscode: typeof engines.vscode === "string",
|
|
106
|
+
publisher: typeof pkg.publisher === "string" ? pkg.publisher : null,
|
|
107
|
+
deps: [...new Set([pkg.dependencies, pkg.peerDependencies, pkg.optionalDependencies].flatMap((d) => Object.keys(obj(d))))],
|
|
108
|
+
scripts: Object.keys(obj(pkg.scripts)),
|
|
109
|
+
packList: Array.isArray(pkg.files) || existsSync(join(root, dir, ".npmignore")),
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
const SKIP_DIRS = new Set(["node_modules", ".git", "dist", "vendor", "target", "build", ".venv", "venv"]);
|
|
113
|
+
/** The directories a workspace pattern such as `packages/*` or `apps/**` names, from `root`. */
|
|
114
|
+
export function expandWorkspacePattern(root, pattern) {
|
|
115
|
+
const parts = pattern.replace(/^\.\//, "").replace(/\/+$/, "").split("/").filter((p) => p !== "" && p !== ".");
|
|
116
|
+
let dirs = [""];
|
|
117
|
+
for (const part of parts) {
|
|
118
|
+
const next = [];
|
|
119
|
+
for (const d of dirs) {
|
|
120
|
+
const abs = join(root, d);
|
|
121
|
+
if (part === "**") {
|
|
122
|
+
const walk = (rel, depth) => {
|
|
123
|
+
next.push(rel);
|
|
124
|
+
if (depth === 0)
|
|
125
|
+
return;
|
|
126
|
+
for (const e of safeReaddir(join(root, rel)))
|
|
127
|
+
if (isDir(join(root, rel, e)) && !SKIP_DIRS.has(e) && !e.startsWith("."))
|
|
128
|
+
walk(rel ? `${rel}/${e}` : e, depth - 1);
|
|
129
|
+
};
|
|
130
|
+
walk(d, 3);
|
|
131
|
+
}
|
|
132
|
+
else if (part.includes("*")) {
|
|
133
|
+
const re = new RegExp(`^${part.split("*").map((s) => s.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join("[^/]*")}$`);
|
|
134
|
+
for (const e of safeReaddir(abs))
|
|
135
|
+
if (re.test(e) && !SKIP_DIRS.has(e) && isDir(join(abs, e)))
|
|
136
|
+
next.push(d ? `${d}/${e}` : e);
|
|
137
|
+
}
|
|
138
|
+
else if (isDir(join(abs, part))) {
|
|
139
|
+
next.push(d ? `${d}/${part}` : part);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
dirs = next;
|
|
143
|
+
}
|
|
144
|
+
return [...new Set(dirs)].filter((d) => d !== "").sort();
|
|
145
|
+
}
|
|
146
|
+
function safeReaddir(dir) {
|
|
147
|
+
try {
|
|
148
|
+
return readdirSync(dir);
|
|
149
|
+
}
|
|
150
|
+
catch {
|
|
151
|
+
return [];
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
/** The workspace patterns of a package.json (`workspaces` as a list or `{ packages }`) or a pnpm-workspace.yaml. */
|
|
155
|
+
export function workspacePatterns(root) {
|
|
156
|
+
const pnpm = readText(join(root, "pnpm-workspace.yaml"));
|
|
157
|
+
if (pnpm !== null) {
|
|
158
|
+
const out = [];
|
|
159
|
+
let inPackages = false;
|
|
160
|
+
for (const line of pnpm.split("\n")) {
|
|
161
|
+
if (/^packages\s*:/.test(line)) {
|
|
162
|
+
inPackages = true;
|
|
163
|
+
continue;
|
|
164
|
+
}
|
|
165
|
+
if (inPackages && /^\S/.test(line))
|
|
166
|
+
inPackages = false;
|
|
167
|
+
const m = inPackages ? /^\s*-\s*['"]?([^'"#]+?)['"]?\s*(#.*)?$/.exec(line) : null;
|
|
168
|
+
if (m)
|
|
169
|
+
out.push(m[1]);
|
|
170
|
+
}
|
|
171
|
+
return out;
|
|
172
|
+
}
|
|
173
|
+
const pkg = readJson(join(root, "package.json"));
|
|
174
|
+
const ws = pkg?.workspaces;
|
|
175
|
+
if (Array.isArray(ws))
|
|
176
|
+
return ws.filter((w) => typeof w === "string");
|
|
177
|
+
if (ws && typeof ws === "object" && Array.isArray(ws.packages))
|
|
178
|
+
return (ws.packages).filter((w) => typeof w === "string");
|
|
179
|
+
return null;
|
|
180
|
+
}
|
|
181
|
+
function git(cwd, args) {
|
|
182
|
+
try {
|
|
183
|
+
return execFileSync("git", args, { cwd, encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] });
|
|
184
|
+
}
|
|
185
|
+
catch {
|
|
186
|
+
return null;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
/** Dockerfiles at the project root and one or two directories below it, `node_modules` and the like left out. */
|
|
190
|
+
function findDockerfiles(root) {
|
|
191
|
+
const out = [];
|
|
192
|
+
const isDockerfile = (n) => n === "Dockerfile" || n === "Containerfile";
|
|
193
|
+
const walk = (rel, depth) => {
|
|
194
|
+
for (const e of safeReaddir(join(root, rel))) {
|
|
195
|
+
const p = rel ? `${rel}/${e}` : e;
|
|
196
|
+
if (isDockerfile(e) && !isDir(join(root, p)))
|
|
197
|
+
out.push(p);
|
|
198
|
+
else if (depth > 0 && !SKIP_DIRS.has(e) && !e.startsWith(".") && isDir(join(root, p)))
|
|
199
|
+
walk(p, depth - 1);
|
|
200
|
+
}
|
|
201
|
+
};
|
|
202
|
+
walk("", 2);
|
|
203
|
+
return out.sort((a, b) => a.split("/").length - b.split("/").length || a.localeCompare(b));
|
|
204
|
+
}
|
|
205
|
+
const GORELEASER_FILES = [".goreleaser.yaml", ".goreleaser.yml", "goreleaser.yaml", "goreleaser.yml"];
|
|
206
|
+
/** Whether a goreleaser config sets `snapshot.version_template` to the release label. */
|
|
207
|
+
export function goreleaserFacts(text) {
|
|
208
|
+
return {
|
|
209
|
+
labelTemplate: /version_template\s*:\s*["']?\{\{\s*\.Env\.CHANT_RELEASE_LABEL\s*\}\}/.test(text),
|
|
210
|
+
snapshot: /^snapshot\s*:/m.test(text),
|
|
211
|
+
images: /^(dockers|dockers_v2|kos)\s*:/m.test(text),
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
/** The lines a goreleaser config needs so its snapshot build carries the release's label. */
|
|
215
|
+
export const GORELEASER_SNAPSHOT = 'snapshot:\n version_template: "{{ .Env.CHANT_RELEASE_LABEL }}"\n';
|
|
216
|
+
/** Read the project at `root` (the directory `chant release init` runs in). */
|
|
217
|
+
/** The sections of a TOML file by header, each holding its own lines only. */
|
|
218
|
+
function tomlSections(text) {
|
|
219
|
+
const out = new Map();
|
|
220
|
+
let name = "";
|
|
221
|
+
for (const line of text.split(/\r?\n/)) {
|
|
222
|
+
const h = /^\s*\[{1,2}\s*([^\]]+?)\s*\]{1,2}\s*(#.*)?$/.exec(line);
|
|
223
|
+
if (h) {
|
|
224
|
+
name = h[1];
|
|
225
|
+
continue;
|
|
226
|
+
}
|
|
227
|
+
out.set(name, `${out.get(name) ?? ""}${line}\n`);
|
|
228
|
+
}
|
|
229
|
+
return out;
|
|
230
|
+
}
|
|
231
|
+
/** A `Cargo.toml`'s name, workspace, stampable version and `publish = false`. */
|
|
232
|
+
export function cargoFacts(text) {
|
|
233
|
+
const sections = tomlSections(text);
|
|
234
|
+
const pkg = sections.get("package") ?? "";
|
|
235
|
+
const str = (body, key) => new RegExp(`^${key}\\s*=\\s*"([^"]*)"`, "m").exec(body)?.[1] ?? null;
|
|
236
|
+
return {
|
|
237
|
+
name: str(pkg, "name"),
|
|
238
|
+
workspace: sections.has("workspace"),
|
|
239
|
+
version: str(pkg, "version") !== null || str(sections.get("workspace.package") ?? "", "version") !== null,
|
|
240
|
+
unpublishable: /^publish\s*=\s*false\b/m.test(pkg),
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
/** A `pyproject.toml`'s project name, and whether its version is a static string that `release.version.files` can stamp. */
|
|
244
|
+
export function pyprojectFacts(text) {
|
|
245
|
+
const sections = tomlSections(text);
|
|
246
|
+
const str = (body, key) => new RegExp(`^${key}\\s*=\\s*["']([^"']*)["']`, "m").exec(body)?.[1] ?? null;
|
|
247
|
+
const project = sections.get("project") ?? "";
|
|
248
|
+
const poetry = sections.get("tool.poetry") ?? "";
|
|
249
|
+
const name = str(project, "name") ?? str(poetry, "name");
|
|
250
|
+
return { name, pyproject: true, version: str(project, "version") !== null || str(poetry, "version") !== null };
|
|
251
|
+
}
|
|
252
|
+
export function detectProject(root) {
|
|
253
|
+
const top = git(root, ["rev-parse", "--show-toplevel"])?.trim() || root;
|
|
254
|
+
const fromTop = relative(top, root).split(sep).join("/");
|
|
255
|
+
const path = fromTop === "" ? null : fromTop;
|
|
256
|
+
const remote = git(root, ["remote", "get-url", "origin"])?.trim();
|
|
257
|
+
const at = remote ? forgeOfRemote(remote) : undefined;
|
|
258
|
+
const origin = at ? { kind: at.kind, host: at.host, repo: at.repo } : null;
|
|
259
|
+
const workflowForge = isDir(join(top, ".github", "workflows")) ? "github" : isDir(join(top, ".forgejo", "workflows")) ? "forgejo" : existsSync(join(top, ".gitlab-ci.yml")) ? "gitlab" : (origin?.kind ?? "github");
|
|
260
|
+
const ciFiles = [
|
|
261
|
+
...[".github/workflows", ".forgejo/workflows", ".gitea/workflows"].flatMap((d) => safeReaddir(join(top, d)).filter((f) => /\.ya?ml$/.test(f) && f !== "chant-release.yml").map((f) => `${d}/${f}`)),
|
|
262
|
+
...(existsSync(join(top, ".gitlab-ci.yml")) ? [".gitlab-ci.yml"] : []),
|
|
263
|
+
];
|
|
264
|
+
let node = null;
|
|
265
|
+
const rootPkg = readPackage(root, ".");
|
|
266
|
+
if (rootPkg) {
|
|
267
|
+
const lockfile = ["package-lock.json", "pnpm-lock.yaml", "yarn.lock", "npm-shrinkwrap.json"].find((f) => existsSync(join(root, f))) ?? null;
|
|
268
|
+
const manager = existsSync(join(root, "pnpm-lock.yaml")) || existsSync(join(root, "pnpm-workspace.yaml")) ? "pnpm" : existsSync(join(root, "yarn.lock")) || existsSync(join(root, ".yarnrc.yml")) ? "yarn" : "npm";
|
|
269
|
+
const patterns = workspacePatterns(root);
|
|
270
|
+
const workspaces = patterns === null
|
|
271
|
+
? null
|
|
272
|
+
: [...new Set(patterns.filter((p) => !p.startsWith("!")).flatMap((p) => expandWorkspacePattern(root, p)))]
|
|
273
|
+
.filter((d) => !patterns.some((p) => p.startsWith("!") && expandWorkspacePattern(root, p.slice(1)).includes(d)))
|
|
274
|
+
.map((d) => readPackage(root, d))
|
|
275
|
+
.filter((p) => p !== null);
|
|
276
|
+
const pkg = readJson(join(root, "package.json"));
|
|
277
|
+
const allDeps = [pkg?.dependencies, pkg?.devDependencies].flatMap((d) => Object.keys(d && typeof d === "object" ? d : {}));
|
|
278
|
+
node = { manager, lockfile, yarnBerry: existsSync(join(root, ".yarnrc.yml")), root: rootPkg, workspaces, hasChant: allDeps.includes("@intentius/chant") };
|
|
279
|
+
}
|
|
280
|
+
const gomod = readText(join(root, "go.mod"));
|
|
281
|
+
const go = gomod === null ? null : { module: /^module\s+(\S+)/m.exec(gomod)?.[1] ?? null };
|
|
282
|
+
const cargo = readText(join(root, "Cargo.toml"));
|
|
283
|
+
const rust = cargo === null ? null : cargoFacts(cargo);
|
|
284
|
+
const pyproject = readText(join(root, "pyproject.toml"));
|
|
285
|
+
const python = pyproject === null ? (existsSync(join(root, "setup.py")) ? { name: null, pyproject: false, version: false } : null) : pyprojectFacts(pyproject);
|
|
286
|
+
const grFile = GORELEASER_FILES.find((f) => existsSync(join(root, f)));
|
|
287
|
+
const goreleaser = grFile ? { file: grFile, ...goreleaserFacts(readText(join(root, grFile)) ?? "") } : null;
|
|
288
|
+
const tagList = (git(top, ["tag", "--list"]) ?? "").split("\n").map((t) => t.trim()).filter(Boolean);
|
|
289
|
+
const chantDecl = readJson(join(root, "chant.workspace.json"));
|
|
290
|
+
const ciGreen = !!(chantDecl?.ci && typeof chantDecl.ci === "object" && chantDecl.ci.green);
|
|
291
|
+
const gitignore = [readText(join(root, ".gitignore")), path ? readText(join(top, ".gitignore")) : null].filter((t) => t !== null).join("\n");
|
|
292
|
+
return {
|
|
293
|
+
path,
|
|
294
|
+
origin,
|
|
295
|
+
workflowForge,
|
|
296
|
+
ciFiles,
|
|
297
|
+
node,
|
|
298
|
+
go,
|
|
299
|
+
rust,
|
|
300
|
+
python,
|
|
301
|
+
dockerfiles: findDockerfiles(root),
|
|
302
|
+
goreleaser,
|
|
303
|
+
tags: readTagHistory(tagList),
|
|
304
|
+
chantCi: ciGreen || tagList.some((t) => t.startsWith("ci/green/") || /^ci\/green-[^/]+\//.test(t)),
|
|
305
|
+
distIgnored: /^\/?dist\/?\s*$/m.test(gitignore) || /^\/?dist\/\*\s*$/m.test(gitignore),
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
/** Packages in dependency order: each after the packages of the list it depends on, ties by directory. */
|
|
309
|
+
export function dependencyOrder(pkgs) {
|
|
310
|
+
const byName = new Map(pkgs.filter((p) => p.name).map((p) => [p.name, p]));
|
|
311
|
+
const out = [];
|
|
312
|
+
const seen = new Set();
|
|
313
|
+
const visit = (p, stack) => {
|
|
314
|
+
if (seen.has(p.dir) || stack.has(p.dir))
|
|
315
|
+
return;
|
|
316
|
+
stack.add(p.dir);
|
|
317
|
+
for (const d of [...p.deps].sort()) {
|
|
318
|
+
const dep = byName.get(d);
|
|
319
|
+
if (dep)
|
|
320
|
+
visit(dep, stack);
|
|
321
|
+
}
|
|
322
|
+
stack.delete(p.dir);
|
|
323
|
+
seen.add(p.dir);
|
|
324
|
+
out.push(p);
|
|
325
|
+
};
|
|
326
|
+
for (const p of [...pkgs].sort((a, b) => a.dir.localeCompare(b.dir)))
|
|
327
|
+
visit(p, new Set());
|
|
328
|
+
return out;
|
|
329
|
+
}
|
|
330
|
+
/** The OCI repository an image is pushed to on the origin's forge registry, or null for a forge without one chant knows. */
|
|
331
|
+
function imageRepository(origin, image, single) {
|
|
332
|
+
if (!origin)
|
|
333
|
+
return null;
|
|
334
|
+
const repo = origin.repo.toLowerCase();
|
|
335
|
+
const suffix = single ? "" : `/${image}`;
|
|
336
|
+
if (origin.kind === "github")
|
|
337
|
+
return origin.host === "github.com" ? `ghcr.io/${repo}${suffix}` : null;
|
|
338
|
+
if (origin.kind === "gitlab")
|
|
339
|
+
return origin.host === "gitlab.com" ? `registry.gitlab.com/${repo}${suffix}` : null;
|
|
340
|
+
return `${origin.host}/${repo}${suffix}`;
|
|
341
|
+
}
|
|
342
|
+
function imageName(dockerfile, fallback) {
|
|
343
|
+
const dir = posix.dirname(dockerfile);
|
|
344
|
+
const raw = dir === "." ? fallback : basename(dir);
|
|
345
|
+
return raw.toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^[^a-z0-9]+/, "") || "image";
|
|
346
|
+
}
|
|
347
|
+
/** A tag prefix a `release.tag` template can hold. */
|
|
348
|
+
function templatePrefix(prefix) {
|
|
349
|
+
return TEMPLATE_PREFIX.test(prefix) && !prefix.startsWith("/") && !prefix.includes("..") && !prefix.includes("//");
|
|
350
|
+
}
|
|
351
|
+
/**
|
|
352
|
+
* The tag template a project's history asks for, and the prefixes to read
|
|
353
|
+
* older releases by. `packages` is how many packages one release publishes:
|
|
354
|
+
* with more than one, a prefix other than `v` names one package's tags, so
|
|
355
|
+
* the release gets `v{version}` and the older tags are only read.
|
|
356
|
+
*/
|
|
357
|
+
export function tagTemplateOf(facts, packages = 1) {
|
|
358
|
+
const h = facts.tags;
|
|
359
|
+
const goSub = facts.go && facts.path;
|
|
360
|
+
const legacy = [h.prefix, ...h.others.map((o) => o.prefix)].filter((p) => p !== null && p !== "" && templatePrefix(p));
|
|
361
|
+
const follows = h.prefix !== null && templatePrefix(h.prefix) && (packages <= 1 || h.prefix === "v" || h.prefix === "");
|
|
362
|
+
if (follows) {
|
|
363
|
+
const template = `${h.prefix}{version}`;
|
|
364
|
+
const goNote = facts.go && h.prefix !== (goSub ? `${facts.path}/v` : "v") ? `The Go module proxy reads ${goSub ? `${facts.path}/v<version>` : "v<version>"} tags, and this repository's are ${h.prefix}<version>.` : null;
|
|
365
|
+
return {
|
|
366
|
+
template,
|
|
367
|
+
legacy,
|
|
368
|
+
reason: `release.tag "${template}": ${h.count} existing tag${h.count === 1 ? "" : "s"} name releases this way, the newest ${h.newest}`,
|
|
369
|
+
note: goNote,
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
const template = goSub ? "{path}/v{version}" : "v{version}";
|
|
373
|
+
const why = h.prefix === null
|
|
374
|
+
? "no tag in the repository names a version"
|
|
375
|
+
: !templatePrefix(h.prefix)
|
|
376
|
+
? `the existing tags (${h.prefix}<version>) hold a character a release.tag template can't`
|
|
377
|
+
: `one release publishes ${packages} packages, and the existing ${h.prefix}<version> tags name one package's releases`;
|
|
378
|
+
return { template, legacy, reason: `release.tag "${template}": ${why}${goSub ? ", and a Go module in a subdirectory is tagged <path>/v<version>" : ""}`, note: null };
|
|
379
|
+
}
|
|
380
|
+
/** `release.green` for the project, with its reason, and a note when nothing checks its commits. */
|
|
381
|
+
function greenOf(facts, reasons, notes) {
|
|
382
|
+
reasons.push(facts.chantCi ? 'release.green "chant": chant ci writes ci/green tags here' : 'release.green "forge-checks": a commit may be released when its checks on the forge passed');
|
|
383
|
+
if (!facts.chantCi && facts.ciFiles.length === 0)
|
|
384
|
+
notes.push("No CI workflow runs on this repository's commits, and a cut refuses a commit with no checks: add CI, or set release.green to \"none\" to release with no gate.");
|
|
385
|
+
return facts.chantCi ? "chant" : "forge-checks";
|
|
386
|
+
}
|
|
387
|
+
/** The workflow's chant, install and build for a Node project, with their reasons. */
|
|
388
|
+
function nodeWorkflow(node, opts, workflow, reasons) {
|
|
389
|
+
if (!node.hasChant) {
|
|
390
|
+
workflow.chant = `npx --yes @intentius/chant@${opts.chantVersion}`;
|
|
391
|
+
reasons.push(`release.workflow.chant: @intentius/chant is not a dependency here, so the jobs run it from npm at ${opts.chantVersion}`);
|
|
392
|
+
}
|
|
393
|
+
const lockless = node.lockfile === null;
|
|
394
|
+
if (node.manager === "pnpm")
|
|
395
|
+
workflow.install = "corepack enable && pnpm install --frozen-lockfile";
|
|
396
|
+
else if (node.manager === "yarn")
|
|
397
|
+
workflow.install = `corepack enable && yarn install ${node.yarnBerry ? "--immutable" : "--frozen-lockfile"}`;
|
|
398
|
+
else if (lockless)
|
|
399
|
+
workflow.install = "npm install";
|
|
400
|
+
if (workflow.install)
|
|
401
|
+
reasons.push(`release.workflow.install: ${node.manager === "npm" ? "there is no package-lock.json for npm ci" : `the lockfile is ${node.manager}'s`}`);
|
|
402
|
+
if (node.manager !== "npm" && node.root.scripts.includes("build"))
|
|
403
|
+
workflow.build = `${node.manager} run build`;
|
|
404
|
+
}
|
|
405
|
+
/** Plan the `release` block for a project. */
|
|
406
|
+
export function planRelease(facts, opts) {
|
|
407
|
+
const release = {};
|
|
408
|
+
const reasons = [];
|
|
409
|
+
const notes = [];
|
|
410
|
+
const registry = [];
|
|
411
|
+
const publish = [];
|
|
412
|
+
const workflow = { trigger: "dispatch" };
|
|
413
|
+
const forge = facts.workflowForge;
|
|
414
|
+
const workflowFile = { github: ".github/workflows/chant-release.yml", forgejo: ".forgejo/workflows/chant-release.yml", gitlab: ".gitlab/chant-release.yml" }[forge];
|
|
415
|
+
const workflowName = posix.basename(workflowFile);
|
|
416
|
+
const node0 = facts.node;
|
|
417
|
+
const publishedCount = node0 ? (node0.workspaces ? [...(node0.root.private ? [] : [node0.root]), ...node0.workspaces] : [node0.root]).filter((p) => p.name && !p.private && !p.vscode).length : 0;
|
|
418
|
+
const tag = tagTemplateOf(facts, publishedCount);
|
|
419
|
+
release.tag = tag.template;
|
|
420
|
+
reasons.push(tag.reason);
|
|
421
|
+
if (tag.note)
|
|
422
|
+
notes.push(tag.note);
|
|
423
|
+
if (tag.legacy.length > 0) {
|
|
424
|
+
release.legacyTags = tag.legacy;
|
|
425
|
+
reasons.push(`release.legacyTags ${JSON.stringify(tag.legacy)}: chant release next and release changed read the newest ${tag.legacy.map((p) => `${p}<version>`).join(" or ")} tag as the last release until chant has cut one`);
|
|
426
|
+
}
|
|
427
|
+
const unread = [facts.tags.prefix, ...facts.tags.others.map((o) => o.prefix)].filter((p) => p !== null && p !== "" && !templatePrefix(p));
|
|
428
|
+
if (unread.length > 0)
|
|
429
|
+
notes.push(`Tags that no release.tag can make are left as they are: ${unread.slice(0, 5).map((p) => `${p}<version>`).join(", ")}.`);
|
|
430
|
+
release.green = greenOf(facts, reasons, notes);
|
|
431
|
+
// npm packages, and VS Code extensions.
|
|
432
|
+
const node = facts.node;
|
|
433
|
+
if (node) {
|
|
434
|
+
const candidates = node.workspaces ? [...(node.root.private ? [] : [node.root]), ...node.workspaces] : [node.root];
|
|
435
|
+
const named = candidates.filter((p) => p.name);
|
|
436
|
+
const extensions = named.filter((p) => p.vscode && !p.private);
|
|
437
|
+
const packages = dependencyOrder(named.filter((p) => !p.private && !p.vscode));
|
|
438
|
+
const skipped = named.filter((p) => p.private);
|
|
439
|
+
if (packages.length > 0) {
|
|
440
|
+
const dirs = packages.map((p) => p.dir);
|
|
441
|
+
const scopedUnset = packages.filter((p) => p.name.startsWith("@") && p.access === null);
|
|
442
|
+
const target = { type: "npm", packages: dirs };
|
|
443
|
+
if (scopedUnset.length > 0)
|
|
444
|
+
target.access = "public";
|
|
445
|
+
publish.push(target);
|
|
446
|
+
reasons.push(`npm target: ${packages.map((p) => p.name).join(", ")}${packages.length > 1 ? ", in dependency order" : ""}${scopedUnset.length > 0 ? `; access "public", since ${scopedUnset.map((p) => p.name).join(", ")} ${scopedUnset.length === 1 ? "is a scoped package" : "are scoped packages"} with no publishConfig.access` : ""}`);
|
|
447
|
+
const names = new Set(packages.map((p) => p.name));
|
|
448
|
+
const internal = packages.some((p) => p.deps.some((d) => names.has(d)));
|
|
449
|
+
release.version = internal ? { packages: dirs, ranges: "exact" } : { packages: dirs };
|
|
450
|
+
reasons.push(`release.version: the release stamps its label into ${dirs.length === 1 ? "the package's" : "each package's"} package.json, so a release needs no version commit${internal ? '; ranges "exact", so each package depends on the versions released beside it' : ""}`);
|
|
451
|
+
const list = packages.map((p) => p.name).join(", ");
|
|
452
|
+
const one = packages.length === 1;
|
|
453
|
+
registry.push(`npm ${list}: on npmjs.com, add a trusted publisher to ${one ? "the package" : "each package"} for ${forge === "gitlab" ? `GitLab CI/CD naming ${facts.origin?.repo ?? "this project"} and the top-level config .gitlab-ci.yml` : `${forge === "github" ? "GitHub Actions" : "this forge"} naming ${facts.origin?.repo ?? "this repository"} and the workflow file ${workflowName}`}, and allow npm dist-tag, since the reveal moves latest. A package that is not on npm yet needs its first version published by hand before it has settings.`);
|
|
454
|
+
}
|
|
455
|
+
if (skipped.length > 0)
|
|
456
|
+
notes.push(`Not published, being private: ${skipped.map((p) => p.name).join(", ")}.`);
|
|
457
|
+
for (const ext of extensions) {
|
|
458
|
+
const vsix = `${ext.dir === "." ? "" : `${ext.dir}/`}dist/${ext.name.replace(/^@[^/]+\//, "")}.vsix`;
|
|
459
|
+
publish.push({ type: "marketplace", marketplace: "vscode", vsix });
|
|
460
|
+
publish.push({ type: "marketplace", marketplace: "openvsx", vsix, auth: "trusted-publishing" });
|
|
461
|
+
reasons.push(`marketplace targets: ${ext.name} is a VS Code extension, published to the VS Code Marketplace and Open VSX from ${vsix}`);
|
|
462
|
+
notes.push(`The build must write ${vsix}, such as with vsce package -o ${vsix}, and the VS Code Marketplace target needs vsce on PATH.`);
|
|
463
|
+
// A GitLab job gets the project's CI/CD variables as they are.
|
|
464
|
+
if (forge !== "gitlab")
|
|
465
|
+
workflow.env = { ...(workflow.env ?? {}), VSCE_PAT: "${{ secrets.VSCE_PAT }}" };
|
|
466
|
+
registry.push(`VS Code Marketplace ${ext.publisher ?? "<publisher>"}.${ext.name}: create a personal access token with Marketplace (Manage) scope and store it as the ${forge === "gitlab" ? "masked CI/CD variable" : "repository secret"} VSCE_PAT.`);
|
|
467
|
+
registry.push(`Open VSX ${ext.publisher ?? "<publisher>"}.${ext.name}: create the namespace ${ext.publisher ?? "<publisher>"} once, and add ${facts.origin?.repo ?? "this repository"} with the workflow file ${workflowName} under the extension's trusted publishers at https://open-vsx.org/user-settings/trusted-publishers.`);
|
|
468
|
+
}
|
|
469
|
+
nodeWorkflow(node, opts, workflow, reasons);
|
|
470
|
+
}
|
|
471
|
+
// Images.
|
|
472
|
+
const goreleaserImages = facts.goreleaser?.images ?? false;
|
|
473
|
+
const dockerfiles = goreleaserImages ? [] : facts.dockerfiles;
|
|
474
|
+
if (goreleaserImages && facts.dockerfiles.length > 0)
|
|
475
|
+
notes.push(`${facts.goreleaser.file} builds the images, so no Dockerfile is declared in release.images.`);
|
|
476
|
+
const fallbackName = (facts.origin?.repo.split("/").pop() ?? facts.node?.root.name?.replace(/^@[^/]+\//, "") ?? facts.go?.module?.split("/").pop() ?? "app");
|
|
477
|
+
const images = [];
|
|
478
|
+
const usedNames = new Set();
|
|
479
|
+
for (const dockerfile of dockerfiles) {
|
|
480
|
+
let name = imageName(dockerfile, fallbackName);
|
|
481
|
+
while (usedNames.has(name))
|
|
482
|
+
name = `${name}-${usedNames.size}`;
|
|
483
|
+
usedNames.add(name);
|
|
484
|
+
const dir = posix.dirname(dockerfile);
|
|
485
|
+
images.push(dir === "." ? { name, dockerfile } : { name, dockerfile, context: dir });
|
|
486
|
+
const repository = imageRepository(facts.origin, name, dockerfiles.length === 1);
|
|
487
|
+
if (repository) {
|
|
488
|
+
publish.push({ type: "oci", image: `dist/images/${name}.tar`, repository });
|
|
489
|
+
if (repository.startsWith("ghcr.io/"))
|
|
490
|
+
registry.push(`${repository}: the workflow pushes with the run's token. The first push makes the package private; make it public in the package's settings if it should be.`);
|
|
491
|
+
else
|
|
492
|
+
registry.push(`${repository}: set OCI_USERNAME and OCI_PASSWORD for the release workflow, as ${forge === "gitlab" ? "masked CI/CD variables" : "secrets in release.workflow.env"}, with push access to the registry.`);
|
|
493
|
+
}
|
|
494
|
+
else
|
|
495
|
+
notes.push(`${dockerfile} is built into release.images as ${name}, and no oci target is declared: origin names no registry chant knows. Add { type: "oci", image: "dist/images/${name}.tar", repository: "<registry>/<name>" }.`);
|
|
496
|
+
}
|
|
497
|
+
if (images.length > 0) {
|
|
498
|
+
release.images = images;
|
|
499
|
+
reasons.push(`release.images: ${dockerfiles.join(", ")} built once at the cut as reproducible OCI archives${publish.some((p) => p.type === "oci") ? ", pushed by the oci target" : ""}`);
|
|
500
|
+
}
|
|
501
|
+
// goreleaser.
|
|
502
|
+
let goreleaserPatch = null;
|
|
503
|
+
if (facts.goreleaser) {
|
|
504
|
+
const gr = facts.goreleaser;
|
|
505
|
+
if (!gr.labelTemplate) {
|
|
506
|
+
goreleaserPatch = gr.snapshot
|
|
507
|
+
? { file: gr.file, append: null, manual: `Set snapshot.version_template to "{{ .Env.CHANT_RELEASE_LABEL }}" in ${gr.file}, so the snapshot build carries the release's label.` }
|
|
508
|
+
: { file: gr.file, append: GORELEASER_SNAPSHOT, manual: null };
|
|
509
|
+
}
|
|
510
|
+
release.artifacts = [{ name: "goreleaser", goreleaser: {} }];
|
|
511
|
+
reasons.push(`release.artifacts: ${gr.file} builds the binaries and archives once at the cut with goreleaser release --snapshot, and the release records each file`);
|
|
512
|
+
if (facts.origin) {
|
|
513
|
+
publish.push({ type: "forge", forge: facts.origin.kind, repo: facts.origin.repo, assets: ["artifact:goreleaser"], notes: { generate: "forge" } });
|
|
514
|
+
reasons.push(`forge target: the goreleaser files as assets of the ${facts.origin.kind} release ${facts.origin.repo}, with generated notes`);
|
|
515
|
+
}
|
|
516
|
+
else
|
|
517
|
+
notes.push(`No forge release is declared for ${gr.file}'s files: origin names no GitHub, GitLab or Forgejo repository.`);
|
|
518
|
+
}
|
|
519
|
+
// Python and Rust packages.
|
|
520
|
+
const versionFiles = [];
|
|
521
|
+
const trustedRepo = facts.origin?.repo ?? "this repository";
|
|
522
|
+
const trustedFor = (what) => forge === "gitlab" ? `GitLab CI/CD naming ${trustedRepo} and the top-level pipeline file .gitlab-ci.yml` : `${what} naming ${trustedRepo} and the workflow file ${workflowName}`;
|
|
523
|
+
const py = facts.python;
|
|
524
|
+
if (py?.pyproject && py.name) {
|
|
525
|
+
const forgejo = forge === "forgejo";
|
|
526
|
+
const entry = { name: "python", build: "python -m pip install build && python -m build", outputs: ["dist/*"] };
|
|
527
|
+
release.artifacts = [...(release.artifacts ?? []), entry];
|
|
528
|
+
publish.push({ type: "pypi", files: ["artifact:python"], auth: forgejo ? "token" : "trusted-publishing" });
|
|
529
|
+
reasons.push(`release.artifacts: ${py.name} is built once at the cut with python -m build, and the release records the sdist and wheel in dist/`);
|
|
530
|
+
reasons.push(`pypi target: the recorded files of ${py.name}, uploaded to PyPI ${forgejo ? "with the token in PYPI_TOKEN" : "with trusted publishing"}`);
|
|
531
|
+
if (py.version)
|
|
532
|
+
versionFiles.push("pyproject.toml");
|
|
533
|
+
else
|
|
534
|
+
notes.push("pyproject.toml has no static version (it is dynamic, or unset), so release.version does not stamp it: the build takes the version from wherever the project sets it.");
|
|
535
|
+
if (forgejo) {
|
|
536
|
+
workflow.env = { ...(workflow.env ?? {}), PYPI_TOKEN: "${{ secrets.PYPI_TOKEN }}" };
|
|
537
|
+
registry.push(`PyPI ${py.name}: create an API token for the project on pypi.org and store it as the secret PYPI_TOKEN; PyPI has no trusted publisher for this forge.`);
|
|
538
|
+
}
|
|
539
|
+
else {
|
|
540
|
+
registry.push(`PyPI ${py.name}: on pypi.org add a trusted publisher to the project's publishing settings (a pending publisher if the project does not exist yet) for ${trustedFor("GitHub Actions")}.${forge === "github" ? " A GitHub publisher can name an environment; leave it empty, since the workflow runs in none." : ""}`);
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
else if (py)
|
|
544
|
+
notes.push(`${py.name ?? "The Python package"} is tagged and not published to PyPI: ${py.pyproject ? "pyproject.toml has no [project] name" : "there is no pyproject.toml for python -m build to read"}. Add a pypi target to release.publish when it is.`);
|
|
545
|
+
const rs = facts.rust;
|
|
546
|
+
if (rs && !rs.unpublishable && (rs.name || rs.workspace)) {
|
|
547
|
+
publish.push({ type: "cargo" });
|
|
548
|
+
reasons.push(`cargo target: ${rs.name ?? "the workspace's crates"}${rs.workspace && rs.name ? " and its workspace members" : ""} published with cargo publish, in dependency order`);
|
|
549
|
+
if (rs.version)
|
|
550
|
+
versionFiles.push("Cargo.toml");
|
|
551
|
+
else
|
|
552
|
+
notes.push("Cargo.toml has no [package] or [workspace.package] version at the root, so release.version does not stamp it: add the member crates' Cargo.toml files to release.version.files.");
|
|
553
|
+
registry.push(`crates.io ${rs.name ?? "each crate"}: ${forge === "github" ? `add a trusted publisher to ${rs.name ? "the crate" : "each crate"} on crates.io for GitHub Actions naming ${trustedRepo} and the workflow file ${workflowName}. A crate's first version can't be published that way: publish it by hand, or store a token that may publish new crates as the secret CARGO_REGISTRY_TOKEN and set CARGO_REGISTRY_TOKEN: "\${{ secrets.CARGO_REGISTRY_TOKEN }}" in release.workflow.env.` : `create an API token that may publish ${rs.name ? "the crate" : "the crates"} and store it as the ${forge === "gitlab" ? "masked CI/CD variable" : "secret"} CARGO_REGISTRY_TOKEN${forge === "gitlab" ? "." : ", and set CARGO_REGISTRY_TOKEN: \"${{ secrets.CARGO_REGISTRY_TOKEN }}\" in release.workflow.env."}`}`);
|
|
554
|
+
}
|
|
555
|
+
else if (rs)
|
|
556
|
+
notes.push(`${rs.name ?? "The crate"} is tagged and not published to crates.io: ${rs.unpublishable ? "Cargo.toml sets publish = false" : "Cargo.toml has no [package] name or [workspace]"}.`);
|
|
557
|
+
if (versionFiles.length > 0) {
|
|
558
|
+
const current = release.version ?? {};
|
|
559
|
+
release.version = { ...current, files: versionFiles };
|
|
560
|
+
reasons.push(`release.version.files: the release stamps its label into ${versionFiles.join(" and ")}, so a release needs no version commit`);
|
|
561
|
+
}
|
|
562
|
+
if (facts.go && !facts.goreleaser)
|
|
563
|
+
reasons.push(`Go module ${facts.go.module ?? ""}: the tag is the release the Go module proxy reads; nothing else is published`.replace(" ", " "));
|
|
564
|
+
if (publish.length > 0)
|
|
565
|
+
release.publish = publish;
|
|
566
|
+
else
|
|
567
|
+
notes.push("No publish target was found: the release records the commit and makes its tag. Add targets to release.publish as the project needs them.");
|
|
568
|
+
release.workflow = workflow;
|
|
569
|
+
reasons.push(`release.workflow: a release started by hand with its label from ${workflowFile}, which cuts a green commit and publishes it`);
|
|
570
|
+
if (!facts.distIgnored && (images.length > 0 || facts.goreleaser || publish.some((p) => p.type === "pypi") || publish.some((p) => p.type === "marketplace")))
|
|
571
|
+
notes.push("dist/ is not in .gitignore: the publish refuses a tree with build outputs git does not ignore.");
|
|
572
|
+
if (forge === "gitlab")
|
|
573
|
+
registry.push(`GitLab: include ${workflowFile} from .gitlab-ci.yml, and store a project access token with write_repository as the masked CI/CD variable CHANT_RELEASE_TOKEN; the cut and publish jobs push with it.`);
|
|
574
|
+
const h = facts.tags.prefix;
|
|
575
|
+
const readsHistory = h !== null && (tag.legacy.includes(h) || tag.template === `${h}{version}`);
|
|
576
|
+
return { release, reasons, notes, registry, workflowFile, goreleaserPatch, readsHistory };
|
|
577
|
+
}
|
|
578
|
+
/** The environment a planned train is recorded for. */
|
|
579
|
+
export const TRAIN_ENV = "npm";
|
|
580
|
+
/**
|
|
581
|
+
* Whether the project's npm, pnpm or yarn workspaces can release as a train:
|
|
582
|
+
* one member per publishable package (#5154). `why` says why a project with
|
|
583
|
+
* several packages gets one release instead, and is null for a project with
|
|
584
|
+
* fewer than two.
|
|
585
|
+
*/
|
|
586
|
+
export function trainFit(facts) {
|
|
587
|
+
const node = facts.node;
|
|
588
|
+
if (!node?.workspaces)
|
|
589
|
+
return { train: false, why: null };
|
|
590
|
+
const published = (p) => p.name !== null && !p.private && !p.vscode;
|
|
591
|
+
const packages = node.workspaces.filter(published);
|
|
592
|
+
const rootPublished = published(node.root);
|
|
593
|
+
if (packages.length + (rootPublished ? 1 : 0) < 2)
|
|
594
|
+
return { train: false, why: null };
|
|
595
|
+
if (rootPublished)
|
|
596
|
+
return { train: false, why: `the root package ${node.root.name} is published too, and a train releases the packages below the root` };
|
|
597
|
+
const ext = [node.root, ...node.workspaces].find((p) => p.vscode && !p.private && p.name);
|
|
598
|
+
if (ext)
|
|
599
|
+
return { train: false, why: `${ext.name} is a VS Code extension, and its .vsix is a file the train workflow does not hand from its cut job to its publish job` };
|
|
600
|
+
if (facts.goreleaser)
|
|
601
|
+
return { train: false, why: `${facts.goreleaser.file} builds files at the cut, which the train workflow does not hand between its jobs` };
|
|
602
|
+
if (facts.dockerfiles.length > 0)
|
|
603
|
+
return { train: false, why: `${facts.dockerfiles[0]} is an image built at the cut, which the train workflow does not hand between its jobs` };
|
|
604
|
+
if (facts.python?.pyproject && facts.python.name)
|
|
605
|
+
return { train: false, why: "pyproject.toml is built at the cut, which the train workflow does not hand between its jobs" };
|
|
606
|
+
if (facts.rust && !facts.rust.unpublishable && (facts.rust.name || facts.rust.workspace))
|
|
607
|
+
return { train: false, why: "Cargo.toml's crates publish beside the npm packages, and a train releases npm packages" };
|
|
608
|
+
if (facts.workflowForge === "gitlab")
|
|
609
|
+
return { train: false, why: "the train workflow renders for GitHub and Forgejo, and this repository runs GitLab CI" };
|
|
610
|
+
return { train: true };
|
|
611
|
+
}
|
|
612
|
+
/** A workspace member name (lowercase letters, digits and dashes, at most 40) for a package. */
|
|
613
|
+
export function memberNameOf(pkg) {
|
|
614
|
+
const clean = (s) => s.toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^[^a-z0-9]+/, "").replace(/-+$/, "").slice(0, 40).replace(/-+$/, "");
|
|
615
|
+
return clean(pkg.name?.replace(/^@[^/]+\//, "") ?? "") || clean(posix.basename(pkg.dir)) || "package";
|
|
616
|
+
}
|
|
617
|
+
/** The tag prefixes of a history that name one package's releases: `core-v`, `core/v`, `@acme/core@`, `packages/core/v`. */
|
|
618
|
+
function ownPrefixes(h, pkg, member) {
|
|
619
|
+
const names = new Set([pkg.name, pkg.name?.replace(/^@[^/]+\//, ""), member, pkg.dir, posix.basename(pkg.dir)].filter((n) => !!n));
|
|
620
|
+
return [h.prefix, ...h.others.map((o) => o.prefix)].filter((p) => p !== null && p !== "" && names.has(p.replace(/[/@_-]v?$/, "")));
|
|
621
|
+
}
|
|
622
|
+
/**
|
|
623
|
+
* Plan a train for a project {@link trainFit} accepts: a member per
|
|
624
|
+
* publishable workspace package, each stamping and publishing its own
|
|
625
|
+
* package, and the root's `release.train` with a dispatched workflow.
|
|
626
|
+
*/
|
|
627
|
+
export function planTrain(facts, opts) {
|
|
628
|
+
const node = facts.node;
|
|
629
|
+
const reasons = [];
|
|
630
|
+
const notes = [];
|
|
631
|
+
const registry = [];
|
|
632
|
+
const forge = facts.workflowForge;
|
|
633
|
+
const workflowFile = { github: ".github/workflows/chant-release.yml", forgejo: ".forgejo/workflows/chant-release.yml", gitlab: ".gitlab/chant-release.yml" }[forge];
|
|
634
|
+
const workflowName = posix.basename(workflowFile);
|
|
635
|
+
const env = TRAIN_ENV;
|
|
636
|
+
const named = node.workspaces.filter((p) => p.name);
|
|
637
|
+
const packages = dependencyOrder(named.filter((p) => !p.private && !p.vscode));
|
|
638
|
+
const skipped = named.filter((p) => p.private);
|
|
639
|
+
const names = new Set(packages.map((p) => p.name));
|
|
640
|
+
const greenReasons = [];
|
|
641
|
+
const green = greenOf(facts, greenReasons, notes);
|
|
642
|
+
// Member names, unique.
|
|
643
|
+
const used = new Set();
|
|
644
|
+
const memberNames = packages.map((p) => {
|
|
645
|
+
const base = memberNameOf(p);
|
|
646
|
+
let name = base;
|
|
647
|
+
for (let i = 2; used.has(name); i++)
|
|
648
|
+
name = `${base.slice(0, 38)}-${i}`;
|
|
649
|
+
used.add(name);
|
|
650
|
+
return name;
|
|
651
|
+
});
|
|
652
|
+
// Tags: a package's own history keeps its prefix; tags shared by every package are the root's legacy tags.
|
|
653
|
+
const h = facts.tags;
|
|
654
|
+
const claimed = new Set();
|
|
655
|
+
const members = packages.map((p, i) => {
|
|
656
|
+
const name = memberNames[i];
|
|
657
|
+
const own = ownPrefixes(h, p, name);
|
|
658
|
+
for (const o of own)
|
|
659
|
+
claimed.add(o);
|
|
660
|
+
const template = own.find(templatePrefix);
|
|
661
|
+
const release = { tag: template ? `${template}{version}` : "{member}/v{version}" };
|
|
662
|
+
const legacy = own.filter((o) => o !== template);
|
|
663
|
+
if (legacy.length > 0)
|
|
664
|
+
release.legacyTags = legacy;
|
|
665
|
+
release.green = green;
|
|
666
|
+
const internal = p.deps.some((d) => names.has(d) && d !== p.name);
|
|
667
|
+
release.version = internal ? { packages: ["."], ranges: "train" } : { packages: ["."] };
|
|
668
|
+
const target = { type: "npm", packages: ["."] };
|
|
669
|
+
if (p.name.startsWith("@") && p.access === null)
|
|
670
|
+
target.access = "public";
|
|
671
|
+
release.publish = [target];
|
|
672
|
+
return { name, dir: p.dir, package: p.name, release };
|
|
673
|
+
});
|
|
674
|
+
const shared = [h.prefix, ...h.others.map((o) => o.prefix)].filter((p) => p !== null && p !== "" && !claimed.has(p));
|
|
675
|
+
const release = { train: shared.length > 0 ? { env, first: "together" } : { env } };
|
|
676
|
+
reasons.push(`release.train: ${packages.length} packages, each a workspace member released at its own version; chant workspace train cut ${env} cuts every member that changed since its last release, and the train publishes them in dependency order${shared.length > 0 ? `. first "together": the packages have shared ${shared.map((p) => `${p}<version>`).join(" and ")} releases, so the first train gives every package one label past the highest version any has, and each later train labels each on its own` : ""}`);
|
|
677
|
+
if (shared.length > 0) {
|
|
678
|
+
release.legacyTags = shared;
|
|
679
|
+
reasons.push(`release.legacyTags ${JSON.stringify(shared)}: chant release changed reads the newest ${shared.map((p) => `${p}<version>`).join(" or ")} tag as every package's last release until the train has cut one`);
|
|
680
|
+
}
|
|
681
|
+
release.green = green;
|
|
682
|
+
reasons.push(...greenReasons);
|
|
683
|
+
const workflow = { trigger: "dispatch" };
|
|
684
|
+
nodeWorkflow(node, opts, workflow, reasons);
|
|
685
|
+
release.workflow = workflow;
|
|
686
|
+
reasons.push(`release.workflow: ${workflowFile}, started by hand with the levels, cuts the train from a green commit and publishes it`);
|
|
687
|
+
for (const m of members) {
|
|
688
|
+
const tag = m.release.tag;
|
|
689
|
+
const ranges = m.release.version.ranges;
|
|
690
|
+
const access = m.release.publish[0].access;
|
|
691
|
+
reasons.push(`${m.dir}/chant.config.ts, member ${m.name}: ${m.package} stamped with its label and published to npm${access ? ' with access "public"' : ""}, tagged ${tag}${ranges ? `; ranges "train", so its range on a sibling names the version the train gives it` : ""}${m.release.legacyTags ? `; its ${m.release.legacyTags.map((p) => `${p}<version>`).join(" and ")} tags read as earlier releases` : ""}`);
|
|
692
|
+
}
|
|
693
|
+
if (skipped.length > 0)
|
|
694
|
+
notes.push(`Not published, being private: ${skipped.map((p) => p.name).join(", ")}. The train's publish job builds ${skipped.length === 1 ? "it" : "them"} when a member needs ${skipped.length === 1 ? "it" : "them"}.`);
|
|
695
|
+
const packed = packages.filter((p) => !p.packList);
|
|
696
|
+
if (packed.length > 0)
|
|
697
|
+
notes.push(`npm packs a package's chant.config.ts with it unless package.json files or an .npmignore leaves it out: ${packed.map((p) => p.name).join(", ")} ${packed.length === 1 ? "has" : "have"} neither.`);
|
|
698
|
+
const repo = facts.origin?.repo ?? "this repository";
|
|
699
|
+
for (const m of members) {
|
|
700
|
+
registry.push(`npm ${m.package}: on npmjs.com, add a trusted publisher for ${forge === "github" ? "GitHub Actions" : "this forge"} naming ${repo} and the workflow file ${workflowName}, and allow npm dist-tag, since the reveal moves latest. Every package names the same file. If ${m.package} is not on npm yet, publish its first version by hand from ${m.dir} (npm publish) so it has settings; the train labels the next past it.`);
|
|
701
|
+
}
|
|
702
|
+
const workspaceName = memberNameOf({ name: facts.origin?.repo.split("/").pop() ?? node.root.name ?? null, dir: facts.path ?? "workspace" }) || "workspace";
|
|
703
|
+
return { release, members, workspaceName, reasons, notes, registry, workflowFile, env };
|
|
704
|
+
}
|
|
705
|
+
const IDENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
|
706
|
+
/** A value as TypeScript source, objects and arrays on one line when short. */
|
|
707
|
+
export function toSource(value, indent, step = " ") {
|
|
708
|
+
if (value === null || typeof value !== "object")
|
|
709
|
+
return JSON.stringify(value);
|
|
710
|
+
const inner = indent + step;
|
|
711
|
+
if (Array.isArray(value)) {
|
|
712
|
+
const items = value.map((v) => toSource(v, inner, step));
|
|
713
|
+
const flat = `[${items.join(", ")}]`;
|
|
714
|
+
return flat.length + indent.length <= 100 && !flat.includes("\n") ? flat : `[\n${items.map((i) => `${inner}${i},`).join("\n")}\n${indent}]`;
|
|
715
|
+
}
|
|
716
|
+
const entries = Object.entries(value).map(([k, v]) => `${IDENT.test(k) ? k : JSON.stringify(k)}: ${toSource(v, inner, step)}`);
|
|
717
|
+
if (entries.length === 0)
|
|
718
|
+
return "{}";
|
|
719
|
+
const flat = `{ ${entries.join(", ")} }`;
|
|
720
|
+
return flat.length + indent.length <= 100 && !flat.includes("\n") ? flat : `{\n${entries.map((e) => `${inner}${e},`).join("\n")}\n${indent}}`;
|
|
721
|
+
}
|
|
722
|
+
/** The `release:` property as source, at `indent`, expanded one level so each field is on its own line. */
|
|
723
|
+
export function releaseBlockSource(release, indent, step = " ") {
|
|
724
|
+
const inner = indent + step;
|
|
725
|
+
return `release: {\n${Object.entries(release).map(([k, v]) => `${inner}${k}: ${toSource(v, inner, step)},`).join("\n")}\n${indent}}`;
|
|
726
|
+
}
|
|
727
|
+
/** A config made of the release block alone. */
|
|
728
|
+
export function newConfigSource(release) {
|
|
729
|
+
return `// chant.config.ts: what chant release cuts and publishes. See https://intentius.io/chant/cli/release/\nexport default {\n ${releaseBlockSource(release, " ")},\n};\n`;
|
|
730
|
+
}
|
|
731
|
+
/**
|
|
732
|
+
* Walk TypeScript source from `from`, skipping strings, template literals and
|
|
733
|
+
* comments, and call `visit` at each other character with the brace depth
|
|
734
|
+
* relative to `from`. Stops when `visit` returns true.
|
|
735
|
+
*/
|
|
736
|
+
function scan(src, from, visit) {
|
|
737
|
+
let depth = 0;
|
|
738
|
+
for (let i = from; i < src.length; i++) {
|
|
739
|
+
const c = src[i];
|
|
740
|
+
const n = src[i + 1];
|
|
741
|
+
if (c === "/" && n === "/") {
|
|
742
|
+
i = src.indexOf("\n", i);
|
|
743
|
+
if (i < 0)
|
|
744
|
+
return;
|
|
745
|
+
continue;
|
|
746
|
+
}
|
|
747
|
+
if (c === "/" && n === "*") {
|
|
748
|
+
i = src.indexOf("*/", i + 2);
|
|
749
|
+
if (i < 0)
|
|
750
|
+
return;
|
|
751
|
+
i++;
|
|
752
|
+
continue;
|
|
753
|
+
}
|
|
754
|
+
if (c === '"' || c === "'" || c === "`") {
|
|
755
|
+
for (i++; i < src.length && src[i] !== c; i++)
|
|
756
|
+
if (src[i] === "\\")
|
|
757
|
+
i++;
|
|
758
|
+
// The closing quote is visited, so a caller sees where the string ends.
|
|
759
|
+
if (i < src.length && visit(i, depth))
|
|
760
|
+
return;
|
|
761
|
+
continue;
|
|
762
|
+
}
|
|
763
|
+
if (c === "{" || c === "[" || c === "(")
|
|
764
|
+
depth++;
|
|
765
|
+
if (visit(i, depth))
|
|
766
|
+
return;
|
|
767
|
+
if (c === "}" || c === "]" || c === ")")
|
|
768
|
+
depth--;
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
/** Where the object a config's default export is opens, or -1. */
|
|
772
|
+
function defaultObjectStart(src) {
|
|
773
|
+
let at = -1;
|
|
774
|
+
scan(src, 0, (i, depth) => {
|
|
775
|
+
if (depth === 0 && src.startsWith("export default", i)) {
|
|
776
|
+
at = i + "export default".length;
|
|
777
|
+
return true;
|
|
778
|
+
}
|
|
779
|
+
return false;
|
|
780
|
+
});
|
|
781
|
+
if (at < 0)
|
|
782
|
+
return -1;
|
|
783
|
+
const rest = src.slice(at);
|
|
784
|
+
const direct = /^\s*(?:(?:[A-Za-z_$][\w$.]*\s*(?:<[^>]*>)?\s*)?\(\s*)?\{/.exec(rest);
|
|
785
|
+
if (direct)
|
|
786
|
+
return at + direct[0].length - 1;
|
|
787
|
+
const ident = /^\s*([A-Za-z_$][\w$]*)\s*(?:;|$|\n|satisfies|as)/.exec(rest);
|
|
788
|
+
if (!ident)
|
|
789
|
+
return -1;
|
|
790
|
+
const decl = new RegExp(`(?:const|let|var)\\s+${ident[1]}\\s*(?::[^=]+)?=\\s*(?:[A-Za-z_$][\\w$.]*\\s*\\(\\s*)?\\{`).exec(src);
|
|
791
|
+
return decl ? decl.index + decl[0].length - 1 : -1;
|
|
792
|
+
}
|
|
793
|
+
/** The end (exclusive) of the bracketed value that opens at `open`. */
|
|
794
|
+
function closeOf(src, open) {
|
|
795
|
+
let end = -1;
|
|
796
|
+
scan(src, open, (i, depth) => {
|
|
797
|
+
if (depth === 1 && i > open && "}])".includes(src[i])) {
|
|
798
|
+
end = i + 1;
|
|
799
|
+
return true;
|
|
800
|
+
}
|
|
801
|
+
return false;
|
|
802
|
+
});
|
|
803
|
+
return end;
|
|
804
|
+
}
|
|
805
|
+
/**
|
|
806
|
+
* Write `release` into a chant.config.ts's default export: before the
|
|
807
|
+
* object's closing brace, or in place of an existing `release` property
|
|
808
|
+
* when `force`. Throws {@link ReleaseInitError}: `release-init-release-exists`
|
|
809
|
+
* for a `release` property without `force`, `release-init-config-unreadable`
|
|
810
|
+
* when the default export is not an object literal this can find.
|
|
811
|
+
*/
|
|
812
|
+
export function insertReleaseBlock(src, release, force) {
|
|
813
|
+
const open = defaultObjectStart(src);
|
|
814
|
+
const close = open < 0 ? -1 : closeOf(src, open);
|
|
815
|
+
if (open < 0 || close < 0) {
|
|
816
|
+
throw new ReleaseInitError("release-init-config-unreadable", "chant.config.ts has no default export of an object literal to add release to", "Add the release block shown here to the config by hand.");
|
|
817
|
+
}
|
|
818
|
+
// The indentation of the object's properties.
|
|
819
|
+
const firstProp = /\n([ \t]+)\S/.exec(src.slice(open, close));
|
|
820
|
+
const lineStart = src.lastIndexOf("\n", open) + 1;
|
|
821
|
+
const outer = /^[ \t]*/.exec(src.slice(lineStart))[0];
|
|
822
|
+
const indent = firstProp ? firstProp[1] : `${outer} `;
|
|
823
|
+
const step = indent.length > outer.length ? indent.slice(outer.length) : " ";
|
|
824
|
+
const block = releaseBlockSource(release, indent, step);
|
|
825
|
+
let keyAt = -1;
|
|
826
|
+
scan(src, open, (i, depth) => {
|
|
827
|
+
if (i >= close)
|
|
828
|
+
return true;
|
|
829
|
+
if (depth === 1 && /[\s{,]/.test(src[i - 1] ?? "") && /^(?:release|"release"|'release')\s*:/.test(src.slice(i))) {
|
|
830
|
+
keyAt = i;
|
|
831
|
+
return true;
|
|
832
|
+
}
|
|
833
|
+
return false;
|
|
834
|
+
});
|
|
835
|
+
if (keyAt >= 0) {
|
|
836
|
+
if (!force)
|
|
837
|
+
throw new ReleaseInitError("release-init-release-exists", "chant.config.ts already has a release block", "Run again with --force to replace it, or add the fields shown here to it by hand.");
|
|
838
|
+
const valueAt = keyAt + /^[^:]*:\s*/.exec(src.slice(keyAt))[0].length;
|
|
839
|
+
if (src[valueAt] !== "{")
|
|
840
|
+
throw new ReleaseInitError("release-init-config-unreadable", "the release property in chant.config.ts is not an object literal", "Replace it with the release block shown here by hand.");
|
|
841
|
+
const end = closeOf(src, valueAt);
|
|
842
|
+
return src.slice(0, keyAt) + block + src.slice(end);
|
|
843
|
+
}
|
|
844
|
+
// Before the closing brace, after the last property, its comma, and a comment on its line.
|
|
845
|
+
const brace = close - 1;
|
|
846
|
+
let last = open;
|
|
847
|
+
scan(src, open, (i) => {
|
|
848
|
+
if (i >= brace)
|
|
849
|
+
return true;
|
|
850
|
+
if (!/\s/.test(src[i]))
|
|
851
|
+
last = i;
|
|
852
|
+
return false;
|
|
853
|
+
});
|
|
854
|
+
const needsComma = last !== open && src[last] !== ",";
|
|
855
|
+
const lineEnd = src.indexOf("\n", last);
|
|
856
|
+
const tail = lineEnd >= 0 && lineEnd < brace ? lineEnd : last + 1;
|
|
857
|
+
const head = src.slice(0, last + 1) + (needsComma ? "," : "") + src.slice(last + 1, tail).replace(/\s+$/, "");
|
|
858
|
+
return `${head}\n${indent}${block},\n${outer}${src.slice(brace)}`;
|
|
859
|
+
}
|