2018-11-24 19:00:02 +00:00
|
|
|
# pragma pylint: disable=attribute-defined-outside-init
|
|
|
|
|
|
|
|
"""
|
2018-11-24 19:02:29 +00:00
|
|
|
This module load custom objects
|
2018-11-24 19:00:02 +00:00
|
|
|
"""
|
|
|
|
import importlib.util
|
|
|
|
import inspect
|
|
|
|
import logging
|
2018-11-24 19:39:16 +00:00
|
|
|
from pathlib import Path
|
2019-12-24 12:34:37 +00:00
|
|
|
from typing import Any, Generator, List, Optional, Tuple, Type, Union
|
2018-11-24 19:00:02 +00:00
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
2019-09-12 01:39:52 +00:00
|
|
|
class IResolver:
|
2018-11-24 19:00:02 +00:00
|
|
|
"""
|
2018-11-25 08:55:36 +00:00
|
|
|
This class contains all the logic to load custom classes
|
2018-11-24 19:00:02 +00:00
|
|
|
"""
|
2019-12-24 12:34:37 +00:00
|
|
|
# Childclasses need to override this
|
|
|
|
object_type: Type[Any]
|
2018-11-24 19:00:02 +00:00
|
|
|
|
2019-12-23 08:53:55 +00:00
|
|
|
@staticmethod
|
|
|
|
def build_search_paths(config, current_path: Path, user_subdir: Optional[str] = None,
|
2019-10-15 10:11:14 +00:00
|
|
|
extra_dir: Optional[str] = None) -> List[Path]:
|
|
|
|
|
2019-10-30 14:55:35 +00:00
|
|
|
abs_paths: List[Path] = [current_path]
|
|
|
|
|
|
|
|
if user_subdir:
|
|
|
|
abs_paths.insert(0, config['user_data_dir'].joinpath(user_subdir))
|
2019-10-15 10:11:14 +00:00
|
|
|
|
|
|
|
if extra_dir:
|
|
|
|
# Add extra directory to the top of the search paths
|
|
|
|
abs_paths.insert(0, Path(extra_dir).resolve())
|
|
|
|
|
|
|
|
return abs_paths
|
|
|
|
|
2019-12-24 12:34:37 +00:00
|
|
|
@classmethod
|
|
|
|
def _get_valid_object(cls, module_path: Path,
|
2019-10-14 12:41:39 +00:00
|
|
|
object_name: str) -> Generator[Any, None, None]:
|
2018-11-24 19:00:02 +00:00
|
|
|
"""
|
2019-10-14 12:41:39 +00:00
|
|
|
Generator returning objects with matching object_type and object_name in the path given.
|
2018-11-24 19:00:02 +00:00
|
|
|
:param module_path: absolute path to the module
|
|
|
|
:param object_name: Class name of the object
|
2019-10-14 12:41:39 +00:00
|
|
|
:return: generator containing matching objects
|
2018-11-24 19:00:02 +00:00
|
|
|
"""
|
|
|
|
|
|
|
|
# Generate spec based on absolute path
|
2019-08-18 16:06:57 +00:00
|
|
|
# Pass object_name as first argument to have logging print a reasonable name.
|
|
|
|
spec = importlib.util.spec_from_file_location(object_name, str(module_path))
|
2018-11-24 19:00:02 +00:00
|
|
|
module = importlib.util.module_from_spec(spec)
|
2019-03-11 18:49:03 +00:00
|
|
|
try:
|
|
|
|
spec.loader.exec_module(module) # type: ignore # importlib does not use typehints
|
2019-03-15 18:50:38 +00:00
|
|
|
except (ModuleNotFoundError, SyntaxError) as err:
|
2019-03-11 18:49:03 +00:00
|
|
|
# Catch errors in case a specific module is not installed
|
2019-03-15 18:50:38 +00:00
|
|
|
logger.warning(f"Could not import {module_path} due to '{err}'")
|
2018-11-24 19:00:02 +00:00
|
|
|
|
|
|
|
valid_objects_gen = (
|
|
|
|
obj for name, obj in inspect.getmembers(module, inspect.isclass)
|
2019-12-24 12:34:37 +00:00
|
|
|
if object_name == name and cls.object_type in obj.__bases__
|
2018-11-24 19:00:02 +00:00
|
|
|
)
|
2019-10-14 12:41:39 +00:00
|
|
|
return valid_objects_gen
|
2018-11-24 19:00:02 +00:00
|
|
|
|
2019-12-24 12:34:37 +00:00
|
|
|
@classmethod
|
|
|
|
def _search_object(cls, directory: Path, object_name: str,
|
2019-07-12 20:45:49 +00:00
|
|
|
kwargs: dict = {}) -> Union[Tuple[Any, Path], Tuple[None, None]]:
|
2018-11-24 19:00:02 +00:00
|
|
|
"""
|
|
|
|
Search for the objectname in the given directory
|
|
|
|
:param directory: relative or absolute directory path
|
2019-12-24 12:34:37 +00:00
|
|
|
:param object_name: ClassName of the object to load
|
2018-11-24 19:00:02 +00:00
|
|
|
:return: object instance
|
|
|
|
"""
|
2019-12-24 12:34:37 +00:00
|
|
|
logger.debug("Searching for %s %s in '%s'",
|
|
|
|
cls.object_type.__name__, object_name, directory)
|
2018-11-24 19:39:16 +00:00
|
|
|
for entry in directory.iterdir():
|
2018-11-24 19:00:02 +00:00
|
|
|
# Only consider python files
|
2018-11-24 19:39:16 +00:00
|
|
|
if not str(entry).endswith('.py'):
|
2018-11-24 19:00:02 +00:00
|
|
|
logger.debug('Ignoring %s', entry)
|
|
|
|
continue
|
2019-07-25 05:16:52 +00:00
|
|
|
module_path = entry.resolve()
|
2019-10-14 12:41:39 +00:00
|
|
|
|
2019-12-24 12:34:37 +00:00
|
|
|
obj = next(cls._get_valid_object(module_path, object_name), None)
|
2019-10-14 12:41:39 +00:00
|
|
|
|
2018-11-24 19:00:02 +00:00
|
|
|
if obj:
|
2019-07-12 20:45:49 +00:00
|
|
|
return (obj(**kwargs), module_path)
|
|
|
|
return (None, None)
|
2019-07-21 13:03:12 +00:00
|
|
|
|
2019-12-24 12:34:37 +00:00
|
|
|
@classmethod
|
|
|
|
def _load_object(cls, paths: List[Path], object_name: str,
|
2019-07-21 17:21:50 +00:00
|
|
|
kwargs: dict = {}) -> Optional[Any]:
|
2019-07-21 13:03:12 +00:00
|
|
|
"""
|
|
|
|
Try to load object from path list.
|
|
|
|
"""
|
|
|
|
|
|
|
|
for _path in paths:
|
|
|
|
try:
|
2019-12-24 12:34:37 +00:00
|
|
|
(module, module_path) = cls._search_object(directory=_path,
|
|
|
|
object_name=object_name,
|
|
|
|
kwargs=kwargs)
|
2019-07-21 13:03:12 +00:00
|
|
|
if module:
|
|
|
|
logger.info(
|
2019-12-24 12:34:37 +00:00
|
|
|
f"Using resolved {cls.object_type.__name__.lower()[1:]} {object_name} "
|
2019-07-21 13:03:12 +00:00
|
|
|
f"from '{module_path}'...")
|
2019-07-21 13:25:48 +00:00
|
|
|
return module
|
2019-07-21 13:03:12 +00:00
|
|
|
except FileNotFoundError:
|
2019-07-25 05:16:52 +00:00
|
|
|
logger.warning('Path "%s" does not exist.', _path.resolve())
|
2019-07-21 13:03:12 +00:00
|
|
|
|
2019-07-21 13:25:48 +00:00
|
|
|
return None
|