devclean-cli 0.4.0

Audit and safely remove rebuildable development artifacts
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
use std::collections::HashSet;
use std::env;
use std::fs;
use std::io::{self, IsTerminal, Write as _};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::{SystemTime, UNIX_EPOCH};

use anyhow::{Context, Result, bail};
use clap::{Args, CommandFactory, Parser, Subcommand};
use clap_complete::Shell;
use devclean::docker;
use devclean::{
    Category, CleanOptions, Config, LearningMode, OutputFormat, RenderOptions, ScanOptions,
    ScanReport, clean_with_options, config_candidates, default_roots, human_bytes, list_quarantine,
    load_config, parse_age, parse_bytes, purge_expired, render_with_options, restore_quarantine,
    scan,
};

#[derive(Debug, Parser)]
#[command(
    name = "devclean",
    version,
    about = "Audit and safely remove rebuildable development artifacts",
    arg_required_else_help = true
)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Debug, Subcommand)]
enum Commands {
    /// Inventory rebuildable artifacts without deleting anything.
    Scan(ScanArgs),
    /// Delete a freshly scanned, safety-validated cleanup plan.
    Clean(CleanArgs),
    /// Show defaults, safety guarantees, configuration, and tool availability.
    Doctor,
    /// List, restore, or purge persistent cleanup safety holds.
    Quarantine(QuarantineArgs),
    /// Generate shell completion scripts.
    Completions(CompletionsArgs),
    /// Generate a roff manual page.
    Manpage(ManpageArgs),
}

#[derive(Debug, Args)]
struct SharedScanArgs {
    /// Roots to scan. Defaults to config, then common development directories.
    #[arg(value_name = "ROOT")]
    roots: Vec<PathBuf>,

    /// Configuration file. Defaults to ./devclean.toml or the platform config directory.
    #[arg(long)]
    config: Option<PathBuf>,

    /// Categories to include. May be repeated or comma-separated.
    #[arg(long, value_enum, value_delimiter = ',')]
    category: Vec<Category>,

    /// Exclude a path glob. May be repeated.
    #[arg(long, value_name = "GLOB")]
    exclude: Vec<String>,

    /// Include package-manager and development-tool caches that are cheap to restore.
    #[arg(long)]
    global_caches: bool,

    /// Include large runtime and model caches that can be expensive to restore.
    #[arg(long)]
    expensive_caches: bool,

    /// Only include artifacts older than this duration, for example 30d or 12h.
    #[arg(long)]
    older_than: Option<String>,

    /// Only include artifacts at least this large, for example 500MiB.
    #[arg(long)]
    min_size: Option<String>,

    /// Maximum directory depth below each root.
    #[arg(long)]
    max_depth: Option<usize>,

    /// Permit cleanup of candidates containing Git-tracked files.
    #[arg(long)]
    allow_tracked: bool,
}

#[derive(Debug, Args)]
struct ScanArgs {
    #[command(flatten)]
    shared: SharedScanArgs,

    /// Include every rebuildable category, including build and test outputs.
    #[arg(long)]
    all: bool,

    /// Include Docker's detailed, read-only disk usage summary.
    #[arg(long)]
    docker: bool,

    /// Report format.
    #[arg(long, value_enum, default_value_t = OutputFormat::Table)]
    format: OutputFormat,

    /// Write the report to a file instead of stdout.
    #[arg(long)]
    output: Option<PathBuf>,

    /// Replace absolute paths in reports with root-relative placeholders.
    #[arg(long)]
    redact_paths: bool,

    #[command(flatten)]
    learning: LearningArgs,
}

#[derive(Debug, Args)]
struct LearningArgs {
    /// Observe large cache-like directories as review-only Learning Mode candidates.
    #[arg(long)]
    learning: bool,
}

#[derive(Debug, Args)]
struct CleanArgs {
    #[command(flatten)]
    shared: SharedScanArgs,

