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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
use std::collections::HashMap;
use std::path::Path;

use regex::Regex;
use toml::{self, Value};

use crate::definition::TemplateDefinition;
use crate::errors::{new_error, ErrorKind, Result};
use crate::utils::read_file;

/// Validate that the struct doesn't have bad data in it
/// and that it doesn't have obvious logic flaws
pub fn validate_definition(def: &TemplateDefinition) -> Vec<String> {
    let mut errs = vec![];
    let mut types = HashMap::new();

    for var in &def.variables {
        let type_str = var.default.type_str();
        types.insert(var.name.to_string(), type_str);

        match var.default {
            Value::String(_) | Value::Integer(_) | Value::Boolean(_) => (),
            _ => {
                errs.push(format!(
                    "Variable `{}` has a default of type {}, which isn't allowed",
                    var.name, type_str
                ));
            }
        }

        if let Some(ref choices) = var.choices {
            let mut choice_found = false;
            for c in choices {
                if *c == var.default {
                    choice_found = true;
                }
            }
            if !choice_found {
                errs.push(format!(
                    "Variable `{}` has `{}` as default, which isn't in the choices",
                    var.name, var.default
                ));
            }
        }

        // Since variables are ordered, we can detect whether the only_if is referring
        // to an unknown variable or a variable of the wrong type
        if let Some(ref cond) = var.only_if {
            if let Some(ref t) = types.get(&cond.name) {
                if **t != cond.value.type_str() {
                    errs.push(format!(
                        "Variable `{}` depends on `{}={}`, but the type of `{}` is {}",
                        var.name, cond.name, cond.value, cond.name, t
                    ));
                }
            } else {
                errs.push(format!(
                    "Variable `{}` depends on `{}`, which wasn't asked",
                    var.name, cond.name
                ));
            }
        }

        if let Some(ref pattern) = var.validation {
            if !var.default.is_str() {
                errs.push(format!(
                    "Variable `{}` has a validation regex but is not a string",
                    var.name
                ));
                continue;
            }

            match Regex::new(pattern) {
                Ok(re) => {
                    if !re.is_match(&var.default.as_str().unwrap()) {
                        errs.push(format!(
                            "Variable `{}` has a default that doesn't pass its validation regex",
                            var.name
                        ));
                    }
                }
                Err(_) => {
                    errs.push(format!(
                        "Variable `{}` has an invalid validation regex: {}",
                        var.name, pattern
                    ));
                }
            }
        }
    }

    errs
}

/// Takes a path to a `template.toml` file and validates it
pub fn validate_file<T: AsRef<Path>>(path: T) -> Result<Vec<String>> {
    let definition: TemplateDefinition = toml::from_str(&read_file(path.as_ref())?)
        .map_err(|err| new_error(ErrorKind::Toml { err }))?;

    Ok(validate_definition(&definition))
}

#[cfg(test)]
mod tests {
    use toml;

    use super::*;

    #[test]
    fn valid_definition_has_no_errors() {
        let def: TemplateDefinition = toml::from_str(
            r#"
            name = "Test template"
            description = "A description"
            kickstart_version = 1

            [[variables]]
            name = "project_name"
            default = "My project"
            prompt = "What's the name of your project?"

            [[variables]]
            name = "database"
            default = "postgres"
            prompt = "Which database to use?"
            choices = ["postgres", "mysql"]

            [[variables]]
            name = "pg_version"
            prompt = "Which version of Postgres?"
            default = "10.4"
            choices = ["10.4", "9.3"]
            only_if = { name = "database", value = "postgres" }

        "#,
        )
        .unwrap();
        let errs = validate_definition(&def);
        assert!(errs.is_empty());
    }

    #[test]
    fn errors_default_not_in_choice() {
        let def: TemplateDefinition = toml::from_str(
            r#"
            name = "Test template"
            description = "A description"
            kickstart_version = 1

            [[variables]]
            name = "project_name"
            default = "My project"
            prompt = "What's the name of your project?"

            [[variables]]
            name = "database"
            default = "postgres"
            prompt = "Which database to use?"
            choices = ["postgres", "mysql"]

            [[variables]]
            name = "pg_version"
            prompt = "Which version of Postgres?"
            default = "10.5"
            choices = ["10.4", "9.3"]
            only_if = { name = "database", value = "postgres" }

        "#,
        )
        .unwrap();
        let errs = validate_definition(&def);
        assert!(!errs.is_empty());
        assert_eq!(
            errs[0],
            "Variable `pg_version` has `\"10.5\"` as default, which isn\'t in the choices"
        );
    }

