From 3971a0fb6a2ca6baae9d6531779374ac1d230aa4 Mon Sep 17 00:00:00 2001 From: Steven Bal Date: Fri, 3 Jan 2025 17:31:25 +0100 Subject: [PATCH] :construction: directive to load/validate yaml examples --- .../documentation/__init__.py | 0 .../documentation/directives.py | 41 +++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 django_setup_configuration/documentation/__init__.py create mode 100644 django_setup_configuration/documentation/directives.py diff --git a/django_setup_configuration/documentation/__init__.py b/django_setup_configuration/documentation/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/django_setup_configuration/documentation/directives.py b/django_setup_configuration/documentation/directives.py new file mode 100644 index 0000000..565dc77 --- /dev/null +++ b/django_setup_configuration/documentation/directives.py @@ -0,0 +1,41 @@ +import importlib + +import yaml +from docutils import nodes +from docutils.parsers.rst import Directive + + +class InjectValidatedExample(Directive): + """ + Directive to inject and validate an example from a model class, + then display it as a YAML code block. + """ + + required_arguments = 1 + optional_arguments = 0 + final_argument_whitespace = False + + def run(self): + full_path = self.arguments[0] + + # Split the full path into module and class parts + *module_parts, class_name = full_path.split(".") + module_name = ".".join(module_parts) + + # Dynamically import the module + module = importlib.import_module(module_name) + step_class = getattr(module, class_name) + + # Validate the example using the model + model_class = step_class.config_model + data = yaml.safe_load(step_class.example) + model_class.parse_obj(data[step_class.namespace]) + + # Convert validated data to YAML + # yaml_output = yaml.dump(step_class.example, default_flow_style=False) + + # Create a literal block with YAML output + literal = nodes.literal_block(step_class.example, step_class.example) + literal["language"] = "yaml" + + return [literal]