use std::collections::HashMap;
use std::sync::{Arc, Mutex};
type RepoUrl = String;
#[derive(Default)]
pub struct RepositoryLockManager {
locks: Arc<Mutex<HashMap<RepoUrl, Arc<Mutex<bool>>>>>,
}
impl RepositoryLockManager {
pub fn new() -> Self {
Self {
locks: Arc::new(Mutex::new(HashMap::new())),
}
}
pub fn acquire_lock(&self, repo_url: &str) -> Result<(), String> {
let mut locks = self
.locks
.lock()
.expect("Failed to acquire global lock for repository locks");
let repo_lock = locks
.entry(repo_url.to_string())
.or_insert_with(|| Arc::new(Mutex::new(false)));
let lock_clone = Arc::clone(repo_lock);
drop(locks);
let guard = lock_clone
.lock()
.unwrap_or_else(|_| panic!("Failed to acquire repository lock for URL: {repo_url}"));
std::mem::drop(guard);
Ok(())
}
pub fn try_acquire_lock(&self, repo_url: &str) -> Result<bool, String> {
let mut locks = self
.locks
.lock()
.expect("Failed to acquire global lock for repository locks");
let repo_lock = locks
.entry(repo_url.to_string())
.or_insert_with(|| Arc::new(Mutex::new(false)));
let lock_clone = Arc::clone(repo_lock);
drop(locks);
match lock_clone.try_lock() {
Ok(guard) => {
std::mem::drop(guard); Ok(true)
}
Err(_) => Ok(false), }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_lock_manager_creation() {
let lock_manager = RepositoryLockManager::new();
assert_eq!(
lock_manager
.locks
.lock()
.expect("Failed to acquire lock on repository locks map")
.len(),
0
);
}
#[test]
fn test_acquire_lock() {
let lock_manager = RepositoryLockManager::new();
let repo_url = "https://github.com/example/repo.git";
let result = lock_manager.acquire_lock(repo_url);
assert!(result.is_ok());
}
#[test]
fn test_try_acquire_lock() {
let lock_manager = RepositoryLockManager::new();
let repo_url = "https://github.com/example/repo.git";
let result = lock_manager.try_acquire_lock(repo_url);
assert!(result.is_ok());
assert!(
result.expect("Failed to unwrap try_acquire_lock result"),
"Expected to acquire lock successfully on first attempt"
);
}
}