    /// Include build and test output categories in addition to safe defaults.
    #[arg(long)]
    all: bool,

    #[command(flatten)]
    docker: DockerArgs,

    #[command(flatten)]
    selection: SelectionArgs,

    /// Skip the final DELETE confirmation.
    #[arg(long)]
    yes: bool,

    /// Keep selected artifacts restorable for this duration, for example 7d.
    #[arg(long, value_name = "DURATION")]
    quarantine_for: Option<String>,

    /// Override the quarantine registry path.
    #[arg(long, hide = true)]
    quarantine_registry: Option<PathBuf>,

    #[command(flatten)]
    report: CleanReportArgs,
}

#[derive(Debug, Args)]
struct DockerArgs {
    /// Prune only unused Docker build cache.
    #[arg(long, conflicts_with = "docker_system")]
    docker: bool,

    /// Prune stopped containers, unused images/networks, and build cache. Never volumes.
    #[arg(long, conflicts_with = "docker")]
    docker_system: bool,

    /// Pass an `until` filter to Docker prune, for example 168h.
    #[arg(long)]
    docker_older_than: Option<String>,
}

#[derive(Debug, Args)]
struct SelectionArgs {
    /// Interactively select candidates by number or range.
    #[arg(long)]
    select: bool,

    /// Clean only exact candidate paths from a previous JSON scan. May be repeated.
    #[arg(
        long = "only-path",
        value_name = "PATH",
        conflicts_with_all = ["select", "target_free"]
    )]
    only_paths: Vec<PathBuf>,

    /// Remove only enough candidates to reach this amount of free space.
    #[arg(long, value_name = "SIZE")]
    target_free: Option<String>,
}

#[derive(Debug, Args)]
struct CleanReportArgs {
    /// Save the exact pre-clean plan as a standalone HTML report.
    #[arg(long)]
    report: Option<PathBuf>,

    /// Replace absolute paths in the saved report with root-relative placeholders.
    #[arg(long)]
    redact_paths: bool,
}

#[derive(Debug, Args)]
struct CompletionsArgs {
    /// Shell syntax to generate.
    #[arg(value_enum)]
    shell: Shell,
}

#[derive(Debug, Args)]
struct ManpageArgs {
    /// Output path. Defaults to stdout.
    #[arg(long)]
    output: Option<PathBuf>,
}

#[derive(Debug, Args)]
struct QuarantineArgs {
    #[command(subcommand)]
    command: QuarantineCommands,
}

#[derive(Debug, Subcommand)]
enum QuarantineCommands {
    /// List restorable safety holds.
    List(QuarantineListArgs),
    /// Restore one safety hold to its original path.
    Restore(QuarantineRestoreArgs),
    /// Permanently delete expired safety holds.
    Purge(QuarantinePurgeArgs),
}

#[derive(Debug, Args)]
struct QuarantineListArgs {
    /// Emit machine-readable JSON.
    #[arg(long)]
    json: bool,
    /// Override the quarantine registry path.
    #[arg(long, hide = true)]
    registry: Option<PathBuf>,
}

#[derive(Debug, Args)]
struct QuarantineRestoreArgs {
    /// Quarantine identifier shown by `quarantine list`.
    id: String,
    /// Override the quarantine registry path.
    #[arg(long, hide = true)]
    registry: Option<PathBuf>,
}

#[derive(Debug, Args)]
struct QuarantinePurgeArgs {
    /// Purge all holds, including those that have not expired.
    #[arg(long)]
    all: bool,
    /// Emit machine-readable JSON.
    #[arg(long)]
    json: bool,
    /// Override the quarantine registry path.
    #[arg(long, hide = true)]
    registry: Option<PathBuf>,
}

