// Replace the generated block of a hand-written markdown document with what a // tool printed, touching nothing outside the markers. The block is delimited by // // // ... // // // on their own lines. The prose around it is the author's; the block is // regenerated (a turnkey's handover tables come from `norsk-ctl instance // export-template --format handover`), and `--check` is the CI snapshot: a // document whose block would change is stale, and the diff is the review. // // | bun run node_modules/@norskvideo/ctl-dev-kit/docs/splice-generated.ts docs/handover.md [--check] import { readFileSync, writeFileSync } from "node:fs"; export const BEGIN_MARKER = ""; export type SpliceResult = | { status: "ok"; value: { next: string; changed: boolean } } | { status: "error"; error: string }; export function spliceGenerated(current: string, generated: string): SpliceResult { const lines = current.split("\n"); const begins = lines.flatMap((l, i) => (l.startsWith(BEGIN_MARKER) && l.trimEnd().endsWith("-->") ? [i] : [])); const ends = lines.flatMap((l, i) => (l.trim() === END_MARKER ? [i] : [])); if (begins.length === 0 || ends.length === 0) { return { status: "error", error: `no generated block: expected a line starting "${BEGIN_MARKER}" and a line "${END_MARKER}"`, }; } if (begins.length > 1 || ends.length > 1) { return { status: "error", error: "more than one generated block; exactly one is spliced" }; } const [begin] = begins; const [end] = ends; if (end < begin) return { status: "error", error: `"${END_MARKER}" precedes the BEGIN marker` }; const body = generated.replace(/^\n+/, "").replace(/\s+$/, ""); const next = [...lines.slice(0, begin + 1), body, ...lines.slice(end)].join("\n"); return { status: "ok", value: { next, changed: next !== current } }; } if (import.meta.main) { const args = process.argv.slice(2); const check = args.includes("--check"); const file = args.find((a) => !a.startsWith("--")); if (!file) { console.error("usage: | splice-generated.ts [--check]"); process.exit(2); } const generated = await Bun.stdin.text(); const result = spliceGenerated(readFileSync(file, "utf8"), generated); if (result.status === "error") { console.error(`splice-generated: ${file}: ${result.error}`); process.exit(2); } const { next, changed } = result.value; if (check) { if (changed) { console.error( `splice-generated: ${file} is stale — its generated block differs from what the generator prints now`, ); process.exit(1); } console.log(`splice-generated: ${file} is current`); process.exit(0); } if (changed) { writeFileSync(file, next); console.log(`splice-generated: updated ${file}`); } else { console.log(`splice-generated: ${file} unchanged`); } }