m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

317 lines
12 KiB

6 months ago
  1. import contextlib
  2. import functools
  3. import logging
  4. import os
  5. from typing import TYPE_CHECKING, Dict, List, Optional, Set, Tuple, cast
  6. from pip._vendor.packaging.utils import canonicalize_name
  7. from pip._vendor.resolvelib import BaseReporter, ResolutionImpossible
  8. from pip._vendor.resolvelib import Resolver as RLResolver
  9. from pip._vendor.resolvelib.structs import DirectedGraph
  10. from pip._internal.cache import WheelCache
  11. from pip._internal.index.package_finder import PackageFinder
  12. from pip._internal.operations.prepare import RequirementPreparer
  13. from pip._internal.req.constructors import install_req_extend_extras
  14. from pip._internal.req.req_install import InstallRequirement
  15. from pip._internal.req.req_set import RequirementSet
  16. from pip._internal.resolution.base import BaseResolver, InstallRequirementProvider
  17. from pip._internal.resolution.resolvelib.provider import PipProvider
  18. from pip._internal.resolution.resolvelib.reporter import (
  19. PipDebuggingReporter,
  20. PipReporter,
  21. )
  22. from pip._internal.utils.packaging import get_requirement
  23. from .base import Candidate, Requirement
  24. from .factory import Factory
  25. if TYPE_CHECKING:
  26. from pip._vendor.resolvelib.resolvers import Result as RLResult
  27. Result = RLResult[Requirement, Candidate, str]
  28. logger = logging.getLogger(__name__)
  29. class Resolver(BaseResolver):
  30. _allowed_strategies = {"eager", "only-if-needed", "to-satisfy-only"}
  31. def __init__(
  32. self,
  33. preparer: RequirementPreparer,
  34. finder: PackageFinder,
  35. wheel_cache: Optional[WheelCache],
  36. make_install_req: InstallRequirementProvider,
  37. use_user_site: bool,
  38. ignore_dependencies: bool,
  39. ignore_installed: bool,
  40. ignore_requires_python: bool,
  41. force_reinstall: bool,
  42. upgrade_strategy: str,
  43. py_version_info: Optional[Tuple[int, ...]] = None,
  44. ):
  45. super().__init__()
  46. assert upgrade_strategy in self._allowed_strategies
  47. self.factory = Factory(
  48. finder=finder,
  49. preparer=preparer,
  50. make_install_req=make_install_req,
  51. wheel_cache=wheel_cache,
  52. use_user_site=use_user_site,
  53. force_reinstall=force_reinstall,
  54. ignore_installed=ignore_installed,
  55. ignore_requires_python=ignore_requires_python,
  56. py_version_info=py_version_info,
  57. )
  58. self.ignore_dependencies = ignore_dependencies
  59. self.upgrade_strategy = upgrade_strategy
  60. self._result: Optional[Result] = None
  61. def resolve(
  62. self, root_reqs: List[InstallRequirement], check_supported_wheels: bool
  63. ) -> RequirementSet:
  64. collected = self.factory.collect_root_requirements(root_reqs)
  65. provider = PipProvider(
  66. factory=self.factory,
  67. constraints=collected.constraints,
  68. ignore_dependencies=self.ignore_dependencies,
  69. upgrade_strategy=self.upgrade_strategy,
  70. user_requested=collected.user_requested,
  71. )
  72. if "PIP_RESOLVER_DEBUG" in os.environ:
  73. reporter: BaseReporter = PipDebuggingReporter()
  74. else:
  75. reporter = PipReporter()
  76. resolver: RLResolver[Requirement, Candidate, str] = RLResolver(
  77. provider,
  78. reporter,
  79. )
  80. try:
  81. limit_how_complex_resolution_can_be = 200000
  82. result = self._result = resolver.resolve(
  83. collected.requirements, max_rounds=limit_how_complex_resolution_can_be
  84. )
  85. except ResolutionImpossible as e:
  86. error = self.factory.get_installation_error(
  87. cast("ResolutionImpossible[Requirement, Candidate]", e),
  88. collected.constraints,
  89. )
  90. raise error from e
  91. req_set = RequirementSet(check_supported_wheels=check_supported_wheels)
  92. # process candidates with extras last to ensure their base equivalent is
  93. # already in the req_set if appropriate.
  94. # Python's sort is stable so using a binary key function keeps relative order
  95. # within both subsets.
  96. for candidate in sorted(
  97. result.mapping.values(), key=lambda c: c.name != c.project_name
  98. ):
  99. ireq = candidate.get_install_requirement()
  100. if ireq is None:
  101. if candidate.name != candidate.project_name:
  102. # extend existing req's extras
  103. with contextlib.suppress(KeyError):
  104. req = req_set.get_requirement(candidate.project_name)
  105. req_set.add_named_requirement(
  106. install_req_extend_extras(
  107. req, get_requirement(candidate.name).extras
  108. )
  109. )
  110. continue
  111. # Check if there is already an installation under the same name,
  112. # and set a flag for later stages to uninstall it, if needed.
  113. installed_dist = self.factory.get_dist_to_uninstall(candidate)
  114. if installed_dist is None:
  115. # There is no existing installation -- nothing to uninstall.
  116. ireq.should_reinstall = False
  117. elif self.factory.force_reinstall:
  118. # The --force-reinstall flag is set -- reinstall.
  119. ireq.should_reinstall = True
  120. elif installed_dist.version != candidate.version:
  121. # The installation is different in version -- reinstall.
  122. ireq.should_reinstall = True
  123. elif candidate.is_editable or installed_dist.editable:
  124. # The incoming distribution is editable, or different in
  125. # editable-ness to installation -- reinstall.
  126. ireq.should_reinstall = True
  127. elif candidate.source_link and candidate.source_link.is_file:
  128. # The incoming distribution is under file://
  129. if candidate.source_link.is_wheel:
  130. # is a local wheel -- do nothing.
  131. logger.info(
  132. "%s is already installed with the same version as the "
  133. "provided wheel. Use --force-reinstall to force an "
  134. "installation of the wheel.",
  135. ireq.name,
  136. )
  137. continue
  138. # is a local sdist or path -- reinstall
  139. ireq.should_reinstall = True
  140. else:
  141. continue
  142. link = candidate.source_link
  143. if link and link.is_yanked:
  144. # The reason can contain non-ASCII characters, Unicode
  145. # is required for Python 2.
  146. msg = (
  147. "The candidate selected for download or install is a "
  148. "yanked version: {name!r} candidate (version {version} "
  149. "at {link})\nReason for being yanked: {reason}"
  150. ).format(
  151. name=candidate.name,
  152. version=candidate.version,
  153. link=link,
  154. reason=link.yanked_reason or "<none given>",
  155. )
  156. logger.warning(msg)
  157. req_set.add_named_requirement(ireq)
  158. reqs = req_set.all_requirements
  159. self.factory.preparer.prepare_linked_requirements_more(reqs)
  160. for req in reqs:
  161. req.prepared = True
  162. req.needs_more_preparation = False
  163. return req_set
  164. def get_installation_order(
  165. self, req_set: RequirementSet
  166. ) -> List[InstallRequirement]:
  167. """Get order for installation of requirements in RequirementSet.
  168. The returned list contains a requirement before another that depends on
  169. it. This helps ensure that the environment is kept consistent as they
  170. get installed one-by-one.
  171. The current implementation creates a topological ordering of the
  172. dependency graph, giving more weight to packages with less
  173. or no dependencies, while breaking any cycles in the graph at
  174. arbitrary points. We make no guarantees about where the cycle
  175. would be broken, other than it *would* be broken.
  176. """
  177. assert self._result is not None, "must call resolve() first"
  178. if not req_set.requirements:
  179. # Nothing is left to install, so we do not need an order.
  180. return []
  181. graph = self._result.graph
  182. weights = get_topological_weights(graph, set(req_set.requirements.keys()))
  183. sorted_items = sorted(
  184. req_set.requirements.items(),
  185. key=functools.partial(_req_set_item_sorter, weights=weights),
  186. reverse=True,
  187. )
  188. return [ireq for _, ireq in sorted_items]
  189. def get_topological_weights(
  190. graph: "DirectedGraph[Optional[str]]", requirement_keys: Set[str]
  191. ) -> Dict[Optional[str], int]:
  192. """Assign weights to each node based on how "deep" they are.
  193. This implementation may change at any point in the future without prior
  194. notice.
  195. We first simplify the dependency graph by pruning any leaves and giving them
  196. the highest weight: a package without any dependencies should be installed
  197. first. This is done again and again in the same way, giving ever less weight
  198. to the newly found leaves. The loop stops when no leaves are left: all
  199. remaining packages have at least one dependency left in the graph.
  200. Then we continue with the remaining graph, by taking the length for the
  201. longest path to any node from root, ignoring any paths that contain a single
  202. node twice (i.e. cycles). This is done through a depth-first search through
  203. the graph, while keeping track of the path to the node.
  204. Cycles in the graph result would result in node being revisited while also
  205. being on its own path. In this case, take no action. This helps ensure we
  206. don't get stuck in a cycle.
  207. When assigning weight, the longer path (i.e. larger length) is preferred.
  208. We are only interested in the weights of packages that are in the
  209. requirement_keys.
  210. """
  211. path: Set[Optional[str]] = set()
  212. weights: Dict[Optional[str], int] = {}
  213. def visit(node: Optional[str]) -> None:
  214. if node in path:
  215. # We hit a cycle, so we'll break it here.
  216. return
  217. # Time to visit the children!
  218. path.add(node)
  219. for child in graph.iter_children(node):
  220. visit(child)
  221. path.remove(node)
  222. if node not in requirement_keys:
  223. return
  224. last_known_parent_count = weights.get(node, 0)
  225. weights[node] = max(last_known_parent_count, len(path))
  226. # Simplify the graph, pruning leaves that have no dependencies.
  227. # This is needed for large graphs (say over 200 packages) because the
  228. # `visit` function is exponentially slower then, taking minutes.
  229. # See https://github.com/pypa/pip/issues/10557
  230. # We will loop until we explicitly break the loop.
  231. while True:
  232. leaves = set()
  233. for key in graph:
  234. if key is None:
  235. continue
  236. for _child in graph.iter_children(key):
  237. # This means we have at least one child
  238. break
  239. else:
  240. # No child.
  241. leaves.add(key)
  242. if not leaves:
  243. # We are done simplifying.
  244. break
  245. # Calculate the weight for the leaves.
  246. weight = len(graph) - 1
  247. for leaf in leaves:
  248. if leaf not in requirement_keys:
  249. continue
  250. weights[leaf] = weight
  251. # Remove the leaves from the graph, making it simpler.
  252. for leaf in leaves:
  253. graph.remove(leaf)
  254. # Visit the remaining graph.
  255. # `None` is guaranteed to be the root node by resolvelib.
  256. visit(None)
  257. # Sanity check: all requirement keys should be in the weights,
  258. # and no other keys should be in the weights.
  259. difference = set(weights.keys()).difference(requirement_keys)
  260. assert not difference, difference
  261. return weights
  262. def _req_set_item_sorter(
  263. item: Tuple[str, InstallRequirement],
  264. weights: Dict[Optional[str], int],
  265. ) -> Tuple[int, str]:
  266. """Key function used to sort install requirements for installation.
  267. Based on the "weight" mapping calculated in ``get_installation_order()``.
  268. The canonical package name is returned as the second member as a tie-
  269. breaker to ensure the result is predictable, which is useful in tests.
  270. """
  271. name = canonicalize_name(item[0])
  272. return weights[name], name