File size: 7,010 Bytes
4c20479 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 | #!/usr/bin/env python3
"""Delete the USD files listed by ``usd_models_cleaner.py --unused``.
Takes the JSON list written by ``usd_models_cleaner.py --out`` and removes each
file from ``assets/usd_models``. Afterwards any directory left holding no USD
file at all is removed whole (its leftover textures/materials went with the
model that referenced them).
Destructive. Preview with --dry-run first; the real run asks for confirmation
unless --yes is given.
Usage:
python scripts/usd_cleaner/usd_models_cleaner.py --unused --out unused_usds.json
python scripts/usd_cleaner/usd_models_delete.py unused_usds.json --dry-run # found in scripts/
python scripts/usd_cleaner/usd_models_delete.py unused_usds.json
"""
from __future__ import annotations
import argparse
import json
import shutil
from pathlib import Path
SCRIPT_DIR = Path(__file__).resolve().parent
REPO_ROOT = SCRIPT_DIR.parent.parent
USD_SUFFIXES = {".usd", ".usda", ".usdc", ".usdz"}
# Never sweep VCS/metadata dirs: they hold no USD, so the "USD-less" rule would
# otherwise eat assets/usd_models/.git wholesale.
PROTECTED = {".git", ".svn", ".hg", ".datasets", "__pycache__"}
def human(nbytes: int) -> str:
size = float(nbytes)
for unit in ("B", "K", "M", "G", "T"):
if size < 1024 or unit == "T":
return f"{size:.1f}{unit}"
size /= 1024
def resolve(value: str) -> Path:
path = Path(value)
return path if path.is_absolute() else REPO_ROOT / path
def is_protected(path: Path, root: Path) -> bool:
"""True if ``path`` is, or sits inside, a protected directory."""
return any(
part in PROTECTED or part.startswith(".")
for part in path.relative_to(root).parts
)
def usd_census(directory: Path, doomed: set):
"""(had a USD beneath, keeps one after ``doomed`` is deleted)."""
had = keeps = False
for f in directory.rglob("*"):
if f.is_file() and f.suffix.lower() in USD_SUFFIXES:
had = True
if f not in doomed:
return True, True
return had, keeps
def main() -> None:
parser = argparse.ArgumentParser(
description="Delete unreferenced USD files and the folders left without any USD"
)
parser.add_argument(
"usd_delete_list",
help="JSON list of paths to delete (from usd_models_cleaner.py --out)",
)
parser.add_argument(
"--models_dir",
default="assets/usd_models",
help="Deletion is confined to this directory",
)
parser.add_argument(
"--dry-run",
action="store_true",
help="Report what would be removed without touching anything",
)
parser.add_argument(
"--yes", action="store_true", help="Skip the confirmation prompt"
)
parser.add_argument(
"--keep_empty_dirs",
action="store_true",
help="Delete only the files; leave USD-less directories in place",
)
args = parser.parse_args()
models_dir = resolve(args.models_dir).resolve()
if not models_dir.is_dir():
raise SystemExit(f"Models directory not found: {models_dir}")
# Accept the list as given, or by bare name from scripts/ or the repo root.
for candidate in (
Path(args.usd_delete_list),
SCRIPT_DIR / args.usd_delete_list,
REPO_ROOT / args.usd_delete_list,
):
if candidate.is_file():
list_path = candidate.resolve()
break
else:
raise SystemExit(f"Delete list not found: {args.usd_delete_list}")
entries = json.loads(list_path.read_text())
if not isinstance(entries, list):
raise SystemExit(f"{list_path} must contain a JSON list of paths")
targets, missing, outside = [], [], []
for entry in entries:
path = resolve(entry).resolve()
# Containment check: a stray "../" in the list must never escape the tree.
if not path.is_relative_to(models_dir):
outside.append(entry)
elif not path.is_file():
missing.append(entry)
else:
targets.append(path)
if outside:
raise SystemExit(
f"Refusing to run: {len(outside)} path(s) fall outside {models_dir}, "
f"e.g. {outside[0]}"
)
doomed = set(targets)
# Plan the directory sweep before deleting anything, so the dry-run and the
# real run agree. Keep only the top-most doomed dirs: rmtree takes the rest.
doomed_dirs = []
if not args.keep_empty_dirs:
# A dir is swept only if it HELD a USD and now holds none. A dir that never
# held one (textures/, materials/) belongs to its parent model — deleting it
# standalone would strip a surviving model of its assets.
candidates = []
for d in models_dir.rglob("*"):
if not d.is_dir() or is_protected(d, models_dir):
continue
had, keeps = usd_census(d, doomed)
if had and not keeps:
candidates.append(d)
candidates.sort(key=lambda d: len(d.parts))
for directory in candidates:
if not any(directory.is_relative_to(kept) for kept in doomed_dirs):
doomed_dirs.append(directory)
# Every file that actually disappears, counted exactly once.
going = set(doomed)
for directory in doomed_dirs:
going.update(f for f in directory.rglob("*") if f.is_file())
freed = sum(f.stat().st_size for f in going if f.exists())
print(f"[delete] list : {list_path}")
print(f"[delete] confined : {models_dir}")
print(f"[delete] to delete : {len(targets)} listed USD files")
if doomed_dirs:
print(
f"[delete] plus : {len(doomed_dirs)} USD-less directories "
f"({len(going) - len(doomed)} further files)"
)
if missing:
print(f"[delete] skipping : {len(missing)} already absent")
print(f"[delete] frees : {human(freed)}")
if not targets:
print("[delete] nothing to do")
return
if args.dry_run:
for path in sorted(going):
print(f" would delete {path.relative_to(REPO_ROOT)}")
for directory in sorted(doomed_dirs):
print(f" would remove dir {directory.relative_to(REPO_ROOT)}")
print(f"\n[delete] dry run — nothing was touched, would free {human(freed)}")
return
if not args.yes:
answer = input(f"Delete {len(going)} files under {models_dir}? [y/N] ")
if answer.strip().lower() not in ("y", "yes"):
raise SystemExit("[delete] aborted")
removed = 0
for path in targets:
if path.exists():
path.unlink()
removed += 1
for directory in doomed_dirs:
if directory.exists():
shutil.rmtree(directory)
print(
f"\n[delete] deleted {removed} listed files, "
f"removed {len(doomed_dirs)} USD-less directories"
)
print(f"[delete] freed {human(freed)}")
if __name__ == "__main__":
main()
|