package file→ .shtukbase/packages/code-pragmatic/checks/import_cycles.ts
checks/import_cycles.ts
129 lines, 5.0 KB.
- // PRG-R02 (Hunt & Thomas, orthogonality). Files that import each other in a ring: a change in one ripples
- // through all of them. TypeScript/JavaScript: relative imports (`import … from './x'`, `export … from`,
- // `require('./x')`, `import('./x')`), `import type` skipped. Python: top-level `import`/`from … import` of
- // modules among the files read (imports inside functions are lazy and skipped). Rust is not read: Cargo
- // already forbids cycles between crates, and `use` between modules of one crate is not a load order.
- import { posix } from 'node:path';
- import { type CheckDef, type Finding, runCheck } from '../../code-lib/checks/lib/run.ts';
- import type { Source } from '../../code-lib/checks/lib/scan.ts';
- import { imports } from '../../code-lib/checks/lib/units.ts';
- const TS_EXT = ['', '.ts', '.tsx', '.mts', '.js', '.jsx', '.mjs', '.cjs', '/index.ts', '/index.tsx', '/index.js', '/index.mjs'];
- function tsTarget(from: string, spec: string, known: Set<string>): string | null {
- if (!spec.startsWith('.')) return null;
- const base = posix.normalize(posix.join(posix.dirname(from), spec));
- const stems = [base, base.replace(/\.(js|mjs|cjs|jsx)$/, '')];
- for (const st of stems) for (const e of TS_EXT) if (known.has(st + e)) return st + e;
- return null;
- }
- function pyTarget(from: string, spec: string, level: number, names: string[], known: Set<string>): string[] {
- const mod = (dir: string, dotted: string): string | null => {
- const p = posix.normalize(posix.join(dir, ...dotted.split('.').filter(Boolean)));
- if (known.has(p + '.py')) return p + '.py';
- if (known.has(p + '/__init__.py')) return p + '/__init__.py';
- return null;
- };
- const out: string[] = [];
- let dirs: string[];
- if (level > 0) {
- let d = posix.dirname(from);
- for (let k = 1; k < level; k++) d = posix.dirname(d);
- dirs = [d];
- } else {
- // absolute: from every folder above the file (the package root is one of them)
- dirs = [];
- let d = posix.dirname(from);
- for (;;) {
- dirs.push(d);
- const up = posix.dirname(d);
- if (up === d) break;
- d = up;
- }
- }
- for (const d of dirs) {
- const m = mod(d, spec);
- // `from . import x` / `from pkg import mod`: the names may be modules themselves
- const subs = names.map((n) => mod(d, spec ? `${spec}.${n}` : n)).filter((x): x is string => !!x);
- if (subs.length) out.push(...subs);
- else if (m) out.push(m);
- if (m || subs.length) break;
- }
- return out;
- }
- /** Strongly connected components (Tarjan) of size > 1, or a file importing itself. */
- function rings(graph: Map<string, Set<string>>): string[][] {
- let index = 0;
- const idx = new Map<string, number>();
- const low = new Map<string, number>();
- const stack: string[] = [];
- const on = new Set<string>();
- const out: string[][] = [];
- const strong = (v: string) => {
- idx.set(v, index);
- low.set(v, index++);
- stack.push(v);
- on.add(v);
- for (const w of graph.get(v) ?? []) {
- if (!idx.has(w)) {
- strong(w);
- low.set(v, Math.min(low.get(v)!, low.get(w)!));
- } else if (on.has(w)) low.set(v, Math.min(low.get(v)!, idx.get(w)!));
- }
- if (low.get(v) === idx.get(v)) {
- const comp: string[] = [];
- let w: string;
- do {
- w = stack.pop()!;
- on.delete(w);
- comp.push(w);
- } while (w !== v);
- if (comp.length > 1 || graph.get(v)?.has(v)) out.push(comp.sort());
- }
- };
- for (const v of [...graph.keys()].sort()) if (!idx.has(v)) strong(v);
- return out;
- }
- export function graphOf(srcs: Source[]): { graph: Map<string, Set<string>>; at: Map<string, number> } {
- const known = new Set(srcs.map((s) => s.rel));
- const graph = new Map<string, Set<string>>();
- const at = new Map<string, number>(); // "a->b" -> line of the import in a
- for (const s of srcs) {
- if (s.lang === 'rs') continue;
- const edges = new Set<string>();
- for (const im of imports(s)) {
- if (im.typeOnly || !im.topLevel) continue;
- const ts = s.lang === 'ts' ? [tsTarget(s.rel, im.spec, known)].filter((x): x is string => !!x) : pyTarget(s.rel, im.spec, im.level, im.names, known);
- for (const t of ts) {
- if (t === s.rel && s.lang === 'py' && t.endsWith('__init__.py')) continue;
- edges.add(t);
- if (!at.has(`${s.rel}->${t}`)) at.set(`${s.rel}->${t}`, im.line);
- }
- }
- graph.set(s.rel, edges);
- }
- return { graph, at };
- }
- export const CHECK: CheckDef = {
- pkg: 'code-pragmatic',
- rule: 'PRG-R02',
- name: 'import-cycles',
- defaults: {},
- scan(srcs) {
- const { graph, at } = graphOf(srcs);
- const out: Finding[] = [];
- for (const ring of rings(graph)) {
- const a = ring[0];
- const next = ring.find((b) => graph.get(a)?.has(b)) ?? a;
- const shown = ring.length > 6 ? [...ring.slice(0, 6), `… ${ring.length - 6} more`] : ring;
- out.push({ rel: a, line: at.get(`${a}->${next}`) ?? 1, msg: `an import cycle of ${ring.length} files: ${shown.join(', ')}: move the common part into a separate module so that dependencies go one way` });
- }
- return out;
- },
- };
- if (import.meta.main) runCheck(CHECK);