use std::cell::RefCell;
use std::collections::HashMap;
use std::fs::{File, OpenOptions};
use std::io;
use std::path::{Path, PathBuf};
thread_local! {
static HELD: RefCell<HashMap<PathBuf, (File, usize)>> = RefCell::new(HashMap::new());
}
fn nest(path: &Path) -> bool {
HELD.with(|held| {
if let Some((_, count)) = held.borrow_mut().get_mut(path) {
*count += 1;
true
} else {
false
}
})
}
fn open(path: &Path) -> io::Result<File> {
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)?;
let gitignore = dir.join(".gitignore");
if !gitignore.exists() {
let _ = std::fs::write(&gitignore, "*\n");
}
}
OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(path)
}
pub(crate) fn acquire(path: &Path) -> io::Result<()> {
if nest(path) {
return Ok(());
}
let file = open(path)?;
file.lock()?;
HELD.with(|held| held.borrow_mut().insert(path.to_path_buf(), (file, 1)));
Ok(())
}
pub(crate) fn try_acquire(path: &Path) -> io::Result<bool> {
if nest(path) {
return Ok(true);
}
let file = open(path)?;
match file.try_lock() {
Ok(()) => {
HELD.with(|held| held.borrow_mut().insert(path.to_path_buf(), (file, 1)));
Ok(true)
}
Err(std::fs::TryLockError::WouldBlock) => Ok(false),
Err(std::fs::TryLockError::Error(e)) => Err(e),
}
}
pub(crate) fn holds_another(path: &Path) -> bool {
HELD.with(|held| {
let held = held.borrow();
!held.is_empty() && !held.contains_key(path)
})
}
pub(crate) fn release(path: &Path) {
HELD.with(|held| {
let mut held = held.borrow_mut();
let last = match held.get_mut(path) {
Some((_, count)) => {
*count -= 1;
*count == 0
}
None => false,
};
if last && let Some((file, _)) = held.remove(path) {
let _ = file.unlock();
}
});
}