wheel.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846
  1. """Support for installing and building the "wheel" binary package format.
  2. """
  3. from __future__ import absolute_import
  4. import collections
  5. import compileall
  6. import contextlib
  7. import csv
  8. import importlib
  9. import logging
  10. import os.path
  11. import re
  12. import shutil
  13. import sys
  14. import warnings
  15. from base64 import urlsafe_b64encode
  16. from itertools import chain, starmap
  17. from zipfile import ZipFile
  18. from pip._vendor import pkg_resources
  19. from pip._vendor.distlib.scripts import ScriptMaker
  20. from pip._vendor.distlib.util import get_export_entry
  21. from pip._vendor.six import PY2, ensure_str, ensure_text, itervalues, reraise, text_type
  22. from pip._vendor.six.moves import filterfalse, map
  23. from pip._internal.exceptions import InstallationError
  24. from pip._internal.locations import get_major_minor_version
  25. from pip._internal.models.direct_url import DIRECT_URL_METADATA_NAME, DirectUrl
  26. from pip._internal.models.scheme import SCHEME_KEYS
  27. from pip._internal.utils.filesystem import adjacent_tmp_file, replace
  28. from pip._internal.utils.misc import captured_stdout, ensure_dir, hash_file, partition
  29. from pip._internal.utils.typing import MYPY_CHECK_RUNNING
  30. from pip._internal.utils.unpacking import (
  31. current_umask,
  32. is_within_directory,
  33. set_extracted_file_to_default_mode_plus_executable,
  34. zip_item_is_executable,
  35. )
  36. from pip._internal.utils.wheel import parse_wheel, pkg_resources_distribution_for_wheel
  37. # Use the custom cast function at runtime to make cast work,
  38. # and import typing.cast when performing pre-commit and type
  39. # checks
  40. if not MYPY_CHECK_RUNNING:
  41. from pip._internal.utils.typing import cast
  42. else:
  43. from email.message import Message
  44. from typing import (
  45. IO,
  46. Any,
  47. Callable,
  48. Dict,
  49. Iterable,
  50. Iterator,
  51. List,
  52. NewType,
  53. Optional,
  54. Protocol,
  55. Sequence,
  56. Set,
  57. Tuple,
  58. Union,
  59. cast,
  60. )
  61. from zipfile import ZipInfo
  62. from pip._vendor.pkg_resources import Distribution
  63. from pip._internal.models.scheme import Scheme
  64. from pip._internal.utils.filesystem import NamedTemporaryFileResult
  65. RecordPath = NewType('RecordPath', text_type)
  66. InstalledCSVRow = Tuple[RecordPath, str, Union[int, str]]
  67. class File(Protocol):
  68. src_record_path = None # type: RecordPath
  69. dest_path = None # type: text_type
  70. changed = None # type: bool
  71. def save(self):
  72. # type: () -> None
  73. pass
  74. logger = logging.getLogger(__name__)
  75. def rehash(path, blocksize=1 << 20):
  76. # type: (text_type, int) -> Tuple[str, str]
  77. """Return (encoded_digest, length) for path using hashlib.sha256()"""
  78. h, length = hash_file(path, blocksize)
  79. digest = 'sha256=' + urlsafe_b64encode(
  80. h.digest()
  81. ).decode('latin1').rstrip('=')
  82. # unicode/str python2 issues
  83. return (digest, str(length)) # type: ignore
  84. def csv_io_kwargs(mode):
  85. # type: (str) -> Dict[str, Any]
  86. """Return keyword arguments to properly open a CSV file
  87. in the given mode.
  88. """
  89. if PY2:
  90. return {'mode': '{}b'.format(mode)}
  91. else:
  92. return {'mode': mode, 'newline': '', 'encoding': 'utf-8'}
  93. def fix_script(path):
  94. # type: (text_type) -> bool
  95. """Replace #!python with #!/path/to/python
  96. Return True if file was changed.
  97. """
  98. # XXX RECORD hashes will need to be updated
  99. assert os.path.isfile(path)
  100. with open(path, 'rb') as script:
  101. firstline = script.readline()
  102. if not firstline.startswith(b'#!python'):
  103. return False
  104. exename = sys.executable.encode(sys.getfilesystemencoding())
  105. firstline = b'#!' + exename + os.linesep.encode("ascii")
  106. rest = script.read()
  107. with open(path, 'wb') as script:
  108. script.write(firstline)
  109. script.write(rest)
  110. return True
  111. def wheel_root_is_purelib(metadata):
  112. # type: (Message) -> bool
  113. return metadata.get("Root-Is-Purelib", "").lower() == "true"
  114. def get_entrypoints(distribution):
  115. # type: (Distribution) -> Tuple[Dict[str, str], Dict[str, str]]
  116. # get the entry points and then the script names
  117. try:
  118. console = distribution.get_entry_map('console_scripts')
  119. gui = distribution.get_entry_map('gui_scripts')
  120. except KeyError:
  121. # Our dict-based Distribution raises KeyError if entry_points.txt
  122. # doesn't exist.
  123. return {}, {}
  124. def _split_ep(s):
  125. # type: (pkg_resources.EntryPoint) -> Tuple[str, str]
  126. """get the string representation of EntryPoint,
  127. remove space and split on '='
  128. """
  129. split_parts = str(s).replace(" ", "").split("=")
  130. return split_parts[0], split_parts[1]
  131. # convert the EntryPoint objects into strings with module:function
  132. console = dict(_split_ep(v) for v in console.values())
  133. gui = dict(_split_ep(v) for v in gui.values())
  134. return console, gui
  135. def message_about_scripts_not_on_PATH(scripts):
  136. # type: (Sequence[str]) -> Optional[str]
  137. """Determine if any scripts are not on PATH and format a warning.
  138. Returns a warning message if one or more scripts are not on PATH,
  139. otherwise None.
  140. """
  141. if not scripts:
  142. return None
  143. # Group scripts by the path they were installed in
  144. grouped_by_dir = collections.defaultdict(set) # type: Dict[str, Set[str]]
  145. for destfile in scripts:
  146. parent_dir = os.path.dirname(destfile)
  147. script_name = os.path.basename(destfile)
  148. grouped_by_dir[parent_dir].add(script_name)
  149. # We don't want to warn for directories that are on PATH.
  150. not_warn_dirs = [
  151. os.path.normcase(i).rstrip(os.sep) for i in
  152. os.environ.get("PATH", "").split(os.pathsep)
  153. ]
  154. # If an executable sits with sys.executable, we don't warn for it.
  155. # This covers the case of venv invocations without activating the venv.
  156. not_warn_dirs.append(os.path.normcase(os.path.dirname(sys.executable)))
  157. warn_for = {
  158. parent_dir: scripts for parent_dir, scripts in grouped_by_dir.items()
  159. if os.path.normcase(parent_dir) not in not_warn_dirs
  160. } # type: Dict[str, Set[str]]
  161. if not warn_for:
  162. return None
  163. # Format a message
  164. msg_lines = []
  165. for parent_dir, dir_scripts in warn_for.items():
  166. sorted_scripts = sorted(dir_scripts) # type: List[str]
  167. if len(sorted_scripts) == 1:
  168. start_text = "script {} is".format(sorted_scripts[0])
  169. else:
  170. start_text = "scripts {} are".format(
  171. ", ".join(sorted_scripts[:-1]) + " and " + sorted_scripts[-1]
  172. )
  173. msg_lines.append(
  174. "The {} installed in '{}' which is not on PATH."
  175. .format(start_text, parent_dir)
  176. )
  177. last_line_fmt = (
  178. "Consider adding {} to PATH or, if you prefer "
  179. "to suppress this warning, use --no-warn-script-location."
  180. )
  181. if len(msg_lines) == 1:
  182. msg_lines.append(last_line_fmt.format("this directory"))
  183. else:
  184. msg_lines.append(last_line_fmt.format("these directories"))
  185. # Add a note if any directory starts with ~
  186. warn_for_tilde = any(
  187. i[0] == "~" for i in os.environ.get("PATH", "").split(os.pathsep) if i
  188. )
  189. if warn_for_tilde:
  190. tilde_warning_msg = (
  191. "NOTE: The current PATH contains path(s) starting with `~`, "
  192. "which may not be expanded by all applications."
  193. )
  194. msg_lines.append(tilde_warning_msg)
  195. # Returns the formatted multiline message
  196. return "\n".join(msg_lines)
  197. def _normalized_outrows(outrows):
  198. # type: (Iterable[InstalledCSVRow]) -> List[Tuple[str, str, str]]
  199. """Normalize the given rows of a RECORD file.
  200. Items in each row are converted into str. Rows are then sorted to make
  201. the value more predictable for tests.
  202. Each row is a 3-tuple (path, hash, size) and corresponds to a record of
  203. a RECORD file (see PEP 376 and PEP 427 for details). For the rows
  204. passed to this function, the size can be an integer as an int or string,
  205. or the empty string.
  206. """
  207. # Normally, there should only be one row per path, in which case the
  208. # second and third elements don't come into play when sorting.
  209. # However, in cases in the wild where a path might happen to occur twice,
  210. # we don't want the sort operation to trigger an error (but still want
  211. # determinism). Since the third element can be an int or string, we
  212. # coerce each element to a string to avoid a TypeError in this case.
  213. # For additional background, see--
  214. # https://github.com/pypa/pip/issues/5868
  215. return sorted(
  216. (ensure_str(record_path, encoding='utf-8'), hash_, str(size))
  217. for record_path, hash_, size in outrows
  218. )
  219. def _record_to_fs_path(record_path):
  220. # type: (RecordPath) -> text_type
  221. return record_path
  222. def _fs_to_record_path(path, relative_to=None):
  223. # type: (text_type, Optional[text_type]) -> RecordPath
  224. if relative_to is not None:
  225. # On Windows, do not handle relative paths if they belong to different
  226. # logical disks
  227. if os.path.splitdrive(path)[0].lower() == \
  228. os.path.splitdrive(relative_to)[0].lower():
  229. path = os.path.relpath(path, relative_to)
  230. path = path.replace(os.path.sep, '/')
  231. return cast('RecordPath', path)
  232. def _parse_record_path(record_column):
  233. # type: (str) -> RecordPath
  234. p = ensure_text(record_column, encoding='utf-8')
  235. return cast('RecordPath', p)
  236. def get_csv_rows_for_installed(
  237. old_csv_rows, # type: List[List[str]]
  238. installed, # type: Dict[RecordPath, RecordPath]
  239. changed, # type: Set[RecordPath]
  240. generated, # type: List[str]
  241. lib_dir, # type: str
  242. ):
  243. # type: (...) -> List[InstalledCSVRow]
  244. """
  245. :param installed: A map from archive RECORD path to installation RECORD
  246. path.
  247. """
  248. installed_rows = [] # type: List[InstalledCSVRow]
  249. for row in old_csv_rows:
  250. if len(row) > 3:
  251. logger.warning('RECORD line has more than three elements: %s', row)
  252. old_record_path = _parse_record_path(row[0])
  253. new_record_path = installed.pop(old_record_path, old_record_path)
  254. if new_record_path in changed:
  255. digest, length = rehash(_record_to_fs_path(new_record_path))
  256. else:
  257. digest = row[1] if len(row) > 1 else ''
  258. length = row[2] if len(row) > 2 else ''
  259. installed_rows.append((new_record_path, digest, length))
  260. for f in generated:
  261. path = _fs_to_record_path(f, lib_dir)
  262. digest, length = rehash(f)
  263. installed_rows.append((path, digest, length))
  264. for installed_record_path in itervalues(installed):
  265. installed_rows.append((installed_record_path, '', ''))
  266. return installed_rows
  267. def get_console_script_specs(console):
  268. # type: (Dict[str, str]) -> List[str]
  269. """
  270. Given the mapping from entrypoint name to callable, return the relevant
  271. console script specs.
  272. """
  273. # Don't mutate caller's version
  274. console = console.copy()
  275. scripts_to_generate = []
  276. # Special case pip and setuptools to generate versioned wrappers
  277. #
  278. # The issue is that some projects (specifically, pip and setuptools) use
  279. # code in setup.py to create "versioned" entry points - pip2.7 on Python
  280. # 2.7, pip3.3 on Python 3.3, etc. But these entry points are baked into
  281. # the wheel metadata at build time, and so if the wheel is installed with
  282. # a *different* version of Python the entry points will be wrong. The
  283. # correct fix for this is to enhance the metadata to be able to describe
  284. # such versioned entry points, but that won't happen till Metadata 2.0 is
  285. # available.
  286. # In the meantime, projects using versioned entry points will either have
  287. # incorrect versioned entry points, or they will not be able to distribute
  288. # "universal" wheels (i.e., they will need a wheel per Python version).
  289. #
  290. # Because setuptools and pip are bundled with _ensurepip and virtualenv,
  291. # we need to use universal wheels. So, as a stopgap until Metadata 2.0, we
  292. # override the versioned entry points in the wheel and generate the
  293. # correct ones. This code is purely a short-term measure until Metadata 2.0
  294. # is available.
  295. #
  296. # To add the level of hack in this section of code, in order to support
  297. # ensurepip this code will look for an ``ENSUREPIP_OPTIONS`` environment
  298. # variable which will control which version scripts get installed.
  299. #
  300. # ENSUREPIP_OPTIONS=altinstall
  301. # - Only pipX.Y and easy_install-X.Y will be generated and installed
  302. # ENSUREPIP_OPTIONS=install
  303. # - pipX.Y, pipX, easy_install-X.Y will be generated and installed. Note
  304. # that this option is technically if ENSUREPIP_OPTIONS is set and is
  305. # not altinstall
  306. # DEFAULT
  307. # - The default behavior is to install pip, pipX, pipX.Y, easy_install
  308. # and easy_install-X.Y.
  309. pip_script = console.pop('pip', None)
  310. if pip_script:
  311. if "ENSUREPIP_OPTIONS" not in os.environ:
  312. scripts_to_generate.append('pip = ' + pip_script)
  313. if os.environ.get("ENSUREPIP_OPTIONS", "") != "altinstall":
  314. scripts_to_generate.append(
  315. 'pip{} = {}'.format(sys.version_info[0], pip_script)
  316. )
  317. scripts_to_generate.append(
  318. 'pip{} = {}'.format(get_major_minor_version(), pip_script)
  319. )
  320. # Delete any other versioned pip entry points
  321. pip_ep = [k for k in console if re.match(r'pip(\d(\.\d)?)?$', k)]
  322. for k in pip_ep:
  323. del console[k]
  324. easy_install_script = console.pop('easy_install', None)
  325. if easy_install_script:
  326. if "ENSUREPIP_OPTIONS" not in os.environ:
  327. scripts_to_generate.append(
  328. 'easy_install = ' + easy_install_script
  329. )
  330. scripts_to_generate.append(
  331. 'easy_install-{} = {}'.format(
  332. get_major_minor_version(), easy_install_script
  333. )
  334. )
  335. # Delete any other versioned easy_install entry points
  336. easy_install_ep = [
  337. k for k in console if re.match(r'easy_install(-\d\.\d)?$', k)
  338. ]
  339. for k in easy_install_ep:
  340. del console[k]
  341. # Generate the console entry points specified in the wheel
  342. scripts_to_generate.extend(starmap('{} = {}'.format, console.items()))
  343. return scripts_to_generate
  344. class ZipBackedFile(object):
  345. def __init__(self, src_record_path, dest_path, zip_file):
  346. # type: (RecordPath, text_type, ZipFile) -> None
  347. self.src_record_path = src_record_path
  348. self.dest_path = dest_path
  349. self._zip_file = zip_file
  350. self.changed = False
  351. def _getinfo(self):
  352. # type: () -> ZipInfo
  353. if not PY2:
  354. return self._zip_file.getinfo(self.src_record_path)
  355. # Python 2 does not expose a way to detect a ZIP's encoding, but the
  356. # wheel specification (PEP 427) explicitly mandates that paths should
  357. # use UTF-8, so we assume it is true.
  358. return self._zip_file.getinfo(self.src_record_path.encode("utf-8"))
  359. def save(self):
  360. # type: () -> None
  361. # directory creation is lazy and after file filtering
  362. # to ensure we don't install empty dirs; empty dirs can't be
  363. # uninstalled.
  364. parent_dir = os.path.dirname(self.dest_path)
  365. ensure_dir(parent_dir)
  366. # When we open the output file below, any existing file is truncated
  367. # before we start writing the new contents. This is fine in most
  368. # cases, but can cause a segfault if pip has loaded a shared
  369. # object (e.g. from pyopenssl through its vendored urllib3)
  370. # Since the shared object is mmap'd an attempt to call a
  371. # symbol in it will then cause a segfault. Unlinking the file
  372. # allows writing of new contents while allowing the process to
  373. # continue to use the old copy.
  374. if os.path.exists(self.dest_path):
  375. os.unlink(self.dest_path)
  376. zipinfo = self._getinfo()
  377. with self._zip_file.open(zipinfo) as f:
  378. with open(self.dest_path, "wb") as dest:
  379. shutil.copyfileobj(f, dest)
  380. if zip_item_is_executable(zipinfo):
  381. set_extracted_file_to_default_mode_plus_executable(self.dest_path)
  382. class ScriptFile(object):
  383. def __init__(self, file):
  384. # type: (File) -> None
  385. self._file = file
  386. self.src_record_path = self._file.src_record_path
  387. self.dest_path = self._file.dest_path
  388. self.changed = False
  389. def save(self):
  390. # type: () -> None
  391. self._file.save()
  392. self.changed = fix_script(self.dest_path)
  393. class MissingCallableSuffix(InstallationError):
  394. def __init__(self, entry_point):
  395. # type: (str) -> None
  396. super(MissingCallableSuffix, self).__init__(
  397. "Invalid script entry point: {} - A callable "
  398. "suffix is required. Cf https://packaging.python.org/"
  399. "specifications/entry-points/#use-for-scripts for more "
  400. "information.".format(entry_point)
  401. )
  402. def _raise_for_invalid_entrypoint(specification):
  403. # type: (str) -> None
  404. entry = get_export_entry(specification)
  405. if entry is not None and entry.suffix is None:
  406. raise MissingCallableSuffix(str(entry))
  407. class PipScriptMaker(ScriptMaker):
  408. def make(self, specification, options=None):
  409. # type: (str, Dict[str, Any]) -> List[str]
  410. _raise_for_invalid_entrypoint(specification)
  411. return super(PipScriptMaker, self).make(specification, options)
  412. def _install_wheel(
  413. name, # type: str
  414. wheel_zip, # type: ZipFile
  415. wheel_path, # type: str
  416. scheme, # type: Scheme
  417. pycompile=True, # type: bool
  418. warn_script_location=True, # type: bool
  419. direct_url=None, # type: Optional[DirectUrl]
  420. requested=False, # type: bool
  421. ):
  422. # type: (...) -> None
  423. """Install a wheel.
  424. :param name: Name of the project to install
  425. :param wheel_zip: open ZipFile for wheel being installed
  426. :param scheme: Distutils scheme dictating the install directories
  427. :param req_description: String used in place of the requirement, for
  428. logging
  429. :param pycompile: Whether to byte-compile installed Python files
  430. :param warn_script_location: Whether to check that scripts are installed
  431. into a directory on PATH
  432. :raises UnsupportedWheel:
  433. * when the directory holds an unpacked wheel with incompatible
  434. Wheel-Version
  435. * when the .dist-info dir does not match the wheel
  436. """
  437. info_dir, metadata = parse_wheel(wheel_zip, name)
  438. if wheel_root_is_purelib(metadata):
  439. lib_dir = scheme.purelib
  440. else:
  441. lib_dir = scheme.platlib
  442. # Record details of the files moved
  443. # installed = files copied from the wheel to the destination
  444. # changed = files changed while installing (scripts #! line typically)
  445. # generated = files newly generated during the install (script wrappers)
  446. installed = {} # type: Dict[RecordPath, RecordPath]
  447. changed = set() # type: Set[RecordPath]
  448. generated = [] # type: List[str]
  449. def record_installed(srcfile, destfile, modified=False):
  450. # type: (RecordPath, text_type, bool) -> None
  451. """Map archive RECORD paths to installation RECORD paths."""
  452. newpath = _fs_to_record_path(destfile, lib_dir)
  453. installed[srcfile] = newpath
  454. if modified:
  455. changed.add(_fs_to_record_path(destfile))
  456. def all_paths():
  457. # type: () -> Iterable[RecordPath]
  458. names = wheel_zip.namelist()
  459. # If a flag is set, names may be unicode in Python 2. We convert to
  460. # text explicitly so these are valid for lookup in RECORD.
  461. decoded_names = map(ensure_text, names)
  462. for name in decoded_names:
  463. yield cast("RecordPath", name)
  464. def is_dir_path(path):
  465. # type: (RecordPath) -> bool
  466. return path.endswith("/")
  467. def assert_no_path_traversal(dest_dir_path, target_path):
  468. # type: (text_type, text_type) -> None
  469. if not is_within_directory(dest_dir_path, target_path):
  470. message = (
  471. "The wheel {!r} has a file {!r} trying to install"
  472. " outside the target directory {!r}"
  473. )
  474. raise InstallationError(
  475. message.format(wheel_path, target_path, dest_dir_path)
  476. )
  477. def root_scheme_file_maker(zip_file, dest):
  478. # type: (ZipFile, text_type) -> Callable[[RecordPath], File]
  479. def make_root_scheme_file(record_path):
  480. # type: (RecordPath) -> File
  481. normed_path = os.path.normpath(record_path)
  482. dest_path = os.path.join(dest, normed_path)
  483. assert_no_path_traversal(dest, dest_path)
  484. return ZipBackedFile(record_path, dest_path, zip_file)
  485. return make_root_scheme_file
  486. def data_scheme_file_maker(zip_file, scheme):
  487. # type: (ZipFile, Scheme) -> Callable[[RecordPath], File]
  488. scheme_paths = {}
  489. for key in SCHEME_KEYS:
  490. encoded_key = ensure_text(key)
  491. scheme_paths[encoded_key] = ensure_text(
  492. getattr(scheme, key), encoding=sys.getfilesystemencoding()
  493. )
  494. def make_data_scheme_file(record_path):
  495. # type: (RecordPath) -> File
  496. normed_path = os.path.normpath(record_path)
  497. try:
  498. _, scheme_key, dest_subpath = normed_path.split(os.path.sep, 2)
  499. except ValueError:
  500. message = (
  501. "Unexpected file in {}: {!r}. .data directory contents"
  502. " should be named like: '<scheme key>/<path>'."
  503. ).format(wheel_path, record_path)
  504. raise InstallationError(message)
  505. try:
  506. scheme_path = scheme_paths[scheme_key]
  507. except KeyError:
  508. valid_scheme_keys = ", ".join(sorted(scheme_paths))
  509. message = (
  510. "Unknown scheme key used in {}: {} (for file {!r}). .data"
  511. " directory contents should be in subdirectories named"
  512. " with a valid scheme key ({})"
  513. ).format(
  514. wheel_path, scheme_key, record_path, valid_scheme_keys
  515. )
  516. raise InstallationError(message)
  517. dest_path = os.path.join(scheme_path, dest_subpath)
  518. assert_no_path_traversal(scheme_path, dest_path)
  519. return ZipBackedFile(record_path, dest_path, zip_file)
  520. return make_data_scheme_file
  521. def is_data_scheme_path(path):
  522. # type: (RecordPath) -> bool
  523. return path.split("/", 1)[0].endswith(".data")
  524. paths = all_paths()
  525. file_paths = filterfalse(is_dir_path, paths)
  526. root_scheme_paths, data_scheme_paths = partition(
  527. is_data_scheme_path, file_paths
  528. )
  529. make_root_scheme_file = root_scheme_file_maker(
  530. wheel_zip,
  531. ensure_text(lib_dir, encoding=sys.getfilesystemencoding()),
  532. )
  533. files = map(make_root_scheme_file, root_scheme_paths)
  534. def is_script_scheme_path(path):
  535. # type: (RecordPath) -> bool
  536. parts = path.split("/", 2)
  537. return (
  538. len(parts) > 2 and
  539. parts[0].endswith(".data") and
  540. parts[1] == "scripts"
  541. )
  542. other_scheme_paths, script_scheme_paths = partition(
  543. is_script_scheme_path, data_scheme_paths
  544. )
  545. make_data_scheme_file = data_scheme_file_maker(wheel_zip, scheme)
  546. other_scheme_files = map(make_data_scheme_file, other_scheme_paths)
  547. files = chain(files, other_scheme_files)
  548. # Get the defined entry points
  549. distribution = pkg_resources_distribution_for_wheel(
  550. wheel_zip, name, wheel_path
  551. )
  552. console, gui = get_entrypoints(distribution)
  553. def is_entrypoint_wrapper(file):
  554. # type: (File) -> bool
  555. # EP, EP.exe and EP-script.py are scripts generated for
  556. # entry point EP by setuptools
  557. path = file.dest_path
  558. name = os.path.basename(path)
  559. if name.lower().endswith('.exe'):
  560. matchname = name[:-4]
  561. elif name.lower().endswith('-script.py'):
  562. matchname = name[:-10]
  563. elif name.lower().endswith(".pya"):
  564. matchname = name[:-4]
  565. else:
  566. matchname = name
  567. # Ignore setuptools-generated scripts
  568. return (matchname in console or matchname in gui)
  569. script_scheme_files = map(make_data_scheme_file, script_scheme_paths)
  570. script_scheme_files = filterfalse(
  571. is_entrypoint_wrapper, script_scheme_files
  572. )
  573. script_scheme_files = map(ScriptFile, script_scheme_files)
  574. files = chain(files, script_scheme_files)
  575. for file in files:
  576. file.save()
  577. record_installed(file.src_record_path, file.dest_path, file.changed)
  578. def pyc_source_file_paths():
  579. # type: () -> Iterator[text_type]
  580. # We de-duplicate installation paths, since there can be overlap (e.g.
  581. # file in .data maps to same location as file in wheel root).
  582. # Sorting installation paths makes it easier to reproduce and debug
  583. # issues related to permissions on existing files.
  584. for installed_path in sorted(set(installed.values())):
  585. full_installed_path = os.path.join(lib_dir, installed_path)
  586. if not os.path.isfile(full_installed_path):
  587. continue
  588. if not full_installed_path.endswith('.py'):
  589. continue
  590. yield full_installed_path
  591. def pyc_output_path(path):
  592. # type: (text_type) -> text_type
  593. """Return the path the pyc file would have been written to.
  594. """
  595. if PY2:
  596. if sys.flags.optimize:
  597. return path + 'o'
  598. else:
  599. return path + 'c'
  600. else:
  601. return importlib.util.cache_from_source(path)
  602. # Compile all of the pyc files for the installed files
  603. if pycompile:
  604. with captured_stdout() as stdout:
  605. with warnings.catch_warnings():
  606. warnings.filterwarnings('ignore')
  607. for path in pyc_source_file_paths():
  608. # Python 2's `compileall.compile_file` requires a str in
  609. # error cases, so we must convert to the native type.
  610. path_arg = ensure_str(
  611. path, encoding=sys.getfilesystemencoding()
  612. )
  613. success = compileall.compile_file(
  614. path_arg, force=True, quiet=True
  615. )
  616. if success:
  617. pyc_path = pyc_output_path(path)
  618. assert os.path.exists(pyc_path)
  619. pyc_record_path = cast(
  620. "RecordPath", pyc_path.replace(os.path.sep, "/")
  621. )
  622. record_installed(pyc_record_path, pyc_path)
  623. logger.debug(stdout.getvalue())
  624. maker = PipScriptMaker(None, scheme.scripts)
  625. # Ensure old scripts are overwritten.
  626. # See https://github.com/pypa/pip/issues/1800
  627. maker.clobber = True
  628. # Ensure we don't generate any variants for scripts because this is almost
  629. # never what somebody wants.
  630. # See https://bitbucket.org/pypa/distlib/issue/35/
  631. maker.variants = {''}
  632. # This is required because otherwise distlib creates scripts that are not
  633. # executable.
  634. # See https://bitbucket.org/pypa/distlib/issue/32/
  635. maker.set_mode = True
  636. # Generate the console and GUI entry points specified in the wheel
  637. scripts_to_generate = get_console_script_specs(console)
  638. gui_scripts_to_generate = list(starmap('{} = {}'.format, gui.items()))
  639. generated_console_scripts = maker.make_multiple(scripts_to_generate)
  640. generated.extend(generated_console_scripts)
  641. generated.extend(
  642. maker.make_multiple(gui_scripts_to_generate, {'gui': True})
  643. )
  644. if warn_script_location:
  645. msg = message_about_scripts_not_on_PATH(generated_console_scripts)
  646. if msg is not None:
  647. logger.warning(msg)
  648. generated_file_mode = 0o666 & ~current_umask()
  649. @contextlib.contextmanager
  650. def _generate_file(path, **kwargs):
  651. # type: (str, **Any) -> Iterator[NamedTemporaryFileResult]
  652. with adjacent_tmp_file(path, **kwargs) as f:
  653. yield f
  654. os.chmod(f.name, generated_file_mode)
  655. replace(f.name, path)
  656. dest_info_dir = os.path.join(lib_dir, info_dir)
  657. # Record pip as the installer
  658. installer_path = os.path.join(dest_info_dir, 'INSTALLER')
  659. with _generate_file(installer_path) as installer_file:
  660. installer_file.write(b'pip\n')
  661. generated.append(installer_path)
  662. # Record the PEP 610 direct URL reference
  663. if direct_url is not None:
  664. direct_url_path = os.path.join(dest_info_dir, DIRECT_URL_METADATA_NAME)
  665. with _generate_file(direct_url_path) as direct_url_file:
  666. direct_url_file.write(direct_url.to_json().encode("utf-8"))
  667. generated.append(direct_url_path)
  668. # Record the REQUESTED file
  669. if requested:
  670. requested_path = os.path.join(dest_info_dir, 'REQUESTED')
  671. with open(requested_path, "w"):
  672. pass
  673. generated.append(requested_path)
  674. record_text = distribution.get_metadata('RECORD')
  675. record_rows = list(csv.reader(record_text.splitlines()))
  676. rows = get_csv_rows_for_installed(
  677. record_rows,
  678. installed=installed,
  679. changed=changed,
  680. generated=generated,
  681. lib_dir=lib_dir)
  682. # Record details of all files installed
  683. record_path = os.path.join(dest_info_dir, 'RECORD')
  684. with _generate_file(record_path, **csv_io_kwargs('w')) as record_file:
  685. # The type mypy infers for record_file is different for Python 3
  686. # (typing.IO[Any]) and Python 2 (typing.BinaryIO). We explicitly
  687. # cast to typing.IO[str] as a workaround.
  688. writer = csv.writer(cast('IO[str]', record_file))
  689. writer.writerows(_normalized_outrows(rows))
  690. @contextlib.contextmanager
  691. def req_error_context(req_description):
  692. # type: (str) -> Iterator[None]
  693. try:
  694. yield
  695. except InstallationError as e:
  696. message = "For req: {}. {}".format(req_description, e.args[0])
  697. reraise(
  698. InstallationError, InstallationError(message), sys.exc_info()[2]
  699. )
  700. def install_wheel(
  701. name, # type: str
  702. wheel_path, # type: str
  703. scheme, # type: Scheme
  704. req_description, # type: str
  705. pycompile=True, # type: bool
  706. warn_script_location=True, # type: bool
  707. direct_url=None, # type: Optional[DirectUrl]
  708. requested=False, # type: bool
  709. ):
  710. # type: (...) -> None
  711. with ZipFile(wheel_path, allowZip64=True) as z:
  712. with req_error_context(req_description):
  713. _install_wheel(
  714. name=name,
  715. wheel_zip=z,
  716. wheel_path=wheel_path,
  717. scheme=scheme,
  718. pycompile=pycompile,
  719. warn_script_location=warn_script_location,
  720. direct_url=direct_url,
  721. requested=requested,
  722. )