brix_processor/
lib.rs

1// Copyright (c) 2021 Ethan Lerner, Caleb Cushing, and the Brix contributors
2//
3// This software is released under the MIT License.
4// https://opensource.org/licenses/MIT
5
6//! # Brix Processor
7//! Brix processor is a wrapper around [handlrbars](https://crates.io/crates/handlebars)
8//! that allows for more complex context handling and adds custom helper functions.
9
10use handlebars::{
11    Context, Handlebars, Helper, HelperDef, HelperResult, JsonRender, Output, RenderContext,
12    RenderError,
13};
14use serde_json::json;
15use serde_json::value::{Map, Value as Json};
16use std::collections::HashMap;
17
18use brix_errors::BrixError;
19mod helpers;
20
21/// Struct that contains an inner handlebars object with registered helpers.
22/// May contain other templating engines in the future.
23pub struct ProcessorCore<'a> {
24    handlebars: handlebars::Handlebars<'a>,
25}
26
27impl<'a> ProcessorCore<'a> {
28    pub fn new() -> Self {
29        let mut handlebars = Handlebars::new();
30        handlebars.register_helper("to-upper", Box::new(helpers::ToUpperHelper));
31        handlebars.register_helper("to-lower", Box::new(helpers::ToLowerHelper));
32        handlebars.register_helper("to-title", Box::new(helpers::ToTitleHelper));
33        handlebars.register_helper("to-case", Box::new(helpers::ToCaseHelper));
34        handlebars.register_helper("to-flat", Box::new(helpers::ToFlatHelper));
35        handlebars.register_helper("to-java-package", Box::new(helpers::ToJavaPackageHelper));
36        handlebars.register_helper(
37            "to-java-package-path",
38            Box::new(helpers::ToJavaPackagePathHelper),
39        );
40        Self { handlebars }
41    }
42
43    /// Render text with the provided context.
44    pub fn process(&self, text: String, context: Map<String, Json>) -> Result<String, BrixError> {
45        let result = self.handlebars.render_template(&text, &context)?;
46        Ok(result)
47    }
48}
49
50/// Create a valid context map by serializing into JSON.
51pub fn create_context(data: HashMap<String, String>) -> Map<String, Json> {
52    let mut res = Map::new();
53    for (key, value) in data.into_iter() {
54        res.insert(key, json!(value));
55    }
56    res
57}