rclean-cli 0.2.0

Find and safely clean rebuildable developer artifacts across local workspaces
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
mod agent;
mod clean;
mod cli;
mod docker;
mod doctor;
mod error;
mod free;
#[cfg(feature = "graveyard")]
mod graveyard;
mod model;
mod output;
mod parse;
mod path_util;
mod plan;
mod rules;
mod scan;
mod stamp;
#[cfg(feature = "tui")]
mod tui;
mod user_rules;
mod watch;

use std::path::{Path, PathBuf};
use std::process::ExitCode;

use clap::Parser;
use cli::{Cli, Commands};
use error::RcleanError;
use model::Safety;
use tracing::error;
use tracing_subscriber::EnvFilter;

fn main() -> ExitCode {
    init_tracing(verbose_flag());
    match run() {
        Ok(code) => code,
        Err(err) => {
            error!("{err}");
            ExitCode::from(1)
        }
    }
}

fn verbose_flag() -> bool {
    std::env::args().any(|a| a == "-v" || a == "--verbose")
}

fn init_tracing(verbose: bool) {
    let default_filter = if verbose { "debug" } else { "warn" };
    let filter =
        EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(default_filter));
    let _ = tracing_subscriber::fmt()
        .with_env_filter(filter)
        .with_level(false)
        .with_target(false)
        .without_time()
        .with_writer(std::io::stderr)
        .try_init();
}