fn main() -> Result<()> {
    match Cli::parse().command {
        Commands::Scan(arguments) => run_scan(&arguments),
        Commands::Clean(arguments) => run_clean(&arguments),
        Commands::Doctor => {
            run_doctor();
            Ok(())
        }
        Commands::Quarantine(arguments) => run_quarantine(&arguments),
        Commands::Completions(arguments) => {
            clap_complete::generate(
                arguments.shell,
                &mut Cli::command(),
                "devclean",
                &mut io::stdout(),
            );
            Ok(())
        }
        Commands::Manpage(arguments) => run_manpage(arguments.output.as_deref()),
    }
}

fn run_scan(arguments: &ScanArgs) -> Result<()> {
    let config = load_config(arguments.shared.config.as_deref())?;
    let categories = select_categories(&arguments.shared, arguments.all, false);
    let report = scan(&scan_options(
        &arguments.shared,
        &config,
        categories,
        arguments.learning.learning,
    )?)?;
    write_report(
        &report,
        arguments.format,
        arguments.output.as_deref(),
        arguments.redact_paths,
    )?;
    if arguments.docker {
        println!("\nDocker disk usage:\n{}", docker::system_df()?);
    }
    Ok(())
}

fn run_clean(arguments: &CleanArgs) -> Result<()> {
    if arguments.docker.docker_older_than.is_some()
        && !arguments.docker.docker
        && !arguments.docker.docker_system
    {
        bail!("--docker-older-than requires --docker or --docker-system");
    }
    let config = load_config(arguments.shared.config.as_deref())?;
    let mut categories = select_categories(&arguments.shared, arguments.all, true);
    if config.clean.expensive_caches {
        categories.insert(Category::ExpensiveGlobalCache);
    }
    let mut report = scan(&scan_options(
        &arguments.shared,
        &config,
        categories,
        false,
    )?)?;
    if let Some(target) = arguments.selection.target_free.as_deref() {
        report = limit_to_target_free(report, parse_bytes(target)?)?;
    }
    if !arguments.selection.only_paths.is_empty() {
        report = select_exact_candidates(report, &arguments.selection.only_paths)?;
    }
    if arguments.selection.select && !report.candidates.is_empty() {
        report = select_candidates(report)?;
    }

    print!(
        "{}",
        render_with_options(&report, OutputFormat::Table, RenderOptions::default())?
    );
    if let Some(path) = &arguments.report.report {
        write_report(
            &report,
            OutputFormat::Html,
            Some(path),
            arguments.report.redact_paths,
        )?;
        println!("pre-clean report: {}", path.display());
    }

    let docker_requested = arguments.docker.docker || arguments.docker.docker_system;
    if report.candidates.is_empty() && !docker_requested {
        println!("nothing to clean");
        return Ok(());
    }
    confirm(arguments.yes)?;

    let clean_options = CleanOptions {
        quarantine_for: arguments
            .quarantine_for
            .as_deref()
            .map(parse_age)
            .transpose()?,
        quarantine_registry: arguments.quarantine_registry.clone(),
    };
    let cleaned = clean_with_options(&report, &clean_options);
    for candidate in &cleaned.removed {
        println!(
            "removed {:>10}  {}",
            human_bytes(candidate.bytes),
            candidate.path.display()
        );
    }
    for entry in &cleaned.quarantined {
        println!(
            "held    {:>10}  {}  until {}",
            human_bytes(entry.bytes),
            entry.original_path.display(),
            entry.expires_at_unix
        );
    }
    if arguments.docker.docker {
        println!(
            "{}",
            docker::prune_build_cache(arguments.docker.docker_older_than.as_deref())?
        );
    } else if arguments.docker.docker_system {
        println!(
            "{}",
            docker::prune_system(arguments.docker.docker_older_than.as_deref())?
        );
    }
    println!(
        "removed {} filesystem candidates, {} estimated",
        cleaned.removed.len(),
        human_bytes(cleaned.removed_bytes)
    );
    if !cleaned.quarantined.is_empty() {
        println!(
            "held {} candidates, {} retained on disk until purge",
            cleaned.quarantined.len(),
            human_bytes(cleaned.quarantined_bytes)
        );
    }
    if !cleaned.failures.is_empty() {
        for failure in &cleaned.failures {
            eprintln!("failed: {failure}");
        }
        bail!("{} candidates could not be removed", cleaned.failures.len());
    }
    Ok(())
}

