Files
iptvnator/tools/release/build-release-notes.mjs
T
4grayandClaude Opus 5 270350c2e1 chore(release): author release notes in .changes instead of reconstructing them (#1256)
* chore(release): author release notes in .changes instead of reconstructing them

CHANGELOG.md has been frozen at 0.12.0 since 2023 while the app shipped
0.23.0, semantic-release sat in devDependencies with no config, and the real
user-facing notes were a 280-line MDX post written from memory at release
time. The gap was never version math — it was authored notes captured while
the context is still fresh.

Add a `.changes/*.md` note format (type, area, issues, screenshot; no version
field, since the release version is chosen deliberately) plus a generator that
composes the GitHub release body, the CHANGELOG.md section and a blog-post
scaffold from the accumulated notes.

Changesets was considered and rejected: it versions multiple published
packages, and this repo has exactly one private package. Its `version` step
would also rewrite CHANGELOG.md into a flatter format than the blog post and
fight the deliberate, updater-constrained version choice.

- hand-rolled frontmatter parser over a YAML engine: the schema is closed, so
  it can reject unknown keys, which is what catches typos
- PR numbers are resolved from the commit that added the note, never written
  by the author
- MDX-significant characters in note bodies are escaped so a stray `<` cannot
  break the website build
- blog scaffold ships `draft: true` with explicit TODO headings; the prose is
  editorial work, only the inventory is mechanical
- revive CHANGELOG.md with an honest pointer for 0.13.0-0.23.0 rather than
  fabricating the missing history
- drop the five unused semantic-release/conventional-changelog packages

Docs: `.changes/README.md`, plus a "Release Notes For User-Visible Changes"
section mirrored in CLAUDE.md and AGENTS.md, and a PR template checkbox for
contributors who never read either.

Tests: 26 unit tests in tools/release/release-notes.test.mjs covering parsing,
validation, grouping and all three renderers.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(release): default the notes version to package.json and harden alt escaping

Review follow-ups on the release-notes generator.

- `--version` now defaults to the root package.json version, so the
  `release🎶*` package scripts run bare instead of failing on a missing
  argument. Bumping package.json is the deliberate act that starts a release,
  which makes it the right single source of truth; `--version` remains as an
  override for dry runs before the bump. The notice goes to stderr so
  `--format github` keeps a pipeable stdout.
- Escape backslashes before apostrophes when building the MDX `alt` string
  literal. A note body ending in a backslash previously produced an
  unterminated string and would have broken the website build.
- Document that release posts are one per minor version, in the slug helper,
  the overwrite error, and `.changes/README.md` — a patch release edits the
  existing post rather than creating a second one.

Tests: +1 regression test for the alt escaping, verified to fail without the
fix (27 total, all passing).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* feat(ci): put authored notes into the tag release body, fail-closed

Wires the .changes pipeline into the release workflow (Codex review P1 on
#1256). Calling the generator from the tag build cannot work — --consume
deletes .changes/ before the tag exists — so the tag build reads what the
generator already wrote: release-meta now fills BODY from the CHANGELOG.md
section matching the tag's version via tools/release/extract-changelog-section.mjs.

generate_release_notes stays on, so GitHub's commit list renders below the
authored notes; the existing draft-metadata repair step already concatenates
RELEASE_BODY with the generated notes, so the rare duplicate-draft path keeps
the same layering unchanged.

The extractor exits non-zero when the section is missing or empty, failing
the release instead of silently shipping PR-title-only notes. A hotfix tag
cut without running release:notes:changelog therefore fails at create-release
by design; the error message names the exact commands to run.

Tests: 5 new extractor tests (32 total in release-tools, all passing);
packaging suite (247) re-run green since build-and-make.yaml is one of its
inputs.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(release): escape all regex metacharacters in the changelog extractor

CodeQL flagged the version-to-RegExp interpolation in
extract-changelog-section.mjs (regex injection + incomplete escaping): only
dots were escaped, and while the CLI validates its argument as bare semver
before calling, the exported extractSection() carries no such guarantee on
its own. Escape the full metacharacter set so no caller can inject pattern
syntax, with tests covering wildcard dots, alternation, `.*` and backslashes.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(release): make changelog generation idempotent per version

Codex review P2 on #1256: rerunning `release:notes:changelog` for the same
version — the normal move after correcting a note before --consume —
prepended a second section instead of replacing the first, leaving duplicate
release entries.

Extract the marker insertion into upsertChangelogSection(): it removes any
existing section for the version, then rebuilds around the marker rather than
string-replacing into it, so the blank-line count on both sides stays exact
on both the fresh-insert and replace paths. The CLI reports when a section
was replaced.

Tests: 4 new cases (insert, replace-not-duplicate, neighbours untouched,
missing marker); 37 total passing. End-to-end rerun verified: one heading,
latest date wins, extractor output unchanged.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-07-25 18:22:43 +02:00

313 lines
8.8 KiB
JavaScript

#!/usr/bin/env node
/**
* Composes release surfaces from the notes accumulated in `.changes/`.
*
* node tools/release/build-release-notes.mjs --validate
* node tools/release/build-release-notes.mjs --version 0.24.0 --format github
* node tools/release/build-release-notes.mjs --version 0.24.0 --format changelog
* node tools/release/build-release-notes.mjs --version 0.24.0 --format blog
* node tools/release/build-release-notes.mjs --version 0.24.0 --consume
*
* Every mode except `--consume` is a safe dry run: nothing is deleted unless
* `--consume` is passed explicitly.
*/
import { execFileSync } from 'node:child_process';
import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import path from 'node:path';
import process from 'node:process';
import { fileURLToPath } from 'node:url';
import { loadNotes } from './release-notes.mjs';
import {
releaseSlug,
renderBlogScaffold,
renderChangelogSection,
renderGithubBody,
upsertChangelogSection,
} from './release-notes-render.mjs';
const workspaceRoot = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
'../..'
);
const CHANGELOG_PATH = path.join(workspaceRoot, 'CHANGELOG.md');
const BLOG_DIR = path.join(workspaceRoot, 'apps/website/src/content/blog');
/** Generated sections are inserted directly below this marker. */
const CHANGELOG_MARKER = '<!-- next-release -->';
const FORMATS = new Set(['github', 'changelog', 'blog']);
function parseArgs(argv) {
const options = {
format: null,
version: null,
previous: null,
date: new Date().toISOString().slice(0, 10),
dir: '.changes',
validate: false,
consume: false,
force: false,
};
for (let index = 0; index < argv.length; index += 1) {
const arg = argv[index];
const takeValue = () => {
const value = argv[index + 1];
if (value === undefined || value.startsWith('--')) {
throw new Error(`${arg} requires a value`);
}
index += 1;
return value;
};
switch (arg) {
case '--format':
options.format = takeValue();
break;
case '--version':
options.version = takeValue();
break;
case '--previous':
options.previous = takeValue();
break;
case '--date':
options.date = takeValue();
break;
case '--dir':
options.dir = takeValue();
break;
case '--validate':
options.validate = true;
break;
case '--consume':
options.consume = true;
break;
case '--force':
options.force = true;
break;
default:
throw new Error(`unknown argument: ${arg}`);
}
}
return options;
}
function git(args) {
return execFileSync('git', args, {
cwd: workspaceRoot,
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'ignore'],
}).trim();
}
/**
* Resolves each note to the commit that added it, and to a PR number when the
* commit subject carries one. Authors never write a PR number themselves —
* they cannot know it while the branch is still local.
*
* @param {object[]} notes
* @returns {Map<string, { commit?: string, pr?: number }>}
*/
function resolveLinks(notes) {
const links = new Map();
for (const note of notes) {
let output = '';
try {
output = git([
'log',
'--diff-filter=A',
'--format=%H%x00%s',
'-1',
'--',
note.sourcePath,
]);
} catch {
// Not a git checkout, or the note is not committed yet. Entries
// simply render without a reference link.
}
if (!output) {
continue;
}
const [commit, subject = ''] = output.split('\0');
const prMatch = subject.match(/\(#(\d+)\)\s*$/);
links.set(note.sourcePath, {
commit,
pr: prMatch ? Number(prMatch[1]) : undefined,
});
}
return links;
}
/** Latest `v*` tag, used for the CHANGELOG compare link. */
function detectPreviousVersion() {
try {
return git(['describe', '--tags', '--abbrev=0', '--match=v*']).replace(
/^v/,
''
);
} catch {
return null;
}
}
/**
* The release version is the one in the root package.json — bumping it is the
* deliberate act that starts a release. `--version` stays available as an
* override (dry runs, previewing a version before the bump), but the default
* keeps a single source of truth and lets the package scripts run bare.
*/
function resolveVersion(options) {
let version = options.version;
if (!version) {
version = JSON.parse(
readFileSync(path.join(workspaceRoot, 'package.json'), 'utf8')
).version;
// stderr, so `--format github` keeps a clean pipeable stdout.
console.error(`Using version ${version} from package.json.`);
}
if (!/^\d+\.\d+\.\d+$/.test(version)) {
throw new Error(
`version must be a bare semver like 0.24.0, got "${version}"`
);
}
return version;
}
function writeChangelog(section, version) {
const { content, replaced } = upsertChangelogSection(
readFileSync(CHANGELOG_PATH, 'utf8'),
section,
version,
CHANGELOG_MARKER
);
if (replaced) {
console.error(`Replacing existing CHANGELOG.md section for ${version}.`);
}
writeFileSync(CHANGELOG_PATH, content, 'utf8');
return CHANGELOG_PATH;
}
function writeBlogScaffold(content, version, force) {
const target = path.join(
BLOG_DIR,
`${releaseSlug(version)}-release-notes.mdx`
);
if (existsSync(target) && !force) {
throw new Error(
[
`${path.relative(workspaceRoot, target)} already exists.`,
'The website publishes one post per minor version, so a patch',
'release edits the existing post instead of creating a new one.',
'Pass --force only to regenerate it from scratch.',
].join(' ')
);
}
writeFileSync(target, content, 'utf8');
return target;
}
function main() {
const options = parseArgs(process.argv.slice(2));
const notesDir = path.resolve(workspaceRoot, options.dir);
const { notes, errors } = loadNotes(notesDir);
if (errors.length > 0) {
console.error('Invalid release notes:\n');
for (const error of errors) {
console.error(` ${error}`);
}
console.error(
'\nSee .changes/README.md for the expected format.'
);
process.exit(1);
}
if (options.validate) {
console.log(`${notes.length} release note(s) valid.`);
}
if (options.format) {
if (!FORMATS.has(options.format)) {
throw new Error(
`unknown --format "${options.format}" (expected ${[...FORMATS].join(', ')})`
);
}
const version = resolveVersion(options);
const links = resolveLinks(notes);
if (notes.length === 0) {
throw new Error(
`no notes found in ${path.relative(workspaceRoot, notesDir)}/ — nothing to render`
);
}
if (options.format === 'github') {
process.stdout.write(`${renderGithubBody(notes, { links })}\n`);
}
if (options.format === 'changelog') {
const section = renderChangelogSection(notes, {
version,
date: options.date,
previousVersion: options.previous ?? detectPreviousVersion(),
links,
});
const target = writeChangelog(section, version);
console.log(`Updated ${path.relative(workspaceRoot, target)}`);
}
if (options.format === 'blog') {
const content = renderBlogScaffold(notes, {
version,
date: options.date,
links,
});
const target = writeBlogScaffold(content, version, options.force);
console.log(`Wrote ${path.relative(workspaceRoot, target)}`);
}
}
if (options.consume) {
for (const note of notes) {
rmSync(note.sourcePath);
}
console.log(`Removed ${notes.length} consumed note(s).`);
}
if (!options.format && !options.validate && !options.consume) {
throw new Error(
'nothing to do — pass --validate, --format <github|changelog|blog>, or --consume'
);
}
}
try {
main();
} catch (error) {
console.error(error.message);
process.exit(1);
}