use crate::error::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::Path;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResolutionEntry {
pub path: String,
pub our_blob: String,
pub their_blob: String,
pub resolved_blob: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ResolutionCache {
entries: HashMap<String, ResolutionEntry>,
}
impl ResolutionCache {
pub fn get(&self, path: &str, our_blob: &str, their_blob: &str) -> Option<&str> {
let key = Self::key(path, our_blob, their_blob);
self.entries.get(&key).map(|e| e.resolved_blob.as_str())
}
pub fn set(&mut self, path: &str, our_blob: &str, their_blob: &str, resolved_blob: &str) {
let key = Self::key(path, our_blob, their_blob);
self.entries.insert(key, ResolutionEntry {
path: path.to_string(),
our_blob: our_blob.to_string(),
their_blob: their_blob.to_string(),
resolved_blob: resolved_blob.to_string(),
});
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub async fn load(path: &Path) -> Result<Self> {
if !path.exists() {
return Ok(Self::default());
}
let data = tokio::fs::read_to_string(path)
.await
.with_context(|| format!("Failed to read resolution cache: {:?}", path))?;
if data.trim().is_empty() {
return Ok(Self::default());
}
serde_json::from_str(&data)
.with_context(|| format!("Failed to parse resolution cache: {:?}", path))
}
pub async fn save(&self, path: &Path) -> Result<()> {
let data = serde_json::to_string_pretty(self)
.context("Failed to serialize resolution cache")?;
crate::atomic::write_atomic(path, data.as_bytes())
.with_context(|| format!("Failed to write resolution cache: {:?}", path))?;
Ok(())
}
fn key(path: &str, our_blob: &str, their_blob: &str) -> String {
format!("{}:{}:{}", path, our_blob, their_blob)
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PendingResolution {
pub branch: String,
pub base_branch: String,
pub conflicts: Vec<ConflictInfo>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConflictInfo {
pub path: String,
pub our_blob: String,
pub their_blob: String,
}
impl PendingResolution {
pub async fn load(path: &Path) -> Result<Option<Self>> {
if !path.exists() {
return Ok(None);
}
let data = tokio::fs::read_to_string(path)
.await
.with_context(|| format!("Failed to read pending resolution: {:?}", path))?;
if data.trim().is_empty() {
return Ok(None);
}
let pending: Self = serde_json::from_str(&data)
.with_context(|| format!("Failed to parse pending resolution: {:?}", path))?;
Ok(Some(pending))
}
pub async fn save(&self, path: &Path) -> Result<()> {
let data = serde_json::to_string_pretty(self)
.context("Failed to serialize pending resolution")?;
crate::atomic::write_atomic(path, data.as_bytes())
.with_context(|| format!("Failed to write pending resolution: {:?}", path))?;
Ok(())
}
pub async fn clear(path: &Path) -> Result<()> {
if path.exists() {
tokio::fs::remove_file(path)
.await
.with_context(|| format!("Failed to remove pending resolution: {:?}", path))?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_cache_set_get() {
let mut cache = ResolutionCache::default();
assert!(cache.get("src/main.rs", "abc", "def").is_none());
cache.set("src/main.rs", "abc", "def", "resolved123");
assert_eq!(cache.get("src/main.rs", "abc", "def"), Some("resolved123"));
assert!(cache.get("src/main.rs", "abc", "xyz").is_none());
assert!(cache.get("src/other.rs", "abc", "def").is_none());
}
#[test]
fn test_cache_len() {
let mut cache = ResolutionCache::default();
assert!(cache.is_empty());
cache.set("a.rs", "1", "2", "3");
cache.set("b.rs", "4", "5", "6");
assert_eq!(cache.len(), 2);
}
#[tokio::test]
async fn test_cache_save_and_load() -> Result<()> {
let temp = tempfile::TempDir::new()?;
let path = temp.path().join("resolutions.json");
let mut cache = ResolutionCache::default();
cache.set("file.rs", "blob_a", "blob_b", "blob_r");
cache.save(&path).await?;
let loaded = ResolutionCache::load(&path).await?;
assert_eq!(loaded.get("file.rs", "blob_a", "blob_b"), Some("blob_r"));
assert_eq!(loaded.len(), 1);
Ok(())
}
#[tokio::test]
async fn test_cache_load_nonexistent() -> Result<()> {
let temp = tempfile::TempDir::new()?;
let path = temp.path().join("nonexistent.json");
let cache = ResolutionCache::load(&path).await?;
assert!(cache.is_empty());
Ok(())
}
#[tokio::test]
async fn test_pending_resolution_save_load_clear() -> Result<()> {
let temp = tempfile::TempDir::new()?;
let path = temp.path().join("pending.json");
let pending = PendingResolution {
branch: "feature".to_string(),
base_branch: "main".to_string(),
conflicts: vec![ConflictInfo {
path: "src/main.rs".to_string(),
our_blob: "abc".to_string(),
their_blob: "def".to_string(),
}],
};
pending.save(&path).await?;
let loaded = PendingResolution::load(&path).await?;
assert!(loaded.is_some());
let loaded = loaded.unwrap();
assert_eq!(loaded.branch, "feature");
assert_eq!(loaded.conflicts.len(), 1);
assert_eq!(loaded.conflicts[0].path, "src/main.rs");
PendingResolution::clear(&path).await?;
let after_clear = PendingResolution::load(&path).await?;
assert!(after_clear.is_none());
Ok(())
}
}