hojichar.utils.load_compose

  1import importlib.util
  2import logging
  3import sys
  4from os import PathLike
  5from pathlib import Path
  6from types import ModuleType
  7from typing import Any, Callable, Optional, Union
  8
  9import hojichar
 10
 11logger = logging.getLogger(__name__)
 12
 13
 14def _load_module(path: Union[str, PathLike]) -> ModuleType:
 15    # HACK type hint `os.PathLike[str]` is not allowed in Python 3.8 or older.
 16    # So I write Union[str, PathLike]
 17    path_obj = Path(path)
 18    module_name = path_obj.stem
 19    spec = importlib.util.spec_from_file_location(module_name, path_obj)
 20    if spec and spec.loader:
 21        module = importlib.util.module_from_spec(spec)
 22        sys.modules[module_name] = module
 23        spec.loader.exec_module(module)
 24    return module
 25
 26
 27def load_filter_from_file(profile_path: Union[str, PathLike]) -> hojichar.Compose:
 28    """
 29    Loading a profile which has `FILTER` variable.
 30    Given path is added to sys.path automaticaly.
 31
 32    Args:
 33        profile_path (str): Path to a Python file that implements custom filter
 34        hojichar.Compose must be defined as FILTER variable in the file.
 35
 36    Raises:
 37        NotImplementedError:
 38
 39    Returns:
 40        hojichar.Compose:
 41    """
 42    sys.path.append(str(Path(profile_path).parent))
 43    module = _load_module(profile_path)
 44    if hasattr(module, "FILTER"):
 45        filter = getattr(module, "FILTER")
 46        if not isinstance(filter, hojichar.Compose):
 47            raise TypeError("FILTER must be hojichar.Compose object.")
 48        return filter
 49    else:
 50        raise NotImplementedError("FILTER is not defined in the profile.")
 51
 52
 53def load_factory_from_file(
 54    profile_path: Union[str, PathLike]
 55) -> Callable[[Optional[Any]], hojichar.Compose]:
 56    """
 57    Loading a function by a profile which has `FACTORY` variable.
 58    Given path is added to sys.path automaticaly.
 59
 60    Args:
 61        profile_path (PathLike): Path to a Python file that implements custom filter
 62
 63    Raises:
 64        NotImplementedError:
 65
 66    Returns:
 67        Callable[[Optional[Any]], hojichar.Compose]:
 68            An alias of the function which returns Compose.
 69    """
 70    sys.path.append(str(Path(profile_path).parent))
 71    module = _load_module(profile_path)
 72    if hasattr(module, "FACTORY"):
 73        factory: Callable[[Optional[Any]], hojichar.Compose] = getattr(module, "FACTORY")
 74        return factory
 75    else:
 76        raise NotImplementedError("FACTORY is not defined in the profile")
 77
 78
 79def load_parametrized_filter_from_file(
 80    profile_path: Union[str, PathLike], *factory_args: str
 81) -> hojichar.Compose:
 82    factory = load_factory_from_file(profile_path)
 83    filter = factory(*factory_args)
 84    return filter
 85
 86
 87def load_compose(profile_path: Union[str, PathLike], *factroy_args: str) -> hojichar.Compose:
 88    """
 89    Loading a Compose file from profile. Loading a Compose file from the profile.
 90    Both `FILTER` and `FACTORY` pattern of the profile is loaded.
 91
 92    Args:
 93        profile_path (PathLike):
 94
 95    Returns:
 96        hojichar.Compose:
 97    """
 98    try:
 99        filter = load_filter_from_file(profile_path)
