|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Remove lower-case built-in generics imported from `typing`. |
| 4 | +""" |
| 5 | + |
| 6 | +from __future__ import annotations |
| 7 | + |
| 8 | +import argparse |
| 9 | +import sys |
| 10 | +from pathlib import Path |
| 11 | +from typing import Iterable, Iterator, Sequence |
| 12 | + |
| 13 | + |
| 14 | +try: |
| 15 | + import libcst as cst |
| 16 | +except ImportError as exc: # pragma: no cover - dependency guard |
| 17 | + raise SystemExit("This script requires `libcst`. Install it via `pip install libcst` and retry.") from exc |
| 18 | + |
| 19 | + |
| 20 | +BUILTIN_TYPING_NAMES = frozenset({"callable", "dict", "frozenset", "list", "set", "tuple", "type"}) |
| 21 | + |
| 22 | + |
| 23 | +class TypingBuiltinImportRemover(cst.CSTTransformer): |
| 24 | + def __init__(self) -> None: |
| 25 | + self.changed = False |
| 26 | + self.removed: list[str] = [] |
| 27 | + self.warnings: list[str] = [] |
| 28 | + |
| 29 | + def leave_ImportFrom(self, original_node: cst.ImportFrom, updated_node: cst.ImportFrom) -> cst.BaseStatement: |
| 30 | + module_name = self._module_name(updated_node.module) |
| 31 | + if module_name != "typing": |
| 32 | + return updated_node |
| 33 | + |
| 34 | + names = updated_node.names |
| 35 | + if isinstance(names, cst.ImportStar): |
| 36 | + self.warnings.append("encountered `from typing import *` (skipped)") |
| 37 | + return updated_node |
| 38 | + |
| 39 | + new_aliases = [] |
| 40 | + removed_here: list[str] = [] |
| 41 | + for alias in names: |
| 42 | + if isinstance(alias, cst.ImportStar): |
| 43 | + self.warnings.append("encountered `from typing import *` (skipped)") |
| 44 | + return updated_node |
| 45 | + if not isinstance(alias.name, cst.Name): |
| 46 | + new_aliases.append(alias) |
| 47 | + continue |
| 48 | + imported_name = alias.name.value |
| 49 | + if imported_name in BUILTIN_TYPING_NAMES: |
| 50 | + removed_here.append(imported_name) |
| 51 | + continue |
| 52 | + new_aliases.append(alias) |
| 53 | + |
| 54 | + if not removed_here: |
| 55 | + return updated_node |
| 56 | + |
| 57 | + self.changed = True |
| 58 | + self.removed.extend(removed_here) |
| 59 | + |
| 60 | + if not new_aliases: |
| 61 | + return cst.RemoveFromParent() |
| 62 | + # Ensure trailing commas are removed. |
| 63 | + formatted_aliases = [] |
| 64 | + for alias in new_aliases: |
| 65 | + if alias.comma is not None and alias is new_aliases[-1]: |
| 66 | + formatted_aliases.append(alias.with_changes(comma=None)) |
| 67 | + else: |
| 68 | + formatted_aliases.append(alias) |
| 69 | + |
| 70 | + return updated_node.with_changes(names=tuple(formatted_aliases)) |
| 71 | + |
| 72 | + def _module_name(self, node: cst.BaseExpression | None) -> str | None: |
| 73 | + if node is None: |
| 74 | + return None |
| 75 | + if isinstance(node, cst.Name): |
| 76 | + return node.value |
| 77 | + if isinstance(node, cst.Attribute): |
| 78 | + prefix = self._module_name(node.value) |
| 79 | + if prefix is None: |
| 80 | + return node.attr.value |
| 81 | + return f"{prefix}.{node.attr.value}" |
| 82 | + return None |
| 83 | + |
| 84 | + |
| 85 | +def iter_python_files(paths: Iterable[Path]) -> Iterator[Path]: |
| 86 | + for path in paths: |
| 87 | + if path.is_dir(): |
| 88 | + yield from (p for p in path.rglob("*.py") if not p.name.startswith(".")) |
| 89 | + yield from (p for p in path.rglob("*.pyi") if not p.name.startswith(".")) |
| 90 | + elif path.suffix in {".py", ".pyi"}: |
| 91 | + yield path |
| 92 | + |
| 93 | + |
| 94 | +def process_file(path: Path, dry_run: bool) -> tuple[bool, TypingBuiltinImportRemover]: |
| 95 | + source = path.read_text(encoding="utf-8") |
| 96 | + module = cst.parse_module(source) |
| 97 | + transformer = TypingBuiltinImportRemover() |
| 98 | + updated = module.visit(transformer) |
| 99 | + |
| 100 | + if not transformer.changed or source == updated.code: |
| 101 | + return False, transformer |
| 102 | + |
| 103 | + if not dry_run: |
| 104 | + path.write_text(updated.code, encoding="utf-8") |
| 105 | + return True, transformer |
| 106 | + |
| 107 | + |
| 108 | +def main(argv: Sequence[str] | None = None) -> int: |
| 109 | + parser = argparse.ArgumentParser(description="Remove lower-case built-in generics imported from typing.") |
| 110 | + parser.add_argument( |
| 111 | + "paths", |
| 112 | + nargs="*", |
| 113 | + type=Path, |
| 114 | + default=[Path("src")], |
| 115 | + help="Files or directories to rewrite (default: src).", |
| 116 | + ) |
| 117 | + parser.add_argument( |
| 118 | + "--dry-run", |
| 119 | + action="store_true", |
| 120 | + help="Only report files that would change without writing them.", |
| 121 | + ) |
| 122 | + args = parser.parse_args(argv) |
| 123 | + |
| 124 | + files = sorted(set(iter_python_files(args.paths))) |
| 125 | + if not files: |
| 126 | + print("No Python files matched the provided paths.", file=sys.stderr) |
| 127 | + return 1 |
| 128 | + |
| 129 | + changed_any = False |
| 130 | + for path in files: |
| 131 | + changed, transformer = process_file(path, dry_run=args.dry_run) |
| 132 | + if changed: |
| 133 | + changed_any = True |
| 134 | + action = "Would update" if args.dry_run else "Updated" |
| 135 | + removed = ", ".join(sorted(set(transformer.removed))) |
| 136 | + print(f"{action}: {path} (removed typing imports: {removed})") |
| 137 | + for warning in transformer.warnings: |
| 138 | + print(f"Warning: {path}: {warning}", file=sys.stderr) |
| 139 | + |
| 140 | + if not changed_any: |
| 141 | + print("No changes needed.") |
| 142 | + return 0 |
| 143 | + |
| 144 | + |
| 145 | +if __name__ == "__main__": |
| 146 | + raise SystemExit(main()) |
0 commit comments