candidates.py 20 KB

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