1 use crate::error::CkError;
3 use std::collections::HashMap;
4 use std::path::{Path, PathBuf};
10 files: HashMap<PathBuf, String>,
11 values: HashMap<PathBuf, Value>,
12 pub variables: HashMap<String, Value>,
13 last_path: Option<PathBuf>,
17 /// Create a new cache, used to read files only once and otherwise store their contents.
18 pub fn new(doc_dir: &str) -> Cache {
20 root: Path::new(doc_dir).to_owned(),
21 files: HashMap::new(),
22 values: HashMap::new(),
23 variables: HashMap::new(),
28 fn resolve_path(&mut self, path: &String) -> PathBuf {
30 let resolve = self.root.join(path);
31 self.last_path = Some(resolve.clone());
34 self.last_path.as_ref().unwrap().clone()
38 fn read_file(&mut self, path: PathBuf) -> Result<String, io::Error> {
39 if let Some(f) = self.files.get(&path) {
43 let file = fs::read_to_string(&path)?;
45 self.files.insert(path, file.clone());
50 /// Get the text from a file. If called multiple times, the file will only be read once
51 pub fn get_file(&mut self, path: &String) -> Result<String, io::Error> {
52 let path = self.resolve_path(path);
56 /// Parse the JSON from a file. If called multiple times, the file will only be read once.
57 pub fn get_value(&mut self, path: &String) -> Result<Value, CkError> {
58 let path = self.resolve_path(path);
60 if let Some(v) = self.values.get(&path) {
64 let content = self.read_file(path.clone())?;
65 let val = serde_json::from_str::<Value>(&content)?;
67 self.values.insert(path, val.clone());