use std::fmt::Write as _;
use std::path::Path;
use crate::analysis::AnalysisResult;
use crate::cli::checking::stale_report::StaleReport;
use crate::cli::cli_error::CliResult;
use crate::cli::command_outcome::CommandOutcome;
use crate::cli::ignore_entry_line::IgnoreEntryLine;
use crate::suppression::ignore_file::IgnoreFile;
pub struct CleanupCommand<'a> {
root: &'a Path,
result: &'a AnalysisResult,
dry_run: bool,
}
impl<'a> CleanupCommand<'a> {
#[must_use]
pub const fn new(root: &'a Path, result: &'a AnalysisResult, dry_run: bool) -> Self {
Self {
root,
result,
dry_run,
}
}
pub fn run(&self) -> CliResult<CommandOutcome> {
let ignore_file = IgnoreFile::load(self.root);
let taken;
let report = if self.dry_run {
StaleReport::dry_run(ignore_file.stale(&self.result.all_fingerprints))
} else {
let pruned;
(pruned, taken) = ignore_file.without_stale(&self.result.all_fingerprints);
if !taken.is_empty() {
pruned.save(self.root)?;
}
StaleReport::removed(taken.iter().collect())
};
let mut out = String::new();
if report.is_empty() {
let _ = writeln!(out, "No stale entries found.");
return Ok(CommandOutcome::succeeded(out));
}
let _ = writeln!(out, "{}", report.heading());
for entry in report.entries() {
let _ = writeln!(out, "{}", IgnoreEntryLine::new(entry));
}
let _ = writeln!(out, "{}", report.summary());
Ok(CommandOutcome::succeeded(out))
}
}