Skip to content

Commit

Permalink
Add AsyncFileLockGuard
Browse files Browse the repository at this point in the history
This data structure will be later used in Tokio-based code which writes to the file protected by this guard.

Signed-off-by: Marek Kaput <marek.kaput@swmansion.com>

commit-id:ebda97d6
  • Loading branch information
mkaput committed Nov 9, 2023
1 parent ec27844 commit e16fa52
Showing 1 changed file with 59 additions and 0 deletions.
59 changes: 59 additions & 0 deletions scarb/src/flock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use std::{fmt, io};

use anyhow::{ensure, Context, Result};
use camino::{Utf8Path, Utf8PathBuf};
use fs4::tokio::AsyncFileExt;
use fs4::{lock_contended_error, FileExt};
use tokio::sync::Mutex;

Expand Down Expand Up @@ -51,6 +52,14 @@ impl FileLockGuard {
self.path = to;
Ok(self)
}

pub fn into_async(mut self) -> AsyncFileLockGuard {
AsyncFileLockGuard {
file: self.file.take().map(tokio::fs::File::from_std),
path: std::mem::take(&mut self.path),
lock_kind: self.lock_kind,
}
}
}

impl Deref for FileLockGuard {
Expand All @@ -75,6 +84,56 @@ impl Drop for FileLockGuard {
}
}

#[derive(Debug)]
pub struct AsyncFileLockGuard {
file: Option<tokio::fs::File>,
path: Utf8PathBuf,
lock_kind: FileLockKind,
}

impl AsyncFileLockGuard {
pub fn path(&self) -> &Utf8Path {
self.path.as_path()
}

pub fn lock_kind(&self) -> FileLockKind {
self.lock_kind
}

pub async fn into_sync(mut self) -> FileLockGuard {
FileLockGuard {
file: match self.file.take() {
None => None,
Some(file) => Some(file.into_std().await),
},
path: std::mem::take(&mut self.path),
lock_kind: self.lock_kind,
}
}
}

impl Deref for AsyncFileLockGuard {
type Target = tokio::fs::File;

fn deref(&self) -> &Self::Target {
self.file.as_ref().unwrap()
}
}

impl DerefMut for AsyncFileLockGuard {
fn deref_mut(&mut self) -> &mut Self::Target {
self.file.as_mut().unwrap()
}
}

impl Drop for AsyncFileLockGuard {
fn drop(&mut self) {
if let Some(file) = self.file.take() {
let _ = file.unlock();
}
}
}

/// An exclusive lock over a global entity identified by a path within a [`Filesystem`].
pub struct AdvisoryLock<'f> {
path: Utf8PathBuf,
Expand Down

0 comments on commit e16fa52

Please sign in to comment.