pub mod human;
pub mod json;
use std::path::PathBuf;
use std::time::Duration;
use crate::classify::{Finding, SkipReason};
use crate::delete::Outcome;
use crate::scan::{Skipped, WalkFailure};
pub const SCHEMA_VERSION: u32 = 4;
pub mod exit {
pub const SUCCESS: i32 = 0;
pub const REMOVAL_FAILED: i32 = 1;
pub const USAGE: i32 = 2;
pub const FINDINGS: i32 = 3;
}
#[derive(Debug, Clone)]
pub struct Entry {
pub path: PathBuf,
pub finding: Finding,
pub bytes: u64,
pub unreadable: usize,
pub outcome: Outcome,
}
impl Entry {
#[must_use]
pub fn ecosystem(&self) -> Option<&'static str> {
self.finding.ecosystem()
}
#[must_use]
pub fn artifact(&self) -> Option<&'static str> {
self.finding.artifact().map(|id| id.artifact().path)
}
#[must_use]
pub fn is_dependency(&self) -> bool {
self.finding
.artifact()
.is_some_and(|id| crate::catalog::is_dependency_artifact(&id.spec()))
}
#[must_use]
pub fn reclaimed_bytes(&self) -> u64 {
match &self.outcome {
Outcome::Removed | Outcome::Detached | Outcome::WouldRemove => self.bytes,
Outcome::PartiallyRemoved { freed, .. } => *freed,
_ => 0,
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Totals {
pub reclaimed: usize,
pub bytes: u64,
pub skipped: usize,
pub refused: usize,
pub failed: usize,
pub partial: usize,
pub partial_bytes: u64,
pub unmeasured: usize,
pub dependencies: usize,
pub detached: usize,
}
#[derive(Debug)]
pub struct RunResult {
pub roots: Vec<PathBuf>,
pub entries: Vec<Entry>,
pub skips: Vec<Skipped>,
pub skipped_count: usize,
pub failures: Vec<WalkFailure>,
pub dry_run: bool,
pub git: Option<crate::git::GitPruneResult>,
pub repositories: Vec<std::path::PathBuf>,
pub timings: Timings,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Timings {
pub total: Duration,
pub scan: Duration,
pub policy: Duration,
pub size: Duration,
pub delete: Duration,
pub git: Duration,
}
impl RunResult {
pub fn sort(&mut self) {
self.entries.sort_by(|left, right| left.path.cmp(&right.path));
self.skips.sort_by(|left, right| left.path.cmp(&right.path));
self.failures.sort_by(|left, right| left.path.cmp(&right.path));
}
#[must_use]
pub fn totals(&self) -> Totals {
let mut totals = Totals {
skipped: self.skipped_count,
..Totals::default()
};
for entry in &self.entries {
totals.bytes += entry.reclaimed_bytes();
if entry.unreadable > 0 {
totals.unmeasured += 1;
}
if entry.outcome.is_reclaimed() && entry.is_dependency() {
totals.dependencies += 1;
}
match &entry.outcome {
Outcome::Removed | Outcome::WouldRemove => totals.reclaimed += 1,
Outcome::Detached => {
totals.reclaimed += 1;
totals.detached += 1;
}
Outcome::Refused(_) => totals.refused += 1,
Outcome::PartiallyRemoved { freed, .. } => {
totals.partial += 1;
totals.partial_bytes += freed;
}
_ => totals.failed += 1,
}
}
totals
}
#[must_use]
pub fn exit_code(&self, exit_code: bool) -> i32 {
let totals = self.totals();
if totals.failed > 0 || totals.partial > 0 {
return exit::REMOVAL_FAILED;
}
if exit_code && self.dry_run && totals.reclaimed > 0 {
return exit::FINDINGS;
}
exit::SUCCESS
}
pub fn skip_reasons(&self) -> impl Iterator<Item = (&PathBuf, &SkipReason)> {
self.skips.iter().map(|skipped| (&skipped.path, &skipped.reason))
}
}
#[cfg(test)]
pub(crate) mod fixtures {
use std::path::Path;
use super::*;
use crate::classify::ArtifactId;
pub(crate) fn spell(path: &str) -> String {
if cfg!(windows) && path.starts_with('/') {
format!("C:{}", path.replace('/', "\\"))
} else {
path.to_owned()
}
}
pub(crate) fn unspell(text: &str) -> String {
if cfg!(windows) {
text.replace("C:\\", "/").replace('\\', "/")
} else {
text.to_owned()
}
}
pub(crate) fn failure(kind: std::io::ErrorKind) -> crate::delete::RemovalFailure {
crate::delete::RemovalFailure::from_io(&std::io::Error::from(kind))
}
pub(crate) fn entry(path: &str, spec: &str, bytes: u64, outcome: Outcome) -> Entry {
let artifact = ArtifactId::from_spec(spec).expect("a catalog spec");
let path = PathBuf::from(path);
let marker_dir = path.parent().unwrap_or(Path::new("/")).to_path_buf();
Entry {
unreadable: 0,
finding: Finding {
path: path.clone(),
provenance: crate::classify::Provenance::Anchored { artifact, marker_dir },
},
path,
bytes,
outcome,
}
}
pub(crate) fn included(path: &str, pattern: &str, bytes: u64, outcome: Outcome) -> Entry {
let path = PathBuf::from(path);
Entry {
unreadable: 0,
finding: Finding {
path: path.clone(),
provenance: crate::classify::Provenance::Included {
pattern: pattern.to_owned(),
},
},
path,
bytes,
outcome,
}
}
pub(crate) fn tagged(path: &str, bytes: u64, outcome: Outcome) -> Entry {
let path = PathBuf::from(path);
Entry {
unreadable: 0,
finding: Finding {
path: path.clone(),
provenance: crate::classify::Provenance::Tagged,
},
path,
bytes,
outcome,
}
}
pub(crate) fn result(entries: Vec<Entry>, dry_run: bool) -> RunResult {
let mut result = RunResult {
roots: vec![PathBuf::from("/projects")],
entries,
skips: Vec::new(),
skipped_count: 0,
failures: Vec::new(),
dry_run,
git: None,
repositories: Vec::new(),
timings: Timings {
total: Duration::from_millis(1234),
scan: Duration::from_millis(900),
policy: Duration::from_millis(12),
size: Duration::from_millis(210),
delete: Duration::from_millis(98),
git: Duration::default(),
},
};
result.sort();
result
}
}
#[cfg(test)]
mod tests {
use super::fixtures::{entry, result};
use super::*;
use crate::delete::Refusal;
#[test]
fn should_sort_entries_by_path_whatever_order_they_arrived_in() {
let result = result(
vec![
entry("/projects/zeta/target", "rust.target", 1, Outcome::Removed),
entry("/projects/alpha/target", "rust.target", 1, Outcome::Removed),
entry("/projects/mid/dist", "node.dist", 1, Outcome::Removed),
],
false,
);
let paths: Vec<_> = result
.entries
.iter()
.map(|entry| entry.path.display().to_string())
.collect();
assert_eq!(
paths,
vec!["/projects/alpha/target", "/projects/mid/dist", "/projects/zeta/target"]
);
}
#[test]
fn should_total_the_bytes_a_run_actually_freed() {
let result = result(
vec![
entry("/projects/a/target", "rust.target", 1_000, Outcome::Removed),
entry("/projects/b/target", "rust.target", 2_000, Outcome::WouldRemove),
entry(
"/projects/c/target",
"rust.target",
4_000,
Outcome::Refused(Refusal::Symlink),
),
entry(
"/projects/d/target",
"rust.target",
8_000,
Outcome::Failed(fixtures::failure(std::io::ErrorKind::Other)),
),
entry(
"/projects/e/target",
"rust.target",
16_000,
Outcome::PartiallyRemoved {
freed: 10_000,
remaining: 6_000,
failure: fixtures::failure(std::io::ErrorKind::DirectoryNotEmpty),
},
),
],
false,
);
let totals = result.totals();
assert_eq!(totals.reclaimed, 2, "only artifacts that are actually gone are counted");
assert_eq!(
totals.bytes, 13_000,
"every byte the run freed, including the 10_000 from an artifact still on disk — \
reporting that one as zero is what made a 130 GB sweep claim it reclaimed 25"
);
assert_eq!(totals.refused, 1);
assert_eq!(totals.failed, 1, "a removal that freed nothing is a plain failure");
assert_eq!(totals.partial, 1);
assert_eq!(totals.partial_bytes, 10_000, "a documented subset of `bytes`");
}
#[test]
fn should_exit_one_when_a_removal_was_only_partial() {
let result = result(
vec![entry(
"/projects/a/target",
"rust.target",
1_000,
Outcome::PartiallyRemoved {
freed: 900,
remaining: 100,
failure: fixtures::failure(std::io::ErrorKind::DirectoryNotEmpty),
},
)],
false,
);
assert_eq!(result.exit_code(false), exit::REMOVAL_FAILED);
}
#[test]
fn should_exit_zero_when_everything_succeeded() {
let result = result(
vec![entry("/projects/a/target", "rust.target", 1, Outcome::Removed)],
false,
);
assert_eq!(result.exit_code(false), exit::SUCCESS);
}
#[test]
fn should_exit_one_when_a_removal_failed() {
let result = result(
vec![entry(
"/projects/a/target",
"rust.target",
1,
Outcome::Failed(fixtures::failure(std::io::ErrorKind::Other)),
)],
false,
);
assert_eq!(result.exit_code(false), exit::REMOVAL_FAILED);
}
#[test]
fn should_exit_three_for_a_dry_run_with_findings_and_exit_code() {
let found = result(
vec![entry("/projects/a/target", "rust.target", 1, Outcome::WouldRemove)],
true,
);
assert_eq!(found.exit_code(true), exit::FINDINGS);
assert_eq!(
found.exit_code(false),
exit::SUCCESS,
"without --exit-code a dry run is informational"
);
let clean = result(Vec::new(), true);
assert_eq!(clean.exit_code(true), exit::SUCCESS);
}
#[test]
fn a_refusal_is_not_a_failure() {
let result = result(
vec![entry(
"/projects/a/target",
"rust.target",
1,
Outcome::Refused(Refusal::Protected),
)],
false,
);
assert_eq!(
result.exit_code(false),
exit::SUCCESS,
"a rail doing its job is not a run failure"
);
}
}