mdbook_tera/
context.rs

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
11/// A context source for the Tera preprocessor.
12pub trait ContextSource {
13    /// Returns a context from the source.
14    fn context(&self) -> Context;
15}
16
17/// Static context source for the Tera preprocessor.
18#[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    /// Construct a context source given a tera context.
31    #[must_use]
32    pub const fn new(context: Context) -> Self {
33        Self { context }
34    }
35
36    /// Construct a context source given a JSON path.
37    ///
38    /// # Errors
39    ///
40    /// Returns an error if the provided path or JSON read is invalid.
41    #[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    /// Construct a context source given a TOML path.
53    ///
54    /// # Errors
55    ///
56    /// Returns an error if the provided path or TOML read is invalid.
57    #[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}