devsweep-cli 0.2.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.
devsweep/scanner.py ADDED
@@ -0,0 +1,418 @@
1
+ """Directory scanning and cleanable folder classification logic."""
2
+
3
+ import os
4
+ from collections.abc import Callable, Sequence
5
+ from datetime import datetime, timezone
6
+ from pathlib import Path
7
+
8
+ from devsweep.ignore import (
9
+ DEFAULT_IGNORE_PATTERNS,
10
+ IgnoreMatcher,
11
+ build_ignore_matcher,
12
+ )
13
+ from devsweep.models import FolderType, ScanResult, ScanSummary
14
+ from devsweep.utils import is_entry_link, is_path_junction, resolve_user_path
15
+
16
+ DEFAULT_IGNORED_DIRS: frozenset[str] = frozenset(DEFAULT_IGNORE_PATTERNS)
17
+
18
+ # Lowercase directory names commonly holding developer workspaces inside $HOME.
19
+ COMMON_PROJECT_DIR_NAMES: frozenset[str] = frozenset({
20
+ "projects",
21
+ "workspace",
22
+ "workspaces",
23
+ "work",
24
+ "dev",
25
+ "development",
26
+ "src",
27
+ "code",
28
+ "repos",
29
+ "repositories",
30
+ "github",
31
+ "gitlab",
32
+ "desktop",
33
+ "documents",
34
+ })
35
+
36
+ # Heavy OS/system folders inside $HOME skipped when falling back to scanning $HOME directly.
37
+ HOME_FALLBACK_EXCLUDES: tuple[str, ...] = (
38
+ "AppData",
39
+ "Application Data",
40
+ "Library",
41
+ ".Trash",
42
+ ".cache",
43
+ ".local",
44
+ "OneDrive",
45
+ "$RECYCLE.BIN",
46
+ "System Volume Information",
47
+ )
48
+
49
+ _CLEANABLE_FOLDER_MAP: dict[str, FolderType] = {
50
+ "node_modules": FolderType.NODE_MODULES,
51
+ ".venv": FolderType.VENV,
52
+ "venv": FolderType.VENV,
53
+ "target": FolderType.RUST_TARGET,
54
+ "dist": FolderType.DIST,
55
+ "build": FolderType.BUILD,
56
+ "__pycache__": FolderType.PYCACHE,
57
+ ".next": FolderType.NEXT,
58
+ ".nuxt": FolderType.NUXT,
59
+ "coverage": FolderType.COVERAGE,
60
+ ".pytest_cache": FolderType.PYTEST_CACHE,
61
+ ".gradle": FolderType.GRADLE,
62
+ ".turbo": FolderType.TURBO,
63
+ ".parcel-cache": FolderType.PARCEL_CACHE,
64
+ ".mypy_cache": FolderType.MYPY_CACHE,
65
+ ".ruff_cache": FolderType.RUFF_CACHE,
66
+ }
67
+
68
+ _VENV_MARKERS: tuple[tuple[str, ...], ...] = (
69
+ ("pyvenv.cfg",),
70
+ ("Scripts", "python.exe"),
71
+ ("Scripts", "activate"),
72
+ ("Scripts", "Activate.ps1"),
73
+ ("bin", "python"),
74
+ ("bin", "python3"),
75
+ ("bin", "activate"),
76
+ )
77
+
78
+
79
+ def _has_virtualenv_marker(path: Path) -> bool:
80
+ """Return True if path contains standard Python virtualenv marker files."""
81
+ for parts in _VENV_MARKERS:
82
+ try:
83
+ if path.joinpath(*parts).is_file():
84
+ return True
85
+ except OSError:
86
+ continue
87
+ return False
88
+
89
+
90
+ def classify_folder(path: Path) -> FolderType | None:
91
+ """Return the FolderType for a cleanable directory, or None if not cleanable."""
92
+ try:
93
+ if not path.is_dir() or path.is_symlink() or is_path_junction(path):
94
+ return None
95
+ except OSError:
96
+ return None
97
+
98
+ name = path.name
99
+ if name in _CLEANABLE_FOLDER_MAP:
100
+ return _CLEANABLE_FOLDER_MAP[name]
101
+
102
+ # Guard against matching plain config folders named `.env` unless it is a virtualenv.
103
+ if name == ".env" and _has_virtualenv_marker(path):
104
+ return FolderType.VENV
105
+
106
+ return None
107
+
108
+
109
+ def _classify_dir_entry(entry: os.DirEntry[str]) -> FolderType | None:
110
+ """Fast-path classification using DirEntry.name to avoid redundant syscalls."""
111
+ name = entry.name
112
+ folder_type = _CLEANABLE_FOLDER_MAP.get(name)
113
+ if folder_type is not None:
114
+ return folder_type
115
+
116
+ if name == ".env" and _has_virtualenv_marker(Path(entry.path)):
117
+ return FolderType.VENV
118
+
119
+ return None
120
+
121
+
122
+ def is_cleanable_folder(path: Path) -> bool:
123
+ """Return True if path is a recognized cleanable developer directory."""
124
+ return classify_folder(path) is not None
125
+
126
+
127
+ def _calculate_dir_size_str(path_str: str) -> int | None:
128
+ """Calculate directory byte size using raw str paths to minimize Path allocations."""
129
+ total_size = 0
130
+ try:
131
+ with os.scandir(path_str) as entries:
132
+ for entry in entries:
133
+ if is_entry_link(entry):
134
+ continue
135
+ try:
136
+ # On Windows, DirEntry.stat() reuses cached FindNextFile metadata.
137
+ if entry.is_file(follow_symlinks=False):
138
+ total_size += entry.stat(follow_symlinks=False).st_size
139
+ elif entry.is_dir(follow_symlinks=False):
140
+ sub_size = _calculate_dir_size_str(entry.path)
141
+ if sub_size is not None:
142
+ total_size += sub_size
143
+ except (PermissionError, OSError):
144
+ continue
145
+ except (PermissionError, OSError):
146
+ return None
147
+ return total_size
148
+
149
+
150
+ def calculate_dir_size(path: Path) -> int:
151
+ """Recursively calculate total byte size of a directory, skipping unreadable entries."""
152
+ size = _calculate_dir_size_str(os.fspath(path))
153
+ return 0 if size is None else size
154
+
155
+
156
+ def _walk_subdirectories(
157
+ dir_path_str: str,
158
+ rel_prefix: str,
159
+ depth: int,
160
+ max_depth: int | None,
161
+ matcher: IgnoreMatcher,
162
+ results: list[ScanResult],
163
+ skipped_errors: list[tuple[Path, str]] | None = None,
164
+ ) -> None:
165
+ """Walk directories in streaming scandir passes with depth and ignore pruning."""
166
+ # Stop descending once max_depth is reached (depth=0 means scan children at depth=1).
167
+ if max_depth is not None and depth >= max_depth:
168
+ return
169
+
170
+ try:
171
+ with os.scandir(dir_path_str) as entries:
172
+ for entry in entries:
173
+ if is_entry_link(entry):
174
+ continue
175
+ try:
176
+ if not entry.is_dir(follow_symlinks=False):
177
+ continue
178
+
179
+ name = entry.name
180
+ rel_posix = f"{rel_prefix}/{name}" if rel_prefix else name
181
+
182
+ # Prune ignored directories (CLI exclude > .devsweepignore > defaults).
183
+ if matcher.is_ignored(rel_posix, is_dir=True):
184
+ continue
185
+
186
+ folder_type = _classify_dir_entry(entry)
187
+ if folder_type is not None:
188
+ mtime = entry.stat(follow_symlinks=False).st_mtime
189
+ dir_size = _calculate_dir_size_str(entry.path)
190
+ if dir_size is None:
191
+ if skipped_errors is not None:
192
+ skipped_errors.append((Path(entry.path), "Permission denied"))
193
+ continue
194
+ results.append(
195
+ ScanResult(
196
+ path=Path(entry.path),
197
+ size_bytes=dir_size,
198
+ folder_type=folder_type,
199
+ modified_time=datetime.fromtimestamp(mtime, tz=timezone.utc),
200
+ )
201
+ )
202
+ # Prune traversal inside cleanable folders to prevent double counting.
203
+ continue
204
+
205
+ _walk_subdirectories(
206
+ entry.path,
207
+ rel_posix,
208
+ depth + 1,
209
+ max_depth,
210
+ matcher,
211
+ results,
212
+ skipped_errors,
213
+ )
214
+ except (PermissionError, OSError) as exc:
215
+ if skipped_errors is not None:
216
+ skipped_errors.append((Path(entry.path), str(exc)))
217
+ continue
218
+ except (PermissionError, OSError) as exc:
219
+ if skipped_errors is not None:
220
+ skipped_errors.append((Path(dir_path_str), str(exc)))
221
+
222
+
223
+ def get_smart_home_roots(home_dir: Path | None = None) -> tuple[list[Path], bool]:
224
+ """Return common project directories under $HOME if present, else fallback to [home]."""
225
+ home = (home_dir or Path.home()).expanduser().resolve()
226
+ project_roots: list[Path] = []
227
+ seen: set[str] = set()
228
+
229
+ try:
230
+ with os.scandir(home) as entries:
231
+ for entry in entries:
232
+ if is_entry_link(entry):
233
+ continue
234
+ try:
235
+ if not entry.is_dir(follow_symlinks=False):
236
+ continue
237
+ if entry.name.lower() in COMMON_PROJECT_DIR_NAMES:
238
+ resolved = Path(entry.path).resolve()
239
+ norm_key = os.path.normcase(str(resolved))
240
+ if norm_key not in seen:
241
+ seen.add(norm_key)
242
+ project_roots.append(resolved)
243
+ except (PermissionError, OSError):
244
+ continue
245
+ except (PermissionError, OSError):
246
+ return [home], False
247
+
248
+ if project_roots:
249
+ project_roots.sort(key=lambda p: p.name.lower())
250
+ return project_roots, True
251
+ return [home], False
252
+
253
+
254
+ def expand_scan_roots(
255
+ paths: Sequence[Path],
256
+ smart_home: bool = True,
257
+ home_dir: Path | None = None,
258
+ ) -> tuple[list[Path], bool]:
259
+ """Expand and deduplicate scan root paths, applying smart home discovery when enabled."""
260
+ home_resolved = (home_dir or Path.home()).expanduser().resolve()
261
+ home_norm = os.path.normcase(str(home_resolved))
262
+
263
+ expanded: list[Path] = []
264
+ seen: set[str] = set()
265
+ used_smart_home = False
266
+
267
+ for raw_path in paths:
268
+ target = resolve_user_path(raw_path)
269
+ if not target.exists():
270
+ raise FileNotFoundError(f"Directory does not exist: {raw_path}")
271
+ if not target.is_dir():
272
+ raise NotADirectoryError(f"Path is not a directory: {raw_path}")
273
+
274
+ if smart_home and os.path.normcase(str(target)) == home_norm:
275
+ home_roots, used_common = get_smart_home_roots(home_resolved)
276
+ used_smart_home = used_common or used_smart_home
277
+ candidates = home_roots
278
+ else:
279
+ candidates = [target]
280
+
281
+ for candidate in candidates:
282
+ norm_key = os.path.normcase(str(candidate))
283
+ if norm_key not in seen:
284
+ seen.add(norm_key)
285
+ expanded.append(candidate)
286
+
287
+ return expanded, used_smart_home
288
+
289
+
290
+ def scan_directory(
291
+ path: Path,
292
+ *,
293
+ max_depth: int | None = None,
294
+ exclude_patterns: Sequence[str] = (),
295
+ use_default_ignores: bool = True,
296
+ ignore_file: Path | None = None,
297
+ ignore_matcher: IgnoreMatcher | None = None,
298
+ extra_default_ignores: Sequence[str] = (),
299
+ ) -> list[ScanResult]:
300
+ """Scan a single directory recursively for cleanable developer folders."""
301
+ if max_depth is not None and max_depth < 0:
302
+ raise ValueError(f"max_depth must be non-negative, got {max_depth}")
303
+
304
+ target = path.expanduser()
305
+ if not target.exists():
306
+ raise FileNotFoundError(f"Directory does not exist: {path}")
307
+ if not target.is_dir():
308
+ raise NotADirectoryError(f"Path is not a directory: {path}")
309
+
310
+ matcher = ignore_matcher or build_ignore_matcher(
311
+ target,
312
+ cli_excludes=exclude_patterns,
313
+ ignore_file=ignore_file,
314
+ use_default_ignores=use_default_ignores,
315
+ extra_default_patterns=extra_default_ignores,
316
+ )
317
+
318
+ results: list[ScanResult] = []
319
+ _walk_subdirectories(
320
+ os.fspath(target),
321
+ "",
322
+ 0,
323
+ max_depth,
324
+ matcher,
325
+ results,
326
+ )
327
+ results.sort(key=lambda item: item.path)
328
+ return results
329
+
330
+
331
+ def scan_paths(
332
+ paths: Sequence[Path],
333
+ *,
334
+ max_depth: int | None = None,
335
+ exclude_patterns: Sequence[str] = (),
336
+ use_default_ignores: bool = True,
337
+ ignore_file: Path | None = None,
338
+ smart_home: bool = True,
339
+ home_dir: Path | None = None,
340
+ on_root_progress: Callable[[Path, int, int], None] | None = None,
341
+ ) -> list[ScanResult]:
342
+ """Scan multiple root paths and deduplicate discovered cleanable folders."""
343
+ if max_depth is not None and max_depth < 0:
344
+ raise ValueError(f"max_depth must be non-negative, got {max_depth}")
345
+
346
+ if not paths:
347
+ return []
348
+
349
+ home_resolved = (home_dir or Path.home()).expanduser().resolve()
350
+ home_norm = os.path.normcase(str(home_resolved))
351
+ roots, used_common_home = expand_scan_roots(
352
+ paths,
353
+ smart_home=smart_home,
354
+ home_dir=home_resolved,
355
+ )
356
+
357
+ home_matcher: IgnoreMatcher | None = None
358
+ if used_common_home:
359
+ home_matcher = build_ignore_matcher(
360
+ home_resolved,
361
+ cli_excludes=exclude_patterns,
362
+ ignore_file=ignore_file,
363
+ use_default_ignores=use_default_ignores,
364
+ )
365
+
366
+ extra_defaults: tuple[str, ...] = ()
367
+ # When $HOME has no common workspace folders, skip heavy OS directories by default.
368
+ if smart_home and not used_common_home:
369
+ for root in roots:
370
+ if os.path.normcase(str(root)) == home_norm:
371
+ extra_defaults = HOME_FALLBACK_EXCLUDES
372
+ break
373
+
374
+ active_roots: list[Path] = []
375
+ for root in roots:
376
+ if home_matcher is not None and home_matcher.is_ignored(root.name, is_dir=True):
377
+ continue
378
+ active_roots.append(root)
379
+
380
+ results: list[ScanResult] = []
381
+ seen_items: set[str] = set()
382
+ total_roots = len(active_roots)
383
+ for idx, root in enumerate(active_roots, start=1):
384
+ if on_root_progress is not None:
385
+ on_root_progress(root, idx, total_roots)
386
+
387
+ for item in scan_directory(
388
+ root,
389
+ max_depth=max_depth,
390
+ exclude_patterns=exclude_patterns,
391
+ use_default_ignores=use_default_ignores,
392
+ ignore_file=ignore_file,
393
+ extra_default_ignores=extra_defaults,
394
+ ):
395
+ norm_key = os.path.normcase(str(item.path.resolve()))
396
+ if norm_key not in seen_items:
397
+ seen_items.add(norm_key)
398
+ results.append(item)
399
+
400
+ results.sort(key=lambda item: item.path)
401
+ return results
402
+
403
+
404
+ def calculate_total_size(results: Sequence[ScanResult]) -> int:
405
+ """Return the sum of size_bytes across the given ScanResult items."""
406
+ return sum(item.size_bytes for item in results)
407
+
408
+
409
+ def summarize_scan(
410
+ results: list[ScanResult],
411
+ skipped_errors: list[tuple[Path, str]] | None = None,
412
+ ) -> ScanSummary:
413
+ """Build a ScanSummary from scanned results."""
414
+ return ScanSummary(
415
+ total_size=calculate_total_size(results),
416
+ items=results,
417
+ skipped_errors=skipped_errors if skipped_errors is not None else [],
418
+ )
devsweep/utils.py ADDED
@@ -0,0 +1,58 @@
1
+ """Shared formatting and filesystem helper utilities."""
2
+
3
+ import os
4
+ from pathlib import Path
5
+
6
+ _SIZE_UNITS: tuple[str, ...] = ("B", "KB", "MB", "GB", "TB", "PB")
7
+
8
+
9
+ def format_size(size_bytes: int) -> str:
10
+ """Format a byte count into a human-readable string (e.g. '1.5 GB', '340 MB')."""
11
+ if size_bytes < 0:
12
+ raise ValueError(f"size_bytes must be non-negative, got {size_bytes}")
13
+
14
+ if size_bytes < 1024:
15
+ return f"{size_bytes} B"
16
+
17
+ value = float(size_bytes)
18
+ unit_index = 0
19
+ while value >= 1024.0 and unit_index < len(_SIZE_UNITS) - 1:
20
+ value /= 1024.0
21
+ unit_index += 1
22
+
23
+ formatted = f"{value:.1f}".rstrip("0").rstrip(".")
24
+ return f"{formatted} {_SIZE_UNITS[unit_index]}"
25
+
26
+
27
+ def is_entry_link(entry: os.DirEntry[str]) -> bool:
28
+ """Return True if a directory entry is a symlink or Windows NTFS junction."""
29
+ try:
30
+ if entry.is_symlink():
31
+ return True
32
+ is_junction = getattr(entry, "is_junction", None)
33
+ if callable(is_junction):
34
+ return bool(is_junction())
35
+ return is_path_junction(Path(entry.path))
36
+ except OSError:
37
+ return True
38
+
39
+
40
+ def resolve_user_path(path: Path) -> Path:
41
+ """Expand leading `~` using Path.home() and resolve to an absolute path."""
42
+ raw = str(path)
43
+ if raw == "~":
44
+ return Path.home().resolve()
45
+ if raw.startswith(("~/", "~\\")):
46
+ return (Path.home() / raw[2:]).resolve()
47
+ return path.expanduser().resolve()
48
+
49
+
50
+ def is_path_junction(path: Path) -> bool:
51
+ """Return True if path is a Windows NTFS junction (safe fallback on <3.12)."""
52
+ isjunction = getattr(os.path, "isjunction", None)
53
+ if callable(isjunction):
54
+ try:
55
+ return bool(isjunction(path))
56
+ except OSError:
57
+ return False
58
+ return False