Skip to content

Commit

Permalink
allows dynamic import
Browse files Browse the repository at this point in the history
  • Loading branch information
ademariag committed Nov 30, 2024
1 parent 69c8e0b commit b9f2eea
Showing 1 changed file with 24 additions and 23 deletions.
47 changes: 24 additions & 23 deletions kapitan/inputs/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit b9f2eea

Please sign in to comment.