ShtukbaseStandard
包文件→ .shtukbase/packages/code-lib/checks/lib/scan.ts

checks/lib/scan.ts

149 行, 6.2 KB.

文件按包中的原样显示:代码及其注释不做翻译。

  1. // Which code the code-* checks read, and with what thresholds.
  2. // Common settings: the page /norms/code.md of the project (`roots`, `exclude`, `languages`). A package's own
  3. // settings: /norms/code/<package>.md (thresholds as plain keys, its own `exclude`). A key missing from a page
  4. // falls back to the default the check passes in. Paths are from the project root; `exclude` takes globs
  5. // (`**` any folders, `*` any name part) and bare names (`vendor` matches a folder or file of that name anywhere).
  6. import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs';
  7. import { posix, relative, resolve, sep } from 'node:path';
  8. import { parseYaml, splitFrontMatter } from '../../../collections/checks/lib/pages.ts';
  9. import { type Lang, type Masked, langOf, lineStarts, mask } from './lex.ts';
  10. export type Settings = Record<string, any>;
  11. export const COMMON_PAGE = 'norms/code.md';
  12. export const packagePage = (pkg: string) => `norms/code/${pkg}.md`;
  13. /** Folders never read: tool caches, builds, dependencies. */
  14. const ALWAYS_SKIP = ['node_modules', 'target', 'dist', 'build', '__pycache__', '.venv', 'venv', '.shtukbase'];
  15. export function readHead(root: string, rel: string): Settings {
  16. const full = posix.join(root, rel);
  17. if (!existsSync(full)) return {};
  18. try {
  19. const head = parseYaml(splitFrontMatter(readFileSync(full, 'utf8'))[0]);
  20. return head && typeof head === 'object' && !Array.isArray(head) ? head : {};
  21. } catch {
  22. return {};
  23. }
  24. }
  25. const list = (v: unknown): string[] =>
  26. (Array.isArray(v) ? v : v === undefined || v === null || v === '' ? [] : [v]).map((x) => String(x).trim()).filter(Boolean);
  27. /** The settings of one package: defaults, then the common page, then the package page (later wins). */
  28. export function settings(root: string, pkg: string, defaults: Settings): Settings {
  29. const common = readHead(root, COMMON_PAGE);
  30. const own = readHead(root, packagePage(pkg));
  31. const out: Settings = { ...defaults };
  32. for (const [k, v] of Object.entries(own)) if (!['type', 'title', 'description', 'exclude'].includes(k)) out[k] = v;
  33. out.roots = list(common.roots).length ? list(common.roots) : ['.'];
  34. out.languages = list(common.languages).length ? list(common.languages) : ['ts', 'py', 'rs'];
  35. out.exclude = [...list(common.exclude), ...list(own.exclude)];
  36. out.tests = common.tests === true; // test files are read only when the project says so
  37. return out;
  38. }
  39. export function globRe(glob: string): RegExp {
  40. let g = glob.replace(/^\.\//, '').replace(/\/+$/, '');
  41. if (!/[*?/]/.test(g)) return new RegExp(`(^|/)${esc(g)}(/|$)`); // a bare name: any segment
  42. let re = '';
  43. for (let k = 0; k < g.length; k++) {
  44. const c = g[k];
  45. if (c === '*' && g[k + 1] === '*') {
  46. if (g[k + 2] === '/') { re += '(?:.*/)?'; k += 2; } else { re += '.*'; k++; }
  47. } else if (c === '*') re += '[^/]*';
  48. else if (c === '?') re += '[^/]';
  49. else re += esc(c);
  50. }
  51. return new RegExp(`^${re}(/|$)`);
  52. }
  53. const esc = (s: string) => s.replace(/[.+^${}()|[\]\\]/g, '\\$&');
  54. export function matcher(globs: string[]): (rel: string) => boolean {
  55. const res = globs.map(globRe);
  56. return (rel) => res.some((r) => r.test(rel));
  57. }
  58. /** A source file, read and masked. `rel` is the path from the project root (posix). */
  59. export type Source = Masked & { rel: string; lang: Lang; raw: string; starts: number[] };
  60. const cache = new Map<string, Source>();
  61. export function load(root: string, rel: string): Source | null {
  62. const hit = cache.get(rel);
  63. if (hit) return hit;
  64. const lang = langOf(rel);
  65. if (!lang) return null;
  66. let raw: string;
  67. try {
  68. raw = readFileSync(resolve(root, rel), 'utf8');
  69. } catch {
  70. return null;
  71. }
  72. if (raw.length > 2_000_000) return null; // generated or vendored blobs
  73. const s: Source = { ...mask(raw, lang), rel, lang, raw, starts: lineStarts(raw) };
  74. cache.set(rel, s);
  75. return s;
  76. }
  77. const toRel = (root: string, full: string) => relative(root, full).split(sep).join('/') || '.';
  78. /** The code files to read: the paths given on the command line, or the roots of the settings. */
  79. export function files(root: string, set: Settings, args: string[] = []): string[] {
  80. const skip = matcher(set.exclude ?? []);
  81. const langs = new Set(set.languages ?? ['ts', 'py', 'rs']);
  82. const out = new Set<string>();
  83. const seen = new Set<string>();
  84. const visit = (full: string, explicit: boolean) => {
  85. let st;
  86. try {
  87. st = statSync(full);
  88. } catch {
  89. return;
  90. }
  91. const rel = toRel(root, full);
  92. const name = full.split(sep).pop() ?? '';
  93. if (st.isDirectory()) {
  94. if (!explicit && (name.startsWith('.') || ALWAYS_SKIP.includes(name) || skip(rel))) return;
  95. let real: string;
  96. try {
  97. real = realpathSync(full);
  98. } catch {
  99. return;
  100. }
  101. if (seen.has(real)) return;
  102. seen.add(real);
  103. for (const e of readdirSync(full).sort()) visit(resolve(full, e), false);
  104. return;
  105. }
  106. const lang = langOf(name);
  107. if (!lang || !langs.has(lang)) return;
  108. if (!explicit && (skip(rel) || /\.d\.ts$|\.min\.js$/.test(name) || (!set.tests && isTest(rel)))) return;
  109. out.add(rel);
  110. };
  111. const targets = args.length ? args : set.roots ?? ['.'];
  112. for (const t of targets) visit(resolve(root, t), args.length > 0);
  113. return [...out].sort();
  114. }
  115. export function sources(root: string, set: Settings, args: string[] = []): Source[] {
  116. return files(root, set, args).map((f) => load(root, f)).filter((s): s is Source => !!s);
  117. }
  118. /** Number of non-blank lines of masked code between two 1-based lines (inclusive): comments and blank lines do not count. */
  119. export function codeLines(src: Source, from = 1, to = src.starts.length): number {
  120. let n = 0;
  121. for (let l = from; l <= to; l++) if (lineText(src, l).trim()) n++;
  122. return n;
  123. }
  124. export function lineText(src: Source, l: number, text = src.code): string {
  125. const a = src.starts[l - 1] ?? text.length;
  126. const b = l < src.starts.length ? src.starts[l] - 1 : text.length;
  127. return text.slice(a, b);
  128. }
  129. /** A test file by its name or folder: such files are skipped by checks that judge production code. */
  130. export function isTest(rel: string): boolean {
  131. 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);
  132. }