Skip to main content

griz_core/
source.rs

1//! Where the engine reads file text from.
2
3use std::{
4    collections::BTreeMap,
5    io::ErrorKind,
6    path::{Path, PathBuf},
7};
8
9/// Reads the current text of a file, or `None` when it does not exist.
10pub trait Source {
11    /// Reads `path`.
12    ///
13    /// # Errors
14    /// Returns a message when the file exists but cannot be read as UTF-8 text.
15    fn read(&self, path: &Path) -> Result<Option<String>, String>;
16}
17
18/// Reads files from disk.
19#[derive(Debug, Clone, Copy, Default)]
20pub struct DiskSource;
21
22impl Source for DiskSource {
23    fn read(&self, path: &Path) -> Result<Option<String>, String> {
24        match std::fs::read_to_string(path) {
25            Ok(text) => Ok(Some(text)),
26            Err(error) if error.kind() == ErrorKind::NotFound => Ok(None),
27            Err(error) => Err(format!("{}: {error}", path.display())),
28        }
29    }
30}
31
32/// Reads recorded file text, so a plan can be rebuilt against the exact bases
33/// it was first computed from.
34#[derive(Debug, Clone, Default)]
35pub struct MapSource {
36    files: BTreeMap<PathBuf, Option<String>>,
37}
38
39impl MapSource {
40    /// Builds a source from recorded texts; `None` records an absent file.
41    #[must_use]
42    pub fn new(files: BTreeMap<PathBuf, Option<String>>) -> Self {
43        Self { files }
44    }
45}
46
47impl Source for MapSource {
48    fn read(&self, path: &Path) -> Result<Option<String>, String> {
49        self.files
50            .get(path)
51            .cloned()
52            .ok_or_else(|| format!("{}: not recorded in this plan", path.display()))
53    }
54}