173 lines
6.2 KiB
JavaScript
173 lines
6.2 KiB
JavaScript
#!/usr/bin/env node
|
|
import { execFileSync } from 'node:child_process';
|
|
import { readFileSync, writeFileSync } from 'node:fs';
|
|
import path from 'node:path';
|
|
import { fileURLToPath } from 'node:url';
|
|
|
|
/**
|
|
* Builds CHANGELOG.md from the Conventional Commits of the history, as the FWS conventions
|
|
* require: `feat` and `fix` feed the Features and Bug Fixes sections, the other types are
|
|
* grouped under "Other changes". The file is generated, so run this script instead of editing it.
|
|
*
|
|
* Usage: node scripts/generate-changelog.js [--check]
|
|
* --check exits with code 1 when CHANGELOG.md is out of date (used by CI and tests)
|
|
*/
|
|
|
|
const rootDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
|
const changelogPath = path.join(rootDir, 'CHANGELOG.md');
|
|
const checkOnly = process.argv.includes('--check');
|
|
|
|
/** Section order and titles; anything else falls into "Other changes". */
|
|
const SECTIONS = [
|
|
{ title: 'Features', test: (type) => type === 'feat' },
|
|
{ title: 'Bug Fixes', test: (type) => type === 'fix' },
|
|
{ title: 'Performance', test: (type) => type === 'perf' },
|
|
{
|
|
title: 'Other changes',
|
|
test: (type) => type !== 'feat' && type !== 'fix' && type !== 'perf',
|
|
},
|
|
];
|
|
|
|
const OTHER_LABELS = {
|
|
build: 'build',
|
|
chore: 'chore',
|
|
ci: 'ci',
|
|
docs: 'docs',
|
|
refactor: 'refactor',
|
|
revert: 'revert',
|
|
style: 'style',
|
|
test: 'test',
|
|
};
|
|
|
|
const git = (args) => execFileSync('git', args, { cwd: rootDir, encoding: 'utf8' });
|
|
|
|
function readCommits() {
|
|
// One record per commit, fields separated by unit separators so bodies stay readable.
|
|
const raw = git([
|
|
'log',
|
|
'--no-merges',
|
|
'--date=short',
|
|
'--format=%H%x1f%ad%x1f%s%x1f%b%x1f%D%x1e',
|
|
// A commit that only rewrites the changelog must not appear in it, otherwise `--check`
|
|
// could never be green once that file is committed.
|
|
'--',
|
|
'.',
|
|
':(exclude)CHANGELOG.md',
|
|
]);
|
|
return raw
|
|
.split('\x1e')
|
|
.map((record) => record.trim())
|
|
.filter(Boolean)
|
|
.map((record) => {
|
|
const [hash, date, subject, body = '', decoration = ''] = record.split('\x1f');
|
|
const match = /^(?<type>[a-z]+)(?:\((?<scope>[^)]*)\))?(?<breaking>!)?: (?<description>.+)$/.exec(
|
|
subject.trim(),
|
|
);
|
|
const breaking = Boolean(match?.groups.breaking) || /BREAKING CHANGE/.test(body);
|
|
return {
|
|
hash,
|
|
date,
|
|
subject: subject.trim(),
|
|
type: match?.groups.type ?? 'other',
|
|
scope: match?.groups.scope ?? null,
|
|
description: match?.groups.description ?? subject.trim(),
|
|
breaking,
|
|
tags: decoration
|
|
.split(',')
|
|
.map((ref) => ref.trim().replace(/^tag: /, ''))
|
|
.filter((ref) => /^v?\d+\.\d+\.\d+/.test(ref)),
|
|
};
|
|
});
|
|
}
|
|
|
|
function entryLine(commit) {
|
|
const scope = commit.scope ? `**${commit.scope}:** ` : '';
|
|
const breaking = commit.breaking ? '**BREAKING** ' : '';
|
|
const label = commit.type === 'other' ? '' : `_(${OTHER_LABELS[commit.type] ?? commit.type})_ `;
|
|
const detail = commit.type === 'other' ? commit.subject : commit.description;
|
|
return `- ${breaking}${scope}${label}${detail} ([${commit.hash.slice(0, 7)}])`;
|
|
}
|
|
|
|
/** A commit without a tag belongs to "Unreleased"; a tag closes the section it points to. */
|
|
function groupByRelease(commits) {
|
|
const releases = [];
|
|
let current = { title: 'Unreleased', date: null, commits: [] };
|
|
|
|
for (const commit of commits) {
|
|
current.commits.push(commit);
|
|
for (const tag of commit.tags) {
|
|
releases.push({ title: tag, date: commit.date, commits: current.commits });
|
|
current = { title: 'Unreleased', date: null, commits: [] };
|
|
}
|
|
}
|
|
if (current.commits.length > 0) releases.push(current);
|
|
return releases;
|
|
}
|
|
|
|
function renderRelease(release) {
|
|
const heading = release.date ? `## [${release.title}] — ${release.date}` : `## [${release.title}]`;
|
|
const lines = [heading];
|
|
|
|
for (const section of SECTIONS) {
|
|
const entries = release.commits.filter((commit) => section.test(commit.type));
|
|
if (entries.length === 0) continue;
|
|
lines.push('', `### ${section.title}`, ...entries.map(entryLine));
|
|
}
|
|
|
|
if (release.commits.length === 0) lines.push('', '_Nothing yet._');
|
|
return lines.join('\n');
|
|
}
|
|
|
|
/** SemVer hint from the commits since the last release: breaking > feature > fix. */
|
|
function suggestVersion(commits) {
|
|
const version = JSON.parse(readFileSync(path.join(rootDir, 'package.json'), 'utf8')).version;
|
|
const [major, minor, patch] = version.split('.').map(Number);
|
|
const breaking = commits.some((commit) => commit.breaking);
|
|
const feature = commits.some((commit) => commit.type === 'feat');
|
|
|
|
// SemVer §4: below 1.0.0 anything may change, so a breaking change only bumps the minor.
|
|
if (major === 0) return breaking || feature ? `0.${minor + 1}.0` : `0.${minor}.${patch + 1}`;
|
|
if (breaking) return `${major + 1}.0.0`;
|
|
if (feature) return `${major}.${minor + 1}.0`;
|
|
return `${major}.${minor}.${patch + 1}`;
|
|
}
|
|
|
|
function buildChangelog(commits) {
|
|
const releases = groupByRelease(commits);
|
|
|
|
return [
|
|
'# Changelog',
|
|
'',
|
|
'All notable changes to this project are documented in this file. It is **generated from the',
|
|
'Conventional Commits** of the history: run `npm run changelog` instead of editing it by hand.',
|
|
'The project follows [Semantic Versioning](https://semver.org/).',
|
|
'',
|
|
releases.map(renderRelease).join('\n\n'),
|
|
'',
|
|
].join('\n');
|
|
}
|
|
|
|
const commits = readCommits();
|
|
const content = buildChangelog(commits);
|
|
const unreleased = commits.filter((commit) => !commit.tags.length);
|
|
const previous = (() => {
|
|
try {
|
|
return readFileSync(changelogPath, 'utf8');
|
|
} catch {
|
|
return null;
|
|
}
|
|
})();
|
|
|
|
if (checkOnly) {
|
|
if (previous !== content) {
|
|
console.error('CHANGELOG.md is out of date: run `npm run changelog`.');
|
|
process.exit(1);
|
|
}
|
|
console.log('CHANGELOG.md is up to date.');
|
|
process.exit(0);
|
|
}
|
|
|
|
writeFileSync(changelogPath, content);
|
|
console.log(`Wrote ${path.relative(rootDir, changelogPath)} from ${commits.length} commits.`);
|
|
console.log(`Suggested next version: ${suggestVersion(unreleased)}`);
|