summaryrefslogtreecommitdiff
path: root/src/codegen.rs
blob: b940b4d123c85f2872c3b738f3bd11bf0a03ebd4 (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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
use crate::{resource, Document, SubplotError, TemplateSpec};
use std::collections::HashMap;
use std::fs::File;
use std::io::Write;
use std::path::{Path, PathBuf};

use base64::encode;

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

/// Generate a test program from a document, using a template spec.
pub fn generate_test_program(
    doc: &mut Document,
    filename: &Path,
    template: &str,
) -> Result<(), SubplotError> {
    let context = context(doc, template)?;
    let docimpl = doc
        .meta()
        .document_impl(template)
        .ok_or(SubplotError::MissingTemplate)?;

    let code = tera(docimpl.spec(), template)?
        .render("template", &context)
        .expect("render");
    write(filename, &code)?;
    Ok(())
}

fn context(doc: &mut Document, template: &str) -> Result<Context, SubplotError> {
    let mut context = Context::new();
    let scenarios = doc.matched_scenarios(template)?;
    context.insert("scenarios", &scenarios);
    context.insert("files", doc.files());

    let mut funcs = vec![];
    if let Some(docimpl) = doc.meta().document_impl(template) {
        for filename in docimpl.functions_filenames() {
            let content = resource::read_as_string(filename, Some(template))
                .map_err(|err| SubplotError::FunctionsFileNotFound(filename.into(), err))?;
            funcs.push(Func::new(filename, content));
        }
    }
    context.insert("functions", &funcs);

    // Any of the above could fail for more serious reasons, but if we get this far
    // and our context would have no scenarios in it, then we complain.
    if scenarios.is_empty() {
        return Err(SubplotError::NoScenariosMatched(template.to_string()));
    }
    Ok(context)
}

fn tera(tmplspec: &TemplateSpec, templatename: &str) -> Result<Tera, SubplotError> {
    // Tera insists on a glob, but we want to load a specific template
    // only, so we use a glob that doesn't match anything.
    let mut tera = Tera::new("/..IGNORE-THIS../..SUBPLOT-TERA-NOT-EXIST../*").expect("new");
    tera.register_filter("base64", base64);
    tera.register_filter("nameslug", nameslug);
    tera.register_filter("commentsafe", commentsafe);
    let dirname = tmplspec.template_filename().parent().unwrap();
    for helper in tmplspec.helpers() {
        let helper_path = dirname.join(helper);
        let helper_content = resource::read_as_string(helper_path, Some(templatename))?;
        let helper_name = helper.display().to_string();
        tera.add_raw_template(&helper_name, &helper_content)
            .map_err(|err| SubplotError::TemplateError(helper_name.to_string(), err))?;
    }
    let template = resource::read_as_string(tmplspec.template_filename(), Some(templatename))?;
    tera.add_raw_template("template", &template)
        .map_err(|err| {
            SubplotError::TemplateError(tmplspec.template_filename().display().to_string(), err)
        })?;
    Ok(tera)
}

fn write(filename: &Path, content: &str) -> Result<(), SubplotError> {
    let mut f: File = File::create(filename)?;
    f.write_all(content.as_bytes())?;
    Ok(())
}

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 nameslug(name: &Value, _: &HashMap<String, Value>) -> tera::Result<Value> {
    match name {
        Value::String(s) => {
            let newname = s
                .chars()
                .map(|c| match c {
                    'a'..='z' => c,
                    'A'..='Z' => c.to_ascii_lowercase(),
                    _ => '_',
                })
                .collect();
            Ok(Value::String(newname))
        }
        _ => Err(tera::Error::msg(
            "can only create nameslugs from strings".to_string(),
        )),
    }
}

fn commentsafe(s: &Value, _: &HashMap<String, Value>) -> tera::Result<Value> {
    match s {
        Value::String(s) => {
            let cleaned = s
                .chars()
                .map(|c| match c {
                    '\n' | '\r' => ' ',
                    _ => c,
                })
                .collect();
            Ok(Value::String(cleaned))
        }
        _ => Err(tera::Error::msg(
            "can only make clean comments from strings".to_string(),
        )),
    }
}

#[derive(Debug, Serialize)]
pub struct Func {
    pub source: PathBuf,
    pub code: String,
}

impl Func {
    pub fn new(source: &Path, code: String) -> Func {
        Func {
            source: source.to_path_buf(),
            code,
        }
    }
}

#[cfg(test)]
mod test {
    use std::collections::HashMap;
    use tera::Value;
    #[test]
    fn verify_commentsafe_filter() {
        static GOOD_CASES: &[(&str, &str)] = &[
            ("", ""),                                         // Empty
            ("hello world", "hello world"),                   // basic strings pass through
            ("Capitalised Words", "Capitalised Words"),       // capitals are OK
            ("multiple\nlines\rblah", "multiple lines blah"), // line breaks are made into spaces
        ];
        for (input, output) in GOOD_CASES.iter().copied() {
            let input = Value::from(input);
            let output = Value::from(output);
            let empty = HashMap::new();
            assert_eq!(super::commentsafe(&input, &empty).ok(), Some(output));
        }
    }

    #[test]
    fn verify_name_slugification() {
        static GOOD_CASES: &[(&str, &str)] = &[
            ("foobar", "foobar"),        // Simple words pass through
            ("FooBar", "foobar"),        // Capital letters are lowercased
            ("Motörhead", "mot_rhead"), // Non-ascii characters are changed for underscores
            ("foo bar", "foo_bar"),      // As is whitespace etc.
        ];
        for (input, output) in GOOD_CASES.iter().copied() {
            let input = Value::from(input);
            let output = Value::from(output);
            let empty = HashMap::new();
            assert_eq!(super::nameslug(&input, &empty).ok(), Some(output));
        }
    }
}