use cargo_cleanme::{
cli::{
self, CleanupRequest, CleanupScope, Cli, ConfigCommand, Invocation, OutputFormat,
ScanIntent,
},
config::{self, ConfigPathResolver},
domain::ScanScope,
error::AppError,
};
use std::collections::BTreeMap;
fn main() {
let cli = Cli::parse_normalized();
let invocation = cli.invocation();
let format = cli.format;
match run(cli) {
Ok(code) => std::process::exit(code),
Err(e) => {
if format == OutputFormat::Log {
eprintln!(
"{}",
cargo_cleanme::output::log::fatal(operation_name(&invocation), error_code(&e))
);
} else {
eprintln!("cargo-cleanme: {e}");
}
std::process::exit(2)
}
}
}
fn operation_name(invocation: &Invocation) -> &'static str {
match invocation {
Invocation::Cleanup(_) => "clean",
Invocation::Scan(_) => "scan",
Invocation::Config(_) => "config",
Invocation::Update { .. } => "update",
Invocation::UsageError(_) => "usage",
}
}
fn error_code(error: &AppError) -> &'static str {
match error {
AppError::Config(_) | AppError::InvalidRoot { .. } => "config",
AppError::Io(_) => "io",
AppError::Scan(_) => "scan",
AppError::Provenance(_) => "provenance",
AppError::Update(_) => "update",
}
}
#[derive(Clone, Copy, Debug)]
struct RunOptions {
no_progress: bool,
stats: bool,
format: OutputFormat,
verbose: bool,
}
fn run(cli: Cli) -> Result<i32, AppError> {
let path = ConfigPathResolver::new(cli.config.clone()).path()?;
let options = RunOptions {
no_progress: cli.no_progress,
stats: cli.stats,
format: cli.format,
verbose: cli.verbose,
};
match cli.invocation() {
Invocation::Update { dry_run } => run_update(dry_run, options.format),
Invocation::Config(command) => run_config(command, &path, options.format),
Invocation::Scan(intent) => run_scan(
intent,
&path,
options,
EmitReport::Yes,
cargo_cleanme::discovery_state::ReconciliationMode::IncompleteDiscard,
)
.map(|outcome| outcome.code),
Invocation::Cleanup(request) => run_cleanup(
request,
&path,
options,
&cargo_cleanme::cleanup::SystemCleanupRunner,
),
Invocation::UsageError(message) => Err(AppError::Config(message)),
}
}
fn update_nothing_to_do_log_line(current: &str, published: &str, dry_run: bool) -> String {
cargo_cleanme::output::log::update(
current,
published,
cargo_cleanme::update::host_target().unwrap_or("unknown"),
dry_run,
)
}
fn run_update(dry_run: bool, format: OutputFormat) -> Result<i32, AppError> {
let plan = match cargo_cleanme::update::update(dry_run) {
Ok(plan) => plan,
Err(cargo_cleanme::update::UpdateError::AlreadyCurrent { current, published }) => {
if format == OutputFormat::Json {
let target = cargo_cleanme::update::host_target().unwrap_or("unknown");
let asset = cargo_cleanme::update::asset_for_target(target).unwrap_or("");
let provenance = std::env::current_exe()
.ok()
.map(|exe| cargo_cleanme::update::classify_provenance(&exe).code())
.unwrap_or("unprovable_ownership");
let document = serde_json::json!({
"schema_version": 1,
"cargo_cleanme_version": env!("CARGO_PKG_VERSION"),
"operation": "update",
"dry_run": dry_run,
"result": {
"from_version": current,
"to_version": published,
"target": target,
"asset": asset,
"tag": format!("v{published}"),
"provenance": provenance,
"changed": false,
}
});
println!("{document}");
} else if format == OutputFormat::Log {
println!(
"{}",
update_nothing_to_do_log_line(¤t, &published, dry_run)
);
} else {
println!(
"cargo-cleanme: already at the latest stable version ({current}; published is {published})"
);
}
return Ok(0);
}
Err(cargo_cleanme::update::UpdateError::NewerThanPublished { current, published }) => {
if format == OutputFormat::Json {
let target = cargo_cleanme::update::host_target().unwrap_or("unknown");
let asset = cargo_cleanme::update::asset_for_target(target).unwrap_or("");
let provenance = std::env::current_exe()
.ok()
.map(|exe| cargo_cleanme::update::classify_provenance(&exe).code())
.unwrap_or("unprovable_ownership");
let document = serde_json::json!({
"schema_version": 1,
"cargo_cleanme_version": env!("CARGO_PKG_VERSION"),
"operation": "update",
"dry_run": dry_run,
"result": {
"from_version": current,
"to_version": published,
"target": target,
"asset": asset,
"tag": format!("v{published}"),
"provenance": provenance,
"changed": false,
}
});
println!("{document}");
} else if format == OutputFormat::Log {
println!(
"{}",
update_nothing_to_do_log_line(¤t, &published, dry_run)
);
} else {
println!(
"cargo-cleanme: this build ({current}) is newer than the published release ({published}); refusing to downgrade it"
);
}
return Ok(0);
}
Err(other) => return Err(other.into()),
};
if format == OutputFormat::Json {
print!(
"{}",
cargo_cleanme::output::update_json_stream(&plan, dry_run)
);
} else if format == OutputFormat::Log {
println!(
"{}",
cargo_cleanme::output::log::update(
&plan.from_version,
&plan.to_version,
&plan.target,
dry_run,
)
);
} else if dry_run {
println!(
"cargo-cleanme: {} -> {} available for {}",
plan.from_version, plan.to_version, plan.target
);
println!(" release: {}", plan.tag);
println!(" asset: {}", plan.asset);
println!(" install: not changed (--dry-run)");
} else {
println!("cargo-cleanme: updated to {}", plan.to_version);
}
Ok(0)
}
fn run_config(
command: ConfigCommand,
path: &std::path::Path,
format: OutputFormat,
) -> Result<i32, AppError> {
if format == OutputFormat::Json {
return Err(AppError::Config(
"config command does not support --format json; use human or log output".into(),
));
}
let log = format == OutputFormat::Log;
match command {
ConfigCommand::Path => {
if log {
println!("{}", cargo_cleanme::output::log::config("path"));
} else {
println!("{}", sanitize_path_text(&path.display().to_string()));
}
}
ConfigCommand::Show => {
let shown = config::show(&config::load_or_create(path)?)?;
if log {
println!("{}", cargo_cleanme::output::log::config("show"));
} else {
println!("{shown}");
}
}
ConfigCommand::Edit => {
config::ensure_exists(path)?;
let (program, args) =
cargo_cleanme::editor::resolve_editor().map_err(AppError::Config)?;
let status = std::process::Command::new(&program)
.args(args)
.arg(path)
.status()
.map_err(|e| {
AppError::Config(format!("cannot launch editor {}: {e}", program.display()))
})?;
if !status.success() {
if log {
eprintln!("{}", cargo_cleanme::output::log::fatal("config", "config"));
} else {
eprintln!(
"cargo-cleanme: editor exited with {status}; config was not reverted: {}",
sanitize_path_text(&path.display().to_string())
);
}
return Ok(1);
}
if !path.exists() {
return Err(AppError::Config(format!(
"editor removed the config file {}; refusing to treat that as an edit to defaults",
sanitize_path_text(&path.display().to_string())
)));
}
config::load(path).map_err(|e| {
AppError::Config(format!(
"edited config {} is invalid: {e}",
sanitize_path_text(&path.display().to_string())
))
})?;
if log {
println!("{}", cargo_cleanme::output::log::config("edit"));
} else {
println!("edited {}", sanitize_path_text(&path.display().to_string()));
}
}
}
Ok(0)
}
struct ResolvedCleanup {
roots: Vec<std::path::PathBuf>,
scope_label: &'static str,
state_generation: Option<u64>,
omitted_diagnostics: Vec<String>,
omitted: Vec<cargo_cleanme::policy::AutomaticOmission>,
blocked: Option<cargo_cleanme::cleanup::ScopeBlock>,
unproven_roots: Vec<cargo_cleanme::domain::UnprovenRoot>,
verification_elapsed: Option<std::time::Duration>,
automatic: bool,
}
fn check_interactive_preconditions(
request: &CleanupRequest,
options: &RunOptions,
) -> Result<(), AppError> {
if !request.interactive {
return Ok(());
}
if options.format != OutputFormat::Human {
return Err(AppError::Config(
"interactive selection requires human output; --format json and --format log are \
automation contracts and cannot carry a terminal session"
.into(),
));
}
if let Err(reason) = cargo_cleanme::interactive::ensure_interactive_terminal(
std::io::IsTerminal::is_terminal(&std::io::stdin()),
std::io::IsTerminal::is_terminal(&std::io::stdout()),
) {
return Err(AppError::Config(format!(
"interactive selection requires a terminal ({reason}); \
drop -i to clean without choosing interactively, or \
use `cargo cleanme scan --all` to inspect the same units read-only"
)));
}
let too_small = cargo_cleanme::interactive::terminal_geometry()
.ok()
.and_then(|(width, height)| {
cargo_cleanme::interactive::ensure_interactive_geometry(width, height).err()
});
if let Some(reason) = too_small {
return Err(AppError::Config(format!(
"interactive selection requires a usable terminal ({reason}); \
drop -i to clean without choosing interactively, or \
use `cargo cleanme scan --all` to inspect the same units read-only"
)));
}
Ok(())
}
fn run_cleanup(
request: CleanupRequest,
config_path: &std::path::Path,
options: RunOptions,
runner: &dyn cargo_cleanme::workspace::CargoRunner,
) -> Result<i32, AppError> {
check_interactive_preconditions(&request, &options)?;
let config = config::load_or_create(config_path)?;
let mode = request.mode;
let resolved = resolve_cleanup_roots(&request.scope, config_path, &config, options, runner)?;
let configured = &config.cleanup.policy;
let overrides = &request.overrides;
let policy = cargo_cleanme::cleanup::CleanupPolicy {
min_reclaimable_bytes: overrides
.min_reclaimable_bytes
.unwrap_or(configured.min_reclaimable_bytes),
min_inactive_seconds: overrides.older_than.or(configured.min_inactive_seconds),
include: if overrides.include.is_empty() {
configured.include.clone()
} else {
config::canonical_policy_patterns(&overrides.include)
},
exclude: if overrides.exclude.is_empty() {
configured.exclude.clone()
} else {
config::canonical_policy_patterns(&overrides.exclude)
},
};
let selector = overrides
.profile
.clone()
.map(cargo_cleanme::cleanup::CleanupSelector::Profile)
.or_else(|| {
overrides
.package
.clone()
.map(cargo_cleanme::cleanup::CleanupSelector::Package)
});
if !resolved.omitted_diagnostics.is_empty() && options.format != OutputFormat::Log {
for diagnostic in &resolved.omitted_diagnostics {
eprintln!("cargo-cleanme: {diagnostic}");
}
}
if !resolved.unproven_roots.is_empty() && options.format != OutputFormat::Log {
for unproven in &resolved.unproven_roots {
eprintln!(
"cargo-cleanme: learned root {} was skipped: {}",
sanitize_path_text(&unproven.root.display().to_string()),
unproven.detail
);
}
}
if let Some(block) = resolved.blocked.clone() {
let report = cargo_cleanme::cleanup::CleanReport {
results: Vec::new(),
diagnostics: resolved.omitted_diagnostics.len(),
failed: 0,
mode,
counters: Default::default(),
scope_blocked: Some(block),
unresolved_ownership: Vec::new(),
out_of_scope_unresolved: 0,
selected_roots: resolved.roots.clone(),
discovered_manifests: 0,
resolved_workspaces: 0,
units_considered: 0,
effective_policy: Some(policy),
selector,
};
emit_cleanup(&report, &resolved, &resolved.roots, options, "")?;
return Ok(1);
}
if resolved.roots.is_empty() {
let empty = cargo_cleanme::cleanup::CleanReport {
results: Vec::new(),
diagnostics: resolved.omitted_diagnostics.len(),
failed: 0,
mode,
counters: Default::default(),
scope_blocked: None,
unresolved_ownership: Vec::new(),
out_of_scope_unresolved: 0,
selected_roots: Vec::new(),
discovered_manifests: 0,
resolved_workspaces: 0,
units_considered: 0,
effective_policy: Some(policy),
selector,
};
emit_cleanup(
&empty,
&resolved,
&[],
options,
"no bounded cleanup roots are known; no cleanup commands were run",
)?;
return Ok(0);
}
let selection = match resolve_candidate_selection(&request, &resolved, &config, mode, options)?
{
SelectionOutcome::Chosen(selection) => selection,
SelectionOutcome::Cancelled => {
eprintln!(
"cargo-cleanme: interactive selection cancelled; no cleanup commands were run"
);
return Ok(0);
}
SelectionOutcome::NothingToClean => {
println!("Nothing to clean.");
return Ok(0);
}
};
let show = options.format == OutputFormat::Human
&& cargo_cleanme::progress::should_show_progress(options.no_progress);
let renderer = cargo_cleanme::progress::IndicatifRenderer::new(!show, options.verbose);
let wall_start = std::time::Instant::now();
let premise = cargo_cleanme::cleanup::AdmissionPremise {
omitted: resolved.omitted.clone(),
};
let cleanup = run_engine_guarded(
&resolved,
&config,
mode,
&renderer,
&policy,
selector.clone(),
Some(premise),
&selection,
);
renderer.finish_and_clear();
let report = cleanup?;
if options.format == OutputFormat::Human
&& options.verbose
&& let Some(generation) = resolved.state_generation
{
println!("state generation last_full_at={generation} (Unix seconds)");
}
emit_cleanup(&report, &resolved, &resolved.roots, options, "")?;
if options.stats {
let elapsed = wall_start.elapsed();
eprintln!(
"cleanup stats: mode={:?} {} {} {} {} verification={} elapsed={:.2}s",
mode,
report.counters.stats_line(),
report.counters.timings_line(),
report.counters.proof_stats_line(),
report.counters.proof_timings_line(),
match resolved.verification_elapsed {
Some(duration) => format!("{:.2}s", duration.as_secs_f64()),
None => "skipped".to_string(),
},
elapsed.as_secs_f64(),
);
}
Ok(cleanup_exit_code(&report, &resolved.unproven_roots))
}
#[derive(Debug)]
enum SelectionOutcome {
Chosen(cargo_cleanme::cleanup::CleanupSelection),
Cancelled,
NothingToClean,
}
fn resolve_candidate_selection(
request: &CleanupRequest,
resolved: &ResolvedCleanup,
config: &config::Config,
mode: cargo_cleanme::cleanup::CleanMode,
options: RunOptions,
) -> Result<SelectionOutcome, AppError> {
if !request.interactive {
let declared = request.selection.resolved()?;
return Ok(SelectionOutcome::Chosen(
declared.excluding(resolved.unproven_roots.clone()),
));
}
check_interactive_preconditions(request, &options)?;
let silent = cargo_cleanme::progress::IndicatifRenderer::new(true, options.verbose);
let anchor = request
.selection
.resolved()?
.excluding(resolved.unproven_roots.clone());
let listing = cargo_cleanme::cleanup::list_cleanup_candidates(
&resolved.roots,
config.scan.recency_seconds,
mode,
&cargo_cleanme::cleanup::SystemCleanupRunner,
&silent,
&anchor,
)?;
if let Some(block) = listing.scope_blocked {
let detail =
cargo_cleanme::cleanup::blocked_listing_detail(&block, &listing.unresolved_ownership);
return Err(AppError::Config(format!(
"cannot present an interactive selection: {detail}"
)));
}
interactive_outcome(cargo_cleanme::interactive::run_interactive(
listing.candidates,
))
}
fn interactive_outcome(
result: Result<cargo_cleanme::interactive::SessionResult, String>,
) -> Result<SelectionOutcome, AppError> {
match result {
Ok(cargo_cleanme::interactive::SessionResult::Selected(roots)) => Ok(
SelectionOutcome::Chosen(cargo_cleanme::cleanup::CleanupSelection::Roots(roots)),
),
Ok(cargo_cleanme::interactive::SessionResult::Cancelled) => Ok(SelectionOutcome::Cancelled),
Ok(cargo_cleanme::interactive::SessionResult::NothingToClean) => {
Ok(SelectionOutcome::NothingToClean)
}
Err(reason) => Err(AppError::Config(reason)),
}
}
#[allow(clippy::too_many_arguments)]
fn run_engine_guarded(
resolved: &ResolvedCleanup,
config: &config::Config,
mode: cargo_cleanme::cleanup::CleanMode,
renderer: &cargo_cleanme::progress::IndicatifRenderer,
policy: &cargo_cleanme::cleanup::CleanupPolicy,
selector: Option<cargo_cleanme::cleanup::CleanupSelector>,
premise: Option<cargo_cleanme::cleanup::AdmissionPremise>,
selection: &cargo_cleanme::cleanup::CleanupSelection,
) -> Result<cargo_cleanme::cleanup::CleanReport, AppError> {
let attempt = |roots: &[std::path::PathBuf],
premise: Option<cargo_cleanme::cleanup::AdmissionPremise>| {
cargo_cleanme::cleanup::clean_with_roots_policy_selector_guarded(
roots,
config.scan.recency_seconds,
&config.cleanup.allowed_output_roots,
mode,
&cargo_cleanme::cleanup::SystemCleanupRunner,
renderer,
policy,
selector.clone(),
premise,
selection,
)
};
match attempt(&resolved.roots, premise.clone()) {
Ok(report) => Ok(report),
Err(AppError::InvalidRoot { path, reason }) if resolved.automatic => {
let entries: cargo_cleanme::policy::CleanupCandidates = resolved
.roots
.iter()
.cloned()
.map(|r| (r, cargo_cleanme::policy::RootProvenance::Automatic))
.collect();
match cargo_cleanme::policy::classify_cleanup_roots(entries) {
Ok(reclassified)
if reclassified.blocked.is_empty()
&& reclassified
.omitted_paths()
.iter()
.any(|p| p == std::path::Path::new(&path)) =>
{
let omitted = reclassified.omitted.clone();
let omission_notices = reclassified.omission_diagnostics().len();
let admitted = collapse_roots(reclassified.admitted);
if admitted.is_empty() {
let diagnostics = omission_notices;
return Ok(cargo_cleanme::cleanup::CleanReport {
results: Vec::new(),
diagnostics,
failed: 0,
mode,
counters: Default::default(),
scope_blocked: None,
unresolved_ownership: Vec::new(),
out_of_scope_unresolved: 0,
selected_roots: Vec::new(),
discovered_manifests: 0,
resolved_workspaces: 0,
units_considered: 0,
effective_policy: Some(policy.clone()),
selector: selector.clone(),
});
}
let rebuilt = cargo_cleanme::cleanup::AdmissionPremise { omitted };
attempt(&admitted, Some(rebuilt))
}
_ => Ok(cargo_cleanme::cleanup::CleanReport {
results: Vec::new(),
diagnostics: resolved.omitted_diagnostics.len(),
failed: 0,
mode,
counters: Default::default(),
scope_blocked: Some(cargo_cleanme::cleanup::ScopeBlock::new(
cargo_cleanme::cleanup::ScopeBlockReason::IncompleteDiscovery,
format!(
"cleanup root {path} became invalid during admission ({reason}); no cleanup commands were run"
),
)),
unresolved_ownership: Vec::new(),
out_of_scope_unresolved: 0,
selected_roots: resolved.roots.clone(),
discovered_manifests: 0,
resolved_workspaces: 0,
units_considered: 0,
effective_policy: Some(policy.clone()),
selector: selector.clone(),
}),
}
}
Err(e) => Err(e),
}
}
fn zero_proven_block(
unproven: &[cargo_cleanme::domain::UnprovenRoot],
) -> Option<cargo_cleanme::cleanup::ScopeBlock> {
if unproven.is_empty() {
return None;
}
let mut paths: Vec<String> = unproven
.iter()
.map(|u| sanitize_path_text(&u.root.display().to_string()))
.collect();
paths.sort();
Some(cargo_cleanme::cleanup::ScopeBlock::new(
cargo_cleanme::cleanup::ScopeBlockReason::OwnershipUnproven,
format!(
"no learned root could be proven: {} root(s) had incomplete coverage ({}); \
no cleanup commands were run — run `cargo cleanme scan --all` for the read-only \
inventory, or `cargo cleanme ROOT` for a bounded scope",
paths.len(),
paths.join(", ")
),
))
}
fn cleanup_exit_code(
report: &cargo_cleanme::cleanup::CleanReport,
unproven: &[cargo_cleanme::domain::UnprovenRoot],
) -> i32 {
if report.failed > 0 || report.scope_blocked.is_some() || !unproven.is_empty() {
1
} else {
0
}
}
fn resolve_full_verdict(
verdict: cargo_cleanme::policy::FullCleanupVerdict,
verification_elapsed: Option<std::time::Duration>,
) -> Result<ResolvedCleanup, AppError> {
let unproven = verdict.unproven.clone();
let proven_count = verdict.proven.len();
let mut resolved = admit_automatic(
verdict.admitted_roots(),
Vec::new(),
"full",
verdict.generation,
)?;
resolved.unproven_roots = unproven.clone();
resolved.verification_elapsed = verification_elapsed;
if proven_count == 0 && !unproven.is_empty() {
resolved.blocked = zero_proven_block(&resolved.unproven_roots);
}
Ok(resolved)
}
fn verify_learned_root_coverage(
outcome: &ScanOutcome,
config: &config::Config,
options: RunOptions,
) -> Result<
Option<(
Vec<cargo_cleanme::domain::RootCoverage>,
std::time::Duration,
)>,
AppError,
> {
if outcome.code == 0 {
return Ok(None);
}
let Some(state) = outcome.full_state.as_ref() else {
return Ok(None);
};
let roots: Vec<std::path::PathBuf> = state
.learned_roots
.iter()
.map(|root| root.path.clone())
.collect();
if roots.is_empty() {
return Ok(None);
}
let policy = cargo_cleanme::policy::resolve(
cargo_cleanme::domain::ScanRequest {
cli_root: None,
full: true,
},
&config.scan,
)?;
let show = options.format == OutputFormat::Human
&& cargo_cleanme::progress::should_show_progress(options.no_progress);
let renderer = cargo_cleanme::progress::IndicatifRenderer::new(!show, options.verbose);
let observer: &dyn cargo_cleanme::progress::ProgressObserver = &renderer;
observer.phase(cargo_cleanme::progress::ScanPhase::Discovery);
let started = std::time::Instant::now();
let coverage = cargo_cleanme::discovery::verify_root_coverage(&roots, &policy, observer);
renderer.finish_and_clear();
let (coverage, _diagnostics) = coverage?;
Ok(Some((coverage, started.elapsed())))
}
fn resolve_cleanup_roots(
scope: &CleanupScope,
config_path: &std::path::Path,
config: &config::Config,
options: RunOptions,
runner: &dyn cargo_cleanme::workspace::CargoRunner,
) -> Result<ResolvedCleanup, AppError> {
match scope {
CleanupScope::Root(root) => {
let absolute = cli::absolutize_root(root)?;
let classified = cargo_cleanme::policy::classify_cleanup_roots(vec![(
absolute,
cargo_cleanme::policy::RootProvenance::Explicit,
)])?;
Ok(ResolvedCleanup {
roots: collapse_roots(classified.admitted),
scope_label: "explicit",
state_generation: None,
omitted_diagnostics: Vec::new(),
omitted: Vec::new(),
blocked: None,
unproven_roots: Vec::new(),
verification_elapsed: None,
automatic: false,
})
}
CleanupScope::Full => {
let outcome = run_scan(
ScanIntent::Full,
config_path,
options,
EmitReport::No,
cargo_cleanme::discovery_state::ReconciliationMode::IncompleteRetain,
)?;
if !outcome.publish_ok {
eprintln!(
"cargo-cleanme: discovery state was not saved; cleaning the reconciled in-memory generation only"
);
}
let coverage = verify_learned_root_coverage(&outcome, config, options)?;
let (coverage, verification_elapsed) = match coverage {
Some((coverage, elapsed)) => (Some(coverage), Some(elapsed)),
None => (None, None),
};
let verdict = cargo_cleanme::policy::full_cleanup_roots(
outcome.code,
outcome.full_state,
coverage.as_deref(),
)?;
resolve_full_verdict(verdict, verification_elapsed)
}
CleanupScope::Maintenance => {
let policy = cargo_cleanme::policy::resolve(
cargo_cleanme::domain::ScanRequest {
cli_root: None,
full: false,
},
&config.scan,
)?;
match policy.scope {
ScanScope::Explicit(root) => {
let classified = cargo_cleanme::policy::classify_cleanup_roots(vec![(
root,
cargo_cleanme::policy::RootProvenance::Explicit,
)])?;
Ok(ResolvedCleanup {
roots: collapse_roots(classified.admitted),
scope_label: "explicit",
state_generation: match cargo_cleanme::discovery_state::load_default() {
cargo_cleanme::discovery_state::StateLoad::Loaded(state) => {
state.last_full_at
}
_ => None,
},
omitted_diagnostics: Vec::new(),
omitted: Vec::new(),
blocked: None,
unproven_roots: Vec::new(),
verification_elapsed: None,
automatic: false,
})
}
ScanScope::ExplicitRoots(roots) => {
let entries = roots
.into_iter()
.map(|r| (r, cargo_cleanme::policy::RootProvenance::Explicit))
.collect();
let classified = cargo_cleanme::policy::classify_cleanup_roots(entries)?;
Ok(ResolvedCleanup {
roots: collapse_roots(classified.admitted),
scope_label: "explicit",
state_generation: None,
omitted_diagnostics: Vec::new(),
omitted: Vec::new(),
blocked: None,
unproven_roots: Vec::new(),
verification_elapsed: None,
automatic: false,
})
}
ScanScope::Routine(_) => {
let home = directories::BaseDirs::new().map(|b| b.home_dir().to_path_buf());
let Some(home) = home else {
return admit_automatic(Vec::new(), Vec::new(), "routine", None);
};
let (entries, warning) = cargo_cleanme::policy::routine_cleanup_candidates(
&home,
config.scan.learned_root_retention_days,
cargo_cleanme::discovery_state::load_default(),
);
if let Some(warning) = warning {
eprintln!("cargo-cleanme: {warning}; using seed/configured Routine roots");
}
let generation = match cargo_cleanme::discovery_state::load_default() {
cargo_cleanme::discovery_state::StateLoad::Loaded(state) => {
state.last_full_at
}
_ => None,
};
admit_automatic(
entries,
working_directory_entries(runner),
"routine",
generation,
)
}
ScanScope::Global(_) => Err(AppError::Config(
"maintenance scope resolved to a global scan, which is unreachable; \
refusing to treat it as an empty cleanup scope"
.into(),
)),
}
}
}
}
fn working_directory_scope_paths(
runner: &dyn cargo_cleanme::workspace::CargoRunner,
) -> Vec<std::path::PathBuf> {
let Ok(cwd) = std::env::current_dir() else {
return Vec::new();
};
cargo_cleanme::workspace::working_directory_scope_roots(&cwd, runner)
}
fn working_directory_entries(
runner: &dyn cargo_cleanme::workspace::CargoRunner,
) -> cargo_cleanme::policy::CleanupCandidates {
working_directory_scope_paths(runner)
.into_iter()
.map(|path| (path, cargo_cleanme::policy::RootProvenance::Operator))
.collect()
}
fn working_directory_is_unreached(routine_roots: &[std::path::PathBuf]) -> bool {
let Ok(cwd) = std::env::current_dir() else {
return false;
};
!routine_roots
.iter()
.any(|root| roots_are_related(root, &cwd))
}
fn roots_are_related(a: &std::path::Path, b: &std::path::Path) -> bool {
let canonical =
|path: &std::path::Path| std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
let (a, b) = (canonical(a), canonical(b));
a.starts_with(&b) || b.starts_with(&a)
}
fn canonicalize_cached(
cache: &mut std::collections::HashMap<std::path::PathBuf, std::path::PathBuf>,
path: &std::path::Path,
) -> std::path::PathBuf {
if let Some(cached) = cache.get(path) {
return cached.clone();
}
let canonical = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
cache.insert(path.to_path_buf(), canonical.clone());
canonical
}
fn sanitize_path_text(path: &str) -> String {
cargo_cleanme::report::escape_path_text(path)
.chars()
.take(200)
.collect()
}
fn admit_automatic(
entries: cargo_cleanme::policy::CleanupCandidates,
operator_entries: cargo_cleanme::policy::CleanupCandidates,
scope_label: &'static str,
state_generation: Option<u64>,
) -> Result<ResolvedCleanup, AppError> {
let classified = cargo_cleanme::policy::classify_cleanup_roots(entries)
.map_err(|e| AppError::Config(format!("automatic cleanup classification failed: {e}")))?;
let operator_classified = if working_directory_is_unreached(&classified.admitted) {
cargo_cleanme::policy::classify_cleanup_roots(operator_entries)
.map_err(|e| AppError::Config(format!("operator root classification failed: {e}")))?
} else {
cargo_cleanme::policy::ClassifiedRoots::default()
};
let mut classified = classified;
classified.admitted.extend(operator_classified.admitted);
classified.omitted.extend(operator_classified.omitted);
classified.blocked.extend(operator_classified.blocked);
let omitted = classified.omitted.clone();
let omitted_diagnostics = classified.omission_diagnostics();
let blocked = if classified.blocked.is_empty() {
None
} else {
let mut entries: Vec<(String, String)> = classified
.blocked
.iter()
.map(|b| {
(
sanitize_path_text(&b.path.display().to_string()),
b.reason.clone(),
)
})
.collect();
entries.sort();
let examples: Vec<String> = entries
.iter()
.take(3)
.map(|(path, reason)| format!("{path} ({reason})"))
.collect();
let sample = if examples.is_empty() {
String::new()
} else {
format!("; examples: {}", examples.join(", "))
};
Some(cargo_cleanme::cleanup::ScopeBlock::new(
cargo_cleanme::cleanup::ScopeBlockReason::IncompleteDiscovery,
format!(
"automatic cleanup scope is uncertain for {} root(s); no cleanup commands were run{sample}",
entries.len(),
),
))
};
Ok(ResolvedCleanup {
roots: collapse_roots(classified.admitted),
scope_label,
state_generation,
omitted_diagnostics,
omitted,
blocked,
unproven_roots: Vec::new(),
verification_elapsed: None,
automatic: true,
})
}
fn emit_cleanup(
report: &cargo_cleanme::cleanup::CleanReport,
resolved: &ResolvedCleanup,
roots: &[std::path::PathBuf],
options: RunOptions,
empty_note: &str,
) -> Result<(), AppError> {
if options.format == OutputFormat::Json {
let document = serde_json::to_string(&cargo_cleanme::output::cleanup(
report,
resolved.scope_label,
resolved.state_generation,
))
.map_err(|e| AppError::Config(format!("cannot serialize JSON report: {e}")))?;
println!("{document}");
} else if options.format == OutputFormat::Log {
println!(
"{}",
cargo_cleanme::output::log::cleanup(report, resolved.scope_label)
);
} else if !empty_note.is_empty() {
println!("{empty_note}");
} else if report_has_nothing_to_report(report) {
println!("Nothing to clean.");
} else {
let human = human_options(options, human_cleanup_roots(resolved));
if options.verbose {
println!(
"combined roots {}\n{}",
roots
.iter()
.map(|r| sanitize_path_text(&r.display().to_string()))
.collect::<Vec<_>>()
.join(", "),
report.render(&human)
);
} else {
println!("{}", report.render(&human));
}
}
Ok(())
}
fn human_options(
options: RunOptions,
roots: Vec<std::path::PathBuf>,
) -> cargo_cleanme::report::HumanOptions {
if options.verbose {
cargo_cleanme::report::HumanOptions::verbose()
} else {
cargo_cleanme::report::HumanOptions::quiet(roots)
}
}
fn human_cleanup_roots(resolved: &ResolvedCleanup) -> Vec<std::path::PathBuf> {
if resolved.scope_label == "full" {
Vec::new()
} else {
resolved.roots.clone()
}
}
fn human_scan_roots(scope: &cargo_cleanme::domain::ScanScope) -> Vec<std::path::PathBuf> {
match scope {
cargo_cleanme::domain::ScanScope::Explicit(root) => {
vec![absolutize_for_display(root)]
}
cargo_cleanme::domain::ScanScope::ExplicitRoots(roots) => {
roots.iter().map(|r| absolutize_for_display(r)).collect()
}
cargo_cleanme::domain::ScanScope::Routine(roots) => {
roots.iter().map(|r| absolutize_for_display(r)).collect()
}
cargo_cleanme::domain::ScanScope::Global(_) => Vec::new(),
}
}
fn absolutize_for_display(root: &std::path::Path) -> std::path::PathBuf {
let absolute = cargo_cleanme::cli::absolutize_root(root).unwrap_or_else(|_| root.to_path_buf());
std::fs::canonicalize(&absolute).unwrap_or(absolute)
}
fn report_has_nothing_to_report(report: &cargo_cleanme::cleanup::CleanReport) -> bool {
report.results.is_empty()
&& report.unresolved_ownership.is_empty()
&& report.out_of_scope_unresolved == 0
&& report.scope_blocked.is_none()
&& report.failed == 0
&& report.diagnostics == 0
}
fn collapse_roots(roots: Vec<std::path::PathBuf>) -> Vec<std::path::PathBuf> {
cargo_cleanme::traverse::collapse_outermost(roots)
.into_iter()
.map(|root| root.spelling)
.collect()
}
fn scope_label(scope: &ScanScope) -> &'static str {
match scope {
ScanScope::Global(_) => "full",
ScanScope::Explicit(_) | ScanScope::ExplicitRoots(_) => "explicit",
ScanScope::Routine(_) => "routine",
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum EmitReport {
Yes,
No,
}
struct ScanOutcome {
code: i32,
full_state: Option<cargo_cleanme::discovery_state::DiscoveryState>,
publish_ok: bool,
}
fn run_scan(
intent: ScanIntent,
config_path: &std::path::Path,
options: RunOptions,
emit_report: EmitReport,
reconciliation_mode: cargo_cleanme::discovery_state::ReconciliationMode,
) -> Result<ScanOutcome, AppError> {
use cargo_cleanme::{domain, progress};
use std::time::SystemTime;
let scan_start = SystemTime::now();
let wall_start = std::time::Instant::now();
let c = config::load_or_create(config_path)?;
let is_maintenance = matches!(intent, ScanIntent::Maintenance);
let (root, full) = match intent {
ScanIntent::Full => (None, true),
ScanIntent::Explicit(root) => (Some(cli::absolutize_root(&root)?), false),
ScanIntent::Maintenance => (None, false),
};
let mut policy = cargo_cleanme::policy::resolve(
domain::ScanRequest {
cli_root: root,
full,
},
&c.scan,
)?;
if is_maintenance && let domain::ScanScope::Routine(roots) = &mut policy.scope {
let routine = roots.clone();
if working_directory_is_unreached(&routine) {
roots.extend(working_directory_scope_paths(
&cargo_cleanme::cleanup::SystemCleanupRunner,
));
}
}
let recency = policy.recency;
let show = options.format == OutputFormat::Human
&& progress::should_show_progress(options.no_progress);
let renderer = progress::IndicatifRenderer::new(!show, options.verbose);
let observer: &dyn progress::ProgressObserver = &renderer;
observer.phase(progress::ScanPhase::Discovery);
let discovery_start = std::time::Instant::now();
let discovered = match cargo_cleanme::discovery::discover_manifests_with_attribution(
&policy,
observer,
options.stats,
) {
Ok(discovered) => discovered,
Err(error) => {
renderer.finish_and_clear();
return Err(error);
}
};
observer.discovery_issues(discovered.diagnostics.len() as u64);
let discovery_elapsed = discovery_start.elapsed();
let full_traversal_complete = discovered.coverage_complete
&& !discovered.diagnostics.iter().any(|d| {
d.category == domain::DiagnosticCategory::PlatformRoot
&& d.severity == domain::DiagnosticSeverity::Error
});
let mut counters = discovered.counters.clone();
counters.discovery_nanos = counters
.discovery_nanos
.saturating_add(cargo_cleanme::domain::elapsed_nanos(discovery_elapsed));
let uncertainty: Vec<std::path::PathBuf> = discovered
.diagnostics
.iter()
.filter(|d| {
matches!(
d.category,
domain::DiagnosticCategory::PermissionDenied
| domain::DiagnosticCategory::Metadata
| domain::DiagnosticCategory::Vanished
)
})
.filter_map(|d| d.path.clone())
.collect();
let mut diagnostics: Vec<domain::ScanDiagnostic> = discovered.diagnostics;
let manifests = discovered.manifests;
counters.manifests_found = manifests.len() as u64;
observer.phase(progress::ScanPhase::Resolution);
let resolution_start = std::time::Instant::now();
let runner = cargo_cleanme::workspace::SystemCargoRunner;
let workspaces = cargo_cleanme::workspace::resolve_workspaces(
&manifests,
&runner,
&mut counters,
&mut diagnostics,
observer,
);
let _resolution_elapsed = resolution_start.elapsed();
use cargo_cleanme::discovery_state::StateLoad;
let loaded_state = cargo_cleanme::discovery_state::load_default();
let mut full_state: Option<cargo_cleanme::discovery_state::DiscoveryState> = None;
let mut publish_ok = true;
let mut pending_notices: Vec<String> = Vec::new();
if full {
let selected = cargo_cleanme::discovery_state::full_reconciliation_prior(&loaded_state);
if let Some((prior, replacing_invalid)) = selected {
let now = cargo_cleanme::discovery_state::now_seconds();
let mut resolved_by_manifest = std::collections::HashMap::new();
let mut canonical_cache = std::collections::HashMap::new();
for ws in &workspaces {
for member in &ws.members {
resolved_by_manifest.insert(
canonicalize_cached(&mut canonical_cache, &member.manifest_path),
ws.root.clone(),
);
}
}
let observations: Vec<_> = manifests
.iter()
.map(|manifest| {
let key = canonicalize_cached(&mut canonical_cache, manifest);
cargo_cleanme::discovery_state::ProjectObservation {
manifest: key.clone(),
workspace: resolved_by_manifest.get(&key).cloned(),
}
})
.collect();
let complete = full_traversal_complete;
let mode = if complete {
cargo_cleanme::discovery_state::ReconciliationMode::Complete
} else {
reconciliation_mode
};
match cargo_cleanme::discovery_state::reconcile_full(
&prior,
&observations,
&uncertainty,
mode,
now,
c.scan.learned_root_retention_days,
directories::BaseDirs::new()
.map(|b| b.home_dir().to_path_buf())
.as_deref(),
) {
cargo_cleanme::discovery_state::Reconciliation::Publish(next) => {
full_state = Some(next.clone());
if mode == cargo_cleanme::discovery_state::ReconciliationMode::Complete {
match cargo_cleanme::discovery_state::publish(&next) {
Ok(()) => {
if replacing_invalid {
pending_notices.push(
"replaced unusable discovery state after successful Full reconciliation"
.into(),
);
}
}
Err(error) => {
publish_ok = false;
pending_notices
.push(format!("discovery state was not saved: {error}"));
}
}
} else {
pending_notices.push(
"discovery state was not updated: the Full traversal was incomplete; \
the learned roots were retained and verified in memory"
.into(),
);
}
}
cargo_cleanme::discovery_state::Reconciliation::NoPublication(reason) => {
publish_ok = false;
pending_notices.push(format!("discovery state was not reconciled: {reason}"));
}
}
} else {
publish_ok = false;
let message = loaded_state
.diagnostic()
.unwrap_or_else(|| "discovery state cannot be safely read".into());
pending_notices.push(format!("{message}; Full state reconciliation was skipped"));
}
} else if let StateLoad::Loaded(prior) = loaded_state {
let now = cargo_cleanme::discovery_state::now_seconds();
let observed: Vec<_> = workspaces.iter().map(|w| w.root.clone()).collect();
let mut next = prior;
for project in &observed {
for root in &mut next.learned_roots {
if project.starts_with(&root.path) {
root.last_project_seen_at = root.last_project_seen_at.max(now);
}
}
}
if !observed.is_empty()
&& let Err(error) = cargo_cleanme::discovery_state::publish(&next)
{
pending_notices.push(format!("discovery state was not saved: {error}"));
}
}
let groups = cargo_cleanme::workspace::build_groups(&workspaces);
observer.phase(progress::ScanPhase::Analysis);
observer.units_total(progress::ScanPhase::Analysis, groups.len() as u64);
let clock_cutoff = match scan_start.checked_sub(recency) {
Some(cutoff) => cutoff,
None => {
renderer.finish_and_clear();
return Err(AppError::Config(
"recency window exceeds system time range".into(),
));
}
};
let physical = cargo_cleanme::workspace::analyze_groups(
&workspaces,
groups,
scan_start,
clock_cutoff,
recency,
&mut counters,
&mut diagnostics,
observer,
);
let full_incomplete = full && !full_traversal_complete;
let mut report = domain::ScanReport {
groups: physical
.into_iter()
.map(|g| domain::EligibleOutputGroup {
display_path: g.display_path,
workspace_roots: g.owners.iter().map(|w| w.0.clone()).collect(),
physical_paths: g.physical_paths,
bytes: g.bytes,
metric: g.metric,
newest_mtime: g.newest_mtime,
artifact_entries: g.artifact_entries,
ownership: g.ownership,
})
.collect(),
diagnostics,
discovered: manifests.len() as u64,
visited_entries: discovered.visited_entries,
counters,
};
observer.phase(progress::ScanPhase::Reporting);
renderer.finish_and_clear();
for notice in &pending_notices {
eprintln!("cargo-cleanme: {notice}");
}
if emit_report == EmitReport::No {
} else if options.format == OutputFormat::Json {
println!(
"{}",
serde_json::to_string(&cargo_cleanme::output::scan(
&report,
scope_label(&policy.scope),
))
.map_err(|e| AppError::Config(format!("cannot serialize JSON report: {e}")))?
);
} else if options.format == OutputFormat::Log {
println!(
"{}",
cargo_cleanme::output::log::scan(&report, scope_label(&policy.scope), full_incomplete)
);
} else {
let human = human_options(options, human_scan_roots(&policy.scope));
println!("{}", cargo_cleanme::report::render(&mut report, &human));
}
if !report.diagnostics.is_empty() && options.format != OutputFormat::Log {
eprintln!(
"{} filesystem diagnostics; rerun with a bounded root if needed",
report.diagnostics.len()
);
if options.verbose {
let mut cargo_groups: BTreeMap<String, (usize, Vec<String>)> = BTreeMap::new();
let mut other_diagnostics = Vec::new();
for diagnostic in &report.diagnostics {
let (stage, reason) = if let Some(reason) = diagnostic
.message
.strip_prefix("cargo locate-project failed:")
{
("locate", reason)
} else if let Some(reason) =
diagnostic.message.strip_prefix("cargo metadata failed:")
{
("metadata", reason)
} else {
other_diagnostics.push(diagnostic);
continue;
};
let cause = reason.split(" | ").skip(1).collect::<Vec<_>>().join(" | ");
let reason_key = if cause.is_empty() {
reason.trim()
} else {
&cause
};
let group = cargo_groups
.entry(format!("{stage}: {reason_key}"))
.or_insert_with(|| (0, Vec::new()));
group.0 += 1;
if group.1.len() < 3
&& let Some(path) = &diagnostic.path
{
group
.1
.push(sanitize_path_text(&path.display().to_string()));
}
}
for (cause, (count, paths)) in cargo_groups.iter().take(8) {
if let Some((stage, reason)) = cause.split_once(": ") {
eprintln!(" {count} Cargo {stage} failure(s): {reason}");
} else {
eprintln!(" {count} Cargo resolution failure(s): {cause}");
}
if !paths.is_empty() {
eprintln!(" examples: {}", paths.join(", "));
}
}
let hidden_cargo_groups = cargo_groups.len().saturating_sub(8);
if hidden_cargo_groups > 0 {
eprintln!(" … {hidden_cargo_groups} additional Cargo failure cause(s)");
}
for diagnostic in other_diagnostics.iter().take(10) {
eprintln!(
" {}: {}{}",
diagnostic.severity.as_str(),
cargo_cleanme::report::escape_path_text(&diagnostic.message),
diagnostic
.path
.as_ref()
.map(|p| format!(" ({})", sanitize_path_text(&p.display().to_string())))
.unwrap_or_default()
);
}
if other_diagnostics.len() > 10 {
eprintln!(
" … {} more non-Cargo diagnostic(s)",
other_diagnostics.len() - 10
);
}
}
}
if options.stats {
let elapsed = wall_start.elapsed();
eprintln!(
"scan stats: {} {} elapsed={:.2}s",
report.counters.stats_line(),
report.counters.timings_line(),
elapsed.as_secs_f64(),
);
if !discovered.top_level_entries.is_empty() {
let attribution = discovered
.top_level_entries
.iter()
.map(|(path, count)| format!("{:?}={count}", path))
.collect::<Vec<_>>()
.join(" ");
eprintln!("scan top-level entries: {attribution}");
}
}
if full_incomplete {
return Ok(ScanOutcome {
code: 1,
full_state,
publish_ok,
});
}
Ok(ScanOutcome {
code: 0,
full_state,
publish_ok,
})
}
#[cfg(test)]
mod tests {
use super::*;
use cargo_cleanme::cleanup::{
CleanMode, CleanOutcome, CleanReport, CleanResult, CleanupReasonCode, ScopeBlock,
ScopeBlockReason,
};
use cargo_cleanme::domain::{OutputOwnershipClass, ScanCounters};
fn empty_report() -> CleanReport {
CleanReport {
results: Vec::new(),
diagnostics: 0,
failed: 0,
mode: CleanMode::Execute,
counters: ScanCounters::default(),
scope_blocked: None,
unresolved_ownership: Vec::new(),
out_of_scope_unresolved: 0,
selected_roots: Vec::new(),
discovered_manifests: 0,
resolved_workspaces: 0,
units_considered: 0,
effective_policy: None,
selector: None,
}
}
#[test]
fn a_complete_platform_walk_needs_no_verification_pass() {
let options = RunOptions {
no_progress: true,
stats: false,
format: OutputFormat::Human,
verbose: false,
};
let state = cargo_cleanme::discovery_state::DiscoveryState {
schema_version: cargo_cleanme::discovery_state::CURRENT_SCHEMA,
last_full_at: Some(1),
learned_roots: vec![cargo_cleanme::discovery_state::LearnedRoot {
path: std::path::PathBuf::from("/work/a"),
last_project_seen_at: 1,
}],
..Default::default()
};
let complete = ScanOutcome {
code: 0,
full_state: Some(state.clone()),
publish_ok: true,
};
let coverage = verify_learned_root_coverage(&complete, &config::Config::default(), options)
.expect("the pass does not fail");
assert!(
coverage.is_none(),
"a completed platform walk needs no second walk"
);
let incomplete = ScanOutcome {
code: 1,
full_state: Some(state),
publish_ok: true,
};
let coverage =
verify_learned_root_coverage(&incomplete, &config::Config::default(), options)
.expect("the pass does not fail");
assert!(
coverage.is_some(),
"an incomplete platform walk must be measured per root"
);
}
#[test]
fn a_full_cleanup_that_proved_nothing_blocks_instead_of_exiting_zero() {
let unproven = vec![cargo_cleanme::domain::UnprovenRoot {
root: std::path::PathBuf::from("/work/unproven"),
detail: "2 permission-denied region(s) under it".into(),
}];
let block = zero_proven_block(&unproven).expect("an unproven root blocks");
assert_eq!(block.reason, ScopeBlockReason::OwnershipUnproven);
assert!(
block.message.contains("/work/unproven"),
"the block names the root: {}",
block.message
);
assert!(
block.message.contains("no cleanup commands were run"),
"the block says nothing ran: {}",
block.message
);
assert!(
zero_proven_block(&[]).is_none(),
"an empty scope is not a block"
);
}
#[test]
fn an_unproven_root_is_admitted_as_a_root_and_excluded_only_as_a_candidate() {
let dir = maintainable_fixture("cleanme-gate-");
let proven_root = dir.path().join("proven");
let unproven_root = dir.path().join("unproven");
std::fs::create_dir_all(&proven_root).expect("the proven root");
std::fs::create_dir_all(&unproven_root).expect("the unproven root");
let verdict = cargo_cleanme::policy::FullCleanupVerdict {
proven: vec![(
proven_root.clone(),
cargo_cleanme::policy::RootProvenance::Automatic,
)],
unproven: vec![cargo_cleanme::domain::UnprovenRoot {
root: unproven_root.clone(),
detail: "1 permission-denied region(s) under it".into(),
}],
generation: Some(7),
};
let resolved =
resolve_full_verdict(verdict, None).expect("the verdict resolves into a scope");
let canonical =
|p: &std::path::Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
assert!(
resolved.roots.contains(&canonical(&unproven_root)),
"the unproven root is a root: the discovery universe must not be narrowed; \
roots: {:?}, omitted: {:?}, blocked: {:?}",
resolved.roots,
resolved.omitted,
resolved.blocked
);
assert!(
resolved.roots.contains(&canonical(&proven_root)),
"the proven root is a root too: {:?}",
resolved.roots
);
assert_eq!(
resolved.unproven_roots.len(),
1,
"the unproven root is disclosed: {:?}",
resolved.unproven_roots
);
assert!(
resolved.blocked.is_none(),
"one proven root is enough to run the scope: {:?}",
resolved.blocked
);
let selection = cargo_cleanme::cleanup::CleanupSelection::All
.excluding(resolved.unproven_roots.clone());
assert!(
!selection.admits(&canonical(&unproven_root)),
"the unproven root's units are not candidates"
);
assert!(
selection.admits(&canonical(&proven_root)),
"the proven root's units stay candidates"
);
}
#[test]
fn a_gate_that_proved_nothing_blocks_even_though_the_roots_are_admitted() {
let dir = maintainable_fixture("cleanme-gate-empty-");
let unproven_root = dir.path().join("unproven");
std::fs::create_dir_all(&unproven_root).expect("the unproven root");
let verdict = cargo_cleanme::policy::FullCleanupVerdict {
proven: Vec::new(),
unproven: vec![cargo_cleanme::domain::UnprovenRoot {
root: unproven_root,
detail: "1 permission-denied region(s) under it".into(),
}],
generation: Some(7),
};
let resolved =
resolve_full_verdict(verdict, None).expect("the verdict resolves into a scope");
let block = resolved
.blocked
.expect("a gate that proved nothing blocks the scope");
assert_eq!(block.reason, ScopeBlockReason::OwnershipUnproven);
assert!(
block.message.contains("no cleanup commands were run"),
"the block says nothing ran: {}",
block.message
);
}
fn maintainable_fixture(prefix: &str) -> tempfile::TempDir {
let base = std::env::current_dir()
.expect("the crate root")
.join("target");
std::fs::create_dir_all(&base).expect("the build directory");
tempfile::Builder::new()
.prefix(prefix)
.tempdir_in(&base)
.expect("the fixture directory")
}
#[test]
fn an_unproven_learned_root_makes_the_exit_code_non_zero() {
let unproven = vec![cargo_cleanme::domain::UnprovenRoot {
root: std::path::PathBuf::from("/work/unproven"),
detail: "1 permission-denied region(s) under it".into(),
}];
assert_eq!(
cleanup_exit_code(&empty_report(), &unproven),
1,
"a skipped root means the boundary was not fully cleaned"
);
assert_eq!(
cleanup_exit_code(&empty_report(), &[]),
0,
"a clean run stays zero"
);
let mut failed = empty_report();
failed.failed = 1;
assert_eq!(cleanup_exit_code(&failed, &[]), 1, "a failure is one");
let mut blocked = empty_report();
blocked.scope_blocked = Some(ScopeBlock::new(
ScopeBlockReason::OwnershipUnproven,
"blocked".into(),
));
assert_eq!(cleanup_exit_code(&blocked, &[]), 1, "a block is one");
}
#[test]
fn the_three_interactive_endings_map_to_three_distinct_outcomes() {
let chosen = interactive_outcome(Ok(cargo_cleanme::interactive::SessionResult::Selected(
vec![std::path::PathBuf::from("/tmp/project")],
)));
assert!(
matches!(chosen, Ok(SelectionOutcome::Chosen(_))),
"a chosen selection is a run to make: {chosen:?}"
);
let cancelled =
interactive_outcome(Ok(cargo_cleanme::interactive::SessionResult::Cancelled));
assert!(
matches!(cancelled, Ok(SelectionOutcome::Cancelled)),
"a deliberate quit is not a failure: {cancelled:?}"
);
let nothing = interactive_outcome(Ok(
cargo_cleanme::interactive::SessionResult::NothingToClean,
));
assert!(
matches!(nothing, Ok(SelectionOutcome::NothingToClean)),
"an empty surface is a plain negative result, not a usage error: {nothing:?}"
);
}
#[test]
fn a_surface_that_cannot_be_presented_is_still_a_usage_error() {
let refused = interactive_outcome(Err("interactive selection requires a terminal".into()));
assert!(
matches!(refused, Err(AppError::Config(_))),
"a refusal to present the surface is a usage error: {refused:?}"
);
}
struct CountingRunner {
calls: std::sync::Mutex<Vec<Vec<std::ffi::OsString>>>,
}
impl CountingRunner {
fn new() -> Self {
Self {
calls: std::sync::Mutex::new(Vec::new()),
}
}
fn count(&self) -> usize {
self.calls.lock().unwrap().len()
}
}
impl cargo_cleanme::workspace::CargoRunner for CountingRunner {
fn run(
&self,
_cwd: &std::path::Path,
args: &[std::ffi::OsString],
) -> std::io::Result<cargo_cleanme::workspace::ProcessOutput> {
self.calls.lock().unwrap().push(args.to_vec());
Err(std::io::Error::other("the runner must not be reached"))
}
}
#[test]
fn the_update_log_line_says_the_mode_the_run_was_asked_for() {
let execute = update_nothing_to_do_log_line("0.2.10", "0.2.10", false);
assert!(
execute.contains("mode=execute"),
"an execute-mode run must say so: {execute}"
);
let simulate = update_nothing_to_do_log_line("0.2.10", "0.2.10", true);
assert!(
simulate.contains("mode=simulate"),
"a dry run must say so: {simulate}"
);
}
#[test]
fn a_static_usage_error_is_refused_before_the_scope_spawns_cargo() {
let d = tempfile::tempdir().unwrap();
let request = CleanupRequest {
scope: CleanupScope::Full,
mode: CleanMode::Execute,
overrides: cargo_cleanme::cli::CleanupOverrides::default(),
selection: cargo_cleanme::cleanup::CleanupSelection::All,
interactive: true,
};
let options = RunOptions {
no_progress: true,
stats: false,
format: OutputFormat::Json,
verbose: false,
};
let runner = CountingRunner::new();
let refused = run_cleanup(request, &d.path().join("config.toml"), options, &runner);
assert!(
matches!(refused, Err(AppError::Config(_))),
"a machine format with -i is a usage error: {refused:?}"
);
assert_eq!(
runner.count(),
0,
"a refused run must not spawn Cargo at all"
);
}
#[cfg(unix)]
#[test]
fn the_scan_surface_names_its_paths_relative_under_a_symlinked_root() {
use std::os::unix::fs::symlink;
let d = tempfile::tempdir().unwrap();
let real = d.path().join("real/app");
std::fs::create_dir_all(real.join("target")).unwrap();
let link = d.path().join("lnk/app");
std::fs::create_dir_all(link.parent().unwrap()).unwrap();
symlink(&real, &link).unwrap();
let base = absolutize_for_display(&link);
assert_eq!(
base,
std::fs::canonicalize(&real).unwrap(),
"the relative-path base must be canonical, like the cleanup surface's"
);
let display = std::fs::canonicalize(real.join("target")).unwrap();
let options = cargo_cleanme::report::HumanOptions::quiet(vec![base]);
assert_eq!(
options.relativized(&display),
std::path::PathBuf::from("app/target"),
"the scan surface must name the path relative to the scope root"
);
}
#[test]
fn a_report_with_nothing_in_it_is_the_empty_case() {
assert!(
report_has_nothing_to_report(&empty_report()),
"a run that cleaned nothing and has nothing to report has one true sentence"
);
}
#[test]
fn a_report_that_says_anything_is_not_the_empty_case() {
let mut with_row = empty_report();
with_row.results.push(CleanResult {
display_path: std::path::PathBuf::from("/tmp/project"),
workspace_roots: Vec::new(),
output_roots: Vec::new(),
ownership: OutputOwnershipClass::PrivateBounded,
outcome: CleanOutcome::Skipped,
policy_disposition: None,
reason_code: CleanupReasonCode::SkippedOutsideSelection,
before_bytes: None,
after_bytes: None,
observed_decrease: None,
detail: String::new(),
});
assert!(
!report_has_nothing_to_report(&with_row),
"a skipped unit the operator must see is not the empty case"
);
let mut with_diagnostic = empty_report();
with_diagnostic.diagnostics = 1;
assert!(
!report_has_nothing_to_report(&with_diagnostic),
"a discovery diagnostic the operator must see is not the empty case"
);
let mut with_out_of_scope = empty_report();
with_out_of_scope.out_of_scope_unresolved = 1;
assert!(
!report_has_nothing_to_report(&with_out_of_scope),
"an out-of-scope unprovable is not the empty case"
);
let mut with_failure = empty_report();
with_failure.failed = 1;
assert!(
!report_has_nothing_to_report(&with_failure),
"a failure is not the empty case"
);
let mut blocked = empty_report();
blocked.scope_blocked = Some(ScopeBlock::new(
ScopeBlockReason::IncompleteDiscovery,
"the scope is uncertain".to_string(),
));
assert!(
!report_has_nothing_to_report(&blocked),
"a blocked scope is not the empty case"
);
}
}