Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 0019fff50ad7c36250367936195de6c6fabbc771
parent 02a9613d768c1cd2580801b0b76dc117a63081a8
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 28 Oct 2026 23:05:52 -0400

changelog: sections, size-budgeted pages, and an amend writer for the latest release

common/lib/changelog.ts reads a changelog as its `## ` sections (version,
date, the anchor the page gives each heading), pages them by size (a page
holds whole sections up to ~96 KB; [Unreleased] always on page 1), and
amends the LATEST release in memory: its version as a bump of the release
before it (patch/minor/major) or a literal, its date, the [Unreleased]
bullets folded in — or withdraws it back to [Unreleased]. Any older
release is refused by name.

common/controller/cutRelease.ts gains amendRelease: the cut's own read,
dirty-tree guard, atomic write and path-limited commit. A version change
commits with the subject the right cut would have had ("Release editor
0.12.0") and says what it amends in the body; an amend to what the file
already says writes and commits nothing.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Mcommon/components/Changelog.tsx | 23++---------------------
Mcommon/controller/cutRelease.test.ts | 148+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/cutRelease.ts | 219+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/changelog.test.ts | 244+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/changelog.ts | 392+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
5 files changed, 1005 insertions(+), 21 deletions(-)

diff --git a/common/components/Changelog.tsx b/common/components/Changelog.tsx @@ -1,7 +1,7 @@ import type { ReactNode } from "react"; import { Children } from "react"; import Markdown from "markdown-to-jsx"; -import { sliceTopEntries } from "../lib/changelog"; +import { changelogAnchor, sliceTopEntries } from "../lib/changelog"; import { CopyLinkButton } from "./CopyLinkButton"; function flattenText(children: ReactNode): string { @@ -20,28 +20,9 @@ function flattenText(children: ReactNode): string { return out; } -const DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/; -const ISO_DATE = /(\d{4}-\d{2}-\d{2})/; - -function slugify(input: string): string { - return input - .toLowerCase() - .replace(/[^a-z0-9-]+/g, "-") - .replace(/-+/g, "-") - .replace(/^-|-$/g, ""); -} - -function anchorFor(text: string): string { - if (DATE_ONLY.test(text)) return text; - const dateMatch = text.match(ISO_DATE); - if (dateMatch) return dateMatch[1]; - const slug = slugify(text); - return slug || "section"; -} - function H2({ children }: { children?: ReactNode }) { const text = flattenText(children).trim(); - const anchor = text ? anchorFor(text) : null; + const anchor = text ? changelogAnchor(text) : null; return ( <h2 id={anchor ?? undefined} diff --git a/common/controller/cutRelease.test.ts b/common/controller/cutRelease.test.ts @@ -5,7 +5,10 @@ import { tmpdir } from "node:os"; import path from "node:path"; import { execa } from "execa"; import { + amendRelease, + amendVersionProblem, cutReleaseForWorkspace, + describeAmend, cutReleases, describeCutFailure, describeRelease, @@ -661,3 +664,148 @@ test( }); }, ); + +// --- amendRelease --------------------------------------------------------------- + +const MISCUT = [ + "# Changelog", + "", + "## [0.11.1] - 2026-10-28", + "- **A major's worth.**", + "", + "## [0.11.0] - 2026-09-30", + "- eleven", + "", +].join("\n"); + +test("amending a patch release to a minor rewrites the heading and commits it as the minor's release", async () => { + await withRepo({ editor: MISCUT }, async (root) => { + const result = await amendRelease({ + workspace: "editor", + release: "0.11.1", + version: "minor", + commit: true, + root, + }); + assert.equal(result.ok, true, describeAmend(result)); + if (!result.ok) return; + assert.deepEqual(result.to, { version: "0.12.0", date: "2026-10-28" }); + assert.equal(result.heading, "## [0.12.0] - 2026-10-28"); + assert.equal(result.changed, true); + assert.equal(result.committed, true); + assert.equal(await read(root, "editor"), MISCUT.replace("[0.11.1]", "[0.12.0]")); + assert.deepEqual((await subjects(root))[0], "Release editor 0.12.0"); + const body = await git(root, "log", "-1", "--format=%b"); + assert.match(body, /Amends release 0\.11\.1 \(2026-10-28\): version 0\.11\.1 -> 0\.12\.0\./); + assert.equal(await git(root, "status", "--porcelain"), ""); + assert.match(describeAmend(result), /^Amended 0\.11\.1 -> \[0\.12\.0\] - 2026-10-28 \(committed [0-9a-f]{8}\)\.$/); + + // The same amend again: nothing written, no commit. + const again = await amendRelease({ + workspace: "editor", + release: "0.11.1", + version: "minor", + commit: true, + root, + }); + assert.equal(again.ok, true); + if (!again.ok) return; + assert.equal(again.changed, false); + assert.equal(again.committed, false); + assert.equal((await subjects(root)).length, 2); + assert.match(describeAmend(again), /already says that; nothing changed\.$/); + }); +}); + +test("an amend refuses an older release, and writes nothing", async () => { + await withRepo({ editor: MISCUT }, async (root) => { + const result = await amendRelease({ + workspace: "editor", + release: "0.11.0", + version: "major", + commit: true, + root, + }); + assert.deepEqual(result, { + ok: false, + workspace: "editor", + error: "Only the latest release can be amended: 0.11.0 is older than 0.11.1.", + }); + assert.equal(await read(root, "editor"), MISCUT); + assert.equal((await subjects(root)).length, 1); + }); +}); + +test("an amend that commits refuses a dirty tree, as a cut does", async () => { + await withRepo({ editor: MISCUT }, async (root) => { + await writeFile(path.join(root, "README.md"), "changed\n"); + const result = await amendRelease({ + workspace: "editor", + release: "0.11.1", + version: "minor", + commit: true, + root, + }); + assert.equal(result.ok, false); + if (result.ok) return; + assert.match(result.error, /Other uncommitted changes present \(README\.md\)\. Commit or stash them before amending a release\./); + assert.equal(await read(root, "editor"), MISCUT); + }); +}); + +test("folding [Unreleased] in, then withdrawing the release, round-trips", async () => { + const pending = MISCUT.replace("# Changelog\n\n", "# Changelog\n\n## [Unreleased]\n- **Later.**\n\n"); + await withRepo({ editor: pending }, async (root) => { + const folded = await amendRelease({ + workspace: "editor", + release: "0.11.1", + fold: true, + date: "2026-10-29", + commit: true, + root, + }); + assert.equal(folded.ok, true, describeAmend(folded)); + if (!folded.ok) return; + assert.equal(folded.folded, 1); + assert.equal( + await read(root, "editor"), + MISCUT.replace("## [0.11.1] - 2026-10-28\n", "## [0.11.1] - 2026-10-29\n- **Later.**\n"), + ); + assert.equal((await subjects(root))[0], "Amend release editor 0.11.1"); + + const withdrawn = await amendRelease({ + workspace: "editor", + release: "0.11.1", + uncut: true, + commit: true, + root, + }); + assert.equal(withdrawn.ok, true, describeAmend(withdrawn)); + if (!withdrawn.ok) return; + assert.equal(withdrawn.to, null); + assert.equal(withdrawn.moved, 2); + assert.equal( + await read(root, "editor"), + MISCUT.replace("## [0.11.1] - 2026-10-28\n", "## [Unreleased]\n- **Later.**\n"), + ); + assert.equal((await subjects(root))[0], "Withdraw release editor 0.11.1"); + }); +}); + +test("amend input is checked before anything is read", async () => { + assert.equal(amendVersionProblem("minor"), null); + assert.equal(amendVersionProblem("1.2.3"), null); + assert.match(amendVersionProblem("next") ?? "", /"patch", "minor" or "major"/); + await withRepo({ editor: MISCUT }, async (root) => { + const bad = await amendRelease({ workspace: "editor", release: "0.11.1", uncut: true, version: "minor", commit: false, root }); + assert.equal(bad.ok, false); + if (!bad.ok) assert.equal(bad.error, "A withdrawal takes no version, date or fold."); + const noName = await amendRelease({ workspace: "editor", release: " ", version: "minor", commit: false, root }); + assert.equal(noName.ok, false); + // Not committing: the file changes, the log does not. + const plain = await amendRelease({ workspace: "editor", release: "0.11.1", version: "major", commit: false, root }); + assert.equal(plain.ok, true); + assert.match(await read(root, "editor"), /^## \[1\.0\.0\] - 2026-10-28$/m); + assert.equal((await subjects(root)).length, 1); + }); +}); diff --git a/common/controller/cutRelease.ts b/common/controller/cutRelease.ts @@ -2,6 +2,8 @@ import fs from "node:fs"; import path from "node:path"; import { getPaths } from "../lib/paths"; import { + amendLatestRelease, + AMEND_BUMPS, compareVersions, countUnreleasedBullets, cutRelease, @@ -12,6 +14,7 @@ import { hasUnreleasedHeading, suggestNextMinorVersion, suggestNextVersion, + uncutLatestRelease, } from "../lib/changelog"; import { commitPath, headSha, listDirtyPaths } from "../lib/git"; import { writeFileAtomic } from "../lib/jsonFile-server"; @@ -25,6 +28,12 @@ import { writeFileAtomic } from "../lib/jsonFile-server"; // workspace is 0.1.0 and stays so) and no tag is made; neither has ever been a // convention in this repo. // +// AN AMEND (`amendRelease`, below) rewrites the LATEST release's heading again +// — its version, its date, the [Unreleased] bullets folded into it — or +// withdraws it back to [Unreleased]; the same file, the same atomic write, the +// same dirty-tree guard and a path-limited commit of its own. History is never +// rewritten: the release commit stays, and the amend is a NEW commit after it. +// // Three callers, one body: the /sites and /changelog "Cut release" form (the // server action, a FormData adapter), `archilyzer release cut` (local, needs no // editor) and `POST /api/ops/cut-release` (`pnpm ops cut-release`). The @@ -469,3 +478,213 @@ export async function describeRelease( nextMinor: suggestNextMinorVersion(latestVersion), }; } + +// --------------------------------------------------------------------------- +// AMEND THE LATEST RELEASE. The same three callers as a cut (the form on +// /changelog and /sites, `archilyzer release amend`, POST +// /api/ops/amend-release), the same read → plan in memory → atomic write → +// path-limited commit. Only the newest release heading; the caller names it +// (`release`), so a form or a command typed against a changelog that has since +// moved on is refused rather than amending something else. +// +// What a cut writes is one heading, so that is all an amend has to put right: +// no package.json, no tag, no generated file carries a release version. The +// commit an amend makes when the version changes has the subject a cut of that +// version would have had (`Release editor 0.12.0`), so the log reads as if the +// release had been cut right; its body says what it amends. + +/** + * Why `version` can never be an amend's — or null: a bump keyword or X.Y.Z(-pre). + */ +export function amendVersionProblem(version: string): string | null { + const v = version.trim(); + if (!v) return "Version is required."; + if ((AMEND_BUMPS as readonly string[]).includes(v) || SEMVER_VERSION.test(v)) return null; + return `Version "${v}" is not a valid semver (expected X.Y.Z or X.Y.Z-prerelease), "patch", "minor" or "major".`; +} + +export type AmendReleaseOptions = { + workspace: ReleaseWorkspace; + // The latest release's version as the caller saw it (the guard). + release: string; + // "patch" | "minor" | "major" (a bump of the release before it) or a + // literal X.Y.Z(-pre). Absent: kept. + version?: string; + // YYYY-MM-DD. Absent: kept. + date?: string; + // Fold the [Unreleased] bullets into it. + fold?: boolean; + // Withdraw it instead: its bullets go back under [Unreleased]. Takes no + // version, date or fold. + uncut?: boolean; + commit: boolean; + root?: string; +}; + +export type AmendReleaseResult = + | { + ok: true; + workspace: ReleaseWorkspace; + from: { version: string; date: string | null }; + // The release as amended; null when it was withdrawn. + to: { version: string; date: string | null } | null; + // The heading now in the file (null when withdrawn). + heading: string | null; + // Bullets folded in from [Unreleased] (an amend) or moved back under it + // (a withdrawal). + folded: number; + moved: number; + // False when the file already said this: nothing written, no commit. + changed: boolean; + committed: boolean; + commitSha?: string; + } + | { + ok: false; + workspace: ReleaseWorkspace; + error: string; + // As a cut's: the file was written and only the commit failed. + written?: true; + }; + +function amendCommitMessage( + workspace: ReleaseWorkspace, + from: { version: string; date: string | null }, + to: { version: string; date: string | null } | null, + folded: number, + moved: number, +): string { + const was = `${from.version}${from.date ? ` (${from.date})` : ""}`; + if (!to) { + return `Withdraw release ${workspace} ${from.version}\n\nIts ${moved} note${ + moved === 1 ? "" : "s" + } are back under [Unreleased].`; + } + const changes: string[] = []; + if (to.version !== from.version) changes.push(`version ${from.version} -> ${to.version}`); + if (to.date !== from.date) changes.push(`date ${from.date ?? "none"} -> ${to.date ?? "none"}`); + if (folded > 0) { + changes.push(`${folded} note${folded === 1 ? "" : "s"} folded in from [Unreleased]`); + } + const body = `Amends release ${was}: ${changes.join("; ") || "no change"}.`; + const subject = + to.version !== from.version + ? `Release ${workspace} ${to.version}` + : `Amend release ${workspace} ${to.version}`; + return `${subject}\n\n${body}`; +} + +/** + * Amend (or withdraw) one workspace's latest release: the dirty-tree guard + * (when committing), the read, the amend in memory, the atomic write, the + * commit. An amend to what the file already says writes and commits nothing. + */ +export async function amendRelease(opts: AmendReleaseOptions): Promise<AmendReleaseResult> { + const { workspace } = opts; + const fail = (error: string): AmendReleaseResult => ({ ok: false, workspace, error }); + const release = opts.release.trim(); + if (!release) return fail("Which release? Name the latest release's version."); + if (opts.uncut && (opts.version || opts.date || opts.fold)) { + return fail("A withdrawal takes no version, date or fold."); + } + if (opts.version !== undefined) { + const problem = amendVersionProblem(opts.version); + if (problem) return fail(problem); + } + if (opts.date !== undefined) { + const problem = dateISOProblem(opts.date); + if (problem) return fail(problem); + } + const repo = releaseRepo(opts.root); + const filePath = repo.changelogs[workspace]; + const relPath = path.relative(repo.root, filePath); + if (opts.commit) { + const problem = await dirtyTreeProblem(repo, [relPath]); + if (problem) return fail(problem.replace("before cutting a release", "before amending a release")); + } + const read = await readChangelog(filePath); + if (!read.ok) return fail(read.error); + + let next: string; + let from: { version: string; date: string | null }; + let to: { version: string; date: string | null } | null; + let folded = 0; + let moved = 0; + try { + if (opts.uncut) { + const plan = uncutLatestRelease(read.source, release); + next = plan.next; + from = { version: plan.version, date: plan.date }; + to = null; + moved = plan.moved; + } else { + const plan = amendLatestRelease(read.source, { + release, + version: opts.version, + date: opts.date, + fold: opts.fold, + }); + next = plan.next; + from = plan.from; + to = plan.to; + folded = plan.folded; + } + } catch (err) { + if (err instanceof CutReleaseError) return fail(err.message); + throw err; + } + const heading = to ? `## [${to.version}]${to.date ? ` - ${to.date}` : ""}` : null; + const done = (changed: boolean, committed: boolean, commitSha?: string): AmendReleaseResult => ({ + ok: true, + workspace, + from, + to, + heading, + folded, + moved, + changed, + committed, + ...(commitSha ? { commitSha } : {}), + }); + if (next === read.source) return done(false, false); + try { + await writeFileAtomic(filePath, next); + } catch (err) { + return fail(`Could not write ${filePath}: ${(err as Error).message}`); + } + if (!opts.commit) return done(true, false); + const result = await commitPath( + repo.root, + relPath, + amendCommitMessage(workspace, from, to, folded, moved), + ); + if (!result.ok) { + return { + ok: false, + workspace, + error: `Amended release ${from.version}, but the commit failed: ${result.error}`, + written: true, + }; + } + return done(true, true, (await headSha(repo.root)) ?? undefined); +} + +/** One line for an amend's outcome — the CLI's, the form's, the route's. */ +export function describeAmend(result: AmendReleaseResult): string { + if (!result.ok) return result.error; + const what = result.to + ? result.changed + ? `Amended ${result.from.version} -> ${result.heading?.replace(/^## /, "")}${ + result.folded ? `, ${result.folded} note${result.folded === 1 ? "" : "s"} folded in` : "" + }` + : `Release ${result.from.version} already says that; nothing changed` + : `Withdrew ${result.from.version}: ${result.moved} note${ + result.moved === 1 ? "" : "s" + } back under [Unreleased]`; + const commit = !result.changed + ? "" + : result.committed + ? ` (committed${result.commitSha ? ` ${result.commitSha.slice(0, 8)}` : ""})` + : " (not committed)"; + return `${what}${commit}.`; +} diff --git a/common/lib/changelog.test.ts b/common/lib/changelog.test.ts @@ -1,7 +1,18 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import { + amendLatestRelease, + bumpVersion, + changelogAnchor, + changelogPageOf, + clampChangelogPage, compareVersions, + CutReleaseError, + describeAmendTarget, + paginateChangelog, + parseChangelogSections, + suggestNextMajorVersion, + uncutLatestRelease, countUnreleasedBullets, cutRelease, dateISOProblem, @@ -97,3 +108,236 @@ test("countUnreleasedBullets counts the top-level bullets under [Unreleased] onl assert.equal(hasUnreleasedHeading(SOURCE), true); assert.equal(hasUnreleasedHeading("## [0.1.0] - 2026-01-01\n- x\n"), false); }); + +// --- the sections, the pages ------------------------------------------------- + +const RELEASED = [ + "# Changelog", + "", + "## [0.11.1] - 2026-10-28", + "- **Big one.**", + "- **Big two.**", + "", + "## [0.11.0] - 2026-09-30", + "- eleven", + "", + "## [0.10.0] - 2026-09-28", + "- ten", + "", + "## [0.9.4] - 2026-09-28", + "- nine four", +].join("\n"); + +test("parseChangelogSections reads each heading's version, date, anchor and span", () => { + const sections = parseChangelogSections(SOURCE); + assert.deepEqual( + sections.map((s) => [s.title, s.anchor, s.unreleased, s.version, s.date]), + [ + ["[Unreleased]", "unreleased", true, null, null], + ["[0.9.0] - 2026-09-26", "2026-09-26", false, "0.9.0", "2026-09-26"], + ["[0.8.7] - 2026-08-12", "2026-08-12", false, "0.8.7", "2026-08-12"], + ], + ); + // The spans tile the file from the first heading to the end. + assert.equal(sections[0].end, sections[1].start); + assert.equal(sections[2].end, SOURCE.length); + assert.equal(SOURCE.slice(sections[1].bodyStart, sections[1].end), "- released\n\n"); + // `###` is not a section. + assert.equal(parseChangelogSections("## [1.0.0] - 2026-01-01\n### Added\n- x\n").length, 1); +}); + +test("changelogAnchor is the heading's date, else its slug", () => { + assert.equal(changelogAnchor("[0.11.1] - 2026-10-28"), "2026-10-28"); + assert.equal(changelogAnchor("2026-05-19"), "2026-05-19"); + assert.equal(changelogAnchor("[Unreleased]"), "unreleased"); + assert.equal(changelogAnchor("!!!"), "section"); +}); + +test("paginateChangelog fills pages by size, keeps the head on page 1, never splits a section", () => { + const big = "- " + "x".repeat(500); + const src = [ + "# Changelog", + "", + "## [Unreleased]", + big, + "", + "## [1.0.2] - 2026-03-03", + "- small", + "", + "## [1.0.1] - 2026-02-02", + big, + big, + "", + "## [1.0.0] - 2026-01-01", + "- small", + "", + ].join("\n"); + const sections = parseChangelogSections(src); + // A budget below one section: each section a page of its own. + assert.deepEqual(paginateChangelog(sections, 10), [[0], [1], [2], [3]]); + // Room for the head and the small release after it, not for the big one. + assert.deepEqual(paginateChangelog(sections, 600), [[0, 1], [2], [3]]); + // Everything fits. + assert.deepEqual(paginateChangelog(sections, 1_000_000), [[0, 1, 2, 3]]); + const pages = paginateChangelog(sections, 600); + assert.equal(changelogPageOf(sections, pages, "unreleased"), 1); + assert.equal(changelogPageOf(sections, pages, "2026-02-02"), 2); + assert.equal(changelogPageOf(sections, pages, "2026-01-01"), 3); + assert.equal(changelogPageOf(sections, pages, "1999-01-01"), null); + // A changelog with no headings is one empty page. + assert.deepEqual(paginateChangelog(parseChangelogSections("# Changelog\n")), [[]]); +}); + +test("paginateChangelog: a head bigger than the budget is page 1 alone", () => { + const src = `## [Unreleased]\n- ${"y".repeat(300)}\n\n## [1.0.0] - 2026-01-01\n- a\n`; + assert.deepEqual(paginateChangelog(parseChangelogSections(src), 100), [[0], [1]]); +}); + +test("clampChangelogPage reads ?page= leniently", () => { + assert.equal(clampChangelogPage(undefined, 4), 1); + assert.equal(clampChangelogPage("3", 4), 3); + assert.equal(clampChangelogPage("9", 4), 4); + assert.equal(clampChangelogPage("0", 4), 1); + assert.equal(clampChangelogPage("two", 4), 1); + assert.equal(clampChangelogPage(["2", "3"], 4), 2); + assert.equal(clampChangelogPage("2", 0), 1); +}); + +// --- amending the latest release ---------------------------------------------- + +test("bumpVersion counts from the release before: patch, minor, major", () => { + assert.equal(bumpVersion("0.11.0", "patch"), "0.11.1"); + assert.equal(bumpVersion("0.11.0", "minor"), "0.12.0"); + assert.equal(bumpVersion("0.11.0", "major"), "1.0.0"); + assert.equal(suggestNextMajorVersion("1.4.2"), "2.0.0"); + assert.equal(suggestNextMajorVersion(null), "1.0.0"); +}); + +test("describeAmendTarget offers the bumps of the previous release", () => { + const t = describeAmendTarget(`## [Unreleased]\n- a\n- b\n\n${RELEASED.replace("# Changelog\n\n", "")}`); + assert.deepEqual(t, { + latest: { version: "0.11.1", date: "2026-10-28" }, + previous: { version: "0.11.0", date: "2026-09-30" }, + bumps: { patch: "0.11.1", minor: "0.12.0", major: "1.0.0" }, + pending: 2, + }); + assert.equal(describeAmendTarget("# Changelog\n\n## [Unreleased]\n- a\n"), null); +}); + +test("amending a patch cut to a minor gives exactly what a minor cut would have", () => { + const plan = amendLatestRelease(RELEASED, { release: "0.11.1", version: "minor" }); + assert.equal(plan.changed, true); + assert.deepEqual(plan.from, { version: "0.11.1", date: "2026-10-28" }); + assert.deepEqual(plan.to, { version: "0.12.0", date: "2026-10-28" }); + // A minor cut from 0.11.0 on that day, byte for byte. + const minorCut = cutRelease( + RELEASED.replace("## [0.11.1] - 2026-10-28", "## [Unreleased]"), + "0.12.0", + "2026-10-28", + ); + assert.equal(plan.next, minorCut); + // A literal says the same. + assert.equal(amendLatestRelease(RELEASED, { version: "0.12.0" }).next, minorCut); +}); + +test("an amend is idempotent: the same amend again changes nothing", () => { + const once = amendLatestRelease(RELEASED, { release: "0.11.1", version: "minor" }).next; + // A retry naming the release it already amended: no heading is 0.11.1 any + // more, and the latest is already the version asked for. + const twice = amendLatestRelease(once, { release: "0.11.1", version: "minor" }); + assert.equal(twice.changed, false); + assert.equal(twice.next, once); + assert.deepEqual(twice.to, { version: "0.12.0", date: "2026-10-28" }); + // Naming it by its new version, too. + assert.equal(amendLatestRelease(once, { release: "0.12.0", version: "minor" }).changed, false); + // And an amend that asks for nothing. + assert.equal(amendLatestRelease(RELEASED, { release: "0.11.1" }).changed, false); +}); + +test("only the latest release can be amended", () => { + assert.throws( + () => amendLatestRelease(RELEASED, { release: "0.11.0", version: "minor" }), + (err: unknown) => + err instanceof CutReleaseError && + err.message === "Only the latest release can be amended: 0.11.0 is older than 0.11.1.", + ); + assert.throws( + () => amendLatestRelease(RELEASED, { release: "0.8.0", version: "major" }), + /0\.8\.0 is not a release in this changelog; the latest is 0\.11\.1\./, + ); + // A stale name with no version to tell a retry from a mistake is refused. + assert.throws( + () => amendLatestRelease(RELEASED, { release: "0.8.0", date: "2026-10-29" }), + /not a release in this changelog/, + ); + assert.throws(() => amendLatestRelease("# Changelog\n", {}), /There is no release to amend\./); +}); + +test("an amend refuses a version that does not follow the previous release, and bad dates", () => { + assert.throws( + () => amendLatestRelease(RELEASED, { version: "0.11.0" }), + /Version 0\.11\.0 is not newer than the previous release, 0\.11\.0\./, + ); + assert.throws(() => amendLatestRelease(RELEASED, { version: "0.10.5" }), /not newer than the previous/); + assert.throws(() => amendLatestRelease(RELEASED, { version: "twelve" }), /not a valid semver/); + assert.throws(() => amendLatestRelease(RELEASED, { date: "2026-02-30" }), /not a calendar date/); + assert.throws( + () => amendLatestRelease(RELEASED, { date: "2026-09-01" }), + /Date 2026-09-01 is before the previous release \(0\.11\.0, 2026-09-30\)\./, + ); + // A date alone. + const redated = amendLatestRelease(RELEASED, { date: "2026-10-29" }); + assert.match(redated.next, /^## \[0\.11\.1\] - 2026-10-29$/m); + assert.equal(redated.next.replace("2026-10-29", "2026-10-28"), RELEASED); +}); + +test("folding moves what waits under [Unreleased] into the release and drops that heading", () => { + const withPending = RELEASED.replace( + "# Changelog\n\n", + "# Changelog\n\n## [Unreleased]\n- **Later one.**\n- **Later two.**\n\n", + ); + const plan = amendLatestRelease(withPending, { release: "0.11.1", version: "minor", fold: true }); + assert.equal(plan.folded, 2); + assert.equal( + plan.next, + RELEASED.replace( + "## [0.11.1] - 2026-10-28\n", + "## [0.12.0] - 2026-10-28\n- **Later one.**\n- **Later two.**\n", + ), + ); + // Again: nothing left to fold, nothing changes. + const again = amendLatestRelease(plan.next, { release: "0.12.0", version: "minor", fold: true }); + assert.equal(again.changed, false); + assert.equal(again.folded, 0); + // Without fold the pending bullets stay where they are. + const kept = amendLatestRelease(withPending, { version: "minor" }); + assert.match(kept.next, /## \[Unreleased\]\n- \*\*Later one\.\*\*/); + assert.equal(kept.folded, 0); +}); + +test("withdrawing the latest release puts its bullets back under [Unreleased]", () => { + const plain = uncutLatestRelease(RELEASED, "0.11.1"); + assert.equal(plain.moved, 2); + assert.equal(plain.next, RELEASED.replace("## [0.11.1] - 2026-10-28", "## [Unreleased]")); + // Then a minor cut gives what the amend gives. + assert.equal( + cutRelease(plain.next, "0.12.0", "2026-10-28"), + amendLatestRelease(RELEASED, { version: "minor" }).next, + ); + // Under bullets already pending, which are newer. + const withPending = RELEASED.replace( + "# Changelog\n\n", + "# Changelog\n\n## [Unreleased]\n- **Later.**\n\n", + ); + const merged = uncutLatestRelease(withPending); + assert.equal( + merged.next, + RELEASED.replace("## [0.11.1] - 2026-10-28\n", "## [Unreleased]\n- **Later.**\n"), + ); + assert.throws(() => uncutLatestRelease(RELEASED, "0.10.0"), /Only the latest release can be amended/); + // The last release in the file keeps no trailing blank line. + assert.equal( + uncutLatestRelease("# Changelog\n\n## [1.0.0] - 2026-01-01\n- a\n").next, + "# Changelog\n\n## [Unreleased]\n- a\n", + ); +}); diff --git a/common/lib/changelog.ts b/common/lib/changelog.ts @@ -197,3 +197,395 @@ export function cutRelease( const replacement = `## [${version}] - ${dateISO}`; return `${before}${replacement}${after}`; } + +/** + * The major bump: `0.11.1` → `1.0.0`. No release yet (or an unreadable + * version) is `1.0.0`. + */ +export function suggestNextMajorVersion(current: string | null): string { + const parsed = parseVersion(current); + if (!parsed) return "1.0.0"; + return `${parsed.core[0] + 1}.0.0`; +} + +// --------------------------------------------------------------------------- +// THE SECTIONS. A changelog read as its `## ` headings: what /changelog pages +// through and what an amend rewrites. Offsets are into the source, so a +// section is `source.slice(start, end)` and its body +// `source.slice(bodyStart, end)`. + +export type ChangelogSection = { + // The heading's text after `## `: `[0.11.1] - 2026-10-28`. + title: string; + // The id the page gives this heading's <h2> (`changelogAnchor`). + anchor: string; + unreleased: boolean; + version: string | null; + date: string | null; + start: number; + bodyStart: number; + end: number; +}; + +const H2_LINE = /^##[ \t]+([^\n]*?)[ \t]*$/gm; +const RELEASE_TITLE = + /^\[(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)\](?:\s+-\s+(\d{4}-\d{2}-\d{2}))?/; +const UNRELEASED_TITLE = /^\[Unreleased\]$/i; +const ANCHOR_DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/; +const ANCHOR_ISO_DATE = /(\d{4}-\d{2}-\d{2})/; + +/** + * The id a changelog heading gets on the page: its date when it has one (so a + * link copied before a re-cut still lands), else a slug of its text + * (`[Unreleased]` → `unreleased`). Two headings of one date share an id; the + * first one wins, as `getElementById` has it. + */ +export function changelogAnchor(text: string): string { + const t = text.trim(); + if (ANCHOR_DATE_ONLY.test(t)) return t; + const date = t.match(ANCHOR_ISO_DATE); + if (date) return date[1]; + const slug = t + .toLowerCase() + .replace(/[^a-z0-9-]+/g, "-") + .replace(/-+/g, "-") + .replace(/^-|-$/g, ""); + return slug || "section"; +} + +/** Every `## ` heading of `source`, in order, with where its section runs. */ +export function parseChangelogSections(source: string): ChangelogSection[] { + const sections: ChangelogSection[] = []; + for (const m of source.matchAll(H2_LINE)) { + const start = m.index ?? 0; + const lineEnd = source.indexOf("\n", start); + const bodyStart = lineEnd === -1 ? source.length : lineEnd + 1; + const title = m[1]; + const release = RELEASE_TITLE.exec(title); + if (sections.length) sections[sections.length - 1].end = start; + sections.push({ + title, + anchor: changelogAnchor(title), + unreleased: UNRELEASED_TITLE.test(title), + version: release ? release[1] : null, + date: release ? (release[2] ?? null) : null, + start, + bodyStart, + end: source.length, + }); + } + return sections; +} + +// --------------------------------------------------------------------------- +// THE PAGES of /changelog. The file is ~760 KB of markdown, and rendering all +// of it made the page a 2.9 MB response the browser took 5-10 s to show. A +// page holds whole sections up to a size budget — at least one, so a section +// bigger than the budget is a page of its own — and the first page always +// opens with everything above the first release ([Unreleased], whatever its +// size). Sizes, not counts: the sections run from 300 bytes to 360 KB. + +export const CHANGELOG_PAGE_BUDGET = 96_000; + +/** The sections of each page, as indexes into `sections`; never empty. */ +export function paginateChangelog( + sections: readonly ChangelogSection[], + budget: number = CHANGELOG_PAGE_BUDGET, +): number[][] { + const pages: number[][] = []; + let current: number[] = []; + let size = 0; + let headDone = false; + sections.forEach((s, i) => { + const len = s.end - s.start; + const head = !headDone && s.version === null; + if (!head) headDone = true; + if (!head && current.length > 0 && size + len > budget) { + pages.push(current); + current = []; + size = 0; + } + current.push(i); + size += len; + }); + if (current.length > 0 || pages.length === 0) pages.push(current); + return pages; +} + +/** The 1-based page holding the first section with `anchor`, or null. */ +export function changelogPageOf( + sections: readonly ChangelogSection[], + pages: readonly number[][], + anchor: string, +): number | null { + const index = sections.findIndex((s) => s.anchor === anchor); + if (index === -1) return null; + const page = pages.findIndex((p) => p.includes(index)); + return page === -1 ? null : page + 1; +} + +/** `?page=` read leniently: anything not a page number is page 1. */ +export function clampChangelogPage(raw: unknown, pageCount: number): number { + const v = Array.isArray(raw) ? raw[0] : raw; + const n = typeof v === "string" && /^\d+$/.test(v) ? Number(v) : 1; + return Math.min(Math.max(n, 1), Math.max(pageCount, 1)); +} + +// --------------------------------------------------------------------------- +// AMENDING THE LATEST RELEASE. A cut is one heading rewrite; an amend rewrites +// the same heading again — its version (a bump of the release BEFORE it, so a +// patch cut can become the minor it should have been), its date — and can +// fold the bullets that have since gathered under [Unreleased] into it, or +// withdraw it (`uncutLatestRelease`: its bullets go back under [Unreleased]). +// Only the newest release: an older one is history other releases were cut +// after. + +export const AMEND_BUMPS = ["patch", "minor", "major"] as const; +export type AmendBump = (typeof AMEND_BUMPS)[number]; + +export function isAmendBump(v: unknown): v is AmendBump { + return (AMEND_BUMPS as readonly unknown[]).includes(v); +} + +/** `previous` bumped by `kind` — what a cut of that kind would have made. */ +export function bumpVersion(previous: string | null, kind: AmendBump): string { + if (kind === "major") return suggestNextMajorVersion(previous); + if (kind === "minor") return suggestNextMinorVersion(previous); + return suggestNextVersion(previous); +} + +export type AmendTarget = { + // The latest release as it is now. + latest: { version: string; date: string | null }; + // The release before it, which a bump counts from (null: it is the first). + previous: { version: string; date: string | null } | null; + // What each bump would make it. + bumps: Record<AmendBump, string>; + // Top-level bullets under an [Unreleased] heading above it. + pending: number; +}; + +/** What the Amend form offers, read-only; null when there is no release. */ +export function describeAmendTarget(source: string): AmendTarget | null { + const sections = parseChangelogSections(source); + const releases = sections.filter((s) => s.version !== null); + const latest = releases[0]; + if (!latest || latest.version === null) return null; + const prev = releases[1]; + const previous = + prev && prev.version !== null ? { version: prev.version, date: prev.date } : null; + const latestIndex = sections.indexOf(latest); + const unreleased = sections.findIndex((s) => s.unreleased); + const pending = + unreleased !== -1 && unreleased < latestIndex + ? countBullets(source.slice(sections[unreleased].bodyStart, sections[unreleased].end)) + : 0; + return { + latest: { version: latest.version, date: latest.date }, + previous, + bumps: { + patch: bumpVersion(previous?.version ?? null, "patch"), + minor: bumpVersion(previous?.version ?? null, "minor"), + major: bumpVersion(previous?.version ?? null, "major"), + }, + pending, + }; +} + +function countBullets(body: string): number { + return body.split("\n").filter((line) => /^[-*+]\s/.test(line)).length; +} + +export type AmendSpec = { + // The release the caller means (its version). Refused unless it is the + // latest — except a retry: when no heading carries it any more and the + // latest already IS the version asked for, the amend goes on against the + // latest (and is then usually a no-op). + release?: string; + // A bump of the previous release, or a literal X.Y.Z(-pre). Absent: kept. + version?: string; + // YYYY-MM-DD. Absent: kept. + date?: string; + // Fold whatever waits under [Unreleased] into the release, and drop that + // heading — as if those bullets had been there when it was cut. + fold?: boolean; +}; + +export type AmendPlan = { + next: string; + changed: boolean; + from: { version: string; date: string | null }; + to: { version: string; date: string | null }; + // Top-level bullets folded in from [Unreleased]. + folded: number; +}; + +// The latest release, after the `release` guard. `target` is the version the +// amend would give it (for the retry rule); null for a withdrawal. +function latestFor( + sections: readonly ChangelogSection[], + release: string | undefined, + target: (previous: string | null) => string | null, +): { latest: ChangelogSection; previous: ChangelogSection | null } { + const releases = sections.filter((s) => s.version !== null); + const latest = releases[0]; + if (!latest || latest.version === null) { + throw new CutReleaseError("There is no release to amend."); + } + const previous = releases[1] ?? null; + const named = release?.trim(); + if (named && named !== latest.version) { + if (releases.some((r) => r.version === named)) { + throw new CutReleaseError( + `Only the latest release can be amended: ${named} is older than ${latest.version}.`, + ); + } + if (target(previous?.version ?? null) !== latest.version) { + throw new CutReleaseError( + `${named} is not a release in this changelog; the latest is ${latest.version}.`, + ); + } + } + return { latest, previous }; +} + +function resolveAmendVersion(spec: string | undefined, previous: string | null, current: string): string { + const v = spec?.trim(); + if (!v) return current; + if (isAmendBump(v)) return bumpVersion(previous, v); + return v; +} + +// One section's text: its heading, its body, and the blank line before the +// next heading (none at the end of the file). +function sectionText(heading: string, body: string, last: boolean): string { + const b = body.replace(/^\n+/, "").trimEnd(); + const text = b ? `${heading}\n${b}\n` : `${heading}\n`; + return last ? text : `${text}\n`; +} + +/** + * Amend the latest release in memory. Throws CutReleaseError with the + * refusal's sentence: no release, an older release named, a version that is + * not semver or not newer than the release before it, a bad date or one + * before the previous release's, an [Unreleased] heading below the release. + * Amending to what is already there is not an error: `changed` is false. + */ +export function amendLatestRelease(source: string, spec: AmendSpec): AmendPlan { + const sections = parseChangelogSections(source); + const { latest, previous } = latestFor(sections, spec.release, (prev) => + resolveAmendVersion(spec.version, prev, "\u0000"), + ); + const current = latest.version as string; + const prevVersion = previous?.version ?? null; + const version = resolveAmendVersion(spec.version, prevVersion, current); + if (!SEMVER_VERSION.test(version)) { + throw new CutReleaseError( + `Version "${version}" is not a valid semver (expected X.Y.Z or X.Y.Z-prerelease), "patch", "minor" or "major".`, + ); + } + if (prevVersion && compareVersions(version, prevVersion) <= 0) { + throw new CutReleaseError( + `Version ${version} is not newer than the previous release, ${prevVersion}.`, + ); + } + if ( + version !== current && + sections.some((s) => s !== latest && s.version === version) + ) { + throw new CutReleaseError(`There is already a release ${version} in this changelog.`); + } + const date = spec.date?.trim() || latest.date; + if (date) { + const problem = dateISOProblem(date); + if (problem) throw new CutReleaseError(problem); + if (previous?.date && date < previous.date) { + throw new CutReleaseError( + `Date ${date} is before the previous release (${prevVersion}, ${previous.date}).`, + ); + } + } + const latestIndex = sections.indexOf(latest); + const unreleasedIndex = sections.findIndex((s) => s.unreleased); + const heading = `## [${version}]${date ? ` - ${date}` : ""}`; + const last = latestIndex === sections.length - 1; + let folded = 0; + let next: string; + if (spec.fold && unreleasedIndex !== -1) { + if (unreleasedIndex > latestIndex) { + throw new CutReleaseError( + "The [Unreleased] heading is below the latest release; move it to the top before folding.", + ); + } + const u = sections[unreleasedIndex]; + const pendingBody = source.slice(u.bodyStart, u.end).trim(); + folded = countBullets(pendingBody); + const body = [pendingBody, source.slice(latest.bodyStart, latest.end).trim()] + .filter(Boolean) + .join("\n"); + next = + source.slice(0, u.start) + + source.slice(u.end, latest.start) + + sectionText(heading, body, last) + + source.slice(latest.end); + } else { + const lineEnd = latest.bodyStart > latest.start && source[latest.bodyStart - 1] === "\n" + ? latest.bodyStart - 1 + : latest.bodyStart; + next = source.slice(0, latest.start) + heading + source.slice(lineEnd); + } + return { + next, + changed: next !== source, + from: { version: current, date: latest.date }, + to: { version, date }, + folded, + }; +} + +export type UncutPlan = { + next: string; + // The release withdrawn. + version: string; + date: string | null; + // Top-level bullets moved back under [Unreleased]. + moved: number; +}; + +/** + * Withdraw the latest release in memory: its heading becomes `## [Unreleased]`, + * or — when an [Unreleased] heading already sits above it — its bullets join + * that section, under the ones already pending (those are newer). + */ +export function uncutLatestRelease(source: string, release?: string): UncutPlan { + const sections = parseChangelogSections(source); + const { latest } = latestFor(sections, release, () => null); + const latestIndex = sections.indexOf(latest); + const unreleasedIndex = sections.findIndex((s) => s.unreleased); + const releaseBody = source.slice(latest.bodyStart, latest.end).trim(); + const moved = countBullets(releaseBody); + const last = latestIndex === sections.length - 1; + let next: string; + if (unreleasedIndex !== -1 && unreleasedIndex < latestIndex) { + const u = sections[unreleasedIndex]; + const pendingBody = source.slice(u.bodyStart, u.end).trim(); + const between = source.slice(u.end, latest.start); + const body = [pendingBody, releaseBody].filter(Boolean).join("\n"); + // Anything between the two (it should be nothing) stays above them. + next = + source.slice(0, u.start) + + between + + sectionText(`## ${u.title}`, body, last) + + source.slice(latest.end); + } else if (unreleasedIndex !== -1) { + throw new CutReleaseError( + "The [Unreleased] heading is below the latest release; move it to the top before withdrawing.", + ); + } else { + next = + source.slice(0, latest.start) + + sectionText("## [Unreleased]", releaseBody, last) + + source.slice(latest.end); + } + return { next, version: latest.version as string, date: latest.date, moved }; +}