fn run_quarantine(arguments: &QuarantineArgs) -> Result<()> {
    match &arguments.command {
        QuarantineCommands::List(arguments) => {
            let entries = list_quarantine(arguments.registry.as_deref())?;
            if arguments.json {
                println!("{}", serde_json::to_string_pretty(&entries)?);
            } else if entries.is_empty() {
                println!("no safety holds");
            } else {
                println!("ID\tEXPIRES\tSIZE\tORIGINAL PATH");
                for entry in entries {
                    println!(
                        "{}\t{}\t{}\t{}",
                        entry.id,
                        entry.expires_at_unix,
                        human_bytes(entry.bytes),
                        entry.original_path.display()
                    );
                }
            }
            Ok(())
        }
        QuarantineCommands::Restore(arguments) => {
            let entry = restore_quarantine(&arguments.id, arguments.registry.as_deref())?;
            println!("restored {}", entry.original_path.display());
            Ok(())
        }
        QuarantineCommands::Purge(arguments) => {
            let now = if arguments.all {
                u64::MAX
            } else {
                SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .map_or(0, |duration| duration.as_secs())
            };
            let report = purge_expired(now, arguments.registry.as_deref())?;
            if arguments.json {
                println!("{}", serde_json::to_string_pretty(&report)?);
            } else {
                println!(
                    "purged {} safety holds, {} reclaimed",
                    report.purged.len(),
                    human_bytes(report.purged_bytes)
                );
                for failure in &report.failures {
                    eprintln!("failed: {failure}");
                }
            }
            if !report.failures.is_empty() {
                bail!("{} safety holds could not be purged", report.failures.len());
            }
            Ok(())
        }
    }
}

fn run_doctor() {
    println!("devclean {}", env!("CARGO_PKG_VERSION"));
    println!("default roots:");
    for root in default_roots() {
        println!("  {}", root.display());
    }
    println!("config search:");
    for path in config_candidates() {
        println!(
            "  {} {}",
            if path.is_file() {
                "loaded"
            } else {
                "candidate"
            },
            path.display()
        );
    }
    println!("tools:");
    for tool in ["cargo", "docker", "git", "npm", "pnpm"] {
        println!(
            "  {tool:<8} {}",
            if command_exists(tool) {
                "available"
            } else {
                "not found"
            }
        );
    }
    println!("safety:");
    println!("  scan is always read-only");
    println!("  clean requires confirmation or --yes");
    println!("  Git-tracked files are protected unless --allow-tracked is explicit");
    println!("  candidates are atomically quarantined before recursive deletion");
    println!("  symlinks, VCS metadata, backups, databases and volumes are protected");
    println!("  --docker prunes build cache only; --docker-system never includes volumes");
}

fn scan_options(
    arguments: &SharedScanArgs,
    config: &Config,
    categories: HashSet<Category>,
    learning_mode: bool,
) -> Result<ScanOptions> {
    let roots = if !arguments.roots.is_empty() {
        arguments
            .roots
            .iter()
            .map(|path| expand_root(path))
            .collect()
    } else if !config.scan.roots.is_empty() {
        config
            .scan
            .roots
            .iter()
            .map(|path| expand_root(path))
            .collect()
    } else {
        default_roots()
    };
    let mut excludes = config.scan.exclude.clone();
    excludes.extend(arguments.exclude.iter().cloned());
    let older_than = arguments
        .older_than
        .as_deref()
        .or(config.scan.older_than.as_deref())
        .map(parse_age)
        .transpose()?;
    let min_size = arguments
        .min_size
        .as_deref()
        .or(config.scan.min_size.as_deref())
        .map(parse_bytes)
        .transpose()?
        .unwrap_or(0);

    Ok(ScanOptions {
        roots,
        categories,
        include_global_caches: arguments.global_caches,
        include_expensive_caches: arguments.expensive_caches || config.clean.expensive_caches,
        max_depth: arguments.max_depth.or(config.scan.max_depth).unwrap_or(24),
        excludes,
        older_than,
        min_size,
        protect_git_tracked: config.clean.protect_git_tracked && !arguments.allow_tracked,
        learning_mode: if learning_mode {
            LearningMode::Enabled
        } else {
            LearningMode::Disabled
        },
    })
}

