use fs2::FileExt;
use std::fs::{File, OpenOptions};
use std::path::{Path, PathBuf};
const LOCK_FILENAME: &str = "mnemoria.lock";
pub struct FileLock {
lock_path: PathBuf,
}
pub struct FileLockGuard {
_file: File,
}
impl Drop for FileLockGuard {
fn drop(&mut self) {
let _ = self._file.unlock();
}
}
impl FileLock {
pub fn new(base_path: &Path) -> Result<Self, crate::Error> {
let lock_path = base_path.join(LOCK_FILENAME);
let _file = OpenOptions::new()
.create(true)
.write(true)
.truncate(false)
.open(&lock_path)?;
Ok(Self { lock_path })
}
pub fn lock_exclusive(&self) -> Result<FileLockGuard, crate::Error> {
let file = File::open(&self.lock_path)?;
file.lock_exclusive()?;
Ok(FileLockGuard { _file: file })
}
pub fn lock_shared(&self) -> Result<FileLockGuard, crate::Error> {
let file = File::open(&self.lock_path)?;
file.lock_shared()?;
Ok(FileLockGuard { _file: file })
}
}