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/cli.py ADDED
@@ -0,0 +1,581 @@
1
+ """Command-line interface for DevSweep."""
2
+
3
+ import os
4
+ import sys
5
+ from pathlib import Path
6
+ from typing import Annotated
7
+
8
+ import typer
9
+ from rich.console import Console
10
+ from rich.text import Text
11
+
12
+ from devsweep import __version__
13
+ from devsweep.cleaner import delete_folders
14
+ from devsweep.display import (
15
+ build_docker_summary_panel,
16
+ build_summary_panel,
17
+ confirm_deletion,
18
+ confirm_docker_deletion,
19
+ deletion_progress,
20
+ docker_clean_progress,
21
+ format_docker_results_json,
22
+ format_scan_results_json,
23
+ get_console,
24
+ get_icon,
25
+ multi_path_scan_progress,
26
+ scanning_spinner,
27
+ select_docker_interactive,
28
+ select_folders_interactive,
29
+ show_delete_summary,
30
+ show_docker_clean_summary,
31
+ show_docker_results,
32
+ show_dry_run_banner,
33
+ show_error,
34
+ show_scan_results,
35
+ show_smart_home_notice,
36
+ sort_scan_results,
37
+ )
38
+ from devsweep.docker import (
39
+ check_docker_available,
40
+ clean_docker_resources,
41
+ scan_docker_resources,
42
+ )
43
+ from devsweep.models import ScanResult
44
+ from devsweep.scanner import expand_scan_roots, scan_paths
45
+ from devsweep.utils import resolve_user_path
46
+
47
+ app = typer.Typer(
48
+ name="devsweep",
49
+ help="Scan and safely clean developer build caches and temporary artifacts.",
50
+ epilog=(
51
+ "Examples:\n\n"
52
+ " devsweep scan .\n\n"
53
+ " devsweep scan ./frontend ./backend --max-depth 2\n\n"
54
+ " devsweep scan ~ --exclude Desktop\n\n"
55
+ " devsweep clean ./projects --interactive\n\n"
56
+ " devsweep docker scan\n\n"
57
+ " devsweep docker clean --dry-run"
58
+ ),
59
+ no_args_is_help=True,
60
+ )
61
+ docker_app = typer.Typer(
62
+ name="docker",
63
+ help="Scan and safely clean unused Docker images, containers, volumes, and build cache.",
64
+ epilog=(
65
+ "Examples:\n\n"
66
+ " devsweep docker scan\n\n"
67
+ " devsweep docker clean --dry-run\n\n"
68
+ " devsweep docker clean --interactive\n\n"
69
+ " devsweep docker clean --yes"
70
+ ),
71
+ no_args_is_help=True,
72
+ )
73
+ app.add_typer(docker_app, name="docker")
74
+
75
+
76
+ def _print_version(console: Console) -> None:
77
+ prefix = get_icon("sweep", console)
78
+ text = Text(f"{prefix} DevSweep ")
79
+ text.append(f"v{__version__}", style="bold cyan")
80
+ console.print(text)
81
+
82
+
83
+ def _version_callback(value: bool) -> None:
84
+ if value:
85
+ no_color = "--no-color" in sys.argv
86
+ _print_version(get_console(no_color=no_color))
87
+ raise typer.Exit()
88
+
89
+
90
+ def _resolve_console(ctx: typer.Context, no_color: bool = False) -> Console:
91
+ root_no_color = bool(ctx.obj.get("no_color", False)) if ctx.obj else False
92
+ return get_console(no_color=no_color or root_no_color)
93
+
94
+
95
+ def _run_scan(
96
+ paths: list[Path] | None,
97
+ max_depth: int | None,
98
+ exclude: list[str] | None,
99
+ ignore_file: Path | None,
100
+ console: Console,
101
+ *,
102
+ quiet: bool = False,
103
+ ) -> tuple[list[Path], Path | None, list[ScanResult]]:
104
+ """Validate target directories, handle smart home scan, and return discovered items."""
105
+ raw_paths = paths if paths else [Path(".")]
106
+ home_norm = os.path.normcase(str(Path.home().expanduser().resolve()))
107
+
108
+ if ignore_file is not None:
109
+ resolved_ignore = ignore_file.expanduser()
110
+ if not resolved_ignore.exists():
111
+ show_error(
112
+ f"Ignore file does not exist: {ignore_file}",
113
+ console=console,
114
+ hint="Verify the path passed to --ignore-file or create a .devsweepignore file.",
115
+ )
116
+ raise typer.Exit(code=1)
117
+ if resolved_ignore.is_dir():
118
+ show_error(
119
+ f"Ignore file path is a directory: {ignore_file}",
120
+ console=console,
121
+ hint="Pass a file path (for example: --ignore-file .devsweepignore).",
122
+ )
123
+ raise typer.Exit(code=1)
124
+
125
+ try:
126
+ expanded_roots, used_common_home = expand_scan_roots(raw_paths, smart_home=True)
127
+ except (FileNotFoundError, NotADirectoryError) as exc:
128
+ show_error(
129
+ str(exc),
130
+ console=console,
131
+ hint="Verify that all target paths exist and are directories.",
132
+ )
133
+ raise typer.Exit(code=1) from exc
134
+
135
+ requested_home = any(
136
+ os.path.normcase(str(resolve_user_path(p))) == home_norm for p in raw_paths
137
+ )
138
+ if quiet:
139
+ results = scan_paths(
140
+ raw_paths,
141
+ max_depth=max_depth,
142
+ exclude_patterns=exclude or (),
143
+ ignore_file=ignore_file,
144
+ smart_home=True,
145
+ )
146
+ else:
147
+ if requested_home:
148
+ show_smart_home_notice(expanded_roots, used_common_home, console=console)
149
+
150
+ if len(expanded_roots) > 1:
151
+ with multi_path_scan_progress(len(expanded_roots), console) as on_root_progress:
152
+ results = scan_paths(
153
+ raw_paths,
154
+ max_depth=max_depth,
155
+ exclude_patterns=exclude or (),
156
+ ignore_file=ignore_file,
157
+ smart_home=True,
158
+ on_root_progress=on_root_progress,
159
+ )
160
+ else:
161
+ label = expanded_roots[0].name or str(expanded_roots[0])
162
+ with scanning_spinner(console, message=f"Scanning {label}..."):
163
+ results = scan_paths(
164
+ raw_paths,
165
+ max_depth=max_depth,
166
+ exclude_patterns=exclude or (),
167
+ ignore_file=ignore_file,
168
+ smart_home=True,
169
+ )
170
+
171
+ single_base = expanded_roots[0] if len(expanded_roots) == 1 else None
172
+ return expanded_roots, single_base, results
173
+
174
+
175
+ @app.callback()
176
+ def main(
177
+ ctx: typer.Context,
178
+ show_version: Annotated[
179
+ bool,
180
+ typer.Option(
181
+ "--version",
182
+ "-V",
183
+ callback=_version_callback,
184
+ is_eager=True,
185
+ help="Show DevSweep version and exit.",
186
+ ),
187
+ ] = False,
188
+ no_color: Annotated[
189
+ bool,
190
+ typer.Option("--no-color", help="Disable colored terminal output."),
191
+ ] = False,
192
+ ) -> None:
193
+ """DevSweep CLI entrypoint."""
194
+ _ = show_version
195
+ ctx.ensure_object(dict)
196
+ ctx.obj["no_color"] = no_color
197
+
198
+
199
+ @app.command(
200
+ epilog="Example:\n\n devsweep version",
201
+ )
202
+ def version(
203
+ ctx: typer.Context,
204
+ no_color: Annotated[
205
+ bool,
206
+ typer.Option("--no-color", help="Disable colored terminal output."),
207
+ ] = False,
208
+ ) -> None:
209
+ """Display the installed DevSweep version."""
210
+ active_console = _resolve_console(ctx, no_color=no_color)
211
+ _print_version(active_console)
212
+
213
+
214
+ @app.command(
215
+ epilog=(
216
+ "Examples:\n\n"
217
+ " devsweep scan .\n\n"
218
+ " devsweep scan ./web ./api --max-depth 2\n\n"
219
+ " devsweep scan ~ --exclude '*backup*' --dry-run\n\n"
220
+ " devsweep scan ./workspace --json\n\n"
221
+ " devsweep scan ./workspace --no-color"
222
+ )
223
+ )
224
+ def scan(
225
+ ctx: typer.Context,
226
+ paths: Annotated[
227
+ list[Path] | None,
228
+ typer.Argument(help="One or more directory paths to scan."),
229
+ ] = None,
230
+ max_depth: Annotated[
231
+ int | None,
232
+ typer.Option(
233
+ "--max-depth",
234
+ "-d",
235
+ min=0,
236
+ help="Maximum directory depth to scan.",
237
+ ),
238
+ ] = None,
239
+ exclude: Annotated[
240
+ list[str] | None,
241
+ typer.Option(
242
+ "--exclude",
243
+ "-e",
244
+ help="Directory name or glob pattern to exclude (can be repeated).",
245
+ ),
246
+ ] = None,
247
+ ignore_file: Annotated[
248
+ Path | None,
249
+ typer.Option(
250
+ "--ignore-file",
251
+ help="Path to a custom gitignore-style ignore file (overrides .devsweepignore).",
252
+ ),
253
+ ] = None,
254
+ dry_run: Annotated[
255
+ bool,
256
+ typer.Option(
257
+ "--dry-run",
258
+ "-n",
259
+ help="Preview cleanable folders without deleting anything.",
260
+ ),
261
+ ] = False,
262
+ json_output: Annotated[
263
+ bool,
264
+ typer.Option(
265
+ "--json",
266
+ help="Output scan results as machine-readable JSON.",
267
+ ),
268
+ ] = False,
269
+ no_color: Annotated[
270
+ bool,
271
+ typer.Option("--no-color", help="Disable colored terminal output."),
272
+ ] = False,
273
+ ) -> None:
274
+ """Scan one or more directories and display cleanable folders."""
275
+ active_console = _resolve_console(ctx, no_color=no_color)
276
+ if dry_run and not json_output:
277
+ show_dry_run_banner(active_console)
278
+
279
+ expanded_roots, single_base, results = _run_scan(
280
+ paths=paths,
281
+ max_depth=max_depth,
282
+ exclude=exclude,
283
+ ignore_file=ignore_file,
284
+ console=active_console,
285
+ quiet=json_output,
286
+ )
287
+ if json_output:
288
+ typer.echo(format_scan_results_json(results, targets=expanded_roots))
289
+ return
290
+
291
+ show_scan_results(
292
+ results,
293
+ console=active_console,
294
+ base_path=single_base,
295
+ base_paths=expanded_roots,
296
+ )
297
+
298
+
299
+ @app.command(
300
+ epilog=(
301
+ "Examples:\n\n"
302
+ " devsweep clean . --dry-run\n\n"
303
+ " devsweep clean ./web ./api --max-depth 2 --interactive\n\n"
304
+ " devsweep clean ./projects --exclude vendor --yes"
305
+ )
306
+ )
307
+ def clean(
308
+ ctx: typer.Context,
309
+ paths: Annotated[
310
+ list[Path] | None,
311
+ typer.Argument(help="One or more directory paths to scan and clean."),
312
+ ] = None,
313
+ max_depth: Annotated[
314
+ int | None,
315
+ typer.Option(
316
+ "--max-depth",
317
+ "-d",
318
+ min=0,
319
+ help="Maximum directory depth to scan.",
320
+ ),
321
+ ] = None,
322
+ exclude: Annotated[
323
+ list[str] | None,
324
+ typer.Option(
325
+ "--exclude",
326
+ "-e",
327
+ help="Directory name or glob pattern to exclude (can be repeated).",
328
+ ),
329
+ ] = None,
330
+ ignore_file: Annotated[
331
+ Path | None,
332
+ typer.Option(
333
+ "--ignore-file",
334
+ help="Path to a custom gitignore-style ignore file (overrides .devsweepignore).",
335
+ ),
336
+ ] = None,
337
+ dry_run: Annotated[
338
+ bool,
339
+ typer.Option(
340
+ "--dry-run",
341
+ "-n",
342
+ help="Show what would be deleted without removing any files.",
343
+ ),
344
+ ] = False,
345
+ interactive: Annotated[
346
+ bool,
347
+ typer.Option(
348
+ "--interactive",
349
+ "-i",
350
+ help="Interactively choose which discovered folders to clean.",
351
+ ),
352
+ ] = False,
353
+ yes: Annotated[
354
+ bool,
355
+ typer.Option(
356
+ "--yes",
357
+ "-y",
358
+ help="Skip confirmation prompt before deletion.",
359
+ ),
360
+ ] = False,
361
+ no_color: Annotated[
362
+ bool,
363
+ typer.Option("--no-color", help="Disable colored terminal output."),
364
+ ] = False,
365
+ ) -> None:
366
+ """Scan and safely clean developer artifacts across one or more paths."""
367
+ active_console = _resolve_console(ctx, no_color=no_color)
368
+ if dry_run:
369
+ show_dry_run_banner(active_console)
370
+
371
+ expanded_roots, single_base, results = _run_scan(
372
+ paths=paths,
373
+ max_depth=max_depth,
374
+ exclude=exclude,
375
+ ignore_file=ignore_file,
376
+ console=active_console,
377
+ )
378
+
379
+ if not results:
380
+ show_scan_results(
381
+ [],
382
+ console=active_console,
383
+ base_path=single_base,
384
+ base_paths=expanded_roots,
385
+ )
386
+ return
387
+
388
+ if interactive:
389
+ selected = select_folders_interactive(
390
+ results, console=active_console, base_path=single_base
391
+ )
392
+ if not selected:
393
+ active_console.print(Text("No folders selected. Nothing to clean.", style="yellow"))
394
+ return
395
+ else:
396
+ selected = sort_scan_results(results)
397
+ show_scan_results(
398
+ selected,
399
+ console=active_console,
400
+ base_path=single_base,
401
+ base_paths=expanded_roots,
402
+ )
403
+
404
+ if dry_run:
405
+ if interactive:
406
+ active_console.print(
407
+ build_summary_panel(
408
+ selected,
409
+ base_path=single_base,
410
+ base_paths=expanded_roots,
411
+ title="Dry-Run Selection Summary",
412
+ )
413
+ )
414
+ return
415
+
416
+ if not yes and not confirm_deletion(selected, console=active_console):
417
+ active_console.print(Text("Cleanup cancelled.", style="yellow"))
418
+ return
419
+
420
+ target_paths = [item.path for item in selected]
421
+ size_map = {item.path: item.size_bytes for item in selected}
422
+
423
+ with deletion_progress(len(target_paths), active_console) as on_progress:
424
+ delete_result = delete_folders(
425
+ target_paths,
426
+ allowed_roots=expanded_roots,
427
+ sizes=size_map,
428
+ require_cleanable=True,
429
+ on_progress=on_progress,
430
+ )
431
+
432
+ show_delete_summary(delete_result, console=active_console, base_path=single_base)
433
+ if delete_result.has_errors:
434
+ raise typer.Exit(code=1)
435
+
436
+
437
+ def _ensure_docker_available(console: Console) -> None:
438
+ available, reason = check_docker_available()
439
+ if not available:
440
+ show_error(
441
+ reason or "Docker is unavailable.",
442
+ console=console,
443
+ hint="Install Docker or start Docker Desktop, then retry `devsweep docker scan`.",
444
+ )
445
+ raise typer.Exit(code=1)
446
+
447
+
448
+ @docker_app.command(
449
+ "scan",
450
+ epilog=(
451
+ "Examples:\n\n"
452
+ " devsweep docker scan\n\n"
453
+ " devsweep docker scan --json\n\n"
454
+ " devsweep docker scan --dry-run\n\n"
455
+ " devsweep docker scan --no-color"
456
+ ),
457
+ )
458
+ def docker_scan(
459
+ ctx: typer.Context,
460
+ dry_run: Annotated[
461
+ bool,
462
+ typer.Option(
463
+ "--dry-run",
464
+ "-n",
465
+ help="Preview unused Docker resources without removing anything.",
466
+ ),
467
+ ] = False,
468
+ json_output: Annotated[
469
+ bool,
470
+ typer.Option(
471
+ "--json",
472
+ help="Output unused Docker resources as machine-readable JSON.",
473
+ ),
474
+ ] = False,
475
+ no_color: Annotated[
476
+ bool,
477
+ typer.Option("--no-color", help="Disable colored terminal output."),
478
+ ] = False,
479
+ ) -> None:
480
+ """List unused Docker dangling images, stopped containers, volumes, and build cache."""
481
+ active_console = _resolve_console(ctx, no_color=no_color)
482
+ if dry_run and not json_output:
483
+ show_dry_run_banner(active_console)
484
+
485
+ _ensure_docker_available(active_console)
486
+ if json_output:
487
+ resources = scan_docker_resources()
488
+ typer.echo(format_docker_results_json(resources))
489
+ return
490
+
491
+ with scanning_spinner(active_console, message="Scanning Docker resources..."):
492
+ resources = scan_docker_resources()
493
+
494
+ show_docker_results(resources, console=active_console)
495
+
496
+
497
+ @docker_app.command(
498
+ "clean",
499
+ epilog=(
500
+ "Examples:\n\n"
501
+ " devsweep docker clean --dry-run\n\n"
502
+ " devsweep docker clean --interactive\n\n"
503
+ " devsweep docker clean --yes"
504
+ ),
505
+ )
506
+ def docker_clean(
507
+ ctx: typer.Context,
508
+ dry_run: Annotated[
509
+ bool,
510
+ typer.Option(
511
+ "--dry-run",
512
+ "-n",
513
+ help="Show Docker resources that would be removed without deleting them.",
514
+ ),
515
+ ] = False,
516
+ interactive: Annotated[
517
+ bool,
518
+ typer.Option(
519
+ "--interactive",
520
+ "-i",
521
+ help="Interactively select which unused Docker resources to remove.",
522
+ ),
523
+ ] = False,
524
+ yes: Annotated[
525
+ bool,
526
+ typer.Option(
527
+ "--yes",
528
+ "-y",
529
+ help="Skip confirmation prompt before removing unused Docker resources.",
530
+ ),
531
+ ] = False,
532
+ no_color: Annotated[
533
+ bool,
534
+ typer.Option("--no-color", help="Disable colored terminal output."),
535
+ ] = False,
536
+ ) -> None:
537
+ """Safely remove unused Docker resources (never touches running containers or in-use images)."""
538
+ active_console = _resolve_console(ctx, no_color=no_color)
539
+ if dry_run:
540
+ show_dry_run_banner(active_console)
541
+
542
+ _ensure_docker_available(active_console)
543
+ with scanning_spinner(active_console, message="Scanning Docker resources..."):
544
+ resources = scan_docker_resources()
545
+
546
+ if not resources:
547
+ show_docker_results([], console=active_console)
548
+ return
549
+
550
+ if interactive:
551
+ selected = select_docker_interactive(resources, console=active_console)
552
+ if not selected:
553
+ active_console.print(
554
+ Text("No Docker resources selected. Nothing to clean.", style="yellow")
555
+ )
556
+ return
557
+ else:
558
+ selected = resources
559
+ show_docker_results(selected, console=active_console)
560
+
561
+ if dry_run:
562
+ if interactive:
563
+ active_console.print(
564
+ build_docker_summary_panel(selected, title="Dry-Run Docker Selection Summary")
565
+ )
566
+ return
567
+
568
+ if not yes and not confirm_docker_deletion(selected, console=active_console):
569
+ active_console.print(Text("Docker cleanup cancelled.", style="yellow"))
570
+ return
571
+
572
+ with docker_clean_progress(len(selected), active_console) as on_progress:
573
+ clean_result = clean_docker_resources(selected, dry_run=False, on_progress=on_progress)
574
+
575
+ show_docker_clean_summary(clean_result, console=active_console)
576
+ if clean_result.has_errors:
577
+ raise typer.Exit(code=1)
578
+
579
+
580
+ if __name__ == "__main__":
581
+ app()