1use std::collections::HashMap;
2use std::fs;
3use std::path::{Path, PathBuf};
4
5use anyhow::{Context, Error, Result};
6
7pub trait FileReader {
8 fn read_to_string(&self, file_name: &Path, template_text: &str) -> Result<String>;
9}
10
11#[derive(PartialEq, Eq, Debug, Clone, Default)]
12pub struct SystemFileReader;
13
14#[derive(PartialEq, Eq, Debug, Clone, Default)]
15pub struct TestFileReader {
16 pub captured_contents: HashMap<PathBuf, String>,
17}
18
19impl FileReader for SystemFileReader {
20 fn read_to_string(&self, file_name: &Path, template_text: &str) -> Result<String> {
21 fs::read_to_string(file_name).with_context(|| {
22 format!(
23 "Could not read template file {} ({})",
24 template_text,
25 file_name.display(),
26 )
27 })
28 }
29}
30
31impl From<HashMap<PathBuf, String>> for TestFileReader {
32 fn from(map: HashMap<PathBuf, String>) -> Self {
33 TestFileReader {
34 captured_contents: map,
35 }
36 }
37}
38
39impl FileReader for TestFileReader {
40 fn read_to_string(&self, file_name: &Path, template_text: &str) -> Result<String> {
41 match self.captured_contents.get(file_name) {
42 Some(file_contents) => Ok(file_contents.to_string()),
43 None => Err(Error::msg(format!(
44 "Could not read template file {} ({})",
45 template_text,
46 file_name.display(),
47 ))),
48 }
49 }
50}