lysosome 0.5.1

Find and safely reclaim the disk your dev tools and coding agents leave behind
//! `scan --share`: a few lines of totals to post, never a path, a project,
//! a branch or a model name. Printed on stdout and, at a terminal, copied to
//! the clipboard. Nothing is uploaded; the person posts it themselves.

use std::io::Write as _;
use std::process::{Command, Stdio};
use std::time::SystemTime;

use lysosome_core::model::{Category, Report};

use crate::scan::Leftovers;
use crate::ui::{human_bytes, plural};

/// The totals the card is made of.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct Totals {
    /// Linked git worktrees found, and their size.
    pub worktrees: u64,
    pub worktree_bytes: u64,
    /// What `clean` can take back from them without losing work.
    pub leftovers: u64,
    /// `REMOVABLE` items in every section.
    pub reclaimable: u64,
}

impl Totals {
    pub fn of(report: &Report, now: SystemTime) -> Self {
        let wts = report
            .findings
            .iter()
            .filter(|f| f.category == Category::Worktrees);
        Totals {
            worktrees: wts.clone().count() as u64,
            worktree_bytes: wts.map(|f| f.size_bytes).sum(),
            leftovers: Leftovers::of(&report.findings, now).total(),
            reclaimable: report.summary.reclaimable_bytes,
        }
    }
}

#[cfg(target_os = "macos")]
const MY_MACHINE: &str = "my Mac";
#[cfg(not(target_os = "macos"))]
const MY_MACHINE: &str = "my machine";

/// The card's text, ending in a newline.
pub fn card(t: Totals) -> String {
    let mut lines = Vec::new();
    if t.worktree_bytes > 0 {
        lines.push(format!(
            "My coding agents left {} holding {} on {MY_MACHINE}.",
            plural(t.worktrees, "git worktree", "git worktrees"),
            human_bytes(t.worktree_bytes),
        ));
        if t.leftovers > 0 {
            lines.push(format!(
                "{} of it can go without losing any work.",
                human_bytes(t.leftovers)
            ));
        }
    } else if t.reclaimable > 0 {
        lines.push(format!(
            "My dev tools left {} I can reclaim on {MY_MACHINE}.",
            human_bytes(t.reclaimable)
        ));
    } else {
        lines.push(format!(
            "My dev tools left nothing behind on {MY_MACHINE}. Tidy."
        ));
    }
    lines.push(format!(
        "Found with lysosome · {}",
        crate::hint::APP_URL.trim_start_matches("https://")
    ));
    let mut s = lines.join("\n");
    s.push('\n');
    s
}

/// Clipboard tools to try, in order: each is argv.
#[cfg(target_os = "macos")]
const CLIPBOARD: &[&[&str]] = &[&["pbcopy"]];
#[cfg(not(target_os = "macos"))]
const CLIPBOARD: &[&[&str]] = &[
    &["wl-copy"],
    &["xclip", "-selection", "clipboard"],
    &["xsel", "--clipboard", "--input"],
];

/// Copy `text` with the first clipboard tool that works. `false` when none did.
pub fn copy(text: &str) -> bool {
    CLIPBOARD.iter().any(|argv| {
        let Ok(mut child) = Command::new(argv[0])
            .args(&argv[1..])
            .stdin(Stdio::piped())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()
        else {
            return false;
        };
        let wrote = child
            .stdin
            .take()
            .is_some_and(|mut i| i.write_all(text.as_bytes()).is_ok());
        child.wait().is_ok_and(|s| s.success()) && wrote
    })
}

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

    const GB: u64 = 1_000_000_000;

    #[test]
    fn card_leads_with_the_worktrees_and_holds_no_paths() {
        let s = card(Totals {
            worktrees: 161,
            worktree_bytes: 150 * GB,
            leftovers: 68 * GB,
            reclaimable: 90 * GB,
        });
        let lines: Vec<&str> = s.lines().collect();
        assert_eq!(
            lines[0],
            format!("My coding agents left 161 git worktrees holding 150 GB on {MY_MACHINE}.")
        );
        assert_eq!(lines[1], "68.0 GB of it can go without losing any work.");
        assert_eq!(lines[2], "Found with lysosome · lysosome.dev");
        assert!(!s.contains('/') && !s.contains('~'), "no paths: {s}");
    }

    #[test]
    fn card_without_worktrees_uses_the_reclaimable_total() {
        let s = card(Totals {
            reclaimable: 12 * GB,
            ..Totals::default()
        });
        assert!(
            s.starts_with("My dev tools left 12.0 GB I can reclaim"),
            "{s}"
        );
        let s = card(Totals {
            worktrees: 2,
            worktree_bytes: GB,
            ..Totals::default()
        });
        assert_eq!(
            s.lines().count(),
            2,
            "no leftovers line when nothing can go: {s}"
        );
        assert!(card(Totals::default()).starts_with("My dev tools left nothing"));
    }
}