|
| 1 | +"""Line-based detection and rewriting of old genslot imports and class names. |
| 2 | +
|
| 3 | +Targets: |
| 4 | +- ``from mellea.stdlib.components.genslot import ...`` → ``genstub`` |
| 5 | +- ``import mellea.stdlib.components.genslot [as ...]`` → ``genstub`` |
| 6 | +- ``from mellea.stdlib.components import genslot [as ...]`` → ``genstub`` |
| 7 | +- ``from .genslot import ...`` (relative imports) → ``genstub`` |
| 8 | +- ``GenerativeSlot`` → ``GenerativeStub`` (and Sync/Async variants) |
| 9 | +""" |
| 10 | + |
| 11 | +from __future__ import annotations |
| 12 | + |
| 13 | +import re |
| 14 | +from dataclasses import dataclass |
| 15 | +from pathlib import Path |
| 16 | + |
| 17 | +# Directories to skip during traversal. |
| 18 | +SKIP_DIRS = {"__pycache__", ".git", ".venv", "node_modules"} |
| 19 | + |
| 20 | +# Ordered longest-first so ``SyncGenerativeSlot`` is replaced before ``GenerativeSlot``. |
| 21 | +_CLASS_RENAMES: list[tuple[str, str]] = [ |
| 22 | + ("AsyncGenerativeSlot", "AsyncGenerativeStub"), |
| 23 | + ("SyncGenerativeSlot", "SyncGenerativeStub"), |
| 24 | + ("GenerativeSlot", "GenerativeStub"), |
| 25 | +] |
| 26 | + |
| 27 | +# --- Module-path patterns --- |
| 28 | + |
| 29 | +# Fully-qualified module path (handles both `from … import` and `import …`). |
| 30 | +_MODULE_OLD = "mellea.stdlib.components.genslot" |
| 31 | +_MODULE_NEW = "mellea.stdlib.components.genstub" |
| 32 | +_MODULE_RE = re.compile(re.escape(_MODULE_OLD)) |
| 33 | + |
| 34 | +# `from mellea.stdlib.components import genslot` (with optional ` as …`). |
| 35 | +_FROM_PARENT_RE = re.compile( |
| 36 | + r"(\bfrom\s+mellea\.stdlib\.components\s+import\s+)" # prefix |
| 37 | + r"(\bgenslot\b)" # the name to replace |
| 38 | +) |
| 39 | + |
| 40 | +# Relative imports: `from .genslot import …` or `from ..components.genslot import …` |
| 41 | +# Matches any leading dots followed by an optional dotted path ending in `.genslot`. |
| 42 | +_RELATIVE_RE = re.compile( |
| 43 | + r"(\bfrom\s+\.[\w.]*?)" # `from .` or `from ..foo.bar` |
| 44 | + r"(\bgenslot\b)" # the segment to replace |
| 45 | +) |
| 46 | + |
| 47 | +# Patterns for old class names — word-boundary aware to avoid false positives. |
| 48 | +_CLASS_RES: list[tuple[re.Pattern[str], str]] = [ |
| 49 | + (re.compile(rf"\b{old}\b"), new) for old, new in _CLASS_RENAMES |
| 50 | +] |
| 51 | + |
| 52 | + |
| 53 | +@dataclass |
| 54 | +class GenStubFixLocation: |
| 55 | + """A single replacement within a file. |
| 56 | +
|
| 57 | + Args: |
| 58 | + filepath: Path to the source file. |
| 59 | + line: One-based line number. |
| 60 | + description: Human-readable description of the replacement. |
| 61 | + """ |
| 62 | + |
| 63 | + filepath: Path |
| 64 | + line: int |
| 65 | + description: str |
| 66 | + |
| 67 | + |
| 68 | +@dataclass |
| 69 | +class GenStubFixResult: |
| 70 | + """Aggregated results across all scanned files. |
| 71 | +
|
| 72 | + Args: |
| 73 | + locations: Individual fix locations. |
| 74 | + total_fixes: Total replacements made (or found in dry-run). |
| 75 | + files_affected: Number of distinct files modified. |
| 76 | + """ |
| 77 | + |
| 78 | + locations: list[GenStubFixLocation] |
| 79 | + total_fixes: int |
| 80 | + files_affected: int |
| 81 | + |
| 82 | + |
| 83 | +def _fix_line(line: str) -> tuple[str, list[str]]: |
| 84 | + """Apply all genslot→genstub replacements to a single line. |
| 85 | +
|
| 86 | + Returns: |
| 87 | + A (new_line, descriptions) tuple. *descriptions* is empty when the |
| 88 | + line was not changed. |
| 89 | + """ |
| 90 | + descriptions: list[str] = [] |
| 91 | + |
| 92 | + # Fully-qualified module path. |
| 93 | + if _MODULE_RE.search(line): |
| 94 | + line = _MODULE_RE.sub(_MODULE_NEW, line) |
| 95 | + descriptions.append(f"{_MODULE_OLD} → {_MODULE_NEW}") |
| 96 | + |
| 97 | + # `from mellea.stdlib.components import genslot` |
| 98 | + if _FROM_PARENT_RE.search(line): |
| 99 | + line = _FROM_PARENT_RE.sub(r"\1genstub", line) |
| 100 | + descriptions.append("import genslot → import genstub") |
| 101 | + |
| 102 | + # Relative imports: `from .genslot import …` |
| 103 | + if _RELATIVE_RE.search(line): |
| 104 | + line = _RELATIVE_RE.sub(r"\1genstub", line) |
| 105 | + descriptions.append(".genslot → .genstub") |
| 106 | + |
| 107 | + for pattern, replacement in _CLASS_RES: |
| 108 | + if pattern.search(line): |
| 109 | + line = pattern.sub(replacement, line) |
| 110 | + old = pattern.pattern.replace(r"\b", "") |
| 111 | + descriptions.append(f"{old} → {replacement}") |
| 112 | + |
| 113 | + return line, descriptions |
| 114 | + |
| 115 | + |
| 116 | +def find_genslot_refs(source: str, filepath: Path) -> list[GenStubFixLocation]: |
| 117 | + """Scan *source* for old genslot references and return their locations. |
| 118 | +
|
| 119 | + Args: |
| 120 | + source: Python source text. |
| 121 | + filepath: Used for the ``filepath`` field in returned locations. |
| 122 | +
|
| 123 | + Returns: |
| 124 | + List of locations that would be changed. |
| 125 | + """ |
| 126 | + locations: list[GenStubFixLocation] = [] |
| 127 | + for lineno, line in enumerate(source.splitlines(), start=1): |
| 128 | + _, descriptions = _fix_line(line) |
| 129 | + for desc in descriptions: |
| 130 | + locations.append( |
| 131 | + GenStubFixLocation(filepath=filepath, line=lineno, description=desc) |
| 132 | + ) |
| 133 | + return locations |
| 134 | + |
| 135 | + |
| 136 | +def fix_genslot_file( |
| 137 | + filepath: Path, *, dry_run: bool = False |
| 138 | +) -> list[GenStubFixLocation]: |
| 139 | + """Fix a single file. |
| 140 | +
|
| 141 | + Args: |
| 142 | + filepath: Path to the Python file to fix. |
| 143 | + dry_run: If ``True``, return locations without modifying the file. |
| 144 | +
|
| 145 | + Returns: |
| 146 | + List of locations found (and optionally fixed). |
| 147 | + """ |
| 148 | + source = filepath.read_text() |
| 149 | + locations = find_genslot_refs(source, filepath) |
| 150 | + |
| 151 | + if not locations or dry_run: |
| 152 | + return locations |
| 153 | + |
| 154 | + new_lines: list[str] = [] |
| 155 | + for line in source.splitlines(keepends=True): |
| 156 | + fixed, _ = _fix_line(line) |
| 157 | + new_lines.append(fixed) |
| 158 | + |
| 159 | + filepath.write_text("".join(new_lines)) |
| 160 | + return locations |
| 161 | + |
| 162 | + |
| 163 | +def fix_genslot_path(path: Path, *, dry_run: bool = False) -> GenStubFixResult: |
| 164 | + """Fix a file or directory recursively. |
| 165 | +
|
| 166 | + Args: |
| 167 | + path: File or directory to process. |
| 168 | + dry_run: If ``True``, report locations without modifying files. |
| 169 | +
|
| 170 | + Returns: |
| 171 | + Aggregated result with all fix locations and summary counts. |
| 172 | + """ |
| 173 | + all_locations: list[GenStubFixLocation] = [] |
| 174 | + files_affected = 0 |
| 175 | + |
| 176 | + if path.is_file(): |
| 177 | + files = [path] |
| 178 | + else: |
| 179 | + files = sorted(path.rglob("*.py")) |
| 180 | + |
| 181 | + for f in files: |
| 182 | + parts = f.relative_to(path).parts if path.is_dir() else () |
| 183 | + if any(part in SKIP_DIRS for part in parts): |
| 184 | + continue |
| 185 | + |
| 186 | + locs = fix_genslot_file(f, dry_run=dry_run) |
| 187 | + if locs: |
| 188 | + all_locations.extend(locs) |
| 189 | + files_affected += 1 |
| 190 | + |
| 191 | + return GenStubFixResult( |
| 192 | + locations=all_locations, |
| 193 | + total_fixes=len(all_locations), |
| 194 | + files_affected=files_affected, |
| 195 | + ) |
0 commit comments