Skip to content
Merged
Show file tree
Hide file tree
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
4 changes: 1 addition & 3 deletions crates/paths/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ chrono = { workspace = true, features = ["now"] }
fs2.workspace = true
itoa.workspace = true
serde.workspace = true
tempfile.workspace = true
thiserror.workspace = true

[target.'cfg(windows)'.dependencies]
Expand All @@ -21,8 +22,5 @@ junction.workspace = true
[target.'cfg(not(windows))'.dependencies]
xdg.workspace = true

[dev-dependencies]
tempfile.workspace = true

[lints]
workspace = true
2 changes: 2 additions & 0 deletions crates/paths/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,8 @@ mod utils;

#[doc(hidden)]
pub use serde as __serde;
#[doc(hidden)]
pub use tempfile as __tempfile;

/// Implemented for path types. Use `from_path_unchecked()` to construct a strongly-typed
/// path directly from a `PathBuf`.
Expand Down
21 changes: 19 additions & 2 deletions crates/paths/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,25 @@ macro_rules! path_type {
}

pub fn write(&self, contents: impl AsRef<[u8]>) -> std::io::Result<()> {
self.create_parent()?;
std::fs::write(self, contents)
use std::io::Write as _;

let path = &self.0;
let parent = path.parent().ok_or_else(||
std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!("cannot replace {} without enclosing directory", path.display()))
)?;
std::fs::create_dir_all(&parent)?;

let mut tmp = $crate::__tempfile::NamedTempFile::new_in(parent)?;
tmp.write_all(contents.as_ref())?;
tmp.as_file().sync_all()?;
tmp.persist(&path)?;
// On Windows, syncing the directory is not necessary and doesn't even work.
#[cfg(not(target_os = "windows"))]
std::fs::File::open(parent)?.sync_all()?;

Ok(())
}

/// Opens a file at this path with the given options, ensuring its parent directory exists.
Expand Down
Loading