wheel.py 29 KB

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