use crate::error::{Error, IoContext, Result};
use fs2::FileExt;
use std::fs::{self, File, OpenOptions};
use std::path::{Path, PathBuf};
#[derive(Debug)]
pub struct SingleInstanceLock {
file: File,
path: PathBuf,
}
impl SingleInstanceLock {
pub fn acquire_at(path: &Path) -> Result<Self> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).ctx(|| format!("mkdir -p {}", parent.display()))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = fs::set_permissions(parent, fs::Permissions::from_mode(0o700));
}
}
let file = OpenOptions::new()
.create(true)
.read(true)
.write(true)
.truncate(false)
.open(path)
.ctx(|| format!("open lock {}", path.display()))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = file.set_permissions(fs::Permissions::from_mode(0o600));
}
file.try_lock_exclusive()
.map_err(|_| Error::Locked(format!("lock {}", path.display())))?;
Ok(Self {
file,
path: path.to_path_buf(),
})
}
#[cfg(feature = "standalone")]
#[cfg_attr(docsrs, doc(cfg(feature = "standalone")))]
pub fn acquire(name: &str) -> Result<Self> {
let path = crate::paths::default_lock_dir()?.join(format!("{}.lock", sanitize_name(name)));
Self::acquire_at(&path)
}
pub fn path(&self) -> &Path {
&self.path
}
}
impl Drop for SingleInstanceLock {
fn drop(&mut self) {
let _ = FileExt::unlock(&self.file);
}
}
pub fn sanitize_name(s: &str) -> String {
s.chars()
.map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
.collect()
}