wheel.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. """Support functions for working with wheel files.
  2. """
  3. import logging
  4. from email.message import Message
  5. from email.parser import Parser
  6. from typing import Tuple
  7. from zipfile import BadZipFile, ZipFile
  8. from pip._vendor.packaging.utils import canonicalize_name
  9. from pip._internal.exceptions import UnsupportedWheel
  10. VERSION_COMPATIBLE = (1, 0)
  11. logger = logging.getLogger(__name__)
  12. def parse_wheel(wheel_zip: ZipFile, name: str) -> Tuple[str, Message]:
  13. """Extract information from the provided wheel, ensuring it meets basic
  14. standards.
  15. Returns the name of the .dist-info directory and the parsed WHEEL metadata.
  16. """
  17. try:
  18. info_dir = wheel_dist_info_dir(wheel_zip, name)
  19. metadata = wheel_metadata(wheel_zip, info_dir)
  20. version = wheel_version(metadata)
  21. except UnsupportedWheel as e:
  22. raise UnsupportedWheel("{} has an invalid wheel, {}".format(name, str(e)))
  23. check_compatibility(version, name)
  24. return info_dir, metadata
  25. def wheel_dist_info_dir(source: ZipFile, name: str) -> str:
  26. """Returns the name of the contained .dist-info directory.
  27. Raises AssertionError or UnsupportedWheel if not found, >1 found, or
  28. it doesn't match the provided name.
  29. """
  30. # Zip file path separators must be /
  31. subdirs = {p.split("/", 1)[0] for p in source.namelist()}
  32. info_dirs = [s for s in subdirs if s.endswith(".dist-info")]
  33. if not info_dirs:
  34. raise UnsupportedWheel(".dist-info directory not found")
  35. if len(info_dirs) > 1:
  36. raise UnsupportedWheel(
  37. "multiple .dist-info directories found: {}".format(", ".join(info_dirs))
  38. )
  39. info_dir = info_dirs[0]
  40. info_dir_name = canonicalize_name(info_dir)
  41. canonical_name = canonicalize_name(name)
  42. if not info_dir_name.startswith(canonical_name):
  43. raise UnsupportedWheel(
  44. ".dist-info directory {!r} does not start with {!r}".format(
  45. info_dir, canonical_name
  46. )
  47. )
  48. return info_dir
  49. def read_wheel_metadata_file(source: ZipFile, path: str) -> bytes:
  50. try:
  51. return source.read(path)
  52. # BadZipFile for general corruption, KeyError for missing entry,
  53. # and RuntimeError for password-protected files
  54. except (BadZipFile, KeyError, RuntimeError) as e:
  55. raise UnsupportedWheel(f"could not read {path!r} file: {e!r}")
  56. def wheel_metadata(source: ZipFile, dist_info_dir: str) -> Message:
  57. """Return the WHEEL metadata of an extracted wheel, if possible.
  58. Otherwise, raise UnsupportedWheel.
  59. """
  60. path = f"{dist_info_dir}/WHEEL"
  61. # Zip file path separators must be /
  62. wheel_contents = read_wheel_metadata_file(source, path)
  63. try:
  64. wheel_text = wheel_contents.decode()
  65. except UnicodeDecodeError as e:
  66. raise UnsupportedWheel(f"error decoding {path!r}: {e!r}")
  67. # FeedParser (used by Parser) does not raise any exceptions. The returned
  68. # message may have .defects populated, but for backwards-compatibility we
  69. # currently ignore them.
  70. return Parser().parsestr(wheel_text)
  71. def wheel_version(wheel_data: Message) -> Tuple[int, ...]:
  72. """Given WHEEL metadata, return the parsed Wheel-Version.
  73. Otherwise, raise UnsupportedWheel.
  74. """
  75. version_text = wheel_data["Wheel-Version"]
  76. if version_text is None:
  77. raise UnsupportedWheel("WHEEL is missing Wheel-Version")
  78. version = version_text.strip()
  79. try:
  80. return tuple(map(int, version.split(".")))
  81. except ValueError:
  82. raise UnsupportedWheel(f"invalid Wheel-Version: {version!r}")
  83. def check_compatibility(version: Tuple[int, ...], name: str) -> None:
  84. """Raises errors or warns if called with an incompatible Wheel-Version.
  85. pip should refuse to install a Wheel-Version that's a major series
  86. ahead of what it's compatible with (e.g 2.0 > 1.1); and warn when
  87. installing a version only minor version ahead (e.g 1.2 > 1.1).
  88. version: a 2-tuple representing a Wheel-Version (Major, Minor)
  89. name: name of wheel or package to raise exception about
  90. :raises UnsupportedWheel: when an incompatible Wheel-Version is given
  91. """
  92. if version[0] > VERSION_COMPATIBLE[0]:
  93. raise UnsupportedWheel(
  94. "{}'s Wheel-Version ({}) is not compatible with this version "
  95. "of pip".format(name, ".".join(map(str, version)))
  96. )
  97. elif version > VERSION_COMPATIBLE:
  98. logger.warning(
  99. "Installing from a newer Wheel-Version (%s)",
  100. ".".join(map(str, version)),
  101. )