blazy 0.2.0

Unified, AI-safe meta-package manager for 22 OS and language package managers
use crate::model::{ActionKind, ActionResult, ProviderId, SCHEMA_VERSION};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::path::Path;
use std::time::{SystemTime, UNIX_EPOCH};

pub const DEFAULT_LOCKFILE: &str = "blazy.lock";

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LockEntry {
    pub provider: ProviderId,
    pub target: String,
    pub command: String,
    pub verified_binary: Option<String>,
    pub updated_at_secs: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Lockfile {
    pub schema_version: String,
    pub entries: BTreeMap<String, LockEntry>,
}

impl Default for Lockfile {
    fn default() -> Self {
        Self {
            schema_version: SCHEMA_VERSION.to_string(),
            entries: BTreeMap::new(),
        }
    }
}

impl Lockfile {
    pub fn load_or_default(path: &Path) -> Self {
        if !path.exists() {
            return Self::default();
        }
        std::fs::read_to_string(path)
            .ok()
            .and_then(|raw| serde_json::from_str::<Lockfile>(&raw).ok())
            .unwrap_or_default()
    }

    pub fn save(&self, path: &Path) -> Result<(), String> {
        let rendered = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?;
        std::fs::write(path, rendered)
            .map_err(|e| format!("failed to write lockfile {}: {e}", path.display()))
    }

    pub fn record_result(&mut self, res: &ActionResult) {
        if !res.success {
            return;
        }
        let key = format!("{}:{}", res.plan.provider, res.plan.target);
        match res.plan.action {
            ActionKind::Add | ActionKind::Update => {
                let ts = SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .map(|d| d.as_secs())
                    .unwrap_or(0);
                self.entries.insert(
                    key,
                    LockEntry {
                        provider: res.plan.provider,
                        target: res.plan.target.clone(),
                        command: res.plan.command_line(),
                        verified_binary: res.verified_binary.clone(),
                        updated_at_secs: ts,
                    },
                );
            }
            ActionKind::Remove => {
                self.entries.remove(&key);
            }
        }
    }
}

pub fn maybe_update_local_lockfile(res: &ActionResult) {
    let manifest_path = Path::new("blazy.toml");
    let lock_path = Path::new(DEFAULT_LOCKFILE);
    if manifest_path.exists() || lock_path.exists() {
        let mut lock = Lockfile::load_or_default(lock_path);
        lock.record_result(res);
        let _ = lock.save(lock_path);
    }
}

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

    #[test]
    fn records_add_and_remove_in_lockfile() {
        let mut lock = Lockfile::default();
        let plan = ExecutionPlan {
            action: ActionKind::Add,
            target: "ripgrep".to_string(),
            provider: ProviderId::Scoop,
            command: "scoop".to_string(),
            args: vec!["install".into(), "ripgrep".into()],
            requires_elevation: false,
            reversible: true,
            notes: vec![],
        };
        let res = ActionResult {
            plan: plan.clone(),
            success: true,
            exit_code: Some(0),
            stdout: String::new(),
            stderr: String::new(),
            duration_ms: 100,
            verified_binary: Some("rg.exe".to_string()),
        };
        lock.record_result(&res);
        assert!(lock.entries.contains_key("scoop:ripgrep"));

        let mut rem_plan = plan;
        rem_plan.action = ActionKind::Remove;
        let rem_res = ActionResult {
            plan: rem_plan,
            success: true,
            exit_code: Some(0),
            stdout: String::new(),
            stderr: String::new(),
            duration_ms: 50,
            verified_binary: None,
        };
        lock.record_result(&rem_res);
        assert!(!lock.entries.contains_key("scoop:ripgrep"));
    }
}