devjanitor 0.1.0__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.
devjanitor/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """devjanitor: reclaim disk space from dependency folders, build output and caches."""
2
+
3
+ __version__ = "0.1.0"
devjanitor/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import run
2
+
3
+ run()
devjanitor/caches.py ADDED
@@ -0,0 +1,123 @@
1
+ """Global (per-user) caches that package managers and toolchains keep.
2
+
3
+ Unlike project folders these live at fixed locations, so there is no marker
4
+ check: a location is offered only if it exists. Every entry here is safe to
5
+ delete because the owning tool re-downloads or rebuilds it on demand.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ from dataclasses import dataclass
12
+ from pathlib import Path
13
+ from typing import Callable, List, Tuple
14
+
15
+ from .targets import Target, _always
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class Cache:
20
+ name: str
21
+ ecosystem: str
22
+ description: str
23
+ # Called at scan time (not import time) so HOME and env vars are current.
24
+ locations: Callable[[], List[Path]]
25
+
26
+
27
+ def _home(*parts: str) -> Path:
28
+ return Path.home().joinpath(*parts)
29
+
30
+
31
+ def _xdg_cache(*parts: str) -> Path:
32
+ base = os.environ.get("XDG_CACHE_HOME") or str(_home(".cache"))
33
+ return Path(base).joinpath(*parts)
34
+
35
+
36
+ def _mac_cache(*parts: str) -> Path:
37
+ return _home("Library", "Caches", *parts)
38
+
39
+
40
+ def _win_local(*parts: str) -> List[Path]:
41
+ base = os.environ.get("LOCALAPPDATA")
42
+ return [Path(base).joinpath(*parts)] if base else []
43
+
44
+
45
+ def _cache_dirs(*parts: str) -> Callable[[], List[Path]]:
46
+ """The usual cache folder for a tool on macOS, Linux and Windows."""
47
+ return lambda: [_mac_cache(*parts), _xdg_cache(*parts), *_win_local(*parts)]
48
+
49
+
50
+ def _paths(*parts_list: Tuple[str, ...]) -> Callable[[], List[Path]]:
51
+ return lambda: [_home(*parts) for parts in parts_list]
52
+
53
+
54
+ CACHES: List[Cache] = [
55
+ # JavaScript
56
+ Cache("npm cache", "node", "npm download cache", _paths((".npm", "_cacache"))),
57
+ Cache("yarn cache", "node", "Yarn download cache",
58
+ lambda: [_mac_cache("Yarn"), _xdg_cache("yarn"), *_win_local("Yarn", "Cache")]),
59
+ Cache("pnpm store", "node", "pnpm content-addressable store",
60
+ lambda: [_home("Library", "pnpm", "store"),
61
+ _home(".local", "share", "pnpm", "store"),
62
+ *_win_local("pnpm", "store")]),
63
+ Cache("bun cache", "node", "Bun install cache", _paths((".bun", "install", "cache"))),
64
+ Cache("deno cache", "node", "Deno module cache", _cache_dirs("deno")),
65
+ Cache("playwright", "node", "Playwright browser downloads",
66
+ lambda: [_mac_cache("ms-playwright"), _xdg_cache("ms-playwright"),
67
+ *_win_local("ms-playwright")]),
68
+ Cache("electron", "node", "Electron binary downloads", _cache_dirs("electron")),
69
+ # Python
70
+ Cache("pip cache", "python", "pip download and wheel cache",
71
+ lambda: [_mac_cache("pip"), _xdg_cache("pip"), *_win_local("pip", "Cache")]),
72
+ Cache("uv cache", "python", "uv package cache",
73
+ lambda: [_xdg_cache("uv"), *_win_local("uv", "cache")]),
74
+ Cache("poetry cache", "python", "Poetry package cache", _cache_dirs("pypoetry")),
75
+ # Rust
76
+ Cache("cargo registry", "rust", "downloaded crate archives and sources",
77
+ _paths((".cargo", "registry", "cache"), (".cargo", "registry", "src"))),
78
+ Cache("cargo git", "rust", "git dependency checkouts",
79
+ _paths((".cargo", "git", "checkouts"))),
80
+ # Go
81
+ Cache("go build cache", "go", "compiled package cache",
82
+ lambda: [_mac_cache("go-build"), _xdg_cache("go-build"),
83
+ *_win_local("go-build")]),
84
+ # JVM
85
+ Cache("gradle caches", "jvm", "Gradle dependency and build cache",
86
+ _paths((".gradle", "caches"))),
87
+ Cache("maven repo", "jvm", "Maven local repository", _paths((".m2", "repository"))),
88
+ # Apple
89
+ Cache("xcode derived data", "ios", "Xcode build products and indexes",
90
+ _paths(("Library", "Developer", "Xcode", "DerivedData"))),
91
+ Cache("ios device support", "ios", "debug symbols, re-copied when a device connects",
92
+ _paths(("Library", "Developer", "Xcode", "iOS DeviceSupport"))),
93
+ Cache("cocoapods cache", "ios", "CocoaPods download cache", _cache_dirs("CocoaPods")),
94
+ Cache("homebrew cache", "system", "downloaded bottles and source archives",
95
+ _cache_dirs("Homebrew")),
96
+ # Dart / Flutter
97
+ Cache("pub cache", "dart", "Dart/Flutter package cache (run pub get afterwards)",
98
+ lambda: [_home(".pub-cache"), *_win_local("Pub", "Cache")]),
99
+ # PHP
100
+ Cache("composer cache", "php", "Composer download cache",
101
+ lambda: [_home(".composer", "cache"), _xdg_cache("composer"),
102
+ *_win_local("Composer")]),
103
+ ]
104
+
105
+
106
+ def find_caches(ecosystems=None):
107
+ """Yield ``(path, Target)`` for every cache location that exists."""
108
+ seen = set()
109
+ for cache in CACHES:
110
+ if ecosystems and cache.ecosystem not in ecosystems:
111
+ continue
112
+ target = Target(cache.name, cache.ecosystem, cache.description, _always)
113
+ for path in cache.locations():
114
+ try:
115
+ if path.is_symlink() or not path.is_dir():
116
+ continue
117
+ key = path.resolve()
118
+ except OSError:
119
+ continue
120
+ if key in seen:
121
+ continue
122
+ seen.add(key)
123
+ yield path, target
devjanitor/cli.py ADDED
@@ -0,0 +1,268 @@
1
+ """Command-line interface for devjanitor."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import os
8
+ import shutil
9
+ import stat
10
+ import sys
11
+ import time
12
+ from pathlib import Path
13
+ from typing import List, Optional
14
+
15
+ from rich.console import Console
16
+ from rich.progress import BarColumn, Progress, SpinnerColumn, TextColumn
17
+ from rich.prompt import Confirm, Prompt
18
+ from rich.table import Table
19
+
20
+ from . import __version__
21
+ from .caches import CACHES, find_caches
22
+ from .scanner import Found, find_targets, measure
23
+ from .targets import TARGETS
24
+ from .utils import display_path, human_size, parse_selection, parse_size, time_ago
25
+
26
+ console = Console()
27
+ err = Console(stderr=True)
28
+
29
+ ECOSYSTEMS = sorted({t.ecosystem for t in TARGETS} | {c.ecosystem for c in CACHES})
30
+
31
+ ECO_STYLE = {
32
+ "node": "green", "python": "yellow", "rust": "red", "jvm": "magenta",
33
+ "dart": "cyan", "ios": "blue", "elixir": "bright_magenta",
34
+ "dotnet": "bright_blue", "terraform": "bright_cyan", "go": "bright_cyan",
35
+ "php": "bright_blue", "system": "white",
36
+ }
37
+
38
+
39
+ def build_parser() -> argparse.ArgumentParser:
40
+ p = argparse.ArgumentParser(
41
+ prog="devjanitor",
42
+ description="Find and delete dependency folders, build output and caches "
43
+ "(node_modules, .venv, target, __pycache__, ...) to free disk space.",
44
+ epilog="examples:\n"
45
+ " devjanitor ~/code scan and pick what to delete\n"
46
+ " devjanitor ~/code --older-than 90 only projects untouched for 90 days\n"
47
+ " devjanitor . --only node,python -n list without deleting\n"
48
+ " devjanitor --global package manager and Xcode caches\n",
49
+ formatter_class=argparse.RawDescriptionHelpFormatter,
50
+ )
51
+ p.add_argument("paths", nargs="*", metavar="PATH",
52
+ help="directories to scan (default: current directory, "
53
+ "or none with --global)")
54
+ p.add_argument("-g", "--global", dest="global_", action="store_true",
55
+ help="also clean per-user caches: npm, pip, cargo, gradle, "
56
+ "Xcode DerivedData, ...")
57
+ p.add_argument("-o", "--older-than", type=int, metavar="DAYS",
58
+ help="only show projects with no changes for DAYS days "
59
+ "(global caches are always shown)")
60
+ p.add_argument("-m", "--min-size", type=parse_size, default=0, metavar="SIZE",
61
+ help="hide entries smaller than SIZE, e.g. 50MB")
62
+ p.add_argument("--only", metavar="LIST",
63
+ help=f"comma-separated ecosystems: {','.join(ECOSYSTEMS)}")
64
+ p.add_argument("-n", "--dry-run", action="store_true",
65
+ help="list what would be cleaned, delete nothing")
66
+ p.add_argument("-y", "--yes", action="store_true",
67
+ help="delete everything found without asking")
68
+ p.add_argument("--json", action="store_true",
69
+ help="print results as JSON (implies --dry-run)")
70
+ p.add_argument("--list-targets", action="store_true",
71
+ help="show every directory type devjanitor recognises")
72
+ p.add_argument("-V", "--version", action="version", version=f"devjanitor {__version__}")
73
+ return p
74
+
75
+
76
+ def print_targets() -> None:
77
+ table = Table(title="Recognised directories", header_style="bold")
78
+ table.add_column("Directory")
79
+ table.add_column("Ecosystem")
80
+ table.add_column("What it is")
81
+ for t in TARGETS:
82
+ style = ECO_STYLE.get(t.ecosystem, "")
83
+ table.add_row(t.dir_name, f"[{style}]{t.ecosystem}[/]", t.description)
84
+ console.print(table)
85
+ table = Table(title="Global caches (--global)", header_style="bold")
86
+ table.add_column("Cache")
87
+ table.add_column("Ecosystem")
88
+ table.add_column("What it is")
89
+ for c in CACHES:
90
+ style = ECO_STYLE.get(c.ecosystem, "")
91
+ table.add_row(c.name, f"[{style}]{c.ecosystem}[/]", c.description)
92
+ console.print(table)
93
+
94
+
95
+ def scan(roots: List[Path], ecosystems: Optional[set],
96
+ include_global: bool = False) -> List[Found]:
97
+ found: List[Found] = []
98
+ if include_global:
99
+ for path, target in find_caches(ecosystems):
100
+ found.append(Found(path=path, target=target, is_global=True))
101
+ dirs_seen = 0
102
+ with console.status("[bold]Scanning…", spinner="dots") as status:
103
+ def on_dir(path: str) -> None:
104
+ nonlocal dirs_seen
105
+ dirs_seen += 1
106
+ if dirs_seen % 200 == 0:
107
+ status.update(f"[bold]Scanning…[/] {dirs_seen:,} folders, "
108
+ f"{len(found)} found [dim]{path[-60:]}[/]")
109
+
110
+ for item in find_targets(roots, ecosystems, on_dir):
111
+ found.append(item)
112
+
113
+ if not found:
114
+ return found
115
+
116
+ with Progress(SpinnerColumn(), TextColumn("[bold]Measuring"), BarColumn(),
117
+ TextColumn("{task.completed}/{task.total}"),
118
+ console=console, transient=True) as progress:
119
+ task = progress.add_task("measure", total=len(found))
120
+ measure(found, on_done=lambda _: progress.advance(task))
121
+ return found
122
+
123
+
124
+ def render(items: List[Found], root: Optional[Path]) -> None:
125
+ table = Table(header_style="bold", show_edge=False, pad_edge=False)
126
+ table.add_column("#", justify="right", style="dim")
127
+ table.add_column("Path", overflow="fold")
128
+ table.add_column("Type")
129
+ table.add_column("Size", justify="right")
130
+ table.add_column("Last activity", justify="right", style="dim")
131
+ biggest = items[0].size if items else 1
132
+ for i, item in enumerate(items, 1):
133
+ style = ECO_STYLE.get(item.target.ecosystem, "")
134
+ size_style = "bold red" if item.size >= max(biggest * 0.5, 500 * 1024**2) else ""
135
+ table.add_row(
136
+ str(i),
137
+ display_path(item.path, root),
138
+ f"[{style}]{item.target.dir_name}[/]",
139
+ f"[{size_style}]{human_size(item.size)}[/]" if size_style else human_size(item.size),
140
+ time_ago(item.last_activity),
141
+ )
142
+ console.print(table)
143
+ total = sum(i.size for i in items)
144
+ noun = "directory" if len(items) == 1 else "directories"
145
+ console.print(f"\n[bold]{len(items)}[/] {noun}, "
146
+ f"[bold green]{human_size(total)}[/] reclaimable\n")
147
+
148
+
149
+ def _make_writable_and_retry(func, path, _exc_info):
150
+ # Some tools write read-only files (Go modules, git objects on Windows).
151
+ # Make the file and its folder writable, then try once more.
152
+ os.chmod(os.path.dirname(path), stat.S_IRWXU)
153
+ if os.path.lexists(path) and not os.path.islink(path):
154
+ os.chmod(path, stat.S_IRWXU)
155
+ func(path)
156
+
157
+
158
+ def delete(items: List[Found]) -> int:
159
+ freed = 0
160
+ failed = []
161
+ with Progress(SpinnerColumn(), TextColumn("[bold]Deleting"), BarColumn(),
162
+ TextColumn("{task.description}"), console=console,
163
+ transient=True) as progress:
164
+ task = progress.add_task("", total=len(items))
165
+ for item in items:
166
+ progress.update(task, description=item.path.name)
167
+ try:
168
+ shutil.rmtree(item.path, onerror=_make_writable_and_retry)
169
+ freed += item.size
170
+ except OSError as exc:
171
+ failed.append((item, exc))
172
+ progress.advance(task)
173
+ for item, exc in failed:
174
+ err.print(f"[red]✗ could not delete {item.path}: {exc}[/]")
175
+ return freed
176
+
177
+
178
+ def main(argv: Optional[List[str]] = None) -> int:
179
+ args = build_parser().parse_args(argv)
180
+
181
+ if args.list_targets:
182
+ print_targets()
183
+ return 0
184
+
185
+ ecosystems = None
186
+ if args.only:
187
+ ecosystems = {e.strip().lower() for e in args.only.split(",") if e.strip()}
188
+ unknown = ecosystems - set(ECOSYSTEMS)
189
+ if unknown:
190
+ err.print(f"[red]Unknown ecosystem(s): {', '.join(sorted(unknown))}. "
191
+ f"Choose from: {', '.join(ECOSYSTEMS)}[/]")
192
+ return 2
193
+
194
+ paths = args.paths or ([] if args.global_ else ["."])
195
+ roots = []
196
+ for raw in paths:
197
+ path = Path(raw).expanduser()
198
+ if not path.is_dir():
199
+ err.print(f"[red]Not a directory: {raw}[/]")
200
+ return 2
201
+ roots.append(path.resolve())
202
+
203
+ started = time.monotonic()
204
+ items = scan(roots, ecosystems, include_global=args.global_)
205
+
206
+ if args.older_than is not None:
207
+ cutoff = time.time() - args.older_than * 86400
208
+ items = [i for i in items
209
+ if i.is_global or (i.last_activity and i.last_activity < cutoff)]
210
+ items = [i for i in items if i.size >= args.min_size]
211
+ items.sort(key=lambda i: i.size, reverse=True)
212
+
213
+ if args.json:
214
+ print(json.dumps([{
215
+ "path": str(i.path), "type": i.target.dir_name,
216
+ "ecosystem": i.target.ecosystem, "bytes": i.size,
217
+ "last_activity": i.last_activity, "global": i.is_global,
218
+ } for i in items], indent=2))
219
+ return 0
220
+
221
+ elapsed = time.monotonic() - started
222
+ if not items:
223
+ console.print(f"[green]✨ Nothing to clean[/] [dim](scanned in {elapsed:.1f}s)[/]")
224
+ return 0
225
+
226
+ root = roots[0] if len(roots) == 1 else None
227
+ render(items, root)
228
+
229
+ if args.dry_run:
230
+ return 0
231
+
232
+ if args.yes:
233
+ chosen = items
234
+ else:
235
+ if not sys.stdin.isatty():
236
+ err.print("[yellow]Not a terminal: pass --yes to delete, or --dry-run to list.[/]")
237
+ return 1
238
+ while True:
239
+ answer = Prompt.ask("Delete which? [dim](e.g. 1,3-5 · all · enter to quit)[/]",
240
+ default="", show_default=False)
241
+ try:
242
+ indexes = parse_selection(answer, len(items))
243
+ break
244
+ except ValueError as exc:
245
+ err.print(f"[red]{exc}[/]")
246
+ if not indexes:
247
+ console.print("Nothing deleted.")
248
+ return 0
249
+ chosen = [items[i] for i in indexes]
250
+ size = human_size(sum(i.size for i in chosen))
251
+ if not Confirm.ask(f"Permanently delete [bold]{len(chosen)}[/] directories "
252
+ f"([bold]{size}[/])?", default=False):
253
+ console.print("Nothing deleted.")
254
+ return 0
255
+
256
+ freed = delete(chosen)
257
+ console.print(f"\n[bold green]✨ You freed {human_size(freed)}![/] "
258
+ "[dim]Reinstall anytime with npm install / pip install / cargo build.[/]",
259
+ highlight=False)
260
+ return 0
261
+
262
+
263
+ def run() -> None:
264
+ try:
265
+ sys.exit(main())
266
+ except (KeyboardInterrupt, EOFError):
267
+ err.print("\n[dim]Interrupted, nothing more deleted.[/]")
268
+ sys.exit(130)
devjanitor/scanner.py ADDED
@@ -0,0 +1,188 @@
1
+ """Walk directory trees, find cleanable directories and measure them."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import stat
7
+ import sys
8
+ from concurrent.futures import ThreadPoolExecutor
9
+ from dataclasses import dataclass, field
10
+ from pathlib import Path
11
+ from typing import Callable, Iterable, Iterator, List, Optional, Set
12
+
13
+ from .targets import Target, match
14
+
15
+ # Directories that are never worth descending into.
16
+ SKIP_NAMES = {".git", ".hg", ".svn", ".Trash", ".cache", "System Volume Information"}
17
+
18
+ # Large, system-managed trees under the home directory. Walking them is slow
19
+ # and, on macOS, can trigger privacy permission prompts.
20
+ _HOME = Path.home()
21
+ SKIP_PATHS = {
22
+ _HOME / "Library",
23
+ _HOME / ".Trash",
24
+ _HOME / "AppData",
25
+ _HOME / ".local" / "share" / "Trash",
26
+ }
27
+ if sys.platform == "darwin":
28
+ SKIP_PATHS |= {Path("/System"), Path("/Library"), Path("/private"), Path("/Volumes")}
29
+
30
+
31
+ @dataclass
32
+ class Found:
33
+ path: Path
34
+ target: Target
35
+ size: int = 0
36
+ last_activity: float = 0.0 # unix time of the newest change in the project
37
+ errors: int = 0
38
+ is_global: bool = False # a per-user cache rather than a project folder
39
+ extra: dict = field(default_factory=dict)
40
+
41
+
42
+ def _disk_usage(st: os.stat_result) -> int:
43
+ # st_blocks reflects the space actually freed on deletion (sparse files,
44
+ # small files rounded up to a block). Not available on Windows.
45
+ blocks = getattr(st, "st_blocks", None)
46
+ if blocks is not None:
47
+ return blocks * 512
48
+ return st.st_size
49
+
50
+
51
+ def dir_size(path: Path) -> tuple:
52
+ """Return ``(bytes, error_count)`` for everything under ``path``.
53
+
54
+ Symlinks are counted but not followed. Hard-linked files are counted once.
55
+ """
56
+ total = 0
57
+ errors = 0
58
+ seen_inodes: Set[tuple] = set()
59
+ stack = [str(path)]
60
+ while stack:
61
+ current = stack.pop()
62
+ try:
63
+ with os.scandir(current) as it:
64
+ for entry in it:
65
+ try:
66
+ st = entry.stat(follow_symlinks=False)
67
+ except OSError:
68
+ errors += 1
69
+ continue
70
+ if stat.S_ISDIR(st.st_mode):
71
+ stack.append(entry.path)
72
+ total += _disk_usage(st)
73
+ continue
74
+ if st.st_nlink > 1:
75
+ key = (st.st_dev, st.st_ino)
76
+ if key in seen_inodes:
77
+ continue
78
+ seen_inodes.add(key)
79
+ total += _disk_usage(st)
80
+ except OSError:
81
+ errors += 1
82
+ return total, errors
83
+
84
+
85
+ def last_activity(project_dir: Path, exclude: Path) -> float:
86
+ """Newest mtime among the entries directly inside ``project_dir``.
87
+
88
+ The cleanable directory itself is excluded: installing dependencies
89
+ should not make a long-abandoned project look recently active.
90
+ """
91
+ newest = 0.0
92
+ try:
93
+ with os.scandir(project_dir) as it:
94
+ for entry in it:
95
+ if entry.name == exclude.name or entry.name in SKIP_NAMES - {".git"}:
96
+ continue
97
+ try:
98
+ newest = max(newest, entry.stat(follow_symlinks=False).st_mtime)
99
+ except OSError:
100
+ pass
101
+ except OSError:
102
+ pass
103
+ if not newest:
104
+ # Nothing else in the project folder: fall back to the folder itself.
105
+ try:
106
+ newest = exclude.stat().st_mtime
107
+ except OSError:
108
+ pass
109
+ return newest
110
+
111
+
112
+ def newest_child_mtime(path: Path) -> float:
113
+ """Newest mtime of ``path`` and the entries directly inside it."""
114
+ try:
115
+ newest = path.stat().st_mtime
116
+ except OSError:
117
+ return 0.0
118
+ try:
119
+ with os.scandir(path) as it:
120
+ for entry in it:
121
+ try:
122
+ newest = max(newest, entry.stat(follow_symlinks=False).st_mtime)
123
+ except OSError:
124
+ pass
125
+ except OSError:
126
+ pass
127
+ return newest
128
+
129
+
130
+ def find_targets(
131
+ roots: Iterable[Path],
132
+ ecosystems: Optional[Set[str]] = None,
133
+ on_dir: Optional[Callable[[str], None]] = None,
134
+ ) -> Iterator[Found]:
135
+ """Yield every cleanable directory below ``roots`` (no sizes yet).
136
+
137
+ Matched directories are not descended into, so ``node_modules`` nested
138
+ inside ``node_modules`` is reported only once, as part of its parent.
139
+ """
140
+ seen: Set[str] = set()
141
+ for root in roots:
142
+ root = Path(root).expanduser().resolve()
143
+ stack = [root]
144
+ while stack:
145
+ current = stack.pop()
146
+ key = str(current)
147
+ if key in seen:
148
+ continue
149
+ seen.add(key)
150
+ if on_dir:
151
+ on_dir(key)
152
+ try:
153
+ entries = list(os.scandir(current))
154
+ except OSError:
155
+ continue
156
+ for entry in entries:
157
+ try:
158
+ if not entry.is_dir(follow_symlinks=False):
159
+ continue
160
+ except OSError:
161
+ continue
162
+ path = Path(entry.path)
163
+ target = match(path, ecosystems)
164
+ if target is not None:
165
+ yield Found(path=path, target=target)
166
+ continue
167
+ if entry.name in SKIP_NAMES or path in SKIP_PATHS:
168
+ continue
169
+ stack.append(path)
170
+
171
+
172
+ def measure(found: List[Found], workers: int = 8,
173
+ on_done: Optional[Callable[[Found], None]] = None) -> List[Found]:
174
+ """Fill in size and last activity for every item, in parallel."""
175
+
176
+ def work(item: Found) -> Found:
177
+ item.size, item.errors = dir_size(item.path)
178
+ if item.is_global:
179
+ item.last_activity = newest_child_mtime(item.path)
180
+ else:
181
+ item.last_activity = last_activity(item.path.parent, item.path)
182
+ return item
183
+
184
+ with ThreadPoolExecutor(max_workers=workers) as pool:
185
+ for item in pool.map(work, found):
186
+ if on_done:
187
+ on_done(item)
188
+ return found
devjanitor/targets.py ADDED
@@ -0,0 +1,119 @@
1
+ """Definitions of the directories devjanitor knows how to clean.
2
+
3
+ Every target has a directory name and a check that must pass before the
4
+ directory is reported. The checks look for a marker file (``package.json``,
5
+ ``Cargo.toml``, ``pyvenv.cfg`` ...) so that a random folder that happens to be
6
+ called ``target`` or ``build`` is never offered for deletion.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass
12
+ from pathlib import Path
13
+ from typing import Callable, Dict, List, Optional
14
+
15
+
16
+ def _always(path: Path) -> bool:
17
+ return True
18
+
19
+
20
+ def _parent_has(*names: str) -> Callable[[Path], bool]:
21
+ def check(path: Path) -> bool:
22
+ parent = path.parent
23
+ return any((parent / name).exists() for name in names)
24
+
25
+ return check
26
+
27
+
28
+ def _parent_has_glob(pattern: str) -> Callable[[Path], bool]:
29
+ def check(path: Path) -> bool:
30
+ return any(path.parent.glob(pattern))
31
+
32
+ return check
33
+
34
+
35
+ def _contains(*names: str) -> Callable[[Path], bool]:
36
+ def check(path: Path) -> bool:
37
+ return any((path / name).exists() for name in names)
38
+
39
+ return check
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class Target:
44
+ dir_name: str
45
+ ecosystem: str
46
+ description: str
47
+ check: Callable[[Path], bool]
48
+
49
+ def matches(self, path: Path) -> bool:
50
+ if path.name != self.dir_name:
51
+ return False
52
+ try:
53
+ return self.check(path)
54
+ except OSError:
55
+ return False
56
+
57
+
58
+ _JS = ("package.json",)
59
+
60
+ TARGETS: List[Target] = [
61
+ # Node / JavaScript
62
+ Target("node_modules", "node", "npm / yarn / pnpm dependencies", _always),
63
+ Target(".next", "node", "Next.js build output", _parent_has(*_JS)),
64
+ Target(".nuxt", "node", "Nuxt build output", _parent_has(*_JS)),
65
+ Target(".svelte-kit", "node", "SvelteKit build output", _parent_has(*_JS)),
66
+ Target(".turbo", "node", "Turborepo cache", _parent_has(*_JS)),
67
+ Target(".parcel-cache", "node", "Parcel cache", _parent_has(*_JS)),
68
+ Target(".angular", "node", "Angular CLI cache", _parent_has("angular.json")),
69
+ # Python
70
+ Target(".venv", "python", "virtual environment", _contains("pyvenv.cfg")),
71
+ Target("venv", "python", "virtual environment", _contains("pyvenv.cfg")),
72
+ Target("__pycache__", "python", "bytecode cache", _always),
73
+ Target(".pytest_cache", "python", "pytest cache", _always),
74
+ Target(".mypy_cache", "python", "mypy cache", _always),
75
+ Target(".ruff_cache", "python", "ruff cache", _always),
76
+ Target(".tox", "python", "tox environments", _always),
77
+ Target(".nox", "python", "nox environments", _always),
78
+ # Rust
79
+ Target("target", "rust", "cargo build output", _parent_has("Cargo.toml")),
80
+ # JVM
81
+ Target("build", "jvm", "Gradle build output",
82
+ _parent_has("build.gradle", "build.gradle.kts")),
83
+ Target(".gradle", "jvm", "Gradle project cache",
84
+ _parent_has("build.gradle", "build.gradle.kts", "settings.gradle",
85
+ "settings.gradle.kts")),
86
+ # (Maven's output dir is also called "target", checked separately below.)
87
+ # Dart / Flutter
88
+ Target(".dart_tool", "dart", "Dart tool cache", _parent_has("pubspec.yaml")),
89
+ # iOS
90
+ Target("Pods", "ios", "CocoaPods dependencies", _parent_has("Podfile")),
91
+ # Elixir
92
+ Target("_build", "elixir", "Mix build output", _parent_has("mix.exs")),
93
+ Target("deps", "elixir", "Mix dependencies", _parent_has("mix.exs")),
94
+ # .NET
95
+ Target("obj", "dotnet", ".NET intermediate output",
96
+ _parent_has_glob("*.*proj")),
97
+ # Terraform
98
+ Target(".terraform", "terraform", "providers and modules",
99
+ _parent_has_glob("*.tf")),
100
+ ]
101
+
102
+ # Maven also builds into "target"; share the dir name with a second check.
103
+ TARGETS.append(Target("target", "jvm", "Maven build output", _parent_has("pom.xml")))
104
+
105
+ TARGETS_BY_NAME: Dict[str, List[Target]] = {}
106
+ for _t in TARGETS:
107
+ TARGETS_BY_NAME.setdefault(_t.dir_name, []).append(_t)
108
+
109
+ ECOSYSTEMS = sorted({t.ecosystem for t in TARGETS})
110
+
111
+
112
+ def match(path: Path, ecosystems: Optional[set] = None) -> Optional[Target]:
113
+ """Return the target ``path`` is an instance of, or ``None``."""
114
+ for target in TARGETS_BY_NAME.get(path.name, ()):
115
+ if ecosystems and target.ecosystem not in ecosystems:
116
+ continue
117
+ if target.matches(path):
118
+ return target
119
+ return None
devjanitor/utils.py ADDED
@@ -0,0 +1,93 @@
1
+ """Small parsing and formatting helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import time
7
+ from pathlib import Path
8
+ from typing import List, Optional
9
+
10
+ _UNITS = ["B", "KB", "MB", "GB", "TB"]
11
+ _SIZE_RE = re.compile(r"^\s*(\d+(?:\.\d+)?)\s*([KMGT]?)i?B?\s*$", re.IGNORECASE)
12
+
13
+
14
+ def human_size(n: float) -> str:
15
+ for unit in _UNITS:
16
+ if abs(n) < 1024 or unit == _UNITS[-1]:
17
+ if unit == "B":
18
+ return f"{int(n)} B"
19
+ return f"{n:.1f} {unit}"
20
+ n /= 1024
21
+ raise AssertionError("unreachable")
22
+
23
+
24
+ def parse_size(text: str) -> int:
25
+ """Parse ``"500MB"``, ``"1.5G"``, ``"200k"`` or ``"1024"`` into bytes."""
26
+ m = _SIZE_RE.match(text)
27
+ if not m:
28
+ raise ValueError(f"invalid size: {text!r} (try 100MB or 1.5GB)")
29
+ number, unit = float(m.group(1)), m.group(2).upper()
30
+ power = " KMGT".index(unit) if unit else 0
31
+ return int(number * 1024 ** power)
32
+
33
+
34
+ def time_ago(timestamp: float, now: Optional[float] = None) -> str:
35
+ if not timestamp:
36
+ return "unknown"
37
+ seconds = max(0.0, (now or time.time()) - timestamp)
38
+ for limit, unit_seconds, name in (
39
+ (60, 1, "second"),
40
+ (3600, 60, "minute"),
41
+ (86400, 3600, "hour"),
42
+ (86400 * 30, 86400, "day"),
43
+ (86400 * 365, 86400 * 30, "month"),
44
+ (float("inf"), 86400 * 365, "year"),
45
+ ):
46
+ if seconds < limit:
47
+ value = int(seconds // unit_seconds)
48
+ if name == "second" and value < 10:
49
+ return "just now"
50
+ return f"{value} {name}{'' if value == 1 else 's'} ago"
51
+ raise AssertionError("unreachable")
52
+
53
+
54
+ def parse_selection(text: str, count: int) -> List[int]:
55
+ """Turn ``"1,3-5"``, ``"all"`` or ``""`` into sorted 0-based indexes.
56
+
57
+ Raises ``ValueError`` on anything out of range or malformed.
58
+ """
59
+ text = text.strip().lower()
60
+ if text in ("", "none", "n", "q"):
61
+ return []
62
+ if text in ("all", "a", "*"):
63
+ return list(range(count))
64
+ chosen = set()
65
+ for part in re.split(r"[,\s]+", text):
66
+ if not part:
67
+ continue
68
+ if "-" in part:
69
+ lo_s, _, hi_s = part.partition("-")
70
+ lo, hi = int(lo_s), int(hi_s)
71
+ if lo > hi:
72
+ lo, hi = hi, lo
73
+ else:
74
+ lo = hi = int(part)
75
+ if lo < 1 or hi > count:
76
+ raise ValueError(f"{part} is out of range (1-{count})")
77
+ chosen.update(range(lo - 1, hi))
78
+ return sorted(chosen)
79
+
80
+
81
+ def display_path(path: Path, root: Optional[Path] = None) -> str:
82
+ """Show ``path`` relative to the scan root, or with ``~`` for home."""
83
+ if root is not None:
84
+ try:
85
+ rel = path.relative_to(root)
86
+ return str(rel) if str(rel) != "." else str(path)
87
+ except ValueError:
88
+ pass
89
+ home = Path.home()
90
+ try:
91
+ return "~/" + str(path.relative_to(home))
92
+ except ValueError:
93
+ return str(path)
@@ -0,0 +1,143 @@
1
+ Metadata-Version: 2.5
2
+ Name: devjanitor
3
+ Version: 0.1.0
4
+ Summary: Find and delete node_modules, .venv, target/ and other dev junk to free disk space.
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Keywords: cleanup,cli,developer-tools,disk-space,node_modules,venv
8
+ Classifier: Environment :: Console
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: System :: Filesystems
13
+ Classifier: Topic :: Utilities
14
+ Requires-Python: >=3.9
15
+ Requires-Dist: rich>=13
16
+ Provides-Extra: dev
17
+ Requires-Dist: pytest>=7; extra == 'dev'
18
+ Description-Content-Type: text/markdown
19
+
20
+ # devjanitor 🧹
21
+
22
+ [![CI](https://github.com/boring89/devjanitor/actions/workflows/ci.yml/badge.svg)](https://github.com/boring89/devjanitor/actions/workflows/ci.yml)
23
+ [![PyPI](https://img.shields.io/pypi/v/devjanitor)](https://pypi.org/project/devjanitor/)
24
+ [![Python](https://img.shields.io/pypi/pyversions/devjanitor)](https://pypi.org/project/devjanitor/)
25
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
26
+
27
+ **Find the projects you forgot about and delete their `node_modules`, `.venv`, `target/` and build output. Every language, one command.**
28
+
29
+ <!-- Demo GIF: run `vhs demo.tape`, commit demo.gif, then uncomment:
30
+ ![devjanitor demo](demo.gif)
31
+ -->
32
+
33
+ ```console
34
+ $ devjanitor ~/code --older-than 90
35
+ # ┃ Path ┃ Type ┃ Size ┃ Last activity
36
+ ━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━━━━━
37
+ 1 │ ml-experiments/.venv │ .venv │ 2.1 GB │ 5 months ago
38
+ 2 │ old-hackathon/node_modules │ node_modules │ 1.2 GB │ 2 years ago
39
+ 3 │ rust-playground/target │ target │ 890.3 MB │ 8 months ago
40
+ 4 │ portfolio-v1/.next │ .next │ 412.7 MB │ 1 year ago
41
+ 5 │ flutter-todo/.dart_tool │ .dart_tool │ 301.5 MB │ 7 months ago
42
+ …
43
+
44
+ 23 directories, 9.4 GB reclaimable
45
+
46
+ Delete which? (e.g. 1,3-5 · all · enter to quit): all
47
+ Permanently delete 23 directories (9.4 GB)? [y/n]: y
48
+
49
+ ✨ You freed 9.4 GB!
50
+ ```
51
+
52
+ ## Why
53
+
54
+ Every side project leaves hundreds of MB of dependencies and build output behind, long after you stopped working on it. devjanitor walks your code folders, finds those leftovers **in every ecosystem** (Node, Python, Rust, Java/Kotlin, Flutter, iOS, Elixir, .NET, Terraform), and shows **when each project was last touched**, so you can clear out the dead ones and leave active work alone.
55
+
56
+ - [npkill](https://github.com/voidcosmos/npkill) only handles `node_modules`.
57
+ - Cache cleaners only clear global caches, not the folders inside your projects.
58
+ - devjanitor does projects first and global caches too (`--global`: npm, pip, cargo, Gradle, Xcode DerivedData, ...).
59
+
60
+ ## Install
61
+
62
+ ```bash
63
+ pipx install devjanitor # or: uv tool install devjanitor
64
+ ```
65
+
66
+ Or run it once without installing:
67
+
68
+ ```bash
69
+ uvx devjanitor ~/code
70
+ ```
71
+
72
+ ## Usage
73
+
74
+ ```bash
75
+ devjanitor # scan the current directory
76
+ devjanitor ~/code ~/work # scan several places
77
+ devjanitor --global # npm/pip/cargo/gradle caches, Xcode DerivedData, ...
78
+ devjanitor ~/code -g # projects and global caches together
79
+ devjanitor ~/code -o 90 # only projects untouched for 90+ days
80
+ devjanitor ~/code -m 100MB # hide anything smaller than 100 MB
81
+ devjanitor ~/code --only node # only node_modules, .next, npm cache, ...
82
+ devjanitor ~/code -n # dry run: list, never delete
83
+ devjanitor ~/code --json # machine-readable output
84
+ devjanitor --list-targets # everything devjanitor recognises
85
+ ```
86
+
87
+ ## What it cleans
88
+
89
+ ### Project folders
90
+
91
+ | Ecosystem | Directories |
92
+ |---|---|
93
+ | Node | `node_modules`, `.next`, `.nuxt`, `.svelte-kit`, `.turbo`, `.parcel-cache`, `.angular` |
94
+ | Python | `.venv`, `venv`, `__pycache__`, `.pytest_cache`, `.mypy_cache`, `.ruff_cache`, `.tox`, `.nox` |
95
+ | Rust | `target` |
96
+ | JVM | `build`, `.gradle` (Gradle), `target` (Maven) |
97
+ | Flutter / Dart | `.dart_tool` |
98
+ | iOS | `Pods` |
99
+ | Elixir | `_build`, `deps` |
100
+ | .NET | `obj` |
101
+ | Terraform | `.terraform` |
102
+
103
+ ### Global caches (`--global`)
104
+
105
+ | Ecosystem | Caches |
106
+ |---|---|
107
+ | Node | npm, Yarn, pnpm store, Bun, Deno, Playwright browsers, Electron |
108
+ | Python | pip, uv, Poetry |
109
+ | Rust | cargo registry, cargo git checkouts |
110
+ | Go | build cache |
111
+ | JVM | Gradle caches, Maven `~/.m2/repository` |
112
+ | Apple | Xcode DerivedData, iOS DeviceSupport, CocoaPods, Homebrew |
113
+ | Dart / Flutter | pub cache |
114
+ | PHP | Composer |
115
+
116
+ Locations follow each tool's defaults on macOS, Linux (`$XDG_CACHE_HOME`) and Windows (`%LOCALAPPDATA%`).
117
+
118
+ ## Safety first
119
+
120
+ Deleting folders is serious, so devjanitor is careful:
121
+
122
+ - **Marker checks.** A folder named `target` is only offered if a `Cargo.toml` or `pom.xml` sits next to it. `.venv` must contain `pyvenv.cfg`. `build` needs a Gradle file. A random folder that happens to share a name is never touched.
123
+ - **Never follows symlinks**, and skips `.git`, `~/Library` and system folders when scanning projects.
124
+ - **Nothing is deleted without your choice and a final `y/N` confirmation** (unless you pass `--yes`).
125
+ - **"Last activity" ignores the junk folder itself**, so a fresh `npm install` won't make a 2-year-old project look recent.
126
+
127
+ Everything devjanitor removes is rebuilt or re-downloaded on demand by `npm install`, `pip install`, `cargo build` and friends.
128
+
129
+ ## Contributing
130
+
131
+ Missing an ecosystem? Adding one is a single line in [`src/devjanitor/targets.py`](src/devjanitor/targets.py) (project folders) or [`src/devjanitor/caches.py`](src/devjanitor/caches.py) (global caches). PRs welcome!
132
+
133
+ ```bash
134
+ git clone https://github.com/boring89/devjanitor && cd devjanitor
135
+ python -m venv .venv && .venv/bin/pip install -e ".[dev]"
136
+ .venv/bin/pytest
137
+ ```
138
+
139
+ If devjanitor freed some space for you, a ⭐ would make my day!
140
+
141
+ ## License
142
+
143
+ MIT
@@ -0,0 +1,12 @@
1
+ devjanitor/__init__.py,sha256=PQKHTO3XZkjO-y34Ekt4h4PaApn9IDVmpzI_OBXHGM8,110
2
+ devjanitor/__main__.py,sha256=yQP0sf-rkTO-3MOotv4blvukvNGwbJFz10hQhMsxcJM,28
3
+ devjanitor/caches.py,sha256=dtdl-sPjKLKApPrE-6Nfi03Q774WJYZZYbTbBli-X5M,5039
4
+ devjanitor/cli.py,sha256=ymAFT8RoixQnM91SKZdBkQGElVkLwsi_Eu6el_XahZw,10578
5
+ devjanitor/scanner.py,sha256=olQJEWzBCbxjo7_tT3uywAiKmrITxuMuTIW9dzhnyhA,6127
6
+ devjanitor/targets.py,sha256=bHjddTSuRg_FxdyTVQtb7Snxv0YpGFIsE6DpvfqBE_Y,4313
7
+ devjanitor/utils.py,sha256=r4QZzKX57HYWNEn7JeIjMKOSS83YxL6h3p-9Re3JNgE,2933
8
+ devjanitor-0.1.0.dist-info/METADATA,sha256=LDZ_9WkdMX7R_LrOUBhNtYL3uzgRU2mp2i_8GivcDWs,6057
9
+ devjanitor-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
10
+ devjanitor-0.1.0.dist-info/entry_points.txt,sha256=yavpc2X9hvDsYuQFrvihpEOor5bnTzFMwOyaJQvV7OA,50
11
+ devjanitor-0.1.0.dist-info/licenses/LICENSE,sha256=6ILldh8wZaEQuP4PJK2rLfwHEvJWFtPtZA3f1-JZoPs,1070
12
+ devjanitor-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ devjanitor = devjanitor.cli:run
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 YuanChi Hsieh
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.