Skip to content
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: 56 additions & 3 deletions crates/uv-fs/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use fs2::FileExt;
use std::fmt::Display;
use std::path::{Path, PathBuf};

use fs2::FileExt;
use tempfile::NamedTempFile;
use tracing::{debug, error, info, trace, warn};

Expand Down Expand Up @@ -599,7 +600,7 @@ impl LockedFile {
path: impl AsRef<Path>,
resource: impl Display,
) -> Result<Self, std::io::Error> {
let file = fs_err::File::create(path.as_ref())?;
let file = Self::create(path)?;
let resource = resource.to_string();
Self::lock_file_blocking(file, &resource)
}
Expand All @@ -610,10 +611,62 @@ impl LockedFile {
path: impl AsRef<Path>,
resource: impl Display,
) -> Result<Self, std::io::Error> {
let file = fs_err::File::create(path.as_ref())?;
let file = Self::create(path)?;
let resource = resource.to_string();
tokio::task::spawn_blocking(move || Self::lock_file_blocking(file, &resource)).await?
}

#[cfg(unix)]
fn create(path: impl AsRef<Path>) -> Result<fs_err::File, std::io::Error> {
use std::os::unix::fs::PermissionsExt;

// If path already exists, return it.
if let Ok(file) = fs_err::OpenOptions::new()
.read(true)
.write(true)
.open(path.as_ref())
{
return Ok(file);
}

// Otherwise, create a temporary file with 777 permissions. We must set
// permissions _after_ creating the file, to override the `umask`.
let file = if let Some(parent) = path.as_ref().parent() {
NamedTempFile::new_in(parent)?
} else {
NamedTempFile::new()?
};
if let Err(err) = file
.as_file()
.set_permissions(std::fs::Permissions::from_mode(0o777))
{
warn!("Failed to set permissions on temporary file: {err}");
}

// Try to move the file to path, but if path exists now, just open path
match file.persist_noclobber(path.as_ref()) {
Ok(file) => Ok(fs_err::File::from_parts(file, path.as_ref())),
Err(err) => {
if err.error.kind() == std::io::ErrorKind::AlreadyExists {
fs_err::OpenOptions::new()
.read(true)
.write(true)
.open(path.as_ref())
} else {
Err(err.error)
}
}
}
}

#[cfg(not(unix))]
fn create(path: impl AsRef<Path>) -> std::io::Result<fs_err::File> {
fs_err::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(path.as_ref())
}
}

impl Drop for LockedFile {
Expand Down