use std::collections::{HashMap, HashSet};
use std::sync::{Arc, Mutex};
use super::key_generator::CacheKeyGenerator;
use crate::remote::models::{
cached_repo::CachedRepository, repo_config::RepositoryConfiguration,
wire_operation::WireOperation,
};
type CacheKey = String;
#[derive(Default)]
pub struct CacheManager {
cache: Arc<Mutex<HashMap<CacheKey, CachedRepository>>>,
}
impl CacheManager {
pub fn new() -> Self {
Self {
cache: Arc::new(Mutex::new(HashMap::new())),
}
}
pub fn get_or_schedule_fetch(
&self,
config: &RepositoryConfiguration,
) -> Result<String, String> {
let key = CacheKeyGenerator::generate_key(config);
let mut cache = self
.cache
.lock()
.expect("Failed to lock cache mutex, likely due to a poisoned mutex (another thread panicked while holding the lock)");
if let Some(cached_repo) = cache.get(&key) {
Ok(cached_repo.local_cache_path.clone())
} else {
let cache_path = Self::get_cache_path(&key)?;
let new_cached_repo = CachedRepository::new(
config.url.clone(),
config.branch.clone(),
cache_path.clone(),
"placeholder_commit_hash".to_string(), );
cache.insert(key, new_cached_repo);
Ok(cache_path)
}
}
fn get_cache_path(key: &str) -> Result<String, String> {
let cache_dir = std::env::temp_dir().join("git-wire-cache").join(key);
std::fs::create_dir_all(&cache_dir)
.map_err(|e| format!("Failed to create cache directory: {e}"))?;
Ok(cache_dir.to_string_lossy().to_string())
}
pub fn plan_fetch_operations(
&self,
configs: &[RepositoryConfiguration],
) -> Result<(Vec<RepositoryConfiguration>, Vec<WireOperation>), String> {
let mut unique_configs: Vec<RepositoryConfiguration> = Vec::new();
let mut seen_keys: HashSet<String> = HashSet::new();
let mut operations: Vec<WireOperation> = Vec::new();
for config in configs {
let key = CacheKeyGenerator::generate_key(config);
if !seen_keys.contains(&key) {
unique_configs.push(config.clone());
seen_keys.insert(key);
}
let cached_path = self.get_or_schedule_fetch(config)?;
operations.push(WireOperation::new(config.clone(), cached_path));
}
Ok((unique_configs, operations))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_cache_manager_creation() {
let cache_manager = CacheManager::new();
assert_eq!(
cache_manager
.cache
.lock()
.expect("Failed to lock cache in test")
.len(),
0
);
}
#[test]
fn test_get_or_schedule_fetch_new_repo() {
let cache_manager = CacheManager::new();
let config = RepositoryConfiguration::new(
"https://github.com/example/repo.git".to_string(),
"main".to_string(),
"./src/module1".to_string(),
vec!["src/".to_string()],
None,
None,
);
let result = cache_manager.get_or_schedule_fetch(&config);
assert!(result.is_ok());
let key = CacheKeyGenerator::generate_key(&config);
let cache = cache_manager
.cache
.lock()
.expect("Failed to lock cache in test");
assert!(cache.contains_key(&key));
}
#[test]
fn test_plan_fetch_operations_with_duplicates() {
let cache_manager = CacheManager::new();
let configs = vec![
RepositoryConfiguration::new(
"https://github.com/example/repo.git".to_string(),
"main".to_string(),
"./src/module1".to_string(),
vec!["src/".to_string(), "lib/".to_string()],
None,
None,
),
RepositoryConfiguration::new(
"https://github.com/example/repo.git".to_string(), "main".to_string(),
"./src/module2".to_string(),
vec!["utils/".to_string()],
None,
None,
),
RepositoryConfiguration::new(
"https://github.com/other/repo.git".to_string(), "main".to_string(),
"./src/module3".to_string(),
vec!["docs/".to_string()],
None,
None,
),
];
let (unique_configs, operations) = cache_manager
.plan_fetch_operations(&configs)
.expect("Failed to plan fetch operations");
assert_eq!(unique_configs.len(), 2);
assert_eq!(operations.len(), 3);
}
}