deadweight-cli 1.0.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- deadweight.py +800 -0
- deadweight_cli-1.0.2.dist-info/METADATA +288 -0
- deadweight_cli-1.0.2.dist-info/RECORD +7 -0
- deadweight_cli-1.0.2.dist-info/WHEEL +5 -0
- deadweight_cli-1.0.2.dist-info/entry_points.txt +2 -0
- deadweight_cli-1.0.2.dist-info/licenses/LICENSE +21 -0
- deadweight_cli-1.0.2.dist-info/top_level.txt +1 -0
deadweight.py
ADDED
|
@@ -0,0 +1,800 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
import math
|
|
6
|
+
import os
|
|
7
|
+
import shutil
|
|
8
|
+
import stat
|
|
9
|
+
import subprocess
|
|
10
|
+
import sys
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from datetime import datetime, timedelta, timezone
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from types import TracebackType
|
|
15
|
+
from typing import Any, Callable, Literal
|
|
16
|
+
|
|
17
|
+
try:
|
|
18
|
+
from rich import box
|
|
19
|
+
from rich.console import Console
|
|
20
|
+
from rich.markup import escape
|
|
21
|
+
from rich.progress import BarColumn, Progress, SpinnerColumn, TextColumn, TimeElapsedColumn
|
|
22
|
+
from rich.prompt import Confirm, Prompt
|
|
23
|
+
from rich.table import Table
|
|
24
|
+
from rich.text import Text
|
|
25
|
+
except ImportError:
|
|
26
|
+
sys.stderr.write("DeadWeight requires the 'rich' package.\nInstall it with: pip install rich\n")
|
|
27
|
+
raise SystemExit(1)
|
|
28
|
+
|
|
29
|
+
__version__ = "1.0.2"
|
|
30
|
+
|
|
31
|
+
HEAVY_DIR_NAMES: frozenset[str] = frozenset(
|
|
32
|
+
{"venv", ".venv", "node_modules", "__pycache__", ".pytest_cache", "dist", "build", ".pio"}
|
|
33
|
+
)
|
|
34
|
+
IGNORED_DIR_NAMES: frozenset[str] = HEAVY_DIR_NAMES | {".git"}
|
|
35
|
+
VENV_MARKER = "pyvenv.cfg"
|
|
36
|
+
|
|
37
|
+
GitStatus = Literal["clean", "dirty", "no-git", "error"]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass(slots=True)
|
|
41
|
+
class HeavyDir:
|
|
42
|
+
path: Path
|
|
43
|
+
size: int
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass(slots=True)
|
|
47
|
+
class GitInfo:
|
|
48
|
+
status: GitStatus
|
|
49
|
+
changed: int = 0
|
|
50
|
+
last_commit: datetime | None = None
|
|
51
|
+
error: str | None = None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass(slots=True)
|
|
55
|
+
class Project:
|
|
56
|
+
path: Path
|
|
57
|
+
heavy_dirs: list[HeavyDir]
|
|
58
|
+
git: GitInfo = field(default_factory=lambda: GitInfo(status="no-git"))
|
|
59
|
+
|
|
60
|
+
@property
|
|
61
|
+
def total_size(self) -> int:
|
|
62
|
+
return sum(item.size for item in self.heavy_dirs)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass(slots=True)
|
|
66
|
+
class ScanTarget:
|
|
67
|
+
path: Path
|
|
68
|
+
recursive: bool
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass(slots=True)
|
|
72
|
+
class ScanResult:
|
|
73
|
+
projects: list[Project]
|
|
74
|
+
scanned_projects: int
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def format_size(size_bytes: int) -> str:
|
|
78
|
+
if size_bytes < 1024:
|
|
79
|
+
return f"{size_bytes} B"
|
|
80
|
+
value = float(size_bytes)
|
|
81
|
+
for unit in ("KB", "MB", "GB", "TB"):
|
|
82
|
+
value /= 1024.0
|
|
83
|
+
if value < 1024.0 or unit == "TB":
|
|
84
|
+
return f"{value:.1f} {unit}"
|
|
85
|
+
return f"{value:.1f} TB"
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def format_gb(size_bytes: int) -> str:
|
|
89
|
+
return f"{size_bytes / (1024 ** 3):.2f} GB"
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def format_reclaim(size_bytes: int) -> str:
|
|
93
|
+
if size_bytes >= 1024 ** 3:
|
|
94
|
+
return format_gb(size_bytes)
|
|
95
|
+
return f"{format_gb(size_bytes)} ({format_size(size_bytes)})"
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def pluralize(count: int, singular: str, plural: str | None = None) -> str:
|
|
99
|
+
if count == 1:
|
|
100
|
+
return f"{count} {singular}"
|
|
101
|
+
return f"{count} {plural if plural is not None else singular + 's'}"
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _is_link(entry: os.DirEntry[str]) -> bool:
|
|
105
|
+
try:
|
|
106
|
+
if entry.is_symlink():
|
|
107
|
+
return True
|
|
108
|
+
junction_check = getattr(entry, "is_junction", None)
|
|
109
|
+
if callable(junction_check):
|
|
110
|
+
return bool(junction_check())
|
|
111
|
+
return bool(getattr(entry.stat(follow_symlinks=False), "st_reparse_tag", 0))
|
|
112
|
+
except OSError:
|
|
113
|
+
return True
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _is_link_path(path: Path) -> bool:
|
|
117
|
+
try:
|
|
118
|
+
if path.is_symlink():
|
|
119
|
+
return True
|
|
120
|
+
junction_check = getattr(path, "is_junction", None)
|
|
121
|
+
if callable(junction_check):
|
|
122
|
+
return bool(junction_check())
|
|
123
|
+
return bool(getattr(path.lstat(), "st_reparse_tag", 0))
|
|
124
|
+
except OSError:
|
|
125
|
+
return True
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _is_venv_dir(path: Path) -> bool:
|
|
129
|
+
if path.name == ".git":
|
|
130
|
+
return False
|
|
131
|
+
try:
|
|
132
|
+
return (path / VENV_MARKER).is_file()
|
|
133
|
+
except OSError:
|
|
134
|
+
return False
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _is_artifact_dir(path: Path) -> bool:
|
|
138
|
+
return path.name in HEAVY_DIR_NAMES or _is_venv_dir(path)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _iter_subdirectories(directory: Path) -> list[Path]:
|
|
142
|
+
subdirectories: list[Path] = []
|
|
143
|
+
try:
|
|
144
|
+
with os.scandir(directory) as entries:
|
|
145
|
+
for entry in entries:
|
|
146
|
+
if _is_link(entry):
|
|
147
|
+
continue
|
|
148
|
+
try:
|
|
149
|
+
if entry.is_dir(follow_symlinks=False):
|
|
150
|
+
subdirectories.append(Path(entry.path))
|
|
151
|
+
except OSError:
|
|
152
|
+
continue
|
|
153
|
+
except OSError:
|
|
154
|
+
return []
|
|
155
|
+
subdirectories.sort(key=lambda item: item.name.lower())
|
|
156
|
+
return subdirectories
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def directory_size(path: Path) -> int:
|
|
160
|
+
total = 0
|
|
161
|
+
stack: list[Path] = [path]
|
|
162
|
+
while stack:
|
|
163
|
+
current = stack.pop()
|
|
164
|
+
try:
|
|
165
|
+
with os.scandir(current) as entries:
|
|
166
|
+
for entry in entries:
|
|
167
|
+
if _is_link(entry):
|
|
168
|
+
continue
|
|
169
|
+
try:
|
|
170
|
+
if entry.is_dir(follow_symlinks=False):
|
|
171
|
+
stack.append(Path(entry.path))
|
|
172
|
+
elif entry.is_file(follow_symlinks=False):
|
|
173
|
+
total += entry.stat(follow_symlinks=False).st_size
|
|
174
|
+
except OSError:
|
|
175
|
+
continue
|
|
176
|
+
except OSError:
|
|
177
|
+
continue
|
|
178
|
+
return total
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def discover_targets(root: Path) -> list[ScanTarget]:
|
|
182
|
+
if (root / ".git").exists():
|
|
183
|
+
return [ScanTarget(path=root, recursive=True)]
|
|
184
|
+
children = _iter_subdirectories(root)
|
|
185
|
+
project_children = [
|
|
186
|
+
child
|
|
187
|
+
for child in children
|
|
188
|
+
if child.name not in IGNORED_DIR_NAMES and not _is_venv_dir(child)
|
|
189
|
+
]
|
|
190
|
+
has_root_heavy = any(_is_artifact_dir(child) for child in children)
|
|
191
|
+
targets: list[ScanTarget] = []
|
|
192
|
+
if has_root_heavy:
|
|
193
|
+
targets.append(ScanTarget(path=root, recursive=False))
|
|
194
|
+
targets.extend(ScanTarget(path=child, recursive=True) for child in project_children)
|
|
195
|
+
if not targets:
|
|
196
|
+
targets.append(ScanTarget(path=root, recursive=False))
|
|
197
|
+
return targets
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def find_heavy_dirs(base: Path, recursive: bool, min_size_bytes: int) -> list[HeavyDir]:
|
|
201
|
+
found: list[HeavyDir] = []
|
|
202
|
+
if recursive:
|
|
203
|
+
stack: list[Path] = [base]
|
|
204
|
+
while stack:
|
|
205
|
+
current = stack.pop()
|
|
206
|
+
for child in _iter_subdirectories(current):
|
|
207
|
+
if _is_artifact_dir(child):
|
|
208
|
+
size = directory_size(child)
|
|
209
|
+
if size >= min_size_bytes:
|
|
210
|
+
found.append(HeavyDir(path=child, size=size))
|
|
211
|
+
elif child.name != ".git":
|
|
212
|
+
stack.append(child)
|
|
213
|
+
else:
|
|
214
|
+
try:
|
|
215
|
+
with os.scandir(base) as entries:
|
|
216
|
+
for entry in entries:
|
|
217
|
+
if _is_link(entry):
|
|
218
|
+
continue
|
|
219
|
+
try:
|
|
220
|
+
if not entry.is_dir(follow_symlinks=False):
|
|
221
|
+
continue
|
|
222
|
+
except OSError:
|
|
223
|
+
continue
|
|
224
|
+
path = Path(entry.path)
|
|
225
|
+
if not _is_artifact_dir(path):
|
|
226
|
+
continue
|
|
227
|
+
size = directory_size(path)
|
|
228
|
+
if size >= min_size_bytes:
|
|
229
|
+
found.append(HeavyDir(path=path, size=size))
|
|
230
|
+
except OSError:
|
|
231
|
+
return found
|
|
232
|
+
found.sort(key=lambda item: item.size, reverse=True)
|
|
233
|
+
return found
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _run_git(project_path: Path, arguments: list[str]) -> subprocess.CompletedProcess[str] | None:
|
|
237
|
+
environment = os.environ.copy()
|
|
238
|
+
environment["GIT_OPTIONAL_LOCKS"] = "0"
|
|
239
|
+
try:
|
|
240
|
+
return subprocess.run(
|
|
241
|
+
["git", "-C", str(project_path), *arguments],
|
|
242
|
+
capture_output=True,
|
|
243
|
+
text=True,
|
|
244
|
+
encoding="utf-8",
|
|
245
|
+
errors="replace",
|
|
246
|
+
timeout=15,
|
|
247
|
+
env=environment,
|
|
248
|
+
check=False,
|
|
249
|
+
)
|
|
250
|
+
except (OSError, subprocess.SubprocessError):
|
|
251
|
+
return None
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def read_git_info(project_path: Path) -> GitInfo:
|
|
255
|
+
if not (project_path / ".git").exists():
|
|
256
|
+
return GitInfo(status="no-git")
|
|
257
|
+
status_result = _run_git(project_path, ["status", "--porcelain"])
|
|
258
|
+
if status_result is None:
|
|
259
|
+
return GitInfo(status="error", error="git executable not available")
|
|
260
|
+
if status_result.returncode != 0:
|
|
261
|
+
message = status_result.stderr.strip() or "git status failed"
|
|
262
|
+
return GitInfo(status="error", error=message)
|
|
263
|
+
changed = sum(1 for line in status_result.stdout.splitlines() if line.strip())
|
|
264
|
+
last_commit: datetime | None = None
|
|
265
|
+
log_result = _run_git(project_path, ["log", "-1", "--format=%ct"])
|
|
266
|
+
if log_result is not None and log_result.returncode == 0:
|
|
267
|
+
raw_timestamp = log_result.stdout.strip()
|
|
268
|
+
if raw_timestamp:
|
|
269
|
+
try:
|
|
270
|
+
last_commit = datetime.fromtimestamp(int(raw_timestamp), tz=timezone.utc)
|
|
271
|
+
except (ValueError, OverflowError, OSError):
|
|
272
|
+
last_commit = None
|
|
273
|
+
status: GitStatus = "dirty" if changed else "clean"
|
|
274
|
+
return GitInfo(status=status, changed=changed, last_commit=last_commit)
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def filter_projects_by_age(
|
|
278
|
+
projects: list[Project], older_than_days: int, now: datetime | None = None
|
|
279
|
+
) -> list[Project]:
|
|
280
|
+
if older_than_days <= 0:
|
|
281
|
+
return projects
|
|
282
|
+
reference = now or datetime.now(timezone.utc)
|
|
283
|
+
cutoff = reference - timedelta(days=older_than_days)
|
|
284
|
+
return [
|
|
285
|
+
project
|
|
286
|
+
for project in projects
|
|
287
|
+
if project.git.last_commit is not None and project.git.last_commit < cutoff
|
|
288
|
+
]
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _display_name(path: Path) -> str:
|
|
292
|
+
return path.name or str(path)
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def _relative_label(path: Path, root: Path) -> str:
|
|
296
|
+
try:
|
|
297
|
+
relative = path.relative_to(root)
|
|
298
|
+
except ValueError:
|
|
299
|
+
return str(path)
|
|
300
|
+
label = relative.as_posix()
|
|
301
|
+
return label if label != "." else _display_name(path)
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def scan(
|
|
305
|
+
root: Path, min_size_mb: float, older_than_days: int, error_console: Console
|
|
306
|
+
) -> ScanResult:
|
|
307
|
+
try:
|
|
308
|
+
with os.scandir(root) as entries:
|
|
309
|
+
for _entry in entries:
|
|
310
|
+
break
|
|
311
|
+
except OSError as exc:
|
|
312
|
+
error_console.print(f"[red]Cannot access {escape(str(root))}:[/red] {escape(str(exc))}")
|
|
313
|
+
return ScanResult(projects=[], scanned_projects=0)
|
|
314
|
+
targets = discover_targets(root)
|
|
315
|
+
min_size_bytes = int(min_size_mb * 1024 * 1024)
|
|
316
|
+
projects: list[Project] = []
|
|
317
|
+
with Progress(
|
|
318
|
+
SpinnerColumn(style="cyan"),
|
|
319
|
+
TextColumn("{task.description}"),
|
|
320
|
+
BarColumn(bar_width=24, complete_style="green", finished_style="green"),
|
|
321
|
+
TextColumn("[dim]{task.completed}/{task.total}[/dim]"),
|
|
322
|
+
TimeElapsedColumn(),
|
|
323
|
+
console=error_console,
|
|
324
|
+
transient=True,
|
|
325
|
+
disable=not error_console.is_terminal,
|
|
326
|
+
) as progress:
|
|
327
|
+
scan_task = progress.add_task("Scanning projects", total=len(targets))
|
|
328
|
+
for target in targets:
|
|
329
|
+
label = _relative_label(target.path, root)
|
|
330
|
+
progress.update(scan_task, description=f"Scanning {escape(label)}")
|
|
331
|
+
heavy_dirs = find_heavy_dirs(target.path, target.recursive, min_size_bytes)
|
|
332
|
+
if heavy_dirs:
|
|
333
|
+
projects.append(Project(path=target.path, heavy_dirs=heavy_dirs))
|
|
334
|
+
progress.advance(scan_task)
|
|
335
|
+
projects.sort(key=lambda item: item.total_size, reverse=True)
|
|
336
|
+
if projects:
|
|
337
|
+
git_task = progress.add_task("Reading Git status", total=len(projects))
|
|
338
|
+
for project in projects:
|
|
339
|
+
label = _relative_label(project.path, root)
|
|
340
|
+
progress.update(git_task, description=f"Git {escape(label)}")
|
|
341
|
+
project.git = read_git_info(project.path)
|
|
342
|
+
progress.advance(git_task)
|
|
343
|
+
projects = filter_projects_by_age(projects, older_than_days)
|
|
344
|
+
return ScanResult(projects=projects, scanned_projects=len(targets))
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def _git_cell(info: GitInfo) -> Text:
|
|
348
|
+
if info.status == "clean":
|
|
349
|
+
return Text("clean", style="green")
|
|
350
|
+
if info.status == "dirty":
|
|
351
|
+
cell = Text("dirty", style="bold red")
|
|
352
|
+
cell.append(f" ({info.changed})", style="dim")
|
|
353
|
+
return cell
|
|
354
|
+
if info.status == "error":
|
|
355
|
+
return Text("error", style="yellow")
|
|
356
|
+
return Text("no git", style="dim")
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def _commit_cell(info: GitInfo) -> Text:
|
|
360
|
+
if info.last_commit is not None:
|
|
361
|
+
return Text(info.last_commit.astimezone().strftime("%Y-%m-%d"), style="dim")
|
|
362
|
+
if info.status == "no-git":
|
|
363
|
+
return Text("—", style="dim")
|
|
364
|
+
return Text("no commits", style="dim")
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
def _artifact_label(artifact: HeavyDir, project_path: Path) -> str:
|
|
368
|
+
try:
|
|
369
|
+
relative = artifact.path.relative_to(project_path)
|
|
370
|
+
except ValueError:
|
|
371
|
+
relative = artifact.path
|
|
372
|
+
return relative.as_posix()
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def _heavy_cell(project: Project, limit: int = 6) -> Text:
|
|
376
|
+
cell = Text()
|
|
377
|
+
visible = project.heavy_dirs[:limit]
|
|
378
|
+
for index, artifact in enumerate(visible):
|
|
379
|
+
if index:
|
|
380
|
+
cell.append("\n")
|
|
381
|
+
cell.append(_artifact_label(artifact, project.path), style="magenta")
|
|
382
|
+
cell.append(" ")
|
|
383
|
+
cell.append(format_size(artifact.size), style="dim")
|
|
384
|
+
remaining = len(project.heavy_dirs) - len(visible)
|
|
385
|
+
if remaining > 0:
|
|
386
|
+
cell.append(f"\n… +{remaining} more", style="dim")
|
|
387
|
+
return cell
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def render_report(
|
|
391
|
+
result: ScanResult,
|
|
392
|
+
root: Path,
|
|
393
|
+
min_size_mb: float,
|
|
394
|
+
older_than_days: int,
|
|
395
|
+
console: Console,
|
|
396
|
+
) -> None:
|
|
397
|
+
total_bytes = sum(project.total_size for project in result.projects)
|
|
398
|
+
total_dirs = sum(len(project.heavy_dirs) for project in result.projects)
|
|
399
|
+
console.print()
|
|
400
|
+
console.print(f"[bold]DeadWeight[/bold] [dim]v{__version__}[/dim]")
|
|
401
|
+
console.print(
|
|
402
|
+
f"[dim]{pluralize(result.scanned_projects, 'target')} scanned in "
|
|
403
|
+
f"{escape(str(root))}[/dim]"
|
|
404
|
+
)
|
|
405
|
+
if min_size_mb > 0:
|
|
406
|
+
console.print(f"[dim]Filter: artifacts ≥ {min_size_mb:g} MB[/dim]")
|
|
407
|
+
if older_than_days > 0:
|
|
408
|
+
console.print(
|
|
409
|
+
f"[dim]Filter: last commit older than "
|
|
410
|
+
f"{pluralize(older_than_days, 'day')}[/dim]"
|
|
411
|
+
)
|
|
412
|
+
console.print()
|
|
413
|
+
if not result.projects:
|
|
414
|
+
console.print("[bold green]No heavy artifacts found.[/bold green]")
|
|
415
|
+
return
|
|
416
|
+
table = Table(
|
|
417
|
+
box=box.ROUNDED,
|
|
418
|
+
header_style="bold cyan",
|
|
419
|
+
border_style="grey37",
|
|
420
|
+
expand=True,
|
|
421
|
+
)
|
|
422
|
+
table.add_column("Project", style="bold", overflow="fold", max_width=24)
|
|
423
|
+
table.add_column("Git", no_wrap=True)
|
|
424
|
+
table.add_column("Last commit", no_wrap=True)
|
|
425
|
+
table.add_column("Heavy artifacts", overflow="fold", ratio=2, min_width=16)
|
|
426
|
+
table.add_column("Size", justify="right", no_wrap=True)
|
|
427
|
+
for project in result.projects:
|
|
428
|
+
table.add_row(
|
|
429
|
+
_display_name(project.path),
|
|
430
|
+
_git_cell(project.git),
|
|
431
|
+
_commit_cell(project.git),
|
|
432
|
+
_heavy_cell(project),
|
|
433
|
+
Text(format_size(project.total_size), style="bold"),
|
|
434
|
+
)
|
|
435
|
+
table.add_section()
|
|
436
|
+
table.add_row(
|
|
437
|
+
Text("TOTAL", style="bold"),
|
|
438
|
+
Text(""),
|
|
439
|
+
Text(""),
|
|
440
|
+
Text(
|
|
441
|
+
f"{pluralize(total_dirs, 'dir')} · "
|
|
442
|
+
f"{pluralize(len(result.projects), 'project')}",
|
|
443
|
+
style="dim",
|
|
444
|
+
),
|
|
445
|
+
Text(format_size(total_bytes), style="bold red"),
|
|
446
|
+
)
|
|
447
|
+
console.print(table)
|
|
448
|
+
console.print()
|
|
449
|
+
console.print(f"[bold]Total junk:[/bold] [red]{format_size(total_bytes)}[/red]")
|
|
450
|
+
console.print(
|
|
451
|
+
f"[bold green]Can free:[/bold green] "
|
|
452
|
+
f"[green]{format_reclaim(total_bytes)}[/green]"
|
|
453
|
+
)
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
def _validate_clean_target(target: Path, root: Path) -> None:
|
|
457
|
+
if target.name not in HEAVY_DIR_NAMES and not _is_venv_dir(target):
|
|
458
|
+
raise OSError(f"refusing to delete unexpected directory: {target}")
|
|
459
|
+
if _is_link_path(target):
|
|
460
|
+
raise OSError(f"refusing to delete link or reparse point: {target}")
|
|
461
|
+
resolved = target.resolve(strict=True)
|
|
462
|
+
if not resolved.is_relative_to(root):
|
|
463
|
+
raise OSError(f"refusing to delete outside scan root: {resolved}")
|
|
464
|
+
if not resolved.is_dir():
|
|
465
|
+
raise OSError(f"not a directory: {resolved}")
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
def _retry_with_write_permission(
|
|
469
|
+
function: Callable[..., Any],
|
|
470
|
+
path: str,
|
|
471
|
+
_exc_info: tuple[type[BaseException], BaseException, TracebackType],
|
|
472
|
+
) -> None:
|
|
473
|
+
os.chmod(path, stat.S_IWRITE)
|
|
474
|
+
function(path)
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
def _artifact_entries(projects: list[Project]) -> list[tuple[Project, HeavyDir]]:
|
|
478
|
+
return [
|
|
479
|
+
(project, artifact)
|
|
480
|
+
for project in projects
|
|
481
|
+
for artifact in project.heavy_dirs
|
|
482
|
+
]
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
def parse_selection(raw: str, count: int) -> list[int]:
|
|
486
|
+
text = raw.strip().lower()
|
|
487
|
+
if not text:
|
|
488
|
+
return []
|
|
489
|
+
if text == "all":
|
|
490
|
+
return list(range(1, count + 1))
|
|
491
|
+
selected: set[int] = set()
|
|
492
|
+
for chunk in text.split(","):
|
|
493
|
+
token = chunk.strip()
|
|
494
|
+
if not token:
|
|
495
|
+
raise ValueError("empty item in selection")
|
|
496
|
+
if "-" in token:
|
|
497
|
+
parts = [part.strip() for part in token.split("-")]
|
|
498
|
+
if len(parts) != 2 or not all(part.isdigit() for part in parts):
|
|
499
|
+
raise ValueError(f"invalid range: {token}")
|
|
500
|
+
start, end = int(parts[0]), int(parts[1])
|
|
501
|
+
if start > end:
|
|
502
|
+
raise ValueError(f"range starts after it ends: {token}")
|
|
503
|
+
if start < 1 or end > count:
|
|
504
|
+
raise ValueError(f"numbers must be between 1 and {count}")
|
|
505
|
+
selected.update(range(start, end + 1))
|
|
506
|
+
else:
|
|
507
|
+
if not token.isdigit():
|
|
508
|
+
raise ValueError(f"not a number or range: {token}")
|
|
509
|
+
number = int(token)
|
|
510
|
+
if number < 1 or number > count:
|
|
511
|
+
raise ValueError(f"numbers must be between 1 and {count}")
|
|
512
|
+
selected.add(number)
|
|
513
|
+
return sorted(selected)
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
def select_artifacts(projects: list[Project], console: Console) -> list[HeavyDir] | None:
|
|
517
|
+
entries = _artifact_entries(projects)
|
|
518
|
+
if not entries:
|
|
519
|
+
return []
|
|
520
|
+
table = Table(
|
|
521
|
+
box=box.ROUNDED,
|
|
522
|
+
header_style="bold cyan",
|
|
523
|
+
border_style="grey37",
|
|
524
|
+
expand=True,
|
|
525
|
+
)
|
|
526
|
+
table.add_column("#", justify="right", style="cyan", no_wrap=True)
|
|
527
|
+
table.add_column("Project", style="bold", overflow="fold", max_width=24)
|
|
528
|
+
table.add_column("Artifact", style="magenta", overflow="fold", ratio=2, min_width=12)
|
|
529
|
+
table.add_column("Size", justify="right", no_wrap=True)
|
|
530
|
+
for index, (project, artifact) in enumerate(entries, start=1):
|
|
531
|
+
table.add_row(
|
|
532
|
+
str(index),
|
|
533
|
+
_display_name(project.path),
|
|
534
|
+
_artifact_label(artifact, project.path),
|
|
535
|
+
format_size(artifact.size),
|
|
536
|
+
)
|
|
537
|
+
console.print()
|
|
538
|
+
console.print("[bold]Select directories to delete[/bold]")
|
|
539
|
+
console.print(
|
|
540
|
+
"[dim]Enter comma-separated numbers, ranges (for example 1, 3-5), "
|
|
541
|
+
"or all. Leave empty to cancel.[/dim]"
|
|
542
|
+
)
|
|
543
|
+
console.print()
|
|
544
|
+
console.print(table)
|
|
545
|
+
console.print()
|
|
546
|
+
while True:
|
|
547
|
+
try:
|
|
548
|
+
raw = Prompt.ask("Selection", console=console)
|
|
549
|
+
except (EOFError, KeyboardInterrupt):
|
|
550
|
+
console.print("\n[yellow]Cleanup cancelled.[/yellow]")
|
|
551
|
+
return None
|
|
552
|
+
try:
|
|
553
|
+
numbers = parse_selection(raw, len(entries))
|
|
554
|
+
except ValueError as exc:
|
|
555
|
+
console.print(f"[red]Invalid selection:[/red] {escape(str(exc))}")
|
|
556
|
+
continue
|
|
557
|
+
if not numbers:
|
|
558
|
+
console.print("[yellow]No selection. Cleanup cancelled.[/yellow]")
|
|
559
|
+
return None
|
|
560
|
+
artifacts = [entries[number - 1][1] for number in numbers]
|
|
561
|
+
console.print(
|
|
562
|
+
f"[dim]{pluralize(len(artifacts), 'directory', 'directories')} selected · "
|
|
563
|
+
f"{format_size(sum(item.size for item in artifacts))}[/dim]"
|
|
564
|
+
)
|
|
565
|
+
return artifacts
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
def clean_artifacts(artifacts: list[HeavyDir], root: Path, console: Console) -> int:
|
|
569
|
+
total_bytes = sum(item.size for item in artifacts)
|
|
570
|
+
if not artifacts:
|
|
571
|
+
console.print("[green]Nothing to clean.[/green]")
|
|
572
|
+
return 0
|
|
573
|
+
console.print()
|
|
574
|
+
try:
|
|
575
|
+
confirmed = Confirm.ask(
|
|
576
|
+
f"Delete [bold]{pluralize(len(artifacts), 'directory', 'directories')}[/bold] "
|
|
577
|
+
f"and free [bold]{format_size(total_bytes)}[/bold]?",
|
|
578
|
+
default=False,
|
|
579
|
+
console=console,
|
|
580
|
+
)
|
|
581
|
+
except (EOFError, KeyboardInterrupt):
|
|
582
|
+
console.print("[yellow]Cleanup cancelled.[/yellow]")
|
|
583
|
+
return 0
|
|
584
|
+
if not confirmed:
|
|
585
|
+
console.print("[yellow]Cleanup cancelled.[/yellow]")
|
|
586
|
+
return 0
|
|
587
|
+
removed = 0
|
|
588
|
+
freed_bytes = 0
|
|
589
|
+
failures: list[tuple[Path, str]] = []
|
|
590
|
+
for artifact in artifacts:
|
|
591
|
+
try:
|
|
592
|
+
_validate_clean_target(artifact.path, root)
|
|
593
|
+
shutil.rmtree(artifact.path, onerror=_retry_with_write_permission)
|
|
594
|
+
removed += 1
|
|
595
|
+
freed_bytes += artifact.size
|
|
596
|
+
except OSError as exc:
|
|
597
|
+
failures.append((artifact.path, str(exc)))
|
|
598
|
+
console.print()
|
|
599
|
+
if failures:
|
|
600
|
+
summary = (
|
|
601
|
+
f"[bold red]Removed {removed} of "
|
|
602
|
+
f"{pluralize(len(artifacts), 'directory', 'directories')}.[/bold red]"
|
|
603
|
+
)
|
|
604
|
+
else:
|
|
605
|
+
summary = f"[bold green]Removed {pluralize(removed, 'directory', 'directories')}.[/bold green]"
|
|
606
|
+
console.print(f"{summary} Freed [green]{format_size(freed_bytes)}[/green].")
|
|
607
|
+
for path, message in failures:
|
|
608
|
+
console.print(
|
|
609
|
+
f"[red]Failed[/red] {escape(str(path))}: [dim]{escape(message)}[/dim]"
|
|
610
|
+
)
|
|
611
|
+
return 1 if failures else 0
|
|
612
|
+
|
|
613
|
+
|
|
614
|
+
def build_json_report(
|
|
615
|
+
result: ScanResult, root: Path, min_size_mb: float, older_than_days: int
|
|
616
|
+
) -> dict[str, Any]:
|
|
617
|
+
projects_payload: list[dict[str, Any]] = []
|
|
618
|
+
total_bytes = 0
|
|
619
|
+
total_dirs = 0
|
|
620
|
+
for project in result.projects:
|
|
621
|
+
total_bytes += project.total_size
|
|
622
|
+
total_dirs += len(project.heavy_dirs)
|
|
623
|
+
projects_payload.append(
|
|
624
|
+
{
|
|
625
|
+
"name": _display_name(project.path),
|
|
626
|
+
"path": str(project.path),
|
|
627
|
+
"git": {
|
|
628
|
+
"status": project.git.status,
|
|
629
|
+
"changed_files": project.git.changed,
|
|
630
|
+
"last_commit": (
|
|
631
|
+
project.git.last_commit.isoformat()
|
|
632
|
+
if project.git.last_commit is not None
|
|
633
|
+
else None
|
|
634
|
+
),
|
|
635
|
+
"error": project.git.error,
|
|
636
|
+
},
|
|
637
|
+
"heavy_dirs": [
|
|
638
|
+
{
|
|
639
|
+
"path": str(artifact.path),
|
|
640
|
+
"name": artifact.path.name,
|
|
641
|
+
"size_bytes": artifact.size,
|
|
642
|
+
"size": format_size(artifact.size),
|
|
643
|
+
}
|
|
644
|
+
for artifact in project.heavy_dirs
|
|
645
|
+
],
|
|
646
|
+
"total_size_bytes": project.total_size,
|
|
647
|
+
"total_size": format_size(project.total_size),
|
|
648
|
+
}
|
|
649
|
+
)
|
|
650
|
+
return {
|
|
651
|
+
"tool": "deadweight",
|
|
652
|
+
"version": __version__,
|
|
653
|
+
"scanned_path": str(root),
|
|
654
|
+
"scanned_projects": result.scanned_projects,
|
|
655
|
+
"generated_at": datetime.now(timezone.utc).isoformat(),
|
|
656
|
+
"min_size_mb": min_size_mb,
|
|
657
|
+
"older_than_days": older_than_days,
|
|
658
|
+
"projects": projects_payload,
|
|
659
|
+
"totals": {
|
|
660
|
+
"projects": len(result.projects),
|
|
661
|
+
"heavy_dirs": total_dirs,
|
|
662
|
+
"total_size_bytes": total_bytes,
|
|
663
|
+
"total_size": format_size(total_bytes),
|
|
664
|
+
"reclaimable_gb": round(total_bytes / (1024 ** 3), 2),
|
|
665
|
+
},
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
|
|
669
|
+
def write_json(payload: dict[str, Any]) -> None:
|
|
670
|
+
text = json.dumps(payload, indent=2, ensure_ascii=False) + "\n"
|
|
671
|
+
buffer = getattr(sys.stdout, "buffer", None)
|
|
672
|
+
if buffer is not None:
|
|
673
|
+
buffer.write(text.encode("utf-8"))
|
|
674
|
+
buffer.flush()
|
|
675
|
+
else:
|
|
676
|
+
sys.stdout.write(text)
|
|
677
|
+
|
|
678
|
+
|
|
679
|
+
def _non_negative_float(value: str) -> float:
|
|
680
|
+
try:
|
|
681
|
+
parsed = float(value)
|
|
682
|
+
except ValueError as exc:
|
|
683
|
+
raise argparse.ArgumentTypeError(f"invalid number: {value}") from exc
|
|
684
|
+
if not math.isfinite(parsed):
|
|
685
|
+
raise argparse.ArgumentTypeError(f"invalid number: {value}")
|
|
686
|
+
if parsed < 0:
|
|
687
|
+
raise argparse.ArgumentTypeError("must be zero or greater")
|
|
688
|
+
return parsed
|
|
689
|
+
|
|
690
|
+
|
|
691
|
+
def _non_negative_int(value: str) -> int:
|
|
692
|
+
try:
|
|
693
|
+
parsed = int(value)
|
|
694
|
+
except ValueError as exc:
|
|
695
|
+
raise argparse.ArgumentTypeError(f"invalid integer: {value}") from exc
|
|
696
|
+
if parsed < 0:
|
|
697
|
+
raise argparse.ArgumentTypeError("must be zero or greater")
|
|
698
|
+
return parsed
|
|
699
|
+
|
|
700
|
+
|
|
701
|
+
def _existing_directory(value: str) -> Path:
|
|
702
|
+
path = Path(value).expanduser()
|
|
703
|
+
try:
|
|
704
|
+
resolved = path.resolve(strict=True)
|
|
705
|
+
except OSError as exc:
|
|
706
|
+
raise argparse.ArgumentTypeError(f"invalid path: {value}") from exc
|
|
707
|
+
if not resolved.is_dir():
|
|
708
|
+
raise argparse.ArgumentTypeError(f"not a directory: {value}")
|
|
709
|
+
return resolved
|
|
710
|
+
|
|
711
|
+
|
|
712
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
713
|
+
parser = argparse.ArgumentParser(
|
|
714
|
+
prog="deadweight",
|
|
715
|
+
description=(
|
|
716
|
+
"Scan a directory for heavy development artifacts (venv, node_modules, "
|
|
717
|
+
"caches, builds) and report Git status for each project."
|
|
718
|
+
),
|
|
719
|
+
epilog=(
|
|
720
|
+
"examples:\n"
|
|
721
|
+
" deadweight\n"
|
|
722
|
+
" deadweight ~/projects\n"
|
|
723
|
+
" deadweight ~/projects --min-size 100\n"
|
|
724
|
+
" deadweight ~/projects --older-than 180\n"
|
|
725
|
+
" deadweight ~/projects --json > report.json\n"
|
|
726
|
+
" deadweight ~/projects --clean\n"
|
|
727
|
+
" deadweight ~/projects --clean --select"
|
|
728
|
+
),
|
|
729
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
730
|
+
)
|
|
731
|
+
parser.add_argument(
|
|
732
|
+
"path",
|
|
733
|
+
nargs="?",
|
|
734
|
+
default=".",
|
|
735
|
+
type=_existing_directory,
|
|
736
|
+
help="directory to scan (default: current directory)",
|
|
737
|
+
)
|
|
738
|
+
parser.add_argument(
|
|
739
|
+
"--min-size",
|
|
740
|
+
metavar="MB",
|
|
741
|
+
type=_non_negative_float,
|
|
742
|
+
default=0.0,
|
|
743
|
+
help="only report heavy directories of at least this size in MB (default: 0)",
|
|
744
|
+
)
|
|
745
|
+
parser.add_argument(
|
|
746
|
+
"--older-than",
|
|
747
|
+
metavar="DAYS",
|
|
748
|
+
type=_non_negative_int,
|
|
749
|
+
default=0,
|
|
750
|
+
help="only report projects whose last commit is older than DAYS days (default: 0)",
|
|
751
|
+
)
|
|
752
|
+
parser.add_argument(
|
|
753
|
+
"--clean",
|
|
754
|
+
action="store_true",
|
|
755
|
+
help="interactively delete found artifacts after confirmation",
|
|
756
|
+
)
|
|
757
|
+
parser.add_argument(
|
|
758
|
+
"--select",
|
|
759
|
+
action="store_true",
|
|
760
|
+
help="choose which artifacts to delete from a numbered list (requires --clean)",
|
|
761
|
+
)
|
|
762
|
+
parser.add_argument(
|
|
763
|
+
"--json",
|
|
764
|
+
dest="as_json",
|
|
765
|
+
action="store_true",
|
|
766
|
+
help="print the report as JSON",
|
|
767
|
+
)
|
|
768
|
+
parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
|
769
|
+
return parser
|
|
770
|
+
|
|
771
|
+
|
|
772
|
+
def main(argv: list[str] | None = None) -> int:
|
|
773
|
+
parser = build_parser()
|
|
774
|
+
args = parser.parse_args(argv)
|
|
775
|
+
if args.clean and args.as_json:
|
|
776
|
+
parser.error("--clean cannot be combined with --json")
|
|
777
|
+
if args.select and not args.clean:
|
|
778
|
+
parser.error("--select requires --clean")
|
|
779
|
+
console = Console()
|
|
780
|
+
error_console = Console(stderr=True)
|
|
781
|
+
root: Path = args.path
|
|
782
|
+
result = scan(root, args.min_size, args.older_than, error_console)
|
|
783
|
+
if args.as_json:
|
|
784
|
+
payload = build_json_report(result, root, args.min_size, args.older_than)
|
|
785
|
+
write_json(payload)
|
|
786
|
+
return 0
|
|
787
|
+
render_report(result, root, args.min_size, args.older_than, console)
|
|
788
|
+
if args.clean:
|
|
789
|
+
if args.select:
|
|
790
|
+
selected = select_artifacts(result.projects, console)
|
|
791
|
+
if selected is None:
|
|
792
|
+
return 0
|
|
793
|
+
else:
|
|
794
|
+
selected = [artifact for _, artifact in _artifact_entries(result.projects)]
|
|
795
|
+
return clean_artifacts(selected, root, console)
|
|
796
|
+
return 0
|
|
797
|
+
|
|
798
|
+
|
|
799
|
+
if __name__ == "__main__":
|
|
800
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: deadweight-cli
|
|
3
|
+
Version: 1.0.2
|
|
4
|
+
Summary: Find and clean heavy build artifacts and virtual environments across your projects.
|
|
5
|
+
Author: DeadWeight contributors
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/ASCTeam-prog/deadweight
|
|
8
|
+
Project-URL: Repository, https://github.com/ASCTeam-prog/deadweight
|
|
9
|
+
Project-URL: Issues, https://github.com/ASCTeam-prog/deadweight/issues
|
|
10
|
+
Project-URL: Releases, https://github.com/ASCTeam-prog/deadweight/releases
|
|
11
|
+
Keywords: cleanup,cli,developer-tools,disk-space,venv,node-modules
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Environment :: Console
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
21
|
+
Classifier: Topic :: Software Development :: Build Tools
|
|
22
|
+
Classifier: Topic :: System :: Filesystems
|
|
23
|
+
Classifier: Topic :: Utilities
|
|
24
|
+
Requires-Python: >=3.11
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
License-File: LICENSE
|
|
27
|
+
Requires-Dist: rich>=13.0
|
|
28
|
+
Dynamic: license-file
|
|
29
|
+
|
|
30
|
+
<p align="center">
|
|
31
|
+
<a href="https://www.python.org/"><img alt="Python 3.11+" src="https://img.shields.io/badge/Python-3.11%2B-3776AB?style=flat-square&logo=python&logoColor=white"></a>
|
|
32
|
+
<a href="LICENSE"><img alt="License: MIT" src="https://img.shields.io/badge/License-MIT-2ea44f?style=flat-square"></a>
|
|
33
|
+
<a href="#usage"><img alt="CLI" src="https://img.shields.io/badge/CLI-Rich-8A2BE2?style=flat-square&logo=gnubash&logoColor=white"></a>
|
|
34
|
+
<a href="#safety"><img alt="Zero-Risk" src="https://img.shields.io/badge/Zero--Risk-read--only%20by%20default-0ea5e9?style=flat-square"></a>
|
|
35
|
+
</p>
|
|
36
|
+
|
|
37
|
+
# DeadWeight
|
|
38
|
+
|
|
39
|
+
**Find the dead weight in your projects before it eats your disk.**
|
|
40
|
+
|
|
41
|
+
DeadWeight is a small CLI for developers who collect virtual environments, `node_modules`, build folders, and caches across dozens of repositories. Point it at a directory, and it shows what is heavy, how stale each project looks, and how much space you can reclaim.
|
|
42
|
+
|
|
43
|
+
<p align="center">
|
|
44
|
+
<img src="https://raw.githubusercontent.com/ASCTeam-prog/deadweight/main/assets/1.png" alt="DeadWeight terminal report showing heavy artifacts, Git status, and reclaimable space" width="100%">
|
|
45
|
+
</p>
|
|
46
|
+
|
|
47
|
+
## Features
|
|
48
|
+
|
|
49
|
+
- Scans a directory tree for heavy artifacts: `venv`, `.venv`, `node_modules`, `__pycache__`, `.pytest_cache`, `dist`, `build`, `.pio`.
|
|
50
|
+
- Detects custom virtual environments by their `pyvenv.cfg` marker, even when the folder is named `my_env` or `atlas vpn env`.
|
|
51
|
+
- Reports Git state for every project with reported artifacts: clean, dirty (with a change count), no repository, or Git error.
|
|
52
|
+
- Shows the date of the last commit so you can spot abandoned projects.
|
|
53
|
+
- Rich, colorized report with per-project and total reclaimable space.
|
|
54
|
+
- Progress bar while scanning, written to `stderr` so machine-readable output stays clean.
|
|
55
|
+
- `--min-size` filter to ignore the small stuff.
|
|
56
|
+
- `--older-than DAYS` filter to focus on abandoned projects with stale Git history.
|
|
57
|
+
- `--json` output for dashboards, scripts, and cron jobs.
|
|
58
|
+
- `--clean` is opt-in and always asks for explicit confirmation first.
|
|
59
|
+
- `--clean --select` shows a numbered list and deletes only the artifacts you choose.
|
|
60
|
+
- Read-only by default. Symlinks and Windows junctions are never followed.
|
|
61
|
+
|
|
62
|
+
## Requirements
|
|
63
|
+
|
|
64
|
+
- Python 3.11 or newer
|
|
65
|
+
- Git (optional, but required for repository status)
|
|
66
|
+
- [rich](https://github.com/Textualize/rich) (installed automatically)
|
|
67
|
+
|
|
68
|
+
## Installation
|
|
69
|
+
|
|
70
|
+
From PyPI:
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
pipx install deadweight-cli
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
The package is named `deadweight-cli` and installs the `deadweight` command.
|
|
77
|
+
|
|
78
|
+
From a source checkout:
|
|
79
|
+
|
|
80
|
+
```bash
|
|
81
|
+
git clone https://github.com/ASCTeam-prog/deadweight.git
|
|
82
|
+
cd deadweight
|
|
83
|
+
pipx install .
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
Or install it into the current environment in editable mode:
|
|
87
|
+
|
|
88
|
+
```bash
|
|
89
|
+
pip install -e .
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
The package exposes a single `deadweight` command:
|
|
93
|
+
|
|
94
|
+
```bash
|
|
95
|
+
deadweight --help
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
## Binary Downloads
|
|
99
|
+
|
|
100
|
+
Prebuilt one-file binaries for every supported platform are attached to each [GitHub Release](https://github.com/ASCTeam-prog/deadweight/releases/latest):
|
|
101
|
+
|
|
102
|
+
| Platform | Download |
|
|
103
|
+
| --- | --- |
|
|
104
|
+
| Windows x64 | [`deadweight-windows-x64.exe`](https://github.com/ASCTeam-prog/deadweight/releases/latest/download/deadweight-windows-x64.exe) |
|
|
105
|
+
| Linux x64 | [`deadweight-linux-x64`](https://github.com/ASCTeam-prog/deadweight/releases/latest/download/deadweight-linux-x64) |
|
|
106
|
+
| macOS arm64 | [`deadweight-macos-arm64`](https://github.com/ASCTeam-prog/deadweight/releases/latest/download/deadweight-macos-arm64) |
|
|
107
|
+
|
|
108
|
+
On Linux and macOS, make the downloaded file executable with `chmod +x <file>` before running it. If macOS Gatekeeper blocks the unsigned binary, remove the quarantine flag with `xattr -d com.apple.quarantine <file>`.
|
|
109
|
+
|
|
110
|
+
## Usage
|
|
111
|
+
|
|
112
|
+
```text
|
|
113
|
+
deadweight [PATH] [--min-size MB] [--older-than DAYS] [--clean] [--select] [--json]
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
| Option | Description |
|
|
117
|
+
| --- | --- |
|
|
118
|
+
| `PATH` | Directory to scan. Defaults to the current directory. |
|
|
119
|
+
| `--min-size MB` | Only report heavy directories of at least this size (in MB). |
|
|
120
|
+
| `--older-than DAYS` | Only report projects whose last commit is older than this many days. |
|
|
121
|
+
| `--clean` | After the report, delete the found artifacts after confirmation. |
|
|
122
|
+
| `--select` | With `--clean`, show a numbered list and delete only the selected artifacts. |
|
|
123
|
+
| `--json` | Print the report as JSON instead of a table. |
|
|
124
|
+
| `--version` | Print the version and exit. |
|
|
125
|
+
|
|
126
|
+
### Scan the current directory
|
|
127
|
+
|
|
128
|
+
```bash
|
|
129
|
+
deadweight
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
### Scan a projects folder
|
|
133
|
+
|
|
134
|
+
```bash
|
|
135
|
+
deadweight ~/projects
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
### Only look at artifacts larger than 100 MB
|
|
139
|
+
|
|
140
|
+
```bash
|
|
141
|
+
deadweight ~/projects --min-size 100
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
### Only look at abandoned projects
|
|
145
|
+
|
|
146
|
+
```bash
|
|
147
|
+
deadweight ~/projects --older-than 180
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
This includes only projects whose last commit is older than 180 days. Projects without a Git repository, without commits, or with Git errors are excluded while the filter is active. The default value is `0`, which disables the filter. It also applies to `--json`, `--clean`, and `--select`.
|
|
151
|
+
|
|
152
|
+
### Export a machine-readable report
|
|
153
|
+
|
|
154
|
+
```bash
|
|
155
|
+
deadweight ~/projects --json > report.json
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
### Clean up interactively
|
|
159
|
+
|
|
160
|
+
```bash
|
|
161
|
+
deadweight ~/projects --clean
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
`--clean` prints the report first, then asks once to confirm deletion of everything that was found:
|
|
165
|
+
|
|
166
|
+
```text
|
|
167
|
+
Delete 14 directories and free 6.4 GB? [y/n] (n):
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
Nothing is deleted unless you answer `y`. Every target is re-checked before removal: it must still be a known artifact directory or a valid virtual environment, and it must live inside the scanned root.
|
|
171
|
+
|
|
172
|
+
### Choose exactly what to clean
|
|
173
|
+
|
|
174
|
+
```bash
|
|
175
|
+
deadweight ~/projects --clean --select
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
`--select` adds a numbered list of every artifact with its project and size. Enter one or more numbers separated by commas, a range such as `3-5`, a combination such as `1, 3-5`, or `all`. An empty answer cancels the cleanup.
|
|
179
|
+
|
|
180
|
+
<p align="center">
|
|
181
|
+
<img src="https://raw.githubusercontent.com/ASCTeam-prog/deadweight/main/assets/2.png" alt="DeadWeight --clean --select showing a numbered artifact list and the selection prompt" width="100%">
|
|
182
|
+
</p>
|
|
183
|
+
|
|
184
|
+
The final confirmation is still required, and only the selected directories are removed.
|
|
185
|
+
|
|
186
|
+
## Sample output
|
|
187
|
+
|
|
188
|
+
```text
|
|
189
|
+
DeadWeight v1.0.2
|
|
190
|
+
4 targets scanned in /home/dev/projects
|
|
191
|
+
|
|
192
|
+
┌───────────────┬───────────┬─────────────┬─────────────────────────────────────────────┬──────────┐
|
|
193
|
+
│ Project │ Git │ Last commit │ Heavy artifacts │ Size │
|
|
194
|
+
├───────────────┼───────────┼─────────────┼─────────────────────────────────────────────┼──────────┤
|
|
195
|
+
│ data-pipeline │ no git │ — │ .venv 3.1 GB │ 3.3 GB │
|
|
196
|
+
│ │ │ │ build 220.8 MB │ │
|
|
197
|
+
│ legacy-api │ dirty (3) │ 2024-11-02 │ .venv 1.2 GB │ 1.2 GB │
|
|
198
|
+
│ │ │ │ __pycache__ 12.4 MB │ │
|
|
199
|
+
│ web-dashboard │ clean │ 2026-05-18 │ node_modules 840.1 MB │ 885.8 MB │
|
|
200
|
+
│ │ │ │ dist 45.7 MB │ │
|
|
201
|
+
├───────────────┼───────────┼─────────────┼─────────────────────────────────────────────┼──────────┤
|
|
202
|
+
│ TOTAL │ │ │ 6 dirs · 3 projects │ 5.4 GB │
|
|
203
|
+
└───────────────┴───────────┴─────────────┴─────────────────────────────────────────────┴──────────┘
|
|
204
|
+
|
|
205
|
+
Total junk: 5.4 GB
|
|
206
|
+
Can free: 5.39 GB
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
## How projects are detected
|
|
210
|
+
|
|
211
|
+
- If the scanned directory is a Git repository, it is treated as **one project**. Artifacts are searched recursively, but `.git`, symlinks, and junctions are skipped.
|
|
212
|
+
- Otherwise, every first-level subdirectory is treated as a separate project.
|
|
213
|
+
- Any directory containing a `pyvenv.cfg` file is treated as a virtual environment, even if its name is not `venv` or `.venv` (for example, `my_env` or `atlas vpn env`).
|
|
214
|
+
- Artifacts found directly in the scanned root, including custom environments, are reported under the root folder's own name instead of being treated as projects.
|
|
215
|
+
- Found artifact directories are never traversed further, so nested caches are counted once and their parent's size wins.
|
|
216
|
+
- Projects with no artifacts above the size threshold are omitted from the report.
|
|
217
|
+
|
|
218
|
+
## JSON output
|
|
219
|
+
|
|
220
|
+
```json
|
|
221
|
+
{
|
|
222
|
+
"tool": "deadweight",
|
|
223
|
+
"version": "1.0.2",
|
|
224
|
+
"scanned_path": "/home/dev/projects",
|
|
225
|
+
"scanned_projects": 4,
|
|
226
|
+
"generated_at": "2026-12-05T12:00:00+00:00",
|
|
227
|
+
"min_size_mb": 0.0,
|
|
228
|
+
"older_than_days": 0,
|
|
229
|
+
"projects": [
|
|
230
|
+
{
|
|
231
|
+
"name": "legacy-api",
|
|
232
|
+
"path": "/home/dev/projects/legacy-api",
|
|
233
|
+
"git": {
|
|
234
|
+
"status": "dirty",
|
|
235
|
+
"changed_files": 3,
|
|
236
|
+
"last_commit": "2024-11-02T09:14:00+00:00",
|
|
237
|
+
"error": null
|
|
238
|
+
},
|
|
239
|
+
"heavy_dirs": [
|
|
240
|
+
{
|
|
241
|
+
"path": "/home/dev/projects/legacy-api/.venv",
|
|
242
|
+
"name": ".venv",
|
|
243
|
+
"size_bytes": 1288490188,
|
|
244
|
+
"size": "1.2 GB"
|
|
245
|
+
}
|
|
246
|
+
],
|
|
247
|
+
"total_size_bytes": 1288490188,
|
|
248
|
+
"total_size": "1.2 GB"
|
|
249
|
+
}
|
|
250
|
+
],
|
|
251
|
+
"totals": {
|
|
252
|
+
"projects": 1,
|
|
253
|
+
"heavy_dirs": 1,
|
|
254
|
+
"total_size_bytes": 1288490188,
|
|
255
|
+
"total_size": "1.2 GB",
|
|
256
|
+
"reclaimable_gb": 1.2
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
```
|
|
260
|
+
|
|
261
|
+
The `totals.reclaimable_gb` field makes it easy to feed the result into dashboards or alerting.
|
|
262
|
+
|
|
263
|
+
## Safety
|
|
264
|
+
|
|
265
|
+
- DeadWeight is **read-only by default**.
|
|
266
|
+
- Deletion requires both `--clean` and a `y` answer to the confirmation prompt.
|
|
267
|
+
- `--select` is only accepted together with `--clean`, and the final confirmation is still mandatory.
|
|
268
|
+
- `--clean` and `--json` cannot be combined, so a prompt can never corrupt JSON output.
|
|
269
|
+
- Only known artifact directory names or directories containing a valid `pyvenv.cfg` marker are eligible for deletion.
|
|
270
|
+
- Symlinks, junctions, unreadable directories, and locked files do not crash the scan; they are skipped or reported.
|
|
271
|
+
- The last line of defense: every deletion target is verified to be inside the scanned root.
|
|
272
|
+
|
|
273
|
+
## Development
|
|
274
|
+
|
|
275
|
+
```bash
|
|
276
|
+
git clone https://github.com/ASCTeam-prog/deadweight.git
|
|
277
|
+
cd deadweight
|
|
278
|
+
pip install -e .
|
|
279
|
+
python deadweight.py --help
|
|
280
|
+
python deadweight.py . --min-size 10
|
|
281
|
+
python -m unittest discover -s tests -v
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
The test suite creates disposable projects in a temporary directory, including custom-named virtual environments, and exercises selective cleanup. Run a manual scan against a scratch directory before trying `--clean` on real projects.
|
|
285
|
+
|
|
286
|
+
## License
|
|
287
|
+
|
|
288
|
+
MIT
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
deadweight.py,sha256=T2eyyvtzLx1eTbE3npRNkSDu21AuOIae2aDIM-IFZFc,27488
|
|
2
|
+
deadweight_cli-1.0.2.dist-info/licenses/LICENSE,sha256=agPtxOwLgNj7EQbYelsKuouMw7nGUP1tCVnXnyyo_oA,1080
|
|
3
|
+
deadweight_cli-1.0.2.dist-info/METADATA,sha256=WldGEXZ_I5PJdlQPOdTSqiz3TSBBwPeupR36Rm9Q--k,12542
|
|
4
|
+
deadweight_cli-1.0.2.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
5
|
+
deadweight_cli-1.0.2.dist-info/entry_points.txt,sha256=R5UzrHuprXVLyNBE4-s9HTgiWseznnSZkutHOjcPdeY,47
|
|
6
|
+
deadweight_cli-1.0.2.dist-info/top_level.txt,sha256=CmRN--HK4erdFse-ZiT46IITBtR6u1taGnDZXvq36yU,11
|
|
7
|
+
deadweight_cli-1.0.2.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 DeadWeight contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
deadweight
|