use crate::model::{ActionKind, ActionResult, ProviderId};
use serde::{Deserialize, Serialize};
use std::fs::{self, OpenOptions};
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HistoryEntry {
pub timestamp_secs: u64,
pub action: ActionKind,
pub provider: ProviderId,
pub target: String,
pub command: String,
pub success: bool,
pub duration_ms: u128,
}
impl HistoryEntry {
pub fn from_result(res: &ActionResult) -> Self {
let timestamp_secs = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
Self {
timestamp_secs,
action: res.plan.action,
provider: res.plan.provider,
target: res.plan.target.clone(),
command: res.plan.command_line(),
success: res.success,
duration_ms: res.duration_ms,
}
}
pub fn inverse(&self) -> Result<(ActionKind, String, ProviderId), String> {
match self.action {
ActionKind::Add => Ok((ActionKind::Remove, self.target.clone(), self.provider)),
ActionKind::Remove => Ok((ActionKind::Add, self.target.clone(), self.provider)),
ActionKind::Update => Err(format!(
"cannot automatically undo update of '{}:{}'",
self.provider, self.target
)),
}
}
}
pub fn default_history_path() -> PathBuf {
if let Ok(custom) = std::env::var("BLAZY_HISTORY_PATH") {
return PathBuf::from(custom);
}
if let Some(base) = std::env::var_os("LOCALAPPDATA")
.or_else(|| std::env::var_os("XDG_DATA_HOME"))
.or_else(|| std::env::var_os("USERPROFILE"))
.or_else(|| std::env::var_os("HOME"))
{
return PathBuf::from(base).join("blazy").join("history.jsonl");
}
PathBuf::from("blazy-history.jsonl")
}
pub fn record_result(res: &ActionResult) -> Result<(), String> {
append_entry_to(&default_history_path(), &HistoryEntry::from_result(res))
}
pub fn append_entry_to(path: &Path, entry: &HistoryEntry) -> Result<(), String> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)
.map_err(|e| format!("failed to create history directory: {e}"))?;
}
let mut file = OpenOptions::new()
.create(true)
.append(true)
.open(path)
.map_err(|e| format!("failed to open history file {}: {e}", path.display()))?;
let line = serde_json::to_string(entry).map_err(|e| e.to_string())?;
writeln!(file, "{line}").map_err(|e| format!("failed writing history: {e}"))?;
Ok(())
}
pub fn read_entries_from(path: &Path, limit: usize) -> Result<Vec<HistoryEntry>, String> {
if !path.exists() {
return Ok(Vec::new());
}
let file = fs::File::open(path)
.map_err(|e| format!("failed to read history file {}: {e}", path.display()))?;
let reader = BufReader::new(file);
let mut entries = Vec::new();
for line in reader.lines().map_while(Result::ok) {
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
if let Ok(entry) = serde_json::from_str::<HistoryEntry>(trimmed) {
entries.push(entry);
}
}
if entries.len() > limit {
let start = entries.len() - limit;
entries = entries.split_off(start);
}
entries.reverse();
Ok(entries)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn appends_and_reads_history_entries() {
let dir = std::env::temp_dir().join(format!(
"blazy_hist_test_{}",
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let path = dir.join("history.jsonl");
let e1 = HistoryEntry {
timestamp_secs: 100,
action: ActionKind::Add,
provider: ProviderId::Scoop,
target: "ripgrep".to_string(),
command: "scoop install ripgrep".to_string(),
success: true,
duration_ms: 420,
};
let e2 = HistoryEntry {
timestamp_secs: 200,
action: ActionKind::Remove,
provider: ProviderId::Uv,
target: "ruff".to_string(),
command: "uv tool uninstall ruff".to_string(),
success: true,
duration_ms: 210,
};
append_entry_to(&path, &e1).unwrap();
append_entry_to(&path, &e2).unwrap();
let entries = read_entries_from(&path, 10).unwrap();
assert_eq!(entries.len(), 2);
assert_eq!(entries[0].target, "ruff");
assert_eq!(entries[1].target, "ripgrep");
let (inv_action, inv_target, inv_provider) = entries[1].inverse().unwrap();
assert_eq!(inv_action, ActionKind::Remove);
assert_eq!(inv_target, "ripgrep");
assert_eq!(inv_provider, ProviderId::Scoop);
let _ = fs::remove_dir_all(&dir);
}
}