ShtukbaseStandard
package file→ .shtukbase/packages/code-pragmatic/checks/import_cycles.ts

checks/import_cycles.ts

129 lines, 5.0 KB.

  1. // PRG-R02 (Hunt & Thomas, orthogonality). Files that import each other in a ring: a change in one ripples
  2. // through all of them. TypeScript/JavaScript: relative imports (`import … from './x'`, `export … from`,
  3. // `require('./x')`, `import('./x')`), `import type` skipped. Python: top-level `import`/`from … import` of
  4. // modules among the files read (imports inside functions are lazy and skipped). Rust is not read: Cargo
  5. // already forbids cycles between crates, and `use` between modules of one crate is not a load order.
  6. import { posix } from 'node:path';
  7. import { type CheckDef, type Finding, runCheck } from '../../code-lib/checks/lib/run.ts';
  8. import type { Source } from '../../code-lib/checks/lib/scan.ts';
  9. import { imports } from '../../code-lib/checks/lib/units.ts';
  10. const TS_EXT = ['', '.ts', '.tsx', '.mts', '.js', '.jsx', '.mjs', '.cjs', '/index.ts', '/index.tsx', '/index.js', '/index.mjs'];
  11. function tsTarget(from: string, spec: string, known: Set<string>): string | null {
  12. if (!spec.startsWith('.')) return null;
  13. const base = posix.normalize(posix.join(posix.dirname(from), spec));
  14. const stems = [base, base.replace(/\.(js|mjs|cjs|jsx)$/, '')];
  15. for (const st of stems) for (const e of TS_EXT) if (known.has(st + e)) return st + e;
  16. return null;
  17. }
  18. function pyTarget(from: string, spec: string, level: number, names: string[], known: Set<string>): string[] {
  19. const mod = (dir: string, dotted: string): string | null => {
  20. const p = posix.normalize(posix.join(dir, ...dotted.split('.').filter(Boolean)));
  21. if (known.has(p + '.py')) return p + '.py';
  22. if (known.has(p + '/__init__.py')) return p + '/__init__.py';
  23. return null;
  24. };
  25. const out: string[] = [];
  26. let dirs: string[];
  27. if (level > 0) {
  28. let d = posix.dirname(from);
  29. for (let k = 1; k < level; k++) d = posix.dirname(d);
  30. dirs = [d];
  31. } else {
  32. // absolute: from every folder above the file (the package root is one of them)
  33. dirs = [];
  34. let d = posix.dirname(from);
  35. for (;;) {
  36. dirs.push(d);
  37. const up = posix.dirname(d);
  38. if (up === d) break;
  39. d = up;
  40. }
  41. }
  42. for (const d of dirs) {
  43. const m = mod(d, spec);
  44. // `from . import x` / `from pkg import mod`: the names may be modules themselves
  45. const subs = names.map((n) => mod(d, spec ? `${spec}.${n}` : n)).filter((x): x is string => !!x);
  46. if (subs.length) out.push(...subs);
  47. else if (m) out.push(m);
  48. if (m || subs.length) break;
  49. }
  50. return out;
  51. }
  52. /** Strongly connected components (Tarjan) of size > 1, or a file importing itself. */
  53. function rings(graph: Map<string, Set<string>>): string[][] {
  54. let index = 0;
  55. const idx = new Map<string, number>();
  56. const low = new Map<string, number>();
  57. const stack: string[] = [];
  58. const on = new Set<string>();
  59. const out: string[][] = [];
  60. const strong = (v: string) => {
  61. idx.set(v, index);
  62. low.set(v, index++);
  63. stack.push(v);
  64. on.add(v);
  65. for (const w of graph.get(v) ?? []) {
  66. if (!idx.has(w)) {
  67. strong(w);
  68. low.set(v, Math.min(low.get(v)!, low.get(w)!));
  69. } else if (on.has(w)) low.set(v, Math.min(low.get(v)!, idx.get(w)!));
  70. }
  71. if (low.get(v) === idx.get(v)) {
  72. const comp: string[] = [];
  73. let w: string;
  74. do {
  75. w = stack.pop()!;
  76. on.delete(w);
  77. comp.push(w);
  78. } while (w !== v);
  79. if (comp.length > 1 || graph.get(v)?.has(v)) out.push(comp.sort());
  80. }
  81. };
  82. for (const v of [...graph.keys()].sort()) if (!idx.has(v)) strong(v);
  83. return out;
  84. }
  85. export function graphOf(srcs: Source[]): { graph: Map<string, Set<string>>; at: Map<string, number> } {
  86. const known = new Set(srcs.map((s) => s.rel));
  87. const graph = new Map<string, Set<string>>();
  88. const at = new Map<string, number>(); // "a->b" -> line of the import in a
  89. for (const s of srcs) {
  90. if (s.lang === 'rs') continue;
  91. const edges = new Set<string>();
  92. for (const im of imports(s)) {
  93. if (im.typeOnly || !im.topLevel) continue;
  94. 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);
  95. for (const t of ts) {
  96. if (t === s.rel && s.lang === 'py' && t.endsWith('__init__.py')) continue;
  97. edges.add(t);
  98. if (!at.has(`${s.rel}->${t}`)) at.set(`${s.rel}->${t}`, im.line);
  99. }
  100. }
  101. graph.set(s.rel, edges);
  102. }
  103. return { graph, at };
  104. }
  105. export const CHECK: CheckDef = {
  106. pkg: 'code-pragmatic',
  107. rule: 'PRG-R02',
  108. name: 'import-cycles',
  109. defaults: {},
  110. scan(srcs) {
  111. const { graph, at } = graphOf(srcs);
  112. const out: Finding[] = [];
  113. for (const ring of rings(graph)) {
  114. const a = ring[0];
  115. const next = ring.find((b) => graph.get(a)?.has(b)) ?? a;
  116. const shown = ring.length > 6 ? [...ring.slice(0, 6), `… ${ring.length - 6} more`] : ring;
  117. 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` });
  118. }
  119. return out;
  120. },
  121. };
  122. if (import.meta.main) runCheck(CHECK);