100        _check_args_num_mismatch(len(factroy_args))
101        return filter
102    except NotImplementedError:
103        return load_parametrized_filter_from_file(profile_path, *factroy_args)
104
105
106def _check_args_num_mismatch(num_args: int) -> None:
107    if num_args > 0:
108        logger.warning(f"Warning: {num_args} arguments are ignored.")
def load_filter_from_file( profile_path: Union[str, os.PathLike]) -> hojichar.core.composition.Compose:
28def load_filter_from_file(profile_path: Union[str, PathLike]) -> hojichar.Compose:
29    """
30    Loading a profile which has `FILTER` variable.
31    Given path is added to sys.path automaticaly.
32
33    Args:
34        profile_path (str): Path to a Python file that implements custom filter
35        hojichar.Compose must be defined as FILTER variable in the file.
36
37    Raises:
38        NotImplementedError:
39
40    Returns:
41        hojichar.Compose:
42    """
43    sys.path.append(str(Path(profile_path).parent))
44    module = _load_module(profile_path)
45    if hasattr(module, "FILTER"):
46        filter = getattr(module, "FILTER")
47        if not isinstance(filter, hojichar.Compose):
48            raise TypeError("FILTER must be hojichar.Compose object.")
49        return filter
50    else:
51        raise NotImplementedError("FILTER is not defined in the profile.")

Loading a profile which has FILTER variable. Given path is added to sys.path automaticaly.

Args: profile_path (str): Path to a Python file that implements custom filter hojichar.Compose must be defined as FILTER variable in the file.

Raises: NotImplementedError:

Returns: hojichar.Compose:

def load_factory_from_file( profile_path: Union[str, os.PathLike]) -> Callable[[Optional[Any]], hojichar.core.composition.Compose]:
54def load_factory_from_file(
55    profile_path: Union[str, PathLike]
56) -> Callable[[Optional[Any]], hojichar.Compose]:
57    """
58    Loading a function by a profile which has `FACTORY` variable.
59    Given path is added to sys.path automaticaly.
60
61    Args:
62        profile_path (PathLike): Path to a Python file that implements custom filter
63
64    Raises:
65        NotImplementedError:
66
67    Returns:
68        Callable[[Optional[Any]], hojichar.Compose]:
69            An alias of the function which returns Compose.
70    """
71    sys.path.append(str(Path(profile_path).parent))
72    module = _load_module(profile_path)
73    if hasattr(module, "FACTORY"):
74        factory: Callable[[Optional[Any]], hojichar.Compose] = getattr(module, "FACTORY")
75        return factory
76    else:
77        raise NotImplementedError("FACTORY is not defined in the profile")

Loading a function by a profile which has FACTORY variable. Given path is added to sys.path automaticaly.

Args: profile_path (PathLike): Path to a Python file that implements custom filter

Raises: NotImplementedError:

Returns: Callable[[Optional[Any]], hojichar.Compose]: An alias of the function which returns Compose.

def load_parametrized_filter_from_file( profile_path: Union[str, os.PathLike], *factory_args: str) -> hojichar.core.composition.Compose:
80def load_parametrized_filter_from_file(
81    profile_path: Union[str, PathLike], *factory_args: str
82) -> hojichar.Compose:
83    factory = load_factory_from_file(profile_path)
84    filter = factory(*factory_args)
85    return filter
def load_compose( profile_path: Union[str, os.PathLike], *factroy_args: str) -> hojichar.core.composition.Compose:
 88def load_compose(profile_path: Union[str, PathLike], *factroy_args: str) -> hojichar.Compose:
 89    """
 90    Loading a Compose file from profile. Loading a Compose file from the profile.
 91    Both `FILTER` and `FACTORY` pattern of the profile is loaded.
 92
 93    Args:
 94        profile_path (PathLike):
 95
 96    Returns:
 97        hojichar.Compose:
 98    """
 99    try:
100        filter = load_filter_from_file(profile_path)
101        _check_args_num_mismatch(len(factroy_args))
102        return filter
103    except NotImplementedError:
104        return load_parametrized_filter_from_file(profile_path, *factroy_args)

Loading a Compose file from profile. Loading a Compose file from the profile. Both FILTER and FACTORY pattern of the profile is loaded.

Args: profile_path (PathLike):

Returns: hojichar.Compose: