Files
systemic-game-design-course/tools/lib.mjs
T
2026-10-28 23:54:55 +01:00

61 lines
2.1 KiB
JavaScript

import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const here = dirname(fileURLToPath(import.meta.url));
/** Course directory; override with COURSE_ROOT (used by tests). */
export function courseRoot() {
return process.env.COURSE_ROOT
? resolve(process.env.COURSE_ROOT)
: join(here, "..", "course");
}
/** Module directories `course/NN-slug/`, sorted by number. */
export function moduleDirs() {
const root = courseRoot();
if (!existsSync(root)) return [];
return readdirSync(root)
.map((name) => ({ name, m: /^(\d\d)-(.+)$/.exec(name) }))
.filter(({ name, m }) => m && statSync(join(root, name)).isDirectory())
.map(({ name, m }) => ({ num: m[1], slug: m[2], path: join(root, name) }))
.sort((a, b) => a.num.localeCompare(b.num));
}
export function testFiles(path, lang) {
const dir = join(path, "tests", lang === "rust" ? "rust" : "ts");
if (!existsSync(dir)) return [];
const ext = lang === "rust" ? /\.rs$/ : /\.test\.ts$/;
return readdirSync(dir).filter((f) => ext.test(f)).sort().map((f) => join(dir, f));
}
/** Test names declared by a module's tests for `lang` ("rust" | "ts"). */
export function testNames(path, lang) {
const re = lang === "rust" ? /fn\s+(test_\w+)/g : /test\(\s*["'](test_\w+)/g;
const names = new Set();
for (const f of testFiles(path, lang)) {
for (const m of readFileSync(f, "utf8").matchAll(re)) names.add(m[1]);
}
return [...names].sort();
}
/** `### test_…` headings in a module's scenarios.md. */
export function scenarioNames(path) {
const f = join(path, "scenarios.md");
if (!existsSync(f)) return [];
const names = new Set();
for (const m of readFileSync(f, "utf8").matchAll(/^### (test_\w+)/gm)) names.add(m[1]);
return [...names].sort();
}
export function loadCatalog() {
const f = join(courseRoot(), "catalog.json");
if (!existsSync(f)) throw new Error(`catalog not found: ${f}`);
return JSON.parse(readFileSync(f, "utf8"));
}
export function fail(msg) {
console.error(msg);
process.exit(1);
}