Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 36 additions & 1 deletion packages/core/src/lifecycle/publish-forge-notes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { createRedactor } from "./publish-credentials";
import { PublishDeclarationSchema } from "./publish-declaration";
import { memberCommits, releaseNotesSection } from "./publish-forge";
import { checkForgeNotesFiles, memberCommits, releaseNotesSection } from "./publish-forge";
import { createPublishTargets } from "./publish-targets";
import { PublishTargetError, type PublishContext } from "./release-publish";
import { appendCut, makeRelease, persistRelease } from "./release-store";
Expand Down Expand Up @@ -407,3 +407,38 @@ describe("a forge release's generated notes (#5153)", () => {
expect(() => decl({ ...GH, notes: { generate: "commits", exclude: ["docs", "test", "chore"], nonConventional: true } })).not.toThrow();
});
});

describe("checkForgeNotesFiles (#5319)", () => {
const decl = (notes: Record<string, unknown>, extra: Record<string, unknown> = {}) => ({ type: "forge", forge: "github", repo: "acme/api", notes, ...extra });
const tagOf = (l: string) => `release/${l}`;
const dir = () => {
const d = member();
writeFileSync(join(d, "CHANGELOG.md"), "# Changelog\n\n## [1.4.0] - 2026-11-01\n\n- a change\n\n## [1.3.0]\n\n- older\n");
return d;
};

test("passes when the file has the heading for the label, with the version or tag filled in", () => {
const d = dir();
expect(() => checkForgeNotesFiles([decl({ file: "CHANGELOG.md", heading: "## [{version}]" })], d, "v1.4.0", tagOf)).not.toThrow();
expect(() => checkForgeNotesFiles([decl({ file: "CHANGELOG.md", heading: "## [1.3.0]" })], d, "v1.4.0", tagOf)).not.toThrow();
});

test("refuses a label with no heading, with the publish's code and remedy", () => {
const err = (() => {
try {
checkForgeNotesFiles([decl({ file: "CHANGELOG.md", heading: "## [{version}]" })], dir(), "v1.5.0", tagOf);
} catch (e) {
return e;
}
})();
expect(err).toBeInstanceOf(PublishTargetError);
expect((err as PublishTargetError).code).toBe("publish-forge-notes-missing");
expect((err as PublishTargetError).message).toContain('no heading "## [1.5.0]"');
expect((err as PublishTargetError).fix).toBe('Write the "## [1.5.0]" section in CHANGELOG.md, or change notes.heading.');
});

test("refuses a missing file, and leaves targets with no notes file alone", () => {
expect(() => checkForgeNotesFiles([decl({ file: "NOPE.md", heading: "## {version}" })], dir(), "v1.4.0", tagOf)).toThrow(/does not exist/);
expect(() => checkForgeNotesFiles([decl({ generate: "commits" }), { type: "npm" }], dir(), "v9.9.9", tagOf)).not.toThrow();
});
});
42 changes: 34 additions & 8 deletions packages/core/src/lifecycle/publish-forge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,39 @@ export function releaseNotesSection(page: string, heading: string, linkBase?: st
return body.replace(/\]\((\/(?!\/)[^)\s]*)/g, (_, path: string) => `](${base}${path}`);
}

/**
* The section of the notes file a forge target names, for `values`, or
* undefined when its notes name no file. Throws `publish-forge-notes-missing`
* when the file or the heading is not there. The publish plans with it, and
* the cut checks with it before it tags (#5319).
*/
function forgeNotesFileSection(decl: ForgePublishDeclaration, cwd: string, values: { label: string; version: string; tag: string }): string | undefined {
const n = decl.notes;
if (!n?.file || !n.heading) return undefined;
const heading = fillNotesText(n.heading, values);
try {
return releaseNotesSection(readFileSync(memberFile(cwd, n.file), "utf8"), heading, n.linkBase);
} catch (err) {
const why = (err as NodeJS.ErrnoException).code === "ENOENT" ? "it does not exist" : (err as Error).message;
throw new PublishTargetError("publish-forge-notes-missing", `the ${decl.forge} release's notes come from ${n.file}, and ${why}`, `Write the "${heading}" section in ${n.file}, or change notes.heading.`);
}
}

/**
* Refuses a cut of `label` when a forge target's notes name a file with no
* section for it (#5319). Run by the cut before anything is recorded or
* tagged, and by the train cut for each member. `tagOf` gives the tag the cut
* will make for the label, which a heading may name as `{tag}`.
*/
export function checkForgeNotesFiles(decls: ReadonlyArray<{ type: string }>, cwd: string, label: string, tagOf: (label: string) => string): void {
for (const d of decls) {
if (d.type !== "forge") continue;
const decl = d as ForgePublishDeclaration;
if (!decl.notes?.file) continue;
forgeNotesFileSection(decl, cwd, { label, version: releaseVersion(label) ?? label, tag: decl.tag ?? tagOf(label) });
}
}

