Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🚧 directive to load/validate yaml examples #44

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file.
41 changes: 41 additions & 0 deletions django_setup_configuration/documentation/directives.py
Original file line number Diff line number Diff line change
@@ -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]
Loading