Files
leleka/scripts/dev/prune_unused_imports.py

143 lines
5.8 KiB
Python

"""Remove `#[allow(unused_imports)]` from a crate and delete the imports the compiler reports as unused (STRA-338 stage 10).
Usage:
python scripts/dev/prune_unused_imports.py strip CRATE_DIR remove every bare `#[allow(unused_imports)]` line
python scripts/dev/prune_unused_imports.py check PACKAGE CONFIG LOG cargo check one feature set (CONFIG: cuda|sm86|all|...)
python scripts/dev/prune_unused_imports.py report LOG... count the unused-import diagnostics per file
python scripts/dev/prune_unused_imports.py fix LOG... apply the removals that every LOG agrees on
The suggestions are the ones `cargo fix` would apply, but a span is removed only when every log (feature set) flags it in
every compilation unit that holds it, and an import that only the library's unit tests use gets `#[cfg(test)]`.
Offline refactoring aid, not part of the product.
"""
import json
import pathlib
import re
import subprocess
import sys
ROOT = pathlib.Path(__file__).resolve().parents[2]
CONFIGS = {
"default": "",
"cuda": "--features cuda-driver",
"sm86": "--features cuda-driver,sm86",
"probe": "--features cuda-driver,expert-tier-probe",
"all": "--all-features",
}
def write(path, data):
with open(path, "wb") as handle:
handle.write(data)
def strip(crate_dir):
changed = 0
for path in sorted(pathlib.Path(crate_dir).rglob("*.rs")):
if "target" in path.parts:
continue
rows = path.read_bytes().decode("utf-8").split("\n")
kept = [r for r in rows if r.strip() != "#[allow(unused_imports)]"]
if len(kept) != len(rows):
changed += len(rows) - len(kept)
write(path, "\n".join(kept).encode("utf-8"))
print(f"removed {changed} lines")
def check(package, config, log):
flags = CONFIGS.get(config, config)
packages = " ".join(f"-p {name}" for name in package.split(","))
cmd = f"check -j1 {packages} --all-targets {flags} --message-format=json"
subprocess.run(["bash", str(ROOT / "scripts/dev/wsl-cargo.sh"), log, *cmd.split()], check=True, cwd=ROOT)
def diagnostics(log):
"""{(file, start, end, replacement): {unit}} of the unused-import removal suggestions of one log. A unit is the
compilation that reported it: `lib`, `lib-test` or `<kind>:<target>` (an integration test, an example). Cargo runs with
one job, so the messages of one rustc process come right before its `compiler-artifact` line, which names the unit."""
found, buffered = {}, []
for line in pathlib.Path(ROOT / log).read_text(encoding="utf-8", errors="replace").splitlines():
if not line.startswith("{"):
continue
record = json.loads(line)
if record.get("reason") == "compiler-message":
message = record["message"]
if (message.get("code") or {}).get("code") == "unused_imports":
buffered.append(message)
elif record.get("reason") == "compiler-artifact":
kind = record["target"]["kind"][0]
if kind == "lib":
unit = "lib-test" if record["profile"]["test"] else "lib"
else:
unit = f"{kind}:{record['target']['name']}"
for message in buffered:
for child in message["children"]:
for span in child["spans"]:
if span.get("suggested_replacement") is not None:
key = (span["file_name"], span["byte_start"], span["byte_end"], span["suggested_replacement"])
found.setdefault(key, set()).add(unit)
buffered = []
return found
def report(logs):
per = {}
for log in logs:
for file, *_ in diagnostics(log):
per[file] = per.get(file, 0) + 1
for file, n in sorted(per.items(), key=lambda kv: -kv[1]):
print(n, file)
print("total", sum(per.values()), "in", len(per), "files")
def decide(logs):
"""(remove, test_only): spans every log flags. `remove`: flagged in every unit that compiles the span.
`test_only`: flagged in the library but used by the library's unit tests (needs `#[cfg(test)]`)."""
maps = [diagnostics(log) for log in logs]
keys = set.intersection(*[set(m) for m in maps])
remove, test_only = set(), set()
for key in keys:
units = [m[key] for m in maps]
outside_lib = "/tests/" in key[0] or "/examples/" in key[0]
both = all(("lib" in u) == ("lib-test" in u) for u in units) or all(u == {"lib-test"} for u in units)
only_lib = all("lib" in u and "lib-test" not in u for u in units)
if outside_lib or both:
remove.add(key)
elif only_lib:
test_only.add(key)
return remove, test_only
def fix(logs):
remove, test_only = decide(logs)
edits = {}
for key in remove:
edits.setdefault(key[0], []).append((key[1], key[2], key[3]))
held = []
for key in test_only:
text = (ROOT / key[0]).read_bytes()[key[1] : key[2]].decode()
if re.match(r"(pub(\([^)]*\))?\s+)?use\s[^{}]*;\s*$", text.strip()):
edits.setdefault(key[0], []).append((key[1], key[1], "#[cfg(test)]\n"))
else:
held.append((key[0], text.strip()[:60]))
for file, items in edits.items():
data = (ROOT / file).read_bytes()
for start, end, replacement in sorted(items, reverse=True):
data = data[:start] + replacement.encode() + data[end:]
write(ROOT / file, data)
print(f"removed {len(remove)}, gated `#[cfg(test)]` {len(test_only) - len(held)}, left {len(held)}")
for item in held:
print(" left:", item)
if __name__ == "__main__":
action, args = sys.argv[1], sys.argv[2:]
if action == "strip":
strip(args[0])
elif action == "check":
check(*args)
elif action == "report":
report(args)
elif action == "fix":
fix(args)