|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import ast |
| 4 | +import sys |
| 5 | +from pathlib import Path |
| 6 | + |
| 7 | + |
| 8 | +def check_pep_604(tree: ast.AST, path: Path) -> list[str]: |
| 9 | + errors = [] |
| 10 | + |
| 11 | + class UnionFinder(ast.NodeVisitor): |
| 12 | + def visit_Subscript(self, node: ast.Subscript) -> None: |
| 13 | + if ( |
| 14 | + isinstance(node.value, ast.Name) |
| 15 | + and "Union" in node.value.id.split(".") |
| 16 | + and isinstance(node.slice, ast.Tuple) |
| 17 | + ): |
| 18 | + new_syntax = " | ".join(ast.unparse(x) for x in node.slice.elts) |
| 19 | + errors.append( |
| 20 | + (f"{path}:{node.lineno}: Use PEP 604 syntax for Unions, e.g. `{new_syntax}`") |
| 21 | + ) |
| 22 | + |
| 23 | + # This doesn't check type aliases (or type var bounds, etc), since those are not |
| 24 | + # currently supported |
| 25 | + class AnnotationFinder(ast.NodeVisitor): |
| 26 | + def visit_AnnAssign(self, node: ast.AnnAssign) -> None: |
| 27 | + UnionFinder().visit(node.annotation) |
| 28 | + |
| 29 | + def visit_arg(self, node: ast.arg) -> None: |
| 30 | + if node.annotation is not None: |
| 31 | + UnionFinder().visit(node.annotation) |
| 32 | + |
| 33 | + AnnotationFinder().visit(tree) |
| 34 | + return errors |
| 35 | + |
| 36 | + |
| 37 | +def main() -> None: |
| 38 | + errors = [] |
| 39 | + for path in Path(".").glob("**/*.pyi"): |
| 40 | + if "@python2" in path.parts: |
| 41 | + continue |
| 42 | + if "stubs/protobuf/google/protobuf" in str(path): # TODO: fix protobuf stubs |
| 43 | + continue |
| 44 | + |
| 45 | + with open(path) as f: |
| 46 | + tree = ast.parse(f.read()) |
| 47 | + errors.extend(check_pep_604(tree, path)) |
| 48 | + |
| 49 | + if errors: |
| 50 | + print("\n".join(errors)) |
| 51 | + sys.exit(1) |
| 52 | + |
| 53 | + |
| 54 | +if __name__ == "__main__": |
| 55 | + main() |
0 commit comments