Skip to content

Commit 8f0c3e3

Browse files
authored
chore: fix codegen to no longer leave unused imports in __init__.py files (#2643)
1 parent e747209 commit 8f0c3e3

1 file changed

Lines changed: 20 additions & 0 deletions

File tree

scripts/sync_client_codegen/codegen_utils.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import re
55
import shlex
66
import subprocess
7+
import tempfile
78
from collections.abc import Iterator
89
from functools import cache
910
from pathlib import Path
@@ -234,6 +235,25 @@ def run_ruff(file_paths: list[Path], verbose: bool = False) -> None:
234235
print("Now running command\n", shlex.join(command))
235236
subprocess.run(command, check=False, capture_output=True)
236237

238+
for fp in file_paths:
239+
if fp.name == "__init__.py":
240+
fix_unused_imports_in_init_file(fp)
241+
242+
243+
def fix_unused_imports_in_init_file(init_file: Path) -> None:
244+
"""Ruff won't auto-remove unused imports in __init__.py (treats them as potential
245+
re-exports, and even --unsafe-fixes doesn't override this). Trick it by temporarily
246+
renaming the file 🧠"""
247+
# delete=False so we can close the handle before ruff opens it (just Windows things....):
248+
with tempfile.NamedTemporaryFile(mode="w", suffix=".py", encoding="utf-8", delete=False) as tmp:
249+
tmp.write(init_file.read_text(encoding="utf-8"))
250+
tmp_path = tmp.name
251+
try:
252+
run_ruff_direct(Path(tmp_path))
253+
init_file.write_text(Path(tmp_path).read_text(encoding="utf-8"), encoding="utf-8")
254+
finally:
255+
Path(tmp_path).unlink(missing_ok=True)
256+
237257

238258
def run_ruff_direct(file_path: Path) -> None:
239259
"""Run ruff directly on a file, bypassing pre-commit.

0 commit comments

Comments
 (0)