1use saphyr::LoadableYamlNode;
2
3use crate::Error;
4use crate::Result;
5use crate::RootSchema;
6use crate::Validator as _;
7use crate::YamlSchema;
8use crate::validation::Context;
9
10#[derive(Debug)]
11pub struct Engine<'a> {
12 pub root_schema: &'a RootSchema<'a>,
13 pub context: Context<'a>,
14}
15
16impl<'a> Engine<'a> {
17 pub fn new(root_schema: &'a RootSchema, context: Context<'a>) -> Self {
18 Engine {
19 root_schema,
20 context,
21 }
22 }
23
24 pub fn evaluate<'b: 'a>(
25 root_schema: &'b RootSchema,
26 value: &str,
27 fail_fast: bool,
28 ) -> Result<Context<'b>> {
29 let context = Context::with_root_schema(root_schema, fail_fast);
30 let engine = Engine::new(root_schema, context);
31 let docs = saphyr::MarkedYaml::load_from_str(value).map_err(Error::YamlParsingError)?;
32 match docs.first() {
33 Some(yaml) => {
34 engine.root_schema.validate(&engine.context, yaml)?;
35 }
36 None => match &engine.root_schema.schema {
37 YamlSchema::Empty | YamlSchema::BooleanLiteral(true) => (),
38 _ => engine
39 .context
40 .add_doc_error("Empty YAML document is not allowed"),
41 },
42 }
43 Ok(engine.context)
44 }
45}
46
47#[cfg(test)]
48mod tests {
49 use super::*;
50 use crate::YamlSchema;
51
52 #[test]
53 fn test_engine_empty_schema() {
54 let root_schema = RootSchema::new(YamlSchema::Empty);
55 let context = Engine::evaluate(&root_schema, "", false).unwrap();
56 assert!(!context.has_errors());
57 }
58
59 #[test]
60 fn test_engine_boolean_literal_true() {
61 let root_schema = RootSchema::new(YamlSchema::BooleanLiteral(true));
62 let context = Engine::evaluate(&root_schema, "", false).unwrap();
63 assert!(!context.has_errors());
64 }
65
66 #[test]
67 fn test_engine_boolean_literal_false() {
68 let root_schema = RootSchema::new(YamlSchema::BooleanLiteral(false));
69 let context = Engine::evaluate(&root_schema, "", false).unwrap();
70 assert!(context.has_errors());
71 }
72}