#!/usr/bin/env node
import { createHash } from 'node:crypto'
import fs from 'node:fs'
import path from 'node:path'
import { cachePath, REPO_ROOT, resolveStorageRoot } from './debug/paths.mjs'
import { createTemporaryFiles } from './debug/temporary-files.mjs'
const changelog = path.join(REPO_ROOT, 'CHANGELOG.md')
const changes = path.join(REPO_ROOT, 'changes')
const versionPart = '(?:0|[1-9]\\d*)'
const tagPattern = `v${versionPart}\\.${versionPart}\\.${versionPart}`
const versionHeading = new RegExp(`^## (${tagPattern}) — (\\d{4}-\\d{2}-\\d{2})$`, 'm')
const groups = [
{ key: 'new', zh: '新增功能', en: 'New Features' },
{ key: 'improvements', zh: '体验优化', en: 'Improvements' },
{ key: 'fixes', zh: '问题修复', en: 'Bug Fixes' },
{ key: 'security', zh: '安全', en: 'Security' },
{ key: 'removals', zh: '移除', en: 'Removals' },
{ key: 'chores', zh: '其他变更', en: 'Chores' },
]
const languages = [['zh', 'cn'], ['en', 'en']]
const navigation = (version) => `[中文](#cn-${version}) | [English](#en-${version})`
const heading = (text, anchor) => anchor ? `
${text}
` : `### ${text}`
const compareVersions = (a, b) => a.localeCompare(b, 'en', { numeric: true })
const sameAuthors = (a, b) => a.join(',') === b.join(',')
const authorSeparator = ' — '
const authorLink = (login) => `[@${login}](https://github.com/${login})`
function checkAuthors(authors, label) {
if (!Array.isArray(authors) || !authors.length ||
authors.some((login) => typeof login !== 'string' || login.length > 39 || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/i.test(login)) ||
new Set(authors.map((login) => login.toLowerCase())).size !== authors.length) {
throw new Error(`${label} needs a nonempty authors list of unique GitHub usernames`)
}
}
function dateIsValid(date) {
if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) return false
const parsed = new Date(`${date}T00:00:00Z`)
return !Number.isNaN(parsed.getTime()) && parsed.toISOString().slice(0, 10) === date
}
function checkEntry(text, label) {
if (typeof text !== 'string' || !text || text !== text.trim() || /[\r\n]/.test(text)) {
throw new Error(`${label} must be one nonempty line without leading or trailing whitespace`)
}
const prose = text.replace(/`[^`]+`/g, '').replace(/\]\([^\s)]+\)/g, ']')
if (text.includes(authorSeparator + '[@')) throw new Error(`${label} must keep author attribution separate from the entry text`)
if (/[::]/.test(prose) || /^(?:[-*+]\s|\d+\.\s|#|<)/.test(text)) {
throw new Error(`${label} must be a plain entry without a list marker, heading, or prose colon`)
}
}
function readChanges() {
let files
try {
files = fs.readdirSync(changes, { withFileTypes: true })
} catch (error) {
if (error.code === 'ENOENT') return []
throw error
}
const fragments = files.map((file) => {
const label = `changes/${file.name}`
if (!file.isFile() || !/^[a-z0-9]+(?:-[a-z0-9]+)*\.json$/.test(file.name)) {
throw new Error(`${label} must be a regular .json file`)
}
const raw = fs.readFileSync(path.join(changes, file.name), 'utf8')
let entry
try {
entry = JSON.parse(raw)
} catch (error) {
throw new Error(`${label}: ${error.message}`)
}
if (!entry || Object.keys(entry).sort().join(',') !== 'authors,en,group,order,zh' ||
!groups.some(({ key }) => key === entry.group) || !Number.isSafeInteger(entry.order) || entry.order < 0) {
throw new Error(`${label} needs a valid group, nonnegative integer order, authors, zh, and en`)
}
checkAuthors(entry.authors, label)
for (const [language] of languages) checkEntry(entry[language], `${label} ${language}`)
return { ...entry, name: file.name, raw }
})
return fragments.sort((a, b) => a.order - b.order || a.name.localeCompare(b.name, 'en'))
}
function readBullet(line, label) {
const separator = line.lastIndexOf(authorSeparator)
if (separator < 0) throw new Error(`${label} needs an author suffix`)
const text = line.slice(0, separator)
const authors = line.slice(separator + authorSeparator.length).split(', ').map((link) =>
link.match(/^\[@([A-Za-z0-9-]+)\]\(https:\/\/github\.com\/\1\)$/)?.[1])
checkEntry(text, label)
checkAuthors(authors, label)
return { text, authors }
}
function readGroups(lines, version, language, prefix) {
const entries = new Map()
let index = -1
for (const line of lines) {
if (line.startsWith('- ') && index >= 0) {
entries.get(groups[index].key).push(readBullet(line.slice(2), `${version} ${language}`))
continue
}
const next = groups.findIndex((group) => line === heading(group[language], index < 0 ? `${prefix}-${version}` : ''))
if (next <= index) throw new Error(`${version} ${language} has an unexpected line or group order: ${line}`)
index = next
entries.set(groups[index].key, [])
}
if (entries.size === 0 || [...entries.values()].some((bullets) => bullets.length === 0)) {
throw new Error(`${version} ${language} must have entries under every group it lists`)
}
return entries
}
function readVersions(source) {
const sections = source.split(/(?=^## )/m).slice(1)
if (!sections.length) throw new Error('CHANGELOG.md has no version sections')
const versions = new Map()
let previous
for (const section of sections) {
const [title, ...raw] = section.split('\n')
const match = title.match(versionHeading)
if (!match) throw new Error(`Unexpected CHANGELOG.md version heading: ${title}`)
const [, tag, date] = match
if (!dateIsValid(date) || (previous && (date > previous.date || compareVersions(tag, previous.tag) >= 0))) {
throw new Error(`${tag} must have a valid date, unique version, and newest-first order`)
}
const [links, ...lines] = raw.filter((line) => line.trim())
const split = lines.findIndex((line) => line.startsWith(``))
if (links !== navigation(tag) || split < 1) throw new Error(`${tag} needs linked Chinese and English sections`)
const zh = readGroups(lines.slice(0, split), tag, 'zh', 'cn')
const en = readGroups(lines.slice(split), tag, 'en', 'en')
for (const { key } of groups) {
const chinese = zh.get(key) ?? []
const english = en.get(key) ?? []
if (chinese.length !== english.length || chinese.some((entry, index) => !sameAuthors(entry.authors, english[index].authors))) {
throw new Error(`${tag} ${key} needs matching Chinese and English entries and authors`)
}
}
versions.set(tag, { date, zh, en })
previous = { tag, date }
}
return versions
}
function render(title, version, fragments) {
const lines = [title, '', navigation(version)]
for (const [language, prefix] of languages) {
let anchor = `${prefix}-${version}`
for (const group of groups) {
const items = fragments.filter((entry) => entry.group === group.key)
if (!items.length) continue
lines.push('', heading(group[language], anchor), '', ...items.map((entry) =>
`- ${entry[language]}${authorSeparator}${entry.authors.map(authorLink).join(', ')}`))
anchor = ''
}
}
return `${lines.join('\n')}\n`
}
function prepare(tag, date, storage) {
const cache = cachePath(storage)
const key = createHash('sha256').update(fs.realpathSync(REPO_ROOT)).digest('hex').slice(0, 12)
const lock = path.join(cache, `changelog-${key}.lock`)
fs.mkdirSync(cache, { recursive: true })
const fd = fs.openSync(lock, 'wx')
try {
fs.writeFileSync(fd, `${process.pid}\n`)
const source = fs.readFileSync(changelog, 'utf8').replaceAll('\r\n', '\n')
const versions = readVersions(source)
const fragments = readChanges()
const [latestTag, latest] = versions.entries().next().value
if (versions.has(tag)) {
const matches = fragments.every(({ group, zh, en, authors }) =>
latest.zh.get(group)?.some((entry, index) =>
entry.text === zh && sameAuthors(entry.authors, authors) && latest.en.get(group)[index].text === en))
if (tag !== latestTag || date !== latest.date || !matches) throw new Error(`${tag} already exists in CHANGELOG.md`)
} else {
if (!fragments.length) throw new Error('No pending changes to prepare')
if (date < latest.date || compareVersions(tag, latestTag) <= 0) throw new Error(`${tag} must follow ${latestTag}`)
const offset = source.search(/^## /m)
const section = render(`## ${tag} — ${date}`, tag, fragments)
const updated = `${source.slice(0, offset)}${section}\n${source.slice(offset)}`
readVersions(updated)
const files = createTemporaryFiles(storage)
const directory = files.create('prepare-changelog', process.pid)
try {
const output = path.join(directory, 'CHANGELOG.md')
fs.writeFileSync(output, updated, 'utf8')
fs.renameSync(output, changelog)
} finally {
files.close(directory)
}
}
for (const { name, raw } of fragments) {
const file = path.join(changes, name)
if (fs.readFileSync(file, 'utf8') !== raw) throw new Error(`changes/${name} was edited during preparation`)
fs.unlinkSync(file)
}
console.log(`changelog: ${tag} prepared, cleared ${fragments.length} fragment(s)`)
} finally {
fs.closeSync(fd)
fs.unlinkSync(lock)
}
}
function main(args) {
const [command, tag, flag, date] = args
if (command === 'prepare' && args.length === 4 && flag === '--date' &&
new RegExp(`^${tagPattern}$`).test(tag) && dateIsValid(date)) {
prepare(tag, date, resolveStorageRoot())
} else if (args.length === 1 && command === 'check') {
const versions = readVersions(fs.readFileSync(changelog, 'utf8').replaceAll('\r\n', '\n'))
console.log(`changelog: ${versions.size} version(s), ${readChanges().length} pending change(s)`)
} else if (args.length === 1 && command === 'preview') {
const fragments = readChanges()
process.stdout.write(fragments.length ? render('## [Unreleased]', 'unreleased', fragments) : 'No pending changes.\n')
} else {
throw new Error('Usage: node scripts/changelog.mjs check | preview | prepare vX.Y.Z --date YYYY-MM-DD')
}
}
try {
main(process.argv.slice(2))
} catch (error) {
console.error(`changelog: ${error.message}`)
process.exitCode = 1
}