path_to_layout.py: module tree walk with flat (#[path]) and default layout, include fixer
This commit is contained in:
+101
-65
@@ -1,17 +1,20 @@
|
||||
"""Replace `#[path = "x.rs"] mod name;` by the directory layout (`parent/name.rs`) with `git mv` (STRA-338 stage 10).
|
||||
|
||||
Usage: python scripts/dev/path_to_layout.py CRATE_DIR [--apply]
|
||||
Usage: python scripts/dev/path_to_layout.py CRATE_DIR [--apply | --fix-includes]
|
||||
|
||||
The module paths do not change, only where the files live. Walking the module tree from the crate roots, a module whose
|
||||
declaration carries a counted `#[path]` (one that is not `tests.rs` and not the `dir/name.rs` form) gets the location its
|
||||
parent's directory gives it: `<parent dir>/<name>.rs`, and the directory that holds its children moves with it. Then
|
||||
declaration carries a `#[path]` (except a `tests.rs` file and a `../` path that leaves the module's directory) gets the
|
||||
location its parent's directory gives it: `<parent dir>/<name>.rs`, and the children that were resolved next to the
|
||||
old file move into the directory named after the new one. Then
|
||||
|
||||
* the `#[path]` of every declaration whose target is now the default location is dropped, the others are rewritten
|
||||
relative to the moved parent;
|
||||
* the `#[path]` of every normalised declaration is dropped, the others are rewritten relative to the moved parent;
|
||||
* `include_str!`, `include_bytes!` and `include!` paths of a moved file are rewritten to reach the same file.
|
||||
|
||||
Without --apply the plan is printed. A module that two parents declare is moved for the first parent only; a target that
|
||||
already exists is reported and left. Offline refactoring aid, not part of the product.
|
||||
A file loaded through `#[path]` (like a crate root or `mod.rs`) resolves its own `mod x;` next to itself; a file at its
|
||||
default place resolves them in a directory named after it. The tool tracks both for the old and the new tree.
|
||||
Without --apply the plan is printed. A target that already exists is reported and left. After --apply, run
|
||||
--fix-includes: it rewrites the `include_str!` of source files that other files read and that moved (read from
|
||||
`git diff -M`). Offline refactoring aid, not part of the product.
|
||||
"""
|
||||
import os
|
||||
import pathlib
|
||||
@@ -20,7 +23,6 @@ import subprocess
|
||||
import sys
|
||||
|
||||
ROOTS = ("lib.rs", "main.rs", "mod.rs")
|
||||
COUNTED = re.compile(r'#\[path\s*=\s*"(?![^"]*tests\.rs")(?![A-Za-z0-9_]+/[A-Za-z0-9_]+\.rs")')
|
||||
PATH_ATTR = re.compile(r'^(\s*)#\[path\s*=\s*"([^"]+)"\]\s*$')
|
||||
MOD_DECL = re.compile(r"^\s*(?:pub(?:\([^)]*\))?\s+)?mod\s+([A-Za-z_][A-Za-z0-9_]*)\s*;\s*$")
|
||||
INCLUDE = re.compile(r'(include_str!|include_bytes!|include!)\(\s*"([^"]+)"\s*\)')
|
||||
@@ -30,8 +32,9 @@ def is_root(path):
|
||||
return path.name in ROOTS or path.parent.name == "bin" and path.parent.parent.name == "src"
|
||||
|
||||
|
||||
def module_dir(path):
|
||||
return path.parent if is_root(path) else path.parent / path.stem
|
||||
def directory(path, flat):
|
||||
"""Where the `mod x;` declarations of a file are resolved."""
|
||||
return path.parent if flat else path.parent / path.stem
|
||||
|
||||
|
||||
def declarations(path):
|
||||
@@ -53,57 +56,59 @@ def declarations(path):
|
||||
|
||||
|
||||
class Plan:
|
||||
def __init__(self, src):
|
||||
self.src, self.new, self.visited = src, {}, set()
|
||||
self.decls = {} # old file -> [(name, mod line, path line, path value, old child)]
|
||||
self.skipped = []
|
||||
"""The module tree walked from the crate roots: for every module file its old and its new place."""
|
||||
|
||||
def old_child(self, old_parent, name, value):
|
||||
base = old_parent.parent / value if value else module_dir(old_parent) / f"{name}.rs"
|
||||
base = pathlib.Path(os.path.normpath(base))
|
||||
if base.is_file():
|
||||
return base
|
||||
alt = module_dir(old_parent) / name / "mod.rs"
|
||||
return alt if not value and alt.is_file() else None
|
||||
def __init__(self):
|
||||
self.new, self.flats, self.decls, self.skipped = {}, {}, {}, []
|
||||
|
||||
def walk(self, old, new):
|
||||
if old in self.visited:
|
||||
def old_child(self, old, old_flat, name, value):
|
||||
"""(file, flat) of the module a declaration names in the old tree."""
|
||||
if value:
|
||||
base = pathlib.Path(os.path.normpath(old.parent / value))
|
||||
return (base, True) if base.is_file() else (None, False)
|
||||
plain = directory(old, old_flat) / f"{name}.rs"
|
||||
nested = directory(old, old_flat) / name / "mod.rs"
|
||||
return (plain, False) if plain.is_file() else (nested, True) if nested.is_file() else (None, False)
|
||||
|
||||
def place(self, canonical, child, dirs, normalise, has_attr):
|
||||
"""(new file, flat, normalised) for a child that is not placed yet; flat None keeps the old kind."""
|
||||
old_dir, new_dir = dirs
|
||||
if normalise and child == canonical:
|
||||
return canonical, False, True
|
||||
if normalise and not canonical.exists() and canonical not in self.new.values():
|
||||
return canonical, False, True
|
||||
if not has_attr and old_dir != new_dir:
|
||||
return new_dir / child.relative_to(old_dir), None, False
|
||||
return child, None, False
|
||||
|
||||
def walk(self, old, new, old_flat, new_flat):
|
||||
if old in self.new:
|
||||
return
|
||||
self.visited.add(old)
|
||||
self.new[old] = new
|
||||
self.new[old], self.flats[old] = new, new_flat
|
||||
dirs = directory(old, old_flat), directory(new, new_flat)
|
||||
rows = []
|
||||
for name, mod_line, path_line, value in declarations(old):
|
||||
child = self.old_child(old, name, value)
|
||||
child, child_flat = self.old_child(old, old_flat, name, value)
|
||||
if child is None:
|
||||
continue
|
||||
canonical = module_dir(new) / f"{name}.rs"
|
||||
counted = value is not None and ".." not in value and COUNTED.search(f'#[path = "{value}"') is not None
|
||||
normalise = value is not None and ".." not in value and not value.endswith("tests.rs")
|
||||
if child in self.new:
|
||||
target = self.new[child]
|
||||
elif counted and child != canonical and not canonical.exists() and canonical not in self.new.values():
|
||||
target = canonical
|
||||
target, normalised = self.new[child], False
|
||||
else:
|
||||
if counted and child != canonical:
|
||||
canonical = dirs[1] / f"{name}.rs"
|
||||
target, flat, normalised = self.place(canonical, child, dirs, normalise, value is not None)
|
||||
if normalise and not normalised:
|
||||
self.skipped.append((str(old), name, "target exists or is taken"))
|
||||
target = self.keep(old, new, child)
|
||||
rows.append((name, mod_line, path_line, value, child, target))
|
||||
self.walk(child, target)
|
||||
self.walk(child, target, child_flat, child_flat if flat is None else flat)
|
||||
rows.append((name, mod_line, path_line, value, target, normalised))
|
||||
self.decls[old] = rows
|
||||
|
||||
def keep(self, old, new, child):
|
||||
"""The child stays where it is, unless its parent's directory moved: then the directory content moves along."""
|
||||
old_dir, new_dir = module_dir(old), module_dir(new)
|
||||
if old_dir != new_dir and child.is_relative_to(old_dir):
|
||||
return new_dir / child.relative_to(old_dir)
|
||||
return child
|
||||
|
||||
|
||||
def collect(crate_dir):
|
||||
src = pathlib.Path(crate_dir).resolve() / "src"
|
||||
plan = Plan(src)
|
||||
roots = [p for p in sorted(src.rglob("*.rs")) if is_root(p)]
|
||||
for root in roots:
|
||||
plan.walk(root, root)
|
||||
plan = Plan()
|
||||
for root in (p for p in sorted(src.rglob("*.rs")) if is_root(p)):
|
||||
plan.walk(root, root, True, True)
|
||||
return plan
|
||||
|
||||
|
||||
@@ -115,38 +120,69 @@ def git(root, *args):
|
||||
subprocess.run(["git", *args], cwd=root, check=True, capture_output=True)
|
||||
|
||||
|
||||
def rewrite(plan, root, apply):
|
||||
def rewrite_file(old, new, rows_info, text):
|
||||
rows, drop = text.split("\n"), set()
|
||||
for _name, _mod_line, path_line, _value, target, normalised in rows_info:
|
||||
if path_line is None:
|
||||
continue
|
||||
if normalised:
|
||||
drop.add(path_line)
|
||||
else:
|
||||
indent = PATH_ATTR.match(rows[path_line]).group(1)
|
||||
rows[path_line] = f'{indent}#[path = "{relative(target, new.parent)}"]'
|
||||
text = "\n".join(r for i, r in enumerate(rows) if i not in drop)
|
||||
if old != new:
|
||||
text = INCLUDE.sub(lambda m: f'{m.group(1)}("{relative(old.parent / m.group(2), new.parent)}")', text)
|
||||
return text
|
||||
|
||||
|
||||
def apply_plan(plan, root, apply):
|
||||
moves = {old: new for old, new in plan.new.items() if old != new}
|
||||
for old, new in sorted(moves.items()):
|
||||
print(f"mv {old.relative_to(root).as_posix()} -> {new.relative_to(root).as_posix()}")
|
||||
print(f"{len(moves)} files move; left as they are: {plan.skipped}")
|
||||
if not apply:
|
||||
print(f"{len(moves)} files would move; skipped: {plan.skipped}")
|
||||
return
|
||||
contents = {old: old.read_text(encoding="utf-8") for old in plan.new}
|
||||
for old, new in sorted(moves.items()):
|
||||
new.parent.mkdir(parents=True, exist_ok=True)
|
||||
git(root, "mv", str(old), str(new))
|
||||
for old, new in plan.new.items():
|
||||
rows = contents[old].split("\n")
|
||||
drop = []
|
||||
for name, mod_line, path_line, value, child, target in plan.decls.get(old, []):
|
||||
default = module_dir(new) / f"{name}.rs"
|
||||
if path_line is None:
|
||||
continue
|
||||
if target == default:
|
||||
drop.append(path_line)
|
||||
else:
|
||||
indent = PATH_ATTR.match(rows[path_line]).group(1)
|
||||
rows[path_line] = f'{indent}#[path = "{relative(target, new.parent)}"]'
|
||||
text = "\n".join(r for i, r in enumerate(rows) if i not in set(drop))
|
||||
if old != new:
|
||||
text = INCLUDE.sub(lambda m: f'{m.group(1)}("{relative(old.parent / m.group(2), new.parent)}")', text)
|
||||
text = rewrite_file(old, new, plan.decls.get(old, []), contents[old])
|
||||
with open(new, "wb") as handle:
|
||||
handle.write(text.encode("utf-8"))
|
||||
print(f"moved {len(moves)} files; skipped {plan.skipped}")
|
||||
|
||||
|
||||
def fix_includes(crate_dir):
|
||||
"""Rewrite `include_str!`, `include_bytes!` and `include!` of `.rs` files that moved (read from `git diff -M`)."""
|
||||
root = pathlib.Path(crate_dir).resolve().parents[1]
|
||||
out = subprocess.run(["git", "diff", "-M", "--name-status", "HEAD"], cwd=root, capture_output=True, text=True).stdout
|
||||
moved = {}
|
||||
for line in out.splitlines():
|
||||
parts = line.split("\t")
|
||||
if parts[0].startswith("R"):
|
||||
moved[pathlib.Path(os.path.normpath(root / parts[1]))] = root / parts[2]
|
||||
changed = 0
|
||||
for path in pathlib.Path(crate_dir).resolve().rglob("*.rs"):
|
||||
text = path.read_text(encoding="utf-8")
|
||||
|
||||
def fix(match):
|
||||
target = pathlib.Path(os.path.normpath(path.parent / match.group(2)))
|
||||
if match.group(2).endswith(".rs") and not target.exists() and target in moved:
|
||||
return f'{match.group(1)}("{relative(moved[target], path.parent)}")'
|
||||
return match.group(0)
|
||||
|
||||
new_text = INCLUDE.sub(fix, text)
|
||||
if new_text != text:
|
||||
changed += 1
|
||||
with open(path, "wb") as handle:
|
||||
handle.write(new_text.encode("utf-8"))
|
||||
print(f"include paths fixed in {changed} files")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
crate = sys.argv[1]
|
||||
plan = collect(crate)
|
||||
rewrite(plan, pathlib.Path(crate).resolve().parents[1], "--apply" in sys.argv)
|
||||
if "--fix-includes" in sys.argv:
|
||||
fix_includes(crate)
|
||||
else:
|
||||
apply_plan(collect(crate), pathlib.Path(crate).resolve().parents[1], "--apply" in sys.argv)
|
||||
|
||||
Reference in New Issue
Block a user