package file→ .shtukbase/packages/code-lib/checks/lib/scan.ts
checks/lib/scan.ts
149 lines, 6.2 KB.
- // Which code the code-* checks read, and with what thresholds.
- // Common settings: the page /norms/code.md of the project (`roots`, `exclude`, `languages`). A package's own
- // settings: /norms/code/<package>.md (thresholds as plain keys, its own `exclude`). A key missing from a page
- // falls back to the default the check passes in. Paths are from the project root; `exclude` takes globs
- // (`**` any folders, `*` any name part) and bare names (`vendor` matches a folder or file of that name anywhere).
- import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs';
- import { posix, relative, resolve, sep } from 'node:path';
- import { parseYaml, splitFrontMatter } from '../../../collections/checks/lib/pages.ts';
- import { type Lang, type Masked, langOf, lineStarts, mask } from './lex.ts';
- export type Settings = Record<string, any>;
- export const COMMON_PAGE = 'norms/code.md';
- export const packagePage = (pkg: string) => `norms/code/${pkg}.md`;
- /** Folders never read: tool caches, builds, dependencies. */
- const ALWAYS_SKIP = ['node_modules', 'target', 'dist', 'build', '__pycache__', '.venv', 'venv', '.shtukbase'];
- export function readHead(root: string, rel: string): Settings {
- const full = posix.join(root, rel);
- if (!existsSync(full)) return {};
- try {
- const head = parseYaml(splitFrontMatter(readFileSync(full, 'utf8'))[0]);
- return head && typeof head === 'object' && !Array.isArray(head) ? head : {};
- } catch {
- return {};
- }
- }
- const list = (v: unknown): string[] =>
- (Array.isArray(v) ? v : v === undefined || v === null || v === '' ? [] : [v]).map((x) => String(x).trim()).filter(Boolean);
- /** The settings of one package: defaults, then the common page, then the package page (later wins). */
- export function settings(root: string, pkg: string, defaults: Settings): Settings {
- const common = readHead(root, COMMON_PAGE);
- const own = readHead(root, packagePage(pkg));
- const out: Settings = { ...defaults };
- for (const [k, v] of Object.entries(own)) if (!['type', 'title', 'description', 'exclude'].includes(k)) out[k] = v;
- out.roots = list(common.roots).length ? list(common.roots) : ['.'];
- out.languages = list(common.languages).length ? list(common.languages) : ['ts', 'py', 'rs'];
- out.exclude = [...list(common.exclude), ...list(own.exclude)];
- out.tests = common.tests === true; // test files are read only when the project says so
- return out;
- }
- export function globRe(glob: string): RegExp {
- let g = glob.replace(/^\.\//, '').replace(/\/+$/, '');
- if (!/[*?/]/.test(g)) return new RegExp(`(^|/)${esc(g)}(/|$)`); // a bare name: any segment
- let re = '';
- for (let k = 0; k < g.length; k++) {
- const c = g[k];
- if (c === '*' && g[k + 1] === '*') {
- if (g[k + 2] === '/') { re += '(?:.*/)?'; k += 2; } else { re += '.*'; k++; }
- } else if (c === '*') re += '[^/]*';
- else if (c === '?') re += '[^/]';
- else re += esc(c);
- }
- return new RegExp(`^${re}(/|$)`);
- }
- const esc = (s: string) => s.replace(/[.+^${}()|[\]\\]/g, '\\$&');
- export function matcher(globs: string[]): (rel: string) => boolean {
- const res = globs.map(globRe);
- return (rel) => res.some((r) => r.test(rel));
- }
- /** A source file, read and masked. `rel` is the path from the project root (posix). */
- export type Source = Masked & { rel: string; lang: Lang; raw: string; starts: number[] };
- const cache = new Map<string, Source>();
- export function load(root: string, rel: string): Source | null {
- const hit = cache.get(rel);
- if (hit) return hit;
- const lang = langOf(rel);
- if (!lang) return null;
- let raw: string;
- try {
- raw = readFileSync(resolve(root, rel), 'utf8');
- } catch {
- return null;
- }
- if (raw.length > 2_000_000) return null; // generated or vendored blobs
- const s: Source = { ...mask(raw, lang), rel, lang, raw, starts: lineStarts(raw) };
- cache.set(rel, s);
- return s;
- }
- const toRel = (root: string, full: string) => relative(root, full).split(sep).join('/') || '.';
- /** The code files to read: the paths given on the command line, or the roots of the settings. */
- export function files(root: string, set: Settings, args: string[] = []): string[] {
- const skip = matcher(set.exclude ?? []);
- const langs = new Set(set.languages ?? ['ts', 'py', 'rs']);
- const out = new Set<string>();
- const seen = new Set<string>();
- const visit = (full: string, explicit: boolean) => {
- let st;
- try {
- st = statSync(full);
- } catch {
- return;
- }
- const rel = toRel(root, full);
- const name = full.split(sep).pop() ?? '';
- if (st.isDirectory()) {
- if (!explicit && (name.startsWith('.') || ALWAYS_SKIP.includes(name) || skip(rel))) return;
- let real: string;
- try {
- real = realpathSync(full);
- } catch {
- return;
- }
- if (seen.has(real)) return;
- seen.add(real);
- for (const e of readdirSync(full).sort()) visit(resolve(full, e), false);
- return;
- }
- const lang = langOf(name);
- if (!lang || !langs.has(lang)) return;
- if (!explicit && (skip(rel) || /\.d\.ts$|\.min\.js$/.test(name) || (!set.tests && isTest(rel)))) return;
- out.add(rel);
- };
- const targets = args.length ? args : set.roots ?? ['.'];
- for (const t of targets) visit(resolve(root, t), args.length > 0);
- return [...out].sort();
- }
- export function sources(root: string, set: Settings, args: string[] = []): Source[] {
- return files(root, set, args).map((f) => load(root, f)).filter((s): s is Source => !!s);
- }
- /** Number of non-blank lines of masked code between two 1-based lines (inclusive): comments and blank lines do not count. */
- export function codeLines(src: Source, from = 1, to = src.starts.length): number {
- let n = 0;
- for (let l = from; l <= to; l++) if (lineText(src, l).trim()) n++;
- return n;
- }
- export function lineText(src: Source, l: number, text = src.code): string {
- const a = src.starts[l - 1] ?? text.length;
- const b = l < src.starts.length ? src.starts[l] - 1 : text.length;
- return text.slice(a, b);
- }
- /** A test file by its name or folder: such files are skipped by checks that judge production code. */
- export function isTest(rel: string): boolean {
- return /(^|\/)(tests?|__tests__|spec)\//.test(rel) || /[._-](test|spec)\.[a-z]+$/.test(rel) || /(^|\/)test_[^/]*\.py$/.test(rel) || /_tests?\.(py|rs)$/.test(rel) || /(^|\/)tests?\.rs$/.test(rel);
- }