Source code for boto3_dataclass.templates.template_helpers
# -*- coding: utf-8 -*-"""Utilities for loading and managing Jinja2 templates used in code generation.It generates the templates/template_enum.py file which contains an enumeration of all templates."""importdataclassesfrompathlibimportPathimportjinja2from..pathsimportpath_enum
[docs]defload_template(relpath:str)->jinja2.Template:""" Load a Jinja2 template by relative path from the ``templates`` directory. :param relpath: The relative path of the template to load, using '/' as the separator. Example: ``type_defs/module.jinja`` """parts=relpath.split("/")path=path_enum.dir_templates.joinpath(*parts)returnjinja2.Template(path.read_text(encoding="utf-8"))
[docs]@dataclasses.dataclassclassTemplateMetadata:""" Data container for metadata about a Jinja2 template file. """path:Path=dataclasses.field(default_factory=Path)@propertydefrelpath(self)->str:""" The path of the template file relative to the ``templates`` directory. """returnstr(self.path.relative_to(path_enum.dir_templates))@propertydefname(self)->str:""" A valid Python identifier derived from the template's relative path. """returnself.relpath.removesuffix(".jinja").replace("/","__").replace(".","_")
[docs]defgen_code():""" Generate the templates/template_enum.py file containing an enumeration of all templates. """template=load_template("template_enum.py.jinja")template_metadata_list=list()forpathinpath_enum.dir_templates.rglob("*.jinja"):template_metadata=TemplateMetadata(path=path)template_metadata_list.append(template_metadata)code=template.render(template_metadata_list=template_metadata_list)path_out=path_enum.dir_templates/"template_enum.py"path_out.write_text(code,encoding="utf-8")