devjanitor 0.1.2__tar.gz → 0.1.3__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: devjanitor
3
- Version: 0.1.2
3
+ Version: 0.1.3
4
4
  Summary: Find and delete node_modules, .venv, target/ and other dev junk to free disk space.
5
5
  License-Expression: MIT
6
6
  License-File: LICENSE
@@ -1,3 +1,3 @@
1
1
  """devjanitor: reclaim disk space from dependency folders, build output and caches."""
2
2
 
3
- __version__ = "0.1.2"
3
+ __version__ = "0.1.3"
@@ -19,7 +19,7 @@ from rich.table import Table
19
19
 
20
20
  from . import __version__
21
21
  from .caches import CACHES, find_caches
22
- from .scanner import Found, find_targets, measure
22
+ from .scanner import Found, find_targets, group_scattered, measure
23
23
  from .targets import TARGETS
24
24
  from .utils import display_path, human_size, parse_selection, parse_size, time_ago
25
25
 
@@ -132,17 +132,21 @@ def render(items: List[Found], root: Optional[Path]) -> None:
132
132
  for i, item in enumerate(items, 1):
133
133
  style = ECO_STYLE.get(item.target.ecosystem, "")
134
134
  size_style = "bold red" if item.size >= max(biggest * 0.5, 500 * 1024**2) else ""
135
+ kind = item.target.dir_name
136
+ if item.members:
137
+ kind += f" [dim]×{item.count}[/]"
135
138
  table.add_row(
136
139
  str(i),
137
140
  display_path(item.path, root),
138
- f"[{style}]{item.target.dir_name}[/]",
141
+ f"[{style}]{kind}[/]",
139
142
  f"[{size_style}]{human_size(item.size)}[/]" if size_style else human_size(item.size),
140
143
  time_ago(item.last_activity),
141
144
  )
142
145
  console.print(table)
143
146
  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}, "
147
+ count = sum(i.count for i in items)
148
+ noun = "directory" if count == 1 else "directories"
149
+ console.print(f"\n[bold]{count}[/] {noun}, "
146
150
  f"[bold green]{human_size(total)}[/] reclaimable\n")
147
151
 
148
152
 
@@ -164,17 +168,22 @@ def delete(items: List[Found]) -> int:
164
168
  task = progress.add_task("", total=len(items))
165
169
  for item in items:
166
170
  progress.update(task, description=item.path.name)
167
- try:
168
- if sys.version_info >= (3, 12):
169
- shutil.rmtree(item.path, onexc=_make_writable_and_retry)
170
- else:
171
- shutil.rmtree(item.path, onerror=_make_writable_and_retry)
171
+ ok = True
172
+ # A grouped row deletes its member folders, never item.path itself.
173
+ for path in item.paths_to_delete:
174
+ try:
175
+ if sys.version_info >= (3, 12):
176
+ shutil.rmtree(path, onexc=_make_writable_and_retry)
177
+ else:
178
+ shutil.rmtree(path, onerror=_make_writable_and_retry)
179
+ except OSError as exc:
180
+ failed.append((path, exc))
181
+ ok = False
182
+ if ok:
172
183
  freed += item.size
173
- except OSError as exc:
174
- failed.append((item, exc))
175
184
  progress.advance(task)
176
- for item, exc in failed:
177
- err.print(f"[red]✗ could not delete {item.path}: {exc}[/]")
185
+ for path, exc in failed:
186
+ err.print(f"[red]✗ could not delete {path}: {exc}[/]")
178
187
  return freed
179
188
 
180
189
 
@@ -210,10 +219,11 @@ def main(argv: Optional[List[str]] = None) -> int:
210
219
  cutoff = time.time() - args.older_than * 86400
211
220
  items = [i for i in items
212
221
  if i.is_global or (i.last_activity and i.last_activity < cutoff)]
213
- items = [i for i in items if i.size >= args.min_size]
214
- items.sort(key=lambda i: i.size, reverse=True)
215
222
 
216
223
  if args.json:
