summaryrefslogtreecommitdiffstats
path: root/vendor/handlebars-3.5.5/src/cli.rs
blob: af83b7f32f2ce3878450946d3c7aae1411801b47 (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 text = if text.starts_with('@') {
        fs::read_to_string(&text[1..]).unwrap()
    } else {
        text.to_owned()
    };
    match Json::from_str(&text) {
        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);
        }
    }
}