From 7256a84cb7719054ce09c18ae506f67380b6e7c5 Mon Sep 17 00:00:00 2001 From: John Pennycook Date: Fri, 26 Jan 2024 07:27:26 -0800 Subject: [PATCH] Add separate function for validating YAML Signed-off-by: John Pennycook --- codebasin/config.py | 3 +-- codebasin/util.py | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/codebasin/config.py b/codebasin/config.py index e22079b..bab0f01 100644 --- a/codebasin/config.py +++ b/codebasin/config.py @@ -571,8 +571,7 @@ def load(config_file, rootdir): raise RuntimeError(f"Could not open {config_file!s}.") # Validate config against a schema - # We don't use any advanced features of YAML, so can use JSON here - util._validate_json(config, schema_name="config") + util._validate_yaml(config, schema_name="config") # Read codebase definition if "codebase" in config: diff --git a/codebasin/util.py b/codebasin/util.py index 9fc1337..8d31b39 100644 --- a/codebasin/util.py +++ b/codebasin/util.py @@ -167,6 +167,38 @@ def _validate_json(json_object: object, schema_name: str) -> bool: return True +def _validate_yaml(yaml_object: object, schema_name: str) -> bool: + """ + Validate YAML against a schema. + + Parameters + ---------- + yaml_object : Object + The YAML to validate. + + schema_name : {'config'} + The schema to validate against. + + Returns + ------- + bool + True if the YAML is valid. + + Raises + ------ + ValueError + If the YAML fails to validate, or the schema name is unrecognized. + + RuntimeError + If the schema file cannot be located. + """ + if schema_name != "config": + raise ValueError("Unrecognized schema name.") + + # We don't use any advanced features of YAML, so can use JSON here + return _validate_json(yaml_object, schema_name) + + def _load_json(file_object: typing.TextIO, schema_name: str) -> object: """ Load JSON from file and validate it against a schema.