req_install.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873
  1. # The following comment should be removed at some point in the future.
  2. # mypy: strict-optional=False
  3. import logging
  4. import os
  5. import shutil
  6. import sys
  7. import uuid
  8. import zipfile
  9. from typing import Any, Dict, Iterable, List, Optional, Sequence, Union
  10. from pip._vendor import pkg_resources, six
  11. from pip._vendor.packaging.markers import Marker
  12. from pip._vendor.packaging.requirements import Requirement
  13. from pip._vendor.packaging.specifiers import SpecifierSet
  14. from pip._vendor.packaging.utils import canonicalize_name
  15. from pip._vendor.packaging.version import Version
  16. from pip._vendor.packaging.version import parse as parse_version
  17. from pip._vendor.pep517.wrappers import Pep517HookCaller
  18. from pip._vendor.pkg_resources import Distribution
  19. from pip._internal.build_env import BuildEnvironment, NoOpBuildEnvironment
  20. from pip._internal.exceptions import InstallationError
  21. from pip._internal.locations import get_scheme
  22. from pip._internal.models.link import Link
  23. from pip._internal.operations.build.metadata import generate_metadata
  24. from pip._internal.operations.build.metadata_legacy import (
  25. generate_metadata as generate_metadata_legacy,
  26. )
  27. from pip._internal.operations.install.editable_legacy import (
  28. install_editable as install_editable_legacy,
  29. )
  30. from pip._internal.operations.install.legacy import LegacyInstallFailure
  31. from pip._internal.operations.install.legacy import install as install_legacy
  32. from pip._internal.operations.install.wheel import install_wheel
  33. from pip._internal.pyproject import load_pyproject_toml, make_pyproject_path
  34. from pip._internal.req.req_uninstall import UninstallPathSet
  35. from pip._internal.utils.deprecation import deprecated
  36. from pip._internal.utils.direct_url_helpers import direct_url_from_link
  37. from pip._internal.utils.hashes import Hashes
  38. from pip._internal.utils.logging import indent_log
  39. from pip._internal.utils.misc import (
  40. ask_path_exists,
  41. backup_dir,
  42. display_path,
  43. dist_in_site_packages,
  44. dist_in_usersite,
  45. get_distribution,
  46. hide_url,
  47. redact_auth_from_url,
  48. )
  49. from pip._internal.utils.packaging import get_metadata
  50. from pip._internal.utils.temp_dir import TempDirectory, tempdir_kinds
  51. from pip._internal.utils.virtualenv import running_under_virtualenv
  52. from pip._internal.vcs import vcs
  53. logger = logging.getLogger(__name__)
  54. def _get_dist(metadata_directory):
  55. # type: (str) -> Distribution
  56. """Return a pkg_resources.Distribution for the provided
  57. metadata directory.
  58. """
  59. dist_dir = metadata_directory.rstrip(os.sep)
  60. # Build a PathMetadata object, from path to metadata. :wink:
  61. base_dir, dist_dir_name = os.path.split(dist_dir)
  62. metadata = pkg_resources.PathMetadata(base_dir, dist_dir)
  63. # Determine the correct Distribution object type.
  64. if dist_dir.endswith(".egg-info"):
  65. dist_cls = pkg_resources.Distribution
  66. dist_name = os.path.splitext(dist_dir_name)[0]
  67. else:
  68. assert dist_dir.endswith(".dist-info")
  69. dist_cls = pkg_resources.DistInfoDistribution
  70. dist_name = os.path.splitext(dist_dir_name)[0].split("-")[0]
  71. return dist_cls(
  72. base_dir,
  73. project_name=dist_name,
  74. metadata=metadata,
  75. )
  76. class InstallRequirement:
  77. """
  78. Represents something that may be installed later on, may have information
  79. about where to fetch the relevant requirement and also contains logic for
  80. installing the said requirement.
  81. """
  82. def __init__(
  83. self,
  84. req, # type: Optional[Requirement]
  85. comes_from, # type: Optional[Union[str, InstallRequirement]]
  86. editable=False, # type: bool
  87. link=None, # type: Optional[Link]
  88. markers=None, # type: Optional[Marker]
  89. use_pep517=None, # type: Optional[bool]
  90. isolated=False, # type: bool
  91. install_options=None, # type: Optional[List[str]]
  92. global_options=None, # type: Optional[List[str]]
  93. hash_options=None, # type: Optional[Dict[str, List[str]]]
  94. constraint=False, # type: bool
  95. extras=(), # type: Iterable[str]
  96. user_supplied=False, # type: bool
  97. ):
  98. # type: (...) -> None
  99. assert req is None or isinstance(req, Requirement), req
  100. self.req = req
  101. self.comes_from = comes_from
  102. self.constraint = constraint
  103. self.editable = editable
  104. self.legacy_install_reason = None # type: Optional[int]
  105. # source_dir is the local directory where the linked requirement is
  106. # located, or unpacked. In case unpacking is needed, creating and
  107. # populating source_dir is done by the RequirementPreparer. Note this
  108. # is not necessarily the directory where pyproject.toml or setup.py is
  109. # located - that one is obtained via unpacked_source_directory.
  110. self.source_dir = None # type: Optional[str]
  111. if self.editable:
  112. assert link
  113. if link.is_file:
  114. self.source_dir = os.path.normpath(
  115. os.path.abspath(link.file_path)
  116. )
  117. if link is None and req and req.url:
  118. # PEP 508 URL requirement
  119. link = Link(req.url)
  120. self.link = self.original_link = link
  121. self.original_link_is_in_wheel_cache = False
  122. # Path to any downloaded or already-existing package.
  123. self.local_file_path = None # type: Optional[str]
  124. if self.link and self.link.is_file:
  125. self.local_file_path = self.link.file_path
  126. if extras:
  127. self.extras = extras
  128. elif req:
  129. self.extras = {
  130. pkg_resources.safe_extra(extra) for extra in req.extras
  131. }
  132. else:
  133. self.extras = set()
  134. if markers is None and req:
  135. markers = req.marker
  136. self.markers = markers
  137. # This holds the pkg_resources.Distribution object if this requirement
  138. # is already available:
  139. self.satisfied_by = None # type: Optional[Distribution]
  140. # Whether the installation process should try to uninstall an existing
  141. # distribution before installing this requirement.
  142. self.should_reinstall = False
  143. # Temporary build location
  144. self._temp_build_dir = None # type: Optional[TempDirectory]
  145. # Set to True after successful installation
  146. self.install_succeeded = None # type: Optional[bool]
  147. # Supplied options
  148. self.install_options = install_options if install_options else []
  149. self.global_options = global_options if global_options else []
  150. self.hash_options = hash_options if hash_options else {}
  151. # Set to True after successful preparation of this requirement
  152. self.prepared = False
  153. # User supplied requirement are explicitly requested for installation
  154. # by the user via CLI arguments or requirements files, as opposed to,
  155. # e.g. dependencies, extras or constraints.
  156. self.user_supplied = user_supplied
  157. self.isolated = isolated
  158. self.build_env = NoOpBuildEnvironment() # type: BuildEnvironment
  159. # For PEP 517, the directory where we request the project metadata
  160. # gets stored. We need this to pass to build_wheel, so the backend
  161. # can ensure that the wheel matches the metadata (see the PEP for
  162. # details).
  163. self.metadata_directory = None # type: Optional[str]
  164. # The static build requirements (from pyproject.toml)
  165. self.pyproject_requires = None # type: Optional[List[str]]
  166. # Build requirements that we will check are available
  167. self.requirements_to_check = [] # type: List[str]
  168. # The PEP 517 backend we should use to build the project
  169. self.pep517_backend = None # type: Optional[Pep517HookCaller]
  170. # Are we using PEP 517 for this requirement?
  171. # After pyproject.toml has been loaded, the only valid values are True
  172. # and False. Before loading, None is valid (meaning "use the default").
  173. # Setting an explicit value before loading pyproject.toml is supported,
  174. # but after loading this flag should be treated as read only.
  175. self.use_pep517 = use_pep517
  176. # This requirement needs more preparation before it can be built
  177. self.needs_more_preparation = False
  178. def __str__(self):
  179. # type: () -> str
  180. if self.req:
  181. s = str(self.req)
  182. if self.link:
  183. s += ' from {}'.format(redact_auth_from_url(self.link.url))
  184. elif self.link:
  185. s = redact_auth_from_url(self.link.url)
  186. else:
  187. s = '<InstallRequirement>'
  188. if self.satisfied_by is not None:
  189. s += ' in {}'.format(display_path(self.satisfied_by.location))
  190. if self.comes_from:
  191. if isinstance(self.comes_from, str):
  192. comes_from = self.comes_from # type: Optional[str]
  193. else:
  194. comes_from = self.comes_from.from_path()
  195. if comes_from:
  196. s += f' (from {comes_from})'
  197. return s
  198. def __repr__(self):
  199. # type: () -> str
  200. return '<{} object: {} editable={!r}>'.format(
  201. self.__class__.__name__, str(self), self.editable)
  202. def format_debug(self):
  203. # type: () -> str
  204. """An un-tested helper for getting state, for debugging.
  205. """
  206. attributes = vars(self)
  207. names = sorted(attributes)
  208. state = (
  209. "{}={!r}".format(attr, attributes[attr]) for attr in sorted(names)
  210. )
  211. return '<{name} object: {{{state}}}>'.format(
  212. name=self.__class__.__name__,
  213. state=", ".join(state),
  214. )
  215. # Things that are valid for all kinds of requirements?
  216. @property
  217. def name(self):
  218. # type: () -> Optional[str]
  219. if self.req is None:
  220. return None
  221. return pkg_resources.safe_name(self.req.name)
  222. @property
  223. def specifier(self):
  224. # type: () -> SpecifierSet
  225. return self.req.specifier
  226. @property
  227. def is_pinned(self):
  228. # type: () -> bool
  229. """Return whether I am pinned to an exact version.
  230. For example, some-package==1.2 is pinned; some-package>1.2 is not.
  231. """
  232. specifiers = self.specifier
  233. return (len(specifiers) == 1 and
  234. next(iter(specifiers)).operator in {'==', '==='})
  235. def match_markers(self, extras_requested=None):
  236. # type: (Optional[Iterable[str]]) -> bool
  237. if not extras_requested:
  238. # Provide an extra to safely evaluate the markers
  239. # without matching any extra
  240. extras_requested = ('',)
  241. if self.markers is not None:
  242. return any(
  243. self.markers.evaluate({'extra': extra})
  244. for extra in extras_requested)
  245. else:
  246. return True
  247. @property
  248. def has_hash_options(self):
  249. # type: () -> bool
  250. """Return whether any known-good hashes are specified as options.
  251. These activate --require-hashes mode; hashes specified as part of a
  252. URL do not.
  253. """
  254. return bool(self.hash_options)
  255. def hashes(self, trust_internet=True):
  256. # type: (bool) -> Hashes
  257. """Return a hash-comparer that considers my option- and URL-based
  258. hashes to be known-good.
  259. Hashes in URLs--ones embedded in the requirements file, not ones
  260. downloaded from an index server--are almost peers with ones from
  261. flags. They satisfy --require-hashes (whether it was implicitly or
  262. explicitly activated) but do not activate it. md5 and sha224 are not
  263. allowed in flags, which should nudge people toward good algos. We
  264. always OR all hashes together, even ones from URLs.
  265. :param trust_internet: Whether to trust URL-based (#md5=...) hashes
  266. downloaded from the internet, as by populate_link()
  267. """
  268. good_hashes = self.hash_options.copy()
  269. link = self.link if trust_internet else self.original_link
  270. if link and link.hash:
  271. good_hashes.setdefault(link.hash_name, []).append(link.hash)
  272. return Hashes(good_hashes)
  273. def from_path(self):
  274. # type: () -> Optional[str]
  275. """Format a nice indicator to show where this "comes from"
  276. """
  277. if self.req is None:
  278. return None
  279. s = str(self.req)
  280. if self.comes_from:
  281. if isinstance(self.comes_from, str):
  282. comes_from = self.comes_from
  283. else:
  284. comes_from = self.comes_from.from_path()
  285. if comes_from:
  286. s += '->' + comes_from
  287. return s
  288. def ensure_build_location(self, build_dir, autodelete, parallel_builds):
  289. # type: (str, bool, bool) -> str
  290. assert build_dir is not None
  291. if self._temp_build_dir is not None:
  292. assert self._temp_build_dir.path
  293. return self._temp_build_dir.path
  294. if self.req is None:
  295. # Some systems have /tmp as a symlink which confuses custom
  296. # builds (such as numpy). Thus, we ensure that the real path
  297. # is returned.
  298. self._temp_build_dir = TempDirectory(
  299. kind=tempdir_kinds.REQ_BUILD, globally_managed=True
  300. )
  301. return self._temp_build_dir.path
  302. # This is the only remaining place where we manually determine the path
  303. # for the temporary directory. It is only needed for editables where
  304. # it is the value of the --src option.
  305. # When parallel builds are enabled, add a UUID to the build directory
  306. # name so multiple builds do not interfere with each other.
  307. dir_name = canonicalize_name(self.name) # type: str
  308. if parallel_builds:
  309. dir_name = f"{dir_name}_{uuid.uuid4().hex}"
  310. # FIXME: Is there a better place to create the build_dir? (hg and bzr
  311. # need this)
  312. if not os.path.exists(build_dir):
  313. logger.debug('Creating directory %s', build_dir)
  314. os.makedirs(build_dir)
  315. actual_build_dir = os.path.join(build_dir, dir_name)
  316. # `None` indicates that we respect the globally-configured deletion
  317. # settings, which is what we actually want when auto-deleting.
  318. delete_arg = None if autodelete else False
  319. return TempDirectory(
  320. path=actual_build_dir,
  321. delete=delete_arg,
  322. kind=tempdir_kinds.REQ_BUILD,
  323. globally_managed=True,
  324. ).path
  325. def _set_requirement(self):
  326. # type: () -> None
  327. """Set requirement after generating metadata.
  328. """
  329. assert self.req is None
  330. assert self.metadata is not None
  331. assert self.source_dir is not None
  332. # Construct a Requirement object from the generated metadata
  333. if isinstance(parse_version(self.metadata["Version"]), Version):
  334. op = "=="
  335. else:
  336. op = "==="
  337. self.req = Requirement(
  338. "".join([
  339. self.metadata["Name"],
  340. op,
  341. self.metadata["Version"],
  342. ])
  343. )
  344. def warn_on_mismatching_name(self):
  345. # type: () -> None
  346. metadata_name = canonicalize_name(self.metadata["Name"])
  347. if canonicalize_name(self.req.name) == metadata_name:
  348. # Everything is fine.
  349. return
  350. # If we're here, there's a mismatch. Log a warning about it.
  351. logger.warning(
  352. 'Generating metadata for package %s '
  353. 'produced metadata for project name %s. Fix your '
  354. '#egg=%s fragments.',
  355. self.name, metadata_name, self.name
  356. )
  357. self.req = Requirement(metadata_name)
  358. def check_if_exists(self, use_user_site):
  359. # type: (bool) -> None
  360. """Find an installed distribution that satisfies or conflicts
  361. with this requirement, and set self.satisfied_by or
  362. self.should_reinstall appropriately.
  363. """
  364. if self.req is None:
  365. return
  366. existing_dist = get_distribution(self.req.name)
  367. if not existing_dist:
  368. return
  369. # pkg_resouces may contain a different copy of packaging.version from
  370. # pip in if the downstream distributor does a poor job debundling pip.
  371. # We avoid existing_dist.parsed_version and let SpecifierSet.contains
  372. # parses the version instead.
  373. existing_version = existing_dist.version
  374. version_compatible = (
  375. existing_version is not None and
  376. self.req.specifier.contains(existing_version, prereleases=True)
  377. )
  378. if not version_compatible:
  379. self.satisfied_by = None
  380. if use_user_site:
  381. if dist_in_usersite(existing_dist):
  382. self.should_reinstall = True
  383. elif (running_under_virtualenv() and
  384. dist_in_site_packages(existing_dist)):
  385. raise InstallationError(
  386. "Will not install to the user site because it will "
  387. "lack sys.path precedence to {} in {}".format(
  388. existing_dist.project_name, existing_dist.location)
  389. )
  390. else:
  391. self.should_reinstall = True
  392. else:
  393. if self.editable:
  394. self.should_reinstall = True
  395. # when installing editables, nothing pre-existing should ever
  396. # satisfy
  397. self.satisfied_by = None
  398. else:
  399. self.satisfied_by = existing_dist
  400. # Things valid for wheels
  401. @property
  402. def is_wheel(self):
  403. # type: () -> bool
  404. if not self.link:
  405. return False
  406. return self.link.is_wheel
  407. # Things valid for sdists
  408. @property
  409. def unpacked_source_directory(self):
  410. # type: () -> str
  411. return os.path.join(
  412. self.source_dir,
  413. self.link and self.link.subdirectory_fragment or '')
  414. @property
  415. def setup_py_path(self):
  416. # type: () -> str
  417. assert self.source_dir, f"No source dir for {self}"
  418. setup_py = os.path.join(self.unpacked_source_directory, 'setup.py')
  419. return setup_py
  420. @property
  421. def pyproject_toml_path(self):
  422. # type: () -> str
  423. assert self.source_dir, f"No source dir for {self}"
  424. return make_pyproject_path(self.unpacked_source_directory)
  425. def load_pyproject_toml(self):
  426. # type: () -> None
  427. """Load the pyproject.toml file.
  428. After calling this routine, all of the attributes related to PEP 517
  429. processing for this requirement have been set. In particular, the
  430. use_pep517 attribute can be used to determine whether we should
  431. follow the PEP 517 or legacy (setup.py) code path.
  432. """
  433. pyproject_toml_data = load_pyproject_toml(
  434. self.use_pep517,
  435. self.pyproject_toml_path,
  436. self.setup_py_path,
  437. str(self)
  438. )
  439. if pyproject_toml_data is None:
  440. self.use_pep517 = False
  441. return
  442. self.use_pep517 = True
  443. requires, backend, check, backend_path = pyproject_toml_data
  444. self.requirements_to_check = check
  445. self.pyproject_requires = requires
  446. self.pep517_backend = Pep517HookCaller(
  447. self.unpacked_source_directory, backend, backend_path=backend_path,
  448. )
  449. def _generate_metadata(self):
  450. # type: () -> str
  451. """Invokes metadata generator functions, with the required arguments.
  452. """
  453. if not self.use_pep517:
  454. assert self.unpacked_source_directory
  455. return generate_metadata_legacy(
  456. build_env=self.build_env,
  457. setup_py_path=self.setup_py_path,
  458. source_dir=self.unpacked_source_directory,
  459. isolated=self.isolated,
  460. details=self.name or f"from {self.link}"
  461. )
  462. assert self.pep517_backend is not None
  463. return generate_metadata(
  464. build_env=self.build_env,
  465. backend=self.pep517_backend,
  466. )
  467. def prepare_metadata(self):
  468. # type: () -> None
  469. """Ensure that project metadata is available.
  470. Under PEP 517, call the backend hook to prepare the metadata.
  471. Under legacy processing, call setup.py egg-info.
  472. """
  473. assert self.source_dir
  474. with indent_log():
  475. self.metadata_directory = self._generate_metadata()
  476. # Act on the newly generated metadata, based on the name and version.
  477. if not self.name:
  478. self._set_requirement()
  479. else:
  480. self.warn_on_mismatching_name()
  481. self.assert_source_matches_version()
  482. @property
  483. def metadata(self):
  484. # type: () -> Any
  485. if not hasattr(self, '_metadata'):
  486. self._metadata = get_metadata(self.get_dist())
  487. return self._metadata
  488. def get_dist(self):
  489. # type: () -> Distribution
  490. return _get_dist(self.metadata_directory)
  491. def assert_source_matches_version(self):
  492. # type: () -> None
  493. assert self.source_dir
  494. version = self.metadata['version']
  495. if self.req.specifier and version not in self.req.specifier:
  496. logger.warning(
  497. 'Requested %s, but installing version %s',
  498. self,
  499. version,
  500. )
  501. else:
  502. logger.debug(
  503. 'Source in %s has version %s, which satisfies requirement %s',
  504. display_path(self.source_dir),
  505. version,
  506. self,
  507. )
  508. # For both source distributions and editables
  509. def ensure_has_source_dir(
  510. self,
  511. parent_dir,
  512. autodelete=False,
  513. parallel_builds=False,
  514. ):
  515. # type: (str, bool, bool) -> None
  516. """Ensure that a source_dir is set.
  517. This will create a temporary build dir if the name of the requirement
  518. isn't known yet.
  519. :param parent_dir: The ideal pip parent_dir for the source_dir.
  520. Generally src_dir for editables and build_dir for sdists.
  521. :return: self.source_dir
  522. """
  523. if self.source_dir is None:
  524. self.source_dir = self.ensure_build_location(
  525. parent_dir,
  526. autodelete=autodelete,
  527. parallel_builds=parallel_builds,
  528. )
  529. # For editable installations
  530. def update_editable(self):
  531. # type: () -> None
  532. if not self.link:
  533. logger.debug(
  534. "Cannot update repository at %s; repository location is "
  535. "unknown",
  536. self.source_dir,
  537. )
  538. return
  539. assert self.editable
  540. assert self.source_dir
  541. if self.link.scheme == 'file':
  542. # Static paths don't get updated
  543. return
  544. vcs_backend = vcs.get_backend_for_scheme(self.link.scheme)
  545. # Editable requirements are validated in Requirement constructors.
  546. # So here, if it's neither a path nor a valid VCS URL, it's a bug.
  547. assert vcs_backend, f"Unsupported VCS URL {self.link.url}"
  548. hidden_url = hide_url(self.link.url)
  549. vcs_backend.obtain(self.source_dir, url=hidden_url)
  550. # Top-level Actions
  551. def uninstall(self, auto_confirm=False, verbose=False):
  552. # type: (bool, bool) -> Optional[UninstallPathSet]
  553. """
  554. Uninstall the distribution currently satisfying this requirement.
  555. Prompts before removing or modifying files unless
  556. ``auto_confirm`` is True.
  557. Refuses to delete or modify files outside of ``sys.prefix`` -
  558. thus uninstallation within a virtual environment can only
  559. modify that virtual environment, even if the virtualenv is
  560. linked to global site-packages.
  561. """
  562. assert self.req
  563. dist = get_distribution(self.req.name)
  564. if not dist:
  565. logger.warning("Skipping %s as it is not installed.", self.name)
  566. return None
  567. logger.info('Found existing installation: %s', dist)
  568. uninstalled_pathset = UninstallPathSet.from_dist(dist)
  569. uninstalled_pathset.remove(auto_confirm, verbose)
  570. return uninstalled_pathset
  571. def _get_archive_name(self, path, parentdir, rootdir):
  572. # type: (str, str, str) -> str
  573. def _clean_zip_name(name, prefix):
  574. # type: (str, str) -> str
  575. assert name.startswith(prefix + os.path.sep), (
  576. f"name {name!r} doesn't start with prefix {prefix!r}"
  577. )
  578. name = name[len(prefix) + 1:]
  579. name = name.replace(os.path.sep, '/')
  580. return name
  581. path = os.path.join(parentdir, path)
  582. name = _clean_zip_name(path, rootdir)
  583. return self.name + '/' + name
  584. def archive(self, build_dir):
  585. # type: (Optional[str]) -> None
  586. """Saves archive to provided build_dir.
  587. Used for saving downloaded VCS requirements as part of `pip download`.
  588. """
  589. assert self.source_dir
  590. if build_dir is None:
  591. return
  592. create_archive = True
  593. archive_name = '{}-{}.zip'.format(self.name, self.metadata["version"])
  594. archive_path = os.path.join(build_dir, archive_name)
  595. if os.path.exists(archive_path):
  596. response = ask_path_exists(
  597. 'The file {} exists. (i)gnore, (w)ipe, '
  598. '(b)ackup, (a)bort '.format(
  599. display_path(archive_path)),
  600. ('i', 'w', 'b', 'a'))
  601. if response == 'i':
  602. create_archive = False
  603. elif response == 'w':
  604. logger.warning('Deleting %s', display_path(archive_path))
  605. os.remove(archive_path)
  606. elif response == 'b':
  607. dest_file = backup_dir(archive_path)
  608. logger.warning(
  609. 'Backing up %s to %s',
  610. display_path(archive_path),
  611. display_path(dest_file),
  612. )
  613. shutil.move(archive_path, dest_file)
  614. elif response == 'a':
  615. sys.exit(-1)
  616. if not create_archive:
  617. return
  618. zip_output = zipfile.ZipFile(
  619. archive_path, 'w', zipfile.ZIP_DEFLATED, allowZip64=True,
  620. )
  621. with zip_output:
  622. dir = os.path.normcase(
  623. os.path.abspath(self.unpacked_source_directory)
  624. )
  625. for dirpath, dirnames, filenames in os.walk(dir):
  626. for dirname in dirnames:
  627. dir_arcname = self._get_archive_name(
  628. dirname, parentdir=dirpath, rootdir=dir,
  629. )
  630. zipdir = zipfile.ZipInfo(dir_arcname + '/')
  631. zipdir.external_attr = 0x1ED << 16 # 0o755
  632. zip_output.writestr(zipdir, '')
  633. for filename in filenames:
  634. file_arcname = self._get_archive_name(
  635. filename, parentdir=dirpath, rootdir=dir,
  636. )
  637. filename = os.path.join(dirpath, filename)
  638. zip_output.write(filename, file_arcname)
  639. logger.info('Saved %s', display_path(archive_path))
  640. def install(
  641. self,
  642. install_options, # type: List[str]
  643. global_options=None, # type: Optional[Sequence[str]]
  644. root=None, # type: Optional[str]
  645. home=None, # type: Optional[str]
  646. prefix=None, # type: Optional[str]
  647. warn_script_location=True, # type: bool
  648. use_user_site=False, # type: bool
  649. pycompile=True # type: bool
  650. ):
  651. # type: (...) -> None
  652. scheme = get_scheme(
  653. self.name,
  654. user=use_user_site,
  655. home=home,
  656. root=root,
  657. isolated=self.isolated,
  658. prefix=prefix,
  659. )
  660. global_options = global_options if global_options is not None else []
  661. if self.editable:
  662. install_editable_legacy(
  663. install_options,
  664. global_options,
  665. prefix=prefix,
  666. home=home,
  667. use_user_site=use_user_site,
  668. name=self.name,
  669. setup_py_path=self.setup_py_path,
  670. isolated=self.isolated,
  671. build_env=self.build_env,
  672. unpacked_source_directory=self.unpacked_source_directory,
  673. )
  674. self.install_succeeded = True
  675. return
  676. if self.is_wheel:
  677. assert self.local_file_path
  678. direct_url = None
  679. if self.original_link:
  680. direct_url = direct_url_from_link(
  681. self.original_link,
  682. self.source_dir,
  683. self.original_link_is_in_wheel_cache,
  684. )
  685. install_wheel(
  686. self.name,
  687. self.local_file_path,
  688. scheme=scheme,
  689. req_description=str(self.req),
  690. pycompile=pycompile,
  691. warn_script_location=warn_script_location,
  692. direct_url=direct_url,
  693. requested=self.user_supplied,
  694. )
  695. self.install_succeeded = True
  696. return
  697. # TODO: Why don't we do this for editable installs?
  698. # Extend the list of global and install options passed on to
  699. # the setup.py call with the ones from the requirements file.
  700. # Options specified in requirements file override those
  701. # specified on the command line, since the last option given
  702. # to setup.py is the one that is used.
  703. global_options = list(global_options) + self.global_options
  704. install_options = list(install_options) + self.install_options
  705. try:
  706. success = install_legacy(
  707. install_options=install_options,
  708. global_options=global_options,
  709. root=root,
  710. home=home,
  711. prefix=prefix,
  712. use_user_site=use_user_site,
  713. pycompile=pycompile,
  714. scheme=scheme,
  715. setup_py_path=self.setup_py_path,
  716. isolated=self.isolated,
  717. req_name=self.name,
  718. build_env=self.build_env,
  719. unpacked_source_directory=self.unpacked_source_directory,
  720. req_description=str(self.req),
  721. )
  722. except LegacyInstallFailure as exc:
  723. self.install_succeeded = False
  724. six.reraise(*exc.parent)
  725. except Exception:
  726. self.install_succeeded = True
  727. raise
  728. self.install_succeeded = success
  729. if success and self.legacy_install_reason == 8368:
  730. deprecated(
  731. reason=(
  732. "{} was installed using the legacy 'setup.py install' "
  733. "method, because a wheel could not be built for it.".
  734. format(self.name)
  735. ),
  736. replacement="to fix the wheel build issue reported above",
  737. gone_in=None,
  738. issue=8368,
  739. )
  740. def check_invalid_constraint_type(req):
  741. # type: (InstallRequirement) -> str
  742. # Check for unsupported forms
  743. problem = ""
  744. if not req.name:
  745. problem = "Unnamed requirements are not allowed as constraints"
  746. elif req.editable:
  747. problem = "Editable requirements are not allowed as constraints"
  748. elif req.extras:
  749. problem = "Constraints cannot have extras"
  750. if problem:
  751. deprecated(
  752. reason=(
  753. "Constraints are only allowed to take the form of a package "
  754. "name and a version specifier. Other forms were originally "
  755. "permitted as an accident of the implementation, but were "
  756. "undocumented. The new implementation of the resolver no "
  757. "longer supports these forms."
  758. ),
  759. replacement=(
  760. "replacing the constraint with a requirement."
  761. ),
  762. # No plan yet for when the new resolver becomes default
  763. gone_in=None,
  764. issue=8210
  765. )
  766. return problem