/** The variables a forge's token is read from, in order. */
export function forgeTokenEnv(decl: Pick<ForgePublishDeclaration, "forge" | "tokenEnv">): string[] {
if (decl.tokenEnv) return [decl.tokenEnv];
Expand Down Expand Up @@ -510,14 +543,7 @@ export function forgeTarget(decl: ForgePublishDeclaration, deps: PublishDeps): P
'Set notes.generate to "commits" for notes from the conventional commits since the previous release.',
);
}
if (!n?.file || !n.heading) return undefined;
const heading = fillNotesText(n.heading, notesValues(ctx, tag));
try {
return releaseNotesSection(readFileSync(memberFile(ctx.cwd, n.file), "utf8"), heading, n.linkBase);
} catch (err) {
const why = (err as NodeJS.ErrnoException).code === "ENOENT" ? "it does not exist" : (err as Error).message;
throw new PublishTargetError("publish-forge-notes-missing", `the ${decl.forge} release's notes come from ${n.file}, and ${why}`, `Write the "${heading}" section in ${n.file}, or change notes.heading.`);
}
return forgeNotesFileSection(decl, ctx.cwd, notesValues(ctx, tag));
};
const notesValues = (ctx: PublishContext, tag: string) => {
const label = ctx.label ?? tag;
Expand Down
64 changes: 64 additions & 0 deletions packages/core/src/lifecycle/release-cut-forge-notes.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/**
* #5319: a cut refuses a forge target whose notes file has no heading for the
* label, before it records anything, so no tag is made for a release the
* publish would refuse.
*/
import { afterAll, describe, expect, test } from "vitest";
import { dirname } from "node:path";
import { rmSync } from "node:fs";
import { cutRelease, ReleaseCutError } from "./release-cut";
import type { CompiledTarget, TargetCompiler } from "../components/release-compile";
import type { ReleaseArtifact } from "./release-store";
import { TestRepo } from "../workspace/trust/test-repo";

const repos: TestRepo[] = [];
afterAll(() => {
for (const r of repos) rmSync(dirname(r.dir), { recursive: true, force: true });
});

const compiler: TargetCompiler = {
async compile(env): Promise<CompiledTarget> {
return { env, params: [], components: [], buildSteps: {}, buildInputs: {}, componentFiles: {}, templates: [{ component: null, path: "dist/out.json", content: "{}\n" }] };
},
async buildArtifacts(): Promise<ReleaseArtifact[]> {
return [];
},
};

const repo = (changelog: string | null) => {
const r = new TestRepo("cut-forge-notes");
repos.push(r);
r.write(
"chant.config.ts",
`export default { environments: ["dev"], release: { publish: [{ type: "forge", forge: "github", repo: "acme/app", assets: [], notes: { file: "CHANGELOG.md", heading: "## [{version}]" } }] } };\n`,
);
if (changelog !== null) r.write("CHANGELOG.md", changelog);
const head = r.commit("init");
r.git(["tag", `ci/green/${head}`]);
return r;
};

describe("the cut and a forge notes file", () => {
test("refuses a label the file has no heading for, before anything is recorded", async () => {
const r = repo("# Changelog\n\n## [0.6.3]\n\n- older\n");
const err = await cutRelease({ cwd: r.dir, compiler, label: "v0.6.4", actor: "alice", env: {} }).catch((e: unknown) => e);
expect(err).toBeInstanceOf(ReleaseCutError);
expect((err as ReleaseCutError).code).toBe("publish-forge-notes-missing");
expect((err as ReleaseCutError).message).toMatch(/^no release was cut: the github release's notes come from CHANGELOG.md, and it has no heading "## \[0.6.4\]"/);
expect((err as ReleaseCutError).fix).toBe('Write the "## [0.6.4]" section in CHANGELOG.md, or change notes.heading.');
expect(() => r.git(["rev-parse", "--verify", "--quiet", "refs/heads/chant/lifecycle"])).toThrow();
});

test("refuses when the file does not exist", async () => {
const r = repo(null);
const err = await cutRelease({ cwd: r.dir, compiler, label: "v0.6.4", actor: "alice", env: {} }).catch((e: unknown) => e);
expect((err as ReleaseCutError).code).toBe("publish-forge-notes-missing");
expect((err as ReleaseCutError).message).toContain("CHANGELOG.md does not exist");
});

test("cuts a label the file has a heading for", async () => {
const r = repo("# Changelog\n\n## [0.6.4] - 2026-11-18\n\n- fixed\n");
const out = await cutRelease({ cwd: r.dir, compiler, label: "v0.6.4", actor: "alice", env: {} });
expect(out.label).toBe("v0.6.4");
});
});
13 changes: 11 additions & 2 deletions packages/core/src/lifecycle/release-cut.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,7 @@ export type ReleaseCutCode =
| "publish-npm-carries-image"
| "publish-npm-pack-failed"
/** #5230: an npm target names a package the registry has never published, or the registry can't say. */
| "publish-forge-notes-missing"
| "publish-npm-never-published"
| "publish-npm-registry-unreadable";

Expand Down Expand Up @@ -641,10 +642,18 @@ async function prepare(req: CutRequest, record = false): Promise<Prepared> {
const { loadChantConfig } = await import("../config");
const { checkPackagesPublished, npmPublishedLookup } = await import("./publish-npm");
const { PublishTargetError } = await import("./release-publish");
const { memberTags, renderReleaseTag, ReleaseTagError } = await import("./release-tag");
try {
checkPackagesPublished((await loadChantConfig(cwd, { fresh: true })).config.release?.publish ?? [], cwd, req.npmPublished ?? npmPublishedLookup());
const decls = (await loadChantConfig(cwd, { fresh: true })).config.release?.publish ?? [];
checkPackagesPublished(decls, cwd, req.npmPublished ?? npmPublishedLookup());
// #5319: a forge target's notes file needs the heading for this label, which the publish refuses without after the tag is pushed.
if (req.label !== null && decls.some((d) => d.type === "forge" && d.notes?.file)) {
const { checkForgeNotesFiles } = await import("./publish-forge");
const tags = await memberTags(cwd);
checkForgeNotesFiles(decls, cwd, req.label, (l) => renderReleaseTag(tags.template, tags.place, l));
}
} catch (err) {
if (err instanceof PublishTargetError) throw new ReleaseCutError(err.code as ReleaseCutCode, `no release was cut: ${err.message}`, err.fix);
if (err instanceof PublishTargetError || err instanceof ReleaseTagError) throw new ReleaseCutError(err.code as ReleaseCutCode, `no release was cut: ${err.message}`, err.fix);
throw err;
}
}
Expand Down
19 changes: 19 additions & 0 deletions packages/core/src/workspace/train-cut.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,25 @@ describe("a package npm has never had", () => {
});
});

