Skip to main content

capsule_library/utils/
paths.rs

1//! Path helpers with no knowledge of the library layout.
2//!
3//! [`tmp_path`] lives here rather than beside the library's own path helpers because it encodes
4//! no layout at all — it appends `.tmp` to whatever it is given. Keeping it here lets
5//! [`capsule_core::sidecar`] do atomic writes without importing `library`, which was the one real
6//! `sidecar -> library` edge (the rest of that pair is rustdoc links).
7
8use std::path::{Path, PathBuf};
9
10/// Make a directory entry durable: `fsync` the directory so a `rename`, `mkdir`, or newly
11/// created file inside it survives a crash that happens after the call returned. The partner
12/// of [`tmp_path`]'s write-then-rename.
13///
14/// A Unix primitive: on other platforms this is a documented no-op rather than a failure (a
15/// directory cannot be opened as a file there), mirroring `capsule-server`'s blob store.
16#[cfg(unix)]
17pub(crate) fn sync_dir(path: &Path) -> std::io::Result<()> {
18    std::fs::File::open(path)?.sync_all()
19}
20
21/// No-op: fsyncing a directory is a Unix primitive. See the Unix variant.
22#[cfg(not(unix))]
23pub(crate) fn sync_dir(_path: &Path) -> std::io::Result<()> {
24    Ok(())
25}
26
27/// Appends `.tmp` to any path.
28///
29/// The write-then-rename partner for atomic file replacement: write to `tmp_path(p)`, fsync,
30/// then rename onto `p` so a reader never observes a half-written file.
31#[must_use]
32pub fn tmp_path(path: &Path) -> PathBuf {
33    let mut s = path.as_os_str().to_owned();
34    s.push(".tmp");
35    PathBuf::from(s)
36}
37
38#[cfg(test)]
39mod tests;