1use crate::version::BONNIE_VERSION;
2use crate::{raw_schema, schema};
3use std::env;
4use std::fs;
5
6pub const DEFAULT_BONNIE_CACHE_PATH: &str = "./.bonnie.cache.json";
8
9fn get_cache_path() -> Result<String, String> {
12 let given_path = env::var("BONNIE_CACHE");
14 match given_path {
15 Ok(path) => Ok(path),
16 Err(env::VarError::NotUnicode(_)) => Err(String::from("The path to your Bonnie cache file given in the 'BONNIE_CACHE' environment variable contained invalid characters. Please make sure it only contains valid Unicode.")),
17 Err(env::VarError::NotPresent) => Ok(DEFAULT_BONNIE_CACHE_PATH.to_string()) }
19}
20
21pub fn cache(
25 cfg: &schema::Config,
26 output: &mut impl std::io::Write,
27 raw_cache_path: Option<&str>,
28) -> Result<(), String> {
29 let cache_path = match raw_cache_path {
30 Some(cache_path) => cache_path.to_string(),
31 None => get_cache_path()?,
32 };
33 let cache_str = serde_json::to_string(cfg);
34 let cache_str = match cache_str {
35 Ok(cache_str) => cache_str,
36 Err(err) => return Err(format!("The following error occurred while attempting to cache your parsed Bonnie configuration: '{}'.", err))
37 };
38 let res = fs::write(&cache_path, cache_str);
39 if let Err(err) = res {
40 return Err(format!("The following error occurred while attempting to write your cached Bonnie configuration to '{}': '{}'.", &cache_path, err));
41 }
42
43 writeln!(
44 output,
45 "Your Bonnie configuration has been successfully cached to '{}'! This will be used to speed up future execution. Please note that this cache will NOT be updated until you explicitly run `bonnie -c` again.",
46 cache_path
47 ).expect("Failed to write caching message.");
48 Ok(())
49}
50
51pub fn cache_exists() -> Result<bool, String> {
52 let exists = fs::metadata(get_cache_path()?).is_ok();
53 Ok(exists)
54}
55
56pub fn load_from_cache(
59 output: &mut impl std::io::Write,
60 raw_cache_path: Option<&str>,
61) -> Result<schema::Config, String> {
62 let cache_path = match raw_cache_path {
63 Some(cache_path) => cache_path.to_string(),
64 None => get_cache_path()?,
65 };
66 let cfg_str = fs::read_to_string(&cache_path);
67 let cfg_str = match cfg_str {
68 Ok(cfg_str) => cfg_str,
69 Err(err) => return Err(format!("The following error occurred while attempting to read your cached Bonnie configuration at '{}': '{}'.", &cache_path, err))
70 };
71
72 let cfg = serde_json::from_str::<schema::Config>(&cfg_str);
73 let cfg = match cfg {
74 Ok(cfg) => cfg,
75 Err(err) => return Err(format!("The following error occurred while attempting to parse your cached Bonnie configuration at '{}': '{}'. If this persists, you can recache with `bonnie -c`.", &cache_path, err))
76 };
77 raw_schema::Config::parse_version_against_current(&cfg.version, BONNIE_VERSION, output)?;
79 raw_schema::Config::load_env_files(Some(cfg.env_files.clone()))?;
81
82 Ok(cfg)
83}