use std::{
collections::BTreeMap,
io::ErrorKind,
path::{Path, PathBuf},
};
pub trait Source {
fn read(&self, path: &Path) -> Result<Option<String>, String>;
}
#[derive(Debug, Clone, Copy, Default)]
pub struct DiskSource;
impl Source for DiskSource {
fn read(&self, path: &Path) -> Result<Option<String>, String> {
match std::fs::read_to_string(path) {
Ok(text) => Ok(Some(text)),
Err(error) if error.kind() == ErrorKind::NotFound => Ok(None),
Err(error) => Err(format!("{}: {error}", path.display())),
}
}
}
#[derive(Debug, Clone, Default)]
pub struct MapSource {
files: BTreeMap<PathBuf, Option<String>>,
}
impl MapSource {
#[must_use]
pub fn new(files: BTreeMap<PathBuf, Option<String>>) -> Self {
Self { files }
}
}
impl Source for MapSource {
fn read(&self, path: &Path) -> Result<Option<String>, String> {
self.files
.get(path)
.cloned()
.ok_or_else(|| format!("{}: not recorded in this plan", path.display()))
}
}