fn select_categories(
    arguments: &SharedScanArgs,
    all: bool,
    conservative_default: bool,
) -> HashSet<Category> {
    let mut categories: HashSet<Category> = if !arguments.category.is_empty() {
        arguments.category.iter().copied().collect()
    } else if all || !conservative_default {
        Category::all().into_iter().collect()
    } else {
        Category::safe_defaults().into_iter().collect()
    };
    if arguments.global_caches {
        categories.insert(Category::GlobalCache);
    }
    if arguments.expensive_caches {
        categories.insert(Category::ExpensiveGlobalCache);
    }
    categories
}

fn expand_root(path: &Path) -> PathBuf {
    let value = path.to_string_lossy();
    if let Some(relative) = value.strip_prefix("~/") {
        return directories::BaseDirs::new()
            .map_or_else(|| path.to_path_buf(), |base| base.home_dir().join(relative));
    }
    path.to_path_buf()
}

fn limit_to_target_free(mut report: ScanReport, target: u64) -> Result<ScanReport> {
    let root = report
        .roots
        .first()
        .context("target-free requires at least one scan root")?;
    let available = fs2::available_space(root)?;
    let needed = target.saturating_sub(available);
    if needed == 0 {
        report.candidates.clear();
        report.total_bytes = 0;
        return Ok(report);
    }
    let mut selected = Vec::new();
    let mut selected_bytes = 0_u64;
    for candidate in report.candidates {
        selected_bytes = selected_bytes.saturating_add(candidate.bytes);
        selected.push(candidate);
        if selected_bytes >= needed {
            break;
        }
    }
    report.candidates = selected;
    report.total_bytes = selected_bytes;
    Ok(report)
}

fn select_candidates(mut report: ScanReport) -> Result<ScanReport> {
    if !io::stdin().is_terminal() {
        bail!("--select requires an interactive terminal");
    }
    for (index, candidate) in report.candidates.iter().enumerate() {
        println!(
            "{:>4}. {:>10}  {}",
            index + 1,
            human_bytes(candidate.bytes),
            candidate.path.display()
        );
    }
    print!("Select candidates (example: 1,3-5 or all): ");
    io::stdout().flush()?;
    let mut response = String::new();
    io::stdin().read_line(&mut response)?;
    let indexes = parse_selection(response.trim(), report.candidates.len())?;
    report.candidates = report
        .candidates
        .into_iter()
        .enumerate()
        .filter_map(|(index, candidate)| indexes.contains(&(index + 1)).then_some(candidate))
        .collect();
    report.total_bytes = report
        .candidates
        .iter()
        .map(|candidate| candidate.bytes)
        .sum();
    Ok(report)
}

fn select_exact_candidates(
    mut report: ScanReport,
    requested_paths: &[PathBuf],
) -> Result<ScanReport> {
    let requested: HashSet<PathBuf> = requested_paths
        .iter()
        .map(|path| path_identity(path))
        .collect();
    let found: HashSet<PathBuf> = report
        .candidates
        .iter()
        .map(|candidate| path_identity(&candidate.path))
        .filter(|path| requested.contains(path))
        .collect();
    let mut missing: Vec<_> = requested.difference(&found).collect();
    missing.sort();
    if let Some(path) = missing.first() {
        bail!(
            "selected path is no longer an eligible cleanup candidate: {}",
            path.display()
        );
    }

    report
        .candidates
        .retain(|candidate| requested.contains(&path_identity(&candidate.path)));
    report.total_bytes = report
        .candidates
        .iter()
        .map(|candidate| candidate.bytes)
        .sum();
    Ok(report)
}

