cleanux 0.1.1

Linux cleaner CLI (CleanMyMac-like): scan & safely trash cache, find duplicates, list large files
Documentation
pub mod cleaners;
pub mod cli;
pub mod config;
pub mod features;
pub mod fsutil;
pub mod model;

use anyhow::Result;
use bytesize::ByteSize;
use cli::{Cli, Command, ReportFormat, Target};
use dialoguer::Confirm;
use std::path::PathBuf;

pub fn run(args: Cli) -> Result<()> {
    let cfg = config::load_config()?;
    let filter = fsutil::PathFilter::from_config(&cfg)?;
    let base_dirs = if std::env::var("CLEANUX_TEST_NODIRS").is_ok() {
        None
    } else {
        directories::BaseDirs::new()
    }
    .ok_or_else(|| anyhow::anyhow!("cannot resolve home dirs"))?;
    let ctx = cleaners::ScanContext {
        base_dirs,
        filter,
        config: &cfg,
        state_dir_override: None,
    };

    match args.cmd {
        Command::Scan { target } => {
            let plan = scan_target(target, &ctx)?;
            emit_report(&plan, &args.report, "scan", false, 0);
        }
        Command::Clean { target } => {
            let plan = scan_target(target, &ctx)?;

            if matches!(args.report, ReportFormat::Text) {
                emit_report(&plan, &args.report, "clean", args.apply, 0);
            }

            if !args.apply {
                if !matches!(args.report, ReportFormat::Text) {
                    emit_report(&plan, &args.report, "clean", false, 0);
                }
                println!("\n(dry-run) Add --apply to actually move items to Trash.");
                return Ok(());
            }

            if !args.yes {
                let ok = confirm_proceed()?;
                if !ok {
                    println!("Cancelled.");
                    return Ok(());
                }
            }

            let paths: Vec<_> = plan.items.iter().map(|i| i.path.clone()).collect();
            if paths.is_empty() {
                if !matches!(args.report, ReportFormat::Text) {
                    emit_report(&plan, &args.report, "clean", true, 0);
                }
                println!("Nothing to clean.");
                return Ok(());
            }

            trash_delete_all(&paths)?;
            if !matches!(args.report, ReportFormat::Text) {
                emit_report(&plan, &args.report, "clean", true, paths.len());
            }
            println!("Done. Moved {} items to Trash.", paths.len());
        }
        Command::Dups {
            path,
            trash,
            min_bytes,
            max_bytes,
        } => {
            features::dups::run_dups(&path, trash, min_bytes, max_bytes)?;
        }
        Command::Large {
            path,
            top,
            min_bytes,
            max_bytes,
        } => {
            features::large::run_large(&path, top, min_bytes, max_bytes)?;
        }
    }

    Ok(())
}

fn confirm_proceed() -> Result<bool> {
    if let Ok(choice) = std::env::var("CLEANUX_CONFIRM") {
        match choice.as_str() {
            "yes" => return Ok(true),
            "no" => return Ok(false),
            _ => {}
        }
    }

    match confirm_interact() {
        Ok(ok) => Ok(ok),
        Err(dialoguer::Error::IO(err)) if err.kind() == std::io::ErrorKind::NotConnected => {
            Ok(false)
        }
        Err(err) => Err(err.into()),
    }
}

fn confirm_interact() -> std::result::Result<bool, dialoguer::Error> {
    if std::env::var("RUST_TEST_THREADS").is_ok()
        && std::env::var("CLEANUX_TEST_FORCE_DIALOGUER").is_err()
        && std::env::var("CLEANUX_CONFIRM_TEST").is_err()
    {
        return Ok(false);
    }
    if let Ok(choice) = std::env::var("CLEANUX_CONFIRM_TEST") {
        return match choice.as_str() {
            "yes" => Ok(true),
            "no" => Ok(false),
            "notconnected" => Err(dialoguer::Error::IO(std::io::Error::new(
                std::io::ErrorKind::NotConnected,
                "test",
            ))),
            "ioerr" => Err(dialoguer::Error::IO(std::io::Error::new(
                std::io::ErrorKind::Other,
                "test",
            ))),
            _ => Ok(false),
        };
    }

    Confirm::new()
        .with_prompt("Proceed to move these items to Trash?")
        .default(false)
        .interact()
}

