-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGameProjectCleaner.py
More file actions
400 lines (315 loc) · 11.5 KB
/
Copy pathGameProjectCleaner.py
File metadata and controls
400 lines (315 loc) · 11.5 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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
#!/usr/bin/env python3
"""
Recursively clean safe-to-recreate cache folders from Unity and Unreal projects.
By default the script starts from the folder where it is executed. When a GUI is
available, it offers a folder picker so another scan root can be selected.
"""
from __future__ import annotations
import argparse
import os
import shutil
import stat
import sys
from dataclasses import dataclass, field
from pathlib import Path
from typing import Iterable
UNITY_CACHE_DIRS = ("Library", "Temp", "obj")
UNREAL_CACHE_DIRS = ("Intermediate", "Saved", "DerivedDataCache", "Binaries", "Build")
ALL_CACHE_DIR_NAMES = frozenset(UNITY_CACHE_DIRS + UNREAL_CACHE_DIRS)
@dataclass
class CacheEntry:
engine: str
project_root: Path
cache_name: str
path: Path
size_bytes: int
@dataclass
class ProjectSummary:
engine: str
root: Path
entries: list[CacheEntry] = field(default_factory=list)
@property
def total_bytes(self) -> int:
return sum(entry.size_bytes for entry in self.entries)
def human_size(num_bytes: int) -> str:
units = ("B", "KB", "MB", "GB", "TB")
size = float(num_bytes)
for unit in units:
if size < 1024 or unit == units[-1]:
if unit == "B":
return f"{int(size)} {unit}"
return f"{size:.2f} {unit}"
size /= 1024
return f"{num_bytes} B"
def is_unity_project(path: Path) -> bool:
return (path / "Assets").is_dir() and (path / "ProjectSettings").is_dir()
def is_unreal_project(path: Path) -> bool:
try:
return any(child.suffix.lower() == ".uproject" for child in path.iterdir() if child.is_file())
except OSError:
return False
def safe_iterdir(path: Path) -> Iterable[Path]:
try:
yield from path.iterdir()
except OSError as exc:
print(f"Warning: cannot read {path}: {exc}", file=sys.stderr)
def folder_size(path: Path) -> int:
total = 0
for root, dirs, files in os.walk(path, topdown=True, followlinks=False):
root_path = Path(root)
kept_dirs = []
for dirname in dirs:
child = root_path / dirname
if child.is_symlink():
continue
kept_dirs.append(dirname)
dirs[:] = kept_dirs
for filename in files:
file_path = root_path / filename
try:
if not file_path.is_symlink():
total += file_path.stat().st_size
except OSError:
pass
return total
def discover_projects(scan_root: Path) -> list[tuple[str, Path]]:
projects: list[tuple[str, Path]] = []
seen: set[tuple[str, Path]] = set()
for root, dirs, _files in os.walk(scan_root, topdown=True, followlinks=False):
root_path = Path(root)
kept_dirs = []
for dirname in dirs:
child = root_path / dirname
if child.is_symlink() or dirname in ALL_CACHE_DIR_NAMES:
continue
kept_dirs.append(dirname)
dirs[:] = kept_dirs
engines = []
if is_unity_project(root_path):
engines.append("Unity")
if is_unreal_project(root_path):
engines.append("Unreal")
for engine in engines:
try:
resolved = root_path.resolve()
except OSError:
resolved = root_path.absolute()
key = (engine, resolved)
if key not in seen:
seen.add(key)
projects.append((engine, root_path))
return projects
def build_summaries(scan_root: Path) -> list[ProjectSummary]:
summaries: list[ProjectSummary] = []
used_paths: set[Path] = set()
for engine, project_root in discover_projects(scan_root):
cache_names = UNITY_CACHE_DIRS if engine == "Unity" else UNREAL_CACHE_DIRS
summary = ProjectSummary(engine=engine, root=project_root)
for cache_name in cache_names:
cache_path = project_root / cache_name
if not cache_path.is_dir() or cache_path.is_symlink():
continue
try:
resolved = cache_path.resolve()
except OSError:
resolved = cache_path.absolute()
if resolved in used_paths:
continue
used_paths.add(resolved)
summary.entries.append(
CacheEntry(
engine=engine,
project_root=project_root,
cache_name=cache_name,
path=cache_path,
size_bytes=folder_size(cache_path),
)
)
if summary.entries:
summaries.append(summary)
return summaries
def make_breakdown(scan_root: Path, summaries: list[ProjectSummary]) -> str:
total = sum(summary.total_bytes for summary in summaries)
lines = [
"Game Project Cleaner scan summary",
f"Root: {scan_root}",
f"Projects with cache folders: {len(summaries)}",
f"Total reclaimable space: {human_size(total)}",
"",
]
for summary in sorted(summaries, key=lambda item: str(item.root).lower()):
lines.append(f"[{summary.engine}] {summary.root}")
lines.append(f" Project total: {human_size(summary.total_bytes)}")
for entry in sorted(summary.entries, key=lambda item: item.cache_name.lower()):
lines.append(f" - {entry.cache_name}: {human_size(entry.size_bytes)}")
lines.append(f" {entry.path}")
lines.append("")
return "\n".join(lines).rstrip()
def make_short_summary(summaries: list[ProjectSummary]) -> str:
total = sum(summary.total_bytes for summary in summaries)
return (
f"{len(summaries)} project folder(s) contain cache data.\n"
f"Total reclaimable space: {human_size(total)}\n\n"
"A detailed breakdown was printed in the console.\n\n"
"Delete these cache folders now?"
)
def get_tk_root():
try:
import tkinter as tk
except Exception:
return None
try:
root = tk.Tk()
root.withdraw()
root.update()
return root
except Exception:
return None
def choose_scan_root(default_root: Path, force_console: bool) -> Path:
if force_console:
return default_root
root = get_tk_root()
if root is None:
return default_root
try:
from tkinter import filedialog, messagebox
use_current = messagebox.askyesno(
"Game Project Cleaner",
f"Scan the current folder?\n\n{default_root}\n\n"
"Choose No to select another starting folder.",
parent=root,
)
if use_current:
return default_root
selected = filedialog.askdirectory(
title="Select the starting folder to scan",
initialdir=str(default_root),
mustexist=True,
parent=root,
)
return Path(selected) if selected else default_root
finally:
root.destroy()
def ask_confirmation(summaries: list[ProjectSummary], assume_yes: bool, force_console: bool) -> bool:
if assume_yes:
return True
if not force_console:
root = get_tk_root()
if root is not None:
try:
from tkinter import messagebox
return bool(
messagebox.askyesno(
"Confirm cache cleanup",
make_short_summary(summaries),
icon="warning",
parent=root,
)
)
finally:
root.destroy()
answer = input("\nDelete these cache folders? Type YES to continue: ").strip()
return answer == "YES"
def show_completion(total_released: int, deleted_count: int, errors: list[str], force_console: bool) -> None:
message = (
f"Deleted cache folders: {deleted_count}\n"
f"Total disk space released: {human_size(total_released)}"
)
if errors:
message += f"\n\nCompleted with {len(errors)} error(s). See console for details."
print("\nCleanup complete")
print(message)
if force_console:
return
root = get_tk_root()
if root is None:
return
try:
from tkinter import messagebox
if errors:
messagebox.showwarning("Game Project Cleaner complete", message, parent=root)
else:
messagebox.showinfo("Game Project Cleaner complete", message, parent=root)
finally:
root.destroy()
def remove_readonly(func, path, _exc_info):
try:
os.chmod(path, stat.S_IWRITE)
func(path)
except OSError:
raise
def delete_entries(summaries: list[ProjectSummary], dry_run: bool) -> tuple[int, int, list[str]]:
total_released = 0
deleted_count = 0
errors: list[str] = []
entries = [entry for summary in summaries for entry in summary.entries]
for entry in sorted(entries, key=lambda item: str(item.path).lower()):
print(f"Deleting {entry.path} ({human_size(entry.size_bytes)})")
if dry_run:
total_released += entry.size_bytes
deleted_count += 1
continue
try:
shutil.rmtree(entry.path, onerror=remove_readonly)
total_released += entry.size_bytes
deleted_count += 1
except OSError as exc:
error = f"{entry.path}: {exc}"
errors.append(error)
print(f"Error: {error}", file=sys.stderr)
return total_released, deleted_count, errors
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Clean Unity and Unreal cache folders under a selected root."
)
parser.add_argument(
"root",
nargs="?",
type=Path,
help="Starting folder to scan. Defaults to the current working folder.",
)
parser.add_argument(
"--yes",
action="store_true",
help="Delete without asking for confirmation after printing the breakdown.",
)
parser.add_argument(
"--dry-run",
action="store_true",
help="Show what would be deleted without removing anything.",
)
parser.add_argument(
"--console",
action="store_true",
help="Disable folder picker and popup dialogs.",
)
return parser.parse_args()
def main() -> int:
args = parse_args()
default_root = (args.root or Path.cwd()).resolve()
if not default_root.exists() or not default_root.is_dir():
print(f"Error: scan root is not a folder: {default_root}", file=sys.stderr)
return 2
scan_root = choose_scan_root(default_root, force_console=args.console or args.root is not None)
scan_root = scan_root.resolve()
print(f"Scanning from: {scan_root}")
summaries = build_summaries(scan_root)
if not summaries:
print("No Unity or Unreal cache folders were found.")
if not args.console:
show_completion(0, 0, [], force_console=False)
return 0
breakdown = make_breakdown(scan_root, summaries)
print()
print(breakdown)
if args.dry_run:
print("\nDry run only. Nothing was deleted.")
return 0
if not ask_confirmation(summaries, assume_yes=args.yes, force_console=args.console):
print("Cleanup cancelled. Nothing was deleted.")
return 0
total_released, deleted_count, errors = delete_entries(summaries, dry_run=False)
show_completion(total_released, deleted_count, errors, force_console=args.console)
return 1 if errors else 0
if __name__ == "__main__":
raise SystemExit(main())