lysosome 0.5.1

Find and safely reclaim the disk your dev tools and coding agents leave behind
//! `scan --summary` / `worktrees --summary`: totals by status, category and
//! kind plus the biggest items, instead of every finding. Small enough for
//! an agent's context; the full report stays one `--json` away.

use std::collections::BTreeMap;
use std::fmt::Write as _;

use lysosome_core::model::{Finding, Report, Status};
use owo_colors::Style;
use serde_json::{json, Value};

use crate::ui::{human_bytes, pad_left, pad_right, plural, Painter, PathShortener};

#[derive(Default, Clone, Copy)]
struct Tally {
    items: u64,
    bytes: u64,
}

impl Tally {
    fn add(&mut self, f: &Finding) {
        self.items += 1;
        self.bytes += f.size_bytes;
    }

    fn json(self) -> Value {
        json!({ "items": self.items, "bytes": self.bytes })
    }
}

/// The findings `top` lists: dormant ones (all of them with `all`), biggest first.
fn top_items(report: &Report, all: bool, top: usize) -> Vec<&Finding> {
    let mut v: Vec<&Finding> = report
        .findings
        .iter()
        .filter(|f| all || f.status.is_dormant())
        .collect();
    v.sort_by(|a, b| b.size_bytes.cmp(&a.size_bytes).then(a.id.cmp(&b.id)));
    v.truncate(top);
    v
}

fn name_of(f: &Finding) -> String {
    f.details
        .get("name")
        .and_then(Value::as_str)
        .map(str::to_string)
        .unwrap_or_else(|| {
            f.path
                .file_name()
                .map(|n| n.to_string_lossy().into_owned())
                .unwrap_or_else(|| f.path.to_string_lossy().into_owned())
        })
}

/// `--summary` output for `scan` / `worktrees`: JSON or the short text.
pub fn output(
    report: &Report,
    args: &crate::ScanArgs,
    global: &crate::GlobalArgs,
    paths: &PathShortener,
) -> anyhow::Result<String> {
    if args.json {
        let mut s = serde_json::to_string_pretty(&json_doc(report, args.all, args.top))?;
        s.push('\n');
        return Ok(s);
    }
    let p = Painter::new(crate::ui::color_enabled(
        global.no_color,
        crate::ui::stdout_is_tty(),
    ));
    Ok(render(report, args.all, args.top, &p, paths))
}

/// The `--summary --json` document (schema/summary.schema.json).
pub fn json_doc(report: &Report, all: bool, top: usize) -> Value {
    let mut by_status: BTreeMap<&str, Tally> = [
        Status::Removable,
        Status::Review,
        Status::Orphan,
        Status::Active,
    ]
    .iter()
    .map(|s| (s.as_str(), Tally::default()))
    .collect();
    let mut by_kind: BTreeMap<&str, BTreeMap<&str, Tally>> = BTreeMap::new();
    for f in &report.findings {
        by_status.entry(f.status.as_str()).or_default().add(f);
        by_kind
            .entry(f.kind.as_str())
            .or_default()
            .entry(f.status.as_str())
            .or_default()
            .add(f);
    }
    let by_kind: serde_json::Map<String, Value> = by_kind
        .into_iter()
        .map(|(k, m)| {
            (
                k.to_string(),
                Value::Object(m.into_iter().map(|(s, t)| (s.into(), t.json())).collect()),
            )
        })
        .collect();
    let top: Vec<Value> = top_items(report, all, top)
        .into_iter()
        .map(|f| {
            json!({
                "id": f.id,
                "category": f.category,
                "kind": f.kind,
                "name": name_of(f),
                "path": f.path.to_string_lossy(),
                "size_bytes": f.size_bytes,
                "tier": f.tier,
                "status": f.status,
                "reason": f.reason,
            })
        })
        .collect();
    json!({
        "schema_version": report.schema_version,
        "tool_version": report.tool_version,
        "kind": "summary",
        "scanned_roots": report.scanned_roots.iter().map(|r| r.to_string_lossy()).collect::<Vec<_>>(),
        "dormant_after_days": report.dormant_after_days,
        "summary": report.summary,
        "findings": report.findings.len(),
        "by_status": by_status.into_iter().map(|(s, t)| (s.to_string(), t.json())).collect::<serde_json::Map<_, _>>(),
        "by_kind": by_kind,
        "top": top,
        "stale_metadata": report.stale_metadata.len(),
        "skipped": report.skipped,
    })
}

