use std::fs;
use std::fs::OpenOptions;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::process;
#[derive(Debug)]
pub struct LockFile {
path: PathBuf,
}
impl LockFile {
pub fn new<P>(
path: P,
lockfile_contents: Option<&[u8]>,
) -> io::Result<LockFile>
where
P: AsRef<Path>,
{
{
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.open(path.as_ref())?;
if let Some(contents) = lockfile_contents {
file.write_all(contents)?;
}
}
debug!(
"Successfully wrote lockfile {:?}, pid: {}",
path.as_ref(),
process::id()
);
Ok(LockFile {
path: path.as_ref().to_path_buf(),
})
}
}
impl Drop for LockFile {
fn drop(&mut self) {
debug!("Removing lockfile {:?}, pid: {}", &self.path, process::id());
fs::remove_file(&self.path).unwrap();
}
}