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 +5 -0
- devsweep/__main__.py +6 -0
- devsweep/cleaner.py +247 -0
- devsweep/cli.py +581 -0
- devsweep/display.py +909 -0
- devsweep/docker.py +307 -0
- devsweep/ignore.py +272 -0
- devsweep/models.py +132 -0
- devsweep/scanner.py +418 -0
- devsweep/utils.py +58 -0
- devsweep_cli-0.2.0.dist-info/METADATA +249 -0
- devsweep_cli-0.2.0.dist-info/RECORD +16 -0
- devsweep_cli-0.2.0.dist-info/WHEEL +5 -0
- devsweep_cli-0.2.0.dist-info/entry_points.txt +2 -0
- devsweep_cli-0.2.0.dist-info/licenses/LICENSE +21 -0
- devsweep_cli-0.2.0.dist-info/top_level.txt +1 -0
devsweep/docker.py
ADDED
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
"""Safe Docker resource discovery and cleanup helpers."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import re
|
|
5
|
+
import shutil
|
|
6
|
+
import subprocess
|
|
7
|
+
from collections.abc import Callable, Sequence
|
|
8
|
+
|
|
9
|
+
from devsweep.models import DockerCleanResult, DockerResource, DockerResourceType
|
|
10
|
+
|
|
11
|
+
_DOCKER_SIZE_RE = re.compile(r"^\s*([0-9]+(?:\.[0-9]+)?)\s*([kKmMgGtTpP]?i?[bB])")
|
|
12
|
+
|
|
13
|
+
_SIZE_MULTIPLIERS: dict[str, int] = {
|
|
14
|
+
"b": 1,
|
|
15
|
+
"kb": 1000,
|
|
16
|
+
"mb": 1000**2,
|
|
17
|
+
"gb": 1000**3,
|
|
18
|
+
"tb": 1000**4,
|
|
19
|
+
"pb": 1000**5,
|
|
20
|
+
"kib": 1024,
|
|
21
|
+
"mib": 1024**2,
|
|
22
|
+
"gib": 1024**3,
|
|
23
|
+
"tib": 1024**4,
|
|
24
|
+
"pib": 1024**5,
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def parse_docker_size(raw: str) -> int:
|
|
29
|
+
"""Parse a Docker CLI human-readable size string (e.g. '1.5GB', '12MB (virtual 100MB)')."""
|
|
30
|
+
if not raw:
|
|
31
|
+
return 0
|
|
32
|
+
match = _DOCKER_SIZE_RE.match(raw.strip())
|
|
33
|
+
if not match:
|
|
34
|
+
return 0
|
|
35
|
+
value = float(match.group(1))
|
|
36
|
+
unit = match.group(2).lower()
|
|
37
|
+
multiplier = _SIZE_MULTIPLIERS.get(unit, 1)
|
|
38
|
+
return round(value * multiplier)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def is_docker_installed() -> bool:
|
|
42
|
+
"""Return True if the Docker CLI binary is present on PATH."""
|
|
43
|
+
return shutil.which("docker") is not None
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _run_docker(
|
|
47
|
+
args: Sequence[str],
|
|
48
|
+
timeout: int = 15,
|
|
49
|
+
) -> subprocess.CompletedProcess[str]:
|
|
50
|
+
"""Run a Docker CLI subcommand safely without invoking a shell."""
|
|
51
|
+
return subprocess.run(
|
|
52
|
+
["docker", *args],
|
|
53
|
+
capture_output=True,
|
|
54
|
+
text=True,
|
|
55
|
+
check=False,
|
|
56
|
+
timeout=timeout,
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def check_docker_available(timeout: int = 5) -> tuple[bool, str | None]:
|
|
61
|
+
"""Check whether Docker CLI is installed and the Docker daemon responds."""
|
|
62
|
+
if not is_docker_installed():
|
|
63
|
+
return False, "Docker CLI is not installed or not available in PATH."
|
|
64
|
+
|
|
65
|
+
try:
|
|
66
|
+
completed = _run_docker(["info", "--format", "{{.ServerVersion}}"], timeout=timeout)
|
|
67
|
+
except subprocess.TimeoutExpired:
|
|
68
|
+
return False, "Timed out while contacting the Docker daemon."
|
|
69
|
+
except OSError as exc:
|
|
70
|
+
return False, f"Unable to execute Docker CLI: {exc}"
|
|
71
|
+
|
|
72
|
+
if completed.returncode != 0:
|
|
73
|
+
detail = (completed.stderr or completed.stdout).strip()
|
|
74
|
+
if detail:
|
|
75
|
+
return False, f"Docker daemon is not running or unreachable: {detail}"
|
|
76
|
+
return False, "Docker daemon is not running or unreachable."
|
|
77
|
+
|
|
78
|
+
return True, None
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _parse_json_lines(stdout: str) -> list[dict[str, object]]:
|
|
82
|
+
"""Parse newline-delimited JSON objects emitted by Docker `--format {{json .}}`."""
|
|
83
|
+
parsed: list[dict[str, object]] = []
|
|
84
|
+
for line in stdout.splitlines():
|
|
85
|
+
stripped = line.strip()
|
|
86
|
+
if not stripped:
|
|
87
|
+
continue
|
|
88
|
+
try:
|
|
89
|
+
obj = json.loads(stripped)
|
|
90
|
+
except json.JSONDecodeError:
|
|
91
|
+
continue
|
|
92
|
+
if isinstance(obj, dict):
|
|
93
|
+
parsed.append(obj)
|
|
94
|
+
return parsed
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _get_volume_sizes() -> dict[str, int]:
|
|
98
|
+
"""Fetch per-volume byte sizes from `docker system df -v` when supported."""
|
|
99
|
+
try:
|
|
100
|
+
completed = _run_docker(["system", "df", "-v", "--format", "{{json .}}"])
|
|
101
|
+
except (subprocess.TimeoutExpired, OSError):
|
|
102
|
+
return {}
|
|
103
|
+
if completed.returncode != 0:
|
|
104
|
+
return {}
|
|
105
|
+
|
|
106
|
+
sizes: dict[str, int] = {}
|
|
107
|
+
for entry in _parse_json_lines(completed.stdout):
|
|
108
|
+
volumes = entry.get("Volumes")
|
|
109
|
+
if isinstance(volumes, list):
|
|
110
|
+
for vol in volumes:
|
|
111
|
+
if isinstance(vol, dict):
|
|
112
|
+
name = str(vol.get("Name", "")).strip()
|
|
113
|
+
size_str = str(vol.get("Size", ""))
|
|
114
|
+
if name:
|
|
115
|
+
sizes[name] = parse_docker_size(size_str)
|
|
116
|
+
return sizes
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def list_dangling_images() -> list[DockerResource]:
|
|
120
|
+
"""Return unused dangling Docker images (`dangling=true`)."""
|
|
121
|
+
completed = _run_docker(
|
|
122
|
+
["images", "-f", "dangling=true", "--no-trunc", "--format", "{{json .}}"]
|
|
123
|
+
)
|
|
124
|
+
if completed.returncode != 0:
|
|
125
|
+
return []
|
|
126
|
+
|
|
127
|
+
resources: list[DockerResource] = []
|
|
128
|
+
for item in _parse_json_lines(completed.stdout):
|
|
129
|
+
image_id = str(item.get("ID", "")).strip()
|
|
130
|
+
if not image_id:
|
|
131
|
+
continue
|
|
132
|
+
short_id = image_id.replace("sha256:", "")[:12]
|
|
133
|
+
repo = str(item.get("Repository", "<none>"))
|
|
134
|
+
tag = str(item.get("Tag", "<none>"))
|
|
135
|
+
created = str(item.get("CreatedSince", "dangling"))
|
|
136
|
+
resources.append(
|
|
137
|
+
DockerResource(
|
|
138
|
+
resource_id=image_id,
|
|
139
|
+
name=f"{repo}:{tag} ({short_id})",
|
|
140
|
+
resource_type=DockerResourceType.IMAGE,
|
|
141
|
+
size_bytes=parse_docker_size(str(item.get("Size", "0B"))),
|
|
142
|
+
status=created,
|
|
143
|
+
)
|
|
144
|
+
)
|
|
145
|
+
return resources
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def list_stopped_containers() -> list[DockerResource]:
|
|
149
|
+
"""Return stopped Docker containers (exited or created, never running)."""
|
|
150
|
+
completed = _run_docker(
|
|
151
|
+
[
|
|
152
|
+
"ps",
|
|
153
|
+
"-a",
|
|
154
|
+
"--size",
|
|
155
|
+
"--no-trunc",
|
|
156
|
+
"-f",
|
|
157
|
+
"status=exited",
|
|
158
|
+
"-f",
|
|
159
|
+
"status=created",
|
|
160
|
+
"--format",
|
|
161
|
+
"{{json .}}",
|
|
162
|
+
]
|
|
163
|
+
)
|
|
164
|
+
if completed.returncode != 0:
|
|
165
|
+
return []
|
|
166
|
+
|
|
167
|
+
resources: list[DockerResource] = []
|
|
168
|
+
for item in _parse_json_lines(completed.stdout):
|
|
169
|
+
container_id = str(item.get("ID", "")).strip()
|
|
170
|
+
if not container_id:
|
|
171
|
+
continue
|
|
172
|
+
name = str(item.get("Names", "")).strip() or container_id[:12]
|
|
173
|
+
status = str(item.get("Status", "stopped")).strip()
|
|
174
|
+
resources.append(
|
|
175
|
+
DockerResource(
|
|
176
|
+
resource_id=container_id,
|
|
177
|
+
name=name,
|
|
178
|
+
resource_type=DockerResourceType.CONTAINER,
|
|
179
|
+
size_bytes=parse_docker_size(str(item.get("Size", "0B"))),
|
|
180
|
+
status=status,
|
|
181
|
+
)
|
|
182
|
+
)
|
|
183
|
+
return resources
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def list_unused_volumes() -> list[DockerResource]:
|
|
187
|
+
"""Return unused dangling Docker volumes (`dangling=true`)."""
|
|
188
|
+
completed = _run_docker(
|
|
189
|
+
["volume", "ls", "-f", "dangling=true", "--format", "{{json .}}"]
|
|
190
|
+
)
|
|
191
|
+
if completed.returncode != 0:
|
|
192
|
+
return []
|
|
193
|
+
|
|
194
|
+
volume_sizes = _get_volume_sizes()
|
|
195
|
+
resources: list[DockerResource] = []
|
|
196
|
+
for item in _parse_json_lines(completed.stdout):
|
|
197
|
+
vol_name = str(item.get("Name", "")).strip()
|
|
198
|
+
if not vol_name:
|
|
199
|
+
continue
|
|
200
|
+
driver = str(item.get("Driver", "local")).strip()
|
|
201
|
+
resources.append(
|
|
202
|
+
DockerResource(
|
|
203
|
+
resource_id=vol_name,
|
|
204
|
+
name=vol_name,
|
|
205
|
+
resource_type=DockerResourceType.VOLUME,
|
|
206
|
+
size_bytes=volume_sizes.get(vol_name, 0),
|
|
207
|
+
status=f"driver: {driver}",
|
|
208
|
+
)
|
|
209
|
+
)
|
|
210
|
+
return resources
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def list_build_cache() -> list[DockerResource]:
|
|
214
|
+
"""Return reclaimable Docker build cache summary from `docker system df`."""
|
|
215
|
+
completed = _run_docker(["system", "df", "--format", "{{json .}}"])
|
|
216
|
+
if completed.returncode != 0:
|
|
217
|
+
return []
|
|
218
|
+
|
|
219
|
+
resources: list[DockerResource] = []
|
|
220
|
+
for item in _parse_json_lines(completed.stdout):
|
|
221
|
+
if str(item.get("Type", "")).strip().lower() != "build cache":
|
|
222
|
+
continue
|
|
223
|
+
reclaimable_raw = str(item.get("Reclaimable", "0B")).strip()
|
|
224
|
+
reclaimable_bytes = parse_docker_size(reclaimable_raw)
|
|
225
|
+
if reclaimable_bytes <= 0:
|
|
226
|
+
continue
|
|
227
|
+
total_count = str(item.get("TotalCount", "?"))
|
|
228
|
+
resources.append(
|
|
229
|
+
DockerResource(
|
|
230
|
+
resource_id="build-cache",
|
|
231
|
+
name=f"Docker Build Cache ({total_count} entries)",
|
|
232
|
+
resource_type=DockerResourceType.BUILD_CACHE,
|
|
233
|
+
size_bytes=reclaimable_bytes,
|
|
234
|
+
status=f"reclaimable: {reclaimable_raw}",
|
|
235
|
+
)
|
|
236
|
+
)
|
|
237
|
+
return resources
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def scan_docker_resources() -> list[DockerResource]:
|
|
241
|
+
"""Scan all cleanable unused Docker resources safely."""
|
|
242
|
+
resources: list[DockerResource] = []
|
|
243
|
+
resources.extend(list_stopped_containers())
|
|
244
|
+
resources.extend(list_dangling_images())
|
|
245
|
+
resources.extend(list_unused_volumes())
|
|
246
|
+
resources.extend(list_build_cache())
|
|
247
|
+
resources.sort(key=lambda item: (-item.size_bytes, item.resource_type.value, item.name))
|
|
248
|
+
return resources
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _clean_command_for_resource(resource: DockerResource) -> list[str]:
|
|
252
|
+
"""Build a safe Docker removal command that never force-removes in-use images/containers."""
|
|
253
|
+
if resource.resource_type == DockerResourceType.CONTAINER:
|
|
254
|
+
return ["rm", resource.resource_id]
|
|
255
|
+
if resource.resource_type == DockerResourceType.IMAGE:
|
|
256
|
+
# Never pass `-f`: Docker refuses removal if any container still references this image.
|
|
257
|
+
return ["image", "rm", resource.resource_id]
|
|
258
|
+
if resource.resource_type == DockerResourceType.VOLUME:
|
|
259
|
+
return ["volume", "rm", resource.resource_id]
|
|
260
|
+
if resource.resource_type == DockerResourceType.BUILD_CACHE:
|
|
261
|
+
return ["builder", "prune", "-f"]
|
|
262
|
+
raise ValueError(f"Unsupported Docker resource type: {resource.resource_type}")
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
_CLEAN_PRIORITY: dict[DockerResourceType, int] = {
|
|
266
|
+
DockerResourceType.CONTAINER: 0,
|
|
267
|
+
DockerResourceType.IMAGE: 1,
|
|
268
|
+
DockerResourceType.VOLUME: 2,
|
|
269
|
+
DockerResourceType.BUILD_CACHE: 3,
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def clean_docker_resources(
|
|
274
|
+
resources: Sequence[DockerResource],
|
|
275
|
+
dry_run: bool = False,
|
|
276
|
+
on_progress: Callable[[DockerResource, int, int], None] | None = None,
|
|
277
|
+
) -> DockerCleanResult:
|
|
278
|
+
"""Safely remove selected unused Docker resources without touching active containers/images."""
|
|
279
|
+
result = DockerCleanResult()
|
|
280
|
+
# Remove stopped containers before images/volumes so released dependencies clean cleanly.
|
|
281
|
+
ordered = sorted(resources, key=lambda item: _CLEAN_PRIORITY.get(item.resource_type, 99))
|
|
282
|
+
total = len(ordered)
|
|
283
|
+
|
|
284
|
+
for index, resource in enumerate(ordered, start=1):
|
|
285
|
+
if on_progress is not None:
|
|
286
|
+
on_progress(resource, index, total)
|
|
287
|
+
|
|
288
|
+
if dry_run:
|
|
289
|
+
result.skipped.append((resource.name, "Dry run - no Docker resources removed"))
|
|
290
|
+
continue
|
|
291
|
+
|
|
292
|
+
cmd = _clean_command_for_resource(resource)
|
|
293
|
+
try:
|
|
294
|
+
completed = _run_docker(cmd, timeout=60)
|
|
295
|
+
except (subprocess.TimeoutExpired, OSError) as exc:
|
|
296
|
+
result.failed.append((resource.name, str(exc)))
|
|
297
|
+
continue
|
|
298
|
+
|
|
299
|
+
if completed.returncode != 0:
|
|
300
|
+
err_msg = (completed.stderr or completed.stdout).strip() or "Docker command failed"
|
|
301
|
+
result.failed.append((resource.name, err_msg))
|
|
302
|
+
continue
|
|
303
|
+
|
|
304
|
+
result.cleaned.append(resource)
|
|
305
|
+
result.reclaimed_bytes += resource.size_bytes
|
|
306
|
+
|
|
307
|
+
return result
|
devsweep/ignore.py
ADDED
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
"""Gitignore-compatible ignore file loader and 3-tier precedence matcher."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import re
|
|
5
|
+
from collections.abc import Iterable, Sequence
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
DEFAULT_IGNORE_FILENAME = ".devsweepignore"
|
|
10
|
+
|
|
11
|
+
DEFAULT_IGNORE_PATTERNS: tuple[str, ...] = (
|
|
12
|
+
".git",
|
|
13
|
+
".idea",
|
|
14
|
+
".vscode",
|
|
15
|
+
".hg",
|
|
16
|
+
".svn",
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True, slots=True)
|
|
21
|
+
class IgnoreRule:
|
|
22
|
+
"""Single compiled gitignore-style pattern rule."""
|
|
23
|
+
|
|
24
|
+
raw: str
|
|
25
|
+
negated: bool
|
|
26
|
+
dir_only: bool
|
|
27
|
+
anchored: bool
|
|
28
|
+
regex: re.Pattern[str]
|
|
29
|
+
|
|
30
|
+
def matches(self, rel_posix: str, is_dir: bool = True) -> bool:
|
|
31
|
+
"""Return True if this rule matches the given POSIX-style relative path."""
|
|
32
|
+
if self.dir_only and not is_dir:
|
|
33
|
+
return False
|
|
34
|
+
return self.regex.match(rel_posix) is not None
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _glob_to_regex(pattern: str) -> str:
|
|
38
|
+
"""Translate a gitignore glob expression into a regular expression fragment."""
|
|
39
|
+
out: list[str] = []
|
|
40
|
+
i = 0
|
|
41
|
+
length = len(pattern)
|
|
42
|
+
|
|
43
|
+
while i < length:
|
|
44
|
+
if pattern.startswith("**/", i):
|
|
45
|
+
out.append("(?:.*/)?")
|
|
46
|
+
i += 3
|
|
47
|
+
continue
|
|
48
|
+
if pattern.startswith("/**", i):
|
|
49
|
+
out.append("(?:/.*)?")
|
|
50
|
+
i += 3
|
|
51
|
+
continue
|
|
52
|
+
if pattern.startswith("**", i):
|
|
53
|
+
out.append(".*")
|
|
54
|
+
i += 2
|
|
55
|
+
continue
|
|
56
|
+
|
|
57
|
+
ch = pattern[i]
|
|
58
|
+
if ch == "*":
|
|
59
|
+
out.append("[^/]*")
|
|
60
|
+
elif ch == "?":
|
|
61
|
+
out.append("[^/]")
|
|
62
|
+
elif ch == "[":
|
|
63
|
+
end = pattern.find("]", i + 1)
|
|
64
|
+
if end == -1:
|
|
65
|
+
out.append(r"\[")
|
|
66
|
+
else:
|
|
67
|
+
content = pattern[i + 1 : end]
|
|
68
|
+
if content.startswith("!"):
|
|
69
|
+
content = "^" + content[1:]
|
|
70
|
+
elif content.startswith("^"):
|
|
71
|
+
content = "\\" + content
|
|
72
|
+
out.append(f"[{content}]")
|
|
73
|
+
i = end
|
|
74
|
+
else:
|
|
75
|
+
out.append(re.escape(ch))
|
|
76
|
+
i += 1
|
|
77
|
+
|
|
78
|
+
return "".join(out)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def compile_ignore_rule(raw_line: str, *, allow_negation: bool = True) -> IgnoreRule | None:
|
|
82
|
+
"""Parse one gitignore-style line into a compiled IgnoreRule, or None if comment/blank."""
|
|
83
|
+
line = raw_line.rstrip("\r\n").strip()
|
|
84
|
+
if not line:
|
|
85
|
+
return None
|
|
86
|
+
|
|
87
|
+
# Handle escaped leading `#` or `!`, otherwise skip `#` comments.
|
|
88
|
+
negated = False
|
|
89
|
+
if line.startswith("#"):
|
|
90
|
+
return None
|
|
91
|
+
if line.startswith((r"\#", r"\!")):
|
|
92
|
+
line = line[1:]
|
|
93
|
+
elif allow_negation and line.startswith("!"):
|
|
94
|
+
negated = True
|
|
95
|
+
line = line[1:].strip()
|
|
96
|
+
if not line:
|
|
97
|
+
return None
|
|
98
|
+
|
|
99
|
+
normalized = line.replace("\\", "/")
|
|
100
|
+
dir_only = normalized.endswith("/")
|
|
101
|
+
if dir_only:
|
|
102
|
+
normalized = normalized.rstrip("/")
|
|
103
|
+
if not normalized:
|
|
104
|
+
return None
|
|
105
|
+
|
|
106
|
+
anchored = normalized.startswith("/") or ("/" in normalized)
|
|
107
|
+
if normalized.startswith("/"):
|
|
108
|
+
normalized = normalized.lstrip("/")
|
|
109
|
+
if not normalized:
|
|
110
|
+
return None
|
|
111
|
+
|
|
112
|
+
body = _glob_to_regex(normalized)
|
|
113
|
+
if anchored:
|
|
114
|
+
expr = rf"^{body}(?:/.*)?$"
|
|
115
|
+
else:
|
|
116
|
+
expr = rf"^(?:.*/)?{body}(?:/.*)?$"
|
|
117
|
+
|
|
118
|
+
flags = re.IGNORECASE if os.name == "nt" else 0
|
|
119
|
+
return IgnoreRule(
|
|
120
|
+
raw=raw_line.strip(),
|
|
121
|
+
negated=negated,
|
|
122
|
+
dir_only=dir_only,
|
|
123
|
+
anchored=anchored,
|
|
124
|
+
regex=re.compile(expr, flags),
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def parse_ignore_lines(
|
|
129
|
+
lines: Iterable[str],
|
|
130
|
+
*,
|
|
131
|
+
allow_negation: bool = True,
|
|
132
|
+
) -> list[IgnoreRule]:
|
|
133
|
+
"""Compile an iterable of gitignore-style lines into IgnoreRule objects."""
|
|
134
|
+
rules: list[IgnoreRule] = []
|
|
135
|
+
for line in lines:
|
|
136
|
+
rule = compile_ignore_rule(line, allow_negation=allow_negation)
|
|
137
|
+
if rule is not None:
|
|
138
|
+
rules.append(rule)
|
|
139
|
+
return rules
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def load_ignore_file(path: Path) -> list[IgnoreRule]:
|
|
143
|
+
"""Read and parse rules from a `.devsweepignore` or custom ignore file."""
|
|
144
|
+
target = path.expanduser()
|
|
145
|
+
if not target.exists():
|
|
146
|
+
raise FileNotFoundError(f"Ignore file does not exist: {path}")
|
|
147
|
+
if target.is_dir():
|
|
148
|
+
raise IsADirectoryError(f"Ignore file path is a directory: {path}")
|
|
149
|
+
|
|
150
|
+
text = target.read_text(encoding="utf-8")
|
|
151
|
+
return parse_ignore_lines(text.splitlines(), allow_negation=True)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def discover_ignore_files(
|
|
155
|
+
scan_root: Path,
|
|
156
|
+
*,
|
|
157
|
+
explicit_ignore_file: Path | None = None,
|
|
158
|
+
cwd: Path | None = None,
|
|
159
|
+
) -> list[Path]:
|
|
160
|
+
"""Resolve ignore files to apply for scan_root (explicit file overrides auto-discovery)."""
|
|
161
|
+
if explicit_ignore_file is not None:
|
|
162
|
+
resolved = explicit_ignore_file.expanduser().resolve()
|
|
163
|
+
if not resolved.exists():
|
|
164
|
+
raise FileNotFoundError(f"Ignore file does not exist: {explicit_ignore_file}")
|
|
165
|
+
if resolved.is_dir():
|
|
166
|
+
raise IsADirectoryError(
|
|
167
|
+
f"Ignore file path is a directory: {explicit_ignore_file}"
|
|
168
|
+
)
|
|
169
|
+
return [resolved]
|
|
170
|
+
|
|
171
|
+
resolved_root = scan_root.expanduser().resolve()
|
|
172
|
+
resolved_cwd = (cwd or Path.cwd()).expanduser().resolve()
|
|
173
|
+
candidates: list[Path] = []
|
|
174
|
+
|
|
175
|
+
# Include CWD `.devsweepignore` when scanning a subdirectory of CWD.
|
|
176
|
+
try:
|
|
177
|
+
if resolved_root != resolved_cwd and resolved_root.is_relative_to(resolved_cwd):
|
|
178
|
+
cwd_ignore = resolved_cwd / DEFAULT_IGNORE_FILENAME
|
|
179
|
+
if cwd_ignore.is_file():
|
|
180
|
+
candidates.append(cwd_ignore)
|
|
181
|
+
except ValueError:
|
|
182
|
+
pass
|
|
183
|
+
|
|
184
|
+
root_ignore = resolved_root / DEFAULT_IGNORE_FILENAME
|
|
185
|
+
if root_ignore.is_file():
|
|
186
|
+
candidates.append(root_ignore)
|
|
187
|
+
|
|
188
|
+
deduped: list[Path] = []
|
|
189
|
+
seen: set[str] = set()
|
|
190
|
+
for candidate in candidates:
|
|
191
|
+
key = os.path.normcase(str(candidate.resolve()))
|
|
192
|
+
if key not in seen:
|
|
193
|
+
seen.add(key)
|
|
194
|
+
deduped.append(candidate)
|
|
195
|
+
return deduped
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
class IgnoreMatcher:
|
|
199
|
+
"""Evaluate ignore precedence: CLI exclude > .devsweepignore > default ignore."""
|
|
200
|
+
|
|
201
|
+
def __init__(
|
|
202
|
+
self,
|
|
203
|
+
*,
|
|
204
|
+
cli_excludes: Sequence[str] = (),
|
|
205
|
+
file_rules: Sequence[IgnoreRule] = (),
|
|
206
|
+
default_patterns: Sequence[str] = DEFAULT_IGNORE_PATTERNS,
|
|
207
|
+
use_defaults: bool = True,
|
|
208
|
+
) -> None:
|
|
209
|
+
self.default_rules: tuple[IgnoreRule, ...] = (
|
|
210
|
+
tuple(parse_ignore_lines(default_patterns, allow_negation=False))
|
|
211
|
+
if use_defaults
|
|
212
|
+
else ()
|
|
213
|
+
)
|
|
214
|
+
self.file_rules: tuple[IgnoreRule, ...] = tuple(file_rules)
|
|
215
|
+
self.cli_rules: tuple[IgnoreRule, ...] = tuple(
|
|
216
|
+
parse_ignore_lines(cli_excludes, allow_negation=False)
|
|
217
|
+
)
|
|
218
|
+
|
|
219
|
+
def is_ignored(self, rel_posix: str, *, is_dir: bool = True) -> bool:
|
|
220
|
+
"""Return True if rel_posix is ignored under 3-tier precedence rules."""
|
|
221
|
+
cleaned = rel_posix.replace("\\", "/").strip("/")
|
|
222
|
+
if not cleaned:
|
|
223
|
+
return False
|
|
224
|
+
|
|
225
|
+
ignored = False
|
|
226
|
+
|
|
227
|
+
# Tier 3 (lowest): default ignore patterns (.git, .idea, .vscode, ...)
|
|
228
|
+
for rule in self.default_rules:
|
|
229
|
+
if rule.matches(cleaned, is_dir=is_dir):
|
|
230
|
+
ignored = True
|
|
231
|
+
|
|
232
|
+
# Tier 2 (middle): .devsweepignore or --ignore-file (supports `!` negation)
|
|
233
|
+
for rule in self.file_rules:
|
|
234
|
+
if rule.matches(cleaned, is_dir=is_dir):
|
|
235
|
+
ignored = not rule.negated
|
|
236
|
+
|
|
237
|
+
# Tier 1 (highest): CLI --exclude flags always win
|
|
238
|
+
for rule in self.cli_rules:
|
|
239
|
+
if rule.matches(cleaned, is_dir=is_dir):
|
|
240
|
+
return True
|
|
241
|
+
|
|
242
|
+
return ignored
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def build_ignore_matcher(
|
|
246
|
+
scan_root: Path,
|
|
247
|
+
*,
|
|
248
|
+
cli_excludes: Sequence[str] = (),
|
|
249
|
+
ignore_file: Path | None = None,
|
|
250
|
+
use_default_ignores: bool = True,
|
|
251
|
+
extra_default_patterns: Sequence[str] = (),
|
|
252
|
+
cwd: Path | None = None,
|
|
253
|
+
) -> IgnoreMatcher:
|
|
254
|
+
"""Build a configured IgnoreMatcher for scan_root."""
|
|
255
|
+
ignore_files = discover_ignore_files(
|
|
256
|
+
scan_root,
|
|
257
|
+
explicit_ignore_file=ignore_file,
|
|
258
|
+
cwd=cwd,
|
|
259
|
+
)
|
|
260
|
+
file_rules: list[IgnoreRule] = []
|
|
261
|
+
for path in ignore_files:
|
|
262
|
+
file_rules.extend(load_ignore_file(path))
|
|
263
|
+
|
|
264
|
+
defaults: list[str] = list(DEFAULT_IGNORE_PATTERNS) if use_default_ignores else []
|
|
265
|
+
defaults.extend(extra_default_patterns)
|
|
266
|
+
|
|
267
|
+
return IgnoreMatcher(
|
|
268
|
+
cli_excludes=cli_excludes,
|
|
269
|
+
file_rules=file_rules,
|
|
270
|
+
default_patterns=defaults,
|
|
271
|
+
use_defaults=bool(defaults),
|
|
272
|
+
)
|
devsweep/models.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""Data models for scan results, deletion summaries, and resource metadata."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from datetime import datetime
|
|
5
|
+
from enum import Enum
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class FolderType(str, Enum):
|
|
10
|
+
"""Classification of discovered directories."""
|
|
11
|
+
|
|
12
|
+
DIRECTORY = "directory"
|
|
13
|
+
NODE_MODULES = "node_modules"
|
|
14
|
+
VENV = "venv"
|
|
15
|
+
RUST_TARGET = "target"
|
|
16
|
+
BUILD = "build"
|
|
17
|
+
DIST = "dist"
|
|
18
|
+
PYCACHE = "__pycache__"
|
|
19
|
+
NEXT = ".next"
|
|
20
|
+
NUXT = ".nuxt"
|
|
21
|
+
COVERAGE = "coverage"
|
|
22
|
+
PYTEST_CACHE = ".pytest_cache"
|
|
23
|
+
GRADLE = ".gradle"
|
|
24
|
+
TURBO = ".turbo"
|
|
25
|
+
PARCEL_CACHE = ".parcel-cache"
|
|
26
|
+
MYPY_CACHE = ".mypy_cache"
|
|
27
|
+
RUFF_CACHE = ".ruff_cache"
|
|
28
|
+
OTHER = "other"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(slots=True)
|
|
32
|
+
class ScanResult:
|
|
33
|
+
"""Represents a scanned directory entry and its computed metadata."""
|
|
34
|
+
|
|
35
|
+
path: Path
|
|
36
|
+
size_bytes: int
|
|
37
|
+
folder_type: FolderType | str
|
|
38
|
+
modified_time: datetime
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass(slots=True)
|
|
42
|
+
class ScanSummary:
|
|
43
|
+
"""Aggregated summary of a directory scan."""
|
|
44
|
+
|
|
45
|
+
total_size: int
|
|
46
|
+
items: list[ScanResult] = field(default_factory=list)
|
|
47
|
+
skipped_errors: list[tuple[Path, str]] = field(default_factory=list)
|
|
48
|
+
|
|
49
|
+
@property
|
|
50
|
+
def count(self) -> int:
|
|
51
|
+
"""Return the number of discovered items."""
|
|
52
|
+
return len(self.items)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass(slots=True)
|
|
56
|
+
class DeleteResult:
|
|
57
|
+
"""Aggregated outcome of a folder cleanup operation."""
|
|
58
|
+
|
|
59
|
+
deleted: list[Path] = field(default_factory=list)
|
|
60
|
+
failed: list[tuple[Path, str]] = field(default_factory=list)
|
|
61
|
+
skipped: list[tuple[Path, str]] = field(default_factory=list)
|
|
62
|
+
freed_bytes: int = 0
|
|
63
|
+
|
|
64
|
+
@property
|
|
65
|
+
def deleted_count(self) -> int:
|
|
66
|
+
"""Return the number of successfully deleted folders."""
|
|
67
|
+
return len(self.deleted)
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def failed_count(self) -> int:
|
|
71
|
+
"""Return the number of folders that failed to delete."""
|
|
72
|
+
return len(self.failed)
|
|
73
|
+
|
|
74
|
+
@property
|
|
75
|
+
def skipped_count(self) -> int:
|
|
76
|
+
"""Return the number of folders skipped due to safety checks."""
|
|
77
|
+
return len(self.skipped)
|
|
78
|
+
|
|
79
|
+
@property
|
|
80
|
+
def has_errors(self) -> bool:
|
|
81
|
+
"""Return True if any deletions failed."""
|
|
82
|
+
return bool(self.failed)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class DockerResourceType(str, Enum):
|
|
86
|
+
"""Classification of cleanable Docker resources."""
|
|
87
|
+
|
|
88
|
+
IMAGE = "image"
|
|
89
|
+
CONTAINER = "container"
|
|
90
|
+
VOLUME = "volume"
|
|
91
|
+
BUILD_CACHE = "build_cache"
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
@dataclass(slots=True)
|
|
95
|
+
class DockerResource:
|
|
96
|
+
"""Represents a single unused or reclaimable Docker resource."""
|
|
97
|
+
|
|
98
|
+
resource_id: str
|
|
99
|
+
name: str
|
|
100
|
+
resource_type: DockerResourceType
|
|
101
|
+
size_bytes: int
|
|
102
|
+
status: str = ""
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
@dataclass(slots=True)
|
|
106
|
+
class DockerCleanResult:
|
|
107
|
+
"""Aggregated outcome of a Docker cleanup operation."""
|
|
108
|
+
|
|
109
|
+
cleaned: list[DockerResource] = field(default_factory=list)
|
|
110
|
+
failed: list[tuple[str, str]] = field(default_factory=list)
|
|
111
|
+
skipped: list[tuple[str, str]] = field(default_factory=list)
|
|
112
|
+
reclaimed_bytes: int = 0
|
|
113
|
+
|
|
114
|
+
@property
|
|
115
|
+
def cleaned_count(self) -> int:
|
|
116
|
+
"""Return the number of successfully cleaned Docker resources."""
|
|
117
|
+
return len(self.cleaned)
|
|
118
|
+
|
|
119
|
+
@property
|
|
120
|
+
def failed_count(self) -> int:
|
|
121
|
+
"""Return the number of Docker resources that failed to clean."""
|
|
122
|
+
return len(self.failed)
|
|
123
|
+
|
|
124
|
+
@property
|
|
125
|
+
def skipped_count(self) -> int:
|
|
126
|
+
"""Return the number of skipped Docker resources."""
|
|
127
|
+
return len(self.skipped)
|
|
128
|
+
|
|
129
|
+
@property
|
|
130
|
+
def has_errors(self) -> bool:
|
|
131
|
+
"""Return True if any Docker cleanup operations failed."""
|
|
132
|
+
return bool(self.failed)
|