wheel.py 27 KB

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