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/display.py ADDED
@@ -0,0 +1,909 @@
1
+ """Rich terminal UI formatting, tables, progress indicators, and prompts."""
2
+
3
+ import json
4
+ from collections.abc import Callable, Iterator, Sequence
5
+ from contextlib import contextmanager
6
+ from pathlib import Path
7
+
8
+ from rich import box
9
+ from rich.console import Console
10
+ from rich.markup import escape
11
+ from rich.panel import Panel
12
+ from rich.progress import BarColumn, MofNCompleteColumn, Progress, SpinnerColumn, TextColumn
13
+ from rich.prompt import Confirm, Prompt
14
+ from rich.table import Table
15
+ from rich.text import Text
16
+
17
+ from devsweep.models import (
18
+ DeleteResult,
19
+ DockerCleanResult,
20
+ DockerResource,
21
+ DockerResourceType,
22
+ FolderType,
23
+ ScanResult,
24
+ )
25
+ from devsweep.utils import format_size
26
+
27
+ FOLDER_TYPE_STYLES: dict[FolderType, str] = {
28
+ FolderType.NODE_MODULES: "bold yellow",
29
+ FolderType.VENV: "bold cyan",
30
+ FolderType.RUST_TARGET: "bold red",
31
+ FolderType.DIST: "bold magenta",
32
+ FolderType.BUILD: "bold blue",
33
+ FolderType.PYCACHE: "green",
34
+ FolderType.NEXT: "bright_cyan",
35
+ FolderType.NUXT: "bright_green",
36
+ FolderType.COVERAGE: "bright_magenta",
37
+ FolderType.PYTEST_CACHE: "bright_blue",
38
+ FolderType.GRADLE: "bold green",
39
+ FolderType.TURBO: "bright_red",
40
+ FolderType.PARCEL_CACHE: "bright_yellow",
41
+ FolderType.MYPY_CACHE: "cyan",
42
+ FolderType.RUFF_CACHE: "magenta",
43
+ FolderType.DIRECTORY: "white",
44
+ FolderType.OTHER: "white",
45
+ }
46
+
47
+ DOCKER_TYPE_STYLES: dict[DockerResourceType, str] = {
48
+ DockerResourceType.IMAGE: "bold yellow",
49
+ DockerResourceType.CONTAINER: "bold cyan",
50
+ DockerResourceType.VOLUME: "bold magenta",
51
+ DockerResourceType.BUILD_CACHE: "bold blue",
52
+ }
53
+
54
+ _UTF_ICONS: dict[str, str] = {
55
+ "sweep": "๐Ÿงน",
56
+ "scan": "๐Ÿ”",
57
+ "docker": "๐Ÿณ",
58
+ "ok": "โœ…",
59
+ "warn": "โš ๏ธ",
60
+ "error": "โŒ",
61
+ "dry_run": "๐Ÿงช",
62
+ "sparkle": "โœจ",
63
+ "home": "๐Ÿ ",
64
+ }
65
+
66
+ _ASCII_ICONS: dict[str, str] = {
67
+ "sweep": "*",
68
+ "scan": ">",
69
+ "docker": "[Docker]",
70
+ "ok": "[OK]",
71
+ "warn": "[!]",
72
+ "error": "[ERR]",
73
+ "dry_run": "[DRY RUN]",
74
+ "sparkle": "[OK]",
75
+ "home": "[HOME]",
76
+ }
77
+
78
+
79
+ def get_console(no_color: bool = False) -> Console:
80
+ """Create a configured Rich Console respecting the no_color preference."""
81
+ if no_color:
82
+ return Console(
83
+ no_color=True,
84
+ color_system=None,
85
+ force_terminal=False,
86
+ highlight=False,
87
+ )
88
+ return Console(no_color=False, highlight=False)
89
+
90
+
91
+ def _supports_unicode_icons(console: Console) -> bool:
92
+ encoding = (console.encoding or "").lower()
93
+ return encoding.startswith("utf") and not console.no_color
94
+
95
+
96
+ def get_icon(name: str, console: Console) -> str:
97
+ """Return a consistent Unicode icon when supported, or a clean ASCII fallback."""
98
+ table = _UTF_ICONS if _supports_unicode_icons(console) else _ASCII_ICONS
99
+ return table.get(name, "")
100
+
101
+
102
+ def get_folder_style(folder_type: FolderType | str) -> str:
103
+ """Return the Rich style string associated with a folder type."""
104
+ if isinstance(folder_type, FolderType):
105
+ return FOLDER_TYPE_STYLES.get(folder_type, "white")
106
+ try:
107
+ return FOLDER_TYPE_STYLES.get(FolderType(folder_type), "white")
108
+ except ValueError:
109
+ return "white"
110
+
111
+
112
+ def _format_folder_type(folder_type: FolderType | str) -> str:
113
+ return folder_type.value if isinstance(folder_type, FolderType) else str(folder_type)
114
+
115
+
116
+ def _format_display_path(item_path: Path, base_path: Path | None) -> str:
117
+ if base_path is None:
118
+ return str(item_path)
119
+ try:
120
+ return str(item_path.relative_to(base_path))
121
+ except ValueError:
122
+ return str(item_path)
123
+
124
+
125
+ def sort_scan_results(results: Sequence[ScanResult]) -> list[ScanResult]:
126
+ """Return scan results sorted by descending byte size, then path."""
127
+ return sorted(results, key=lambda item: (-item.size_bytes, str(item.path)))
128
+
129
+
130
+ @contextmanager
131
+ def scanning_spinner(
132
+ console: Console,
133
+ message: str = "Scanning directories...",
134
+ ) -> Iterator[None]:
135
+ """Display a transient Rich spinner while scanning is in progress."""
136
+ spinner_name = "dots" if _supports_unicode_icons(console) else "line"
137
+
138
+ with Progress(
139
+ SpinnerColumn(spinner_name=spinner_name, style="cyan"),
140
+ TextColumn("[bold cyan]{task.description}[/bold cyan]"),
141
+ transient=True,
142
+ console=console,
143
+ ) as progress:
144
+ progress.add_task(description=message, total=None)
145
+ yield
146
+
147
+
148
+ @contextmanager
149
+ def multi_path_scan_progress(
150
+ total_roots: int,
151
+ console: Console,
152
+ ) -> Iterator[Callable[[Path, int, int], None]]:
153
+ """Display an overall Rich progress bar when scanning multiple target roots."""
154
+ spinner_name = "dots" if _supports_unicode_icons(console) else "line"
155
+
156
+ with Progress(
157
+ SpinnerColumn(spinner_name=spinner_name, style="cyan"),
158
+ TextColumn("[bold cyan]{task.description}[/bold cyan]"),
159
+ BarColumn(),
160
+ MofNCompleteColumn(),
161
+ transient=True,
162
+ console=console,
163
+ ) as progress:
164
+ task_id = progress.add_task("Scanning directories...", total=max(total_roots, 1))
165
+
166
+ def _on_root(root: Path, index: int, total: int) -> None:
167
+ safe_label = escape(root.name or str(root))
168
+ progress.update(
169
+ task_id,
170
+ completed=index - 1,
171
+ description=f"Scanning {safe_label} ({index}/{total})...",
172
+ )
173
+
174
+ yield _on_root
175
+ progress.update(task_id, completed=max(total_roots, 1))
176
+
177
+
178
+ def build_scan_table(
179
+ results: Sequence[ScanResult],
180
+ base_path: Path | None = None,
181
+ show_index: bool = False,
182
+ ) -> Table:
183
+ """Build a Rich Table presenting scanned folders sorted largest-first."""
184
+ table = Table(
185
+ title="Cleanable Developer Folders",
186
+ box=box.ROUNDED,
187
+ header_style="bold white",
188
+ border_style="bright_black",
189
+ show_lines=False,
190
+ expand=False,
191
+ )
192
+ if show_index:
193
+ table.add_column("#", justify="right", style="dim", no_wrap=True)
194
+ table.add_column("Path", style="white", overflow="fold")
195
+ table.add_column("Type", no_wrap=True)
196
+ table.add_column("Size", justify="right", style="bold green", no_wrap=True)
197
+
198
+ sorted_items = sort_scan_results(results)
199
+ for idx, item in enumerate(sorted_items, start=1):
200
+ type_label = _format_folder_type(item.folder_type)
201
+ type_style = get_folder_style(item.folder_type)
202
+ display_path = _format_display_path(item.path, base_path)
203
+
204
+ row: list[Text | str] = []
205
+ if show_index:
206
+ row.append(str(idx))
207
+ row.append(Text(display_path))
208
+ row.append(Text(type_label, style=type_style))
209
+ row.append(Text(format_size(item.size_bytes), style="bold green"))
210
+ table.add_row(*row)
211
+
212
+ return table
213
+
214
+
215
+ def _format_targets_summary(
216
+ summary_text: Text,
217
+ base_path: Path | None = None,
218
+ base_paths: Sequence[Path] | None = None,
219
+ ) -> None:
220
+ targets: list[Path] = list(base_paths) if base_paths is not None else (
221
+ [base_path] if base_path is not None else []
222
+ )
223
+ if not targets:
224
+ return
225
+ if len(targets) == 1:
226
+ summary_text.append("Target: ", style="bold")
227
+ summary_text.append(f"{targets[0]}\n", style="dim")
228
+ return
229
+
230
+ preview = ", ".join(str(p) for p in targets[:3])
231
+ if len(targets) > 3:
232
+ preview = f"{preview} (+{len(targets) - 3} more)"
233
+ summary_text.append(f"Targets ({len(targets)}): ", style="bold")
234
+ summary_text.append(f"{preview}\n", style="dim")
235
+
236
+
237
+ def build_summary_panel(
238
+ results: Sequence[ScanResult],
239
+ base_path: Path | None = None,
240
+ title: str = "Scan Summary",
241
+ base_paths: Sequence[Path] | None = None,
242
+ ) -> Panel:
243
+ """Build a summary Rich Panel showing total reclaimable disk space."""
244
+ total_size = sum(item.size_bytes for item in results)
245
+ summary_text = Text()
246
+ _format_targets_summary(summary_text, base_path=base_path, base_paths=base_paths)
247
+
248
+ summary_text.append("Folders found: ", style="bold")
249
+ summary_text.append(f"{len(results)}", style="bold cyan")
250
+ summary_text.append(" | ", style="dim")
251
+ summary_text.append("Total reclaimable: ", style="bold")
252
+ summary_text.append(format_size(total_size), style="bold green")
253
+
254
+ return Panel(
255
+ summary_text,
256
+ title=title,
257
+ border_style="cyan",
258
+ box=box.ROUNDED,
259
+ expand=False,
260
+ )
261
+
262
+
263
+ def show_dry_run_banner(console: Console | None = None) -> None:
264
+ """Display a prominent warning banner for dry-run mode."""
265
+ active_console = console or get_console()
266
+ prefix = get_icon("dry_run", active_console)
267
+ base_label = "DRY RUN - No files will be deleted"
268
+ label = f"{prefix} {base_label}" if _supports_unicode_icons(active_console) else base_label
269
+ banner_text = Text(label, style="bold yellow")
270
+ active_console.print(
271
+ Panel(
272
+ banner_text,
273
+ border_style="yellow",
274
+ box=box.ROUNDED,
275
+ expand=False,
276
+ )
277
+ )
278
+
279
+
280
+ def show_smart_home_notice(
281
+ roots: Sequence[Path],
282
+ used_common_dirs: bool,
283
+ console: Console | None = None,
284
+ ) -> None:
285
+ """Inform the user which project folders are scanned during `devsweep scan ~`."""
286
+ active_console = console or get_console()
287
+ prefix = get_icon("home", active_console)
288
+ if used_common_dirs:
289
+ names = ", ".join(p.name for p in roots)
290
+ notice = Text.assemble(
291
+ (f"{prefix} Smart home scan: ", "bold cyan"),
292
+ (f"scanning {len(roots)} project folder(s) ({names})", "dim"),
293
+ )
294
+ else:
295
+ notice = Text.assemble(
296
+ (f"{prefix} Smart home scan: ", "bold cyan"),
297
+ ("scanning home directory (skipping heavy OS folders)", "dim"),
298
+ )
299
+ active_console.print(notice)
300
+
301
+
302
+ def show_scan_results(
303
+ results: list[ScanResult],
304
+ console: Console | None = None,
305
+ base_path: Path | None = None,
306
+ show_index: bool = False,
307
+ base_paths: Sequence[Path] | None = None,
308
+ ) -> None:
309
+ """Render scan results as a styled Rich table and summary panel."""
310
+ active_console = console or get_console()
311
+ effective_base = (
312
+ base_path
313
+ if base_path is not None
314
+ else (base_paths[0] if base_paths is not None and len(base_paths) == 1 else None)
315
+ )
316
+
317
+ if not results:
318
+ sparkle = get_icon("sparkle", active_console)
319
+ empty_text = Text()
320
+ _format_targets_summary(empty_text, base_path=base_path, base_paths=base_paths)
321
+ empty_text.append(
322
+ f"{sparkle} Workspace is clean! "
323
+ "No cleanable folders found (0 folders, 0 B reclaimable).",
324
+ style="green",
325
+ )
326
+ active_console.print(
327
+ Panel(
328
+ empty_text,
329
+ title="Scan Summary",
330
+ border_style="green",
331
+ box=box.ROUNDED,
332
+ expand=False,
333
+ )
334
+ )
335
+ return
336
+
337
+ table = build_scan_table(results, base_path=effective_base, show_index=show_index)
338
+ panel = build_summary_panel(results, base_path=effective_base, base_paths=base_paths)
339
+ active_console.print(table)
340
+ active_console.print(panel)
341
+
342
+
343
+ def build_selection_table(
344
+ items: Sequence[ScanResult],
345
+ selected_indices: set[int],
346
+ base_path: Path | None = None,
347
+ ) -> Table:
348
+ """Build an interactive checkbox table using 1-based item indices."""
349
+ table = Table(
350
+ title="Select Folders to Clean",
351
+ box=box.ROUNDED,
352
+ header_style="bold white",
353
+ border_style="bright_black",
354
+ expand=False,
355
+ )
356
+ table.add_column("#", justify="right", style="dim", no_wrap=True)
357
+ table.add_column("Selected", justify="center", no_wrap=True)
358
+ table.add_column("Path", style="white", overflow="fold")
359
+ table.add_column("Type", no_wrap=True)
360
+ table.add_column("Size", justify="right", style="bold green", no_wrap=True)
361
+
362
+ for idx, item in enumerate(items, start=1):
363
+ is_selected = idx in selected_indices
364
+ marker = Text("[x]", style="bold green") if is_selected else Text("[ ]", style="dim")
365
+ type_label = _format_folder_type(item.folder_type)
366
+ type_style = get_folder_style(item.folder_type)
367
+ display_path = _format_display_path(item.path, base_path)
368
+
369
+ table.add_row(
370
+ str(idx),
371
+ marker,
372
+ Text(display_path),
373
+ Text(type_label, style=type_style),
374
+ Text(format_size(item.size_bytes), style="bold green"),
375
+ )
376
+
377
+ return table
378
+
379
+
380
+ def parse_index_tokens(raw_input: str, total_items: int) -> set[int]:
381
+ """Parse 1-based numbers and ranges (e.g. '1, 3-5') into a set of indices."""
382
+ if total_items < 1:
383
+ raise ValueError("No items available to select.")
384
+
385
+ tokens = [tok for tok in raw_input.replace(",", " ").split() if tok]
386
+ if not tokens:
387
+ return set()
388
+
389
+ indices: set[int] = set()
390
+ for token in tokens:
391
+ if "-" in token:
392
+ parts = token.split("-", maxsplit=1)
393
+ if len(parts) != 2 or not parts[0].isdigit() or not parts[1].isdigit():
394
+ raise ValueError(f"Invalid range '{token}'.")
395
+ start, end = int(parts[0]), int(parts[1])
396
+ if start < 1 or end > total_items or start > end:
397
+ raise ValueError(f"Range '{token}' is out of bounds (1-{total_items}).")
398
+ indices.update(range(start, end + 1))
399
+ elif token.isdigit():
400
+ idx = int(token)
401
+ if idx < 1 or idx > total_items:
402
+ raise ValueError(f"Index '{idx}' is out of bounds (1-{total_items}).")
403
+ indices.add(idx)
404
+ else:
405
+ raise ValueError(f"Unknown selection '{token}'.")
406
+ return indices
407
+
408
+
409
+ def select_folders_interactive(
410
+ results: Sequence[ScanResult],
411
+ console: Console | None = None,
412
+ base_path: Path | None = None,
413
+ ) -> list[ScanResult]:
414
+ """Prompt the user to interactively select folders with Select All / Select None."""
415
+ active_console = console or get_console()
416
+ ordered_items = sort_scan_results(results)
417
+ if not ordered_items:
418
+ return []
419
+
420
+ total = len(ordered_items)
421
+ selected_indices: set[int] = set()
422
+
423
+ while True:
424
+ active_console.print(
425
+ build_selection_table(ordered_items, selected_indices, base_path=base_path)
426
+ )
427
+ selected_bytes = sum(ordered_items[idx - 1].size_bytes for idx in selected_indices)
428
+ active_console.print(
429
+ Text.assemble(
430
+ ("Selected: ", "bold"),
431
+ (f"{len(selected_indices)}/{total}", "bold cyan"),
432
+ (" | ", "dim"),
433
+ ("Size: ", "bold"),
434
+ (format_size(selected_bytes), "bold green"),
435
+ )
436
+ )
437
+ active_console.print(
438
+ Text(
439
+ "Commands: numbers/ranges (e.g. 1,3-5) to toggle | "
440
+ "'all' (Select All) | 'none' (Select None) | 'done' (or Enter) | 'q' (Cancel)",
441
+ style="dim",
442
+ )
443
+ )
444
+
445
+ try:
446
+ choice = Prompt.ask("Selection", console=active_console, default="done").strip()
447
+ except (EOFError, KeyboardInterrupt):
448
+ return []
449
+
450
+ lowered = choice.lower()
451
+ if lowered in {"", "done", "d", "ok"}:
452
+ break
453
+ if lowered in {"q", "quit", "cancel"}:
454
+ return []
455
+ if lowered in {"all", "a"}:
456
+ selected_indices = set(range(1, total + 1))
457
+ continue
458
+ if lowered in {"none", "n"}:
459
+ selected_indices.clear()
460
+ continue
461
+
462
+ try:
463
+ toggled = parse_index_tokens(choice, total)
464
+ except ValueError as exc:
465
+ show_error(str(exc), console=active_console)
466
+ continue
467
+
468
+ selected_indices.symmetric_difference_update(toggled)
469
+
470
+ return [ordered_items[idx - 1] for idx in sorted(selected_indices)]
471
+
472
+
473
+ def confirm_deletion(
474
+ selected: Sequence[ScanResult],
475
+ console: Console | None = None,
476
+ ) -> bool:
477
+ """Prompt user for explicit confirmation before deleting selected folders."""
478
+ active_console = console or get_console()
479
+ total_size = sum(item.size_bytes for item in selected)
480
+ prompt_text = Text.assemble(
481
+ ("Are you sure you want to delete ", "bold yellow"),
482
+ (f"{len(selected)}", "bold red"),
483
+ (" folder(s) (", "bold yellow"),
484
+ (format_size(total_size), "bold red"),
485
+ (")?", "bold yellow"),
486
+ )
487
+ active_console.print(prompt_text)
488
+
489
+ try:
490
+ return Confirm.ask("Confirm deletion", console=active_console, default=False)
491
+ except (EOFError, KeyboardInterrupt):
492
+ return False
493
+
494
+
495
+ @contextmanager
496
+ def deletion_progress(
497
+ total: int,
498
+ console: Console,
499
+ ) -> Iterator[Callable[[Path, int, int], None]]:
500
+ """Display a Rich progress bar during folder deletion and yield a callback."""
501
+ encoding = (console.encoding or "").lower()
502
+ spinner_name = "dots" if encoding.startswith("utf") and not console.no_color else "line"
503
+
504
+ with Progress(
505
+ SpinnerColumn(spinner_name=spinner_name, style="yellow"),
506
+ TextColumn("[bold yellow]{task.description}[/bold yellow]"),
507
+ BarColumn(),
508
+ MofNCompleteColumn(),
509
+ transient=True,
510
+ console=console,
511
+ ) as progress:
512
+ task_id = progress.add_task("Deleting folders...", total=max(total, 1))
513
+
514
+ def _on_progress(current_path: Path, index: int, total_items: int) -> None:
515
+ safe_name = escape(current_path.name or str(current_path))
516
+ progress.update(
517
+ task_id,
518
+ completed=index - 1,
519
+ description=f"Deleting {safe_name} ({index}/{total_items})...",
520
+ )
521
+
522
+ yield _on_progress
523
+ progress.update(task_id, completed=max(total, 1))
524
+
525
+
526
+ def show_delete_summary(
527
+ result: DeleteResult,
528
+ console: Console | None = None,
529
+ base_path: Path | None = None,
530
+ ) -> None:
531
+ """Display a detailed summary report after folder deletion completes."""
532
+ active_console = console or get_console()
533
+ summary_text = Text()
534
+ summary_text.append("Deleted: ", style="bold")
535
+ summary_text.append(f"{result.deleted_count} folder(s)\n", style="bold cyan")
536
+ summary_text.append("Freed space: ", style="bold")
537
+ summary_text.append(f"{format_size(result.freed_bytes)}\n", style="bold green")
538
+ summary_text.append("Errors: ", style="bold")
539
+ summary_text.append(
540
+ str(result.failed_count),
541
+ style="bold red" if result.failed_count > 0 else "bold green",
542
+ )
543
+ if result.skipped_count > 0:
544
+ summary_text.append(" | ", style="dim")
545
+ summary_text.append("Skipped: ", style="bold")
546
+ summary_text.append(str(result.skipped_count), style="bold yellow")
547
+
548
+ if result.failed_count > 0:
549
+ border_style = "red"
550
+ elif result.skipped_count > 0:
551
+ border_style = "yellow"
552
+ else:
553
+ border_style = "green"
554
+
555
+ active_console.print(
556
+ Panel(
557
+ summary_text,
558
+ title="Cleanup Summary",
559
+ border_style=border_style,
560
+ box=box.ROUNDED,
561
+ expand=False,
562
+ )
563
+ )
564
+
565
+ for failed_path, reason in result.failed:
566
+ display_path = _format_display_path(failed_path, base_path)
567
+ err_line = Text(" [Failed] ", style="bold red")
568
+ err_line.append(f"{display_path}: {reason}")
569
+ active_console.print(err_line)
570
+
571
+ for skipped_path, reason in result.skipped:
572
+ display_path = _format_display_path(skipped_path, base_path)
573
+ skip_line = Text(" [Skipped] ", style="bold yellow")
574
+ skip_line.append(f"{display_path}: {reason}")
575
+ active_console.print(skip_line)
576
+
577
+
578
+ def get_docker_style(resource_type: DockerResourceType | str) -> str:
579
+ """Return the Rich style string associated with a Docker resource type."""
580
+ if isinstance(resource_type, DockerResourceType):
581
+ return DOCKER_TYPE_STYLES.get(resource_type, "white")
582
+ try:
583
+ return DOCKER_TYPE_STYLES.get(DockerResourceType(resource_type), "white")
584
+ except ValueError:
585
+ return "white"
586
+
587
+
588
+ def build_docker_table(
589
+ resources: Sequence[DockerResource],
590
+ selected_indices: set[int] | None = None,
591
+ ) -> Table:
592
+ """Build a Rich Table displaying unused Docker resources."""
593
+ is_selectable = selected_indices is not None
594
+ table = Table(
595
+ title="Select Docker Resources to Clean" if is_selectable else "Unused Docker Resources",
596
+ box=box.ROUNDED,
597
+ header_style="bold white",
598
+ border_style="bright_black",
599
+ expand=False,
600
+ )
601
+ if is_selectable:
602
+ table.add_column("#", justify="right", style="dim", no_wrap=True)
603
+ table.add_column("Selected", justify="center", no_wrap=True)
604
+ table.add_column("Resource", style="white", overflow="fold")
605
+ table.add_column("Type", no_wrap=True)
606
+ table.add_column("Status", style="dim", overflow="fold")
607
+ table.add_column("Size", justify="right", style="bold green", no_wrap=True)
608
+
609
+ for idx, item in enumerate(resources, start=1):
610
+ row: list[Text | str] = []
611
+ if is_selectable and selected_indices is not None:
612
+ row.append(str(idx))
613
+ row.append(
614
+ Text("[x]", style="bold green")
615
+ if idx in selected_indices
616
+ else Text("[ ]", style="dim")
617
+ )
618
+ row.append(Text(item.name))
619
+ row.append(Text(item.resource_type.value, style=get_docker_style(item.resource_type)))
620
+ row.append(Text(item.status or "-"))
621
+ row.append(Text(format_size(item.size_bytes), style="bold green"))
622
+ table.add_row(*row)
623
+
624
+ return table
625
+
626
+
627
+ def build_docker_summary_panel(
628
+ resources: Sequence[DockerResource],
629
+ title: str = "Docker Scan Summary",
630
+ ) -> Panel:
631
+ """Build a summary Rich Panel showing reclaimable Docker space."""
632
+ total_size = sum(item.size_bytes for item in resources)
633
+ summary_text = Text()
634
+ summary_text.append("Resources found: ", style="bold")
635
+ summary_text.append(f"{len(resources)}", style="bold cyan")
636
+ summary_text.append(" | ", style="dim")
637
+ summary_text.append("Total reclaimable: ", style="bold")
638
+ summary_text.append(format_size(total_size), style="bold green")
639
+
640
+ return Panel(
641
+ summary_text,
642
+ title=title,
643
+ border_style="cyan",
644
+ box=box.ROUNDED,
645
+ expand=False,
646
+ )
647
+
648
+
649
+ def show_docker_results(
650
+ resources: Sequence[DockerResource],
651
+ console: Console | None = None,
652
+ ) -> None:
653
+ """Render unused Docker resources in a Rich table and summary panel."""
654
+ active_console = console or get_console()
655
+ if not resources:
656
+ active_console.print(
657
+ Panel(
658
+ Text(
659
+ "Docker looks clean! No unused Docker resources found "
660
+ "(0 items, 0 B reclaimable).",
661
+ style="green",
662
+ ),
663
+ title="Docker Scan Summary",
664
+ border_style="green",
665
+ box=box.ROUNDED,
666
+ expand=False,
667
+ )
668
+ )
669
+ return
670
+
671
+ active_console.print(build_docker_table(resources))
672
+ active_console.print(build_docker_summary_panel(resources))
673
+
674
+
675
+ def select_docker_interactive(
676
+ resources: Sequence[DockerResource],
677
+ console: Console | None = None,
678
+ ) -> list[DockerResource]:
679
+ """Prompt the user to interactively select Docker resources to clean."""
680
+ active_console = console or get_console()
681
+ ordered = list(resources)
682
+ if not ordered:
683
+ return []
684
+
685
+ total = len(ordered)
686
+ selected_indices: set[int] = set()
687
+
688
+ while True:
689
+ active_console.print(build_docker_table(ordered, selected_indices=selected_indices))
690
+ selected_bytes = sum(ordered[idx - 1].size_bytes for idx in selected_indices)
691
+ active_console.print(
692
+ Text.assemble(
693
+ ("Selected: ", "bold"),
694
+ (f"{len(selected_indices)}/{total}", "bold cyan"),
695
+ (" | ", "dim"),
696
+ ("Size: ", "bold"),
697
+ (format_size(selected_bytes), "bold green"),
698
+ )
699
+ )
700
+ active_console.print(
701
+ Text(
702
+ "Commands: numbers/ranges (e.g. 1,3-5) to toggle | "
703
+ "'all' (Select All) | 'none' (Select None) | 'done' (or Enter) | 'q' (Cancel)",
704
+ style="dim",
705
+ )
706
+ )
707
+
708
+ try:
709
+ choice = Prompt.ask("Selection", console=active_console, default="done").strip()
710
+ except (EOFError, KeyboardInterrupt):
711
+ return []
712
+
713
+ lowered = choice.lower()
714
+ if lowered in {"", "done", "d", "ok"}:
715
+ break
716
+ if lowered in {"q", "quit", "cancel"}:
717
+ return []
718
+ if lowered in {"all", "a"}:
719
+ selected_indices = set(range(1, total + 1))
720
+ continue
721
+ if lowered in {"none", "n"}:
722
+ selected_indices.clear()
723
+ continue
724
+
725
+ try:
726
+ toggled = parse_index_tokens(choice, total)
727
+ except ValueError as exc:
728
+ show_error(str(exc), console=active_console)
729
+ continue
730
+
731
+ selected_indices.symmetric_difference_update(toggled)
732
+
733
+ return [ordered[idx - 1] for idx in sorted(selected_indices)]
734
+
735
+
736
+ def confirm_docker_deletion(
737
+ selected: Sequence[DockerResource],
738
+ console: Console | None = None,
739
+ ) -> bool:
740
+ """Prompt user for explicit confirmation before cleaning Docker resources."""
741
+ active_console = console or get_console()
742
+ total_size = sum(item.size_bytes for item in selected)
743
+ prompt_text = Text.assemble(
744
+ ("Are you sure you want to remove ", "bold yellow"),
745
+ (f"{len(selected)}", "bold red"),
746
+ (" unused Docker resource(s) (", "bold yellow"),
747
+ (format_size(total_size), "bold red"),
748
+ (")?", "bold yellow"),
749
+ )
750
+ active_console.print(prompt_text)
751
+
752
+ try:
753
+ return Confirm.ask("Confirm Docker cleanup", console=active_console, default=False)
754
+ except (EOFError, KeyboardInterrupt):
755
+ return False
756
+
757
+
758
+ @contextmanager
759
+ def docker_clean_progress(
760
+ total: int,
761
+ console: Console,
762
+ ) -> Iterator[Callable[[DockerResource, int, int], None]]:
763
+ """Display a Rich progress bar while removing Docker resources."""
764
+ encoding = (console.encoding or "").lower()
765
+ spinner_name = "dots" if encoding.startswith("utf") and not console.no_color else "line"
766
+
767
+ with Progress(
768
+ SpinnerColumn(spinner_name=spinner_name, style="yellow"),
769
+ TextColumn("[bold yellow]{task.description}[/bold yellow]"),
770
+ BarColumn(),
771
+ MofNCompleteColumn(),
772
+ transient=True,
773
+ console=console,
774
+ ) as progress:
775
+ task_id = progress.add_task("Cleaning Docker resources...", total=max(total, 1))
776
+
777
+ def _on_progress(resource: DockerResource, index: int, total_items: int) -> None:
778
+ safe_name = escape(resource.name)
779
+ progress.update(
780
+ task_id,
781
+ completed=index - 1,
782
+ description=f"Removing {safe_name} ({index}/{total_items})...",
783
+ )
784
+
785
+ yield _on_progress
786
+ progress.update(task_id, completed=max(total, 1))
787
+
788
+
789
+ def show_docker_clean_summary(
790
+ result: DockerCleanResult,
791
+ console: Console | None = None,
792
+ ) -> None:
793
+ """Display a summary report after Docker cleanup completes."""
794
+ active_console = console or get_console()
795
+ summary_text = Text()
796
+ summary_text.append("Cleaned: ", style="bold")
797
+ summary_text.append(f"{result.cleaned_count} resource(s)\n", style="bold cyan")
798
+ summary_text.append("Reclaimed space: ", style="bold")
799
+ summary_text.append(f"{format_size(result.reclaimed_bytes)}\n", style="bold green")
800
+ summary_text.append("Errors: ", style="bold")
801
+ summary_text.append(
802
+ str(result.failed_count),
803
+ style="bold red" if result.failed_count > 0 else "bold green",
804
+ )
805
+ if result.skipped_count > 0:
806
+ summary_text.append(" | ", style="dim")
807
+ summary_text.append("Skipped: ", style="bold")
808
+ summary_text.append(str(result.skipped_count), style="bold yellow")
809
+
810
+ if result.failed_count > 0:
811
+ border_style = "red"
812
+ elif result.skipped_count > 0:
813
+ border_style = "yellow"
814
+ else:
815
+ border_style = "green"
816
+
817
+ active_console.print(
818
+ Panel(
819
+ summary_text,
820
+ title="Docker Cleanup Summary",
821
+ border_style=border_style,
822
+ box=box.ROUNDED,
823
+ expand=False,
824
+ )
825
+ )
826
+
827
+ for name, reason in result.failed:
828
+ err_line = Text(" [Failed] ", style="bold red")
829
+ err_line.append(f"{name}: {reason}")
830
+ active_console.print(err_line)
831
+
832
+ for name, reason in result.skipped:
833
+ skip_line = Text(" [Skipped] ", style="bold yellow")
834
+ skip_line.append(f"{name}: {reason}")
835
+ active_console.print(skip_line)
836
+
837
+
838
+ def show_error(
839
+ message: str,
840
+ console: Console | None = None,
841
+ hint: str | None = None,
842
+ ) -> None:
843
+ """Render a styled Rich error panel with an optional troubleshooting hint."""
844
+ active_console = console or get_console()
845
+ err_icon = get_icon("error", active_console)
846
+ body = Text("Error: ", style="bold red")
847
+ body.append(message)
848
+ if hint:
849
+ body.append("\nHint: ", style="bold yellow")
850
+ body.append(hint, style="dim")
851
+
852
+ active_console.print(
853
+ Panel(
854
+ body,
855
+ title=f"{err_icon} Error",
856
+ border_style="red",
857
+ box=box.ROUNDED,
858
+ expand=False,
859
+ )
860
+ )
861
+
862
+
863
+ def format_scan_results_json(
864
+ results: Sequence[ScanResult],
865
+ targets: Sequence[Path] | None = None,
866
+ ) -> str:
867
+ """Serialize discovered folder scan results into a deterministic JSON payload."""
868
+ ordered = sort_scan_results(results)
869
+ total_reclaimable = sum(item.size_bytes for item in ordered)
870
+ payload: dict[str, object] = {
871
+ "targets": [str(target) for target in targets] if targets is not None else [],
872
+ "count": len(ordered),
873
+ "total_reclaimable_bytes": total_reclaimable,
874
+ "total_reclaimable_human": format_size(total_reclaimable),
875
+ "items": [
876
+ {
877
+ "path": str(item.path),
878
+ "folder_type": _format_folder_type(item.folder_type),
879
+ "size_bytes": item.size_bytes,
880
+ "size_human": format_size(item.size_bytes),
881
+ "modified_time": item.modified_time.isoformat(),
882
+ }
883
+ for item in ordered
884
+ ],
885
+ }
886
+ return json.dumps(payload, indent=2, ensure_ascii=False)
887
+
888
+
889
+ def format_docker_results_json(resources: Sequence[DockerResource]) -> str:
890
+ """Serialize unused Docker scan results into a deterministic JSON payload."""
891
+ ordered = list(resources)
892
+ total_reclaimable = sum(item.size_bytes for item in ordered)
893
+ payload: dict[str, object] = {
894
+ "count": len(ordered),
895
+ "total_reclaimable_bytes": total_reclaimable,
896
+ "total_reclaimable_human": format_size(total_reclaimable),
897
+ "resources": [
898
+ {
899
+ "resource_id": item.resource_id,
900
+ "name": item.name,
901
+ "resource_type": item.resource_type.value,
902
+ "size_bytes": item.size_bytes,
903
+ "size_human": format_size(item.size_bytes),
904
+ "status": item.status,
905
+ }
906
+ for item in ordered
907
+ ],
908
+ }
909
+ return json.dumps(payload, indent=2, ensure_ascii=False)