fn run() -> Result<ExitCode, RcleanError> {
    let cli = Cli::parse();

    let Some(command) = cli.command else {
        return run_default_interactive();
    };

    match command {
        Commands::Agent(args) => match args.command {
            cli::AgentCommands::Doctor(doctor_args) => {
                let report = agent::diagnose_agent(doctor_args.tool);
                if doctor_args.json {
                    let json = serde_json::to_string_pretty(&report)
                        .map_err(error::RcleanError::Output)?;
                    println!("{json}");
                } else {
                    output::print_agent_report(&report);
                }
                Ok(ExitCode::SUCCESS)
            }
            cli::AgentCommands::Optimize(optimize_args) => {
                let result = agent::optimize(agent::OptimizeOptions {
                    tool: optimize_args.tool,
                    disable_auto_update: optimize_args.disable_auto_update,
                    apply: optimize_args.yes,
                    codex_defaults_domain: optimize_args.defaults_domain,
                })?;
                if optimize_args.json {
                    let json = serde_json::to_string_pretty(&result)
                        .map_err(error::RcleanError::Output)?;
                    println!("{json}");
                } else {
                    output::print_agent_optimize_result(&result);
                }
                Ok(ExitCode::SUCCESS)
            }
        },
        Commands::Docker(args) => match args.command {
            cli::DockerCommands::Report(report_args) => {
                let timeout = parse::parse_timeout_duration(&report_args.timeout)?;
                let report = docker::report(docker::DockerReportOptions {
                    timeout,
                    ..docker::DockerReportOptions::default()
                });
                let available = report.status.is_available();
                if report_args.json {
                    let json = serde_json::to_string_pretty(&report)
                        .map_err(error::RcleanError::Output)?;
                    println!("{json}");
                } else {
                    docker::print_report(&report);
                }
                if available {
                    Ok(ExitCode::SUCCESS)
                } else {
                    Ok(ExitCode::from(3))
                }
            }
        },
        Commands::Scan(args) => {
            let options = args.to_scan_options()?;
            let report = scan::scan(&args.paths_or_current_dir(), &options)?;
            if let Some(plan_path) = &args.write_plan {
                plan::write_action_plan(&report, plan_path, args.include_caution, false, "trash")?;
                // User-facing success confirmation. Bypass the tracing
                // filter (default `warn` would hide info!) so the message
                // stays visible without --verbose, matching v0.1.0.
                write_stderr_line(format_args!("wrote action plan: {}", plan_path.display()))?;
            }
            if args.json {
                output::print_json(&report)?;
            } else {
                output::print_table(&report);
            }
            if report.summary.candidates == 0 {
                Ok(ExitCode::from(3))
            } else {
                Ok(ExitCode::SUCCESS)
            }
        }
        Commands::Clean(args) => run_clean(args),
        Commands::Free(args) => free::run(args),
        Commands::Tui(args) => {
            #[cfg(feature = "tui")]
            {
                tui::run_command(args)
            }
            #[cfg(not(feature = "tui"))]
            {
                let _ = args;
                Err(RcleanError::from(
                    "TUI support is not enabled in this build; rebuild with --features tui"
                        .to_string(),
                ))
            }
        }
        Commands::Watch(args) => watch::run(args),
        Commands::Stamp(args) => stamp::run(args),
        Commands::Explain(args) => {
            let explanation =
                scan::explain_path_with_activity_depth(&args.path, args.activity_depth)?;
            output::print_explanation(&explanation);
            match explanation.safety {
                // ReportOnly shares the "refuse to clean" semantic with
                // Blocked; surface the same exit code so callers don't
                // have to distinguish unless they want to.
                Safety::Blocked | Safety::ReportOnly => Ok(ExitCode::from(4)),
                Safety::Unknown => Ok(ExitCode::from(3)),
                Safety::Safe | Safety::Caution => Ok(ExitCode::SUCCESS),
            }
        }
        Commands::Rules => {
            output::print_rules();
            Ok(ExitCode::SUCCESS)
        }
        Commands::Completions(args) => {
            use clap::CommandFactory;
            clap_complete::generate(
                args.shell,
                &mut Cli::command(),
                "rclean",
                &mut std::io::stdout(),
            );
            Ok(ExitCode::SUCCESS)
        }
        Commands::Man => {
            use clap::CommandFactory;
            let man = clap_mangen::Man::new(Cli::command());
            let mut buffer = Vec::new();
            man.render(&mut buffer).map_err(|err| {
                RcleanError::Clean(crate::error::CleanError::Generic(format!(
                    "failed to render man page: {err}"
                )))
            })?;
            use std::io::Write;
            std::io::stdout().write_all(&buffer).map_err(|err| {
                RcleanError::Clean(crate::error::CleanError::Generic(format!(
                    "failed to write man page: {err}"
                )))
            })?;
            Ok(ExitCode::SUCCESS)
        }
        Commands::Doctor(args) => {
            let report = if args.docker {
                doctor::diagnose_with_options(doctor::DoctorOptions {
                    include_docker: true,
                })
            } else {
                doctor::diagnose()
            };
            output::print_doctor(&report);
            if report.applicable_count() == 0 {
                Ok(ExitCode::from(3))
            } else {
                Ok(ExitCode::SUCCESS)
            }
        }
        #[cfg(feature = "graveyard")]
        Commands::Restore(args) => {
            let yard = graveyard::Graveyard::open(graveyard::default_root());
            let record = yard.restore_by_id(&args.id, args.to.as_deref())?;
            eprintln!(
                "restored {} -> {}",
                record.id,
                record.original_path.display()
            );
            Ok(ExitCode::SUCCESS)
        }
        #[cfg(feature = "graveyard")]
        Commands::Graveyard(args) => match args.command {
            cli::GraveyardCommands::List(list_args) => {
                let yard = graveyard::Graveyard::open(graveyard::default_root());
                let records = yard.list()?;
                if list_args.json {
                    let json = serde_json::to_string_pretty(&records)
                        .map_err(error::RcleanError::Output)?;
                    println!("{json}");
                } else {
                    output::print_graveyard_list(&records);
                }
                if records.is_empty() {
                    Ok(ExitCode::from(3))
                } else {
                    Ok(ExitCode::SUCCESS)
                }
            }
            cli::GraveyardCommands::Gc(gc_args) => {
                let yard = graveyard::Graveyard::open(graveyard::default_root());
                let collected = yard.gc(gc_args.dry_run)?;
                if gc_args.dry_run {
                    eprintln!("dry-run: would remove {} expired grave(s)", collected.len());
                } else {
                    eprintln!("removed {} expired grave(s)", collected.len());
                }
                Ok(ExitCode::SUCCESS)
            }
        },
    }
}

/// The no-subcommand entry point (spec: docs/specs/v0.2-best-ux.md §3.2 B2):
/// scan the current directory, select interactively, and delete
/// recoverably. Without a human at a terminal this must never reach a
/// destructive path — agents and scripts use explicit subcommands.
fn run_default_interactive() -> Result<ExitCode, RcleanError> {
    use std::io::IsTerminal;

    if !(std::io::stdin().is_terminal() && std::io::stdout().is_terminal()) {
        use clap::CommandFactory;
        Cli::command().print_help().map_err(|err| {
            RcleanError::Clean(crate::error::CleanError::Generic(format!(
                "failed to print help: {err}"
            )))
        })?;
        return Ok(ExitCode::from(2));
    }

    let cli = Cli::parse_from(DEFAULT_INTERACTIVE_ARGV);
    match cli.command {
        Some(Commands::Clean(args)) => run_clean(args),
        _ => Err(RcleanError::from(
            "internal error: default interactive argv did not parse as a clean command".to_string(),
        )),
    }
}

