utils.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. # This file is part of Radicale - CalDAV and CardDAV server
  2. # Copyright © 2014 Jean-Marc Martins
  3. # Copyright © 2012-2017 Guillaume Ayoub
  4. # Copyright © 2017-2018 Unrud <unrud@outlook.com>
  5. #
  6. # This library is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This library is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  18. from importlib import import_module, metadata
  19. from typing import Callable, Sequence, Type, TypeVar, Union
  20. from radicale import config
  21. from radicale.log import logger
  22. _T_co = TypeVar("_T_co", covariant=True)
  23. def load_plugin(internal_types: Sequence[str], module_name: str,
  24. class_name: str, base_class: Type[_T_co],
  25. configuration: "config.Configuration") -> _T_co:
  26. type_: Union[str, Callable] = configuration.get(module_name, "type")
  27. if callable(type_):
  28. logger.info("%s type is %r", module_name, type_)
  29. return type_(configuration)
  30. if type_ in internal_types:
  31. module = "radicale.%s.%s" % (module_name, type_)
  32. else:
  33. module = type_
  34. try:
  35. class_ = getattr(import_module(module), class_name)
  36. except Exception as e:
  37. raise RuntimeError("Failed to load %s module %r: %s" %
  38. (module_name, module, e)) from e
  39. logger.info("%s type is %r", module_name, module)
  40. return class_(configuration)
  41. def package_version(name):
  42. return metadata.version(name)