224
+ # One entry per directory: scripts get exact paths, never groups.
225
+ items = [i for i in items if i.size >= args.min_size]
226
+ items.sort(key=lambda i: i.size, reverse=True)
217
227
  print(json.dumps([{
218
228
  "path": str(i.path), "type": i.target.dir_name,
219
229
  "ecosystem": i.target.ecosystem, "bytes": i.size,
@@ -221,6 +231,10 @@ def main(argv: Optional[List[str]] = None) -> int:
221
231
  } for i in items], indent=2))
222
232
  return 0
223
233
 
234
+ items = group_scattered(items, roots)
235
+ items = [i for i in items if i.size >= args.min_size]
236
+ items.sort(key=lambda i: i.size, reverse=True)
237
+
224
238
  elapsed = time.monotonic() - started
225
239
  if not items:
226
240
  console.print(f"[green]✨ Nothing to clean[/] [dim](scanned in {elapsed:.1f}s)[/]")
@@ -251,7 +265,8 @@ def main(argv: Optional[List[str]] = None) -> int:
251
265
  return 0
252
266
  chosen = [items[i] for i in indexes]
253
267
  size = human_size(sum(i.size for i in chosen))
254
- if not Confirm.ask(f"Permanently delete [bold]{len(chosen)}[/] directories "
268
+ count = sum(i.count for i in chosen)
269
+ if not Confirm.ask(f"Permanently delete [bold]{count}[/] directories "
255
270
  f"([bold]{size}[/])?", default=False):
256
271
  console.print("Nothing deleted.")
257
272
  return 0
@@ -12,20 +12,32 @@ from typing import Callable, Iterable, Iterator, List, Optional, Set
12
12
 
13
13
  from .targets import Target, match
14
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
- }
15
+ # Directories that are never worth descending into. Installed packages
16
+ # (site-packages) can ship their own node_modules that are not regenerable.
17
+ SKIP_NAMES = {".git", ".hg", ".svn", ".Trash", ".cache", "System Volume Information",
18
+ "site-packages", "dist-packages"}
19
+
20
+ # Folders directly in the home directory that belong to tools, not to the
21
+ # user's projects. The node_modules inside ~/.vscode/extensions or
22
+ # ~/.nvm/versions are part of installed software: deleting them breaks it.
23
+ # Hidden folders (~/.vscode, ~/.nvm, ~/.local, ~/.cursor, ...) are skipped too.
24
+ HOME_SKIP_NAMES = {"Library", "AppData", "Applications", "go", "miniconda3",
25
+ "anaconda3", "miniforge3", "mambaforge", "opt"}
26
+
27
+ SYSTEM_SKIP_PATHS = set()
27
28
  if sys.platform == "darwin":
28
- SKIP_PATHS |= {Path("/System"), Path("/Library"), Path("/private"), Path("/Volumes")}
29
+ SYSTEM_SKIP_PATHS = {Path("/System"), Path("/Library"), Path("/private"),
30
+ Path("/Volumes"), Path("/Applications")}
31
+
32
+
33
+ def is_tool_managed(path: Path, home: Path) -> bool:
34
+ """True for folders that installed software owns, which are never scanned
35
+ unless the user passes them as a root explicitly."""
36
+ if path.name in SKIP_NAMES or path in SYSTEM_SKIP_PATHS:
37
+ return True
38
+ if path.parent == home:
39
+ return path.name.startswith(".") or path.name in HOME_SKIP_NAMES
40
+ return False
29
41
 
30
42
 
31
43
  @dataclass
@@ -36,8 +48,79 @@ class Found:
36
48
  last_activity: float = 0.0 # unix time of the newest change in the project
37
49
  errors: int = 0
38
50
  is_global: bool = False # a per-user cache rather than a project folder
51
+ # For a grouped row: the directories that are actually deleted. ``path``
52
+ # is then the project they belong to and must never be deleted itself.
53
+ members: List[Path] = field(default_factory=list)
39
54
  extra: dict = field(default_factory=dict)
40
55
 
