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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
use crate::{Adaptor, Map, RealmeError, Value};
/// A cache system for storing environment and other values.
pub struct RealmeCache {
/// Environment-specific configurations.
pub env: Map<String, Value>,
/// General cache for values.
pub cache: Map<String, Value>,
}
impl RealmeCache {
/// Constructs a new `RealmeCache`.
pub fn new() -> Self {
Self {
env: Map::new(),
cache: Map::new(),
}
}
/// Handles an adaptor by parsing it and updating the cache and environment
/// maps accordingly.
///
/// # Arguments
/// * `adaptor` - The adaptor to handle.
/// * `env_flag` - A flag to determine if the environment should be updated.
///
/// # Errors
/// Returns `RealmeError` if the adaptor cannot be parsed or if the expected
/// environment value is missing.
pub fn handle_adaptor(
&mut self,
adaptor: &Adaptor,
env_flag: bool,
) -> Result<(), RealmeError> {
match adaptor.parse() {
Ok(Value::Table(table)) => {
for (k, v) in table {
if env_flag {
self.cache.insert(k.clone(), v.clone());
self.env.insert(k, v);
continue;
}
match v {
Value::String(s) if s == "{{env}}" => {
if let Some(env_value) = self.cache.get(&k) {
self.env.insert(k, env_value.clone());
} else {
return Err(RealmeError::new_build_error(
format!(
"replace {k} with env value failed"
),
));
}
}
_ => {
self.cache.insert(k, v);
}
}
}
}
Err(e) => {
return Err(RealmeError::new_build_error(e.to_string()));
}
Ok(value) => {
return Err(RealmeError::new_build_error(format!(
"adaptor parse result is not a table: {value}"
)));
}
}
Ok(())
}
}