diff --git a/pr-checks/changenotes.mts b/pr-checks/changenotes.mts index 2fb86b0ca..c7a10d022 100755 --- a/pr-checks/changenotes.mts +++ b/pr-checks/changenotes.mts @@ -1,11 +1,20 @@ #!/usr/bin/env npx tsx import * as fs from "node:fs"; +import { readFileSync } from "node:fs"; import { pathToFileURL } from "node:url"; import { parseArgs } from "node:util"; +import path from "path"; +import { matter } from "lite-matter"; + +import { + addBodyLinesToUnreleasedSection, + parseChangelog, + renderChangelog, +} from "./changelog"; import { isValidAllChangenoteFiles } from "./changelog/validate.mjs"; -import { CHANGENOTES_DIR } from "./config"; +import { CHANGELOG_FILE, CHANGENOTES_DIR } from "./config"; const entryPoint = process.argv[1]; if (entryPoint && import.meta.url === pathToFileURL(entryPoint).href) { @@ -27,6 +36,8 @@ function main(): number { case undefined: case "help": return usage(); + case "flush": + return flush(); case "validate": return validate(); default: @@ -36,10 +47,47 @@ function main(): number { } function usage(): number { - console.log(`Usage: changenotes.mts validate`); + const message = + "Usage: changenotes.mts flush\n" + + " changenotes.mts validate\n" + + " changenotes.mts help"; + console.log(message); return 0; } +function flush(): number { + try { + // Get the file paths to our changenotes; these will be useful later. + const changenotePaths = fs + .readdirSync(CHANGENOTES_DIR) + .filter((name) => name !== ".gitkeep") + .map((name) => path.join(CHANGENOTES_DIR, name)); + + // From the file paths, we read the files to obtain the actual notes themselves. + const changenotes = changenotePaths.map((filePath) => { + const fileBody = readFileSync(filePath).toString(); + const { content } = matter(fileBody); + return content.trim(); + }); + + const changelogContents = fs.readFileSync(CHANGELOG_FILE).toString(); + const changelog = parseChangelog(changelogContents); + addBodyLinesToUnreleasedSection(changelog, changenotes); + fs.writeFileSync(CHANGELOG_FILE, renderChangelog(changelog)); + + // Delete changenotes only after successful processing. + for (const p of changenotePaths) { + fs.unlinkSync(p); + } + + return 0; + } catch (e) { + console.error("Failed to flush changenotes to 'CHANGELOG.md'", e); + } + + return 1; +} + function validate(): number { try { if (isValidAllChangenoteFiles(fs.readdirSync(CHANGENOTES_DIR))) {