Path: blob/main/test/lib/python3.9/site-packages/pip/_internal/metadata/base.py
4805 views
import csv1import email.message2import json3import logging4import pathlib5import re6import zipfile7from typing import (8IO,9TYPE_CHECKING,10Collection,11Container,12Iterable,13Iterator,14List,15Optional,16Tuple,17Union,18)1920from pip._vendor.packaging.requirements import Requirement21from pip._vendor.packaging.specifiers import InvalidSpecifier, SpecifierSet22from pip._vendor.packaging.utils import NormalizedName23from pip._vendor.packaging.version import LegacyVersion, Version2425from pip._internal.exceptions import NoneMetadataError26from pip._internal.locations import site_packages, user_site27from pip._internal.models.direct_url import (28DIRECT_URL_METADATA_NAME,29DirectUrl,30DirectUrlValidationError,31)32from pip._internal.utils.compat import stdlib_pkgs # TODO: Move definition here.33from pip._internal.utils.egg_link import egg_link_path_from_sys_path34from pip._internal.utils.misc import is_local, normalize_path35from pip._internal.utils.urls import url_to_path3637if TYPE_CHECKING:38from typing import Protocol39else:40Protocol = object4142DistributionVersion = Union[LegacyVersion, Version]4344InfoPath = Union[str, pathlib.PurePath]4546logger = logging.getLogger(__name__)474849class BaseEntryPoint(Protocol):50@property51def name(self) -> str:52raise NotImplementedError()5354@property55def value(self) -> str:56raise NotImplementedError()5758@property59def group(self) -> str:60raise NotImplementedError()616263def _convert_installed_files_path(64entry: Tuple[str, ...],65info: Tuple[str, ...],66) -> str:67"""Convert a legacy installed-files.txt path into modern RECORD path.6869The legacy format stores paths relative to the info directory, while the70modern format stores paths relative to the package root, e.g. the71site-packages directory.7273:param entry: Path parts of the installed-files.txt entry.74:param info: Path parts of the egg-info directory relative to package root.75:returns: The converted entry.7677For best compatibility with symlinks, this does not use ``abspath()`` or78``Path.resolve()``, but tries to work with path parts:79801. While ``entry`` starts with ``..``, remove the equal amounts of parts81from ``info``; if ``info`` is empty, start appending ``..`` instead.822. Join the two directly.83"""84while entry and entry[0] == "..":85if not info or info[-1] == "..":86info += ("..",)87else:88info = info[:-1]89entry = entry[1:]90return str(pathlib.Path(*info, *entry))919293class BaseDistribution(Protocol):94@classmethod95def from_directory(cls, directory: str) -> "BaseDistribution":96"""Load the distribution from a metadata directory.9798:param directory: Path to a metadata directory, e.g. ``.dist-info``.99"""100raise NotImplementedError()101102@classmethod103def from_wheel(cls, wheel: "Wheel", name: str) -> "BaseDistribution":104"""Load the distribution from a given wheel.105106:param wheel: A concrete wheel definition.107:param name: File name of the wheel.108109:raises InvalidWheel: Whenever loading of the wheel causes a110:py:exc:`zipfile.BadZipFile` exception to be thrown.111:raises UnsupportedWheel: If the wheel is a valid zip, but malformed112internally.113"""114raise NotImplementedError()115116def __repr__(self) -> str:117return f"{self.raw_name} {self.version} ({self.location})"118119def __str__(self) -> str:120return f"{self.raw_name} {self.version}"121122@property123def location(self) -> Optional[str]:124"""Where the distribution is loaded from.125126A string value is not necessarily a filesystem path, since distributions127can be loaded from other sources, e.g. arbitrary zip archives. ``None``128means the distribution is created in-memory.129130Do not canonicalize this value with e.g. ``pathlib.Path.resolve()``. If131this is a symbolic link, we want to preserve the relative path between132it and files in the distribution.133"""134raise NotImplementedError()135136@property137def editable_project_location(self) -> Optional[str]:138"""The project location for editable distributions.139140This is the directory where pyproject.toml or setup.py is located.141None if the distribution is not installed in editable mode.142"""143# TODO: this property is relatively costly to compute, memoize it ?144direct_url = self.direct_url145if direct_url:146if direct_url.is_local_editable():147return url_to_path(direct_url.url)148else:149# Search for an .egg-link file by walking sys.path, as it was150# done before by dist_is_editable().151egg_link_path = egg_link_path_from_sys_path(self.raw_name)152if egg_link_path:153# TODO: get project location from second line of egg_link file154# (https://github.com/pypa/pip/issues/10243)155return self.location156return None157158@property159def installed_location(self) -> Optional[str]:160"""The distribution's "installed" location.161162This should generally be a ``site-packages`` directory. This is163usually ``dist.location``, except for legacy develop-installed packages,164where ``dist.location`` is the source code location, and this is where165the ``.egg-link`` file is.166167The returned location is normalized (in particular, with symlinks removed).168"""169raise NotImplementedError()170171@property172def info_location(self) -> Optional[str]:173"""Location of the .[egg|dist]-info directory or file.174175Similarly to ``location``, a string value is not necessarily a176filesystem path. ``None`` means the distribution is created in-memory.177178For a modern .dist-info installation on disk, this should be something179like ``{location}/{raw_name}-{version}.dist-info``.180181Do not canonicalize this value with e.g. ``pathlib.Path.resolve()``. If182this is a symbolic link, we want to preserve the relative path between183it and other files in the distribution.184"""185raise NotImplementedError()186187@property188def installed_by_distutils(self) -> bool:189"""Whether this distribution is installed with legacy distutils format.190191A distribution installed with "raw" distutils not patched by setuptools192uses one single file at ``info_location`` to store metadata. We need to193treat this specially on uninstallation.194"""195info_location = self.info_location196if not info_location:197return False198return pathlib.Path(info_location).is_file()199200@property201def installed_as_egg(self) -> bool:202"""Whether this distribution is installed as an egg.203204This usually indicates the distribution was installed by (older versions205of) easy_install.206"""207location = self.location208if not location:209return False210return location.endswith(".egg")211212@property213def installed_with_setuptools_egg_info(self) -> bool:214"""Whether this distribution is installed with the ``.egg-info`` format.215216This usually indicates the distribution was installed with setuptools217with an old pip version or with ``single-version-externally-managed``.218219Note that this ensure the metadata store is a directory. distutils can220also installs an ``.egg-info``, but as a file, not a directory. This221property is *False* for that case. Also see ``installed_by_distutils``.222"""223info_location = self.info_location224if not info_location:225return False226if not info_location.endswith(".egg-info"):227return False228return pathlib.Path(info_location).is_dir()229230@property231def installed_with_dist_info(self) -> bool:232"""Whether this distribution is installed with the "modern format".233234This indicates a "modern" installation, e.g. storing metadata in the235``.dist-info`` directory. This applies to installations made by236setuptools (but through pip, not directly), or anything using the237standardized build backend interface (PEP 517).238"""239info_location = self.info_location240if not info_location:241return False242if not info_location.endswith(".dist-info"):243return False244return pathlib.Path(info_location).is_dir()245246@property247def canonical_name(self) -> NormalizedName:248raise NotImplementedError()249250@property251def version(self) -> DistributionVersion:252raise NotImplementedError()253254@property255def setuptools_filename(self) -> str:256"""Convert a project name to its setuptools-compatible filename.257258This is a copy of ``pkg_resources.to_filename()`` for compatibility.259"""260return self.raw_name.replace("-", "_")261262@property263def direct_url(self) -> Optional[DirectUrl]:264"""Obtain a DirectUrl from this distribution.265266Returns None if the distribution has no `direct_url.json` metadata,267or if `direct_url.json` is invalid.268"""269try:270content = self.read_text(DIRECT_URL_METADATA_NAME)271except FileNotFoundError:272return None273try:274return DirectUrl.from_json(content)275except (276UnicodeDecodeError,277json.JSONDecodeError,278DirectUrlValidationError,279) as e:280logger.warning(281"Error parsing %s for %s: %s",282DIRECT_URL_METADATA_NAME,283self.canonical_name,284e,285)286return None287288@property289def installer(self) -> str:290try:291installer_text = self.read_text("INSTALLER")292except (OSError, ValueError, NoneMetadataError):293return "" # Fail silently if the installer file cannot be read.294for line in installer_text.splitlines():295cleaned_line = line.strip()296if cleaned_line:297return cleaned_line298return ""299300@property301def editable(self) -> bool:302return bool(self.editable_project_location)303304@property305def local(self) -> bool:306"""If distribution is installed in the current virtual environment.307308Always True if we're not in a virtualenv.309"""310if self.installed_location is None:311return False312return is_local(self.installed_location)313314@property315def in_usersite(self) -> bool:316if self.installed_location is None or user_site is None:317return False318return self.installed_location.startswith(normalize_path(user_site))319320@property321def in_site_packages(self) -> bool:322if self.installed_location is None or site_packages is None:323return False324return self.installed_location.startswith(normalize_path(site_packages))325326def is_file(self, path: InfoPath) -> bool:327"""Check whether an entry in the info directory is a file."""328raise NotImplementedError()329330def iter_distutils_script_names(self) -> Iterator[str]:331"""Find distutils 'scripts' entries metadata.332333If 'scripts' is supplied in ``setup.py``, distutils records those in the334installed distribution's ``scripts`` directory, a file for each script.335"""336raise NotImplementedError()337338def read_text(self, path: InfoPath) -> str:339"""Read a file in the info directory.340341:raise FileNotFoundError: If ``path`` does not exist in the directory.342:raise NoneMetadataError: If ``path`` exists in the info directory, but343cannot be read.344"""345raise NotImplementedError()346347def iter_entry_points(self) -> Iterable[BaseEntryPoint]:348raise NotImplementedError()349350@property351def metadata(self) -> email.message.Message:352"""Metadata of distribution parsed from e.g. METADATA or PKG-INFO.353354This should return an empty message if the metadata file is unavailable.355356:raises NoneMetadataError: If the metadata file is available, but does357not contain valid metadata.358"""359raise NotImplementedError()360361@property362def metadata_version(self) -> Optional[str]:363"""Value of "Metadata-Version:" in distribution metadata, if available."""364return self.metadata.get("Metadata-Version")365366@property367def raw_name(self) -> str:368"""Value of "Name:" in distribution metadata."""369# The metadata should NEVER be missing the Name: key, but if it somehow370# does, fall back to the known canonical name.371return self.metadata.get("Name", self.canonical_name)372373@property374def requires_python(self) -> SpecifierSet:375"""Value of "Requires-Python:" in distribution metadata.376377If the key does not exist or contains an invalid value, an empty378SpecifierSet should be returned.379"""380value = self.metadata.get("Requires-Python")381if value is None:382return SpecifierSet()383try:384# Convert to str to satisfy the type checker; this can be a Header object.385spec = SpecifierSet(str(value))386except InvalidSpecifier as e:387message = "Package %r has an invalid Requires-Python: %s"388logger.warning(message, self.raw_name, e)389return SpecifierSet()390return spec391392def iter_dependencies(self, extras: Collection[str] = ()) -> Iterable[Requirement]:393"""Dependencies of this distribution.394395For modern .dist-info distributions, this is the collection of396"Requires-Dist:" entries in distribution metadata.397"""398raise NotImplementedError()399400def iter_provided_extras(self) -> Iterable[str]:401"""Extras provided by this distribution.402403For modern .dist-info distributions, this is the collection of404"Provides-Extra:" entries in distribution metadata.405"""406raise NotImplementedError()407408def _iter_declared_entries_from_record(self) -> Optional[Iterator[str]]:409try:410text = self.read_text("RECORD")411except FileNotFoundError:412return None413# This extra Path-str cast normalizes entries.414return (str(pathlib.Path(row[0])) for row in csv.reader(text.splitlines()))415416def _iter_declared_entries_from_legacy(self) -> Optional[Iterator[str]]:417try:418text = self.read_text("installed-files.txt")419except FileNotFoundError:420return None421paths = (p for p in text.splitlines(keepends=False) if p)422root = self.location423info = self.info_location424if root is None or info is None:425return paths426try:427info_rel = pathlib.Path(info).relative_to(root)428except ValueError: # info is not relative to root.429return paths430if not info_rel.parts: # info *is* root.431return paths432return (433_convert_installed_files_path(pathlib.Path(p).parts, info_rel.parts)434for p in paths435)436437def iter_declared_entries(self) -> Optional[Iterator[str]]:438"""Iterate through file entires declared in this distribution.439440For modern .dist-info distributions, this is the files listed in the441``RECORD`` metadata file. For legacy setuptools distributions, this442comes from ``installed-files.txt``, with entries normalized to be443compatible with the format used by ``RECORD``.444445:return: An iterator for listed entries, or None if the distribution446contains neither ``RECORD`` nor ``installed-files.txt``.447"""448return (449self._iter_declared_entries_from_record()450or self._iter_declared_entries_from_legacy()451)452453454class BaseEnvironment:455"""An environment containing distributions to introspect."""456457@classmethod458def default(cls) -> "BaseEnvironment":459raise NotImplementedError()460461@classmethod462def from_paths(cls, paths: Optional[List[str]]) -> "BaseEnvironment":463raise NotImplementedError()464465def get_distribution(self, name: str) -> Optional["BaseDistribution"]:466"""Given a requirement name, return the installed distributions.467468The name may not be normalized. The implementation must canonicalize469it for lookup.470"""471raise NotImplementedError()472473def _iter_distributions(self) -> Iterator["BaseDistribution"]:474"""Iterate through installed distributions.475476This function should be implemented by subclass, but never called477directly. Use the public ``iter_distribution()`` instead, which478implements additional logic to make sure the distributions are valid.479"""480raise NotImplementedError()481482def iter_all_distributions(self) -> Iterator[BaseDistribution]:483"""Iterate through all installed distributions without any filtering."""484for dist in self._iter_distributions():485# Make sure the distribution actually comes from a valid Python486# packaging distribution. Pip's AdjacentTempDirectory leaves folders487# e.g. ``~atplotlib.dist-info`` if cleanup was interrupted. The488# valid project name pattern is taken from PEP 508.489project_name_valid = re.match(490r"^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$",491dist.canonical_name,492flags=re.IGNORECASE,493)494if not project_name_valid:495logger.warning(496"Ignoring invalid distribution %s (%s)",497dist.canonical_name,498dist.location,499)500continue501yield dist502503def iter_installed_distributions(504self,505local_only: bool = True,506skip: Container[str] = stdlib_pkgs,507include_editables: bool = True,508editables_only: bool = False,509user_only: bool = False,510) -> Iterator[BaseDistribution]:511"""Return a list of installed distributions.512513This is based on ``iter_all_distributions()`` with additional filtering514options. Note that ``iter_installed_distributions()`` without arguments515is *not* equal to ``iter_all_distributions()``, since some of the516configurations exclude packages by default.517518:param local_only: If True (default), only return installations519local to the current virtualenv, if in a virtualenv.520:param skip: An iterable of canonicalized project names to ignore;521defaults to ``stdlib_pkgs``.522:param include_editables: If False, don't report editables.523:param editables_only: If True, only report editables.524:param user_only: If True, only report installations in the user525site directory.526"""527it = self.iter_all_distributions()528if local_only:529it = (d for d in it if d.local)530if not include_editables:531it = (d for d in it if not d.editable)532if editables_only:533it = (d for d in it if d.editable)534if user_only:535it = (d for d in it if d.in_usersite)536return (d for d in it if d.canonical_name not in skip)537538539class Wheel(Protocol):540location: str541542def as_zipfile(self) -> zipfile.ZipFile:543raise NotImplementedError()544545546class FilesystemWheel(Wheel):547def __init__(self, location: str) -> None:548self.location = location549550def as_zipfile(self) -> zipfile.ZipFile:551return zipfile.ZipFile(self.location, allowZip64=True)552553554class MemoryWheel(Wheel):555def __init__(self, location: str, stream: IO[bytes]) -> None:556self.location = location557self.stream = stream558559def as_zipfile(self) -> zipfile.ZipFile:560return zipfile.ZipFile(self.stream, allowZip64=True)561562563