pub fn scan_target(target: Target, ctx: &cleaners::ScanContext<'_>) -> Result<model::Plan> {
    if std::env::var("CLEANUX_TEST_SCAN_ERROR").is_ok() {
        return Err(anyhow::anyhow!("forced scan error"));
    }
    let mut items = Vec::new();
    for cleaner in cleaners::registry() {
        if !ctx.config.is_cleaner_enabled(cleaner.id()) {
            continue;
        }
        if !target.allows(cleaner.group()) {
            continue;
        }
        match cleaner.scan(ctx) {
            Ok(plan) => items.extend(plan.items),
            Err(err) => eprintln!("warn: cleaner {} failed: {}", cleaner.id(), err),
        }
    }

    Ok(model::Plan::new(items))
}

fn trash_delete_all(paths: &[PathBuf]) -> Result<()> {
    if std::env::var("CLEANUX_TEST_TRASH_ERROR").is_ok() {
        return Err(anyhow::anyhow!("forced trash error"));
    }
    trash::delete_all(paths)?;
    Ok(())
}

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

    #[test]
    fn trash_delete_all_errors_on_missing_path() {
        let missing = std::env::temp_dir().join("cleanux_missing_trash_test");
        let _ = std::fs::remove_file(&missing);
        assert!(trash_delete_all(&[missing]).is_err());
    }
}

fn summaries_for(plan: &model::Plan) -> Vec<model::CleanerSummary> {
    use std::collections::HashMap;
    let mut map: HashMap<String, model::CleanerSummary> = HashMap::new();
    for item in &plan.items {
        let entry = map
            .entry(item.cleaner_id.clone())
            .or_insert(model::CleanerSummary {
                cleaner_id: item.cleaner_id.clone(),
                group: item.group,
                items: 0,
                total_bytes: 0,
            });
        entry.items += 1;
        entry.total_bytes = entry.total_bytes.saturating_add(item.bytes);
    }

    let mut summaries: Vec<_> = map.into_values().collect();
    summaries.sort_by_key(|s| (s.group.as_str(), s.cleaner_id.clone()));
    summaries
}

fn emit_report(
    plan: &model::Plan,
    format: &ReportFormat,
    action: &str,
    applied: bool,
    moved: usize,
) {
    match format {
        ReportFormat::Text => {
            print_plan(plan);
        }
        ReportFormat::Json => {
            let report = model::RunReport {
                action: action.to_string(),
                plan: plan.clone(),
                summaries: summaries_for(plan),
                applied,
                moved,
            };
            match serde_json::to_string_pretty(&report) {
                Ok(txt) => println!("{}", txt),
                Err(err) => eprintln!("warn: failed to serialize report: {}", err),
            }
        }
    }
}

pub fn print_plan(plan: &model::Plan) {
    let mut items = plan.items.clone();
    items.sort_by_key(|i| std::cmp::Reverse(i.bytes));

    println!("Items: {}", plan.items.len());
    println!("Total: {}", ByteSize(plan.total_bytes));

    let summaries = summaries_for(plan);
    if !summaries.is_empty() {
        println!("\nBy cleaner:");
        for s in summaries {
            println!(
                "  {:<16} {:<8} {:>5} items  {:>10}",
                s.cleaner_id,
                s.group.as_str(),
                s.items,
                ByteSize(s.total_bytes)
            );
        }
    }

    if !items.is_empty() {
        println!("\nItems:");
        for item in &items {
            println!(
                "  {:>10}  {:<14}  {}",
                ByteSize(item.bytes),
                item.cleaner_id,
                item.path.display()
            );
        }
    }
}