#[cfg(any(feature = "json", feature = "toml"))]
use std::fs;
#[cfg(any(feature = "json", feature = "toml"))]
use std::path::Path;
pub use tera::Context;
#[cfg(any(feature = "json", feature = "toml"))]
use crate::Error;
pub trait ContextSource {
fn context(&self) -> Context;
}
#[derive(Clone)]
pub struct StaticContextSource {
context: Context,
}
impl ContextSource for StaticContextSource {
fn context(&self) -> Context {
self.context.clone()
}
}
impl StaticContextSource {
#[must_use]
pub const fn new(context: Context) -> Self {
Self { context }
}
#[cfg(feature = "json")]
pub fn from_json_file<P>(path: P) -> Result<Self, Error>
where
P: AsRef<Path>,
{
let context_str = fs::read_to_string(path)?;
let value = context_str.parse()?;
let context = Context::from_value(value)?;
Ok(Self::new(context))
}
#[cfg(feature = "toml")]
pub fn from_toml_file<P>(path: P) -> Result<Self, Error>
where
P: AsRef<Path>,
{
let context_str = fs::read_to_string(path)?;
let value: toml::Value = context_str.parse()?;
let context = Context::from_serialize(value)?;
Ok(Self::new(context))
}
}
impl Default for StaticContextSource {
fn default() -> Self {
Self::new(Context::default())
}
}