check_dependencies.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. # Copyright 2022 The Matrix.org Foundation C.I.C.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. #
  15. """
  16. This module exposes a single function which checks synapse's dependencies are present
  17. and correctly versioned. It makes use of `importlib.metadata` to do so. The details
  18. are a bit murky: there's no easy way to get a map from "extras" to the packages they
  19. require. But this is probably just symptomatic of Python's package management.
  20. """
  21. import logging
  22. from typing import Iterable, NamedTuple, Optional
  23. from packaging.requirements import Requirement
  24. DISTRIBUTION_NAME = "matrix-synapse"
  25. try:
  26. from importlib import metadata
  27. except ImportError:
  28. import importlib_metadata as metadata # type: ignore[no-redef]
  29. __all__ = ["check_requirements"]
  30. class DependencyException(Exception):
  31. @property
  32. def message(self) -> str:
  33. return "\n".join(
  34. [
  35. "Missing Requirements: %s" % (", ".join(self.dependencies),),
  36. "To install run:",
  37. " pip install --upgrade --force %s" % (" ".join(self.dependencies),),
  38. "",
  39. ]
  40. )
  41. @property
  42. def dependencies(self) -> Iterable[str]:
  43. for i in self.args[0]:
  44. yield '"' + i + '"'
  45. DEV_EXTRAS = {"lint", "mypy", "test", "dev"}
  46. RUNTIME_EXTRAS = (
  47. set(metadata.metadata(DISTRIBUTION_NAME).get_all("Provides-Extra")) - DEV_EXTRAS
  48. )
  49. VERSION = metadata.version(DISTRIBUTION_NAME)
  50. def _is_dev_dependency(req: Requirement) -> bool:
  51. return req.marker is not None and any(
  52. req.marker.evaluate({"extra": e}) for e in DEV_EXTRAS
  53. )
  54. class Dependency(NamedTuple):
  55. requirement: Requirement
  56. must_be_installed: bool
  57. def _generic_dependencies() -> Iterable[Dependency]:
  58. """Yield pairs (requirement, must_be_installed)."""
  59. requirements = metadata.requires(DISTRIBUTION_NAME)
  60. assert requirements is not None
  61. for raw_requirement in requirements:
  62. req = Requirement(raw_requirement)
  63. if _is_dev_dependency(req):
  64. continue
  65. # https://packaging.pypa.io/en/latest/markers.html#usage notes that
  66. # > Evaluating an extra marker with no environment is an error
  67. # so we pass in a dummy empty extra value here.
  68. must_be_installed = req.marker is None or req.marker.evaluate({"extra": ""})
  69. yield Dependency(req, must_be_installed)
  70. def _dependencies_for_extra(extra: str) -> Iterable[Dependency]:
  71. """Yield additional dependencies needed for a given `extra`."""
  72. requirements = metadata.requires(DISTRIBUTION_NAME)
  73. assert requirements is not None
  74. for raw_requirement in requirements:
  75. req = Requirement(raw_requirement)
  76. if _is_dev_dependency(req):
  77. continue
  78. # Exclude mandatory deps by only selecting deps needed with this extra.
  79. if (
  80. req.marker is not None
  81. and req.marker.evaluate({"extra": extra})
  82. and not req.marker.evaluate({"extra": ""})
  83. ):
  84. yield Dependency(req, True)
  85. def _not_installed(requirement: Requirement, extra: Optional[str] = None) -> str:
  86. if extra:
  87. return (
  88. f"Synapse {VERSION} needs {requirement.name} for {extra}, "
  89. f"but it is not installed"
  90. )
  91. else:
  92. return f"Synapse {VERSION} needs {requirement.name}, but it is not installed"
  93. def _incorrect_version(
  94. requirement: Requirement, got: str, extra: Optional[str] = None
  95. ) -> str:
  96. if extra:
  97. return (
  98. f"Synapse {VERSION} needs {requirement} for {extra}, "
  99. f"but got {requirement.name}=={got}"
  100. )
  101. else:
  102. return (
  103. f"Synapse {VERSION} needs {requirement}, but got {requirement.name}=={got}"
  104. )
  105. def _no_reported_version(requirement: Requirement, extra: Optional[str] = None) -> str:
  106. if extra:
  107. return (
  108. f"Synapse {VERSION} needs {requirement} for {extra}, "
  109. f"but can't determine {requirement.name}'s version"
  110. )
  111. else:
  112. return (
  113. f"Synapse {VERSION} needs {requirement}, "
  114. f"but can't determine {requirement.name}'s version"
  115. )
  116. def check_requirements(extra: Optional[str] = None) -> None:
  117. """Check Synapse's dependencies are present and correctly versioned.
  118. If provided, `extra` must be the name of an pacakging extra (e.g. "saml2" in
  119. `pip install matrix-synapse[saml2]`).
  120. If `extra` is None, this function checks that
  121. - all mandatory dependencies are installed and correctly versioned, and
  122. - each optional dependency that's installed is correctly versioned.
  123. If `extra` is not None, this function checks that
  124. - the dependencies needed for that extra are installed and correctly versioned.
  125. :raises DependencyException: if a dependency is missing or incorrectly versioned.
  126. :raises ValueError: if this extra does not exist.
  127. """
  128. # First work out which dependencies are required, and which are optional.
  129. if extra is None:
  130. dependencies = _generic_dependencies()
  131. elif extra in RUNTIME_EXTRAS:
  132. dependencies = _dependencies_for_extra(extra)
  133. else:
  134. raise ValueError(f"Synapse {VERSION} does not provide the feature '{extra}'")
  135. deps_unfulfilled = []
  136. errors = []
  137. for (requirement, must_be_installed) in dependencies:
  138. try:
  139. dist: metadata.Distribution = metadata.distribution(requirement.name)
  140. except metadata.PackageNotFoundError:
  141. if must_be_installed:
  142. deps_unfulfilled.append(requirement.name)
  143. errors.append(_not_installed(requirement, extra))
  144. else:
  145. if dist.version is None:
  146. # This shouldn't happen---it suggests a borked virtualenv. (See #12223)
  147. # Try to give a vaguely helpful error message anyway.
  148. # Type-ignore: the annotations don't reflect reality: see
  149. # https://github.com/python/typeshed/issues/7513
  150. # https://bugs.python.org/issue47060
  151. deps_unfulfilled.append(requirement.name) # type: ignore[unreachable]
  152. errors.append(_no_reported_version(requirement, extra))
  153. # We specify prereleases=True to allow prereleases such as RCs.
  154. elif not requirement.specifier.contains(dist.version, prereleases=True):
  155. deps_unfulfilled.append(requirement.name)
  156. errors.append(_incorrect_version(requirement, dist.version, extra))
  157. if deps_unfulfilled:
  158. for err in errors:
  159. logging.error(err)
  160. raise DependencyException(deps_unfulfilled)