check_imports.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. """跨层导入检查脚本。用法: python scripts/check_imports.py"""
  2. import sys
  3. import io
  4. from pathlib import Path
  5. # Windows 控制台编码兼容
  6. sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
  7. ROOT = Path(__file__).parent.parent
  8. violations = 0
  9. RULES = [
  10. {
  11. "name": "views/ 禁止直接导入 foundation/database/",
  12. "check_dirs": ["views"],
  13. "forbidden": ["foundation.database"],
  14. },
  15. {
  16. "name": "reviewers/ 禁止直接导入 foundation/database/",
  17. "check_dirs": [
  18. "core/construction_review/component/reviewers",
  19. "core/construction_review/component/doc_worker",
  20. ],
  21. "forbidden": ["foundation.database"],
  22. },
  23. ]
  24. for rule in RULES:
  25. print(f"\n检查: {rule['name']}")
  26. for check_dir in rule["check_dirs"]:
  27. full_dir = ROOT / check_dir
  28. if not full_dir.exists():
  29. print(f" 跳过(目录不存在): {check_dir}")
  30. continue
  31. for py_file in full_dir.rglob("*.py"):
  32. try:
  33. content = py_file.read_text(encoding="utf-8")
  34. except Exception:
  35. continue
  36. for pattern in rule["forbidden"]:
  37. import_line = f"from {pattern}"
  38. if import_line in content:
  39. print(f" ❌ {py_file.relative_to(ROOT)}")
  40. violations += 1
  41. if violations:
  42. print(f"\n共发现 {violations} 处跨层导入违规")
  43. sys.exit(1)
  44. else:
  45. print("\n跨层导入检查通过")