prepare.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  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 import requests
  10. from pip._vendor.six import PY2
  11. from pip._internal.distributions import (
  12. make_distribution_for_install_requirement,
  13. )
  14. from pip._internal.distributions.installed import InstalledDistribution
  15. from pip._internal.exceptions import (
  16. DirectoryUrlHashUnsupported,
  17. HashMismatch,
  18. HashUnpinned,
  19. InstallationError,
  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
  224. unpack_file(file.path, location, file.content_type)
  225. return file
  226. def _download_http_url(
  227. link, # type: Link
  228. downloader, # type: Downloader
  229. temp_dir, # type: str
  230. hashes, # type: Optional[Hashes]
  231. ):
  232. # type: (...) -> Tuple[str, str]
  233. """Download link url into temp_dir using provided session"""
  234. download = downloader(link)
  235. file_path = os.path.join(temp_dir, download.filename)
  236. with open(file_path, 'wb') as content_file:
  237. for chunk in download.chunks:
  238. content_file.write(chunk)
  239. if hashes:
  240. hashes.check_against_path(file_path)
  241. return file_path, download.response.headers.get('content-type', '')
  242. def _check_download_dir(link, download_dir, hashes):
  243. # type: (Link, str, Optional[Hashes]) -> Optional[str]
  244. """ Check download_dir for previously downloaded file with correct hash
  245. If a correct file is found return its path else None
  246. """
  247. download_path = os.path.join(download_dir, link.filename)
  248. if not os.path.exists(download_path):
  249. return None
  250. # If already downloaded, does its hash match?
  251. logger.info('File was already downloaded %s', download_path)
  252. if hashes:
  253. try:
  254. hashes.check_against_path(download_path)
  255. except HashMismatch:
  256. logger.warning(
  257. 'Previously-downloaded file %s has bad hash. '
  258. 'Re-downloading.',
  259. download_path
  260. )
  261. os.unlink(download_path)
  262. return None
  263. return download_path
  264. class RequirementPreparer(object):
  265. """Prepares a Requirement
  266. """
  267. def __init__(
  268. self,
  269. build_dir, # type: str
  270. download_dir, # type: Optional[str]
  271. src_dir, # type: str
  272. wheel_download_dir, # type: Optional[str]
  273. build_isolation, # type: bool
  274. req_tracker, # type: RequirementTracker
  275. downloader, # type: Downloader
  276. finder, # type: PackageFinder
  277. require_hashes, # type: bool
  278. use_user_site, # type: bool
  279. ):
  280. # type: (...) -> None
  281. super(RequirementPreparer, self).__init__()
  282. self.src_dir = src_dir
  283. self.build_dir = build_dir
  284. self.req_tracker = req_tracker
  285. self.downloader = downloader
  286. self.finder = finder
  287. # Where still-packed archives should be written to. If None, they are
  288. # not saved, and are deleted immediately after unpacking.
  289. self.download_dir = download_dir
  290. # Where still-packed .whl files should be written to. If None, they are
  291. # written to the download_dir parameter. Separate to download_dir to
  292. # permit only keeping wheel archives for pip wheel.
  293. self.wheel_download_dir = wheel_download_dir
  294. # NOTE
  295. # download_dir and wheel_download_dir overlap semantically and may
  296. # be combined if we're willing to have non-wheel archives present in
  297. # the wheelhouse output by 'pip wheel'.
  298. # Is build isolation allowed?
  299. self.build_isolation = build_isolation
  300. # Should hash-checking be required?
  301. self.require_hashes = require_hashes
  302. # Should install in user site-packages?
  303. self.use_user_site = use_user_site
  304. @property
  305. def _download_should_save(self):
  306. # type: () -> bool
  307. if not self.download_dir:
  308. return False
  309. if os.path.exists(self.download_dir):
  310. return True
  311. logger.critical('Could not find download directory')
  312. raise InstallationError(
  313. "Could not find or access download directory '{}'"
  314. .format(self.download_dir))
  315. def prepare_linked_requirement(
  316. self,
  317. req, # type: InstallRequirement
  318. ):
  319. # type: (...) -> AbstractDistribution
  320. """Prepare a requirement that would be obtained from req.link
  321. """
  322. assert req.link
  323. link = req.link
  324. # TODO: Breakup into smaller functions
  325. if link.scheme == 'file':
  326. path = link.file_path
  327. logger.info('Processing %s', display_path(path))
  328. else:
  329. logger.info('Collecting %s', req.req or req)
  330. download_dir = self.download_dir
  331. if link.is_wheel and self.wheel_download_dir:
  332. # when doing 'pip wheel` we download wheels to a
  333. # dedicated dir.
  334. download_dir = self.wheel_download_dir
  335. if link.is_wheel:
  336. if download_dir:
  337. # When downloading, we only unpack wheels to get
  338. # metadata.
  339. autodelete_unpacked = True
  340. else:
  341. # When installing a wheel, we use the unpacked
  342. # wheel.
  343. autodelete_unpacked = False
  344. else:
  345. # We always delete unpacked sdists after pip runs.
  346. autodelete_unpacked = True
  347. with indent_log():
  348. # Since source_dir is only set for editable requirements.
  349. assert req.source_dir is None
  350. req.ensure_has_source_dir(self.build_dir, autodelete_unpacked)
  351. # If a checkout exists, it's unwise to keep going. version
  352. # inconsistencies are logged later, but do not fail the
  353. # installation.
  354. # FIXME: this won't upgrade when there's an existing
  355. # package unpacked in `req.source_dir`
  356. if os.path.exists(os.path.join(req.source_dir, 'setup.py')):
  357. raise PreviousBuildDirError(
  358. "pip can't proceed with requirements '{}' due to a"
  359. " pre-existing build directory ({}). This is "
  360. "likely due to a previous installation that failed"
  361. ". pip is being responsible and not assuming it "
  362. "can delete this. Please delete it and try again."
  363. .format(req, req.source_dir)
  364. )
  365. # Now that we have the real link, we can tell what kind of
  366. # requirements we have and raise some more informative errors
  367. # than otherwise. (For example, we can raise VcsHashUnsupported
  368. # for a VCS URL rather than HashMissing.)
  369. if self.require_hashes:
  370. # We could check these first 2 conditions inside
  371. # unpack_url and save repetition of conditions, but then
  372. # we would report less-useful error messages for
  373. # unhashable requirements, complaining that there's no
  374. # hash provided.
  375. if link.is_vcs:
  376. raise VcsHashUnsupported()
  377. elif link.is_existing_dir():
  378. raise DirectoryUrlHashUnsupported()
  379. if not req.original_link and not req.is_pinned:
  380. # Unpinned packages are asking for trouble when a new
  381. # version is uploaded. This isn't a security check, but
  382. # it saves users a surprising hash mismatch in the
  383. # future.
  384. #
  385. # file:/// URLs aren't pinnable, so don't complain
  386. # about them not being pinned.
  387. raise HashUnpinned()
  388. hashes = req.hashes(trust_internet=not self.require_hashes)
  389. if self.require_hashes and not hashes:
  390. # Known-good hashes are missing for this requirement, so
  391. # shim it with a facade object that will provoke hash
  392. # computation and then raise a HashMissing exception
  393. # showing the user what the hash should be.
  394. hashes = MissingHashes()
  395. try:
  396. local_file = unpack_url(
  397. link, req.source_dir, self.downloader, download_dir,
  398. hashes=hashes,
  399. )
  400. except requests.HTTPError as exc:
  401. logger.critical(
  402. 'Could not install requirement %s because of error %s',
  403. req,
  404. exc,
  405. )
  406. raise InstallationError(
  407. 'Could not install requirement {} because of HTTP '
  408. 'error {} for URL {}'.format(req, exc, link)
  409. )
  410. # For use in later processing, preserve the file path on the
  411. # requirement.
  412. if local_file:
  413. req.local_file_path = local_file.path
  414. abstract_dist = _get_prepared_distribution(
  415. req, self.req_tracker, self.finder, self.build_isolation,
  416. )
  417. if download_dir:
  418. if link.is_existing_dir():
  419. logger.info('Link is a directory, ignoring download_dir')
  420. elif local_file:
  421. download_location = os.path.join(
  422. download_dir, link.filename
  423. )
  424. if not os.path.exists(download_location):
  425. shutil.copy(local_file.path, download_location)
  426. logger.info(
  427. 'Saved %s', display_path(download_location)
  428. )
  429. if self._download_should_save:
  430. # Make a .zip of the source_dir we already created.
  431. if link.is_vcs:
  432. req.archive(self.download_dir)
  433. return abstract_dist
  434. def prepare_editable_requirement(
  435. self,
  436. req, # type: InstallRequirement
  437. ):
  438. # type: (...) -> AbstractDistribution
  439. """Prepare an editable requirement
  440. """
  441. assert req.editable, "cannot prepare a non-editable req as editable"
  442. logger.info('Obtaining %s', req)
  443. with indent_log():
  444. if self.require_hashes:
  445. raise InstallationError(
  446. 'The editable requirement {} cannot be installed when '
  447. 'requiring hashes, because there is no single file to '
  448. 'hash.'.format(req)
  449. )
  450. req.ensure_has_source_dir(self.src_dir)
  451. req.update_editable(not self._download_should_save)
  452. abstract_dist = _get_prepared_distribution(
  453. req, self.req_tracker, self.finder, self.build_isolation,
  454. )
  455. if self._download_should_save:
  456. req.archive(self.download_dir)
  457. req.check_if_exists(self.use_user_site)
  458. return abstract_dist
  459. def prepare_installed_requirement(
  460. self,
  461. req, # type: InstallRequirement
  462. skip_reason # type: str
  463. ):
  464. # type: (...) -> AbstractDistribution
  465. """Prepare an already-installed requirement
  466. """
  467. assert req.satisfied_by, "req should have been satisfied but isn't"
  468. assert skip_reason is not None, (
  469. "did not get skip reason skipped but req.satisfied_by "
  470. "is set to {}".format(req.satisfied_by)
  471. )
  472. logger.info(
  473. 'Requirement %s: %s (%s)',
  474. skip_reason, req, req.satisfied_by.version
  475. )
  476. with indent_log():
  477. if self.require_hashes:
  478. logger.debug(
  479. 'Since it is already installed, we are trusting this '
  480. 'package without checking its hash. To ensure a '
  481. 'completely repeatable environment, install into an '
  482. 'empty virtualenv.'
  483. )
  484. abstract_dist = InstalledDistribution(req)
  485. return abstract_dist