provider.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. import collections
  2. import math
  3. from functools import lru_cache
  4. from typing import (
  5. TYPE_CHECKING,
  6. Dict,
  7. Iterable,
  8. Iterator,
  9. Mapping,
  10. Sequence,
  11. TypeVar,
  12. Union,
  13. )
  14. from pip._vendor.resolvelib.providers import AbstractProvider
  15. from .base import Candidate, Constraint, Requirement
  16. from .candidates import REQUIRES_PYTHON_IDENTIFIER
  17. from .factory import Factory
  18. if TYPE_CHECKING:
  19. from pip._vendor.resolvelib.providers import Preference
  20. from pip._vendor.resolvelib.resolvers import RequirementInformation
  21. PreferenceInformation = RequirementInformation[Requirement, Candidate]
  22. _ProviderBase = AbstractProvider[Requirement, Candidate, str]
  23. else:
  24. _ProviderBase = AbstractProvider
  25. # Notes on the relationship between the provider, the factory, and the
  26. # candidate and requirement classes.
  27. #
  28. # The provider is a direct implementation of the resolvelib class. Its role
  29. # is to deliver the API that resolvelib expects.
  30. #
  31. # Rather than work with completely abstract "requirement" and "candidate"
  32. # concepts as resolvelib does, pip has concrete classes implementing these two
  33. # ideas. The API of Requirement and Candidate objects are defined in the base
  34. # classes, but essentially map fairly directly to the equivalent provider
  35. # methods. In particular, `find_matches` and `is_satisfied_by` are
  36. # requirement methods, and `get_dependencies` is a candidate method.
  37. #
  38. # The factory is the interface to pip's internal mechanisms. It is stateless,
  39. # and is created by the resolver and held as a property of the provider. It is
  40. # responsible for creating Requirement and Candidate objects, and provides
  41. # services to those objects (access to pip's finder and preparer).
  42. D = TypeVar("D")
  43. V = TypeVar("V")
  44. def _get_with_identifier(
  45. mapping: Mapping[str, V],
  46. identifier: str,
  47. default: D,
  48. ) -> Union[D, V]:
  49. """Get item from a package name lookup mapping with a resolver identifier.
  50. This extra logic is needed when the target mapping is keyed by package
  51. name, which cannot be directly looked up with an identifier (which may
  52. contain requested extras). Additional logic is added to also look up a value
  53. by "cleaning up" the extras from the identifier.
  54. """
  55. if identifier in mapping:
  56. return mapping[identifier]
  57. # HACK: Theoretically we should check whether this identifier is a valid
  58. # "NAME[EXTRAS]" format, and parse out the name part with packaging or
  59. # some regular expression. But since pip's resolver only spits out three
  60. # kinds of identifiers: normalized PEP 503 names, normalized names plus
  61. # extras, and Requires-Python, we can cheat a bit here.
  62. name, open_bracket, _ = identifier.partition("[")
  63. if open_bracket and name in mapping:
  64. return mapping[name]
  65. return default
  66. class PipProvider(_ProviderBase):
  67. """Pip's provider implementation for resolvelib.
  68. :params constraints: A mapping of constraints specified by the user. Keys
  69. are canonicalized project names.
  70. :params ignore_dependencies: Whether the user specified ``--no-deps``.
  71. :params upgrade_strategy: The user-specified upgrade strategy.
  72. :params user_requested: A set of canonicalized package names that the user
  73. supplied for pip to install/upgrade.
  74. """
  75. def __init__(
  76. self,
  77. factory: Factory,
  78. constraints: Dict[str, Constraint],
  79. ignore_dependencies: bool,
  80. upgrade_strategy: str,
  81. user_requested: Dict[str, int],
  82. ) -> None:
  83. self._factory = factory
  84. self._constraints = constraints
  85. self._ignore_dependencies = ignore_dependencies
  86. self._upgrade_strategy = upgrade_strategy
  87. self._user_requested = user_requested
  88. self._known_depths: Dict[str, float] = collections.defaultdict(lambda: math.inf)
  89. def identify(self, requirement_or_candidate: Union[Requirement, Candidate]) -> str:
  90. return requirement_or_candidate.name
  91. def get_preference(
  92. self,
  93. identifier: str,
  94. resolutions: Mapping[str, Candidate],
  95. candidates: Mapping[str, Iterator[Candidate]],
  96. information: Mapping[str, Iterable["PreferenceInformation"]],
  97. backtrack_causes: Sequence["PreferenceInformation"],
  98. ) -> "Preference":
  99. """Produce a sort key for given requirement based on preference.
  100. The lower the return value is, the more preferred this group of
  101. arguments is.
  102. Currently pip considers the following in order:
  103. * Prefer if any of the known requirements is "direct", e.g. points to an
  104. explicit URL.
  105. * If equal, prefer if any requirement is "pinned", i.e. contains
  106. operator ``===`` or ``==``.
  107. * If equal, calculate an approximate "depth" and resolve requirements
  108. closer to the user-specified requirements first. If the depth cannot
  109. by determined (eg: due to no matching parents), it is considered
  110. infinite.
  111. * Order user-specified requirements by the order they are specified.
  112. * If equal, prefers "non-free" requirements, i.e. contains at least one
  113. operator, such as ``>=`` or ``<``.
  114. * If equal, order alphabetically for consistency (helps debuggability).
  115. """
  116. try:
  117. next(iter(information[identifier]))
  118. except StopIteration:
  119. # There is no information for this identifier, so there's no known
  120. # candidates.
  121. has_information = False
  122. else:
  123. has_information = True
  124. if has_information:
  125. lookups = (r.get_candidate_lookup() for r, _ in information[identifier])
  126. candidate, ireqs = zip(*lookups)
  127. else:
  128. candidate, ireqs = None, ()
  129. operators = [
  130. specifier.operator
  131. for specifier_set in (ireq.specifier for ireq in ireqs if ireq)
  132. for specifier in specifier_set
  133. ]
  134. direct = candidate is not None
  135. pinned = any(op[:2] == "==" for op in operators)
  136. unfree = bool(operators)
  137. try:
  138. requested_order: Union[int, float] = self._user_requested[identifier]
  139. except KeyError:
  140. requested_order = math.inf
  141. if has_information:
  142. parent_depths = (
  143. self._known_depths[parent.name] if parent is not None else 0.0
  144. for _, parent in information[identifier]
  145. )
  146. inferred_depth = min(d for d in parent_depths) + 1.0
  147. else:
  148. inferred_depth = math.inf
  149. else:
  150. inferred_depth = 1.0
  151. self._known_depths[identifier] = inferred_depth
  152. requested_order = self._user_requested.get(identifier, math.inf)
  153. # Requires-Python has only one candidate and the check is basically
  154. # free, so we always do it first to avoid needless work if it fails.
  155. requires_python = identifier == REQUIRES_PYTHON_IDENTIFIER
  156. # Prefer the causes of backtracking on the assumption that the problem
  157. # resolving the dependency tree is related to the failures that caused
  158. # the backtracking
  159. backtrack_cause = self.is_backtrack_cause(identifier, backtrack_causes)
  160. return (
  161. not requires_python,
  162. not direct,
  163. not pinned,
  164. not backtrack_cause,
  165. inferred_depth,
  166. requested_order,
  167. not unfree,
  168. identifier,
  169. )
  170. def find_matches(
  171. self,
  172. identifier: str,
  173. requirements: Mapping[str, Iterator[Requirement]],
  174. incompatibilities: Mapping[str, Iterator[Candidate]],
  175. ) -> Iterable[Candidate]:
  176. def _eligible_for_upgrade(identifier: str) -> bool:
  177. """Are upgrades allowed for this project?
  178. This checks the upgrade strategy, and whether the project was one
  179. that the user specified in the command line, in order to decide
  180. whether we should upgrade if there's a newer version available.
  181. (Note that we don't need access to the `--upgrade` flag, because
  182. an upgrade strategy of "to-satisfy-only" means that `--upgrade`
  183. was not specified).
  184. """
  185. if self._upgrade_strategy == "eager":
  186. return True
  187. elif self._upgrade_strategy == "only-if-needed":
  188. user_order = _get_with_identifier(
  189. self._user_requested,
  190. identifier,
  191. default=None,
  192. )
  193. return user_order is not None
  194. return False
  195. constraint = _get_with_identifier(
  196. self._constraints,
  197. identifier,
  198. default=Constraint.empty(),
  199. )
  200. return self._factory.find_candidates(
  201. identifier=identifier,
  202. requirements=requirements,
  203. constraint=constraint,
  204. prefers_installed=(not _eligible_for_upgrade(identifier)),
  205. incompatibilities=incompatibilities,
  206. is_satisfied_by=self.is_satisfied_by,
  207. )
  208. @lru_cache(maxsize=None)
  209. def is_satisfied_by(self, requirement: Requirement, candidate: Candidate) -> bool:
  210. return requirement.is_satisfied_by(candidate)
  211. def get_dependencies(self, candidate: Candidate) -> Sequence[Requirement]:
  212. with_requires = not self._ignore_dependencies
  213. return [r for r in candidate.iter_dependencies(with_requires) if r is not None]
  214. @staticmethod
  215. def is_backtrack_cause(
  216. identifier: str, backtrack_causes: Sequence["PreferenceInformation"]
  217. ) -> bool:
  218. for backtrack_cause in backtrack_causes:
  219. if identifier == backtrack_cause.requirement.name:
  220. return True
  221. if backtrack_cause.parent and identifier == backtrack_cause.parent.name:
  222. return True
  223. return False