-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsystem-cleaner.py
More file actions
219 lines (184 loc) · 7.58 KB
/
system-cleaner.py
File metadata and controls
219 lines (184 loc) · 7.58 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
#!/usr/bin/env python3
"""
System Cleaner — Find and clean temp files, cache, and empty directories.
Usage:
python system-cleaner.py <directory>
python system-cleaner.py <directory> --clean
python system-cleaner.py <directory> --ext .tmp --ext .log --ext .cache
Options:
--clean Actually delete files (default: scan-only / dry-run)
--ext EXT File extension to target (repeatable, default: .tmp .log .cache .bak .swp)
--max-age DAYS Only delete files older than N days
--remove-empty Remove empty directories after cleaning
--min-size SIZE Only delete files larger than SIZE (e.g. 1MB)
--help Show this help message and exit
Examples:
python system-cleaner.py ~/Downloads
python system-cleaner.py ~/Downloads --clean --max-age 30
python system-cleaner.py /tmp --clean --ext .tmp --remove-empty
python system-cleaner.py . --clean --ext .pyc --ext __pycache__ --min-size 100KB
"""
import os
import sys
import time
import argparse
from pathlib import Path
DEFAULT_EXTS = {".tmp", ".log", ".cache", ".bak", ".swp"}
TEMP_DIR_NAMES = {"__pycache__", ".cache", "temp", "tmp", "cache", ".temp"}
# List of common temp/cache directory names to detect
CACHE_SUBDIRS = {
"__pycache__", "node_modules/.cache", ".mypy_cache",
".pytest_cache", ".gradle", ".sass-cache",
}
def parse_size(size_str: str) -> int:
"""Convert human-readable size string to bytes."""
size_str = size_str.strip().upper()
units = {"B": 1, "KB": 1024, "MB": 1024 ** 2, "GB": 1024 ** 3}
for unit, multiplier in units.items():
if size_str.endswith(unit):
try:
num = float(size_str[: -len(unit)])
return int(num * multiplier)
except ValueError:
break
try:
return int(size_str)
except ValueError:
print(f"Error: Invalid size format: '{size_str}'.")
sys.exit(1)
def format_size(size_bytes: int) -> str:
"""Format bytes to human-readable string."""
for unit in ("B", "KB", "MB", "GB"):
if abs(size_bytes) < 1024:
return f"{size_bytes:.1f} {unit}"
size_bytes /= 1024
return f"{size_bytes:.1f} TB"
def scan_and_clean(directory: Path, clean: bool, extensions: set[str],
max_age_days: float | None, remove_empty: bool,
min_size_bytes: int) -> tuple[int, int, int]:
"""
Scan directory and optionally clean temp/cache files.
Returns (files_found, bytes_freed, empty_dirs_removed).
"""
files_found = 0
bytes_freed = 0
empty_dirs_removed = 0
now = time.time()
# Collect all paths to process
all_paths: list[Path] = []
try:
for root, dirs, files in os.walk(directory, topdown=False):
root_path = Path(root)
for fname in files:
all_paths.append(root_path / fname)
for dname in dirs:
all_paths.append(root_path / dname)
except PermissionError as e:
print(f" ! Permission denied: {e}")
# Process files
for path in all_paths:
if not path.exists():
continue
is_dir = path.is_dir()
action_taken = False
if is_dir:
# Check if it's a known cache/temp directory
if path.name in TEMP_DIR_NAMES or str(path) in CACHE_SUBDIRS:
action_taken = True
# Remove empty directories
if remove_empty:
try:
if not any(path.iterdir()):
if clean:
print(f" [REMOVE] {path}")
path.rmdir()
empty_dirs_removed += 1
else:
print(f" [FOUND] {path} (empty dir)")
files_found += 1
action_taken = True
except (OSError, PermissionError):
pass
else:
# Check extension
if path.suffix.lower() in extensions:
action_taken = True
# Check name patterns for cache files
if not action_taken and path.name in {".DS_Store", "Thumbs.db", "desktop.ini"}:
action_taken = True
if action_taken and not is_dir:
try:
stat = path.stat()
file_size = stat.st_size
# Check max age
if max_age_days is not None:
age_days = (now - stat.st_mtime) / 86400
if age_days < max_age_days:
continue
# Check min size
if min_size_bytes and file_size < min_size_bytes:
continue
files_found += 1
bytes_freed += file_size
if clean:
print(f" [DELETE] {path} ({format_size(file_size)})")
path.unlink()
else:
print(f" [FOUND] {path} ({format_size(file_size)})")
except (OSError, PermissionError) as e:
print(f" ! {path}: {e}")
return files_found, bytes_freed, empty_dirs_removed
def main():
parser = argparse.ArgumentParser(
description="Find and clean temp files, cache, and empty directories.",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=(
"Examples:\n"
" python system-cleaner.py ~/Downloads\n"
" python system-cleaner.py ~/Downloads --clean --max-age 30\n"
" python system-cleaner.py /tmp --clean --ext .tmp --remove-empty\n"
" python system-cleaner.py . --clean --ext .pyc --min-size 100KB\n"
),
)
parser.add_argument("directory", help="Directory to scan")
parser.add_argument("--clean", action="store_true",
help="Actually delete files (default: scan-only)")
parser.add_argument("--ext", action="append", default=[],
help="File extension to target (repeatable)")
parser.add_argument("--max-age", type=float,
help="Only delete files older than N days")
parser.add_argument("--remove-empty", action="store_true",
help="Remove empty directories")
parser.add_argument("--min-size", type=str,
help="Only delete files larger than this (e.g. 1MB)")
args = parser.parse_args()
target = Path(args.directory)
if not target.is_dir():
print(f"Error: '{args.directory}' is not a valid directory.")
sys.exit(1)
# Build extension set
extensions = set(DEFAULT_EXTS)
if args.ext:
extensions = {f".{e.strip('.')}" for e in args.ext}
min_size_bytes = parse_size(args.min_size) if args.min_size else 0
mode = "CLEAN" if args.clean else "SCAN"
print(f"System Cleaner [{mode}]")
print(f" Directory: {target}")
print(f" Extensions: {', '.join(sorted(extensions))}")
if args.max_age:
print(f" Max age: {args.max_age} day(s)")
if min_size_bytes:
print(f" Min size: {format_size(min_size_bytes)}")
print()
files_found, bytes_freed, empty_removed = scan_and_clean(
target, args.clean, extensions, args.max_age,
args.remove_empty, min_size_bytes,
)
print(f"\nSummary: {files_found} item(s), {format_size(bytes_freed)} "
f"{'deleted' if args.clean else 'found'}")
if args.remove_empty:
print(f" Empty dirs removed: {empty_removed}")
if not args.clean and files_found > 0:
print("\nRun with --clean to delete these files.")
if __name__ == "__main__":
main()