@intentius/chant 0.124.80 → 0.124.84

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 (56) hide show
  1. package/dist/cli/handlers/notify-relay.js +1 -1
  2. package/dist/components/capability.d.ts +11 -0
  3. package/dist/components/capability.d.ts.map +1 -1
  4. package/dist/lifecycle/__fixtures__/publish-fakes.d.ts +14 -1
  5. package/dist/lifecycle/__fixtures__/publish-fakes.d.ts.map +1 -1
  6. package/dist/lifecycle/__fixtures__/publish-fakes.js +14 -4
  7. package/dist/lifecycle/publish-oci.d.ts +4 -0
  8. package/dist/lifecycle/publish-oci.d.ts.map +1 -1
  9. package/dist/lifecycle/publish-oci.js +90 -20
  10. package/dist/notify-relay.d.ts +6 -1
  11. package/dist/notify-relay.d.ts.map +1 -1
  12. package/dist/notify-relay.js +4 -1
  13. package/dist/op/index.d.ts +1 -1
  14. package/dist/op/index.d.ts.map +1 -1
  15. package/dist/op/index.js +1 -1
  16. package/dist/op/op-waves-after-plan.d.ts.map +1 -1
  17. package/dist/op/op-waves-after-plan.js +1 -2
  18. package/dist/op/op-waves-capability.d.ts +9 -0
  19. package/dist/op/op-waves-capability.d.ts.map +1 -1
  20. package/dist/op/op-waves-capability.js +9 -2
  21. package/dist/op/op-waves-run.d.ts.map +1 -1
  22. package/dist/op/op-waves-run.js +49 -10
  23. package/dist/op/op-waves.d.ts +9 -5
  24. package/dist/op/op-waves.d.ts.map +1 -1
  25. package/dist/parallelism.d.ts +9 -0
  26. package/dist/parallelism.d.ts.map +1 -1
  27. package/dist/parallelism.js +15 -0
  28. package/dist/release-floors.d.ts +1 -1
  29. package/dist/release-floors.d.ts.map +1 -1
  30. package/dist/release-floors.js +8 -8
  31. package/dist/wave-runtime.mjs +225 -225
  32. package/dist/workspace/release-workflow.d.ts +48 -6
  33. package/dist/workspace/release-workflow.d.ts.map +1 -1
  34. package/dist/workspace/release-workflow.js +81 -8
  35. package/package.json +1 -1
  36. package/src/audit/core.test.ts +8 -1
  37. package/src/cli/handlers/notify-relay.ts +1 -1
  38. package/src/components/capability.ts +11 -0
  39. package/src/lifecycle/__fixtures__/publish-fakes.ts +26 -4
  40. package/src/lifecycle/publish-oci.ts +87 -15
  41. package/src/lifecycle/publish-targets.test.ts +59 -2
  42. package/src/notify-relay-repo.test.ts +17 -4
  43. package/src/notify-relay-signers.test.ts +84 -0
  44. package/src/notify-relay.ts +10 -3
  45. package/src/op/index.ts +1 -0
  46. package/src/op/op-waves-after-plan.ts +1 -2
  47. package/src/op/op-waves-capability.ts +12 -4
  48. package/src/op/op-waves-gate-port.test.ts +2 -3
  49. package/src/op/op-waves-parallel-plans.test.ts +185 -0
  50. package/src/op/op-waves-parallelism.test.ts +5 -0
  51. package/src/op/op-waves-run.ts +47 -11
  52. package/src/op/op-waves.ts +9 -5
  53. package/src/parallelism.ts +26 -0
  54. package/src/release-floors.ts +8 -8
  55. package/src/workspace/release-workflow.test.ts +152 -11
  56. package/src/workspace/release-workflow.ts +102 -9
@@ -6,7 +6,7 @@ import { tmpdir } from "node:os";
6
6
  import { join } from "node:path";
7
7
  import { parseYAML } from "../yaml";
8
8
  import { ACTION_PINS } from "../action-pins";
9
- import { renderReleaseWorkflow, RELEASE_DIGESTS_FILE, type ReleaseWorkflowInput } from "./release-workflow";
9
+ import { NPM_TRUSTED_PUBLISHING_SETUP, renderReleaseWorkflow, RELEASE_DIGESTS_PATHS, type ReleaseWorkflowInput, type ReleaseWorkflowTarget } from "./release-workflow";
10
10
  import type { SecurityGroup } from "./security";
11
11
 
12
12
  const FIXTURES = join(__dirname, "__fixtures__", "release-workflow");
