use std::path::Path;
pub(crate) struct FileLock {
#[cfg(unix)]
_file: std::fs::File,
}
impl FileLock {
#[cfg(unix)]
pub(crate) fn acquire(target: &Path) -> std::io::Result<Self> {
use std::os::unix::io::AsRawFd;
let mut lock_path = target.as_os_str().to_os_string();
lock_path.push(".lock");
let lock_path = std::path::PathBuf::from(lock_path);
if let Some(parent) = lock_path.parent() {
std::fs::create_dir_all(parent)?;
}
let file = std::fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(&lock_path)?;
if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX) } != 0 {
return Err(std::io::Error::last_os_error());
}
Ok(Self { _file: file })
}
#[cfg(not(unix))]
pub(crate) fn acquire(_target: &Path) -> std::io::Result<Self> {
Ok(Self {})
}
}