/// Human `--summary`: one line per status, per category, then the top items.
pub fn render(
    report: &Report,
    all: bool,
    top: usize,
    p: &Painter,
    paths: &PathShortener,
) -> String {
    let mut o = String::new();
    writeln!(o).ok();
    writeln!(
        o,
        "  {} {} {}",
        p.bold("Reclaimable now:"),
        p.paint(
            human_bytes(report.summary.reclaimable_bytes),
            Style::new().bold().underline().green()
        ),
        p.dim(format!(
            "({} found)",
            plural(report.findings.len() as u64, "item", "items")
        ))
    )
    .ok();
    let mut by_status: BTreeMap<Status, Tally> = BTreeMap::new();
    for f in &report.findings {
        by_status.entry(f.status).or_default().add(f);
    }
    writeln!(o).ok();
    for (s, t) in &by_status {
        writeln!(
            o,
            "    {}  {}  {}",
            pad_right(s.as_str(), 9),
            pad_left(&human_bytes(t.bytes), 9),
            p.dim(plural(t.items, "item", "items"))
        )
        .ok();
    }
    let cats: Vec<_> = report
        .summary
        .by_category
        .iter()
        .filter(|(_, b)| **b > 0)
        .collect();
    if !cats.is_empty() {
        writeln!(o).ok();
        writeln!(o, "  {}", p.bold("Dormant by category")).ok();
        for (c, b) in cats {
            writeln!(
                o,
                "    {}  {}",
                pad_left(&human_bytes(*b), 9),
                c.display_name()
            )
            .ok();
        }
    }
    let items = top_items(report, all, top);
    if !items.is_empty() {
        writeln!(o).ok();
        writeln!(o, "  {}", p.bold(format!("Top {}", items.len()))).ok();
        for f in items {
            writeln!(
                o,
                "    {}  {}  {}  {}",
                pad_right(f.status.as_str(), 9),
                pad_left(&human_bytes(f.size_bytes), 9),
                pad_right(&f.kind, 16),
                paths.short(&f.path)
            )
            .ok();
        }
    }
    writeln!(o).ok();
    writeln!(
        o,
        "  {}",
        p.dim("Nothing was changed. Drop --summary for every item and reason.")
    )
    .ok();
    o
}

#[cfg(test)]
mod tests {
    use super::*;
    use lysosome_core::model::{Category, Skipped, Tier};

    fn f(id: &str, status: Status, size: u64) -> Finding {
        Finding {
            id: id.into(),
            category: Category::Artifacts,
            kind: "node_modules".into(),
            path: format!("/p/{id}").into(),
            size_bytes: size,
            tier: Tier::RegenerableExpensive,
            status,
            reason: String::new(),
            last_activity: None,
            details: json!({}),
            cleanup: None,
        }
    }

    #[test]
    fn totals_and_top_skip_active_unless_all() {
        let r = Report::new(
            vec!["/p".into()],
            30,
            vec![
                f("a", Status::Removable, 10),
                f("b", Status::Active, 100),
                f("c", Status::Review, 5),
            ],
            vec![],
            Skipped::default(),
        );
        let v = json_doc(&r, false, 1);
        assert_eq!(
            v["by_status"]["REMOVABLE"],
            json!({"items": 1, "bytes": 10})
        );
        assert_eq!(v["by_status"]["ACTIVE"]["bytes"], 100);
        assert_eq!(v["by_status"]["ORPHAN"]["items"], 0);
        assert_eq!(v["by_kind"]["node_modules"]["REVIEW"]["bytes"], 5);
        assert_eq!(v["top"].as_array().unwrap().len(), 1);
        assert_eq!(v["top"][0]["id"], "a");
        assert_eq!(json_doc(&r, true, 1)["top"][0]["id"], "b");
        assert_eq!(v["findings"], 3);
    }
}