use crate::domain::*;
use std::path::{Path, PathBuf};
#[derive(Clone, Debug, Default)]
pub struct HumanOptions {
pub roots: Vec<PathBuf>,
pub verbose: bool,
}
impl HumanOptions {
pub fn quiet(roots: Vec<PathBuf>) -> Self {
Self {
roots,
verbose: false,
}
}
pub fn verbose() -> Self {
Self {
roots: Vec::new(),
verbose: true,
}
}
pub fn path(&self, p: &Path) -> String {
path_text(&self.relativized(p))
}
pub fn relativized(&self, p: &Path) -> PathBuf {
for root in &self.roots {
if let Ok(rest) = p.strip_prefix(root) {
let components = rest.components().count();
if components >= 2 {
return rest.to_path_buf();
}
let Some(name) = root.file_name() else {
return rest.to_path_buf();
};
if components == 0 {
return PathBuf::from(name);
}
return PathBuf::from(name).join(rest);
}
}
p.to_path_buf()
}
}
fn path_text(p: &Path) -> String {
let text = p.to_string_lossy();
escape_path_text(&text).into_owned()
}
pub fn escape_path_text(text: &str) -> std::borrow::Cow<'_, str> {
if !text.chars().any(char::is_control) {
return std::borrow::Cow::Borrowed(text);
}
let mut escaped = String::with_capacity(text.len() + 8);
for c in text.chars() {
if c.is_control() {
escaped.push_str(&format!("\\u{{{:x}}}", c as u32));
} else {
escaped.push(c);
}
}
std::borrow::Cow::Owned(escaped)
}
pub fn format_bytes(n: u64) -> String {
const UNITS: [&str; 7] = ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"];
let mut hundredths = u128::from(n) * 100;
let mut unit = 0usize;
while unit + 1 < UNITS.len() && hundredths >= 1024 * 100 {
hundredths = (hundredths + 512) / 1024;
unit += 1;
}
let number = format!("{}.{:02}", hundredths / 100, hundredths % 100);
format!("{number:>6} {}", UNITS[unit])
}
pub fn render(report: &mut ScanReport, options: &HumanOptions) -> String {
report.groups.sort_by(|a, b| {
b.bytes
.cmp(&a.bytes)
.then_with(|| a.display_path.cmp(&b.display_path))
});
let total = report
.groups
.iter()
.fold(0u64, |s, g| s.saturating_add(g.bytes));
let mut o = String::new();
let rendered: Vec<String> = report
.groups
.iter()
.map(|g| options.path(&g.display_path))
.collect();
let width = rendered
.iter()
.map(|path| path.chars().count())
.max()
.unwrap_or(0);
for (g, path) in report.groups.iter().zip(rendered.iter()) {
o.push_str(&format!(
"{:<width$} {} [{}]\n",
path,
format_bytes(g.bytes).trim(),
g.ownership.label(),
));
}
o.push_str(&format!(
"\n{} inventory estimate across {} inactive Cargo output groups\n",
format_bytes(total),
report.groups.len()
));
o
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
fn group(path: &str, bytes: u64) -> EligibleOutputGroup {
EligibleOutputGroup {
display_path: PathBuf::from(path),
workspace_roots: vec![PathBuf::from("/ws")],
physical_paths: vec![PathBuf::from(path)],
bytes,
metric: SizeMetric::Allocated,
newest_mtime: None,
artifact_entries: 1,
ownership: OutputOwnershipClass::PrivateBounded,
}
}
#[cfg(unix)]
#[test]
fn report_escapes_control_bytes_in_paths() {
let mut r = ScanReport::default();
r.groups.push(group("/tmp/esc\u{1b}[2J-bell\u{7}", 1));
let text = render(&mut r, &HumanOptions::default());
assert!(text.contains("\\u{1b}"));
assert!(text.contains("\\u{7}"));
assert!(!text.contains('\u{1b}'));
assert!(!text.contains('\u{7}'));
}
#[cfg(unix)]
#[test]
fn report_escapes_non_utf8_paths() {
use std::os::unix::ffi::OsStringExt;
let mut r = ScanReport::default();
let p = std::path::PathBuf::from(std::ffi::OsString::from_vec(b"/tmp/bad-\xff".to_vec()));
r.groups.push(EligibleOutputGroup {
display_path: p,
workspace_roots: vec![PathBuf::from("/ws")],
physical_paths: vec![PathBuf::from("/ws/target")],
bytes: 1,
metric: SizeMetric::Allocated,
newest_mtime: None,
artifact_entries: 1,
ownership: OutputOwnershipClass::PrivateBounded,
});
let text = render(&mut r, &HumanOptions::default());
assert!(!text.chars().any(|c| c.is_control() && c != '\n'));
assert!(text.contains('\u{fffd}'));
}
#[test]
fn report_ordering_and_zero_report() {
let mut r = ScanReport::default();
assert!(render(&mut r, &HumanOptions::default()).contains("0.00 B inventory estimate"));
r.groups.push(group("/z", 3));
r.groups.push(group("/a", 3));
let text = render(&mut r, &HumanOptions::default());
assert!(text.find("/a").unwrap() < text.find("/z").unwrap());
}
#[test]
fn zero_state_uses_the_same_inventory_wording_as_results() {
let empty = render(&mut ScanReport::default(), &HumanOptions::default());
let mut r = ScanReport::default();
r.groups.push(group("/a", 10));
let with_results = render(&mut r, &HumanOptions::default());
assert!(with_results.contains("inventory estimate"));
assert!(empty.contains("inventory estimate"));
assert!(!empty.contains("reclaimable"));
}
#[test]
fn format_bytes_scales_to_eib_and_promotes_rounded_units() {
assert_eq!(format_bytes(0).trim(), "0.00 B");
assert_eq!(format_bytes(500).trim(), "500.00 B");
assert_eq!(format_bytes(1024).trim(), "1.00 KiB");
assert_eq!(format_bytes(1_048_575).trim(), "1.00 MiB");
assert_eq!(format_bytes(1024u64.pow(6)).trim(), "1.00 EiB");
assert_eq!(format_bytes(u64::MAX).trim(), "16.00 EiB");
}
#[test]
fn groups_render_every_group_with_ownership_and_deduped_total() {
let mut r = ScanReport::default();
for (path, bytes, ownership) in [
("/z/shared", 300u64, OutputOwnershipClass::Shared),
("/a/private", 300u64, OutputOwnershipClass::PrivateBounded),
(
"/e/external",
100u64,
OutputOwnershipClass::ExternalUnproven,
),
] {
r.groups.push(EligibleOutputGroup {
ownership,
..group(path, bytes)
});
}
let text = render(&mut r, &HumanOptions::default());
assert!(text.find("/a/private").unwrap() < text.find("/z/shared").unwrap());
assert!(text.contains("/e/external"));
assert!(text.contains("[private]"));
assert!(text.contains("[shared]"));
assert!(text.contains("[external-unproven]"));
assert!(text.contains("inventory estimate"));
assert!(!text.contains("recovered"));
}
#[test]
fn groups_total_does_not_double_count_equal_roots() {
let mut r = ScanReport::default();
r.groups.push(EligibleOutputGroup {
physical_paths: vec![PathBuf::from("/ws/target"), PathBuf::from("/ws/target")],
artifact_entries: 2,
..group("/ws/target", 500)
});
let text = render(&mut r, &HumanOptions::default());
assert!(text.contains("500"));
assert!(text.contains("1 inactive Cargo output group"));
}
#[test]
fn a_bounded_scope_spells_its_paths_relative_to_the_scope_root() {
let mut r = ScanReport::default();
r.groups.push(group("/work/alpha/target", 10));
r.groups.push(group("/elsewhere/beta/target", 20));
let text = render(&mut r, &HumanOptions::quiet(vec![PathBuf::from("/work")]));
assert!(
text.contains("alpha/target"),
"a path under the scope root is relative: {text}"
);
assert!(
text.contains("/elsewhere/beta/target"),
"a path under no scope root stays absolute: {text}"
);
assert!(
!text.contains("/work/alpha/target"),
"the relative path must not keep the root prefix: {text}"
);
}
#[test]
fn a_full_scope_spells_its_paths_absolutely() {
let mut r = ScanReport::default();
r.groups.push(group("/home/user/alpha/target", 10));
let text = render(&mut r, &HumanOptions::quiet(Vec::new()));
assert!(
text.contains("/home/user/alpha/target"),
"the Full scope's paths are absolute: {text}"
);
}
#[test]
fn a_one_component_path_is_qualified_with_the_scope_root_name() {
let mut r = ScanReport::default();
r.groups.push(group("/projects/my-app/target", 10));
let text = render(
&mut r,
&HumanOptions::quiet(vec![PathBuf::from("/projects/my-app")]),
);
let qualified = PathBuf::from("my-app").join("target");
assert!(
text.contains(qualified.to_string_lossy().as_ref()),
"{text}"
);
assert!(!text.contains("/projects/my-app/target"), "{text}");
}
#[test]
fn the_scope_root_itself_is_spelled_with_its_own_name() {
let mut r = ScanReport::default();
r.groups.push(group("/work", 10));
let text = render(&mut r, &HumanOptions::quiet(vec![PathBuf::from("/work")]));
assert!(text.contains("work"), "the scope root names itself: {text}");
assert!(
!text.contains(" /work"),
"the scope root is not spelled absolutely: {text}"
);
}
}