1#[cfg(any(feature = "json", feature = "toml"))]
2use std::fs;
3#[cfg(any(feature = "json", feature = "toml"))]
4use std::path::Path;
5
6pub use tera::Context;
7
8#[cfg(any(feature = "json", feature = "toml"))]
9use crate::Error;
10
11pub trait ContextSource {
13 fn context(&self) -> Context;
15}
16
17#[derive(Clone)]
19pub struct StaticContextSource {
20 context: Context,
21}
22
23impl ContextSource for StaticContextSource {
24 fn context(&self) -> Context {
25 self.context.clone()
26 }
27}
28
29impl StaticContextSource {
30 #[must_use]
32 pub const fn new(context: Context) -> Self {
33 Self { context }
34 }
35
36 #[cfg(feature = "json")]
42 pub fn from_json_file<P>(path: P) -> Result<Self, Error>
43 where
44 P: AsRef<Path>,
45 {
46 let context_str = fs::read_to_string(path)?;
47 let value = context_str.parse()?;
48 let context = Context::from_value(value)?;
49 Ok(Self::new(context))
50 }
51
52 #[cfg(feature = "toml")]
58 pub fn from_toml_file<P>(path: P) -> Result<Self, Error>
59 where
60 P: AsRef<Path>,
61 {
62 let context_str = fs::read_to_string(path)?;
63 let value: toml::Table = context_str.parse()?;
64 let context = Context::from_serialize(value)?;
65 Ok(Self::new(context))
66 }
67}
68
69impl Default for StaticContextSource {
70 fn default() -> Self {
71 Self::new(Context::default())
72 }
73}