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/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """DevSweep package initialization and version metadata."""
2
+
3
+ __version__ = "0.2.0"
4
+
5
+ __all__ = ["__version__"]
devsweep/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ """Allow running DevSweep via `python -m devsweep`."""
2
+
3
+ from devsweep.cli import app
4
+
5
+ if __name__ == "__main__":
6
+ app()
devsweep/cleaner.py ADDED
@@ -0,0 +1,247 @@
1
+ """Safe folder deletion and protected path validation logic."""
2
+
3
+ import os
4
+ import posixpath
5
+ import shutil
6
+ import sys
7
+ from collections.abc import Callable, Mapping, Sequence
8
+ from pathlib import Path, PurePath, PurePosixPath, PureWindowsPath
9
+
10
+ from devsweep.models import DeleteResult
11
+ from devsweep.scanner import calculate_dir_size, is_cleanable_folder
12
+ from devsweep.utils import is_path_junction
13
+
14
+ _POSIX_ANCESTOR_PROTECTED: tuple[str, ...] = (
15
+ "/",
16
+ "/home",
17
+ "/Users",
18
+ "/tmp",
19
+ "/var",
20
+ "/opt",
21
+ "/mnt",
22
+ "/media",
23
+ "/Applications",
24
+ "/Volumes",
25
+ "/private",
26
+ )
27
+
28
+ _POSIX_SYSTEM_TREE_PROTECTED: tuple[str, ...] = (
29
+ "/bin",
30
+ "/boot",
31
+ "/dev",
32
+ "/etc",
33
+ "/lib",
34
+ "/lib64",
35
+ "/proc",
36
+ "/root",
37
+ "/run",
38
+ "/sbin",
39
+ "/srv",
40
+ "/sys",
41
+ "/usr",
42
+ "/System",
43
+ "/Library",
44
+ )
45
+
46
+ _WINDOWS_SYSTEM_TREE_LITERAL: tuple[str, ...] = (
47
+ "C:\\Windows",
48
+ "C:\\Program Files",
49
+ "C:\\Program Files (x86)",
50
+ )
51
+
52
+ _WINDOWS_ANCESTOR_LITERAL: tuple[str, ...] = (
53
+ "C:\\",
54
+ "C:\\Users",
55
+ "C:\\ProgramData",
56
+ )
57
+
58
+
59
+ def _normalize_path(path: Path) -> Path:
60
+ """Resolve and normalize path casing for the host platform."""
61
+ resolved = path.expanduser().resolve()
62
+ return Path(os.path.normcase(str(resolved)))
63
+
64
+
65
+ def _is_same_or_ancestor(candidate: PurePath, protected: PurePath) -> bool:
66
+ """Return True if candidate is identical to or a parent directory of protected."""
67
+ if candidate == protected:
68
+ return True
69
+ return protected.is_relative_to(candidate)
70
+
71
+
72
+ def _is_within_tree(candidate: PurePath, protected_root: PurePath) -> bool:
73
+ """Return True if candidate is identical to, an ancestor of, or inside protected_root."""
74
+ return _is_same_or_ancestor(candidate, protected_root) or candidate.is_relative_to(
75
+ protected_root
76
+ )
77
+
78
+
79
+ def get_protected_paths() -> tuple[list[Path], list[Path]]:
80
+ """Return (ancestor_protected, system_tree_protected) normalized paths."""
81
+ home = Path.home()
82
+ ancestor_raw: list[Path] = [home, home.parent]
83
+ system_raw: list[Path] = []
84
+
85
+ if os.name == "nt" or sys.platform == "win32":
86
+ system_drive = os.environ.get("SystemDrive", "C:")
87
+ system_root = (
88
+ os.environ.get("SystemRoot")
89
+ or os.environ.get("WINDIR")
90
+ or f"{system_drive}\\Windows"
91
+ )
92
+ prog_files = os.environ.get("ProgramFiles", f"{system_drive}\\Program Files")
93
+ prog_files_x86 = os.environ.get("ProgramFiles(x86)", f"{system_drive}\\Program Files (x86)")
94
+ prog_data = os.environ.get("ProgramData", f"{system_drive}\\ProgramData")
95
+
96
+ ancestor_raw.extend(
97
+ [Path(f"{system_drive}\\"), Path(f"{system_drive}\\Users"), Path(prog_data)]
98
+ )
99
+ system_raw.extend([Path(system_root), Path(prog_files), Path(prog_files_x86)])
100
+ else:
101
+ ancestor_raw.extend(Path(p) for p in _POSIX_ANCESTOR_PROTECTED)
102
+ system_raw.extend(Path(p) for p in _POSIX_SYSTEM_TREE_PROTECTED)
103
+
104
+ ancestor_protected = [_normalize_path(p) for p in ancestor_raw]
105
+ system_protected = [_normalize_path(p) for p in system_raw]
106
+ return ancestor_protected, system_protected
107
+
108
+
109
+ def _matches_literal_cross_platform_protected(path: Path) -> bool:
110
+ """Catch POSIX protected literals on Windows and Windows protected literals on POSIX."""
111
+ if not path.drive and path.as_posix().startswith("/"):
112
+ posix_path = PurePosixPath(posixpath.normpath(path.as_posix()))
113
+ for raw_ancestor in _POSIX_ANCESTOR_PROTECTED:
114
+ if _is_same_or_ancestor(posix_path, PurePosixPath(raw_ancestor)):
115
+ return True
116
+ for raw_tree in _POSIX_SYSTEM_TREE_PROTECTED:
117
+ if _is_within_tree(posix_path, PurePosixPath(raw_tree)):
118
+ return True
119
+
120
+ raw_str = str(path)
121
+ if len(raw_str) >= 2 and raw_str[1] == ":":
122
+ win_path = PureWindowsPath(raw_str.lower())
123
+ for raw_ancestor in _WINDOWS_ANCESTOR_LITERAL:
124
+ if _is_same_or_ancestor(win_path, PureWindowsPath(raw_ancestor.lower())):
125
+ return True
126
+ for raw_tree in _WINDOWS_SYSTEM_TREE_LITERAL:
127
+ if _is_within_tree(win_path, PureWindowsPath(raw_tree.lower())):
128
+ return True
129
+
130
+ return False
131
+
132
+
133
+ def is_protected_path(path: Path) -> bool:
134
+ """Return True if path targets or threatens a critical OS or user root directory."""
135
+ if _matches_literal_cross_platform_protected(path):
136
+ return True
137
+
138
+ try:
139
+ normalized = _normalize_path(path)
140
+ except OSError:
141
+ return True
142
+
143
+ # Protect every filesystem / drive root (e.g. '/', 'C:\\', 'D:\\').
144
+ if normalized == normalized.parent or len(normalized.parts) <= 1:
145
+ return True
146
+
147
+ ancestor_protected, system_protected = get_protected_paths()
148
+ for protected in ancestor_protected:
149
+ if _is_same_or_ancestor(normalized, protected):
150
+ return True
151
+
152
+ for protected_tree in system_protected:
153
+ if _is_within_tree(normalized, protected_tree):
154
+ return True
155
+
156
+ return False
157
+
158
+
159
+ def validate_deletion_target(
160
+ path: Path,
161
+ allowed_roots: Sequence[Path] | None = None,
162
+ require_cleanable: bool = True,
163
+ ) -> tuple[bool, str | None]:
164
+ """Validate that path is safe to delete and within allowed cleanup boundaries."""
165
+ try:
166
+ if path.is_symlink() or is_path_junction(path):
167
+ return False, "Refusing to delete symlink or NTFS junction."
168
+ except OSError as exc:
169
+ return False, str(exc)
170
+
171
+ try:
172
+ resolved = path.expanduser().resolve()
173
+ except OSError as exc:
174
+ return False, str(exc)
175
+
176
+ if is_protected_path(resolved):
177
+ return False, f"Protected path cannot be deleted: {resolved}"
178
+
179
+ norm_target = _normalize_path(resolved)
180
+ if allowed_roots is not None:
181
+ normalized_roots = [_normalize_path(root) for root in allowed_roots]
182
+ in_scope = any(
183
+ norm_target != root and norm_target.is_relative_to(root)
184
+ for root in normalized_roots
185
+ )
186
+ if not in_scope:
187
+ return False, f"Path is outside allowed cleanup scope: {resolved}"
188
+
189
+ if not resolved.exists():
190
+ return False, f"Path does not exist: {resolved}"
191
+ if not resolved.is_dir():
192
+ return False, f"Path is not a directory: {resolved}"
193
+
194
+ if require_cleanable and not is_cleanable_folder(resolved):
195
+ return False, f"Path is not a recognized cleanable folder: {resolved}"
196
+
197
+ return True, None
198
+
199
+
200
+ def delete_folders(
201
+ paths: Sequence[Path],
202
+ allowed_roots: Sequence[Path] | None = None,
203
+ sizes: Mapping[Path, int] | None = None,
204
+ require_cleanable: bool = True,
205
+ dry_run: bool = False,
206
+ on_progress: Callable[[Path, int, int], None] | None = None,
207
+ ) -> DeleteResult:
208
+ """Safely delete validated directories using shutil.rmtree and return DeleteResult."""
209
+ result = DeleteResult()
210
+ total = len(paths)
211
+ normalized_sizes: dict[Path, int] = (
212
+ {_normalize_path(k): v for k, v in sizes.items()} if sizes is not None else {}
213
+ )
214
+
215
+ for index, raw_path in enumerate(paths, start=1):
216
+ if on_progress is not None:
217
+ on_progress(raw_path, index, total)
218
+
219
+ is_valid, reason = validate_deletion_target(
220
+ raw_path,
221
+ allowed_roots=allowed_roots,
222
+ require_cleanable=require_cleanable,
223
+ )
224
+ if not is_valid:
225
+ result.skipped.append((raw_path, reason or "Validation failed"))
226
+ continue
227
+
228
+ resolved = raw_path.expanduser().resolve()
229
+ norm_key = _normalize_path(resolved)
230
+ folder_size = normalized_sizes.get(norm_key)
231
+ if folder_size is None:
232
+ folder_size = calculate_dir_size(resolved)
233
+
234
+ if dry_run:
235
+ result.skipped.append((raw_path, "Dry run - no files deleted"))
236
+ continue
237
+
238
+ try:
239
+ shutil.rmtree(resolved)
240
+ except (PermissionError, OSError) as exc:
241
+ result.failed.append((raw_path, str(exc)))
242
+ continue
243
+
244
+ result.deleted.append(raw_path)
245
+ result.freed_bytes += folder_size
246
+
247
+ return result