160 lines
5.1 KiB
Python
160 lines
5.1 KiB
Python
"""Static, offline handler and runner call checks for PLoop's Python source."""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import ast
|
||
from dataclasses import dataclass
|
||
from pathlib import Path
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class Violation:
|
||
path: Path
|
||
line: int
|
||
rule_id: str
|
||
message: str
|
||
remediation: str
|
||
|
||
def render(self) -> str:
|
||
return (
|
||
f"{self.path.as_posix()}:{self.line}: {self.rule_id} {self.message}"
|
||
f";{self.remediation}"
|
||
)
|
||
|
||
|
||
def main() -> int:
|
||
arguments = _parser().parse_args()
|
||
violations = check_tree(arguments.root)
|
||
print(f"violations={len(violations)}")
|
||
for violation in violations:
|
||
print(violation.render())
|
||
return 1 if violations else 0
|
||
|
||
|
||
def check_tree(root: Path) -> tuple[Violation, ...]:
|
||
resolved_root = root.resolve()
|
||
violations: list[Violation] = []
|
||
for path in sorted(resolved_root.rglob("*.py")):
|
||
relative_path = path.relative_to(resolved_root)
|
||
try:
|
||
tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(relative_path))
|
||
except SyntaxError as error:
|
||
violations.append(
|
||
Violation(
|
||
relative_path,
|
||
error.lineno or 1,
|
||
"PARSE001",
|
||
"Python 源文件无法解析",
|
||
"修正语法后重新运行检查",
|
||
)
|
||
)
|
||
continue
|
||
violations.extend(_check_module(relative_path, tree))
|
||
return tuple(violations)
|
||
|
||
|
||
def _parser() -> argparse.ArgumentParser:
|
||
parser = argparse.ArgumentParser(
|
||
description="Check PLoop API, worker, and re-evaluate call boundaries."
|
||
)
|
||
parser.add_argument("root", type=Path)
|
||
return parser
|
||
|
||
|
||
def _check_module(path: Path, tree: ast.Module) -> tuple[Violation, ...]:
|
||
aliases = _aliases(tree)
|
||
violations: list[Violation] = []
|
||
if "re_evaluate" in path.stem:
|
||
for node in ast.walk(tree):
|
||
if isinstance(node, (ast.Import, ast.ImportFrom)) and any(
|
||
_is_runner_or_adapter(module) for module in _modules_from_import(node)
|
||
):
|
||
violations.append(
|
||
_violation(
|
||
path,
|
||
node.lineno,
|
||
"CALL001",
|
||
"re-evaluate handler 不得依赖 adapter 或 runner",
|
||
"改为调用 application 的 re-evaluate command",
|
||
)
|
||
)
|
||
if _is_api_or_worker_handler(path):
|
||
for node in ast.walk(tree):
|
||
if isinstance(node, ast.Call) and _is_direct_process_or_redis_call(node.func, aliases):
|
||
violations.append(
|
||
_violation(
|
||
path,
|
||
node.lineno,
|
||
"CALL002",
|
||
"API 或 worker handler 不得直接调用 subprocess 或 Redis",
|
||
"改为调用 application command 或 port",
|
||
)
|
||
)
|
||
return tuple(violations)
|
||
|
||
|
||
def _aliases(tree: ast.Module) -> dict[str, str]:
|
||
aliases: dict[str, str] = {}
|
||
for node in ast.walk(tree):
|
||
if isinstance(node, ast.Import):
|
||
for alias in node.names:
|
||
aliases[alias.asname or alias.name.split(".", 1)[0]] = alias.name
|
||
elif isinstance(node, ast.ImportFrom) and node.module:
|
||
for alias in node.names:
|
||
aliases[alias.asname or alias.name] = f"{node.module}.{alias.name}"
|
||
return aliases
|
||
|
||
|
||
def _modules_from_import(node: ast.Import | ast.ImportFrom) -> tuple[str, ...]:
|
||
if isinstance(node, ast.Import):
|
||
return tuple(alias.name for alias in node.names)
|
||
if node.module is None:
|
||
return ()
|
||
return tuple(f"{node.module}.{alias.name}" for alias in node.names)
|
||
|
||
|
||
def _is_runner_or_adapter(module: str) -> bool:
|
||
parts = module.split(".")
|
||
return "runner" in parts or "adapter" in parts or "adapters" in parts
|
||
|
||
|
||
def _is_api_or_worker_handler(path: Path) -> bool:
|
||
if path.parts[:1] == ("api",):
|
||
return True
|
||
return path.parts[:1] == ("worker",) and (
|
||
path.name == "handler.py" or "handler" in path.parts
|
||
)
|
||
|
||
|
||
def _is_direct_process_or_redis_call(function: ast.expr, aliases: dict[str, str]) -> bool:
|
||
dotted = _resolve_alias(_dotted_name(function), aliases)
|
||
return dotted.split(".", 1)[0] in {"subprocess", "redis"}
|
||
|
||
|
||
def _resolve_alias(dotted: str, aliases: dict[str, str]) -> str:
|
||
if not dotted:
|
||
return dotted
|
||
first, separator, remainder = dotted.partition(".")
|
||
resolved = aliases.get(first, first)
|
||
return f"{resolved}.{remainder}" if separator else resolved
|
||
|
||
|
||
def _dotted_name(node: ast.expr) -> str:
|
||
if isinstance(node, ast.Name):
|
||
return node.id
|
||
if isinstance(node, ast.Attribute):
|
||
parent = _dotted_name(node.value)
|
||
return f"{parent}.{node.attr}" if parent else node.attr
|
||
return ""
|
||
|
||
|
||
def _violation(
|
||
path: Path, line: int, rule_id: str, message: str, remediation: str
|
||
) -> Violation:
|
||
return Violation(path, line, rule_id, message, remediation)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main())
|