summaryrefslogtreecommitdiffstats
path: root/vendor/handlebars/src/cli.rs
blob: 571900da28a7622b03c4a504c643c24f84ba45f2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
use std::env;
use std::fs;
use std::process;
use std::str::FromStr;

use serde_json::value::Value as Json;

use handlebars::Handlebars;

fn usage() -> ! {
    eprintln!("Usage: handlebars-cli template.hbs '{{\"json\": \"data\"}}'");
    process::exit(1);
}

fn parse_json(text: &str) -> Json {
    let result = if let Some(text) = text.strip_prefix('@') {
        fs::read_to_string(text).unwrap()
    } else {
        text.to_owned()
    };
    match Json::from_str(&result) {
        Ok(json) => json,
        Err(_) => usage(),
    }
}

fn main() {
    let mut args = env::args();
    args.next(); // skip own filename
    let (filename, json) = match (args.next(), args.next()) {
        (Some(filename), Some(json)) => (filename, json),
        _ => usage(),
    };
    let data = parse_json(&json);

    let mut handlebars = Handlebars::new();

    handlebars
        .register_template_file(&filename, &filename)
        .ok()
        .unwrap();
    match handlebars.render(&filename, &data) {
        Ok(data) => {
            println!("{}", data);
        }
        Err(e) => {
            println!("Error rendering {}: {}", filename, e);
            process::exit(2);
        }
    }
}