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.

597 lines
21 KiB

6 months ago
  1. import logging
  2. import sys
  3. from typing import TYPE_CHECKING, Any, FrozenSet, Iterable, Optional, Tuple, Union, cast
  4. from pip._vendor.packaging.utils import NormalizedName, canonicalize_name
  5. from pip._vendor.packaging.version import Version
  6. from pip._internal.exceptions import (
  7. HashError,
  8. InstallationSubprocessError,
  9. MetadataInconsistent,
  10. )
  11. from pip._internal.metadata import BaseDistribution
  12. from pip._internal.models.link import Link, links_equivalent
  13. from pip._internal.models.wheel import Wheel
  14. from pip._internal.req.constructors import (
  15. install_req_from_editable,
  16. install_req_from_line,
  17. )
  18. from pip._internal.req.req_install import InstallRequirement
  19. from pip._internal.utils.direct_url_helpers import direct_url_from_link
  20. from pip._internal.utils.misc import normalize_version_info
  21. from .base import Candidate, CandidateVersion, Requirement, format_name
  22. if TYPE_CHECKING:
  23. from .factory import Factory
  24. logger = logging.getLogger(__name__)
  25. BaseCandidate = Union[
  26. "AlreadyInstalledCandidate",
  27. "EditableCandidate",
  28. "LinkCandidate",
  29. ]
  30. # Avoid conflicting with the PyPI package "Python".
  31. REQUIRES_PYTHON_IDENTIFIER = cast(NormalizedName, "<Python from Requires-Python>")
  32. def as_base_candidate(candidate: Candidate) -> Optional[BaseCandidate]:
  33. """The runtime version of BaseCandidate."""
  34. base_candidate_classes = (
  35. AlreadyInstalledCandidate,
  36. EditableCandidate,
  37. LinkCandidate,
  38. )
  39. if isinstance(candidate, base_candidate_classes):
  40. return candidate
  41. return None
  42. def make_install_req_from_link(
  43. link: Link, template: InstallRequirement
  44. ) -> InstallRequirement:
  45. assert not template.editable, "template is editable"
  46. if template.req:
  47. line = str(template.req)
  48. else:
  49. line = link.url
  50. ireq = install_req_from_line(
  51. line,
  52. user_supplied=template.user_supplied,
  53. comes_from=template.comes_from,
  54. use_pep517=template.use_pep517,
  55. isolated=template.isolated,
  56. constraint=template.constraint,
  57. global_options=template.global_options,
  58. hash_options=template.hash_options,
  59. config_settings=template.config_settings,
  60. )
  61. ireq.original_link = template.original_link
  62. ireq.link = link
  63. ireq.extras = template.extras
  64. return ireq
  65. def make_install_req_from_editable(
  66. link: Link, template: InstallRequirement
  67. ) -> InstallRequirement:
  68. assert template.editable, "template not editable"
  69. ireq = install_req_from_editable(
  70. link.url,
  71. user_supplied=template.user_supplied,
  72. comes_from=template.comes_from,
  73. use_pep517=template.use_pep517,
  74. isolated=template.isolated,
  75. constraint=template.constraint,
  76. permit_editable_wheels=template.permit_editable_wheels,
  77. global_options=template.global_options,
  78. hash_options=template.hash_options,
  79. config_settings=template.config_settings,
  80. )
  81. ireq.extras = template.extras
  82. return ireq
  83. def _make_install_req_from_dist(
  84. dist: BaseDistribution, template: InstallRequirement
  85. ) -> InstallRequirement:
  86. if template.req:
  87. line = str(template.req)
  88. elif template.link:
  89. line = f"{dist.canonical_name} @ {template.link.url}"
  90. else:
  91. line = f"{dist.canonical_name}=={dist.version}"
  92. ireq = install_req_from_line(
  93. line,
  94. user_supplied=template.user_supplied,
  95. comes_from=template.comes_from,
  96. use_pep517=template.use_pep517,
  97. isolated=template.isolated,
  98. constraint=template.constraint,
  99. global_options=template.global_options,
  100. hash_options=template.hash_options,
  101. config_settings=template.config_settings,
  102. )
  103. ireq.satisfied_by = dist
  104. return ireq
  105. class _InstallRequirementBackedCandidate(Candidate):
  106. """A candidate backed by an ``InstallRequirement``.
  107. This represents a package request with the target not being already
  108. in the environment, and needs to be fetched and installed. The backing
  109. ``InstallRequirement`` is responsible for most of the leg work; this
  110. class exposes appropriate information to the resolver.
  111. :param link: The link passed to the ``InstallRequirement``. The backing
  112. ``InstallRequirement`` will use this link to fetch the distribution.
  113. :param source_link: The link this candidate "originates" from. This is
  114. different from ``link`` when the link is found in the wheel cache.
  115. ``link`` would point to the wheel cache, while this points to the
  116. found remote link (e.g. from pypi.org).
  117. """
  118. dist: BaseDistribution
  119. is_installed = False
  120. def __init__(
  121. self,
  122. link: Link,
  123. source_link: Link,
  124. ireq: InstallRequirement,
  125. factory: "Factory",
  126. name: Optional[NormalizedName] = None,
  127. version: Optional[CandidateVersion] = None,
  128. ) -> None:
  129. self._link = link
  130. self._source_link = source_link
  131. self._factory = factory
  132. self._ireq = ireq
  133. self._name = name
  134. self._version = version
  135. self.dist = self._prepare()
  136. def __str__(self) -> str:
  137. return f"{self.name} {self.version}"
  138. def __repr__(self) -> str:
  139. return f"{self.__class__.__name__}({str(self._link)!r})"
  140. def __hash__(self) -> int:
  141. return hash((self.__class__, self._link))
  142. def __eq__(self, other: Any) -> bool:
  143. if isinstance(other, self.__class__):
  144. return links_equivalent(self._link, other._link)
  145. return False
  146. @property
  147. def source_link(self) -> Optional[Link]:
  148. return self._source_link
  149. @property
  150. def project_name(self) -> NormalizedName:
  151. """The normalised name of the project the candidate refers to"""
  152. if self._name is None:
  153. self._name = self.dist.canonical_name
  154. return self._name
  155. @property
  156. def name(self) -> str:
  157. return self.project_name
  158. @property
  159. def version(self) -> CandidateVersion:
  160. if self._version is None:
  161. self._version = self.dist.version
  162. return self._version
  163. def format_for_error(self) -> str:
  164. return "{} {} (from {})".format(
  165. self.name,
  166. self.version,
  167. self._link.file_path if self._link.is_file else self._link,
  168. )
  169. def _prepare_distribution(self) -> BaseDistribution:
  170. raise NotImplementedError("Override in subclass")
  171. def _check_metadata_consistency(self, dist: BaseDistribution) -> None:
  172. """Check for consistency of project name and version of dist."""
  173. if self._name is not None and self._name != dist.canonical_name:
  174. raise MetadataInconsistent(
  175. self._ireq,
  176. "name",
  177. self._name,
  178. dist.canonical_name,
  179. )
  180. if self._version is not None and self._version != dist.version:
  181. raise MetadataInconsistent(
  182. self._ireq,
  183. "version",
  184. str(self._version),
  185. str(dist.version),
  186. )
  187. def _prepare(self) -> BaseDistribution:
  188. try:
  189. dist = self._prepare_distribution()
  190. except HashError as e:
  191. # Provide HashError the underlying ireq that caused it. This
  192. # provides context for the resulting error message to show the
  193. # offending line to the user.
  194. e.req = self._ireq
  195. raise
  196. except InstallationSubprocessError as exc:
  197. # The output has been presented already, so don't duplicate it.
  198. exc.context = "See above for output."
  199. raise
  200. self._check_metadata_consistency(dist)
  201. return dist
  202. def iter_dependencies(self, with_requires: bool) -> Iterable[Optional[Requirement]]:
  203. requires = self.dist.iter_dependencies() if with_requires else ()
  204. for r in requires:
  205. yield from self._factory.make_requirements_from_spec(str(r), self._ireq)
  206. yield self._factory.make_requires_python_requirement(self.dist.requires_python)
  207. def get_install_requirement(self) -> Optional[InstallRequirement]:
  208. return self._ireq
  209. class LinkCandidate(_InstallRequirementBackedCandidate):
  210. is_editable = False
  211. def __init__(
  212. self,
  213. link: Link,
  214. template: InstallRequirement,
  215. factory: "Factory",
  216. name: Optional[NormalizedName] = None,
  217. version: Optional[CandidateVersion] = None,
  218. ) -> None:
  219. source_link = link
  220. cache_entry = factory.get_wheel_cache_entry(source_link, name)
  221. if cache_entry is not None:
  222. logger.debug("Using cached wheel link: %s", cache_entry.link)
  223. link = cache_entry.link
  224. ireq = make_install_req_from_link(link, template)
  225. assert ireq.link == link
  226. if ireq.link.is_wheel and not ireq.link.is_file:
  227. wheel = Wheel(ireq.link.filename)
  228. wheel_name = canonicalize_name(wheel.name)
  229. assert name == wheel_name, f"{name!r} != {wheel_name!r} for wheel"
  230. # Version may not be present for PEP 508 direct URLs
  231. if version is not None:
  232. wheel_version = Version(wheel.version)
  233. assert version == wheel_version, "{!r} != {!r} for wheel {}".format(
  234. version, wheel_version, name
  235. )
  236. if cache_entry is not None:
  237. assert ireq.link.is_wheel
  238. assert ireq.link.is_file
  239. if cache_entry.persistent and template.link is template.original_link:
  240. ireq.cached_wheel_source_link = source_link
  241. if cache_entry.origin is not None:
  242. ireq.download_info = cache_entry.origin
  243. else:
  244. # Legacy cache entry that does not have origin.json.
  245. # download_info may miss the archive_info.hashes field.
  246. ireq.download_info = direct_url_from_link(
  247. source_link, link_is_in_wheel_cache=cache_entry.persistent
  248. )
  249. super().__init__(
  250. link=link,
  251. source_link=source_link,
  252. ireq=ireq,
  253. factory=factory,
  254. name=name,
  255. version=version,
  256. )
  257. def _prepare_distribution(self) -> BaseDistribution:
  258. preparer = self._factory.preparer
  259. return preparer.prepare_linked_requirement(self._ireq, parallel_builds=True)
  260. class EditableCandidate(_InstallRequirementBackedCandidate):
  261. is_editable = True
  262. def __init__(
  263. self,
  264. link: Link,
  265. template: InstallRequirement,
  266. factory: "Factory",
  267. name: Optional[NormalizedName] = None,
  268. version: Optional[CandidateVersion] = None,
  269. ) -> None:
  270. super().__init__(
  271. link=link,
  272. source_link=link,
  273. ireq=make_install_req_from_editable(link, template),
  274. factory=factory,
  275. name=name,
  276. version=version,
  277. )
  278. def _prepare_distribution(self) -> BaseDistribution:
  279. return self._factory.preparer.prepare_editable_requirement(self._ireq)
  280. class AlreadyInstalledCandidate(Candidate):
  281. is_installed = True
  282. source_link = None
  283. def __init__(
  284. self,
  285. dist: BaseDistribution,
  286. template: InstallRequirement,
  287. factory: "Factory",
  288. ) -> None:
  289. self.dist = dist
  290. self._ireq = _make_install_req_from_dist(dist, template)
  291. self._factory = factory
  292. self._version = None
  293. # This is just logging some messages, so we can do it eagerly.
  294. # The returned dist would be exactly the same as self.dist because we
  295. # set satisfied_by in _make_install_req_from_dist.
  296. # TODO: Supply reason based on force_reinstall and upgrade_strategy.
  297. skip_reason = "already satisfied"
  298. factory.preparer.prepare_installed_requirement(self._ireq, skip_reason)
  299. def __str__(self) -> str:
  300. return str(self.dist)
  301. def __repr__(self) -> str:
  302. return f"{self.__class__.__name__}({self.dist!r})"
  303. def __hash__(self) -> int:
  304. return hash((self.__class__, self.name, self.version))
  305. def __eq__(self, other: Any) -> bool:
  306. if isinstance(other, self.__class__):
  307. return self.name == other.name and self.version == other.version
  308. return False
  309. @property
  310. def project_name(self) -> NormalizedName:
  311. return self.dist.canonical_name
  312. @property
  313. def name(self) -> str:
  314. return self.project_name
  315. @property
  316. def version(self) -> CandidateVersion:
  317. if self._version is None:
  318. self._version = self.dist.version
  319. return self._version
  320. @property
  321. def is_editable(self) -> bool:
  322. return self.dist.editable
  323. def format_for_error(self) -> str:
  324. return f"{self.name} {self.version} (Installed)"
  325. def iter_dependencies(self, with_requires: bool) -> Iterable[Optional[Requirement]]:
  326. if not with_requires:
  327. return
  328. for r in self.dist.iter_dependencies():
  329. yield from self._factory.make_requirements_from_spec(str(r), self._ireq)
  330. def get_install_requirement(self) -> Optional[InstallRequirement]:
  331. return None
  332. class ExtrasCandidate(Candidate):
  333. """A candidate that has 'extras', indicating additional dependencies.
  334. Requirements can be for a project with dependencies, something like
  335. foo[extra]. The extras don't affect the project/version being installed
  336. directly, but indicate that we need additional dependencies. We model that
  337. by having an artificial ExtrasCandidate that wraps the "base" candidate.
  338. The ExtrasCandidate differs from the base in the following ways:
  339. 1. It has a unique name, of the form foo[extra]. This causes the resolver
  340. to treat it as a separate node in the dependency graph.
  341. 2. When we're getting the candidate's dependencies,
  342. a) We specify that we want the extra dependencies as well.
  343. b) We add a dependency on the base candidate.
  344. See below for why this is needed.
  345. 3. We return None for the underlying InstallRequirement, as the base
  346. candidate will provide it, and we don't want to end up with duplicates.
  347. The dependency on the base candidate is needed so that the resolver can't
  348. decide that it should recommend foo[extra1] version 1.0 and foo[extra2]
  349. version 2.0. Having those candidates depend on foo=1.0 and foo=2.0
  350. respectively forces the resolver to recognise that this is a conflict.
  351. """
  352. def __init__(
  353. self,
  354. base: BaseCandidate,
  355. extras: FrozenSet[str],
  356. *,
  357. comes_from: Optional[InstallRequirement] = None,
  358. ) -> None:
  359. """
  360. :param comes_from: the InstallRequirement that led to this candidate if it
  361. differs from the base's InstallRequirement. This will often be the
  362. case in the sense that this candidate's requirement has the extras
  363. while the base's does not. Unlike the InstallRequirement backed
  364. candidates, this requirement is used solely for reporting purposes,
  365. it does not do any leg work.
  366. """
  367. self.base = base
  368. self.extras = frozenset(canonicalize_name(e) for e in extras)
  369. # If any extras are requested in their non-normalized forms, keep track
  370. # of their raw values. This is needed when we look up dependencies
  371. # since PEP 685 has not been implemented for marker-matching, and using
  372. # the non-normalized extra for lookup ensures the user can select a
  373. # non-normalized extra in a package with its non-normalized form.
  374. # TODO: Remove this attribute when packaging is upgraded to support the
  375. # marker comparison logic specified in PEP 685.
  376. self._unnormalized_extras = extras.difference(self.extras)
  377. self._comes_from = comes_from if comes_from is not None else self.base._ireq
  378. def __str__(self) -> str:
  379. name, rest = str(self.base).split(" ", 1)
  380. return "{}[{}] {}".format(name, ",".join(self.extras), rest)
  381. def __repr__(self) -> str:
  382. return f"{self.__class__.__name__}(base={self.base!r}, extras={self.extras!r})"
  383. def __hash__(self) -> int:
  384. return hash((self.base, self.extras))
  385. def __eq__(self, other: Any) -> bool:
  386. if isinstance(other, self.__class__):
  387. return self.base == other.base and self.extras == other.extras
  388. return False
  389. @property
  390. def project_name(self) -> NormalizedName:
  391. return self.base.project_name
  392. @property
  393. def name(self) -> str:
  394. """The normalised name of the project the candidate refers to"""
  395. return format_name(self.base.project_name, self.extras)
  396. @property
  397. def version(self) -> CandidateVersion:
  398. return self.base.version
  399. def format_for_error(self) -> str:
  400. return "{} [{}]".format(
  401. self.base.format_for_error(), ", ".join(sorted(self.extras))
  402. )
  403. @property
  404. def is_installed(self) -> bool:
  405. return self.base.is_installed
  406. @property
  407. def is_editable(self) -> bool:
  408. return self.base.is_editable
  409. @property
  410. def source_link(self) -> Optional[Link]:
  411. return self.base.source_link
  412. def _warn_invalid_extras(
  413. self,
  414. requested: FrozenSet[str],
  415. valid: FrozenSet[str],
  416. ) -> None:
  417. """Emit warnings for invalid extras being requested.
  418. This emits a warning for each requested extra that is not in the
  419. candidate's ``Provides-Extra`` list.
  420. """
  421. invalid_extras_to_warn = frozenset(
  422. extra
  423. for extra in requested
  424. if extra not in valid
  425. # If an extra is requested in an unnormalized form, skip warning
  426. # about the normalized form being missing.
  427. and extra in self.extras
  428. )
  429. if not invalid_extras_to_warn:
  430. return
  431. for extra in sorted(invalid_extras_to_warn):
  432. logger.warning(
  433. "%s %s does not provide the extra '%s'",
  434. self.base.name,
  435. self.version,
  436. extra,
  437. )
  438. def _calculate_valid_requested_extras(self) -> FrozenSet[str]:
  439. """Get a list of valid extras requested by this candidate.
  440. The user (or upstream dependant) may have specified extras that the
  441. candidate doesn't support. Any unsupported extras are dropped, and each
  442. cause a warning to be logged here.
  443. """
  444. requested_extras = self.extras.union(self._unnormalized_extras)
  445. valid_extras = frozenset(
  446. extra
  447. for extra in requested_extras
  448. if self.base.dist.is_extra_provided(extra)
  449. )
  450. self._warn_invalid_extras(requested_extras, valid_extras)
  451. return valid_extras
  452. def iter_dependencies(self, with_requires: bool) -> Iterable[Optional[Requirement]]:
  453. factory = self.base._factory
  454. # Add a dependency on the exact base
  455. # (See note 2b in the class docstring)
  456. yield factory.make_requirement_from_candidate(self.base)
  457. if not with_requires:
  458. return
  459. valid_extras = self._calculate_valid_requested_extras()
  460. for r in self.base.dist.iter_dependencies(valid_extras):
  461. yield from factory.make_requirements_from_spec(
  462. str(r),
  463. self._comes_from,
  464. valid_extras,
  465. )
  466. def get_install_requirement(self) -> Optional[InstallRequirement]:
  467. # We don't return anything here, because we always
  468. # depend on the base candidate, and we'll get the
  469. # install requirement from that.
  470. return None
  471. class RequiresPythonCandidate(Candidate):
  472. is_installed = False
  473. source_link = None
  474. def __init__(self, py_version_info: Optional[Tuple[int, ...]]) -> None:
  475. if py_version_info is not None:
  476. version_info = normalize_version_info(py_version_info)
  477. else:
  478. version_info = sys.version_info[:3]
  479. self._version = Version(".".join(str(c) for c in version_info))
  480. # We don't need to implement __eq__() and __ne__() since there is always
  481. # only one RequiresPythonCandidate in a resolution, i.e. the host Python.
  482. # The built-in object.__eq__() and object.__ne__() do exactly what we want.
  483. def __str__(self) -> str:
  484. return f"Python {self._version}"
  485. @property
  486. def project_name(self) -> NormalizedName:
  487. return REQUIRES_PYTHON_IDENTIFIER
  488. @property
  489. def name(self) -> str:
  490. return REQUIRES_PYTHON_IDENTIFIER
  491. @property
  492. def version(self) -> CandidateVersion:
  493. return self._version
  494. def format_for_error(self) -> str:
  495. return f"Python {self.version}"
  496. def iter_dependencies(self, with_requires: bool) -> Iterable[Optional[Requirement]]:
  497. return ()
  498. def get_install_requirement(self) -> Optional[InstallRequirement]:
  499. return None