Source code for colander_data_converter.exporters.mermaid

 1import json
 2from importlib import resources
 3from typing import TextIO
 4
 5from colander_data_converter.base.models import ColanderFeed
 6from colander_data_converter.exporters.exporter import BaseExporter
 7from colander_data_converter.exporters.template import TemplateExporter
 8
 9resource_package = __name__
10
11
[docs] 12class MermaidExporter(BaseExporter): 13 """ 14 Exporter class for generating Mermaid diagrams from Colander feed data. 15 16 This exporter uses Jinja2 templates to transform Colander feed data into 17 Mermaid diagram syntax. It supports custom themes and falls back to a 18 default theme if none is provided. 19 """ 20
[docs] 21 def __init__(self, feed: ColanderFeed, theme: dict = None): 22 """ 23 Initialize the Mermaid exporter. 24 25 Args: 26 feed (~colander_data_converter.base.models.ColanderFeed): The Colander feed data to be exported 27 theme (dict, optional): Custom theme configuration. If None, loads the default theme automatically 28 """ 29 self.feed = feed 30 self.theme = theme 31 if not self.theme: 32 self.load_default_theme() 33 template_name = "mermaid.jinja2" 34 template_source_dir = resources.files(resource_package).joinpath("..").joinpath("data").joinpath("templates") 35 self.template_exporter = TemplateExporter(feed, str(template_source_dir), template_name) 36 self.feed.resolve_references()
37
[docs] 38 def load_default_theme(self): 39 """ 40 Load the default theme configuration from the package resources. 41 42 Reads the default theme JSON file from the package's data/themes directory 43 and loads it into the theme attribute. This method is automatically called 44 during initialization if no custom theme is provided. 45 46 Raises: 47 FileNotFoundError: If the default theme file cannot be found 48 json.JSONDecodeError: If the theme file contains invalid JSON 49 """ 50 theme_file = ( 51 resources.files(resource_package) 52 .joinpath("..") 53 .joinpath("data") 54 .joinpath("themes") 55 .joinpath("default.json") 56 ) 57 with theme_file.open() as f: 58 self.theme = json.load(f)
59
[docs] 60 def export(self, output: TextIO, **kwargs): 61 """ 62 Export the Colander feed data as a Mermaid diagram. 63 64 Uses the configured template and theme to generate Mermaid diagram syntax 65 and writes it to the provided output stream. It does not render the diagram. 66 67 Args: 68 output (TextIO): The output stream to write the Mermaid diagram to 69 **kwargs: Additional keyword arguments passed to the template engine 70 """ 71 self.template_exporter.export(output, theme=self.theme)