wheel.py 29 KB

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