unis-oa/backend/scripts/check_globals.py

51 lines
1.7 KiB
Python

"""Flag names read at module or function scope that nothing ever defines.
Catches the `NameError` class of bug that only fires on rarely walked paths,
such as the fresh-install seed branch. Stdlib only, no linter required::
python3 scripts/check_globals.py [dir ...]
"""
from __future__ import annotations
import builtins
import pathlib
import symtable
import sys
SKIP = {"__name__", "__file__", "__doc__", "__package__", "__spec__", "__builtins__"}
def undefined_names(path: pathlib.Path) -> list[str]:
"""Global-scope reads that no module-level binding, import or builtin provides."""
table = symtable.symtable(path.read_text(encoding="utf-8"), str(path), "exec")
known = set(table.get_identifiers()) | set(dir(builtins)) | SKIP
found: set[str] = set()
def walk(node: symtable.SymbolTable) -> None:
for symbol in node.get_symbols():
if symbol.is_global() and not symbol.is_assigned() and symbol.get_name() not in known:
found.add(symbol.get_name())
for child in node.get_children():
walk(child)
walk(table)
return sorted(found)
def main(argv: list[str]) -> int:
roots = [pathlib.Path(a) for a in argv] or [pathlib.Path("app")]
files = sorted(f for root in roots for f in (root.rglob("*.py") if root.is_dir() else [root]))
bad = {str(f): names for f in files if (names := undefined_names(f))}
for name, values in bad.items():
print(f"[FAIL] {name}: 未定义的名字 {', '.join(values)}")
if bad:
print(f"共 {len(bad)} 个文件存在未定义引用")
return 1
print(f"通过:{len(files)} 个文件无未定义引用")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))