56
+ @property
57
+ def paths_to_delete(self) -> List[Path]:
58
+ return self.members or [self.path]
59
+
60
+ @property
61
+ def count(self) -> int:
62
+ return len(self.members) or 1
63
+
64
+
65
+ # Small directories that projects scatter by the dozen. Each project's copies
66
+ # are shown as one row instead of one row per folder.
67
+ GROUPED_NAMES = {"__pycache__"}
68
+
69
+ PROJECT_MARKERS = (".git", "pyproject.toml", "setup.py", "setup.cfg",
70
+ "requirements.txt", "package.json", "Cargo.toml", "go.mod")
71
+
72
+
73
+ def project_root(path: Path, stop: Path, cache: dict) -> Path:
74
+ """Nearest ancestor of ``path`` (up to ``stop``) that looks like a project."""
75
+ current = path.parent
76
+ walked = []
77
+ while True:
78
+ if current in cache:
79
+ result = cache[current]
80
+ break
81
+ walked.append(current)
82
+ if any((current / m).exists() for m in PROJECT_MARKERS):
83
+ result = current
84
+ break
85
+ if current == stop or current.parent == current:
86
+ # No project marker: group under the top-level folder of the
87
+ # scan root rather than lumping everything into the root itself.
88
+ result = walked[-2] if len(walked) >= 2 else stop
89
+ break
90
+ current = current.parent
91
+ for p in walked:
92
+ if p != stop: # the root's answer depends on which child we came from
93
+ cache[p] = result
94
+ return result
95
+
96
+
97
+ def group_scattered(items: List[Found], roots: List[Path]) -> List[Found]:
98
+ """Merge the GROUPED_NAMES folders of each project into one row."""
99
+ cache: dict = {}
100
+ groups: dict = {}
101
+ result: List[Found] = []
102
+ for item in items:
103
+ if item.is_global or item.target.dir_name not in GROUPED_NAMES:
104
+ result.append(item)
105
+ continue
106
+ stop = next((r for r in roots if r == item.path or r in item.path.parents),
107
+ item.path.parent)
108
+ key = (project_root(item.path, stop, cache), item.target.dir_name)
109
+ groups.setdefault(key, []).append(item)
110
+ for (project, _), members in groups.items():
111
+ if len(members) == 1:
112
+ result.append(members[0])
113
+ continue
114
+ result.append(Found(
115
+ path=project,
116
+ target=members[0].target,
117
+ size=sum(m.size for m in members),
118
+ last_activity=max(m.last_activity for m in members),
119
+ errors=sum(m.errors for m in members),
120
+ members=sorted(m.path for m in members),
121
+ ))
122
+ return result
123
+
41
124
 
42
125
  def _disk_usage(st: os.stat_result) -> int:
43
126
  # st_blocks reflects the space actually freed on deletion (sparse files,
