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.

prepare.py 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. """Prepares a distribution for installation
  2. """
  3. # The following comment should be removed at some point in the future.
  4. # mypy: strict-optional=False
  5. # mypy: disallow-untyped-defs=False
  6. import logging
  7. import os
  8. from pip._vendor import requests
  9. from pip._internal.distributions import (
  10. make_distribution_for_install_requirement,
  11. )
  12. from pip._internal.distributions.installed import InstalledDistribution
  13. from pip._internal.download import unpack_url
  14. from pip._internal.exceptions import (
  15. DirectoryUrlHashUnsupported,
  16. HashUnpinned,
  17. InstallationError,
  18. PreviousBuildDirError,
  19. VcsHashUnsupported,
  20. )
  21. from pip._internal.utils.compat import expanduser
  22. from pip._internal.utils.hashes import MissingHashes
  23. from pip._internal.utils.logging import indent_log
  24. from pip._internal.utils.marker_files import write_delete_marker_file
  25. from pip._internal.utils.misc import display_path, normalize_path
  26. from pip._internal.utils.typing import MYPY_CHECK_RUNNING
  27. if MYPY_CHECK_RUNNING:
  28. from typing import Optional
  29. from pip._internal.distributions import AbstractDistribution
  30. from pip._internal.index import PackageFinder
  31. from pip._internal.network.session import PipSession
  32. from pip._internal.req.req_install import InstallRequirement
  33. from pip._internal.req.req_tracker import RequirementTracker
  34. logger = logging.getLogger(__name__)
  35. def _get_prepared_distribution(req, req_tracker, finder, build_isolation):
  36. """Prepare a distribution for installation.
  37. """
  38. abstract_dist = make_distribution_for_install_requirement(req)
  39. with req_tracker.track(req):
  40. abstract_dist.prepare_distribution_metadata(finder, build_isolation)
  41. return abstract_dist
  42. class RequirementPreparer(object):
  43. """Prepares a Requirement
  44. """
  45. def __init__(
  46. self,
  47. build_dir, # type: str
  48. download_dir, # type: Optional[str]
  49. src_dir, # type: str
  50. wheel_download_dir, # type: Optional[str]
  51. progress_bar, # type: str
  52. build_isolation, # type: bool
  53. req_tracker # type: RequirementTracker
  54. ):
  55. # type: (...) -> None
  56. super(RequirementPreparer, self).__init__()
  57. self.src_dir = src_dir
  58. self.build_dir = build_dir
  59. self.req_tracker = req_tracker
  60. # Where still-packed archives should be written to. If None, they are
  61. # not saved, and are deleted immediately after unpacking.
  62. if download_dir:
  63. download_dir = expanduser(download_dir)
  64. self.download_dir = download_dir
  65. # Where still-packed .whl files should be written to. If None, they are
  66. # written to the download_dir parameter. Separate to download_dir to
  67. # permit only keeping wheel archives for pip wheel.
  68. if wheel_download_dir:
  69. wheel_download_dir = normalize_path(wheel_download_dir)
  70. self.wheel_download_dir = wheel_download_dir
  71. # NOTE
  72. # download_dir and wheel_download_dir overlap semantically and may
  73. # be combined if we're willing to have non-wheel archives present in
  74. # the wheelhouse output by 'pip wheel'.
  75. self.progress_bar = progress_bar
  76. # Is build isolation allowed?
  77. self.build_isolation = build_isolation
  78. @property
  79. def _download_should_save(self):
  80. # type: () -> bool
  81. if not self.download_dir:
  82. return False
  83. if os.path.exists(self.download_dir):
  84. return True
  85. logger.critical('Could not find download directory')
  86. raise InstallationError(
  87. "Could not find or access download directory '%s'"
  88. % display_path(self.download_dir))
  89. def prepare_linked_requirement(
  90. self,
  91. req, # type: InstallRequirement
  92. session, # type: PipSession
  93. finder, # type: PackageFinder
  94. require_hashes, # type: bool
  95. ):
  96. # type: (...) -> AbstractDistribution
  97. """Prepare a requirement that would be obtained from req.link
  98. """
  99. assert req.link
  100. link = req.link
  101. # TODO: Breakup into smaller functions
  102. if link.scheme == 'file':
  103. path = link.file_path
  104. logger.info('Processing %s', display_path(path))
  105. else:
  106. logger.info('Collecting %s', req.req or req)
  107. with indent_log():
  108. # @@ if filesystem packages are not marked
  109. # editable in a req, a non deterministic error
  110. # occurs when the script attempts to unpack the
  111. # build directory
  112. req.ensure_has_source_dir(self.build_dir)
  113. # If a checkout exists, it's unwise to keep going. version
  114. # inconsistencies are logged later, but do not fail the
  115. # installation.
  116. # FIXME: this won't upgrade when there's an existing
  117. # package unpacked in `req.source_dir`
  118. if os.path.exists(os.path.join(req.source_dir, 'setup.py')):
  119. raise PreviousBuildDirError(
  120. "pip can't proceed with requirements '%s' due to a"
  121. " pre-existing build directory (%s). This is "
  122. "likely due to a previous installation that failed"
  123. ". pip is being responsible and not assuming it "
  124. "can delete this. Please delete it and try again."
  125. % (req, req.source_dir)
  126. )
  127. # Now that we have the real link, we can tell what kind of
  128. # requirements we have and raise some more informative errors
  129. # than otherwise. (For example, we can raise VcsHashUnsupported
  130. # for a VCS URL rather than HashMissing.)
  131. if require_hashes:
  132. # We could check these first 2 conditions inside
  133. # unpack_url and save repetition of conditions, but then
  134. # we would report less-useful error messages for
  135. # unhashable requirements, complaining that there's no
  136. # hash provided.
  137. if link.is_vcs:
  138. raise VcsHashUnsupported()
  139. elif link.is_existing_dir():
  140. raise DirectoryUrlHashUnsupported()
  141. if not req.original_link and not req.is_pinned:
  142. # Unpinned packages are asking for trouble when a new
  143. # version is uploaded. This isn't a security check, but
  144. # it saves users a surprising hash mismatch in the
  145. # future.
  146. #
  147. # file:/// URLs aren't pinnable, so don't complain
  148. # about them not being pinned.
  149. raise HashUnpinned()
  150. hashes = req.hashes(trust_internet=not require_hashes)
  151. if require_hashes and not hashes:
  152. # Known-good hashes are missing for this requirement, so
  153. # shim it with a facade object that will provoke hash
  154. # computation and then raise a HashMissing exception
  155. # showing the user what the hash should be.
  156. hashes = MissingHashes()
  157. download_dir = self.download_dir
  158. if link.is_wheel and self.wheel_download_dir:
  159. # when doing 'pip wheel` we download wheels to a
  160. # dedicated dir.
  161. download_dir = self.wheel_download_dir
  162. try:
  163. unpack_url(
  164. link, req.source_dir, download_dir,
  165. session=session, hashes=hashes,
  166. progress_bar=self.progress_bar
  167. )
  168. except requests.HTTPError as exc:
  169. logger.critical(
  170. 'Could not install requirement %s because of error %s',
  171. req,
  172. exc,
  173. )
  174. raise InstallationError(
  175. 'Could not install requirement %s because of HTTP '
  176. 'error %s for URL %s' %
  177. (req, exc, link)
  178. )
  179. if link.is_wheel:
  180. if download_dir:
  181. # When downloading, we only unpack wheels to get
  182. # metadata.
  183. autodelete_unpacked = True
  184. else:
  185. # When installing a wheel, we use the unpacked
  186. # wheel.
  187. autodelete_unpacked = False
  188. else:
  189. # We always delete unpacked sdists after pip runs.
  190. autodelete_unpacked = True
  191. if autodelete_unpacked:
  192. write_delete_marker_file(req.source_dir)
  193. abstract_dist = _get_prepared_distribution(
  194. req, self.req_tracker, finder, self.build_isolation,
  195. )
  196. if self._download_should_save:
  197. # Make a .zip of the source_dir we already created.
  198. if link.is_vcs:
  199. req.archive(self.download_dir)
  200. return abstract_dist
  201. def prepare_editable_requirement(
  202. self,
  203. req, # type: InstallRequirement
  204. require_hashes, # type: bool
  205. use_user_site, # type: bool
  206. finder # type: PackageFinder
  207. ):
  208. # type: (...) -> AbstractDistribution
  209. """Prepare an editable requirement
  210. """
  211. assert req.editable, "cannot prepare a non-editable req as editable"
  212. logger.info('Obtaining %s', req)
  213. with indent_log():
  214. if require_hashes:
  215. raise InstallationError(
  216. 'The editable requirement %s cannot be installed when '
  217. 'requiring hashes, because there is no single file to '
  218. 'hash.' % req
  219. )
  220. req.ensure_has_source_dir(self.src_dir)
  221. req.update_editable(not self._download_should_save)
  222. abstract_dist = _get_prepared_distribution(
  223. req, self.req_tracker, finder, self.build_isolation,
  224. )
  225. if self._download_should_save:
  226. req.archive(self.download_dir)
  227. req.check_if_exists(use_user_site)
  228. return abstract_dist
  229. def prepare_installed_requirement(
  230. self,
  231. req, # type: InstallRequirement
  232. require_hashes, # type: bool
  233. skip_reason # type: str
  234. ):
  235. # type: (...) -> AbstractDistribution
  236. """Prepare an already-installed requirement
  237. """
  238. assert req.satisfied_by, "req should have been satisfied but isn't"
  239. assert skip_reason is not None, (
  240. "did not get skip reason skipped but req.satisfied_by "
  241. "is set to %r" % (req.satisfied_by,)
  242. )
  243. logger.info(
  244. 'Requirement %s: %s (%s)',
  245. skip_reason, req, req.satisfied_by.version
  246. )
  247. with indent_log():
  248. if require_hashes:
  249. logger.debug(
  250. 'Since it is already installed, we are trusting this '
  251. 'package without checking its hash. To ensure a '
  252. 'completely repeatable environment, install into an '
  253. 'empty virtualenv.'
  254. )
  255. abstract_dist = InstalledDistribution(req)
  256. return abstract_dist