-
Notifications
You must be signed in to change notification settings - Fork 92
Expand file tree
/
Copy pathcleanup.py
More file actions
182 lines (147 loc) · 5.3 KB
/
cleanup.py
File metadata and controls
182 lines (147 loc) · 5.3 KB
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
#!/usr/bin/env python3
"""Clean temporary directories across the Plato codebase."""
from __future__ import annotations
import argparse
import os
import shutil
from pathlib import Path
from collections.abc import Iterable
RUNTIME_NAME = "runtime"
PYCACHE_NAME = "__pycache__"
EXCLUDED_NAMES = {".venv"}
def find_runtime_roots(root: Path) -> list[Path]:
"""Return all ``runtime`` directories located beneath ``root``."""
root = root.resolve()
runtime_roots: list[Path] = []
seen_runtime: set[Path] = set()
def add_runtime(candidate: Path) -> None:
try:
resolved = candidate.resolve()
except OSError:
return
if resolved in seen_runtime or not candidate.is_dir():
return
seen_runtime.add(resolved)
runtime_roots.append(candidate)
if root.name == RUNTIME_NAME:
add_runtime(root)
for current, dirnames, _ in os.walk(root, topdown=True):
pruned_dirs = []
for dirname in dirnames:
if dirname in EXCLUDED_NAMES:
continue
if dirname == RUNTIME_NAME:
add_runtime(Path(current) / dirname)
continue
if dirname == PYCACHE_NAME:
continue
pruned_dirs.append(dirname)
dirnames[:] = pruned_dirs
return runtime_roots
def iter_pycache_directories(root: Path) -> Iterable[Path]:
"""Yield all ``__pycache__`` directories under ``root`` (excluding excluded paths)."""
root = root.resolve()
if root.name == PYCACHE_NAME and root.is_dir():
yield root
seen_pycache: set[Path] = set()
for current, dirnames, _ in os.walk(root, topdown=True):
pruned_dirs = []
for dirname in dirnames:
if dirname in EXCLUDED_NAMES:
continue
if dirname == PYCACHE_NAME:
candidate = Path(current) / dirname
resolved_candidate = candidate.resolve()
if resolved_candidate in seen_pycache:
continue
seen_pycache.add(resolved_candidate)
yield candidate
continue
pruned_dirs.append(dirname)
dirnames[:] = pruned_dirs
def clean_directory(path: Path) -> int:
"""Remove all contents of the directory at ``path``. Returns items deleted."""
removed = 0
for child in path.iterdir():
try:
if child.is_symlink() or child.is_file():
child.unlink()
elif child.is_dir():
shutil.rmtree(child)
else:
continue
removed += 1
except OSError as exc:
print(f"Failed to remove {child}: {exc}")
return removed
def remove_directory(path: Path) -> bool:
"""Remove the directory at ``path`` entirely. Returns ``True`` on success."""
try:
shutil.rmtree(path)
return True
except OSError as exc:
print(f"Failed to remove {path}: {exc}")
return False
def resolve_root(path_str: str | None) -> Path:
"""Resolve the repository root to clean under."""
if path_str is None:
return Path(__file__).resolve().parent
return Path(path_str).resolve()
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description=(
"Remove Plato runtime directories (and their contents) under the "
"given root directory and delete any __pycache__ folders."
)
)
parser.add_argument(
"root",
nargs="?",
help="Optional root directory to scan (defaults to script location).",
)
return parser.parse_args()
def main() -> None:
args = parse_args()
root = resolve_root(args.root)
if not root.is_dir():
raise SystemExit(f"Root path is not a directory: {root}")
print(f"Cleaning temporary directories under: {root}")
runtime_roots = find_runtime_roots(root)
runtime_total = len(runtime_roots)
runtime_removed = 0
fallback_dirs = 0
fallback_items = 0
for runtime_dir in runtime_roots:
if remove_directory(runtime_dir):
print(f"Deleted runtime directory {runtime_dir}")
runtime_removed += 1
continue
cleared = clean_directory(runtime_dir)
print(f"Failed to delete {runtime_dir}; cleared {cleared} items instead.")
fallback_dirs += 1
fallback_items += cleared
if runtime_total == 0:
print("No runtime directories found.")
else:
print(f"Removed {runtime_removed} of {runtime_total} runtime directories.")
if fallback_dirs:
print(
f"Cleared {fallback_items} items in "
f"{fallback_dirs} undeleted runtime directories."
)
if not root.exists():
print("Root directory removed; skipped __pycache__ cleanup.")
return
pycache_removed = 0
pycache_total = 0
for pycache_dir in iter_pycache_directories(root):
if remove_directory(pycache_dir):
print(f"Deleted __pycache__ directory {pycache_dir}")
pycache_removed += 1
pycache_total += 1
if pycache_total == 0:
print("No __pycache__ directories found.")
else:
print(f"Removed {pycache_removed} of {pycache_total} __pycache__ directories.")
if __name__ == "__main__":
main()