1use anyhow::Result;
2use nils_common::fs as shared_fs;
3use std::io;
4use std::path::Path;
5
6pub const SECRET_FILE_MODE: u32 = shared_fs::SECRET_FILE_MODE;
7
8pub fn sha256_file(path: &Path) -> Result<String> {
9 match shared_fs::sha256_file(path) {
10 Ok(hash) => Ok(hash),
11 Err(shared_fs::FileHashError::OpenFile { source, .. }) => Err(anyhow::Error::new(source)
12 .context(format!("failed to open for sha256: {}", path.display()))),
13 Err(shared_fs::FileHashError::ReadFile { source, .. }) => Err(source.into()),
14 }
15}
16
17pub fn write_atomic(path: &Path, contents: &[u8], mode: u32) -> Result<()> {
18 shared_fs::write_atomic(path, contents, mode).map_err(map_atomic_write_error)
19}
20
21pub fn write_timestamp(path: &Path, iso: Option<&str>) -> Result<()> {
22 match shared_fs::write_timestamp(path, iso) {
23 Ok(()) => Ok(()),
24 Err(shared_fs::TimestampError::CreateParentDir { path, source }) => {
25 Err(anyhow::Error::new(source)
26 .context(format!("failed to create dir: {}", path.display())))
27 }
28 Err(shared_fs::TimestampError::WriteFile { path, source }) => {
29 Err(anyhow::Error::new(source)
30 .context(format!("failed to write timestamp: {}", path.display())))
31 }
32 Err(shared_fs::TimestampError::RemoveFile { .. }) => Ok(()),
33 }
34}
35
36fn map_atomic_write_error(err: shared_fs::AtomicWriteError) -> anyhow::Error {
37 match err {
38 shared_fs::AtomicWriteError::CreateParentDir { path, source } => {
39 anyhow::Error::new(source).context(format!("failed to create dir: {}", path.display()))
40 }
41 shared_fs::AtomicWriteError::CreateTempFile { source, .. } => {
42 anyhow::Error::new(source).context("failed to create temp file")
43 }
44 shared_fs::AtomicWriteError::TempPathExhausted { .. } => anyhow::Error::new(
45 io::Error::new(io::ErrorKind::AlreadyExists, "temp file already exists"),
46 )
47 .context("failed to create unique temp file"),
48 shared_fs::AtomicWriteError::WriteTempFile { path, source } => anyhow::Error::new(source)
49 .context(format!("failed to write temp file: {}", path.display())),
50 shared_fs::AtomicWriteError::SetPermissions { path, source } => anyhow::Error::new(source)
51 .context(format!("failed to set permissions: {}", path.display())),
52 shared_fs::AtomicWriteError::ReplaceFile { from, to, source } => anyhow::Error::new(source)
53 .context(format!(
54 "failed to rename {} -> {}",
55 from.display(),
56 to.display()
57 )),
58 }
59}