fn path_identity(path: &Path) -> PathBuf {
    let expanded = expand_root(path);
    fs::canonicalize(&expanded).unwrap_or(expanded)
}

fn parse_selection(value: &str, maximum: usize) -> Result<HashSet<usize>> {
    if value.eq_ignore_ascii_case("all") {
        return Ok((1..=maximum).collect());
    }
    let mut selected = HashSet::new();
    for part in value
        .split(',')
        .map(str::trim)
        .filter(|part| !part.is_empty())
    {
        if let Some((start, end)) = part.split_once('-') {
            let start = start.parse::<usize>()?;
            let end = end.parse::<usize>()?;
            if start == 0 || start > end || end > maximum {
                bail!("selection range `{part}` is outside 1..={maximum}");
            }
            selected.extend(start..=end);
        } else {
            let index = part.parse::<usize>()?;
            if index == 0 || index > maximum {
                bail!("selection `{index}` is outside 1..={maximum}");
            }
            selected.insert(index);
        }
    }
    if selected.is_empty() {
        bail!("no candidates selected");
    }
    Ok(selected)
}

fn write_report(
    report: &ScanReport,
    format: OutputFormat,
    path: Option<&Path>,
    redact_paths: bool,
) -> Result<()> {
    let rendered = render_with_options(report, format, RenderOptions { redact_paths })?;
    if let Some(path) = path {
        if let Some(parent) = path.parent() {
            if !parent.as_os_str().is_empty() {
                fs::create_dir_all(parent)
                    .with_context(|| format!("failed to create {}", parent.display()))?;
            }
        }
        fs::write(path, rendered).with_context(|| format!("failed to write {}", path.display()))?;
    } else {
        print!("{rendered}");
    }
    Ok(())
}

fn run_manpage(path: Option<&Path>) -> Result<()> {
    let man = clap_mangen::Man::new(Cli::command());
    if let Some(path) = path {
        let mut file = fs::File::create(path)
            .with_context(|| format!("failed to create {}", path.display()))?;
        man.render(&mut file)?;
    } else {
        man.render(&mut io::stdout())?;
    }
    Ok(())
}

fn confirm(assume_yes: bool) -> Result<()> {
    if assume_yes {
        return Ok(());
    }
    if !io::stdin().is_terminal() {
        bail!("refusing non-interactive cleanup without --yes");
    }
    print!("Type DELETE to remove the listed artifacts: ");
    io::stdout().flush()?;
    let mut response = String::new();
    io::stdin().read_line(&mut response)?;
    if response.trim() != "DELETE" {
        bail!("cleanup cancelled");
    }
    Ok(())
}

fn command_exists(command: &str) -> bool {
    Command::new(command)
        .arg("--version")
        .output()
        .is_ok_and(|output| output.status.success())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_selection_should_accept_ranges() -> Result<()> {
        let selected = parse_selection("1,3-5", 5)?;

        assert_eq!(selected, HashSet::from([1, 3, 4, 5]));
        Ok(())
    }

    #[test]
    fn parse_selection_should_reject_out_of_range_value() {
        assert!(parse_selection("6", 5).is_err());
    }

    #[test]
    fn exact_selection_should_reject_stale_path() {
        let report = ScanReport {
            roots: vec![PathBuf::from("/tmp/project")],
            candidates: Vec::new(),
            review_candidates: Vec::new(),
            learning_observations: Vec::new(),
            warnings: Vec::new(),
            total_bytes: 0,
            review_total_bytes: 0,
            observed_total_bytes: 0,
            protect_git_tracked: true,
        };

        assert!(
            select_exact_candidates(report, &[PathBuf::from("/tmp/project/node_modules")]).is_err()
        );
    }
}