use std::fs::{self, File, TryLockError};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use super::files::COUNTER;
use crate::store::fileio::{private, private_mkdir, remove_file};
const LOCK: &str = ".lock";
pub struct Lock {
_file: File,
directory: PathBuf,
}
pub fn try_lock(directory: &Path) -> io::Result<Option<Lock>> {
private_mkdir(directory)?;
let path = directory.join(LOCK);
let mut file = private().read(true).write(true).create(true).open(&path)?;
if file.metadata()?.len() == 0 {
file.write_all(b"\0")?;
}
match file.try_lock() {
Ok(()) => {}
Err(TryLockError::WouldBlock) => return Ok(None),
Err(TryLockError::Error(error)) => return Err(error),
}
if !same_file(&file, &path)? {
return Ok(None);
}
Ok(Some(Lock {
_file: file,
directory: directory.to_path_buf(),
}))
}
pub fn tidy(lock: Lock) -> io::Result<()> {
if cfg!(windows) {
return Ok(());
}
let mut counted = false;
for entry in fs::read_dir(&lock.directory)? {
let name = entry?.file_name();
counted |= name == COUNTER;
if name != LOCK && name != COUNTER {
return Ok(());
}
}
if counted {
remove_file(&lock.directory.join(COUNTER))?;
}
remove_file(&lock.directory.join(LOCK))?;
match fs::remove_dir(&lock.directory) {
Err(error)
if !matches!(
error.kind(),
io::ErrorKind::NotFound | io::ErrorKind::DirectoryNotEmpty
) =>
{
Err(error)
}
_ => Ok(()),
}
}
#[cfg(unix)]
fn same_file(file: &File, path: &Path) -> io::Result<bool> {
use std::os::unix::fs::MetadataExt;
let held = file.metadata()?;
match fs::metadata(path) {
Ok(now) => Ok(held.dev() == now.dev() && held.ino() == now.ino()),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
Err(error) => Err(error),
}
}
#[cfg(not(unix))]
fn same_file(_: &File, _: &Path) -> io::Result<bool> {
Ok(true)
}