wheel.py 27 KB

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