包文件→ .shtukbase/packages/code-lib/checks/lib/run.ts
checks/lib/run.ts
61 行, 2.8 KB.
文件按包中的原样显示:代码及其注释不做翻译。
- // Runs one code heuristic as a package check. The working directory is the project root.
- // The norm's page decides how loud the check is: `mode: enforce` — findings fail the check (exit 1);
- // `observe` or `warn` — findings are printed and the check passes (exit 0). A norm that is not active
- // (or whose page is gone) is not checked. Arguments are paths: then only they are read, not the roots.
- // A finding is silenced in place by a comment `code-allow: <check>` (or the rule id) on its line or the line above.
- import { type Settings, type Source, readHead, settings, sources } from './scan.ts';
- export type Finding = { rel: string; line: number; msg: string };
- export type CheckDef = {
- pkg: string;
- rule: string; // DM-R01
- name: string; // the action name, also the word for `code-allow:`
- defaults: Settings;
- scan: (srcs: Source[], set: Settings, root: string) => Finding[];
- };
- export const rulePage = (pkg: string, rule: string) => `norms/rules/${pkg}/${rule}.md`;
- /** Findings of a check without printing: used by `runCheck` and by tests. */
- export function findings(def: CheckDef, root: string, args: string[]): Finding[] {
- const set = settings(root, def.pkg, def.defaults);
- const srcs = sources(root, set, args);
- const byRel = new Map(srcs.map((s) => [s.rel, s]));
- const allow = new RegExp(`code-allow:[^\\n]*\\b(${def.name}|${def.rule})\\b`);
- return def
- .scan(srcs, set, root)
- .filter((f) => {
- const s = byRel.get(f.rel);
- if (!s) return true;
- const lines = s.raw.split('\n');
- return !allow.test(lines[f.line - 1] ?? '') && !allow.test(lines[f.line - 2] ?? '');
- })
- .sort((a, b) => (a.rel === b.rel ? a.line - b.line : a.rel < b.rel ? -1 : 1));
- }
- export function runCheck(def: CheckDef): void {
- const root = process.cwd();
- const args = process.argv.slice(2).filter((a) => !a.startsWith('--'));
- const head = readHead(root, rulePage(def.pkg, def.rule));
- const status = String(head.status ?? '').trim();
- if (!Object.keys(head).length || (status && status !== 'active')) {
- process.exitCode = 0;
- return;
- }
- const mode = String(head.mode ?? 'observe').trim();
- const found = findings(def, root, args);
- for (const f of found) console.log(`${f.rel}:${f.line}: ${f.msg}`);
- if (found.length && mode !== 'enforce')
- console.log(`${def.rule} (mode: ${mode}): ${found.length} findings — the check only warns; to block, set mode: enforce in /${rulePage(def.pkg, def.rule)}`);
- process.exitCode = found.length && mode === 'enforce' ? 1 : 0;
- }
- /** Lines of a function that are code, trimmed, for small body tests. */
- export function compact(text: string): string {
- return text.replace(/\s+/g, ' ').trim();
- }
- export function num(v: unknown, d: number): number {
- const n = Number(v);
- return Number.isFinite(n) && n > 0 ? n : d;
- }