|
| 1 | +# Copyright (c) Microsoft Corporation. |
| 2 | +# Licensed under the MIT license. |
| 3 | + |
| 4 | +""" |
| 5 | +Enforce ``.github/instructions/style-guide.instructions.md`` §1: every ``async def`` in |
| 6 | +``pyrit/`` must end with the ``_async`` suffix. |
| 7 | +
|
| 8 | +Mechanism: walk every ``pyrit/**/*.py`` file with ``ast`` and flag every ``AsyncFunctionDef`` |
| 9 | +whose name does not end in ``_async`` and is not exempted via either: |
| 10 | +
|
| 11 | +1. **Hard-coded framework exemptions** (``_FRAMEWORK_EXEMPT_NAMES``) — names whose meaning |
| 12 | + is dictated by an external framework or by the Python data model |
| 13 | + (e.g. ``lifespan`` for FastAPI, ``dispatch`` for Starlette middleware, ``__call__`` |
| 14 | + on Protocol classes). The set is intentionally small; one-off exemptions |
| 15 | + should use the per-line ``# pyrit-async-suffix-exempt`` marker instead. |
| 16 | +
|
| 17 | +2. **Per-line ``# pyrit-async-suffix-exempt`` marker** on any line of the ``async def`` |
| 18 | + header (the marker is scanned across the full signature, which the formatter may |
| 19 | + split across multiple lines). Common reasons: a deprecation shim that intentionally |
| 20 | + keeps the old non-``_async`` name for one release cycle; a one-off external-SDK or |
| 21 | + protocol method name. |
| 22 | +""" |
| 23 | + |
| 24 | +from __future__ import annotations |
| 25 | + |
| 26 | +import ast |
| 27 | +import sys |
| 28 | +from pathlib import Path |
| 29 | + |
| 30 | +# Project layout — anchor everything off the repo root (directory containing pyrit/). |
| 31 | +_REPO_ROOT = Path(__file__).resolve().parent.parent |
| 32 | +_SCAN_ROOTS = ("pyrit",) |
| 33 | + |
| 34 | +# Framework-mandated names: do NOT add to this set for one-off exemptions. |
| 35 | +# Use a per-line ``# pyrit-async-suffix-exempt`` marker instead so each exemption is |
| 36 | +# visible at the violation site. |
| 37 | +_FRAMEWORK_EXEMPT_NAMES: frozenset[str] = frozenset( |
| 38 | + { |
| 39 | + "lifespan", # FastAPI app lifespan context manager |
| 40 | + "dispatch", # Starlette BaseHTTPMiddleware.dispatch override |
| 41 | + "__call__", # Python dunder; Protocol classes commonly define async __call__ |
| 42 | + } |
| 43 | +) |
| 44 | + |
| 45 | +_NOQA_MARKER = "# pyrit-async-suffix-exempt" |
| 46 | + |
| 47 | + |
| 48 | +def _is_violation_name(name: str) -> bool: |
| 49 | + """Return True if ``name`` violates the async-suffix rule.""" |
| 50 | + if name.endswith("_async"): |
| 51 | + return False |
| 52 | + if name.startswith("__a"): |
| 53 | + # Async dunders: __aenter__, __aexit__, __aiter__, __anext__. |
| 54 | + return False |
| 55 | + return name not in _FRAMEWORK_EXEMPT_NAMES |
| 56 | + |
| 57 | + |
| 58 | +def _line_has_noqa(source_lines: list[str], lineno: int) -> bool: |
| 59 | + """Return True if ``source_lines[lineno - 1]`` carries the exempt marker.""" |
| 60 | + if lineno < 1 or lineno > len(source_lines): |
| 61 | + return False |
| 62 | + return _NOQA_MARKER in source_lines[lineno - 1] |
| 63 | + |
| 64 | + |
| 65 | +def _header_has_noqa(source_lines: list[str], node: ast.AsyncFunctionDef) -> bool: |
| 66 | + """Return True if any line of the def header carries the exempt marker. |
| 67 | +
|
| 68 | + The header spans ``node.lineno`` through the line just before the function body |
| 69 | + starts (which is where the formatter may place the marker after splitting a |
| 70 | + long signature across multiple lines). |
| 71 | + """ |
| 72 | + start = node.lineno |
| 73 | + end = node.body[0].lineno - 1 if node.body else start |
| 74 | + return any(_line_has_noqa(source_lines, lineno) for lineno in range(start, max(start, end) + 1)) |
| 75 | + |
| 76 | + |
| 77 | +def _scan_file(path: Path) -> list[tuple[str, int, str]]: |
| 78 | + """Return ``(relative_path, line, name)`` violations in ``path``. |
| 79 | +
|
| 80 | + ``relative_path`` is forward-slash normalized relative to the repo root so that |
| 81 | + violations are reported portably between Windows and Linux checkouts. |
| 82 | + """ |
| 83 | + source = path.read_text(encoding="utf-8") |
| 84 | + try: |
| 85 | + tree = ast.parse(source, filename=str(path)) |
| 86 | + except SyntaxError as exc: |
| 87 | + rel = path.relative_to(_REPO_ROOT).as_posix() |
| 88 | + # Surface the parse failure as a violation so an unparseable file can't |
| 89 | + # silently slip past the check. Other hooks (e.g. ruff) should flag the |
| 90 | + # syntax error too, but we don't rely on their ordering. |
| 91 | + message = f"{exc.msg} (line {exc.lineno})" if exc.lineno is not None else exc.msg |
| 92 | + return [(rel, exc.lineno or 0, f"<SyntaxError: {message}>")] |
| 93 | + source_lines = source.splitlines() |
| 94 | + rel = path.relative_to(_REPO_ROOT).as_posix() |
| 95 | + violations: list[tuple[str, int, str]] = [] |
| 96 | + for node in ast.walk(tree): |
| 97 | + if not isinstance(node, ast.AsyncFunctionDef): |
| 98 | + continue |
| 99 | + if not _is_violation_name(node.name): |
| 100 | + continue |
| 101 | + if _header_has_noqa(source_lines, node): |
| 102 | + continue |
| 103 | + violations.append((rel, node.lineno, node.name)) |
| 104 | + return violations |
| 105 | + |
| 106 | + |
| 107 | +def _scan_repo() -> list[tuple[str, int, str]]: |
| 108 | + """Return all violations across the scanned roots, sorted for determinism.""" |
| 109 | + violations: list[tuple[str, int, str]] = [] |
| 110 | + for root in _SCAN_ROOTS: |
| 111 | + for path in sorted((_REPO_ROOT / root).rglob("*.py")): |
| 112 | + violations.extend(_scan_file(path)) |
| 113 | + return violations |
| 114 | + |
| 115 | + |
| 116 | +def main() -> int: |
| 117 | + violations = _scan_repo() |
| 118 | + if not violations: |
| 119 | + return 0 |
| 120 | + |
| 121 | + print( |
| 122 | + "[ERROR] Async functions are missing the `_async` suffix " |
| 123 | + "(see .github/instructions/style-guide.instructions.md §1):" |
| 124 | + ) |
| 125 | + for path, line, name in violations: |
| 126 | + if name.startswith("<SyntaxError"): |
| 127 | + print(f" {path}:{line}: could not parse file: {name[1:-1]}") |
| 128 | + else: |
| 129 | + print(f" {path}:{line}: async def {name}(...)") |
| 130 | + print("") |
| 131 | + print("Rename each function to end in `_async`, or — if the name is dictated") |
| 132 | + print("by a framework — add `# pyrit-async-suffix-exempt` at the end of the `async def` line.") |
| 133 | + return 1 |
| 134 | + |
| 135 | + |
| 136 | +if __name__ == "__main__": |
| 137 | + sys.exit(main()) |
0 commit comments