1mod lock_guard;
2mod lock_path;
3#[cfg(test)]
4mod tests;
5
6pub use crate::lock_guard::LockGuard;
7pub use crate::lock_path::LockPath;
8use fs2::FileExt;
9use std::fs::{File, OpenOptions};
10use std::path::{Path, PathBuf};
11
12pub type Result<T> = std::io::Result<T>;
13
14pub fn lock<P: AsRef<Path>>(file_path: &LockPath<P>) -> Result<LockGuard> {
18 let lock_file = open_file_for_locking(file_path.to_path_buf())?;
19 lock_file.lock_exclusive()?;
20
21 Ok(lock_file.into())
22}
23
24pub fn try_lock<P: AsRef<Path>>(file_path: &LockPath<P>) -> Result<LockGuard> {
28 let lock_file = open_file_for_locking(file_path.to_path_buf())?;
29 lock_file.try_lock_exclusive()?;
30
31 Ok(lock_file.into())
32}
33
34fn open_file_for_locking(file_path: PathBuf) -> Result<File> {
35 let lock_file: File = OpenOptions::new()
36 .write(true)
37 .create(true)
38 .open(file_path)?;
39
40 Ok(lock_file)
41}