use std::fs::{File, OpenOptions, TryLockError};
use std::io::{self, Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
pub const LOCK_FILE: &str = "plm.lock";
#[derive(Debug)]
pub struct DirLock {
path: PathBuf,
_file: File,
}
impl DirLock {
pub fn acquire(root: &Path) -> io::Result<DirLock> {
std::fs::create_dir_all(root)?;
let path = root.join(LOCK_FILE);
let mut file = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(&path)?;
match file.try_lock() {
Ok(()) => {}
Err(TryLockError::WouldBlock) => {
let mut text = String::new();
let _ = file.read_to_string(&mut text);
let holder = match text.trim() {
"" => "another process".to_string(),
pid => format!("another brep-plm process (pid {pid})"),
};
return Err(io::Error::new(
io::ErrorKind::ResourceBusy,
format!(
"{} is in use by {holder} — stop that server first, or give this one a different --data",
root.display()
),
));
}
Err(TryLockError::Error(error)) => return Err(error),
}
file.set_len(0)?;
file.seek(SeekFrom::Start(0))?;
writeln!(file, "{}", std::process::id())?;
file.flush()?;
Ok(DirLock { path, _file: file })
}
pub fn path(&self) -> &Path {
&self.path
}
}
impl Drop for DirLock {
fn drop(&mut self) {
let _ = self._file.unlock();
}
}