Path: blob/main/test/lib/python3.9/site-packages/pip/_internal/utils/wheel.py
4804 views
"""Support functions for working with wheel files.1"""23import logging4from email.message import Message5from email.parser import Parser6from typing import Tuple7from zipfile import BadZipFile, ZipFile89from pip._vendor.packaging.utils import canonicalize_name1011from pip._internal.exceptions import UnsupportedWheel1213VERSION_COMPATIBLE = (1, 0)141516logger = logging.getLogger(__name__)171819def parse_wheel(wheel_zip: ZipFile, name: str) -> Tuple[str, Message]:20"""Extract information from the provided wheel, ensuring it meets basic21standards.2223Returns the name of the .dist-info directory and the parsed WHEEL metadata.24"""25try:26info_dir = wheel_dist_info_dir(wheel_zip, name)27metadata = wheel_metadata(wheel_zip, info_dir)28version = wheel_version(metadata)29except UnsupportedWheel as e:30raise UnsupportedWheel("{} has an invalid wheel, {}".format(name, str(e)))3132check_compatibility(version, name)3334return info_dir, metadata353637def wheel_dist_info_dir(source: ZipFile, name: str) -> str:38"""Returns the name of the contained .dist-info directory.3940Raises AssertionError or UnsupportedWheel if not found, >1 found, or41it doesn't match the provided name.42"""43# Zip file path separators must be /44subdirs = {p.split("/", 1)[0] for p in source.namelist()}4546info_dirs = [s for s in subdirs if s.endswith(".dist-info")]4748if not info_dirs:49raise UnsupportedWheel(".dist-info directory not found")5051if len(info_dirs) > 1:52raise UnsupportedWheel(53"multiple .dist-info directories found: {}".format(", ".join(info_dirs))54)5556info_dir = info_dirs[0]5758info_dir_name = canonicalize_name(info_dir)59canonical_name = canonicalize_name(name)60if not info_dir_name.startswith(canonical_name):61raise UnsupportedWheel(62".dist-info directory {!r} does not start with {!r}".format(63info_dir, canonical_name64)65)6667return info_dir686970def read_wheel_metadata_file(source: ZipFile, path: str) -> bytes:71try:72return source.read(path)73# BadZipFile for general corruption, KeyError for missing entry,74# and RuntimeError for password-protected files75except (BadZipFile, KeyError, RuntimeError) as e:76raise UnsupportedWheel(f"could not read {path!r} file: {e!r}")777879def wheel_metadata(source: ZipFile, dist_info_dir: str) -> Message:80"""Return the WHEEL metadata of an extracted wheel, if possible.81Otherwise, raise UnsupportedWheel.82"""83path = f"{dist_info_dir}/WHEEL"84# Zip file path separators must be /85wheel_contents = read_wheel_metadata_file(source, path)8687try:88wheel_text = wheel_contents.decode()89except UnicodeDecodeError as e:90raise UnsupportedWheel(f"error decoding {path!r}: {e!r}")9192# FeedParser (used by Parser) does not raise any exceptions. The returned93# message may have .defects populated, but for backwards-compatibility we94# currently ignore them.95return Parser().parsestr(wheel_text)969798def wheel_version(wheel_data: Message) -> Tuple[int, ...]:99"""Given WHEEL metadata, return the parsed Wheel-Version.100Otherwise, raise UnsupportedWheel.101"""102version_text = wheel_data["Wheel-Version"]103if version_text is None:104raise UnsupportedWheel("WHEEL is missing Wheel-Version")105106version = version_text.strip()107108try:109return tuple(map(int, version.split(".")))110except ValueError:111raise UnsupportedWheel(f"invalid Wheel-Version: {version!r}")112113114def check_compatibility(version: Tuple[int, ...], name: str) -> None:115"""Raises errors or warns if called with an incompatible Wheel-Version.116117pip should refuse to install a Wheel-Version that's a major series118ahead of what it's compatible with (e.g 2.0 > 1.1); and warn when119installing a version only minor version ahead (e.g 1.2 > 1.1).120121version: a 2-tuple representing a Wheel-Version (Major, Minor)122name: name of wheel or package to raise exception about123124:raises UnsupportedWheel: when an incompatible Wheel-Version is given125"""126if version[0] > VERSION_COMPATIBLE[0]:127raise UnsupportedWheel(128"{}'s Wheel-Version ({}) is not compatible with this version "129"of pip".format(name, ".".join(map(str, version)))130)131elif version > VERSION_COMPATIBLE:132logger.warning(133"Installing from a newer Wheel-Version (%s)",134".".join(map(str, version)),135)136137138