    #[test]
    fn errors_only_if_unkwnon_variable_name() {
        let def: TemplateDefinition = toml::from_str(
            r#"
            name = "Test template"
            description = "A description"
            kickstart_version = 1

            [[variables]]
            name = "project_name"
            default = "My project"
            prompt = "What's the name of your project?"

            [[variables]]
            name = "pg_version"
            prompt = "Which version of Postgres?"
            default = "10.4"
            choices = ["10.4", "9.3"]
            only_if = { name = "database", value = true }

        "#,
        )
        .unwrap();
        let errs = validate_definition(&def);
        assert!(!errs.is_empty());
        assert_eq!(errs[0], "Variable `pg_version` depends on `database`, which wasn\'t asked");
    }

    #[test]
    fn errors_only_if_not_matching_type() {
        let def: TemplateDefinition = toml::from_str(
            r#"
            name = "Test template"
            description = "A description"
            kickstart_version = 1

            [[variables]]
            name = "project_name"
            default = "My project"
            prompt = "What's the name of your project?"

            [[variables]]
            name = "database"
            default = "postgres"
            prompt = "Which database to use?"
            choices = ["postgres", "mysql"]

            [[variables]]
            name = "pg_version"
            prompt = "Which version of Postgres?"
            default = "10.4"
            choices = ["10.4", "9.3"]
            only_if = { name = "database", value = true }

        "#,
        )
        .unwrap();
        let errs = validate_definition(&def);
        assert!(!errs.is_empty());
        assert_eq!(errs[0], "Variable `pg_version` depends on `database=true`, but the type of `database` is string");
    }

    #[test]
    fn errors_validation_regex_on_wrong_type() {
        let def: TemplateDefinition = toml::from_str(
            r#"
            name = "Test template"
            description = "A description"
            kickstart_version = 1

            [[variables]]
            name = "project"
            default = true
            prompt = "What's the name of your project?"
            validation = "[0-9]+"

        "#,
        )
        .unwrap();
        let errs = validate_definition(&def);
        assert!(!errs.is_empty());
        assert_eq!(errs[0], "Variable `project` has a validation regex but is not a string");
    }

    #[test]
    fn errors_invalid_validation_regex() {
        let def: TemplateDefinition = toml::from_str(
            r#"
            name = "Test template"
            description = "A description"
            kickstart_version = 1

            [[variables]]
            name = "project_name"
            default = "My project"
            prompt = "What's the name of your project?"
            validation = "**[0-9]++"

        "#,
        )
        .unwrap();
        let errs = validate_definition(&def);
        assert!(!errs.is_empty());
        assert_eq!(errs[0], "Variable `project_name` has an invalid validation regex: **[0-9]++");
    }

    #[test]
    fn errors_default_doesnt_match_validation_regex() {
        let def: TemplateDefinition = toml::from_str(
            r#"
            name = "Test template"
            description = "A description"
            kickstart_version = 1

            [[variables]]
            name = "project_name"
            default = "123"
            prompt = "What's the name of your project?"
            validation = "^([a-zA-Z][a-zA-Z0-9_-]+)$"

        "#,
        )
        .unwrap();
        let errs = validate_definition(&def);
        assert!(!errs.is_empty());
        assert_eq!(
            errs[0],
            "Variable `project_name` has a default that doesn\'t pass its validation regex"
        );
    }

    #[test]
    fn errors_on_unsupported_type() {
        let def: TemplateDefinition = toml::from_str(
            r#"
            name = "Test template"
            description = "A description"
            kickstart_version = 1

            [[variables]]
            name = "project_name"
            default = 1.2
            prompt = "What's the name of your project?"
            validation = "^([a-zA-Z][a-zA-Z0-9_-]+)$"

        "#,
        )
        .unwrap();
        let errs = validate_definition(&def);
        assert!(!errs.is_empty());
        assert_eq!(
            errs[0],
            "Variable `project_name` has a default of type float, which isn\'t allowed"
        );
    }
}