use cargo_cleanme::{
cli::{
self, CleanupRequest, CleanupScope, Cli, ConfigCommand, Invocation, OutputFormat,
ScanIntent,
},
config::{self, ConfigPathResolver},
domain::ScanScope,
error::AppError,
};
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",
}
}
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,
}
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,
};
match cli.invocation() {
Invocation::Update { dry_run } => run_update(dry_run, options.format),
Invocation::Config(command) => run_config(command, &path),
Invocation::Scan(intent) => run_scan(intent, &path, options, EmitReport::Yes),
Invocation::Cleanup(request) => run_cleanup(request, &path, options),
}
}
fn run_update(dry_run: bool, format: OutputFormat) -> Result<i32, AppError> {
let plan = cargo_cleanme::update::update(dry_run)?;
if format == OutputFormat::Json {
print!(
"{}",
cargo_cleanme::output::update_json_stream(&plan, 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) -> Result<i32, AppError> {
match command {
ConfigCommand::Path => println!("{}", path.display()),
ConfigCommand::Show => {
println!("{}", config::show(&config::load_or_create(path)?)?)
}
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() {
eprintln!(
"cargo-cleanme: editor exited with {status}; config was not reverted: {}",
path.display()
);
return Ok(status.code().unwrap_or(1));
}
if !path.exists() {
return Err(AppError::Config(format!(
"editor removed the config file {}; refusing to treat that as an edit to defaults",
path.display()
)));
}
config::load(path).map_err(|e| {
AppError::Config(format!("edited config {} is invalid: {e}", path.display()))
})?;
println!("edited {}", path.display());
}
}
Ok(0)
}
struct ResolvedCleanup {
roots: Vec<std::path::PathBuf>,
scope_label: &'static str,
state_generation: Option<u64>,
}
fn run_cleanup(
request: CleanupRequest,
config_path: &std::path::Path,
options: RunOptions,
) -> Result<i32, AppError> {
let config = config::load_or_create(config_path)?;
let mode = request.mode;
let mut resolved = resolve_cleanup_roots(&request.scope, config_path, &config, options)?;
resolved.roots = collapse_roots(resolved.roots);
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 {
overrides.include.clone()
},
exclude: if overrides.exclude.is_empty() {
configured.exclude.clone()
} else {
overrides.exclude.clone()
},
};
let selector = overrides
.profile
.clone()
.map(cargo_cleanme::cleanup::CleanupSelector::Profile)
.or_else(|| {
overrides
.package
.clone()
.map(cargo_cleanme::cleanup::CleanupSelector::Package)
});
if resolved.roots.is_empty() {
let empty = cargo_cleanme::cleanup::CleanReport {
results: Vec::new(),
diagnostics: 0,
failed: 0,
mode,
counters: Default::default(),
scope_blocked: None,
unresolved_ownership: Vec::new(),
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 show = options.format == OutputFormat::Human
&& cargo_cleanme::progress::should_show_progress(options.no_progress);
let renderer = cargo_cleanme::progress::IndicatifRenderer::new(!show);
let wall_start = std::time::Instant::now();
let report = cargo_cleanme::cleanup::clean_with_roots_policy_selector(
&resolved.roots,
config.scan.recency_seconds,
&config.cleanup.allowed_output_roots,
mode,
&cargo_cleanme::cleanup::SystemCleanupRunner,
&renderer,
&policy,
selector,
)?;
renderer.finish_and_clear();
if options.format == OutputFormat::Human
&& 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={:?} {} {} {} {} elapsed={:.2}s",
mode,
report.counters.stats_line(),
report.counters.timings_line(),
report.counters.proof_stats_line(),
report.counters.proof_timings_line(),
elapsed.as_secs_f64(),
);
}
Ok(if report.failed > 0 || report.scope_blocked.is_some() {
1
} else {
0
})
}
fn resolve_cleanup_roots(
scope: &CleanupScope,
config_path: &std::path::Path,
config: &config::Config,
options: RunOptions,
) -> Result<ResolvedCleanup, AppError> {
match scope {
CleanupScope::Root(root) => Ok(ResolvedCleanup {
roots: vec![cli::absolutize_root(root)],
scope_label: "explicit",
state_generation: None,
}),
CleanupScope::Full => {
let code = run_scan(ScanIntent::Full, config_path, options, EmitReport::No)?;
if code != 0 {
return Err(AppError::Config(format!(
"full reconciliation reported an incomplete scan (exit {code}); \
no cleanup commands were run against its unproven learned roots"
)));
}
let state = match cargo_cleanme::discovery_state::load_default() {
cargo_cleanme::discovery_state::StateLoad::Loaded(state) => Some(state),
_ => None,
};
Ok(ResolvedCleanup {
roots: state
.as_ref()
.map(|s| s.learned_roots.iter().map(|r| r.path.clone()).collect())
.unwrap_or_default(),
scope_label: "full",
state_generation: state.as_ref().and_then(|s| s.last_full_at),
})
}
CleanupScope::Maintenance => {
let policy = cargo_cleanme::policy::resolve(
cargo_cleanme::domain::ScanRequest {
cli_root: None,
full: false,
},
&config.scan,
)?;
let (roots, scope_label) = match policy.scope {
ScanScope::Routine(roots) => (roots, "routine"),
ScanScope::Explicit(root) => (vec![root], "explicit"),
ScanScope::ExplicitRoots(roots) => (roots, "explicit"),
ScanScope::Global(_) => {
return Err(AppError::Config(
"maintenance scope resolved to a global scan, which is unreachable; \
refusing to treat it as an empty cleanup scope"
.into(),
));
}
};
let generation = match cargo_cleanme::discovery_state::load_default() {
cargo_cleanme::discovery_state::StateLoad::Loaded(state) => state.last_full_at,
_ => None,
};
Ok(ResolvedCleanup {
roots,
scope_label,
state_generation: generation,
})
}
}
}
fn emit_cleanup(
report: &cargo_cleanme::cleanup::CleanReport,
resolved: &ResolvedCleanup,
roots: &[std::path::PathBuf],
options: RunOptions,
empty_note: &str,
) {
if options.format == OutputFormat::Json {
let document = serde_json::to_string(&cargo_cleanme::output::cleanup(
report,
resolved.scope_label,
resolved.state_generation,
))
.expect("the cleanup envelope is built from owned strings and integers");
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!(
"combined roots {}\n{}",
roots
.iter()
.map(|r| r.display().to_string())
.collect::<Vec<_>>()
.join(", "),
report.render()
);
} else {
println!("{empty_note}");
}
}
fn collapse_roots(roots: Vec<std::path::PathBuf>) -> Vec<std::path::PathBuf> {
let mut roots: Vec<_> = roots
.into_iter()
.map(|p| std::fs::canonicalize(&p).unwrap_or(p))
.collect();
roots.sort();
roots.dedup();
let mut collapsed: Vec<std::path::PathBuf> = Vec::new();
for path in roots {
if !collapsed.iter().any(|parent| path.starts_with(parent)) {
collapsed.push(path);
}
}
collapsed
}
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,
}
fn run_scan(
intent: ScanIntent,
config_path: &std::path::Path,
options: RunOptions,
emit_report: EmitReport,
) -> Result<i32, 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 (root, full) = match intent {
ScanIntent::Full => (None, true),
ScanIntent::Explicit(root) => (Some(root), false),
ScanIntent::Maintenance => (None, false),
};
let policy = cargo_cleanme::policy::resolve(
domain::ScanRequest {
cli_root: root,
full,
},
&c.scan,
)?;
let recency = policy.recency;
let show = options.format == OutputFormat::Human
&& progress::should_show_progress(options.no_progress);
let renderer = progress::IndicatifRenderer::new(!show);
let observer: &dyn progress::ProgressObserver = &renderer;
observer.phase(progress::ScanPhase::Discovery);
let discovery_start = std::time::Instant::now();
let discovered = cargo_cleanme::discovery::discover_manifests_with_attribution(
&policy,
observer,
options.stats,
)?;
let discovery_elapsed = discovery_start.elapsed();
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();
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();
for ws in &workspaces {
for member in &ws.members {
resolved_by_manifest.insert(
std::fs::canonicalize(&member.manifest_path)
.unwrap_or_else(|_| member.manifest_path.clone()),
ws.root.clone(),
);
}
}
let observations: Vec<_> = manifests
.iter()
.map(|manifest| {
let key = std::fs::canonicalize(manifest).unwrap_or_else(|_| manifest.clone());
cargo_cleanme::discovery_state::ProjectObservation {
manifest: key.clone(),
workspace: resolved_by_manifest.get(&key).cloned(),
}
})
.collect();
let complete = !diagnostics.iter().any(|d| {
d.category == domain::DiagnosticCategory::PlatformRoot
&& d.severity == domain::DiagnosticSeverity::Error
});
match cargo_cleanme::discovery_state::reconcile_full(
&prior,
&observations,
&uncertainty,
complete,
now,
c.scan.learned_root_retention_days as u16,
directories::BaseDirs::new()
.map(|b| b.home_dir().to_path_buf())
.as_deref(),
) {
cargo_cleanme::discovery_state::Reconciliation::Publish(next) => {
match cargo_cleanme::discovery_state::publish(&next) {
Ok(()) => {
if replacing_invalid {
eprintln!(
"cargo-cleanme: replaced unusable discovery state after successful Full reconciliation"
);
}
}
Err(error) => {
eprintln!("cargo-cleanme: discovery state was not saved: {error}")
}
}
}
cargo_cleanme::discovery_state::Reconciliation::NoPublication(reason) => {
eprintln!("cargo-cleanme: discovery state was not reconciled: {reason}")
}
}
} else {
let message = loaded_state
.diagnostic()
.unwrap_or_else(|| "discovery state cannot be safely read".into());
eprintln!("cargo-cleanme: {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)
{
eprintln!("cargo-cleanme: 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 = scan_start
.checked_sub(recency)
.ok_or_else(|| 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
&& diagnostics.iter().any(|d| {
d.category == domain::DiagnosticCategory::PlatformRoot
&& d.severity == domain::DiagnosticSeverity::Error
});
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();
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 {
println!("{}", cargo_cleanme::report::render(&mut report));
}
if !report.diagnostics.is_empty() && options.format != OutputFormat::Log {
eprintln!(
"{} filesystem diagnostics; rerun with a bounded root if needed",
report.diagnostics.len()
);
for diagnostic in report.diagnostics.iter().take(10) {
eprintln!(
" {}: {}{}",
format!("{:?}", diagnostic.severity).to_lowercase(),
diagnostic.message,
diagnostic
.path
.as_ref()
.map(|p| format!(" ({})", p.display()))
.unwrap_or_default()
);
}
if report.diagnostics.len() > 10 {
eprintln!(" … {} more", report.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(1);
}
Ok(0)
}