diff options
| author | S. Solomon Darnell | 2025-03-28 21:52:21 -0500 |
|---|---|---|
| committer | S. Solomon Darnell | 2025-03-28 21:52:21 -0500 |
| commit | 4a52a71956a8d46fcb7294ac71734504bb09bcc2 (patch) | |
| tree | ee3dc5af3b6313e921cd920906356f5d4febc4ed /.venv/lib/python3.12/site-packages/strictyaml/any_validator.py | |
| parent | cc961e04ba734dd72309fb548a2f97d67d578813 (diff) | |
| download | gn-ai-master.tar.gz | |
Diffstat (limited to '.venv/lib/python3.12/site-packages/strictyaml/any_validator.py')
| -rw-r--r-- | .venv/lib/python3.12/site-packages/strictyaml/any_validator.py | 66 |
1 files changed, 66 insertions, 0 deletions
diff --git a/.venv/lib/python3.12/site-packages/strictyaml/any_validator.py b/.venv/lib/python3.12/site-packages/strictyaml/any_validator.py new file mode 100644 index 00000000..c2a47b0a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/strictyaml/any_validator.py @@ -0,0 +1,66 @@ +from strictyaml.ruamel.comments import CommentedSeq, CommentedMap +from strictyaml.compound import FixedSeq, Map +from strictyaml.validators import Validator +from strictyaml.exceptions import YAMLSerializationError +from strictyaml.scalar import Bool, EmptyDict, EmptyList, Float, Int, Str + + +def schema_from_document(document): + if isinstance(document, CommentedMap): + return Map( + {key: schema_from_document(value) for key, value in document.items()} + ) + elif isinstance(document, CommentedSeq): + return FixedSeq([schema_from_document(item) for item in document]) + else: + return Str() + + +def schema_from_data(data, allow_empty): + if isinstance(data, dict): + if len(data) == 0: + if allow_empty: + return EmptyDict() + raise YAMLSerializationError( + "Empty dicts are not serializable to StrictYAML unless schema is used." + ) + return Map( + {key: schema_from_data(value, allow_empty) for key, value in data.items()} + ) + elif isinstance(data, list): + if len(data) == 0: + if allow_empty: + return EmptyList() + raise YAMLSerializationError( + "Empty lists are not serializable to StrictYAML unless schema is used." + ) + return FixedSeq([schema_from_data(item, allow_empty) for item in data]) + elif isinstance(data, bool): + return Bool() + elif isinstance(data, int): + return Int() + elif isinstance(data, float): + return Float() + else: + return Str() + + +class Any(Validator): + """ + Validates any YAML and returns simple dicts/lists of strings. + """ + + def validate(self, chunk): + return schema_from_document(chunk.contents)(chunk) + + def to_yaml(self, data, allow_empty=False): + """ + Args: + allow_empty (bool): True to allow EmptyDict and EmptyList in the + schema generated from the data. + """ + return schema_from_data(data, allow_empty=allow_empty).to_yaml(data) + + @property + def key_validator(self): + return Str() |
