From 4bae25b8ed297656394f774b99c1894451d8deda Mon Sep 17 00:00:00 2001 From: yuma14 Date: Fri, 10 Nov 2023 18:09:00 +0900 Subject: [PATCH] add TextAsTemplate transformer --- src/pipeline.rs | 1 + src/pipeline/step.rs | 3 ++- src/transformer.rs | 2 ++ src/transformer/text_as_template.rs | 25 +++++++++++++++++++++++++ 4 files changed, 30 insertions(+), 1 deletion(-) create mode 100644 src/transformer/text_as_template.rs diff --git a/src/pipeline.rs b/src/pipeline.rs index 2334a23..6e576f8 100644 --- a/src/pipeline.rs +++ b/src/pipeline.rs @@ -104,6 +104,7 @@ impl Pipeline { EnumTransformer::TemplateRenderer(t) => t.transform(&input, &store), EnumTransformer::JsonPath(t) => t.transform(&input, &store), EnumTransformer::JsonPathAll(t) => t.transform(&input, &store), + EnumTransformer::TextAsTemplate(t) => t.transform(&input, &store), } .with_context(|| "transformer failed".to_string())?; debug!("transform output type: {}", value.get_type_name()); diff --git a/src/pipeline/step.rs b/src/pipeline/step.rs index e325c0b..b728bbf 100644 --- a/src/pipeline/step.rs +++ b/src/pipeline/step.rs @@ -2,7 +2,7 @@ use std::{collections::HashMap, path::PathBuf}; use serde::{Deserialize, Serialize}; -use crate::transformer::{JsonPathQuery, JsonPathQueryAll, TemplateRenderer}; +use crate::transformer::{JsonPathQuery, JsonPathQueryAll, TemplateRenderer, TextAsTemplate}; #[derive(Debug, Serialize, Deserialize)] #[serde(tag = "type")] @@ -35,6 +35,7 @@ pub enum EnumTransformer { TemplateRenderer(TemplateRenderer), JsonPath(JsonPathQuery), JsonPathAll(JsonPathQueryAll), + TextAsTemplate(TextAsTemplate), } #[derive(Debug, Deserialize, Serialize)] diff --git a/src/transformer.rs b/src/transformer.rs index e3a703b..ffb403a 100644 --- a/src/transformer.rs +++ b/src/transformer.rs @@ -3,10 +3,12 @@ use crate::{store::Store, Value}; mod json_path_query; mod json_path_query_all; mod template_renderer; +mod text_as_template; pub use json_path_query::*; pub use json_path_query_all::*; pub use template_renderer::*; +pub use text_as_template::*; pub trait Transformer { fn transform(&self, value: &Value, store: &Store) -> anyhow::Result; diff --git a/src/transformer/text_as_template.rs b/src/transformer/text_as_template.rs new file mode 100644 index 0000000..34cbb06 --- /dev/null +++ b/src/transformer/text_as_template.rs @@ -0,0 +1,25 @@ +use anyhow::Context; +use handlebars::Template; +use serde::{Deserialize, Serialize}; + +use crate::{store::Store, Value}; + +use super::Transformer; + +#[derive(Debug, Deserialize, Serialize)] +pub struct TextAsTemplate; + +impl Transformer for TextAsTemplate { + fn transform(&self, value: &Value, _store: &Store) -> anyhow::Result { + if let Value::JSON(serde_json::Value::String(string)) = value { + Ok(Value::Template(Template::compile(string).with_context( + || format!("failed to compile template {}", string), + )?)) + } else { + anyhow::bail!( + "value should be string, but it was {}", + value.get_type_name() + ) + } + } +}