Skip to main content

rigspark_cli/
maintenance_file.rs

1//! Safe read/replace/create of maintenance data files (catalogs, evidence, state).
2
3use rigspark_runtime::secure_fs::Directory;
4use std::{
5    io,
6    path::{Path, PathBuf},
7};
8
9const MAX_FILE_BYTES: u64 = 16 * 1024 * 1024;
10
11pub struct File {
12    directory: Directory,
13    name: PathBuf,
14}
15impl File {
16    pub fn open(path: &Path) -> io::Result<Self> {
17        let path = std::path::absolute(path)?;
18        let parent = path
19            .parent()
20            .ok_or_else(|| io::Error::other("file parent required"))?
21            .canonicalize()?;
22        let name = PathBuf::from(
23            path.file_name()
24                .ok_or_else(|| io::Error::other("filename required"))?,
25        );
26        Ok(Self {
27            directory: Directory::open(&parent)?,
28            name,
29        })
30    }
31    pub fn read(&self) -> io::Result<Vec<u8>> {
32        self.directory.read(&self.name, MAX_FILE_BYTES, false)
33    }
34    pub fn read_optional(&self) -> io::Result<Option<Vec<u8>>> {
35        match self.read() {
36            Ok(bytes) => Ok(Some(bytes)),
37            Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
38            Err(error) => Err(error),
39        }
40    }
41    /// Replaces the file in place, or creates it on the first run.
42    pub fn write_json(&self, value: &impl serde::Serialize, exists: bool) -> io::Result<()> {
43        let encoded = format!(
44            "{}\n",
45            serde_json::to_string_pretty(value).map_err(io::Error::other)?
46        );
47        self.directory
48            .write(&self.name, encoded.as_bytes(), !exists, exists)
49    }
50    /// Replaces the file in place, or creates it when `exists` is false.
51    pub fn write_bytes(&self, bytes: &[u8], exists: bool) -> io::Result<()> {
52        self.directory.write(&self.name, bytes, !exists, exists)
53    }
54}