/// Argv equivalent of the default interactive flow. Built from the
/// stable CLI surface instead of hand-constructing `CleanArgs` so every
/// clap default (depth, min-size, ...) stays in one place.
#[cfg(all(feature = "tui", feature = "graveyard"))]
const DEFAULT_INTERACTIVE_ARGV: [&str; 4] = ["rclean", "clean", "--tui", "--graveyard"];
#[cfg(all(feature = "tui", not(feature = "graveyard")))]
const DEFAULT_INTERACTIVE_ARGV: [&str; 3] = ["rclean", "clean", "--tui"];
#[cfg(all(not(feature = "tui"), feature = "graveyard"))]
const DEFAULT_INTERACTIVE_ARGV: [&str; 3] = ["rclean", "clean", "--graveyard"];
#[cfg(all(not(feature = "tui"), not(feature = "graveyard")))]
const DEFAULT_INTERACTIVE_ARGV: [&str; 2] = ["rclean", "clean"];

fn run_clean(mut args: cli::CleanArgs) -> Result<ExitCode, RcleanError> {
    let action_plan = args
        .plan
        .as_deref()
        .map(plan::read_action_plan)
        .transpose()?;
    let delete_mode = if let Some(action_plan) = &action_plan {
        enforce_action_plan_delete_mode(&mut args, &action_plan.delete_mode)?;
        action_plan.delete_mode.clone()
    } else {
        requested_delete_mode(&args).to_string()
    };
    if !args.allow_broad_root {
        if let Some(action_plan) = &action_plan {
            let plan_roots: Vec<std::path::PathBuf> = action_plan
                .roots
                .iter()
                .map(std::path::PathBuf::from)
                .collect();
            clean::check_broad_roots(&plan_roots)?;
        } else {
            clean::check_broad_roots(&clean_roots_for_broad_check(&args)?)?;
        }
    }
    let (selected, report) = if let Some(action_plan) = &action_plan {
        let selected = plan::selected_from_action_plan(action_plan)?;
        plan::revalidate_selected(action_plan, &selected)?;
        (selected, None)
    } else {
        let options = args.common.to_scan_options()?;
        let report = scan::scan(&args.common.paths_or_current_dir(), &options)?;
        if let Some(plan_path) = &args.common.write_plan {
            plan::write_action_plan(
                &report,
                plan_path,
                args.common.include_caution,
                args.permanent,
                &delete_mode,
            )?;
            // User-facing success confirmation. Bypass the tracing
            // filter (default `warn` would hide info!) so the message
            // stays visible without --verbose, matching v0.1.0.
            write_stderr_line(format_args!("wrote action plan: {}", plan_path.display()))?;
        }
        let selected = clean::select_candidates(&report, &args)?;
        (selected, Some(report))
    };

    if let Some(report) = &report {
        if args.common.json {
            output::print_json(report)?;
        } else {
            output::print_table(report);
        }
    }
    if !args.common.json {
        clean::print_plan(&selected, &delete_mode, args.dry_run);
    }

    if selected.is_empty() {
        return Ok(ExitCode::from(3));
    }

    if args.dry_run {
        return Ok(ExitCode::SUCCESS);
    }

    if let Some(audit_log) = args.audit_log.as_deref() {
        clean::validate_audit_log_path(audit_log, &selected)?;
    }
    clean::confirm_if_needed(&selected, &args)?;
    let mut audit_logger = args
        .audit_log
        .as_deref()
        .map(clean::DeleteAuditLogger::new)
        .transpose()?;
    #[cfg(feature = "graveyard")]
    let result = if args.graveyard {
        // SPEC §4.7.1: lazy create on first bury.
        let yard = graveyard::Graveyard::open(graveyard::default_root());
        clean::delete_selected_into_graveyard(&selected, &yard, audit_logger.as_mut())?
    } else {
        clean::delete_selected(&selected, args.permanent, audit_logger.as_mut())?
    };
    #[cfg(not(feature = "graveyard"))]
    let result = clean::delete_selected(&selected, args.permanent, audit_logger.as_mut())?;
    clean::print_clean_result(&result);
    if !args.common.json {
        clean::print_recovery_summary(&result, &delete_mode);
    }

    if result.failed.is_empty() {
        Ok(ExitCode::SUCCESS)
    } else {
        Ok(ExitCode::from(1))
    }
}

