capri-core: add fsutil module

This commit is contained in:
nocode committed 2026-11-11 20:20:47 +01:00
1 parent 7dc065a9e7
commit 92f136a344
1 file changed
+70
+70
View File
@@ -0,0 +1,70 @@
use std::fs::{self, File, OpenOptions};
use std::io::Write;
use std::os::unix::fs::OpenOptionsExt;
use std::path::Path;
use anyhow::{bail, Context, Result};
/// Writes `bytes` to `path` atomically: private temp file (0600, create_new), fsync, rename, fsync dir.
pub fn write_atomic(path: &Path, bytes: &[u8]) -> Result<()> {
let dir = path.parent().context("Path has no parent")?;
let name = path.file_name().context("Path has no file name")?.to_string_lossy();
let tmp = dir.join(format!(".{name}.{}.tmp", uuid::Uuid::new_v4()));
let result = (|| -> Result<()> {
let mut file = OpenOptions::new().write(true).create_new(true).mode(0o600).open(&tmp)?;
file.write_all(bytes)?;
file.sync_all()?;
fs::rename(&tmp, path)?;
File::open(dir)?.sync_all()?;
Ok(())
})();
if result.is_err() {
let _ = fs::remove_file(&tmp);
}
result.with_context(|| format!("Cannot write {}", path.display()))
}
pub fn write_json_atomic<T: serde::Serialize>(path: &Path, value: &T) -> Result<()> {
let mut bytes = serde_json::to_vec_pretty(value)?;
bytes.push(b'\n');
write_atomic(path, &bytes)
}
/// Reads a regular, non-symlink file of at most `max` bytes. `Ok(None)` when it does not exist.
pub fn read_regular(path: &Path, max: u64) -> Result<Option<Vec<u8>>> {
let meta = match fs::symlink_metadata(path) {
Ok(meta) => meta,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(e.into()),
};
if !meta.file_type().is_file() {
bail!("{} is not a regular file", path.display());
}
if meta.len() > max {
bail!("{} exceeds {max} bytes", path.display());
}
let file = OpenOptions::new().read(true).custom_flags(libc::O_NOFOLLOW).open(path)?;
let mut bytes = Vec::with_capacity(meta.len() as usize);
std::io::Read::read_to_end(&mut std::io::Read::take(file, max + 1), &mut bytes)?;
if bytes.len() as u64 > max {
bail!("{} exceeds {max} bytes", path.display());
}
Ok(Some(bytes))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn atomic_write_then_read() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("a.json");
write_atomic(&path, b"hello").unwrap();
assert_eq!(read_regular(&path, 10).unwrap().unwrap(), b"hello");
assert!(read_regular(&path, 2).is_err());
assert!(read_regular(&dir.path().join("missing"), 10).unwrap().is_none());
std::os::unix::fs::symlink(&path, dir.path().join("link")).unwrap();
assert!(read_regular(&dir.path().join("link"), 10).is_err());
}
}