Skip to content

Commit 48303b9

Browse files
TMHSDigitalclaude
andcommitted
scripts: one browser-module list, one slug helper, strict flags everywhere
shared.mjs BROWSER_MODULES is now the one list of lib modules shipped to the browser; build copies it and the tests read it, and a test fails if a browser module or site/public script imports from node: or names a lib file the build does not ship. checks.mjs drops its slugify copy for search.mjs slugOf. shortlist.js keeps its own escapeHtml (entry pages do not load shared.mjs) and a test holds it equal to esc(). Every script now parses flags through site/lib/cli.mjs (node:util parseArgs, strict): an unknown or mistyped flag, or a flag missing its value, exits 2 with the usage line instead of being ignored. thumbs --limit with no value used to start an unlimited fetch run; it is now refused. Closes #236 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LpkeXQPaUhxjgqdqnk6BrJ
1 parent 52311b2 commit 48303b9

15 files changed

Lines changed: 162 additions & 63 deletions

‎site/build.mjs‎

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ import { execFileSync } from "node:child_process";
1414
import fs from "node:fs";
1515
import path from "node:path";
1616
import { fileURLToPath } from "node:url";
17-
import { baseHeadHtml, commercialLabel, headAssetsHtml, esc, latestAllowedDate, OG_CARD_NAME, opensearchLinkHtml, opensearchXml, PAGE_MODULES, PREVIEW_CREDIT_LINE, sponsorButtonHtml } from "./lib/shared.mjs";
17+
import { baseHeadHtml, BROWSER_MODULES, commercialLabel, headAssetsHtml, esc, latestAllowedDate, OG_CARD_NAME, opensearchLinkHtml, opensearchXml, PAGE_MODULES, PREVIEW_CREDIT_LINE, sponsorButtonHtml } from "./lib/shared.mjs";
1818
import { filmstripHtml, groupedEntriesHtml } from "./lib/cards.mjs";
1919
import { guidePageHtml } from "./lib/guide-page.mjs";
2020
import { renderGuide } from "./lib/guide-render.mjs";
@@ -23,6 +23,7 @@ import { filmstripPick, isAttributionLicence, previewCredit, thumbRelPath } from
2323
import { summaryFromBody } from "./lib/frontmatter.mjs";
2424
import { readCatalog, idMatchesFile } from "./lib/entry-files.mjs";
2525
import { optionalFields } from "./lib/entry-fields.mjs";
26+
import { cliArgs } from "./lib/cli.mjs";
2627
import { entryPageHtml, scriptJson } from "./lib/entry-page.mjs";
2728
import { LinkError, makeLinkResolver, caseMismatch } from "./lib/links.mjs";
2829
import { atomFeed, catalogCsv, commitDatesFromLog, DATED_PATHS, homeJsonLd, sitemapXml } from "./lib/exports.mjs";
@@ -549,7 +550,7 @@ function checkPages(files) {
549550

550551
function main() {
551552
const started = Date.now();
552-
const clean = process.argv.includes("--clean");
553+
const clean = cliArgs({ clean: { type: "boolean" } }, "node site/build.mjs [--clean]").values.clean === true;
553554
const config = JSON.parse(fs.readFileSync(CONFIG_PATH, "utf8"));
554555
const vocab = JSON.parse(fs.readFileSync(VOCAB_PATH, "utf8"));
555556
const formatVocab = JSON.parse(fs.readFileSync(FORMATS_PATH, "utf8"));
@@ -637,14 +638,8 @@ function main() {
637638
if (clean) for (const name of fs.readdirSync(DIST)) fs.rmSync(path.join(DIST, name), { recursive: true, force: true });
638639
// index.html is a template; its filled-in version is written below.
639640
copyPublic(PUBLIC, new Set(["index.html"]));
640-
// The shortlist builds its CREDITS file with the same code as the stack pages.
641-
copyOut(path.join(__dirname, "lib", "owes.mjs"), "owes.js");
642-
// The catalog search and the 404 page's guesses, tested in lib.test.mjs.
643-
copyOut(path.join(__dirname, "lib", "search.mjs"), "search.js");
644-
// The entry template and its helpers, served as modules to app.js and the
645-
// category pages. Neither may import from node:.
646-
copyOut(path.join(__dirname, "lib", "cards.mjs"), "cards.mjs");
647-
copyOut(path.join(__dirname, "lib", "shared.mjs"), "shared.mjs");
641+
// Lib modules the browser loads (shared.mjs BROWSER_MODULES; none imports node:).
642+
for (const [out, src] of Object.entries(BROWSER_MODULES)) copyOut(path.join(__dirname, "lib", src), out);
648643
const hasCard = fs.existsSync(OG_CARD_SRC);
649644
if (hasCard) copyOut(OG_CARD_SRC, OG_CARD_NAME);
650645
// data.json is the public machine-readable catalog (see site/README.md);

‎site/check-added.mjs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,10 @@ import path from "node:path";
1111
import { fileURLToPath } from "node:url";
1212
import { firstAddedFromLog, lateAddedDates } from "./lib/added-dates.mjs";
1313
import { readCatalog } from "./lib/entry-files.mjs";
14+
import { cliArgs } from "./lib/cli.mjs";
15+
16+
// No flags: a mistyped one fails instead of being ignored.
17+
cliArgs({}, "node site/check-added.mjs");
1418

1519
const __dirname = path.dirname(fileURLToPath(import.meta.url));
1620
const ROOT = path.resolve(__dirname, "..");

‎site/check-links.mjs‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import { fileURLToPath } from "node:url";
2525
import { maintenanceFromRepo } from "./checks.mjs";
2626
import { readCatalog, usableRecord } from "./lib/entry-files.mjs";
2727
import { safeFetch } from "./lib/safe-fetch.mjs";
28+
import { cliArgs } from "./lib/cli.mjs";
2829
import { checkMaintenanceRepos, classify, reportUrl, staleDaysFrom } from "./lib/link-check.mjs";
2930

3031
const __dirname = path.dirname(fileURLToPath(import.meta.url));
@@ -37,10 +38,6 @@ const UA =
3738
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0 Safari/537.36 " +
3839
"(+https://github.com/TMHSDigital/Free-Game-Dev-Assets link check)";
3940

40-
function arg(name, fallback) {
41-
const i = process.argv.indexOf(name);
42-
return i === -1 ? fallback : process.argv[i + 1];
43-
}
4441

4542
function loadEntries() {
4643
const out = [];
@@ -99,6 +96,7 @@ function checkMaintenance(entries) {
9996
}
10097

10198
// Flags are checked before the first request, so a typo fails in a second.
99+
const { values: flags } = cliArgs({ report: { type: "string" }, "stale-days": { type: "string" } }, "node site/check-links.mjs [--report <file.md>] [--stale-days 365]");
102100
const staleArg = staleDaysFrom(process.argv);
103101
if (staleArg.error) {
104102
console.error(staleArg.error);
@@ -153,7 +151,7 @@ const report = [
153151
"",
154152
].join("\n");
155153

156-
const reportPath = arg("--report", null);
154+
const reportPath = flags.report ?? null;
157155
if (reportPath) fs.writeFileSync(reportPath, report);
158156
else process.stdout.write(report);
159157
if (process.env.GITHUB_OUTPUT) fs.appendFileSync(process.env.GITHUB_OUTPUT, `problems=${problems}\n`);

‎site/checks.mjs‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import { ENGINE_LOCK_NOTES, isRealDate, MAINTENANCE_NOTES, PERSPECTIVES, STATUS_
1414
import { headingSlug } from "./lib/guide-render.mjs";
1515
import { isAttributionLicence, isPrivateHost, PREVIEW_LICENSES, previewEligibility, safeImageUrl } from "./lib/thumbs.mjs";
1616
import { parseStack, pickPath, StackError } from "./lib/stacks.mjs";
17+
import { slugOf } from "./lib/search.mjs";
1718

1819
export { evidenceSection };
1920

@@ -656,14 +657,11 @@ export function checkValueAliases(rel, meta, aliases) {
656657
* matches the publisher field, so the tag adds nothing but a way to be wrong.
657658
* The licence-restating tags are retired in site/value-aliases.json (V19).
658659
*/
659-
export function slugify(text) {
660-
return String(text).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
661-
}
662660

663661
export function checkTagsRestatePublisher(rel, meta) {
664662
const errors = [];
665663
if (empty(meta.publisher)) return errors;
666-
const own = slugify(meta.publisher);
664+
const own = slugOf(meta.publisher);
667665
for (const t of Array.isArray(meta.tags) ? meta.tags.map(String) : []) {
668666
if (t === own) {
669667
errors.push(`${rel} tag "${t}" restates publisher "${meta.publisher}"; search and grouping use the publisher field`);

‎site/lib/cli.mjs‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/**
2+
* Command-line flags for the site scripts, through node:util parseArgs in
3+
* strict mode: an unknown or mistyped flag, or a value-taking flag with no
4+
* value, stops the script with its usage line instead of being ignored.
5+
*/
6+
import { parseArgs } from "node:util";
7+
8+
/** `{ values, positionals }` for argv (without node and the script), or throws a TypeError naming the problem. */
9+
export function readArgs(argv, options, { positionals = false } = {}) {
10+
return parseArgs({ args: argv, options, strict: true, allowPositionals: positionals });
11+
}
12+
13+
/** readArgs over process.argv; on a bad flag, prints the reason and `usage` and exits 2. */
14+
export function cliArgs(options, usage, { positionals = false } = {}) {
15+
try {
16+
return readArgs(process.argv.slice(2), options, { positionals });
17+
} catch (err) {
18+
console.error(`${err.message}\nusage: ${usage}`);
19+
process.exit(2);
20+
}
21+
}

‎site/lib/lib.test.mjs‎

Lines changed: 51 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1357,7 +1357,7 @@ eq("search: q from the URL is capped", readState(`?q=${"a".repeat(5000)}`, { q:
13571357
const libDir = new URL("./", import.meta.url);
13581358
const publicDir = new URL("../public/", import.meta.url);
13591359
// dist name -> source file (build.mjs copies these four from site/lib).
1360-
const fromLib = { "search.js": "search.mjs", "owes.js": "owes.mjs", "cards.mjs": "cards.mjs", "shared.mjs": "shared.mjs" };
1360+
const { BROWSER_MODULES: fromLib } = await import("./shared.mjs");
13611361
const src = (name) => nodeFs.readFileSync(fromLib[name] ? new URL(fromLib[name], libDir) : new URL(name, publicDir), "utf8");
13621362
const importsOf = (name) => [...src(name).matchAll(/^import[^;]*?from "\.\/([^"]+)";/gm)].map((m) => m[1]);
13631363
const closure = (roots) => {
@@ -1768,7 +1768,7 @@ eq("search: q from the URL is capped", readState(`?q=${"a".repeat(5000)}`, { q:
17681768
const nodePath = await import("node:path");
17691769
const publicDir = new URL("../public/", import.meta.url);
17701770
// dist name -> source module in site/lib (build.mjs copies these out).
1771-
const fromLib = { "search.js": "search.mjs", "owes.js": "owes.mjs", "cards.mjs": "cards.mjs", "shared.mjs": "shared.mjs" };
1771+
const { BROWSER_MODULES: fromLib } = await import("./shared.mjs");
17721772
const scripts = nodeFs.readdirSync(publicDir).filter((f) => f.endsWith(".js")).sort();
17731773
const tmp = nodeFs.mkdtempSync(nodePath.join(os.tmpdir(), "fgda-client-"));
17741774
const exportsOfPublic = (text) => {
@@ -1877,9 +1877,15 @@ eq("search: q from the URL is capped", readState(`?q=${"a".repeat(5000)}`, { q:
18771877
eq("pr-diff: modified licence is a field change", JSON.stringify(rows[1].fields[0]), '{"field":"license","before":"CC0","after":"MIT"}');
18781878
eq("pr-diff: unchanged type change has no fields", rows[3].fields.length, 0);
18791879
const { baseArg } = await import("../pr-diff.mjs");
1880-
eq("pr-diff: a sha base is accepted", baseArg(["node", "x", "--base", "abc1234"]), "abc1234");
1881-
eq("pr-diff: a ref name is refused (exit 2)", baseArg(["node", "x", "--base", "main"]), null);
1882-
eq("pr-diff: a missing base is refused", baseArg(["node", "x", "--base"]), null);
1880+
eq("pr-diff: a sha base is accepted", baseArg(["--base", "abc1234"]), "abc1234");
1881+
eq("pr-diff: a ref name is refused (exit 2)", baseArg(["--base", "main"]), null);
1882+
let missingBase = "";
1883+
try { baseArg(["--base"]); } catch (e) { missingBase = e.message; }
1884+
has("pr-diff: --base with no value is an error", missingBase, "--base");
1885+
eq("pr-diff: no --base gives null", baseArg([]), null);
1886+
let unknownFlag = "";
1887+
try { baseArg(["--bsae", "abc1234"]); } catch (e) { unknownFlag = e.message; }
1888+
has("pr-diff: a mistyped flag is an error", unknownFlag, "Unknown option '--bsae'");
18831889

18841890
const one = licenceDiffMarkdown([{ file: "catalog/a.md", change: "added", fields: [{ field: "tags", before: null, after: "a, b" }], evidence: null }]);
18851891
has("licence diff: one entry", one, "1 entry changed.");
@@ -1961,6 +1967,46 @@ eq("search: q from the URL is capped", readState(`?q=${"a".repeat(5000)}`, { q:
19611967
eq("fields: preview is not exported", "preview" in optionalFields({ preview: "none" }), false);
19621968
}
19631969

1970+
/* browser modules never import from node: (#236) -------------------------- */
1971+
{
1972+
const { BROWSER_MODULES, PAGE_MODULES } = await import("./shared.mjs");
1973+
const publicDir = new URL("../public/", import.meta.url);
1974+
const sources = [
1975+
...Object.values(BROWSER_MODULES).map((f) => [`lib/${f}`, nodeFs.readFileSync(new URL(f, import.meta.url), "utf8")]),
1976+
...nodeFs.readdirSync(publicDir).filter((f) => f.endsWith(".js")).map((f) => [`public/${f}`, nodeFs.readFileSync(new URL(f, publicDir), "utf8")]),
1977+
];
1978+
for (const [name, text] of sources) {
1979+
lacks(`browser: ${name} imports nothing from node:`, text, 'from "node:');
1980+
lacks(`browser: ${name} imports no lib file by its source name`, [...text.matchAll(/from "\.\/([^"]+)"/g)].map((m) => m[1]).filter((f) => f.endsWith(".mjs") && !(f in BROWSER_MODULES)).join(), ".mjs");
1981+
}
1982+
const served = new Set([...Object.keys(BROWSER_MODULES), ...nodeFs.readdirSync(publicDir)]);
1983+
for (const [page, mods] of Object.entries(PAGE_MODULES)) for (const m of mods) eq(`browser: ${page} preloads ${m}, which is served`, served.has(m), true);
1984+
}
1985+
1986+
/* strict flags; the shortlist's esc copy (#236) --------------------------- */
1987+
{
1988+
const { readArgs } = await import("./cli.mjs");
1989+
const errOf = (f) => { try { f(); return ""; } catch (e) { return e.message; } };
1990+
eq("cli: known flags read", readArgs(["--report", "r.md", "--clean"], { report: { type: "string" }, clean: { type: "boolean" } }).values.report, "r.md");
1991+
has("cli: an unknown flag is refused", errOf(() => readArgs(["--reprot", "r.md"], { report: { type: "string" } })), "Unknown option '--reprot'");
1992+
has("cli: a value flag with no value is refused", errOf(() => readArgs(["--report"], { report: { type: "string" } })), "argument missing");
1993+
has("cli: positionals refused unless allowed", errOf(() => readArgs(["2d"], {})), "Unexpected argument");
1994+
eq("cli: positionals when allowed", readArgs(["2d", "x"], {}, { positionals: true }).positionals.join(), "2d,x");
1995+
const { thumbsOptions } = await import("../thumbs.mjs");
1996+
const t = thumbsOptions(["--only", "a,b", "--limit", "3", "--dry-run"]);
1997+
eq("thumbs flags: parsed", `${[...t.only].join()}|${t.limit}|${t.dryRun}|${t.force}`, "a,b|3|true|false");
1998+
eq("thumbs flags: no limit is unlimited", thumbsOptions([]).limit, Infinity);
1999+
has("thumbs flags: a limit must be a whole number", errOf(() => thumbsOptions(["--limit", "x"])), "--limit needs a whole number");
2000+
has("thumbs flags: a limit needs a value", errOf(() => thumbsOptions(["--limit"])), "argument missing");
2001+
2002+
const { esc } = await import("./shared.mjs");
2003+
const short = nodeFs.readFileSync(new URL("../public/shortlist.js", import.meta.url), "utf8");
2004+
const body = short.match(/function escapeHtml\(str\) \{([\s\S]*?)\n\}/)[1];
2005+
const escapeHtml = new Function("str", body);
2006+
const sample = `<a href="x" title='y'>Tom & "Jerry"</a>`;
2007+
eq("shortlist's escapeHtml matches shared esc", escapeHtml(sample), esc(sample));
2008+
}
2009+
19642010
/* lint: unused imports (#230) --------------------------------------------- */
19652011
{
19662012
const { unusedImports, scriptFiles } = await import("../lint.mjs");

‎site/lib/shared.mjs‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -278,6 +278,18 @@ export const FONT_FILES = ["fonts/public-sans.woff2", "fonts/ibm-plex-mono-400.w
278278
* them in parallel instead of discovering each import one round trip later.
279279
* lib.test.mjs walks the real import graph and fails if a list drifts.
280280
*/
281+
/**
282+
* The lib modules the browser loads, output name in site/dist -> source in
283+
* site/lib. build.mjs copies exactly these, and lib.test.mjs checks that none
284+
* of them (or any site/public script) imports from node:.
285+
*/
286+
export const BROWSER_MODULES = {
287+
"owes.js": "owes.mjs", // the shortlist's CREDITS file, same code as the stack pages
288+
"search.js": "search.mjs", // the catalog search and the 404 page's guesses
289+
"cards.mjs": "cards.mjs", // the entry card template, for app.js and the category pages
290+
"shared.mjs": "shared.mjs",
291+
};
292+
281293
export const PAGE_MODULES = {
282294
home: ["app.js", "search.js", "cards.mjs", "shared.mjs", "views.js", "shortlist.js", "owes.js"],
283295
entry: ["shortlist.js", "owes.js"],

‎site/lint.mjs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import { execFileSync } from "node:child_process";
99
import fs from "node:fs";
1010
import path from "node:path";
1111
import { fileURLToPath } from "node:url";
12+
import { cliArgs } from "./lib/cli.mjs";
1213

1314
const __dirname = path.dirname(fileURLToPath(import.meta.url));
1415
const ROOT = path.resolve(__dirname, "..");
@@ -63,6 +64,7 @@ export function unusedImports(text) {
6364
}
6465

6566
function main() {
67+
cliArgs({}, "node site/lint.mjs");
6668
const errors = [];
6769
const files = scriptFiles();
6870
for (const file of files) {

‎site/new-entry.mjs‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import path from "node:path";
1717
import { fileURLToPath } from "node:url";
1818
import { entryFromIssue, newEntryProblem, newEntryText, parseIssueForm } from "./lib/scaffold.mjs";
1919
import { slugOf } from "./lib/search.mjs";
20+
import { cliArgs } from "./lib/cli.mjs";
2021

2122
const __dirname = path.dirname(fileURLToPath(import.meta.url));
2223
const ROOT = path.resolve(__dirname, "..");
@@ -27,10 +28,8 @@ function fail(msg) {
2728
process.exit(1);
2829
}
2930

30-
function flag(name) {
31-
const i = process.argv.indexOf(name);
32-
return i === -1 ? null : process.argv[i + 1] || "";
33-
}
31+
const USAGE = "node site/new-entry.mjs <category> <id> | --from-issue <number> [--id <id>]";
32+
const { values: opts, positionals } = cliArgs({ "from-issue": { type: "string" }, id: { type: "string" } }, USAGE, { positionals: true });
3433

3534
const config = JSON.parse(fs.readFileSync(path.join(__dirname, "config.json"), "utf8"));
3635
const today = new Date().toISOString().slice(0, 10);
@@ -45,7 +44,7 @@ let text;
4544
let fromIssue = null;
4645
const warnings = [];
4746

48-
const issueArg = flag("--from-issue");
47+
const issueArg = opts["from-issue"] ?? null;
4948
if (issueArg !== null) {
5049
if (!/^\d+$/.test(issueArg)) fail("usage: node site/new-entry.mjs --from-issue <number> [--id <id>]");
5150
const repo = String(config.site?.repo || "").replace(/^https:\/\/github\.com\//, "").replace(/\/+$/, "");
@@ -59,16 +58,17 @@ if (issueArg !== null) {
5958
const form = parseIssueForm(issue.body);
6059
if (!form["Publisher URL"] || !form["Category"]) fail(`issue #${issue.number} is not a "New source" form (no Publisher URL or Category answer)`);
6160
category = form["Category"];
62-
id = flag("--id") || slugOf(form["Name"] || "");
61+
id = opts.id || slugOf(form["Name"] || "");
6362
fromIssue = issue.number;
6463
const vocab = JSON.parse(fs.readFileSync(path.join(__dirname, "license-vocabulary.json"), "utf8"));
6564
const problem = newEntryProblem({ category, id, categories: Object.keys(config.categories || {}), taken: takenBy(id) });
66-
if (problem) fail(`${problem}${flag("--id") ? "" : " (pass --id <id> to choose another)"}`);
65+
if (problem) fail(`${problem}${opts.id ? "" : " (pass --id <id> to choose another)"}`);
6766
const draft = entryFromIssue(template, form, { id, issue: issue.number, today, vocab });
6867
text = draft.text;
6968
warnings.push(...draft.warnings);
7069
} else {
71-
[category, id] = process.argv.slice(2);
70+
if (opts.id !== undefined) fail(`--id goes with --from-issue; usage: ${USAGE}`);
71+
[category, id] = positionals;
7272
const problem = newEntryProblem({ category, id, categories: Object.keys(config.categories || {}), taken: takenBy(id) });
7373
if (problem) fail(problem);
7474
text = newEntryText(template, { id, category, today });

‎site/pr-diff.mjs‎

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -14,32 +14,30 @@ import { execFileSync } from "node:child_process";
1414
import fs from "node:fs";
1515
import path from "node:path";
1616
import { fileURLToPath } from "node:url";
17+
import { cliArgs, readArgs } from "./lib/cli.mjs";
1718
import { changedEntries, diffRows, licenceDiffMarkdown } from "./lib/licence-diff.mjs";
1819

1920
const __dirname = path.dirname(fileURLToPath(import.meta.url));
2021
const ROOT = path.resolve(__dirname, "..");
2122

22-
/** The --base value, or null when it is missing or not a commit sha. */
23-
export function baseArg(argv) {
24-
const i = argv.indexOf("--base");
25-
const base = i === -1 ? null : argv[i + 1] || null;
26-
return base && /^[0-9a-f]{7,40}$/i.test(base) ? base : null;
27-
}
23+
const USAGE = "node site/pr-diff.mjs --base <commit sha> [--out <file>]";
2824

29-
function arg(name) {
30-
const i = process.argv.indexOf(name);
31-
return i === -1 ? null : process.argv[i + 1] || null;
25+
/** The --base value, or null when it is missing or not a commit sha. Throws on an unknown flag. */
26+
export function baseArg(args) {
27+
const base = readArgs(args, { base: { type: "string" }, out: { type: "string" } }).values.base;
28+
return base && /^[0-9a-f]{7,40}$/i.test(base) ? base : null;
3229
}
3330

3431
const git = (args) => execFileSync("git", args, { cwd: ROOT, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
3532

3633
function main() {
37-
const base = baseArg(process.argv);
34+
const { values: flags } = cliArgs({ base: { type: "string" }, out: { type: "string" } }, USAGE);
35+
const base = baseArg(process.argv.slice(2));
3836
if (!base) {
39-
console.error("usage: node site/pr-diff.mjs --base <commit sha> [--out <file>]");
37+
console.error(`usage: ${USAGE}`);
4038
process.exit(2);
4139
}
42-
const out = arg("--out");
40+
const out = flags.out ?? null;
4341
// Renames are reported as a removal and an addition, which shows both ids.
4442
const changes = changedEntries(git(["diff", "--no-renames", "--name-status", "-z", base, "HEAD", "--", "catalog/"]));
4543
const rows = diffRows(changes, {

0 commit comments

Comments
 (0)