summaryrefslogtreecommitdiff
path: root/src/bin/sp-codegen.rs
blob: 3342b9752e6278dd64588a4c8345b02d47fef8df (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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
use std::collections::HashMap;
use std::fs::File;
use std::io::prelude::{Read, Write};
use std::path::{Path, PathBuf};
use std::process::Command;
use subplot::{Document, Result};
// use subplot::{
//     Bindings, Document, Error, MatchedStep, PartialStep, Result, Scenario, ScenarioStep,
// };

use base64::encode;
use structopt::StructOpt;

use tera::{Context, Tera, Value};

// Define the command line arguments.
#[derive(Debug, StructOpt)]
#[structopt(name = "codegen", about = "Subplot code generator.")]
struct Opt {
    // Input filename.
    #[structopt(parse(from_os_str))]
    filename: PathBuf,

    // Write generated test program to this file.
    #[structopt(
        long,
        short,
        parse(from_os_str),
        help = "Writes generated test program to FILE"
    )]
    output: PathBuf,

    // Run the generated test program after writing it?
    #[structopt(long, short, help = "Runs generated test program")]
    run: bool,

    #[structopt(
        long,
        short,
        help = "Look for code templates in DIR",
        default_value = "/usr/share/subplot",
        name = "DIR"
    )]
    templates: PathBuf,
}

fn main() -> Result<()> {
    let opt = Opt::from_args();
    let mut doc = Document::from_file(&opt.filename)?;
    let scenarios = doc.matched_scenarios()?;
    let meta = doc.meta();

    let mut context = Context::new();
    context.insert("scenarios", &scenarios);

    context.insert("files", doc.files());

    let (funcs_filename, funcs) = match meta.functions_filename() {
        Some(filename) => (filename, cat(filename)?),
        None => ("", "".to_string()),
    };
    context.insert("functions", &funcs);
    context.insert("functions_filename", funcs_filename);

    let glob = format!("{}/**/*", opt.templates.to_str().unwrap());
    let mut tera = Tera::new(&glob).expect("new");
    tera.register_filter("base64", base64);

    let code = tera.render("python.py", &context).expect("render");
    let mut f: File = File::create(&opt.output)?;
    f.write_all(&code.as_bytes())?;

    if opt.run && !run(&opt.output)? {
        eprintln!("Test program failed.");
        std::process::exit(1);
    }

    Ok(())
}

fn cat<P: AsRef<Path>>(filename: P) -> Result<String> {
    let mut f = File::open(filename)?;
    let mut buf = String::new();
    f.read_to_string(&mut buf)?;
    Ok(buf)
}

fn base64(v: &Value, _: &HashMap<String, Value>) -> tera::Result<Value> {
    match v {
        Value::String(s) => Ok(Value::String(encode(s))),
        _ => Err(tera::Error::msg(
            "can only base64 encode strings".to_string(),
        )),
    }
}

fn run(filename: &Path) -> Result<bool> {
    let status = Command::new("python3").arg(filename).status()?;
    Ok(status.success())
}