resolver.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. import functools
  2. import logging
  3. from pip._vendor import six
  4. from pip._vendor.packaging.utils import canonicalize_name
  5. from pip._vendor.resolvelib import BaseReporter, ResolutionImpossible
  6. from pip._vendor.resolvelib import Resolver as RLResolver
  7. from pip._internal.exceptions import InstallationError
  8. from pip._internal.req.req_install import check_invalid_constraint_type
  9. from pip._internal.req.req_set import RequirementSet
  10. from pip._internal.resolution.base import BaseResolver
  11. from pip._internal.resolution.resolvelib.provider import PipProvider
  12. from pip._internal.utils.misc import dist_is_editable
  13. from pip._internal.utils.typing import MYPY_CHECK_RUNNING
  14. from .factory import Factory
  15. if MYPY_CHECK_RUNNING:
  16. from typing import Dict, List, Optional, Set, Tuple
  17. from pip._vendor.packaging.specifiers import SpecifierSet
  18. from pip._vendor.resolvelib.resolvers import Result
  19. from pip._vendor.resolvelib.structs import Graph
  20. from pip._internal.cache import WheelCache
  21. from pip._internal.index.package_finder import PackageFinder
  22. from pip._internal.operations.prepare import RequirementPreparer
  23. from pip._internal.req.req_install import InstallRequirement
  24. from pip._internal.resolution.base import InstallRequirementProvider
  25. logger = logging.getLogger(__name__)
  26. class Resolver(BaseResolver):
  27. _allowed_strategies = {"eager", "only-if-needed", "to-satisfy-only"}
  28. def __init__(
  29. self,
  30. preparer, # type: RequirementPreparer
  31. finder, # type: PackageFinder
  32. wheel_cache, # type: Optional[WheelCache]
  33. make_install_req, # type: InstallRequirementProvider
  34. use_user_site, # type: bool
  35. ignore_dependencies, # type: bool
  36. ignore_installed, # type: bool
  37. ignore_requires_python, # type: bool
  38. force_reinstall, # type: bool
  39. upgrade_strategy, # type: str
  40. py_version_info=None, # type: Optional[Tuple[int, ...]]
  41. lazy_wheel=False, # type: bool
  42. ):
  43. super(Resolver, self).__init__()
  44. if lazy_wheel:
  45. logger.warning(
  46. 'pip is using lazily downloaded wheels using HTTP '
  47. 'range requests to obtain dependency information. '
  48. 'This experimental feature is enabled through '
  49. '--use-feature=fast-deps and it is not ready for production.'
  50. )
  51. assert upgrade_strategy in self._allowed_strategies
  52. self.factory = Factory(
  53. finder=finder,
  54. preparer=preparer,
  55. make_install_req=make_install_req,
  56. wheel_cache=wheel_cache,
  57. use_user_site=use_user_site,
  58. force_reinstall=force_reinstall,
  59. ignore_installed=ignore_installed,
  60. ignore_requires_python=ignore_requires_python,
  61. py_version_info=py_version_info,
  62. lazy_wheel=lazy_wheel,
  63. )
  64. self.ignore_dependencies = ignore_dependencies
  65. self.upgrade_strategy = upgrade_strategy
  66. self._result = None # type: Optional[Result]
  67. def resolve(self, root_reqs, check_supported_wheels):
  68. # type: (List[InstallRequirement], bool) -> RequirementSet
  69. constraints = {} # type: Dict[str, SpecifierSet]
  70. user_requested = set() # type: Set[str]
  71. requirements = []
  72. for req in root_reqs:
  73. if req.constraint:
  74. # Ensure we only accept valid constraints
  75. problem = check_invalid_constraint_type(req)
  76. if problem:
  77. raise InstallationError(problem)
  78. name = canonicalize_name(req.name)
  79. if name in constraints:
  80. constraints[name] = constraints[name] & req.specifier
  81. else:
  82. constraints[name] = req.specifier
  83. else:
  84. if req.user_supplied and req.name:
  85. user_requested.add(canonicalize_name(req.name))
  86. r = self.factory.make_requirement_from_install_req(
  87. req, requested_extras=(),
  88. )
  89. if r is not None:
  90. requirements.append(r)
  91. provider = PipProvider(
  92. factory=self.factory,
  93. constraints=constraints,
  94. ignore_dependencies=self.ignore_dependencies,
  95. upgrade_strategy=self.upgrade_strategy,
  96. user_requested=user_requested,
  97. )
  98. reporter = BaseReporter()
  99. resolver = RLResolver(provider, reporter)
  100. try:
  101. try_to_avoid_resolution_too_deep = 2000000
  102. self._result = resolver.resolve(
  103. requirements, max_rounds=try_to_avoid_resolution_too_deep,
  104. )
  105. except ResolutionImpossible as e:
  106. error = self.factory.get_installation_error(e)
  107. six.raise_from(error, e)
  108. req_set = RequirementSet(check_supported_wheels=check_supported_wheels)
  109. for candidate in self._result.mapping.values():
  110. ireq = candidate.get_install_requirement()
  111. if ireq is None:
  112. continue
  113. # Check if there is already an installation under the same name,
  114. # and set a flag for later stages to uninstall it, if needed.
  115. # * There isn't, good -- no uninstalltion needed.
  116. # * The --force-reinstall flag is set. Always reinstall.
  117. # * The installation is different in version or editable-ness, so
  118. # we need to uninstall it to install the new distribution.
  119. # * The installed version is the same as the pending distribution.
  120. # Skip this distrubiton altogether to save work.
  121. installed_dist = self.factory.get_dist_to_uninstall(candidate)
  122. if installed_dist is None:
  123. ireq.should_reinstall = False
  124. elif self.factory.force_reinstall:
  125. ireq.should_reinstall = True
  126. elif installed_dist.parsed_version != candidate.version:
  127. ireq.should_reinstall = True
  128. elif dist_is_editable(installed_dist) != candidate.is_editable:
  129. ireq.should_reinstall = True
  130. else:
  131. continue
  132. link = candidate.source_link
  133. if link and link.is_yanked:
  134. # The reason can contain non-ASCII characters, Unicode
  135. # is required for Python 2.
  136. msg = (
  137. u'The candidate selected for download or install is a '
  138. u'yanked version: {name!r} candidate (version {version} '
  139. u'at {link})\nReason for being yanked: {reason}'
  140. ).format(
  141. name=candidate.name,
  142. version=candidate.version,
  143. link=link,
  144. reason=link.yanked_reason or u'<none given>',
  145. )
  146. logger.warning(msg)
  147. req_set.add_named_requirement(ireq)
  148. return req_set
  149. def get_installation_order(self, req_set):
  150. # type: (RequirementSet) -> List[InstallRequirement]
  151. """Get order for installation of requirements in RequirementSet.
  152. The returned list contains a requirement before another that depends on
  153. it. This helps ensure that the environment is kept consistent as they
  154. get installed one-by-one.
  155. The current implementation creates a topological ordering of the
  156. dependency graph, while breaking any cycles in the graph at arbitrary
  157. points. We make no guarantees about where the cycle would be broken,
  158. other than they would be broken.
  159. """
  160. assert self._result is not None, "must call resolve() first"
  161. graph = self._result.graph
  162. weights = get_topological_weights(graph)
  163. sorted_items = sorted(
  164. req_set.requirements.items(),
  165. key=functools.partial(_req_set_item_sorter, weights=weights),
  166. reverse=True,
  167. )
  168. return [ireq for _, ireq in sorted_items]
  169. def get_topological_weights(graph):
  170. # type: (Graph) -> Dict[Optional[str], int]
  171. """Assign weights to each node based on how "deep" they are.
  172. This implementation may change at any point in the future without prior
  173. notice.
  174. We take the length for the longest path to any node from root, ignoring any
  175. paths that contain a single node twice (i.e. cycles). This is done through
  176. a depth-first search through the graph, while keeping track of the path to
  177. the node.
  178. Cycles in the graph result would result in node being revisited while also
  179. being it's own path. In this case, take no action. This helps ensure we
  180. don't get stuck in a cycle.
  181. When assigning weight, the longer path (i.e. larger length) is preferred.
  182. """
  183. path = set() # type: Set[Optional[str]]
  184. weights = {} # type: Dict[Optional[str], int]
  185. def visit(node):
  186. # type: (Optional[str]) -> None
  187. if node in path:
  188. # We hit a cycle, so we'll break it here.
  189. return
  190. # Time to visit the children!
  191. path.add(node)
  192. for child in graph.iter_children(node):
  193. visit(child)
  194. path.remove(node)
  195. last_known_parent_count = weights.get(node, 0)
  196. weights[node] = max(last_known_parent_count, len(path))
  197. # `None` is guaranteed to be the root node by resolvelib.
  198. visit(None)
  199. # Sanity checks
  200. assert weights[None] == 0
  201. assert len(weights) == len(graph)
  202. return weights
  203. def _req_set_item_sorter(
  204. item, # type: Tuple[str, InstallRequirement]
  205. weights, # type: Dict[Optional[str], int]
  206. ):
  207. # type: (...) -> Tuple[int, str]
  208. """Key function used to sort install requirements for installation.
  209. Based on the "weight" mapping calculated in ``get_installation_order()``.
  210. The canonical package name is returned as the second member as a tie-
  211. breaker to ensure the result is predictable, which is useful in tests.
  212. """
  213. name = canonicalize_name(item[0])
  214. return weights[name], name