1 use crate::error::CkError;
3 use std::collections::HashMap;
5 use std::path::{Path, PathBuf};
12 files: HashMap<PathBuf, String>,
13 values: HashMap<PathBuf, Value>,
14 pub variables: HashMap<String, Value>,
15 last_path: Option<PathBuf>,
19 /// Create a new cache, used to read files only once and otherwise store their contents.
20 pub fn new(doc_dir: &str) -> Cache {
22 root: Path::new(doc_dir).to_owned(),
23 files: HashMap::new(),
24 values: HashMap::new(),
25 variables: HashMap::new(),
30 fn resolve_path(&mut self, path: &String) -> PathBuf {
32 let resolve = self.root.join(path);
33 self.last_path = Some(resolve.clone());
38 // FIXME: Point to a line number
39 .expect("No last path set. Make sure to specify a full path before using `-`")
44 fn read_file(&mut self, path: PathBuf) -> Result<String, io::Error> {
45 if let Some(f) = self.files.get(&path) {
49 let file = fs::read_to_string(&path)?;
51 self.files.insert(path, file.clone());
56 /// Get the text from a file. If called multiple times, the file will only be read once
57 pub fn get_file(&mut self, path: &String) -> Result<String, io::Error> {
58 let path = self.resolve_path(path);
62 /// Parse the JSON from a file. If called multiple times, the file will only be read once.
63 pub fn get_value(&mut self, path: &String) -> Result<Value, CkError> {
64 let path = self.resolve_path(path);
66 if let Some(v) = self.values.get(&path) {
70 let content = self.read_file(path.clone())?;
71 let val = serde_json::from_str::<Value>(&content)?;
73 self.values.insert(path, val.clone());