包文件→ .shtukbase/packages/code-deep-modules/checks/shallow_modules.ts
checks/shallow_modules.ts
36 行, 1.7 KB.
文件按包中的原样显示:代码及其注释不做翻译。
- // DM-R01 (Ousterhout, deep modules). A file that exports many functions and holds little code behind them:
- // at least `minExports` exported functions and fewer than `minDepth` lines of code per exported function.
- // Exported: TypeScript `export function` / `export const f = (…) =>`, Python top-level `def` without `_`
- // (or the names in `__all__`), Rust `pub fn` (`pub(crate)` is not exported).
- import { type CheckDef, num, runCheck } from '../../code-lib/checks/lib/run.ts';
- import { codeLines } from '../../code-lib/checks/lib/scan.ts';
- import { functions } from '../../code-lib/checks/lib/units.ts';
- export const CHECK: CheckDef = {
- pkg: 'code-deep-modules',
- rule: 'DM-R01',
- name: 'shallow-modules',
- defaults: { minExports: 6, minDepth: 8 },
- scan(srcs, set) {
- const minExports = num(set.minExports, 6);
- const minDepth = num(set.minDepth, 8);
- const out = [];
- for (const s of srcs) {
- let exported = functions(s).filter((f) => f.exported);
- if (s.lang === 'py') {
- const all = /^__all__\s*=\s*[[(]([^\])]*)/m.exec(s.raw);
- if (all) {
- const names = new Set((all[1].match(/['"](\w+)['"]/g) ?? []).map((x) => x.slice(1, -1)));
- exported = functions(s).filter((f) => f.indent === 0 && names.has(f.name));
- }
- }
- if (exported.length < minExports) continue;
- const depth = codeLines(s) / exported.length;
- if (depth < minDepth)
- out.push({ rel: s.rel, line: 1, msg: `the module is shallow: ${exported.length} public functions, ${depth.toFixed(1)} lines of code per function (threshold ${minDepth}): hide the small functions, give the module fewer and larger entry points` });
- }
- return out;
- },
- };
- if (import.meta.main) runCheck(CHECK);