summaryrefslogtreecommitdiffstats
path: root/src/tools/jsondocck/src/cache.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/tools/jsondocck/src/cache.rs')
-rw-r--r--src/tools/jsondocck/src/cache.rs70
1 files changed, 12 insertions, 58 deletions
diff --git a/src/tools/jsondocck/src/cache.rs b/src/tools/jsondocck/src/cache.rs
index a188750c5..f9e542327 100644
--- a/src/tools/jsondocck/src/cache.rs
+++ b/src/tools/jsondocck/src/cache.rs
@@ -1,77 +1,31 @@
-use crate::error::CkError;
+use crate::config::Config;
use serde_json::Value;
use std::collections::HashMap;
-use std::io;
-use std::path::{Path, PathBuf};
+use std::path::Path;
use fs_err as fs;
#[derive(Debug)]
pub struct Cache {
- root: PathBuf,
- files: HashMap<PathBuf, String>,
- values: HashMap<PathBuf, Value>,
+ value: Value,
pub variables: HashMap<String, Value>,
- last_path: Option<PathBuf>,
}
impl Cache {
/// Create a new cache, used to read files only once and otherwise store their contents.
- pub fn new(doc_dir: &str) -> Cache {
+ pub fn new(config: &Config) -> Cache {
+ let root = Path::new(&config.doc_dir);
+ let filename = Path::new(&config.template).file_stem().unwrap();
+ let file_path = root.join(&Path::with_extension(Path::new(filename), "json"));
+ let content = fs::read_to_string(&file_path).expect("failed to read JSON file");
+
Cache {
- root: Path::new(doc_dir).to_owned(),
- files: HashMap::new(),
- values: HashMap::new(),
+ value: serde_json::from_str::<Value>(&content).expect("failed to convert from JSON"),
variables: HashMap::new(),
- last_path: None,
}
}
- fn resolve_path(&mut self, path: &String) -> PathBuf {
- if path != "-" {
- let resolve = self.root.join(path);
- self.last_path = Some(resolve.clone());
- resolve
- } else {
- self.last_path
- .as_ref()
- // FIXME: Point to a line number
- .expect("No last path set. Make sure to specify a full path before using `-`")
- .clone()
- }
- }
-
- fn read_file(&mut self, path: PathBuf) -> Result<String, io::Error> {
- if let Some(f) = self.files.get(&path) {
- return Ok(f.clone());
- }
-
- let file = fs::read_to_string(&path)?;
-
- self.files.insert(path, file.clone());
-
- Ok(file)
- }
-
- /// Get the text from a file. If called multiple times, the file will only be read once
- pub fn get_file(&mut self, path: &String) -> Result<String, io::Error> {
- let path = self.resolve_path(path);
- self.read_file(path)
- }
-
- /// Parse the JSON from a file. If called multiple times, the file will only be read once.
- pub fn get_value(&mut self, path: &String) -> Result<Value, CkError> {
- let path = self.resolve_path(path);
-
- if let Some(v) = self.values.get(&path) {
- return Ok(v.clone());
- }
-
- let content = self.read_file(path.clone())?;
- let val = serde_json::from_str::<Value>(&content)?;
-
- self.values.insert(path, val.clone());
-
- Ok(val)
+ pub fn value(&self) -> &Value {
+ &self.value
}
}