From b9f2eea89bb00bc7cd809369ec5cfe8434501511 Mon Sep 17 00:00:00 2001 From: Alessandro De Maria Date: Sat, 30 Nov 2024 22:10:08 +0000 Subject: [PATCH] allows dynamic import --- kapitan/inputs/__init__.py | 47 +++++++++++++++++++------------------- 1 file changed, 24 insertions(+), 23 deletions(-) diff --git a/kapitan/inputs/__init__.py b/kapitan/inputs/__init__.py index 956e9d232..b7f49cab3 100644 --- a/kapitan/inputs/__init__.py +++ b/kapitan/inputs/__init__.py @@ -2,34 +2,35 @@ # # SPDX-License-Identifier: Apache-2.0 +import functools # Import functools for caching +import importlib from typing import Type from kapitan.inventory.model.input_types import InputTypes from .base import InputType -from .copy import Copy -from .external import External -from .helm import Helm -from .jinja2 import Jinja2 -from .jsonnet import Jsonnet -from .kadet import Kadet -from .remove import Remove - -# Dict mapping values for command line flag `--inventory-backend` to the -# associated `Inventory` subclass. -AVAILABLE_INPUT_TYPES: dict[str, Type[InputType]] = { - InputTypes.JINJA2: Jinja2, - InputTypes.HELM: Helm, - InputTypes.JSONNET: Jsonnet, - InputTypes.KADET: Kadet, - InputTypes.COPY: Copy, - InputTypes.EXTERNAL: External, - InputTypes.REMOVE: Remove, -} +@functools.lru_cache(maxsize=None) # Use lru_cache for caching def get_compiler(input_type: InputType) -> Type[InputType]: - """ - Get the `Inventory` subclass associated with the given `backend_name`. - """ - return AVAILABLE_INPUT_TYPES.get(input_type) + """Dynamically imports and returns the compiler class based on input_type.""" + + module_map = { + InputTypes.JINJA2: "jinja2", + InputTypes.HELM: "helm", + InputTypes.JSONNET: "jsonnet", + InputTypes.KADET: "kadet", + InputTypes.COPY: "copy", + InputTypes.EXTERNAL: "external", + InputTypes.REMOVE: "remove", + } + + module_name = module_map.get(input_type) + if module_name: + try: + module = importlib.import_module(f".{module_name}", package=__name__) + return getattr(module, module_name.capitalize()) # Capitalize to get class name + except (ImportError, AttributeError) as e: + raise ImportError(f"Could not import module or class for {input_type}: {e}") from e + else: + return None # Or raise an appropriate error for unknown input_type