INNER CODE UNIT · Rust
file_lock
kubie-org/kubie · src/ioutil.rs:64
pub fn file_lock<P, F, T>(path: P, scope: F) -> Result<T, anyhow::Error>
where
P: AsRef<Path>,
F: FnOnce() -> Result<T, anyhow::Error> + UnwindSafe,
{
let path = path.as_ref();
let file = OpenOptions::new()
.append(true)
.truncate(false)
.read(true)
.create(true)
.open(path)
.with_context(|| format!("Could not open lock file at {}", path.display()))?;
file.lock_exclusive()
.with_context(|| format!("Could not lock file at {}", path.display()))?;
// Run the given closure, but catch any panics so we can unlock before resuming the panic.