@@ -139,6 +222,10 @@ def find_targets(
139
222
  inside ``node_modules`` is reported only once, as part of its parent.
140
223
  """
141
224
  seen: Set[str] = set()
225
+ try:
226
+ home = Path.home().resolve()
227
+ except (OSError, RuntimeError):
228
+ home = Path("/nonexistent")
142
229
  for root in roots:
143
230
  root = Path(root).expanduser().resolve()
144
231
  stack = [root]
@@ -165,7 +252,7 @@ def find_targets(
165
252
  if target is not None:
166
253
  yield Found(path=path, target=target)
167
254
  continue
168
- if entry.name in SKIP_NAMES or path in SKIP_PATHS:
255
+ if is_tool_managed(path, home):
169
256
  continue
170
257
  stack.append(path)
171
258
 
@@ -270,3 +270,84 @@ def test_delete_read_only_files(tmp_path):
270
270
  os.chmod(f.parent, st.S_IRUSR | st.S_IXUSR)
271
271
  assert main([str(tmp_path), "--yes"]) == 0
272
272
  assert not (tmp_path / "p/node_modules").exists()
273
+
274
+
275
+ # --- tool-managed folders ---------------------------------------------------
276
+
277
+ def test_skips_tool_managed_folders_in_home(fake_home):
278
+ # Installed software: deleting these node_modules would break it.
279
+ make(fake_home / ".vscode/extensions/ms-python/node_modules/x.js")
280
+ make(fake_home / ".vscode/extensions/ms-python/package.json", b"{}")
281
+ make(fake_home / ".nvm/versions/node/v22/lib/node_modules/npm/index.js")
282
+ make(fake_home / "miniconda3/pkgs/x/node_modules/y.js")
283
+ make(fake_home / "venvs/tool/lib/python3.12/site-packages/jupyterlab/node_modules/z.js")
284
+ # A real project in the home folder is still found.
285
+ make(fake_home / "code/app/package.json", b"{}")
286
+ make(fake_home / "code/app/node_modules/a.js")
287
+ found = names(find_targets([fake_home]), fake_home)
288
+ assert found == ["code/app/node_modules"]
289
+
290
+
291
+ def test_explicit_root_inside_hidden_home_folder_is_scanned(fake_home):
292
+ make(fake_home / ".config/myproj/package.json", b"{}")
293
+ make(fake_home / ".config/myproj/node_modules/a.js")
294
+ root = fake_home / ".config"
295
+ assert names(find_targets([root]), root) == ["myproj/node_modules"]
296
+
297
+
298
+ # --- grouping scattered __pycache__ -----------------------------------------
299
+
300
+ @pytest.fixture
301
+ def pycache_tree(tmp_path):
302
+ make(tmp_path / "comfy/pyproject.toml", b"")
303
+ for pkg in ["nodes", "models", "utils/io", "utils/net"]:
304
+ make(tmp_path / f"comfy/{pkg}/mod.py", b"print()")
305
+ make(tmp_path / f"comfy/{pkg}/__pycache__/mod.cpython-312.pyc")
306
+ make(tmp_path / "other/requirements.txt", b"")
307
+ make(tmp_path / "other/a/__pycache__/x.pyc")
308
+ make(tmp_path / "other/b/__pycache__/y.pyc")
309
+ make(tmp_path / "solo/setup.py", b"")
310
+ make(tmp_path / "solo/__pycache__/z.pyc")
311
+ return tmp_path
312
+
313
+
314
+ def test_group_scattered_per_project(pycache_tree):
315
+ from devjanitor.scanner import group_scattered
316
+ items = measure(list(find_targets([pycache_tree])))
317
+ rows = {r.path.relative_to(pycache_tree).as_posix(): r
318
+ for r in group_scattered(items, [pycache_tree])}
319
+ assert set(rows) == {"comfy", "other", "solo/__pycache__"}
320
+ assert rows["comfy"].count == 4
321
+ assert rows["other"].count == 2
322
+ assert rows["solo/__pycache__"].members == []
323
+ assert rows["comfy"].size == sum(i.size for i in items
324
+ if "comfy" in i.path.parts)
325
+
326
+
327
+ def test_deleting_group_keeps_project(pycache_tree):
328
+ assert main([str(pycache_tree), "--yes"]) == 0
329
+ assert (pycache_tree / "comfy/pyproject.toml").exists()
330
+ assert (pycache_tree / "comfy/nodes/mod.py").exists()
331
+ assert (pycache_tree / "other/a").exists()
332
+ assert not list(pycache_tree.rglob("__pycache__"))
333
+
334
+
335
+ def test_json_is_not_grouped(pycache_tree, capsys):
336
+ import json
337
+ assert main([str(pycache_tree), "--json"]) == 0
338
+ assert len(json.loads(capsys.readouterr().out)) == 7
339
+
340
+
341
+ def test_table_shows_group_count(pycache_tree, capsys):
342
+ assert main([str(pycache_tree), "-n"]) == 0
343
+ out = capsys.readouterr().out
344
+ assert "×4" in out and "×2" in out
345
+ assert "7 directories" in out
346
+
347
+
348
+ def test_group_without_marker_uses_top_level_folder(tmp_path):
349
+ from devjanitor.scanner import group_scattered
350
+ for sub in ["env/lib/a", "env/lib/b", "tools/x", "tools/y"]:
351
+ make(tmp_path / sub / "__pycache__/m.pyc")
352
+ rows = group_scattered(measure(list(find_targets([tmp_path]))), [tmp_path])
353
+ assert sorted(r.path.name for r in rows) == ["env", "tools"]
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes