docx-templating 1.0.0

Rust library for DOCX templating with variable replacement, conditionals, and loops
Documentation
//! Template context and data lookup.
//!
//! Provides the [`Context`] type for supplying data to templates, and the
//! [`IntoContext`] trait that lets `Template::render` accept JSON, a context or
//! any borrowed serializable value.

#[cfg(test)]
use crate::syntax::ast::Path;
use serde::Serialize;
use serde_json::Value;

/// Template data context wrapping JSON values.
///
/// Provides path resolution for template evaluation.
///
/// # Examples
///
/// ```
/// use docx_templating::Context;
/// use serde_json::json;
///
/// // From JSON
/// let ctx = Context::from_json(json!({
///     "user": {
///         "name": "Ada Lovelace"
///     }
/// }));
/// ```
#[derive(Debug, Clone)]
pub struct Context {
    root: Value,
}

impl Context {
    /// Create context from a JSON value.
    pub fn from_json(value: Value) -> Self {
        Self { root: value }
    }

    /// Create context from any serializable type.
    ///
    /// # Errors
    ///
    /// Returns error if serialization to JSON fails.
    ///
    /// # Examples
    ///
    /// ```
    /// use docx_templating::Context;
    /// use serde::Serialize;
    ///
    /// #[derive(Serialize)]
    /// struct User {
    ///     name: String,
    ///     age: u32,
    /// }
    ///
    /// let user = User { name: "Ada".into(), age: 36 };
    /// let ctx = Context::from_serialize(&user).unwrap();
    /// ```
    pub fn from_serialize<T: Serialize + ?Sized>(value: &T) -> crate::Result<Self> {
        let json = serde_json::to_value(value).map_err(ContextError::Serialization)?;
        Ok(Self::from_json(json))
    }

    /// Resolve a path to a value reference.
    ///
    /// Returns `Ok(Some(&value))` if path exists,
    /// `Ok(None)` if path is valid but doesn't exist,
    /// `Err(...)` if path traversal encounters type mismatches.
    ///
    /// Paths are an internal representation, so this helper is crate visible
    /// only. Callers outside the crate reach values by rendering a template.
    #[cfg(test)]
    pub(crate) fn resolve(&self, path: &Path) -> crate::Result<Option<&Value>> {
        crate::domain::engine::resolve_path(&self.root, path).map_err(crate::Error::from)
    }

    /// Get the root value (internal use).
    pub(crate) fn root(&self) -> &Value {
        &self.root
    }
}

impl From<Value> for Context {
    fn from(value: Value) -> Self {
        Self::from_json(value)
    }
}

impl Default for Context {
    /// An empty context, the same as `Context::from_json(json!({}))`.
    fn default() -> Self {
        Self::from_json(Value::Object(serde_json::Map::new()))
    }
}

impl Serialize for Context {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        self.root.serialize(serializer)
    }
}

/// Anything that can be turned into a [`Context`].
///
/// [`Template::render`](crate::Template::render) takes `impl IntoContext`, so a
/// caller can pass whichever form they already have:
///
/// - a [`Context`], by value or by reference
/// - a [`serde_json::Value`], such as the result of [`serde_json::json!`]
/// - a reference to any [`serde::Serialize`] value, such as a borrowed struct
///
/// Passing a reference avoids cloning the data and keeps the struct in the
/// caller's own type.
///
/// # Examples
///
/// ```
/// use docx_templating::{Context, IntoContext};
/// use serde::Serialize;
///
/// #[derive(Serialize)]
/// struct User {
///     name: String,
/// }
///
/// let user = User { name: "Ada".into() };
/// let context = user.into_context().unwrap();
/// assert!(context.into_context().is_ok());
/// ```
pub trait IntoContext {
    /// Convert this value into a context.
    ///
    /// # Errors
    ///
    /// Returns [`ContextError::Serialization`] if the value cannot be
    /// represented as JSON, which only happens for borrowed serializable
    /// values.
    fn into_context(self) -> crate::Result<Context>;
}

impl IntoContext for Context {
    fn into_context(self) -> crate::Result<Context> {
        Ok(self)
    }
}

impl IntoContext for Value {
    fn into_context(self) -> crate::Result<Context> {
        Ok(Context::from_json(self))
    }
}

impl<T: Serialize + ?Sized> IntoContext for &T {
    fn into_context(self) -> crate::Result<Context> {
        Context::from_serialize(self)
    }
}

/// Context error type.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ContextError {
    /// Serialization to JSON failed.
    #[error("failed to serialize value to JSON: {0}")]
    Serialization(#[source] serde_json::Error),
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]

    use super::*;
    use crate::syntax::ast::PathSegment;
    use serde::Serialize;
    use serde_json::json;

    #[test]
    fn test_from_json() {
        let ctx = Context::from_json(json!({"name": "Ada"}));
        assert!(ctx.root().is_object());
    }

    #[test]
    fn test_from_value_trait() {
        let ctx: Context = json!({"name": "Ada"}).into();
        assert!(ctx.root().is_object());
    }

    #[test]
    fn test_from_serialize() {
        #[derive(Serialize)]
        struct User {
            name: String,
            age: u32,
        }

        let user = User {
            name: "Ada".to_string(),
            age: 36,
        };
        let ctx = Context::from_serialize(&user).unwrap();

        let path = Path::field("name");
        let value = ctx.resolve(&path).unwrap();
        assert_eq!(value, Some(&json!("Ada")));
    }

    #[test]
    fn test_resolve_top_level() {
        let ctx = Context::from_json(json!({"name": "Ada"}));
        let path = Path::field("name");

        let value = ctx.resolve(&path).unwrap();
        assert_eq!(value, Some(&json!("Ada")));
    }

    #[test]
    fn test_resolve_nested() {
        let ctx = Context::from_json(json!({
            "user": {
                "name": "Ada",
                "age": 36
            }
        }));

        let path = Path::new(vec![
            PathSegment::Field("user".to_string()),
            PathSegment::Field("name".to_string()),
        ]);

        let value = ctx.resolve(&path).unwrap();
        assert_eq!(value, Some(&json!("Ada")));
    }

    #[test]
    fn test_resolve_missing_returns_none() {
        let ctx = Context::from_json(json!({"name": "Ada"}));
        let path = Path::field("missing");

        let value = ctx.resolve(&path).unwrap();
        assert_eq!(value, None);
    }

    #[test]
    fn test_resolve_type_mismatch_errors() {
        let ctx = Context::from_json(json!({"items": [1, 2, 3]}));
        let path = Path::new(vec![
            PathSegment::Field("items".to_string()),
            PathSegment::Field("name".to_string()),
        ]);

        let result = ctx.resolve(&path);
        assert!(result.is_err());
    }

    #[test]
    fn test_default_context_is_an_empty_object() {
        let ctx = Context::default();
        assert_eq!(ctx.root(), &json!({}));
    }

    #[test]
    fn test_context_serializes_as_its_root_value() {
        let ctx = Context::from_json(json!({"name": "Ada"}));
        assert_eq!(serde_json::to_value(&ctx).unwrap(), json!({"name": "Ada"}));
    }

    #[test]
    fn test_into_context_accepts_a_context() {
        let ctx = Context::from_json(json!({"name": "Ada"}));
        assert_eq!(ctx.into_context().unwrap().root(), &json!({"name": "Ada"}));
    }

    #[test]
    fn test_into_context_accepts_a_value() {
        let ctx = json!({"name": "Ada"}).into_context().unwrap();
        assert_eq!(ctx.root(), &json!({"name": "Ada"}));
    }

    #[test]
    fn test_into_context_accepts_a_borrowed_struct() {
        #[derive(Serialize)]
        struct User {
            name: String,
        }

        let user = User {
            name: "Ada".to_owned(),
        };

        // A plain value reaches the reference impl through method autoref.
        let ctx = user.into_context().unwrap();
        assert_eq!(ctx.root(), &json!({"name": "Ada"}));
    }

    #[test]
    fn test_into_context_accepts_a_borrowed_context() {
        let ctx = Context::from_json(json!({"name": "Ada"}));
        let copied = (&ctx).into_context().unwrap();
        assert_eq!(copied.root(), &json!({"name": "Ada"}));
    }
}