@@ -91,8 +91,8 @@ describe("a dispatched release (#4656)", () => {
91
91
  "npm ci",
92
92
  "git fetch origin 'refs/tags/ci/*:refs/tags/ci/*'",
93
93
  "git fetch origin chant/lifecycle:chant/lifecycle",
94
- `npx chant release images "$CHANT_RELEASE_LABEL" -o ${RELEASE_DIGESTS_FILE}`,
95
- `echo "CHANT_RELEASE_DIGESTS=$PWD/${RELEASE_DIGESTS_FILE}" >> "$GITHUB_ENV"`,
94
+ 'npx chant release images "$CHANT_RELEASE_LABEL" -o "$RUNNER_TEMP/chant-release-digests.json"',
95
+ 'echo "CHANT_RELEASE_DIGESTS=$RUNNER_TEMP/chant-release-digests.json" >> "$GITHUB_ENV"',
96
96
  "npm run build",
97
97
  'npx chant release verify "$CHANT_RELEASE_LABEL"',
98
98
  'npx chant release publish "$CHANT_RELEASE_LABEL" --require-provenance --yes',
@@ -103,7 +103,7 @@ describe("a dispatched release (#4656)", () => {
103
103
  const plain = parseYAML(dispatch("github", { groups: SECURE, images: true })) as GhDoc;
104
104
  const doc = parseYAML(dispatch("github", { groups: SECURE, images: true, version: true })) as GhDoc;
105
105
  const publish = runs(plain.jobs.publish!);
106
- const at = publish.indexOf(`npx chant release images "$CHANT_RELEASE_LABEL" -o ${RELEASE_DIGESTS_FILE}`);
106
+ const at = publish.indexOf('npx chant release images "$CHANT_RELEASE_LABEL" -o "$RUNNER_TEMP/chant-release-digests.json"');
107
107
  expect(runs(doc.jobs.publish!)).toEqual([...publish.slice(0, at), 'npx chant release stamp "$CHANT_RELEASE_LABEL"', ...publish.slice(at)]);
108
108
  expect(runs(doc.jobs.cut!)).toEqual(runs(plain.jobs.cut!));
109
109
  const gl = parseYAML(dispatch("gitlab", { images: true, version: true })) as Record<string, { script: string[] }>;
@@ -132,8 +132,8 @@ describe("a dispatched release (#4656)", () => {
132
132
  const publish = doc["chant-release-publish"]!;
133
133
  expect(publish.id_tokens).toEqual({ SIGSTORE_ID_TOKEN: { aud: "sigstore" } });
134
134
  expect(publish.script.slice(-5)).toEqual([
135
- `npx chant release images "$CHANT_RELEASE_LABEL" -o ${RELEASE_DIGESTS_FILE}`,
136
- `export CHANT_RELEASE_DIGESTS="$PWD/${RELEASE_DIGESTS_FILE}"`,
135
+ 'npx chant release images "$CHANT_RELEASE_LABEL" -o "/tmp/chant-release-digests.json"',
136
+ 'export CHANT_RELEASE_DIGESTS="/tmp/chant-release-digests.json"',
137
137
  "npm run build",
138
138
  'npx chant release verify "$CHANT_RELEASE_LABEL"',
139
139
  'npx chant release publish "$CHANT_RELEASE_LABEL" --require-provenance --yes',
@@ -155,8 +155,8 @@ describe("the tag trigger with images or after (#4656)", () => {
155
155
  "npm ci",
156
156
  "git fetch origin 'refs/tags/ci/*:refs/tags/ci/*'",
157
157
  "git fetch origin chant/lifecycle:chant/lifecycle",
158
- `npx chant release images "\${GITHUB_REF_NAME#release/}" -o ${RELEASE_DIGESTS_FILE}`,
159
- `echo "CHANT_RELEASE_DIGESTS=$PWD/${RELEASE_DIGESTS_FILE}" >> "$GITHUB_ENV"`,
158
+ 'npx chant release images "${GITHUB_REF_NAME#release/}" -o "$RUNNER_TEMP/chant-release-digests.json"',
159
+ 'echo "CHANT_RELEASE_DIGESTS=$RUNNER_TEMP/chant-release-digests.json" >> "$GITHUB_ENV"',
160
160
  "npm run build",
161
161
  'npx chant release publish "${GITHUB_REF_NAME#release/}" --yes',
162
162
  ]);
@@ -243,9 +243,14 @@ describe("the publish job hands GITHUB_TOKEN to a GitHub forge target (#4767)",
243
243
  test("a tokenEnv, another forge's target, or no forge target renders the file it did", () => {
244
244
  const plain = renderReleaseWorkflow({ forge: "github", groups: new Set() });
245
245
  expect(plain).toBe(readFileSync(join(FIXTURES, "github-plain.yml"), "utf-8"));
246
- for (const publish of [[{ ...ghForge, tokenEnv: "RELEASE_TOKEN" }], [{ ...ghForge, forge: "gitlab" as const }], [{ type: "npm" as const, packages: ["."] }], []]) {
246
+ for (const publish of [[{ ...ghForge, tokenEnv: "RELEASE_TOKEN" }], [{ ...ghForge, forge: "gitlab" as const }], []]) {
247
247
  expect(renderReleaseWorkflow({ forge: "github", groups: new Set(), publish }), JSON.stringify(publish)).toBe(plain);
248
248
  }
249
+ // An npm target sets no GITHUB_TOKEN; it adds only the npm upgrade trusted publishing needs (#4786).
250
+ const npmTarget = { type: "npm" as const, packages: ["."] };
251
+ const npmOnly = renderReleaseWorkflow({ forge: "github", groups: new Set(), publish: [npmTarget] });
252
+ expect(npmOnly).not.toContain("GITHUB_TOKEN");
253
+ expect(npmOnly.split("\n").filter((l) => !plain.split("\n").includes(l))).toEqual([` - run: ${JSON.stringify(NPM_TRUSTED_PUBLISHING_SETUP)}`]);
249
254
  // Forgejo's and GitLab's job tokens are not a GitHub token.
250
255
  for (const forge of ["forgejo", "gitlab"] as const) {
251
256
  expect(renderReleaseWorkflow({ forge, groups: new Set(), publish: [ghForge] })).toBe(readFileSync(join(FIXTURES, `${forge}-plain.yml`), "utf-8"));
@@ -301,7 +306,7 @@ describe("the cut hands its image archives to the publish job (#4657)", () => {
301
306
  expect(down).toBeGreaterThan(-1);
302
307
  expect(publish[down]!.with).toEqual({ name: "chant-release-images", path: "dist/images" });
303
308
  expect(check).toBeGreaterThan(down);
304
- expect(publish[check]!.run).toBe('npx chant release images "$CHANT_RELEASE_LABEL" --no-build -o .chant/release-digests.json');
309
+ expect(publish[check]!.run).toBe('npx chant release images "$CHANT_RELEASE_LABEL" --no-build -o "$RUNNER_TEMP/chant-release-digests.json"');
305
310
  });
306
311
 
307
312
  test("Forgejo takes v3 of the artifact actions, and a workspace root prefixes the paths", () => {
@@ -315,7 +320,7 @@ describe("the cut hands its image archives to the publish job (#4657)", () => {
315
320
  test("GitLab: the cut keeps the archives as artifacts the publish job needs, and checks them without building", () => {
316
321
  const doc = parseYAML(renderReleaseWorkflow({ forge: "gitlab", groups: new Set(), images: true, imageArchives: archives, pipeline: { trigger: "dispatch" } })) as Record<string, { artifacts?: unknown; script: string[] }>;
317
322
  expect(doc["chant-release-cut"]!.artifacts).toEqual({ paths: archives, expire_in: "1 day" });
318
- expect(doc["chant-release-publish"]!.script).toContain('npx chant release images "$CHANT_RELEASE_LABEL" --no-build -o .chant/release-digests.json');
323
+ expect(doc["chant-release-publish"]!.script).toContain('npx chant release images "$CHANT_RELEASE_LABEL" --no-build -o "/tmp/chant-release-digests.json"');
319
324
  });
320
325
 
321
326
  test("without the archive paths the publish job builds the images again, as before", () => {
@@ -324,3 +329,139 @@ describe("the cut hands its image archives to the publish job (#4657)", () => {
324
329
  expect(doc.jobs.publish!.steps.find((s) => s.run?.includes("release images"))!.run).not.toContain("--no-build");
325
330
  });
326
331
  });
332
+
333
+ describe("the publish job leaves the checkout as the cut left it (#4853)", () => {
334
+ // `chant release publish` refuses a dirty tree, and a repository that commits
335
+ // files under .chant/ can't ignore the directory, so no step the generator
336
+ // writes may put the digests in the checkout.
337
+ const lines = (doc: unknown): string[] =>
338
+ typeof doc === "string" ? doc.split("\n") : Array.isArray(doc) ? doc.flatMap(lines) : doc && typeof doc === "object" ? Object.values(doc).flatMap(lines) : [];
339
+ test("on every forge and trigger, the digests go to the runner's temp directory and CHANT_RELEASE_DIGESTS names that file", () => {
340
+ for (const forge of FORGES) {
341
+ for (const trigger of ["tag", "dispatch"] as const) {
342
+ for (const root of [".", "packages/app"]) {
343
+ const all = lines(parseYAML(renderReleaseWorkflow({ forge, groups: SECURE, images: true, imageArchives: ["dist/app.tar"], workspaceRoot: root, pipeline: { trigger } })));
344
+ const where = `${forge} ${trigger} ${root}`;
345
+ const images = all.filter((l) => l.includes("release images "));
346
+ expect(images.length, where).toBe(1);
347
+ expect(images[0], where).toMatch(new RegExp(` -o "${RELEASE_DIGESTS_PATHS[forge].replace(/[$.]/g, "\\$&")}"$`));
348
+ const env = all.filter((l) => l.includes("CHANT_RELEASE_DIGESTS="));
349
+ expect(env, where).toEqual([forge === "gitlab" ? `export CHANT_RELEASE_DIGESTS="${RELEASE_DIGESTS_PATHS.gitlab}"` : `echo "CHANT_RELEASE_DIGESTS=${RELEASE_DIGESTS_PATHS[forge]}" >> "$GITHUB_ENV"`]);
350
+ expect(all.join("\n"), where).not.toContain(".chant/");
351
+ }
352
+ }
353
+ }
354
+ });
355
+ });
356
+
357
+ describe("the gate stops when the green commit's workflow files differ from the dispatched one's (#4852)", () => {
358
+ // The gate's shell, run in a scratch repository, with a chant that answers
359
+ // `ci last-green` with `green`. GitHub refuses the job's token a tag on a
360
+ // commit whose workflow files differ from the default branch's, so the gate
361
+ // stops before the cut builds anything.
362
+ function gate(over: Partial<ReleaseWorkflowInput> = {}) {
363
+ const dir = mkdtempSync(join(tmpdir(), "chant-4852-"));
364
+ const git = (...args: string[]) => {
365
+ const r = spawnSync("git", ["-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgsign=false", ...args], { cwd: dir, encoding: "utf-8" });
366
+ if (r.status !== 0) throw new Error(r.stderr);
367
+ return r.stdout.trim();
368
+ };
369
+ git("init", "-q", "-b", "main");
370
+ const commit = (files: Record<string, string>, msg: string) => {
371
+ for (const [f, t] of Object.entries(files)) {
372
+ spawnSync("mkdir", ["-p", join(dir, f, "..")]);
373
+ spawnSync("sh", ["-c", `printf '%s' "$1" > "$2"`, "sh", t, join(dir, f)]);
374
+ }
375
+ git("add", "-A");
376
+ git("commit", "-q", "-m", msg);
377
+ return git("rev-parse", "HEAD");
378
+ };
379
+ const green = commit({ ".github/workflows/chant-release.yml": "v1\n", "src/a.ts": "1\n" }, "green");
380
+ const stub = join(dir, "..", `${dir.split("/").pop()}-chant`);
381
+ spawnSync("sh", ["-c", `printf '#!/bin/sh\\necho "{\\\\"commit\\\\":{\\\\"sha\\\\":\\\\"%s\\\\"}}"\\n' "$1" > "$2" && chmod +x "$2"`, "sh", green, stub]);
382
+ const doc = parseYAML(renderReleaseWorkflow({ forge: "github", groups: new Set(), pipeline: { trigger: "dispatch", chant: stub }, ...over })) as GhDoc;
383
+ const script = doc.jobs.gate!.steps.find((s) => s.id === "green")!.run!;
384
+ const run = (sha: string) => {
385
+ const out = join(dir, ".gh-output");
386
+ const r = spawnSync("bash", ["-e", "-c", script], { cwd: dir, encoding: "utf-8", env: { ...process.env, GITHUB_SHA: sha, GITHUB_OUTPUT: out } });
387
+ return { status: r.status, stderr: r.stderr, output: spawnSync("cat", [out], { encoding: "utf-8" }).stdout };
388
+ };
389
+ return { commit, run, green };
390
+ }
391
+
392
+ test("a commit after the green one that changed only code: the gate hands on the green commit", () => {
393
+ const { commit, run, green } = gate();
394
+ const head = commit({ "src/a.ts": "2\n" }, "code");
395
+ const r = run(head);
396
+ expect(r.stderr).toBe("");
397
+ expect(r.status).toBe(0);
398
+ expect(r.output).toBe(`commit=${green}\n`);
399
+ });
400
+
401
+ test("a commit after the green one changed .github/workflows: the gate stops and names it", () => {
402
+ const { commit, run, green } = gate();
403
+ const changed = commit({ ".github/workflows/chant-release.yml": "v2\n" }, "workflows");
404
+ const head = commit({ "src/a.ts": "2\n" }, "code");
405
+ const r = run(head);
406
+ expect(r.status).toBe(1);
407
+ expect(r.output).toBe("");
408
+ expect(r.stderr).toContain(`the newest green commit, ${green}, has other workflow files than ${head}, and GitHub refuses this job's token a tag on it, so no release is cut. Dispatch again once ${changed}, which changed .github/workflows, or a commit after it is green.`);
409
+ });
410
+
411
+ test("forgejo and gitlab render no such check, and neither does gate: head", () => {
412
+ for (const forge of ["forgejo", "gitlab"] as const) expect(dispatch(forge)).not.toContain(".github/workflows");
413
+ expect(dispatch("github", { pipeline: { trigger: "dispatch", gate: "head" } })).not.toContain(":(top).github/workflows");
414
+ expect(dispatch("github")).toContain(":(top).github/workflows");
415
+ });
416
+ });
417
+
418
+ describe("GHCR credentials and npm trusted publishing from the targets (#4786)", () => {
419
+ const ghcr: ReleaseWorkflowTarget = { type: "oci", repository: "ghcr.io/acme/app" };
420
+ const npm: ReleaseWorkflowTarget = { type: "npm" };
421
+ const qemu = { uses: "docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4.4.0", with: { platforms: "arm64" } };
422
+ const render = (publish: ReleaseWorkflowTarget[], pipeline: ReleaseWorkflowInput["pipeline"] = {}, forge: (typeof FORGES)[number] = "github") =>
423
+ renderReleaseWorkflow({ forge, groups: new Set(), images: true, imageArchives: ["dist/app.tar"], publish, pipeline: { trigger: "dispatch", ...pipeline } });
424
+
425
+ test("an oci target on ghcr.io with no credentials named: packages: write, and the job token as OCI_USERNAME and OCI_PASSWORD in the cut and the publish", () => {
426
+ const doc = parseYAML(render([ghcr])) as GhDoc;
427
+ expect(doc.permissions).toEqual({ contents: "write", "id-token": "write", packages: "write" });
428
+ for (const job of ["cut", "publish"]) {
429
+ expect(doc.jobs[job]!.env, job).toMatchObject({ OCI_USERNAME: "${{ github.actor }}", OCI_PASSWORD: "${{ github.token }}" });
430
+ }
431
+ expect(runs(doc.jobs.publish!)).not.toContain(NPM_TRUSTED_PUBLISHING_SETUP);
432
+ });
433
+
434
+ test("an npm target on npmjs: the cut and the publish upgrade npm after the install when the runner's is older than trusted publishing needs", () => {
435
+ const doc = parseYAML(render([npm])) as GhDoc;
436
+ expect(doc.permissions).toEqual({ contents: "write", "id-token": "write" });
437
+ for (const job of ["cut", "publish"]) {
438
+ const r = runs(doc.jobs[job]!);
439
+ expect(r[r.indexOf("npm ci") + 1], job).toBe(NPM_TRUSTED_PUBLISHING_SETUP);
440
+ expect(doc.jobs[job]!.env?.OCI_PASSWORD, job).toBeUndefined();
441
+ }
442
+ expect(NPM_TRUSTED_PUBLISHING_SETUP).toContain('"11.5.1"');
443
+ });
444
+
445
+ test("a config that wired them by hand renders the same file once it drops them", () => {
446
+ const byHand = render([ghcr, npm], {
447
+ permissions: { packages: "write" },
448
+ env: { OCI_USERNAME: "${{ github.actor }}", OCI_PASSWORD: "${{ github.token }}" },
449
+ setup: [qemu, { run: NPM_TRUSTED_PUBLISHING_SETUP }],
450
+ });
451
+ expect(render([ghcr, npm], { setup: [qemu] })).toBe(byHand);
452
+ });
453
+
454
+ test("the config wins: its own credentials, scope or registry, other forges, and a config with neither target render as before", () => {
455
+ const plain = render([]);
456
+ expect(render([{ type: "oci", repository: "docker.io/acme/app" }])).toBe(plain);
457
+ expect(render([{ ...ghcr, usernameEnv: "GHCR_USER", passwordEnv: "GHCR_TOKEN" }])).toBe(plain);
458
+ expect(render([{ type: "npm", registry: "https://npm.pkg.github.com" }])).toBe(plain);
459
+ for (const forge of ["forgejo", "gitlab"] as const) expect(render([ghcr, npm], {}, forge), forge).toBe(render([], {}, forge));
460
+ const own = parseYAML(render([ghcr], { env: { OCI_PASSWORD: "${{ secrets.GHCR }}" } })) as GhDoc;
461
+ expect(own.jobs.publish!.env).toMatchObject({ OCI_USERNAME: "${{ github.actor }}", OCI_PASSWORD: "${{ secrets.GHCR }}" });
462
+ // A tag-triggered workflow reads the targets the same way.
463
+ const tagged = parseYAML(renderReleaseWorkflow({ forge: "github", groups: new Set(), publish: [ghcr, npm] })) as GhDoc;
464
+ expect(tagged.permissions?.packages).toBe("write");
465
+ expect(runs(tagged.jobs.publish!)).toContain(NPM_TRUSTED_PUBLISHING_SETUP);
466
+ });
467
+ });
@@ -121,7 +121,57 @@ export interface ReleaseWorkflowInput {
121
121
  * `tokenEnv` reads `GITHUB_TOKEN`, so the publish job sets it to the job's
122
122
  * token unless `release.workflow.env` sets it.
123
123
  */
124
- publish?: ReadonlyArray<{ type: string; forge?: string; tokenEnv?: string }>;
124
+ publish?: ReadonlyArray<ReleaseWorkflowTarget>;
125
+ }
126
+
127
+ /** What the generator reads of a `release.publish` target: enough to know which credentials and tools its job needs. */
128
+ export interface ReleaseWorkflowTarget {
129
+ type: string;
130
+ forge?: string;
131
+ tokenEnv?: string;
132
+ /** An `oci` target's `<registry host>/<name>`. */
133
+ repository?: string;
134
+ usernameEnv?: string;
135
+ passwordEnv?: string;
136
+ /** An `npm` target's registry. */
137
+ registry?: string;
138
+ }
139
+
140
+ /** npm trusted publishing needs this npm or later (#4786). */
141
+ export const NPM_TRUSTED_PUBLISHING_MIN = "11.5.1";
142
+ /** The npm a publish job installs when the runner's Node bundles one older than {@link NPM_TRUSTED_PUBLISHING_MIN}. */
143
+ export const NPM_TRUSTED_PUBLISHING_VERSION = "11.19.0";
144
+
145
+ /**
146
+ * The shell line that installs {@link NPM_TRUSTED_PUBLISHING_VERSION} when the
147
+ * runner's npm is older than {@link NPM_TRUSTED_PUBLISHING_MIN}, and prints the
148
+ * npm in use.
149
+ */
150
+ export const NPM_TRUSTED_PUBLISHING_SETUP = `have="$(npm --version)"; if [ "$(printf '%s\\n' "${NPM_TRUSTED_PUBLISHING_MIN}" "$have" | sort -V | head -n1)" != "${NPM_TRUSTED_PUBLISHING_MIN}" ]; then npm install -g npm@${NPM_TRUSTED_PUBLISHING_VERSION}; fi; npm --version`;
151
+
152
+ /**
153
+ * What a GitHub release workflow needs for its targets, worked out from them
154
+ * (#4786), so no product wires it by hand:
155
+ *
156
+ * - an `oci` target on `ghcr.io` that names no credentials pushes with the
157
+ * job's token: `packages: write`, and `OCI_USERNAME` and `OCI_PASSWORD`
158
+ * from `github.actor` and `github.token`;
159
+ * - an `npm` target on npmjs publishes with trusted publishing, which needs
160
+ * npm {@link NPM_TRUSTED_PUBLISHING_MIN}: the jobs upgrade npm when the
161
+ * runner's is older.
162
+ *
163
+ * `release.workflow` wins: a scope, variable or the same setup line it names
164
+ * is not added again. Other forges, and configs without such targets, get
165
+ * nothing.
166
+ */
167
+ export function targetExtras(forge: ReleaseWorkflowForge, targets: ReadonlyArray<ReleaseWorkflowTarget>, p: ReleasePipelineConfig): Pick<ReleasePipelineConfig, "permissions" | "env" | "setup"> {
168
+ if (forge !== "github") return {};
169
+ const ghcr = targets.some((t) => t.type === "oci" && /^ghcr\.io\//.test(t.repository ?? "") && !t.usernameEnv && !t.passwordEnv);
170
+ const npm = targets.some((t) => t.type === "npm" && (t.registry === undefined || /^https:\/\/registry\.npmjs\.org\/?$/.test(t.registry)));
171
+ const permissions = ghcr && p.permissions?.packages === undefined ? { packages: "write" as const } : undefined;
172
+ const env = ghcr ? Object.fromEntries((["OCI_USERNAME", "OCI_PASSWORD"] as const).filter((k) => p.env?.[k] === undefined).map((k) => [k, k === "OCI_USERNAME" ? "${{ github.actor }}" : "${{ github.token }}"])) : {};
173
+ const setup = npm && !(p.setup ?? []).some((s) => !("uses" in s) && s.run === NPM_TRUSTED_PUBLISHING_SETUP) ? [{ run: NPM_TRUSTED_PUBLISHING_SETUP }] : [];
174
+ return { ...(permissions ? { permissions } : {}), ...(Object.keys(env).length > 0 ? { env } : {}), ...(setup.length > 0 ? { setup } : {}) };
125
175
  }
126
176
 
127
177
  /** The flags `chant release publish` gets under the groups. */
@@ -129,9 +179,22 @@ export function publishFlags(groups: ReadonlySet<SecurityGroup>): string[] {
129
179
  return [...(groups.has("supply-chain") ? ["--require-provenance"] : []), "--yes"];
130
180
  }
131
181
 
132
- /** Where `chant release images` writes the digests the publish job's build reads (#4657). */
182
+ /** Where `chant release images` writes the digests the publish job's build reads (#4657), by default and at a workstation. */
133
183
  export const RELEASE_DIGESTS_FILE = ".chant/release-digests.json";
134
184
 
185
+ /**
186
+ * Where a generated publish job writes the digests: the runner's temp
187
+ * directory, outside the checkout, so `chant release publish` finds the tree
188
+ * as the cut left it (#4853). A repository that commits files under `.chant/`
189
+ * can't ignore the directory, and a digests file there made the publish
190
+ * refuse with `release-worktree-dirty`.
191
+ */
192
+ export const RELEASE_DIGESTS_PATHS: Record<ReleaseWorkflowForge, string> = {
193
+ github: "$RUNNER_TEMP/chant-release-digests.json",
194
+ forgejo: "$RUNNER_TEMP/chant-release-digests.json",
195
+ gitlab: "/tmp/chant-release-digests.json",
196
+ };
197
+
135
198
  /** A string as a single-quoted shell word. */
136
199
  function sq(s: string): string {
137
200
  return `'${s.replaceAll("'", "'\\''")}'`;
@@ -149,7 +212,17 @@ export function renderReleaseWorkflow(input: ReleaseWorkflowInput): string {
149
212
  const after = p.after ?? [];
150
213
  const images = input.images === true;
151
214
  const version = input.version === true;
152
- const extra = jobExtras(p, input.forge);
215
+ // #4786: the targets' own needs first, then the config's, so a config that set them by hand renders the same file without them.
216
+ const derived = targetExtras(input.forge, input.publish ?? [], p);
217
+ const extra = jobExtras(
218
+ {
219
+ ...p,
220
+ ...(derived.permissions ? { permissions: { ...p.permissions, ...derived.permissions } } : {}),
221
+ ...(derived.env ? { env: { ...p.env, ...derived.env } } : {}),
222
+ ...(derived.setup ? { setup: [...(p.setup ?? []), ...derived.setup] } : {}),
223
+ },
224
+ input.forge,
225
+ );
153
226
  // #4767: Forgejo's job token is not a GitHub token, and GitLab has no such expression.
154
227
  const forgeToken =
155
228
  input.forge === "github" && p.env?.GITHUB_TOKEN === undefined && (input.publish ?? []).some((t) => t.type === "forge" && t.forge === "github" && !t.tokenEnv)
@@ -161,7 +234,8 @@ export function renderReleaseWorkflow(input: ReleaseWorkflowInput): string {
161
234
  return input.forge === "gitlab" ? renderGitlabDispatch(o) : renderGithubDispatch(o);
162
235
  }
163
236
  // #4657: the images are built from the release, so chant/lifecycle is fetched before them and the build after.
164
- const imageLines = (label: string, env: string): string[] => [`${chant} release images ${label} -o ${RELEASE_DIGESTS_FILE}`, env];
237
+ const digests = RELEASE_DIGESTS_PATHS[input.forge];
238
+ const imageLines = (label: string, env: string): string[] => [`${chant} release images ${label} -o "${digests}"`, env];
165
239
  if (input.forge === "gitlab") {
166
240
  const label = '"${CI_COMMIT_TAG#release/}"';
167
241
  const fetches = [" - git fetch origin 'refs/tags/ci/*:refs/tags/ci/*'", " - git fetch origin chant/lifecycle:chant/lifecycle"];
@@ -178,7 +252,7 @@ export function renderReleaseWorkflow(input: ReleaseWorkflowInput): string {
178
252
  ` - ${install}`,
179
253
  ...extra.gitlabScript.map((l) => ` - ${l}`),
180
254
  ...(version ? [` - ${chant} release stamp ${label}`] : []),
181
- ...(images ? [...fetches, ...imageLines(label, `export CHANT_RELEASE_DIGESTS="$PWD/${RELEASE_DIGESTS_FILE}"`).map((l) => ` - ${l}`)] : []),
255
+ ...(images ? [...fetches, ...imageLines(label, `export CHANT_RELEASE_DIGESTS="${digests}"`).map((l) => ` - ${l}`)] : []),
182
256
  ...(build ? [` - ${build}`] : []),
183
257
  ...(images ? [] : fetches),
184
258
  ...(verify ? [` - ${chant} release verify ${label}`] : []),
@@ -221,7 +295,7 @@ export function renderReleaseWorkflow(input: ReleaseWorkflowInput): string {
221
295
  ` - run: ${install}`,
222
296
  ...extra.githubSteps,
223
297
  ...(version ? [` - run: ${chant} release stamp ${label}`] : []),
224
- ...(images ? [...fetches, ...imageLines(label, `echo "CHANT_RELEASE_DIGESTS=$PWD/${RELEASE_DIGESTS_FILE}" >> "$GITHUB_ENV"`).map((l) => ` - run: ${l}`)] : []),
298
+ ...(images ? [...fetches, ...imageLines(label, `echo "CHANT_RELEASE_DIGESTS=${digests}" >> "$GITHUB_ENV"`).map((l) => ` - run: ${l}`)] : []),
225
299
  ...(build ? [` - run: ${build}`] : []),
226
300
  ...(images ? [] : fetches),
227
301
  ...(verify ? [` - run: ${chant} release verify ${label}`] : []),
@@ -339,7 +413,7 @@ function commonDir(paths: readonly string[]): string {
339
413
 
340
414
  /** The `release images` line of a publish job: checking the archives handed on, or building them again. */
341
415
  function imagesLine(o: DispatchInput): string {
342
- return `${o.chant} release images "$CHANT_RELEASE_LABEL"${o.archives.length > 0 ? " --no-build" : ""} -o ${RELEASE_DIGESTS_FILE}`;
416
+ return `${o.chant} release images "$CHANT_RELEASE_LABEL"${o.archives.length > 0 ? " --no-build" : ""} -o "${RELEASE_DIGESTS_PATHS[o.forge]}"`;
343
417
  }
344
418
 
345
419
  /** The publish job's `release stamp` line (#4840). */
@@ -351,12 +425,31 @@ function stampLine(o: DispatchInput): string {
351
425
  const field = (path: string): string =>
352
426
  `node -e 'const f=process.argv[1];const t=f?require("fs").readFileSync(f,"utf8"):require("fs").readFileSync(0,"utf8");const d=JSON.parse(t);process.stdout.write(String(${path}??""))'`;
353
427
 
428
+ /**
429
+ * GitHub refuses the job's token a ref on a commit whose workflow files differ
430
+ * from the default branch's (#4852). The gate checks before the cut builds
431
+ * anything: when the green commit's `.github/workflows` differs from the
432
+ * dispatched commit's, it stops and names the newest commit that changed
433
+ * them, the one to wait for.
434
+ */
435
+ function workflowFilesCheck(dispatched: string): string[] {
436
+ const files = '":(top).github/workflows"';
437
+ return [
438
+ `if ! git diff --quiet "$commit" "${dispatched}" -- ${files}; then`,
439
+ ` changed="$(git log -1 --format=%H "$commit..${dispatched}" -- ${files})"`,
440
+ ` echo "the newest green commit, $commit, has other workflow files than ${dispatched}, and GitHub refuses this job's token a tag on it, so no release is cut. Dispatch again once \${changed:-${dispatched}}, which changed .github/workflows, or a commit after it is green." >&2`,
441
+ " exit 1",
442
+ "fi",
443
+ ];
444
+ }
445
+
354
446
  /** The gate's shell: the commit to cut, from `ci last-green`, refused when there is none or, under `head`, when it is not the dispatched one. */
355
447
  function gateScript(o: DispatchInput, dispatched: string): string[] {
356
448
  return [
357
449
  `commit="$(${o.chant} ci last-green --from "${dispatched}"${o.lane ? ` --lane ${o.lane}` : ""} --json | ${field("d.commit?.sha")})"`,
358
450
  `if [ -z "$commit" ]; then echo "no green commit at or below ${dispatched}, so no release is cut" >&2; exit 1; fi`,
359
451
  ...(o.gate === "head" ? [`if [ "$commit" != "${dispatched}" ]; then echo "${dispatched} is not green (the newest green commit below it is $commit), so no release is cut" >&2; exit 1; fi`] : []),
452
+ ...(o.forge === "github" && o.gate !== "head" ? workflowFilesCheck(dispatched) : []),
360
453
  ];
361
454
  }
362
455
 
@@ -454,7 +547,7 @@ function renderGithubDispatch(o: DispatchInput): string {
454
547
  ? [` - uses: ${usesRef(o.forge === "forgejo" ? ACTION_PINS.downloadArtifact3 : ACTION_PINS.downloadArtifact4)}`, " with:", ` name: ${RELEASE_IMAGES_ARTIFACT}`, ` path: ${commonDir(o.archives)}`]
455
548
  : []),
456
549
  ...(o.version ? [` - run: ${stampLine(o)}`] : []),
457
- ...(o.images ? [` - run: ${imagesLine(o)}`, ` - run: echo "CHANT_RELEASE_DIGESTS=$PWD/${RELEASE_DIGESTS_FILE}" >> "$GITHUB_ENV"`] : []),
550
+ ...(o.images ? [` - run: ${imagesLine(o)}`, ` - run: echo "CHANT_RELEASE_DIGESTS=${RELEASE_DIGESTS_PATHS[o.forge]}" >> "$GITHUB_ENV"`] : []),
458
551
  ...(o.build ? [` - run: ${o.build}`] : []),
459
552
  ...(o.verify ? [` - run: ${o.chant} release verify "$CHANT_RELEASE_LABEL"`] : []),
460
553
  ` - run: ${o.chant} release publish "$CHANT_RELEASE_LABEL" ${o.flags}`,
@@ -509,7 +602,7 @@ function renderGitlabDispatch(o: DispatchInput): string {
509
602
  ...fetches,
510
603
  ...auth,
511
604
  ...(o.version ? [stampLine(o)] : []),
512
- ...(o.images ? [imagesLine(o), `export CHANT_RELEASE_DIGESTS="$PWD/${RELEASE_DIGESTS_FILE}"`] : []),
605
+ ...(o.images ? [imagesLine(o), `export CHANT_RELEASE_DIGESTS="${RELEASE_DIGESTS_PATHS.gitlab}"`] : []),
513
606
  ...(o.build ? [o.build] : []),
514
607
  ...(o.verify ? [`${o.chant} release verify "$CHANT_RELEASE_LABEL"`] : []),
515
608
  `${o.chant} release publish "$CHANT_RELEASE_LABEL" ${o.flags}`,