Debian Codegraph @

strictyaml/any_validator.py

raw
1 from strictyaml.ruamel.comments import CommentedSeq, CommentedMap
2 from strictyaml.compound import FixedSeq, Map
3 from strictyaml.validators import Validator
4 from strictyaml.exceptions import YAMLSerializationError
5 from strictyaml.scalar import Bool, EmptyDict, EmptyList, Float, Int, Str
6
7
8 def schema_from_document(document):
9 if isinstance(document, CommentedMap):
10 return Map(
11 {key: schema_from_document(value) for key, value in document.items()}
12 )
13 elif isinstance(document, CommentedSeq):
14 return FixedSeq([schema_from_document(item) for item in document])
15 else:
16 return Str()
17
18
19 def schema_from_data(data, allow_empty):
20 if isinstance(data, dict):
21 if len(data) == 0:
22 if allow_empty:
23 return EmptyDict()
24 raise YAMLSerializationError(
25 "Empty dicts are not serializable to StrictYAML unless schema is used."
26 )
27 return Map(
28 {key: schema_from_data(value, allow_empty) for key, value in data.items()}
29 )
30 elif isinstance(data, list):
31 if len(data) == 0:
32 if allow_empty:
33 return EmptyList()
34 raise YAMLSerializationError(
35 "Empty lists are not serializable to StrictYAML unless schema is used."
36 )
37 return FixedSeq([schema_from_data(item, allow_empty) for item in data])
38 elif isinstance(data, bool):
39 return Bool()
40 elif isinstance(data, int):
41 return Int()
42 elif isinstance(data, float):
43 return Float()
44 else:
45 return Str()
46
47
48 class Any(Validator):
49 """
50 Validates any YAML and returns simple dicts/lists of strings.
51 """
52
53 def validate(self, chunk):
54 return schema_from_document(chunk.contents)(chunk)
55
56 def to_yaml(self, data, allow_empty=False):
57 """
58 Args:
59 allow_empty (bool): True to allow EmptyDict and EmptyList in the
60 schema generated from the data.
61 """
62 return schema_from_data(data, allow_empty=allow_empty).to_yaml(data)
63
64 @property
65 def key_validator(self):
66 return Str()