Skip to content

Commit

Permalink
Add support for hcl/tf/tfvars
Browse files Browse the repository at this point in the history
  • Loading branch information
lumasepa committed Sep 6, 2019
1 parent 52b3b7d commit e03d82a
Show file tree
Hide file tree
Showing 10 changed files with 93 additions and 17 deletions.
28 changes: 28 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ serde_json = "1.0.40"
serde_yaml = "0.8.9"
glob = "0.3.0"
base64 = "0.10.1"
molysite = ""
molysite = { git = "https://github.com/evq/molysite" }

[[bin]]
name = "j2_render"
Expand Down
14 changes: 13 additions & 1 deletion examples/ctx.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,17 @@
"my_number": 1,
"my_float": 1.2,
"my_array": [ "this is", "a list of", "three strings"],
"my_obj": {"a": "a", "b": "b"}
"my_obj": {"a": "a", "b": "b"},
"comple_obj": {
"1": 1,
"obj": {
"a": "a"
},
"array": [
{
"a": true
},
null
]
}
}
16 changes: 16 additions & 0 deletions examples/ctx.tfvars
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@


obj = {
a = "a"
b = {
c = [
"abs"
]
}
}

list = [1,2,3]

str = "hi"

number = 1
11 changes: 11 additions & 0 deletions examples/ctx.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
number = 1
string = "hi"
array = [1,2,3]

[obj]
name = "j2_render"
version = "0.0.1"
obj3 = {}

[obj.obj2]
name = "j2_render"
4 changes: 2 additions & 2 deletions examples/template.j2
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@ this is my float: {{my_float}}
{% endfor %}

{% for key, value in my_obj %}
{{key}}. {{value}}
{{key}}: {{value}}
{% endfor %}

{{ bash(command='ls -la | tr -s " "') }}

1. {{ my_string | sed(expression="s|this||g") | bash(command="wc")}}
2. {{ my_string | bash(command='sed -e "s|this||g" | wc')}}

{{bash(command="echo $var1 $var2", var1="hola", var2="mundo")}}
{{bash(command="echo $var1 $var2", var1="hello", var2="world")}}
12 changes: 3 additions & 9 deletions src/filters.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,11 @@
//tera
//--stdin -i json,yaml,hcl,tfvars,template
//--env -e load env vars in ctx
//--ctx -c file_path [format] multiple files allowed
//--template -t file_path

use crate::inners::exec_cmd;
use base64;
use glob::glob;
use std::collections::HashMap;
use std::fs;
use std::path::Path;
use std::process::Command;
use tera::{Error, Result, Value};
use tera::{Result, Value};

pub fn bash(piped_arg: Value, args: HashMap<String, Value>) -> Result<Value> {
let data = if let Value::String(data) = piped_arg {
Expand Down Expand Up @@ -134,7 +128,7 @@ pub fn strip_line_breaks(piped_arg: Value, _: HashMap<String, Value>) -> Result<

pub fn remove_extension(piped_arg: Value, _: HashMap<String, Value>) -> Result<Value> {
if let Value::String(filename) = piped_arg {
let mut parts: Vec<_> = filename.split(".").collect();
let mut parts: Vec<_> = filename.split('.').collect();
parts.pop();
let filename = parts.join(".");
return Ok(Value::String(filename));
Expand All @@ -158,7 +152,7 @@ pub fn b64decode(piped_arg: Value, _: HashMap<String, Value>) -> Result<Value> {
.map_err(|e| format!("b64decode: decoding error : {}", e).into())
.and_then(|decoded_data| {
String::from_utf8(decoded_data)
.map(|decode_data| Value::String(decode_data))
.map(Value::String)
.map_err(|e| format!("b64decode: utf8 decoding error : {}", e).into())
});
} else {
Expand Down
2 changes: 1 addition & 1 deletion src/functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ pub fn tab_all_lines(args: HashMap<String, Value>) -> Result<Value> {
"tab_all_lines: Error number of spaces is not unsigned integer",
))? as usize;
let spaces = " ".repeat(num_spaces);
let lines: Vec<_> = lines.split("\n").map(|line| spaces.clone() + line).collect();
let lines: Vec<_> = lines.split('\n').map(|line| spaces.clone() + line).collect();
return Ok(Value::String(lines.join("\n")));
} else {
return Err("tab_all_lines: Invalid type for arg num_spaces, expected number".into());
Expand Down
2 changes: 1 addition & 1 deletion src/inners.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::collections::HashMap;
use std::process::Command;
use tera::{Result, Value};

pub fn exec_cmd(command: &mut Command, cmd_str: &String, env: &HashMap<String, Value>) -> Result<Value> {
pub fn exec_cmd(command: &mut Command, cmd_str: &str, env: &HashMap<String, Value>) -> Result<Value> {
for (k, v) in env.iter() {
let value = if let Value::String(data) = v {
data
Expand Down
19 changes: 17 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@ j2_render [opts]
--out [file_path] output file for rendered template, default stdout
--env -e load env vars in ctx
--ctx -c [file_path] context files to be loaded in context, multiple files allowed, default empty
--var -v key=value adds a pair key value to the context
--template -t [file_path] template to be rendered, default empty
--print-ctx -p print the context as json and exits
--help shows this help
"
)
Expand All @@ -48,6 +50,15 @@ pub fn parse_args() -> (String, Option<String>, bool, Context) {
while let Some(arg) = args.pop() {
match arg.as_str() {
"--print-ctx" | "-p" => print_ctx = true,
"--var" | "-v" => {
let variable = args
.pop()
.expect("error specified --var/-v flag but not value provided");
let mut parts : Vec<&str> = variable.split('=').collect();
let key = parts.pop().expect("Error no key=value found");
let value = parts.join("=");
context.insert(&key, &value)
}
"--out" | "-o" => {
let filepath = args
.pop()
Expand Down Expand Up @@ -125,7 +136,9 @@ pub fn populate_ctx(context: &mut Context, format: String, data: String) {
}
}
"hcl" | "tfvars" | "tf" => {
let parsed_hcl = parse_hcl(&data).expect("Error parsing hcl/tf/tfvars");
let value = parse_hcl(&data).expect("Error parsing hcl/tf/tfvars");
let value = value.to_string().parse::<serde_json::Value>().expect("Error parsing json of hcl/tf/tfvars");

let object = value
.as_object()
.expect("Error expected object in root of hcl/tf/tfvars file");
Expand All @@ -141,8 +154,10 @@ pub fn main() -> std::result::Result<(), String> {
let (template, out, print_ctx, context) = parse_args();

if print_ctx {
println!()
println!("{}", context.as_json().expect("Error encoding ctx as json").to_string());
exit(0)
}

let mut tera = Tera::default();
tera.add_raw_template("template", &template)
.expect("Error loading template in engine");
Expand Down

0 comments on commit e03d82a

Please sign in to comment.