|
21 | 21 |
|
22 | 22 | import copy |
23 | 23 | import logging |
| 24 | +import importlib.util |
| 25 | +import sys |
| 26 | +import os |
| 27 | + |
24 | 28 | from pathlib import Path |
25 | 29 | from typing import Any, Generator, Iterable, Iterator |
26 | 30 |
|
|
33 | 37 | log = logging.getLogger('objdictgen') |
34 | 38 |
|
35 | 39 |
|
| 40 | +def executeCustomGenerator(filename: str, filepath: TPath, node: NodeProtocol) -> None: |
| 41 | + """Execute custom python file for code generation""" |
| 42 | + parent_dir = os.path.dirname(os.path.abspath(filename)) |
| 43 | + sys.path.append(parent_dir) |
| 44 | + spec = importlib.util.spec_from_file_location("CustomGenerator", filename) |
| 45 | + customModule = importlib.util.module_from_spec(spec) |
| 46 | + sys.modules["CustomGenerator"] = customModule |
| 47 | + # Handle errors coming from custom code |
| 48 | + try: |
| 49 | + spec.loader.exec_module(customModule) |
| 50 | + except Exception as e: |
| 51 | + print(f"error executing {filename}: {e}") |
| 52 | + return |
| 53 | + |
| 54 | + if hasattr(customModule, 'GenerateFile'): |
| 55 | + customModule.GenerateFile(filepath, node) |
| 56 | + else: |
| 57 | + raise AttributeError(f"{filename} does not have a 'GenerateFile' function.") |
| 58 | + |
| 59 | + |
36 | 60 | # ------------------------------------------------------------------------------ |
37 | 61 | # Definition of Node Object |
38 | 62 | # ------------------------------------------------------------------------------ |
@@ -192,7 +216,7 @@ def LoadJson(contents: str, validate=True) -> Node: |
192 | 216 | """ Import a new Node from a JSON string """ |
193 | 217 | return jsonod.generate_node(contents, validate=validate) |
194 | 218 |
|
195 | | - def DumpFile(self, filepath: TPath, filetype: str|None = "jsonc", **kwargs): |
| 219 | + def DumpFile(self, filepath: TPath, filetype: str|None = "jsonc", custom_genfile: TPath|None = None, **kwargs): |
196 | 220 | """ Save node into file """ |
197 | 221 |
|
198 | 222 | # Attempt to determine the filetype from the filepath |
@@ -223,6 +247,15 @@ def DumpFile(self, filepath: TPath, filetype: str|None = "jsonc", **kwargs): |
223 | 247 | with open(filepath, "w", encoding="utf-8") as f: |
224 | 248 | f.write(jdata) |
225 | 249 | return |
| 250 | + |
| 251 | + if custom_genfile is not None: |
| 252 | + log.debug("Invoking custom generator: %s", custom_genfile) |
| 253 | + try: |
| 254 | + executeCustomGenerator(custom_genfile, filepath, self) |
| 255 | + return |
| 256 | + except (ImportError, ModuleNotFoundError): |
| 257 | + log.debug("Failed to load custom generator: %s", custom_genfile) |
| 258 | + raise |
226 | 259 |
|
227 | 260 | if filetype == 'c': |
228 | 261 | log.debug("Writing C files '%s'", filepath) |
|
0 commit comments