use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use git_lfs_api::Lock;
pub fn cache_path(cwd: &Path) -> Result<PathBuf, git_lfs_git::Error> {
Ok(git_lfs_git::lfs_dir(cwd)?.join("cache").join("locks.json"))
}
pub fn read(cwd: &Path) -> Vec<Lock> {
let Ok(path) = cache_path(cwd) else {
return Vec::new();
};
let bytes = match fs::read(&path) {
Ok(b) => b,
Err(_) => return Vec::new(),
};
serde_json::from_slice::<Vec<Lock>>(&bytes).unwrap_or_default()
}
pub fn add(cwd: &Path, lock: &Lock) {
let Ok(path) = cache_path(cwd) else {
return;
};
let mut locks = read(cwd);
locks.retain(|l| l.id != lock.id);
locks.push(lock.clone());
let _ = write(&path, &locks);
}
pub fn remove_by_id(cwd: &Path, id: &str) {
let Ok(path) = cache_path(cwd) else {
return;
};
let mut locks = read(cwd);
let before = locks.len();
locks.retain(|l| l.id != id);
if locks.len() == before {
return;
}
let _ = write(&path, &locks);
}
pub fn remove_by_path(cwd: &Path, repo_relative_path: &str) {
let Ok(file) = cache_path(cwd) else {
return;
};
let mut locks = read(cwd);
let before = locks.len();
locks.retain(|l| l.path != repo_relative_path);
if locks.len() == before {
return;
}
let _ = write(&file, &locks);
}
fn write(path: &Path, locks: &[Lock]) -> io::Result<()> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let bytes = serde_json::to_vec(locks).map_err(io::Error::other)?;
fs::write(path, bytes)
}