blob: 5f72bd171a17c073049afe6f158aaee0e4be2b79 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
use crate::config::Config;
use serde_json::Value;
use std::collections::HashMap;
use std::path::Path;
use fs_err as fs;
#[derive(Debug)]
pub struct Cache {
value: Value,
pub variables: HashMap<String, Value>,
}
impl Cache {
/// Create a new cache, used to read files only once and otherwise store their contents.
pub fn new(config: &Config) -> Cache {
let root = Path::new(&config.doc_dir);
// `filename` needs to replace `-` with `_` to be sure the JSON path will always be valid.
let filename =
Path::new(&config.template).file_stem().unwrap().to_str().unwrap().replace('-', "_");
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 {
value: serde_json::from_str::<Value>(&content).expect("failed to convert from JSON"),
variables: HashMap::from([("FILE".to_owned(), config.template.clone().into())]),
}
}
pub fn value(&self) -> &Value {
&self.value
}
}
|