utils.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. import sys
  19. from importlib import import_module
  20. from typing import Callable, Sequence, Type, TypeVar, Union
  21. from radicale import config
  22. from radicale.log import logger
  23. if sys.version_info < (3, 8):
  24. import pkg_resources
  25. else:
  26. from importlib import metadata
  27. _T_co = TypeVar("_T_co", covariant=True)
  28. def load_plugin(internal_types: Sequence[str], module_name: str,
  29. class_name: str, base_class: Type[_T_co],
  30. configuration: "config.Configuration") -> _T_co:
  31. type_: Union[str, Callable] = configuration.get(module_name, "type")
  32. if callable(type_):
  33. logger.info("%s type is %r", module_name, type_)
  34. return type_(configuration)
  35. if type_ in internal_types:
  36. module = "radicale.%s.%s" % (module_name, type_)
  37. else:
  38. module = type_
  39. try:
  40. class_ = getattr(import_module(module), class_name)
  41. except Exception as e:
  42. raise RuntimeError("Failed to load %s module %r: %s" %
  43. (module_name, module, e)) from e
  44. logger.info("%s type is %r", module_name, module)
  45. return class_(configuration)
  46. def package_version(name):
  47. if sys.version_info < (3, 8):
  48. return pkg_resources.get_distribution(name).version
  49. return metadata.version(name)