Files
douyi_guaji_main/tools/find_duplicate_excepts.py
T

76 lines
2.0 KiB
Python

from __future__ import annotations
import ast
import sys
from pathlib import Path
from typing import Iterable
def _iter_py_files(path: Path) -> Iterable[Path]:
if path.is_file():
if path.suffix.lower() == ".py":
yield path
return
for p in path.rglob("*.py"):
if p.is_file():
yield p
def _exc_type_key(exc: ast.expr | None) -> str:
if exc is None:
return "BaseException" # bare except
try:
return ast.unparse(exc)
except Exception:
return type(exc).__name__
class DuplicateExceptVisitor(ast.NodeVisitor):
def __init__(self, file_path: Path) -> None:
self.file_path = file_path
def visit_Try(self, node: ast.Try) -> None:
seen: dict[str, int] = {}
for handler in node.handlers:
key = _exc_type_key(handler.type)
lineno = int(getattr(handler, "lineno", 0) or 0)
if key in seen:
prev = seen[key]
print(
f"{self.file_path}:{lineno}: duplicate except for {key} (previous at line {prev})"
)
else:
seen[key] = lineno
self.generic_visit(node)
def main(argv: list[str] | None = None) -> int:
argv = list(sys.argv[1:] if argv is None else argv)
target = Path(argv[0]) if argv else Path("douyin")
if not target.exists():
print(f"Path not found: {target}")
return 2
exit_code = 0
for py_file in _iter_py_files(target):
try:
source = py_file.read_text(encoding="utf-8")
tree = ast.parse(source)
except (OSError, UnicodeDecodeError) as e:
print(f"{py_file}: read error: {e}")
exit_code = 1
continue
except SyntaxError as e:
print(f"{py_file}:{getattr(e, 'lineno', 0)}: SyntaxError: {e}")
exit_code = 1
continue
DuplicateExceptVisitor(py_file).visit(tree)
return exit_code
if __name__ == "__main__":
raise SystemExit(main())