From 10290cf8d00ac25be3fe519459d78b0c397ecab1 Mon Sep 17 00:00:00 2001 From: cmoineau <cyril.moineau@cea.fr> Date: Mon, 22 Apr 2024 07:20:33 +0000 Subject: [PATCH] Add generate_file function to aidge_core. --- aidge_core/__init__.py | 2 +- aidge_core/export/__init__.py | 1 + aidge_core/export/code_generation.py | 32 ++++++++++++++++++++++++++++ 3 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 aidge_core/export/code_generation.py diff --git a/aidge_core/__init__.py b/aidge_core/__init__.py index 5f4e83672..701e25323 100644 --- a/aidge_core/__init__.py +++ b/aidge_core/__init__.py @@ -8,5 +8,5 @@ http://www.eclipse.org/legal/epl-2.0. SPDX-License-Identifier: EPL-2.0 """ from aidge_core.aidge_core import * # import so generated by PyBind -from aidge_core.export import ExportNode +from aidge_core.export import ExportNode, generate_file import aidge_core.utils diff --git a/aidge_core/export/__init__.py b/aidge_core/export/__init__.py index 00b44121d..6fc846d93 100644 --- a/aidge_core/export/__init__.py +++ b/aidge_core/export/__init__.py @@ -1 +1,2 @@ from .node_export import * +from .code_generation import * diff --git a/aidge_core/export/code_generation.py b/aidge_core/export/code_generation.py new file mode 100644 index 000000000..f267ac52b --- /dev/null +++ b/aidge_core/export/code_generation.py @@ -0,0 +1,32 @@ +import os +from jinja2 import Environment, FileSystemLoader + + +def generate_file(file_path: str, template_path: str, **kwargs) -> None: + """Generate a file at `file_path` using the jinja template located at `file_path`. + kwargs are used + + :param file_path: path where to generate the file + :type file_path: str + :param template_path: Path to the template to use for code generation + :type template_path: str + """ + # Get directory name of the file + dirname = os.path.dirname(file_path) + + # If directory doesn't exist, create it + if not os.path.exists(dirname): + os.makedirs(dirname) + + # Get directory name and name of the template + template_dir = os.path.dirname(template_path) + template_name = os.path.basename(template_path) + + # Select template + template = Environment(loader=FileSystemLoader( + template_dir)).get_template(template_name) + + # Generate file + content = template.render(kwargs) + with open(file_path, mode="w", encoding="utf-8") as message: + message.write(content) -- GitLab