wheel.py 29 KB

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