From 0387ba811813dc169548c7108d9a95de43dd17a0 Mon Sep 17 00:00:00 2001 From: Federico Terzi Date: Fri, 12 Nov 2021 22:13:37 +0100 Subject: [PATCH] feat(render): add logic to enable variable injection escape --- espanso-render/src/renderer/mod.rs | 36 +++++++++++++++++++++++++++++ espanso-render/src/renderer/util.rs | 7 +++++- 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/espanso-render/src/renderer/mod.rs b/espanso-render/src/renderer/mod.rs index 7ed547e..92b38e6 100644 --- a/espanso-render/src/renderer/mod.rs +++ b/espanso-render/src/renderer/mod.rs @@ -175,6 +175,8 @@ impl<'a> Renderer for DefaultRenderer<'a> { template.body.clone() }; + let body = util::unescape_variable_inections(&body); + // Process the casing style let body_with_casing = match options.casing_style { CasingStyle::None => body, @@ -810,6 +812,32 @@ mod tests { assert!(matches!(res, RenderResult::Success(str) if str == "hello {{first}} two")); } + #[test] + fn escaped_variable_injection() { + let renderer = get_renderer(); + let mut template = template_for_str("hello {{second}}"); + template.vars = vec![ + Variable { + name: "first".to_string(), + var_type: "mock".to_string(), + params: Params::from_iter(vec![("echo".to_string(), Value::String("one".to_string()))]), + ..Default::default() + }, + Variable { + name: "second".to_string(), + var_type: "mock".to_string(), + params: Params::from_iter(vec![( + "echo".to_string(), + Value::String("\\{\\{first\\}\\} two".to_string()), + )]), + ..Default::default() + }, + ]; + + let res = renderer.render(&template, &Default::default(), &Default::default()); + assert!(matches!(res, RenderResult::Success(str) if str == "hello {{first}} two")); + } + #[test] fn variable_injection_missing_var() { let renderer = get_renderer(); @@ -911,4 +939,12 @@ mod tests { ); assert!(matches!(res, RenderResult::Success(str) if str == "hello local")); } + + #[test] + fn variable_escape() { + let renderer = get_renderer(); + let template = template("hello \\{\\{var\\}\\}", &[("var", "world")]); + let res = renderer.render(&template, &Default::default(), &Default::default()); + assert!(matches!(res, RenderResult::Success(str) if str == "hello {{var}}")); + } } diff --git a/espanso-render/src/renderer/util.rs b/espanso-render/src/renderer/util.rs index 0e13772..299e164 100644 --- a/espanso-render/src/renderer/util.rs +++ b/espanso-render/src/renderer/util.rs @@ -108,7 +108,12 @@ pub(crate) fn render_variables(body: &str, scope: &Scope) -> Result { return Err(error.into()); } - Ok(output) + let unescaped_output = unescape_variable_inections(&output); + Ok(unescaped_output) +} + +pub(crate) fn unescape_variable_inections(body: &str) -> String { + body.replace("\\{\\{", "{{").replace("\\}\\}", "}}") } pub(crate) fn inject_variables_into_params(params: &Params, scope: &Scope) -> Result {