prepare.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  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. import logging
  6. import mimetypes
  7. import os
  8. import shutil
  9. from pip._vendor.six import PY2
  10. from pip._internal.distributions import (
  11. make_distribution_for_install_requirement,
  12. )
  13. from pip._internal.distributions.installed import InstalledDistribution
  14. from pip._internal.exceptions import (
  15. DirectoryUrlHashUnsupported,
  16. HashMismatch,
  17. HashUnpinned,
  18. InstallationError,
  19. NetworkConnectionError,
  20. PreviousBuildDirError,
  21. VcsHashUnsupported,
  22. )
  23. from pip._internal.utils.filesystem import copy2_fixed
  24. from pip._internal.utils.hashes import MissingHashes
  25. from pip._internal.utils.logging import indent_log
  26. from pip._internal.utils.misc import (
  27. display_path,
  28. hide_url,
  29. path_to_display,
  30. rmtree,
  31. )
  32. from pip._internal.utils.temp_dir import TempDirectory
  33. from pip._internal.utils.typing import MYPY_CHECK_RUNNING
  34. from pip._internal.utils.unpacking import unpack_file
  35. from pip._internal.vcs import vcs
  36. if MYPY_CHECK_RUNNING:
  37. from typing import (
  38. Callable, List, Optional, Tuple,
  39. )
  40. from mypy_extensions import TypedDict
  41. from pip._internal.distributions import AbstractDistribution
  42. from pip._internal.index.package_finder import PackageFinder
  43. from pip._internal.models.link import Link
  44. from pip._internal.network.download import Downloader
  45. from pip._internal.req.req_install import InstallRequirement
  46. from pip._internal.req.req_tracker import RequirementTracker
  47. from pip._internal.utils.hashes import Hashes
  48. if PY2:
  49. CopytreeKwargs = TypedDict(
  50. 'CopytreeKwargs',
  51. {
  52. 'ignore': Callable[[str, List[str]], List[str]],
  53. 'symlinks': bool,
  54. },
  55. total=False,
  56. )
  57. else:
  58. CopytreeKwargs = TypedDict(
  59. 'CopytreeKwargs',
  60. {
  61. 'copy_function': Callable[[str, str], None],
  62. 'ignore': Callable[[str, List[str]], List[str]],
  63. 'ignore_dangling_symlinks': bool,
  64. 'symlinks': bool,
  65. },
  66. total=False,
  67. )
  68. logger = logging.getLogger(__name__)
  69. def _get_prepared_distribution(
  70. req, # type: InstallRequirement
  71. req_tracker, # type: RequirementTracker
  72. finder, # type: PackageFinder
  73. build_isolation # type: bool
  74. ):
  75. # type: (...) -> AbstractDistribution
  76. """Prepare a distribution for installation.
  77. """
  78. abstract_dist = make_distribution_for_install_requirement(req)
  79. with req_tracker.track(req):
  80. abstract_dist.prepare_distribution_metadata(finder, build_isolation)
  81. return abstract_dist
  82. def unpack_vcs_link(link, location):
  83. # type: (Link, str) -> None
  84. vcs_backend = vcs.get_backend_for_scheme(link.scheme)
  85. assert vcs_backend is not None
  86. vcs_backend.unpack(location, url=hide_url(link.url))
  87. class File(object):
  88. def __init__(self, path, content_type):
  89. # type: (str, str) -> None
  90. self.path = path
  91. self.content_type = content_type
  92. def get_http_url(
  93. link, # type: Link
  94. downloader, # type: Downloader
  95. download_dir=None, # type: Optional[str]
  96. hashes=None, # type: Optional[Hashes]
  97. ):
  98. # type: (...) -> File
  99. temp_dir = TempDirectory(kind="unpack", globally_managed=True)
  100. # If a download dir is specified, is the file already downloaded there?
  101. already_downloaded_path = None
  102. if download_dir:
  103. already_downloaded_path = _check_download_dir(
  104. link, download_dir, hashes
  105. )
  106. if already_downloaded_path:
  107. from_path = already_downloaded_path
  108. content_type = mimetypes.guess_type(from_path)[0]
  109. else:
  110. # let's download to a tmp dir
  111. from_path, content_type = _download_http_url(
  112. link, downloader, temp_dir.path, hashes
  113. )
  114. return File(from_path, content_type)
  115. def _copy2_ignoring_special_files(src, dest):
  116. # type: (str, str) -> None
  117. """Copying special files is not supported, but as a convenience to users
  118. we skip errors copying them. This supports tools that may create e.g.
  119. socket files in the project source directory.
  120. """
  121. try:
  122. copy2_fixed(src, dest)
  123. except shutil.SpecialFileError as e:
  124. # SpecialFileError may be raised due to either the source or
  125. # destination. If the destination was the cause then we would actually
  126. # care, but since the destination directory is deleted prior to
  127. # copy we ignore all of them assuming it is caused by the source.
  128. logger.warning(
  129. "Ignoring special file error '%s' encountered copying %s to %s.",
  130. str(e),
  131. path_to_display(src),
  132. path_to_display(dest),
  133. )
  134. def _copy_source_tree(source, target):
  135. # type: (str, str) -> None
  136. target_abspath = os.path.abspath(target)
  137. target_basename = os.path.basename(target_abspath)
  138. target_dirname = os.path.dirname(target_abspath)
  139. def ignore(d, names):
  140. # type: (str, List[str]) -> List[str]
  141. skipped = [] # type: List[str]
  142. if d == source:
  143. # Pulling in those directories can potentially be very slow,
  144. # exclude the following directories if they appear in the top
  145. # level dir (and only it).
  146. # See discussion at https://github.com/pypa/pip/pull/6770
  147. skipped += ['.tox', '.nox']
  148. if os.path.abspath(d) == target_dirname:
  149. # Prevent an infinite recursion if the target is in source.
  150. # This can happen when TMPDIR is set to ${PWD}/...
  151. # and we copy PWD to TMPDIR.
  152. skipped += [target_basename]
  153. return skipped
  154. kwargs = dict(ignore=ignore, symlinks=True) # type: CopytreeKwargs
  155. if not PY2:
  156. # Python 2 does not support copy_function, so we only ignore
  157. # errors on special file copy in Python 3.
  158. kwargs['copy_function'] = _copy2_ignoring_special_files
  159. shutil.copytree(source, target, **kwargs)
  160. def get_file_url(
  161. link, # type: Link
  162. download_dir=None, # type: Optional[str]
  163. hashes=None # type: Optional[Hashes]
  164. ):
  165. # type: (...) -> File
  166. """Get file and optionally check its hash.
  167. """
  168. # If a download dir is specified, is the file already there and valid?
  169. already_downloaded_path = None
  170. if download_dir:
  171. already_downloaded_path = _check_download_dir(
  172. link, download_dir, hashes
  173. )
  174. if already_downloaded_path:
  175. from_path = already_downloaded_path
  176. else:
  177. from_path = link.file_path
  178. # If --require-hashes is off, `hashes` is either empty, the
  179. # link's embedded hash, or MissingHashes; it is required to
  180. # match. If --require-hashes is on, we are satisfied by any
  181. # hash in `hashes` matching: a URL-based or an option-based
  182. # one; no internet-sourced hash will be in `hashes`.
  183. if hashes:
  184. hashes.check_against_path(from_path)
  185. content_type = mimetypes.guess_type(from_path)[0]
  186. return File(from_path, content_type)
  187. def unpack_url(
  188. link, # type: Link
  189. location, # type: str
  190. downloader, # type: Downloader
  191. download_dir=None, # type: Optional[str]
  192. hashes=None, # type: Optional[Hashes]
  193. ):
  194. # type: (...) -> Optional[File]
  195. """Unpack link into location, downloading if required.
  196. :param hashes: A Hashes object, one of whose embedded hashes must match,
  197. or HashMismatch will be raised. If the Hashes is empty, no matches are
  198. required, and unhashable types of requirements (like VCS ones, which
  199. would ordinarily raise HashUnsupported) are allowed.
  200. """
  201. # non-editable vcs urls
  202. if link.is_vcs:
  203. unpack_vcs_link(link, location)
  204. return None
  205. # If it's a url to a local directory
  206. if link.is_existing_dir():
  207. if os.path.isdir(location):
  208. rmtree(location)
  209. _copy_source_tree(link.file_path, location)
  210. return None
  211. # file urls
  212. if link.is_file:
  213. file = get_file_url(link, download_dir, hashes=hashes)
  214. # http urls
  215. else:
  216. file = get_http_url(
  217. link,
  218. downloader,
  219. download_dir,
  220. hashes=hashes,
  221. )
  222. # unpack the archive to the build dir location. even when only downloading
  223. # archives, they have to be unpacked to parse dependencies, except wheels
  224. if not link.is_wheel:
  225. unpack_file(file.path, location, file.content_type)
  226. return file
  227. def _download_http_url(
  228. link, # type: Link
  229. downloader, # type: Downloader
  230. temp_dir, # type: str
  231. hashes, # type: Optional[Hashes]
  232. ):
  233. # type: (...) -> Tuple[str, str]
  234. """Download link url into temp_dir using provided session"""
  235. download = downloader(link)
  236. file_path = os.path.join(temp_dir, download.filename)
  237. with open(file_path, 'wb') as content_file:
  238. for chunk in download.chunks:
  239. content_file.write(chunk)
  240. if hashes:
  241. hashes.check_against_path(file_path)
  242. return file_path, download.response.headers.get('content-type', '')
  243. def _check_download_dir(link, download_dir, hashes):
  244. # type: (Link, str, Optional[Hashes]) -> Optional[str]
  245. """ Check download_dir for previously downloaded file with correct hash
  246. If a correct file is found return its path else None
  247. """
  248. download_path = os.path.join(download_dir, link.filename)
  249. if not os.path.exists(download_path):
  250. return None
  251. # If already downloaded, does its hash match?
  252. logger.info('File was already downloaded %s', download_path)
  253. if hashes:
  254. try:
  255. hashes.check_against_path(download_path)
  256. except HashMismatch:
  257. logger.warning(
  258. 'Previously-downloaded file %s has bad hash. '
  259. 'Re-downloading.',
  260. download_path
  261. )
  262. os.unlink(download_path)
  263. return None
  264. return download_path
  265. class RequirementPreparer(object):
  266. """Prepares a Requirement
  267. """
  268. def __init__(
  269. self,
  270. build_dir, # type: str
  271. download_dir, # type: Optional[str]
  272. src_dir, # type: str
  273. wheel_download_dir, # type: Optional[str]
  274. build_isolation, # type: bool
  275. req_tracker, # type: RequirementTracker
  276. downloader, # type: Downloader
  277. finder, # type: PackageFinder
  278. require_hashes, # type: bool
  279. use_user_site, # type: bool
  280. ):
  281. # type: (...) -> None
  282. super(RequirementPreparer, self).__init__()
  283. self.src_dir = src_dir
  284. self.build_dir = build_dir
  285. self.req_tracker = req_tracker
  286. self.downloader = downloader
  287. self.finder = finder
  288. # Where still-packed archives should be written to. If None, they are
  289. # not saved, and are deleted immediately after unpacking.
  290. self.download_dir = download_dir
  291. # Where still-packed .whl files should be written to. If None, they are
  292. # written to the download_dir parameter. Separate to download_dir to
  293. # permit only keeping wheel archives for pip wheel.
  294. self.wheel_download_dir = wheel_download_dir
  295. # NOTE
  296. # download_dir and wheel_download_dir overlap semantically and may
  297. # be combined if we're willing to have non-wheel archives present in
  298. # the wheelhouse output by 'pip wheel'.
  299. # Is build isolation allowed?
  300. self.build_isolation = build_isolation
  301. # Should hash-checking be required?
  302. self.require_hashes = require_hashes
  303. # Should install in user site-packages?
  304. self.use_user_site = use_user_site
  305. @property
  306. def _download_should_save(self):
  307. # type: () -> bool
  308. if not self.download_dir:
  309. return False
  310. if os.path.exists(self.download_dir):
  311. return True
  312. logger.critical('Could not find download directory')
  313. raise InstallationError(
  314. "Could not find or access download directory '{}'"
  315. .format(self.download_dir))
  316. def _log_preparing_link(self, req):
  317. # type: (InstallRequirement) -> None
  318. """Log the way the link prepared."""
  319. if req.link.is_file:
  320. path = req.link.file_path
  321. logger.info('Processing %s', display_path(path))
  322. else:
  323. logger.info('Collecting %s', req.req or req)
  324. def _ensure_link_req_src_dir(self, req, download_dir, parallel_builds):
  325. # type: (InstallRequirement, Optional[str], bool) -> None
  326. """Ensure source_dir of a linked InstallRequirement."""
  327. # Since source_dir is only set for editable requirements.
  328. if req.link.is_wheel:
  329. # We don't need to unpack wheels, so no need for a source
  330. # directory.
  331. return
  332. assert req.source_dir is None
  333. # We always delete unpacked sdists after pip runs.
  334. req.ensure_has_source_dir(
  335. self.build_dir,
  336. autodelete=True,
  337. parallel_builds=parallel_builds,
  338. )
  339. # If a checkout exists, it's unwise to keep going. version
  340. # inconsistencies are logged later, but do not fail the
  341. # installation.
  342. # FIXME: this won't upgrade when there's an existing
  343. # package unpacked in `req.source_dir`
  344. if os.path.exists(os.path.join(req.source_dir, 'setup.py')):
  345. raise PreviousBuildDirError(
  346. "pip can't proceed with requirements '{}' due to a"
  347. "pre-existing build directory ({}). This is likely "
  348. "due to a previous installation that failed . pip is "
  349. "being responsible and not assuming it can delete this. "
  350. "Please delete it and try again.".format(req, req.source_dir)
  351. )
  352. def _get_linked_req_hashes(self, req):
  353. # type: (InstallRequirement) -> Hashes
  354. # By the time this is called, the requirement's link should have
  355. # been checked so we can tell what kind of requirements req is
  356. # and raise some more informative errors than otherwise.
  357. # (For example, we can raise VcsHashUnsupported for a VCS URL
  358. # rather than HashMissing.)
  359. if not self.require_hashes:
  360. return req.hashes(trust_internet=True)
  361. # We could check these first 2 conditions inside unpack_url
  362. # and save repetition of conditions, but then we would
  363. # report less-useful error messages for unhashable
  364. # requirements, complaining that there's no hash provided.
  365. if req.link.is_vcs:
  366. raise VcsHashUnsupported()
  367. if req.link.is_existing_dir():
  368. raise DirectoryUrlHashUnsupported()
  369. # Unpinned packages are asking for trouble when a new version
  370. # is uploaded. This isn't a security check, but it saves users
  371. # a surprising hash mismatch in the future.
  372. # file:/// URLs aren't pinnable, so don't complain about them
  373. # not being pinned.
  374. if req.original_link is None and not req.is_pinned:
  375. raise HashUnpinned()
  376. # If known-good hashes are missing for this requirement,
  377. # shim it with a facade object that will provoke hash
  378. # computation and then raise a HashMissing exception
  379. # showing the user what the hash should be.
  380. return req.hashes(trust_internet=False) or MissingHashes()
  381. def prepare_linked_requirement(self, req, parallel_builds=False):
  382. # type: (InstallRequirement, bool) -> AbstractDistribution
  383. """Prepare a requirement to be obtained from req.link."""
  384. assert req.link
  385. link = req.link
  386. self._log_preparing_link(req)
  387. if link.is_wheel and self.wheel_download_dir:
  388. # Download wheels to a dedicated dir when doing `pip wheel`.
  389. download_dir = self.wheel_download_dir
  390. else:
  391. download_dir = self.download_dir
  392. with indent_log():
  393. self._ensure_link_req_src_dir(req, download_dir, parallel_builds)
  394. try:
  395. local_file = unpack_url(
  396. link, req.source_dir, self.downloader, download_dir,
  397. hashes=self._get_linked_req_hashes(req)
  398. )
  399. except NetworkConnectionError as exc:
  400. raise InstallationError(
  401. 'Could not install requirement {} because of HTTP '
  402. 'error {} for URL {}'.format(req, exc, link)
  403. )
  404. # For use in later processing, preserve the file path on the
  405. # requirement.
  406. if local_file:
  407. req.local_file_path = local_file.path
  408. abstract_dist = _get_prepared_distribution(
  409. req, self.req_tracker, self.finder, self.build_isolation,
  410. )
  411. if download_dir:
  412. if link.is_existing_dir():
  413. logger.info('Link is a directory, ignoring download_dir')
  414. elif local_file:
  415. download_location = os.path.join(
  416. download_dir, link.filename
  417. )
  418. if not os.path.exists(download_location):
  419. shutil.copy(local_file.path, download_location)
  420. download_path = display_path(download_location)
  421. logger.info('Saved %s', download_path)
  422. if self._download_should_save:
  423. # Make a .zip of the source_dir we already created.
  424. if link.is_vcs:
  425. req.archive(self.download_dir)
  426. return abstract_dist
  427. def prepare_editable_requirement(
  428. self,
  429. req, # type: InstallRequirement
  430. ):
  431. # type: (...) -> AbstractDistribution
  432. """Prepare an editable requirement
  433. """
  434. assert req.editable, "cannot prepare a non-editable req as editable"
  435. logger.info('Obtaining %s', req)
  436. with indent_log():
  437. if self.require_hashes:
  438. raise InstallationError(
  439. 'The editable requirement {} cannot be installed when '
  440. 'requiring hashes, because there is no single file to '
  441. 'hash.'.format(req)
  442. )
  443. req.ensure_has_source_dir(self.src_dir)
  444. req.update_editable(not self._download_should_save)
  445. abstract_dist = _get_prepared_distribution(
  446. req, self.req_tracker, self.finder, self.build_isolation,
  447. )
  448. if self._download_should_save:
  449. req.archive(self.download_dir)
  450. req.check_if_exists(self.use_user_site)
  451. return abstract_dist
  452. def prepare_installed_requirement(
  453. self,
  454. req, # type: InstallRequirement
  455. skip_reason # type: str
  456. ):
  457. # type: (...) -> AbstractDistribution
  458. """Prepare an already-installed requirement
  459. """
  460. assert req.satisfied_by, "req should have been satisfied but isn't"
  461. assert skip_reason is not None, (
  462. "did not get skip reason skipped but req.satisfied_by "
  463. "is set to {}".format(req.satisfied_by)
  464. )
  465. logger.info(
  466. 'Requirement %s: %s (%s)',
  467. skip_reason, req, req.satisfied_by.version
  468. )
  469. with indent_log():
  470. if self.require_hashes:
  471. logger.debug(
  472. 'Since it is already installed, we are trusting this '
  473. 'package without checking its hash. To ensure a '
  474. 'completely repeatable environment, install into an '
  475. 'empty virtualenv.'
  476. )
  477. abstract_dist = InstalledDistribution(req)
  478. return abstract_dist