Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add AsyncFileLockGuard #844

Merged
merged 1 commit into from
Nov 16, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading