From 644c70819f1bf7202815492d3c8e9ee62aeaf0b9 Mon Sep 17 00:00:00 2001 From: Jiahao XU <30436523+NobodyXu@users.noreply.github.com> Date: Sat, 22 Feb 2025 22:24:40 +1100 Subject: [PATCH] Add FileLock::set_file_path Signed-off-by: Jiahao XU <30436523+NobodyXu@users.noreply.github.com> --- crates/fs-lock/src/lib.rs | 29 ++++++++++++++++++++++++----- 1 file changed, 24 insertions(+), 5 deletions(-) diff --git a/crates/fs-lock/src/lib.rs b/crates/fs-lock/src/lib.rs index a8931dd0..9a0b3010 100644 --- a/crates/fs-lock/src/lib.rs +++ b/crates/fs-lock/src/lib.rs @@ -12,16 +12,28 @@ use fs4::fs_std::FileExt; /// A locked file. #[derive(Debug)] -pub struct FileLock(File, Option>); +pub struct FileLock( + File, + #[cfg(feature = "tracing")] + Option>, +); impl FileLock { + fn new(file: File) -> Self { + Self( + file, + #[cfg(feature = "tracing")] + None, + ) + } + /// Take an exclusive lock on a [`File`]. /// /// Note that this operation is blocking, and should not be called in async contexts. pub fn new_exclusive(file: File) -> io::Result { FileExt::lock_exclusive(&file)?; - Ok(Self(file, None)) + Ok(Self:new(file)) } /// Try to take an exclusive lock on a [`File`]. @@ -33,7 +45,7 @@ impl FileLock { /// Note that this operation is blocking, and should not be called in async contexts. pub fn new_try_exclusive(file: File) -> Result)> { match FileExt::try_lock_exclusive(&file) { - Ok(()) => Ok(Self(file, None)), + Ok(()) => Ok(Self::new(file)), Err(e) if e.raw_os_error() == fs4::lock_contended_error().raw_os_error() => { Err((file, None)) } @@ -47,7 +59,7 @@ impl FileLock { pub fn new_shared(file: File) -> io::Result { FileExt::lock_shared(&file)?; - Ok(Self(file, None)) + Ok(Self::new(file)) } /// Try to take a shared lock on a [`File`]. @@ -59,13 +71,20 @@ impl FileLock { /// Note that this operation is blocking, and should not be called in async contexts. pub fn new_try_shared(file: File) -> Result)> { match FileExt::try_lock_shared(&file) { - Ok(()) => Ok(Self(file, None)), + Ok(()) => Ok(Self::new(file)), Err(e) if e.raw_os_error() == fs4::lock_contended_error().raw_os_error() => { Err((file, None)) } Err(e) => Err((file, Some(e))), } } + + /// Set path to the file for logging on unlock error, if feature tracing is enabled + pub fn set_file_path(mut self, path: impl Into>) -> Self { + #[cfg(feature = "tracing")] + self.1 = Some(path.into()); + self + } } impl Drop for FileLock {