|
| 1 | +import { execFileSync } from "node:child_process"; |
| 2 | +import { mkdirSync, readdirSync, writeFileSync } from "node:fs"; |
| 3 | +import { dirname, relative, resolve } from "node:path"; |
| 4 | +import { fileURLToPath } from "node:url"; |
| 5 | + |
| 6 | +const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); |
| 7 | +const docsDirectory = resolve(root, "docs"); |
| 8 | + |
| 9 | +function markdownFiles(directory) { |
| 10 | + return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => { |
| 11 | + const path = resolve(directory, entry.name); |
| 12 | + if (entry.isDirectory()) return markdownFiles(path); |
| 13 | + return entry.name.toLowerCase().endsWith(".md") ? [path] : []; |
| 14 | + }); |
| 15 | +} |
| 16 | + |
| 17 | +export function collectLastUpdatedDates() { |
| 18 | + const dates = {}; |
| 19 | + |
| 20 | + for (const file of markdownFiles(docsDirectory)) { |
| 21 | + const documentPath = relative(docsDirectory, file).replaceAll("\\", "/"); |
| 22 | + const repositoryPath = `docs/${documentPath}`; |
| 23 | + const date = execFileSync( |
| 24 | + "git", |
| 25 | + ["log", "-1", "--follow", "--format=%cs", "--", repositoryPath], |
| 26 | + { cwd: root, encoding: "utf8" }, |
| 27 | + ).trim(); |
| 28 | + |
| 29 | + if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) { |
| 30 | + throw new Error(`Could not determine the last commit date for ${repositoryPath}.`); |
| 31 | + } |
| 32 | + |
| 33 | + dates[documentPath] = date; |
| 34 | + } |
| 35 | + |
| 36 | + return Object.fromEntries(Object.entries(dates).sort(([left], [right]) => left.localeCompare(right))); |
| 37 | +} |
| 38 | + |
| 39 | +export function writeLastUpdatedManifest(outputFile) { |
| 40 | + const dates = collectLastUpdatedDates(); |
| 41 | + mkdirSync(dirname(outputFile), { recursive: true }); |
| 42 | + writeFileSync(outputFile, `${JSON.stringify(dates, null, 2)}\n`, "utf8"); |
| 43 | + console.log(`Generated last-updated metadata for ${Object.keys(dates).length} documents.`); |
| 44 | +} |
| 45 | + |
| 46 | +const invokedDirectly = process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url); |
| 47 | +if (invokedDirectly) { |
| 48 | + writeLastUpdatedManifest(resolve(process.argv[2] || resolve(docsDirectory, "last-updated.json"))); |
| 49 | +} |
0 commit comments