wheel.py 27 KB

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