fn clean_roots_for_broad_check(args: &cli::CleanArgs) -> Result<Vec<PathBuf>, RcleanError> {
    let roots = args.common.paths_or_current_dir();
    if !args.common.tmp || std::env::var_os("RCLEAN_TMP_ROOTS").is_some() {
        return Ok(roots);
    }

    roots
        .into_iter()
        .filter_map(|root| match is_builtin_tmp_root(&root) {
            Ok(true) => None,
            Ok(false) => Some(Ok(root)),
            Err(err) => Some(Err(err)),
        })
        .collect()
}

fn is_builtin_tmp_root(path: &Path) -> Result<bool, RcleanError> {
    let canonical = path.canonicalize().map_err(|source| {
        RcleanError::Clean(crate::error::CleanError::Generic(format!(
            "failed to canonicalize temp root {}: {source}",
            path.display()
        )))
    })?;

    #[cfg(target_os = "macos")]
    let roots = [Path::new("/private/tmp"), Path::new("/tmp")];
    #[cfg(all(not(target_os = "macos"), not(target_os = "windows")))]
    let roots = [Path::new("/tmp")];
    #[cfg(target_os = "windows")]
    let roots: [&Path; 0] = [];

    Ok(roots.iter().any(|root| {
        root.canonicalize()
            .map(|builtin| builtin == canonical)
            .unwrap_or_else(|_| *root == canonical)
    }))
}

fn requested_delete_mode(args: &cli::CleanArgs) -> &'static str {
    if args.permanent {
        return "permanent";
    }
    #[cfg(feature = "graveyard")]
    if args.graveyard {
        return "graveyard";
    }
    "trash"
}

fn requested_explicit_delete_mode(args: &cli::CleanArgs) -> Option<&'static str> {
    if args.permanent {
        return Some("permanent");
    }
    #[cfg(feature = "graveyard")]
    if args.graveyard {
        return Some("graveyard");
    }
    None
}

fn enforce_action_plan_delete_mode(
    args: &mut cli::CleanArgs,
    plan_delete_mode: &str,
) -> Result<(), RcleanError> {
    if let Some(cli_delete_mode) = requested_explicit_delete_mode(args)
        && cli_delete_mode != plan_delete_mode
    {
        return Err(error::CleanError::Generic(format!(
            "CLI delete mode {cli_delete_mode:?} conflicts with action plan deleteMode \
             {plan_delete_mode:?}; replay the plan without a mode flag or regenerate it with \
             the intended delete mode"
        ))
        .into());
    }

    match plan_delete_mode {
        "trash" => {
            args.permanent = false;
            #[cfg(feature = "graveyard")]
            {
                args.graveyard = false;
            }
            Ok(())
        }
        "permanent" => {
            args.permanent = true;
            #[cfg(feature = "graveyard")]
            {
                args.graveyard = false;
            }
            Ok(())
        }
        "graveyard" => {
            #[cfg(feature = "graveyard")]
            {
                args.permanent = false;
                args.graveyard = true;
                Ok(())
            }
            #[cfg(not(feature = "graveyard"))]
            {
                Err(error::CleanError::Generic(
                    "action plan deleteMode \"graveyard\" requires a build with the graveyard \
                     feature; rebuild with default features or regenerate the plan with deleteMode \
                     \"trash\" or \"permanent\""
                        .to_string(),
                )
                .into())
            }
        }
        other => Err(error::CleanError::Generic(format!(
            "unsupported action plan deleteMode {other:?}; expected trash, graveyard, or permanent"
        ))
        .into()),
    }
}

fn write_stderr_line(args: std::fmt::Arguments<'_>) -> Result<(), RcleanError> {
    use std::io::Write;

    let mut stderr = std::io::stderr().lock();
    stderr.write_fmt(args)?;
    stderr.write_all(b"\n")?;
    Ok(())
}

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

    #[test]
    fn default_interactive_argv_parses_as_interactive_recoverable_clean() {
        let cli = Cli::parse_from(DEFAULT_INTERACTIVE_ARGV);
        let Some(Commands::Clean(args)) = cli.command else {
            panic!("default interactive argv must parse as a clean command");
        };
        assert!(!args.all);
        assert!(!args.dry_run);
        assert!(!args.permanent);
        assert!(args.plan.is_none());
        assert!(args.common.paths.is_empty());
        assert_eq!(args.tui, cfg!(feature = "tui"));
        #[cfg(feature = "graveyard")]
        assert!(args.graveyard);
    }
}