You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

75 lines
2.1 KiB
Rust

extern crate nom;
use parser::Template;
use renderer::compile_template;
use renderer::CompileError;
use renderer::DustRenderer;
use std::env;
use std::fs;
use std::io::{self, Read};
use std::path::Path;
mod integrations;
mod parser;
mod renderer;
fn main() {
let context = read_context_from_stdin();
let argv: Vec<String> = env::args().collect();
if argv.len() < 2 {
panic!("Need to pass templates");
}
let template_paths = &argv[1..];
let template_contents: Vec<(String, String)> = template_paths
.iter()
.map(|p| {
let template_content = fs::read_to_string(&p).unwrap();
(p.to_string(), template_content)
})
.collect();
let compiled_templates_result: Result<Vec<(String, Template)>, CompileError> =
template_contents
.iter()
.map(|(p, contents)| template_from_file(p, contents))
.collect();
let compiled_templates = compiled_templates_result.unwrap();
let main_template_name = &compiled_templates
.first()
.expect("There should be more than 1 template")
.0;
let mut dust_renderer = DustRenderer::new();
compiled_templates.iter().for_each(|(name, template)| {
dust_renderer.load_source(template, name.to_owned());
});
println!(
"{}",
dust_renderer
.render(main_template_name, Some(&context))
.expect("Failed to render")
);
}
fn template_from_file<'a>(
file_path: &str,
file_contents: &'a str,
) -> Result<(String, Template<'a>), CompileError> {
let path: &Path = Path::new(file_path);
let name = path.file_stem().ok_or(CompileError {
message: format!("Failed to get file stem on {}", file_path),
})?;
Ok((
name.to_string_lossy().to_string(),
compile_template(file_contents)?,
))
}
fn read_context_from_stdin() -> serde_json::Value {
let mut buffer = String::new();
io::stdin()
.read_to_string(&mut buffer)
.expect("Failed to read stdin");
serde_json::from_str(&buffer).expect("Failed to parse json")
}