module_boundary_audit.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. r"""模块边界审计(用户令 2026-09-22:按算法/数据接入管理/前端/后端等模块重构,组件化、高内聚低耦合、可插拔)。
  4. ## 它查什么(每条都由 `configs/modules.yaml` 驱动)
  5. | 规则 | 内容 | 退出码 |
  6. |---|---|---|
  7. | R1 结构 | 每个登记模块目录含 `common/<pkg>/__init__.py`、`common/<pkg>/api.py`、`README.md` | 5 |
  8. | R2 边界 | 模块之间**只许经对方 `api.py`**:`app_x/**/*.py` 里 import 另一个 `app_y` 的实现包(非 `api`)即违规 | 6 |
  9. | R3 依赖方向 | 只许 import `allow` 里列出的模块;反向依赖/成环即违规 | 7 |
  10. | R4 公共层纯净 | `app_common/**` 不得 import 任何其它业务模块 | 7 |
  11. | R5 接口可用 | 每个 `api.py` 的 `_TARGETS` 转发目标(既有实现的文件路径)必须真实存在 | 8 |
  12. 另外**统计迁移进度**(不算失败):`src/**`、`scripts/**` 里还有多少件尚未迁进模块目录(P1–P7 的度量)。
  13. ## 用法
  14. python scripts/module_boundary_audit.py # 审计(rc=0 通过)
  15. python scripts/module_boundary_audit.py --brief # 只打结论与进度
  16. 退出码: 0 通过 · 5 结构缺失 · 6 边界违规 · 7 依赖违规 · 8 接口目标缺失
  17. """
  18. from __future__ import annotations
  19. import ast
  20. import pathlib
  21. import re
  22. import sys
  23. ROOT = pathlib.Path(__file__).resolve().parents[1]
  24. sys.path.insert(0, str(ROOT))
  25. from src import paths as P # noqa: E402
  26. def load_registry() -> dict:
  27. import yaml
  28. return yaml.safe_load(P.config('modules.yaml').read_text(encoding='utf-8'))
  29. def module_pkg(name: str) -> str:
  30. return f'{name}_guanlan'
  31. def _imports_of(path: pathlib.Path) -> list[str]:
  32. """→ 该文件里所有 import 的模块名(`import a.b` 与 `from a.b import c` 都算 a.b)。"""
  33. try:
  34. tree = ast.parse(path.read_text(encoding='utf-8'))
  35. except SyntaxError:
  36. return []
  37. out = []
  38. for n in ast.walk(tree):
  39. if isinstance(n, ast.Import):
  40. out += [a.name for a in n.names]
  41. elif isinstance(n, ast.ImportFrom) and n.module:
  42. out.append(n.module)
  43. return out
  44. def audit(verbose: bool = True):
  45. reg = load_registry()
  46. mods = {m['name']: m for m in reg['modules']}
  47. problems: list[tuple[str, str]] = [] # (规则, 说明)
  48. notes: list[str] = []
  49. # R1 结构
  50. for name, m in mods.items():
  51. base = ROOT / name
  52. for rel in (f'common/__init__.py', f'common/{module_pkg(name)}/__init__.py',
  53. f'common/{module_pkg(name)}/api.py', 'README.md'):
  54. if not (base / rel).is_file():
  55. problems.append(('R1', f'{name}/ 缺 {rel}'))
  56. # R5 接口目标存在
  57. for name in mods:
  58. api = ROOT / name / 'common' / module_pkg(name) / 'api.py'
  59. if not api.is_file():
  60. continue
  61. try:
  62. tree = ast.parse(api.read_text(encoding='utf-8'))
  63. except SyntaxError as e:
  64. problems.append(('R1', f'{name}/api.py 语法错误: {e}'))
  65. continue
  66. tg = {}
  67. for n in tree.body:
  68. if isinstance(n, ast.Assign) and getattr(n.targets[0], 'id', '') == '_TARGETS':
  69. try:
  70. tg = ast.literal_eval(n.value)
  71. except Exception: # noqa: BLE001
  72. tg = {}
  73. for pub, target in tg.items():
  74. rel = pathlib.Path(*target.split('.'))
  75. if not ((ROOT / rel).with_suffix('.py').is_file() or (ROOT / rel / '__init__.py').is_file()):
  76. problems.append(('R5', f'{name}.api.{pub} → {target} 的转发目标不存在'))
  77. # R2/R3/R4 边界与依赖
  78. for name, m in mods.items():
  79. allow = set(m.get('allow') or [])
  80. for f in (ROOT / name).rglob('*.py'):
  81. for imp in _imports_of(f):
  82. parts = imp.split('.')
  83. if parts[0] not in mods or parts[0] == name:
  84. continue
  85. other = parts[0]
  86. # 只许 app_<other>.common.app_<other>_guanlan.api
  87. ok_face = (len(parts) >= 4 and parts[1] == 'common'
  88. and parts[3] == 'api' and parts[2] == module_pkg(other))
  89. if not ok_face:
  90. problems.append(('R2', f'{f.relative_to(ROOT).as_posix()} 直接 import {imp}'
  91. f'(应走 {other}.common.{module_pkg(other)}.api)'))
  92. if other not in allow:
  93. problems.append(('R3', f'{f.relative_to(ROOT).as_posix()} import {other}'
  94. f',但 {name} 的 allow 未包含它'))
  95. if name == 'app_common':
  96. problems.append(('R4', f'{f.relative_to(ROOT).as_posix()} 公共层依赖了业务模块 {other}'))
  97. # R6 入口与布局解耦: 安装器必须能在当前布局下解析出包版本
  98. _ver_cands = ['app_common/common/app_common_guanlan/version.py', 'src/version.py']
  99. _found = None
  100. for _c in _ver_cands:
  101. _f = ROOT / _c
  102. if _f.is_file() and re.search(r"^VERSION\s*=\s*'([^']+)'", _f.read_text(encoding='utf-8'), re.M):
  103. _found = (_c, re.search(r"^VERSION\s*=\s*'([^']+)'", _f.read_text(encoding='utf-8'), re.M).group(1))
  104. break
  105. if not _found:
  106. problems.append(('R6', f'当前布局下没有任何候选版本文件含 `VERSION = \'…\'` 字面量(候选: {_ver_cands})'
  107. ' ⇒ install.ps1/install.sh 会读不到包版本'))
  108. else:
  109. _ps1 = (ROOT / 'install.ps1').read_text(encoding='utf-8') if (ROOT / 'install.ps1').is_file() else ''
  110. _sh = (ROOT / 'install.sh').read_text(encoding='utf-8') if (ROOT / 'install.sh').is_file() else ''
  111. if _ps1 and 'app_common' not in _ps1:
  112. problems.append(('R6', 'install.ps1 未包含新布局的候选路径(app_common/...)⇒ 平台件搬家后会读不到版本'))
  113. if _sh and 'app_common' not in _sh:
  114. problems.append(('R6', 'install.sh 未包含新布局的候选路径(app_common/...)⇒ 平台件搬家后会读不到版本'))
  115. # R7 入口读 JSON 必须指定 UTF-8(PS 5.1 默认 ANSI)
  116. _ps1f = ROOT / 'install.ps1'
  117. if _ps1f.is_file():
  118. for _i, _ln in enumerate(_ps1f.read_text(encoding='utf-8').splitlines(), 1):
  119. if _ln.strip().startswith('#'):
  120. continue # 注释里提到 Get-Content/.json 不算
  121. if 'Get-Content' in _ln and '.json' in _ln and '-Encoding' not in _ln:
  122. problems.append(('R7', f'install.ps1:{_i} 读 JSON 未指定 -Encoding UTF8 ⇒ PS 5.1 会按 ANSI 解码中文'))
  123. # 迁移进度(不算失败)
  124. legacy = [p for p in list((ROOT / 'src').rglob('*.py')) + list((ROOT / 'scripts').rglob('*.py'))
  125. if p.is_file()]
  126. notes.append(f'尚未迁入模块目录的既有实现件: src/** {len(list((ROOT / "src").rglob("*.py")))} 件 · '
  127. f'scripts/** {len(list((ROOT / "scripts").rglob("*.py")))} 件(迁移进度按 docs/重构方案_模块化_v0.1.md 的 P1–P7 推进)')
  128. rc = 0
  129. if any(p[0] in ('R1',) for p in problems):
  130. rc = 5
  131. if any(p[0] == 'R2' for p in problems):
  132. rc = rc or 6
  133. if any(p[0] in ('R3', 'R4', 'R6', 'R7') for p in problems):
  134. rc = rc or 7
  135. if any(p[0] == 'R5' for p in problems):
  136. rc = rc or 8
  137. if verbose:
  138. print('模块边界审计 · 登记模块 %d 个(%s)' % (len(mods), '、'.join(mods)))
  139. for n in notes:
  140. print(' [i]', n)
  141. if problems:
  142. for rule, msg in problems:
  143. print(' [X] %s %s' % (rule, msg))
  144. else:
  145. print(' [OK] 结构齐全 · 模块间只经 api 调用 · 依赖方向合规 · 公共层纯净 · 接口目标全在位')
  146. return rc, problems, notes, mods
  147. def main() -> int:
  148. brief = '--brief' in sys.argv
  149. rc, problems, notes, mods = audit(verbose=not brief)
  150. if brief:
  151. print('[OK] module_boundary_audit rc=0(登记 %d 模块)' % len(mods) if rc == 0
  152. else '[X] module_boundary_audit rc=%d(%d 条违规)' % (rc, len(problems)))
  153. return rc
  154. if __name__ == '__main__':
  155. raise SystemExit(main())