describe("a member's forge notes file (#5319)", () => {
test("refuses the train before any member is cut when a member's file has no heading for its label", async () => {
const x = setup();
x.r.write(
"release/lex/chant.config.ts",
`export default { environments: ["npm"], release: { publish: [{ type: "forge", forge: "github", repo: "acme/lex", assets: [], notes: { file: "CHANGELOG.md", heading: "## [{version}]" } }] } };\n`,
);
x.r.write("release/lex/CHANGELOG.md", "# Changelog\n\n## [1.0.0]\n\n- first\n");
const head = x.r.commit("forge notes");
x.r.git(["tag", `ci/green/${head}`]);
let cuts = 0;
const err = await cutTrain({ cwd: x.nested, env: "npm", at: head, registry: npmVersions(x.npm), yes: true, noPush: true, cutter: async () => ({ tag: (cuts++, null) }) }).catch((e: unknown) => e);
expect(err).toBeInstanceOf(TrainCutError);
expect((err as TrainCutError).code).toBe("publish-forge-notes-missing");
expect((err as TrainCutError).message).toContain('nothing was cut: lex: the github release\'s notes come from CHANGELOG.md, and it has no heading "## [');
expect(cuts).toBe(0);
});
});

describe("release.train.check", () => {
test("a failing release.train.check stops the train before any cut", async () => {
const x = setup();
Expand Down
21 changes: 21 additions & 0 deletions packages/core/src/workspace/train-cut.ts
Original file line number Diff line number Diff line change
Expand Up @@ -568,6 +568,27 @@ export async function cutTrain(q: TrainCutRun): Promise<TrainCutOutcome> {
if (failed.length > 0) throw new TrainCutError("train-doctor-failed", `release doctor found a target that can't publish from here in ${failed.join(", ")}`, "Nothing was cut. Fix what the doctor reports and run the train again.");
}

// #5319: a member's forge notes file needs the heading for the label the train cuts it at, before the first member is tagged.
{
const { loadChantConfig } = await import("../config");
const { checkForgeNotesFiles } = await import("../lifecycle/publish-forge");
const { PublishTargetError } = await import("../lifecycle/release-publish");
const { memberTags, renderReleaseTag } = await import("../lifecycle/release-tag");
for (const m of plan.members) {
if (m.resumed) continue;
const dir = resolve(root, m.dir);
try {
const decls = (await loadChantConfig(dir)).config.release?.publish ?? [];
if (!decls.some((d) => d.type === "forge" && d.notes?.file)) continue;
const tags = await memberTags(dir);
checkForgeNotesFiles(decls, dir, m.label, (l) => renderReleaseTag(tags.template, tags.place, l));
} catch (err) {
if (err instanceof PublishTargetError) throw new TrainCutError(err.code, `nothing was cut: ${m.member}: ${err.message}`, err.fix);
throw err;
}
}
}

const cutter = q.cutter ?? spawnMemberCut;
const tags: Record<string, string> = {};
for (const m of plan.members) {
Expand Down
Loading