[pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci
This commit is contained in:
pre-commit-ci[bot] 2024-04-13 00:00:18 +00:00
parent 72ad6dc953
commit f4cd1ba0d6
813 changed files with 66015 additions and 58839 deletions

View file

@ -1,16 +1,23 @@
from typing import List, Optional
from __future__ import annotations
from .base import BaseDistribution, BaseEnvironment, FilesystemWheel, MemoryWheel, Wheel
from typing import List
from typing import Optional
from .base import BaseDistribution
from .base import BaseEnvironment
from .base import FilesystemWheel
from .base import MemoryWheel
from .base import Wheel
__all__ = [
"BaseDistribution",
"BaseEnvironment",
"FilesystemWheel",
"MemoryWheel",
"Wheel",
"get_default_environment",
"get_environment",
"get_wheel_distribution",
'BaseDistribution',
'BaseEnvironment',
'FilesystemWheel',
'MemoryWheel',
'Wheel',
'get_default_environment',
'get_environment',
'get_wheel_distribution',
]
@ -26,7 +33,7 @@ def get_default_environment() -> BaseEnvironment:
return Environment.default()
def get_environment(paths: Optional[List[str]]) -> BaseEnvironment:
def get_environment(paths: list[str] | None) -> BaseEnvironment:
"""Get a representation of the environment specified by ``paths``.
This returns an Environment instance from the chosen backend based on the

View file

@ -1,3 +1,5 @@
from __future__ import annotations
import csv
import email.message
import json
@ -5,38 +7,35 @@ import logging
import pathlib
import re
import zipfile
from typing import (
IO,
TYPE_CHECKING,
Collection,
Container,
Iterable,
Iterator,
List,
Optional,
Tuple,
Union,
)
from pip._vendor.packaging.requirements import Requirement
from pip._vendor.packaging.specifiers import InvalidSpecifier, SpecifierSet
from pip._vendor.packaging.utils import NormalizedName
from pip._vendor.packaging.version import LegacyVersion, Version
from typing import Collection
from typing import Container
from typing import IO
from typing import Iterable
from typing import Iterator
from typing import List
from typing import Optional
from typing import Tuple
from typing import TYPE_CHECKING
from typing import Union
from pip._internal.exceptions import NoneMetadataError
from pip._internal.locations import site_packages, user_site
from pip._internal.models.direct_url import (
DIRECT_URL_METADATA_NAME,
DirectUrl,
DirectUrlValidationError,
)
from pip._internal.locations import site_packages
from pip._internal.locations import user_site
from pip._internal.models.direct_url import DIRECT_URL_METADATA_NAME
from pip._internal.models.direct_url import DirectUrl
from pip._internal.models.direct_url import DirectUrlValidationError
from pip._internal.utils.compat import stdlib_pkgs # TODO: Move definition here.
from pip._internal.utils.egg_link import (
egg_link_path_from_location,
egg_link_path_from_sys_path,
)
from pip._internal.utils.misc import is_local, normalize_path
from pip._internal.utils.egg_link import egg_link_path_from_location
from pip._internal.utils.egg_link import egg_link_path_from_sys_path
from pip._internal.utils.misc import is_local
from pip._internal.utils.misc import normalize_path
from pip._internal.utils.urls import url_to_path
from pip._vendor.packaging.requirements import Requirement
from pip._vendor.packaging.specifiers import InvalidSpecifier
from pip._vendor.packaging.specifiers import SpecifierSet
from pip._vendor.packaging.utils import NormalizedName
from pip._vendor.packaging.version import LegacyVersion
from pip._vendor.packaging.version import Version
if TYPE_CHECKING:
from typing import Protocol
@ -65,8 +64,8 @@ class BaseEntryPoint(Protocol):
def _convert_installed_files_path(
entry: Tuple[str, ...],
info: Tuple[str, ...],
entry: tuple[str, ...],
info: tuple[str, ...],
) -> str:
"""Convert a legacy installed-files.txt path into modern RECORD path.
@ -85,9 +84,9 @@ def _convert_installed_files_path(
from ``info``; if ``info`` is empty, start appending ``..`` instead.
2. Join the two directly.
"""
while entry and entry[0] == "..":
if not info or info[-1] == "..":
info += ("..",)
while entry and entry[0] == '..':
if not info or info[-1] == '..':
info += ('..',)
else:
info = info[:-1]
entry = entry[1:]
@ -96,13 +95,13 @@ def _convert_installed_files_path(
class BaseDistribution(Protocol):
def __repr__(self) -> str:
return f"{self.raw_name} {self.version} ({self.location})"
return f'{self.raw_name} {self.version} ({self.location})'
def __str__(self) -> str:
return f"{self.raw_name} {self.version}"
return f'{self.raw_name} {self.version}'
@property
def location(self) -> Optional[str]:
def location(self) -> str | None:
"""Where the distribution is loaded from.
A string value is not necessarily a filesystem path, since distributions
@ -116,7 +115,7 @@ class BaseDistribution(Protocol):
raise NotImplementedError()
@property
def editable_project_location(self) -> Optional[str]:
def editable_project_location(self) -> str | None:
"""The project location for editable distributions.
This is the directory where pyproject.toml or setup.py is located.
@ -138,7 +137,7 @@ class BaseDistribution(Protocol):
return None
@property
def installed_location(self) -> Optional[str]:
def installed_location(self) -> str | None:
"""The distribution's "installed" location.
This should generally be a ``site-packages`` directory. This is
@ -158,7 +157,7 @@ class BaseDistribution(Protocol):
return normalize_path(location)
@property
def info_location(self) -> Optional[str]:
def info_location(self) -> str | None:
"""Location of the .[egg|dist]-info directory or file.
Similarly to ``location``, a string value is not necessarily a
@ -196,7 +195,7 @@ class BaseDistribution(Protocol):
location = self.location
if not location:
return False
return location.endswith(".egg")
return location.endswith('.egg')
@property
def installed_with_setuptools_egg_info(self) -> bool:
@ -212,7 +211,7 @@ class BaseDistribution(Protocol):
info_location = self.info_location
if not info_location:
return False
if not info_location.endswith(".egg-info"):
if not info_location.endswith('.egg-info'):
return False
return pathlib.Path(info_location).is_dir()
@ -228,7 +227,7 @@ class BaseDistribution(Protocol):
info_location = self.info_location
if not info_location:
return False
if not info_location.endswith(".dist-info"):
if not info_location.endswith('.dist-info'):
return False
return pathlib.Path(info_location).is_dir()
@ -246,10 +245,10 @@ class BaseDistribution(Protocol):
This is a copy of ``pkg_resources.to_filename()`` for compatibility.
"""
return self.raw_name.replace("-", "_")
return self.raw_name.replace('-', '_')
@property
def direct_url(self) -> Optional[DirectUrl]:
def direct_url(self) -> DirectUrl | None:
"""Obtain a DirectUrl from this distribution.
Returns None if the distribution has no `direct_url.json` metadata,
@ -267,7 +266,7 @@ class BaseDistribution(Protocol):
DirectUrlValidationError,
) as e:
logger.warning(
"Error parsing %s for %s: %s",
'Error parsing %s for %s: %s',
DIRECT_URL_METADATA_NAME,
self.canonical_name,
e,
@ -277,14 +276,14 @@ class BaseDistribution(Protocol):
@property
def installer(self) -> str:
try:
installer_text = self.read_text("INSTALLER")
installer_text = self.read_text('INSTALLER')
except (OSError, ValueError, NoneMetadataError):
return "" # Fail silently if the installer file cannot be read.
return '' # Fail silently if the installer file cannot be read.
for line in installer_text.splitlines():
cleaned_line = line.strip()
if cleaned_line:
return cleaned_line
return ""
return ''
@property
def editable(self) -> bool:
@ -350,16 +349,16 @@ class BaseDistribution(Protocol):
raise NotImplementedError()
@property
def metadata_version(self) -> Optional[str]:
def metadata_version(self) -> str | None:
"""Value of "Metadata-Version:" in distribution metadata, if available."""
return self.metadata.get("Metadata-Version")
return self.metadata.get('Metadata-Version')
@property
def raw_name(self) -> str:
"""Value of "Name:" in distribution metadata."""
# The metadata should NEVER be missing the Name: key, but if it somehow
# does, fall back to the known canonical name.
return self.metadata.get("Name", self.canonical_name)
return self.metadata.get('Name', self.canonical_name)
@property
def requires_python(self) -> SpecifierSet:
@ -368,14 +367,14 @@ class BaseDistribution(Protocol):
If the key does not exist or contains an invalid value, an empty
SpecifierSet should be returned.
"""
value = self.metadata.get("Requires-Python")
value = self.metadata.get('Requires-Python')
if value is None:
return SpecifierSet()
try:
# Convert to str to satisfy the type checker; this can be a Header object.
spec = SpecifierSet(str(value))
except InvalidSpecifier as e:
message = "Package %r has an invalid Requires-Python: %s"
message = 'Package %r has an invalid Requires-Python: %s'
logger.warning(message, self.raw_name, e)
return SpecifierSet()
return spec
@ -396,17 +395,17 @@ class BaseDistribution(Protocol):
"""
raise NotImplementedError()
def _iter_declared_entries_from_record(self) -> Optional[Iterator[str]]:
def _iter_declared_entries_from_record(self) -> Iterator[str] | None:
try:
text = self.read_text("RECORD")
text = self.read_text('RECORD')
except FileNotFoundError:
return None
# This extra Path-str cast normalizes entries.
return (str(pathlib.Path(row[0])) for row in csv.reader(text.splitlines()))
def _iter_declared_entries_from_legacy(self) -> Optional[Iterator[str]]:
def _iter_declared_entries_from_legacy(self) -> Iterator[str] | None:
try:
text = self.read_text("installed-files.txt")
text = self.read_text('installed-files.txt')
except FileNotFoundError:
return None
paths = (p for p in text.splitlines(keepends=False) if p)
@ -425,7 +424,7 @@ class BaseDistribution(Protocol):
for p in paths
)
def iter_declared_entries(self) -> Optional[Iterator[str]]:
def iter_declared_entries(self) -> Iterator[str] | None:
"""Iterate through file entires declared in this distribution.
For modern .dist-info distributions, this is the files listed in the
@ -437,8 +436,8 @@ class BaseDistribution(Protocol):
contains neither ``RECORD`` nor ``installed-files.txt``.
"""
return (
self._iter_declared_entries_from_record()
or self._iter_declared_entries_from_legacy()
self._iter_declared_entries_from_record() or
self._iter_declared_entries_from_legacy()
)
@ -446,14 +445,14 @@ class BaseEnvironment:
"""An environment containing distributions to introspect."""
@classmethod
def default(cls) -> "BaseEnvironment":
def default(cls) -> BaseEnvironment:
raise NotImplementedError()
@classmethod
def from_paths(cls, paths: Optional[List[str]]) -> "BaseEnvironment":
def from_paths(cls, paths: list[str] | None) -> BaseEnvironment:
raise NotImplementedError()
def get_distribution(self, name: str) -> Optional["BaseDistribution"]:
def get_distribution(self, name: str) -> BaseDistribution | None:
"""Given a requirement name, return the installed distributions.
The name may not be normalized. The implementation must canonicalize
@ -461,7 +460,7 @@ class BaseEnvironment:
"""
raise NotImplementedError()
def _iter_distributions(self) -> Iterator["BaseDistribution"]:
def _iter_distributions(self) -> Iterator[BaseDistribution]:
"""Iterate through installed distributions.
This function should be implemented by subclass, but never called
@ -470,7 +469,7 @@ class BaseEnvironment:
"""
raise NotImplementedError()
def iter_distributions(self) -> Iterator["BaseDistribution"]:
def iter_distributions(self) -> Iterator[BaseDistribution]:
"""Iterate through installed distributions."""
for dist in self._iter_distributions():
# Make sure the distribution actually comes from a valid Python
@ -478,13 +477,13 @@ class BaseEnvironment:
# e.g. ``~atplotlib.dist-info`` if cleanup was interrupted. The
# valid project name pattern is taken from PEP 508.
project_name_valid = re.match(
r"^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$",
r'^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$',
dist.canonical_name,
flags=re.IGNORECASE,
)
if not project_name_valid:
logger.warning(
"Ignoring invalid distribution %s (%s)",
'Ignoring invalid distribution %s (%s)',
dist.canonical_name,
dist.location,
)

View file

@ -1,28 +1,37 @@
from __future__ import annotations
import email.message
import email.parser
import logging
import os
import pathlib
import zipfile
from typing import Collection, Iterable, Iterator, List, Mapping, NamedTuple, Optional
from typing import Collection
from typing import Iterable
from typing import Iterator
from typing import List
from typing import Mapping
from typing import NamedTuple
from typing import Optional
from pip._internal.exceptions import InvalidWheel
from pip._internal.exceptions import NoneMetadataError
from pip._internal.exceptions import UnsupportedWheel
from pip._internal.utils.misc import display_path
from pip._internal.utils.wheel import parse_wheel
from pip._internal.utils.wheel import read_wheel_metadata_file
from pip._vendor import pkg_resources
from pip._vendor.packaging.requirements import Requirement
from pip._vendor.packaging.utils import NormalizedName, canonicalize_name
from pip._vendor.packaging.utils import canonicalize_name
from pip._vendor.packaging.utils import NormalizedName
from pip._vendor.packaging.version import parse as parse_version
from pip._internal.exceptions import InvalidWheel, NoneMetadataError, UnsupportedWheel
from pip._internal.utils.misc import display_path
from pip._internal.utils.wheel import parse_wheel, read_wheel_metadata_file
from .base import (
BaseDistribution,
BaseEntryPoint,
BaseEnvironment,
DistributionVersion,
InfoPath,
Wheel,
)
from .base import BaseDistribution
from .base import BaseEntryPoint
from .base import BaseEnvironment
from .base import DistributionVersion
from .base import InfoPath
from .base import Wheel
logger = logging.getLogger(__name__)
@ -52,7 +61,7 @@ class WheelMetadata:
except UnicodeDecodeError as e:
# Augment the default error with the origin of the file.
raise UnsupportedWheel(
f"Error decoding metadata for {self._wheel_name}: {e} in {name} file"
f'Error decoding metadata for {self._wheel_name}: {e} in {name} file',
)
def get_metadata_lines(self, name: str) -> Iterable[str]:
@ -61,7 +70,7 @@ class WheelMetadata:
def metadata_isdir(self, name: str) -> bool:
return False
def metadata_listdir(self, name: str) -> List[str]:
def metadata_listdir(self, name: str) -> list[str]:
return []
def run_script(self, script_name: str, namespace: str) -> None:
@ -73,7 +82,7 @@ class Distribution(BaseDistribution):
self._dist = dist
@classmethod
def from_directory(cls, directory: str) -> "Distribution":
def from_directory(cls, directory: str) -> Distribution:
dist_dir = directory.rstrip(os.sep)
# Build a PathMetadata object, from path to metadata. :wink:
@ -81,19 +90,19 @@ class Distribution(BaseDistribution):
metadata = pkg_resources.PathMetadata(base_dir, dist_dir)
# Determine the correct Distribution object type.
if dist_dir.endswith(".egg-info"):
if dist_dir.endswith('.egg-info'):
dist_cls = pkg_resources.Distribution
dist_name = os.path.splitext(dist_dir_name)[0]
else:
assert dist_dir.endswith(".dist-info")
assert dist_dir.endswith('.dist-info')
dist_cls = pkg_resources.DistInfoDistribution
dist_name = os.path.splitext(dist_dir_name)[0].split("-")[0]
dist_name = os.path.splitext(dist_dir_name)[0].split('-')[0]
dist = dist_cls(base_dir, project_name=dist_name, metadata=metadata)
return cls(dist)
@classmethod
def from_wheel(cls, wheel: Wheel, name: str) -> "Distribution":
def from_wheel(cls, wheel: Wheel, name: str) -> Distribution:
"""Load the distribution from a given wheel.
:raises InvalidWheel: Whenever loading of the wheel causes a
@ -105,14 +114,14 @@ class Distribution(BaseDistribution):
with wheel.as_zipfile() as zf:
info_dir, _ = parse_wheel(zf, name)
metadata_text = {
path.split("/", 1)[-1]: read_wheel_metadata_file(zf, path)
path.split('/', 1)[-1]: read_wheel_metadata_file(zf, path)
for path in zf.namelist()
if path.startswith(f"{info_dir}/")
if path.startswith(f'{info_dir}/')
}
except zipfile.BadZipFile as e:
raise InvalidWheel(wheel.location, name) from e
except UnsupportedWheel as e:
raise UnsupportedWheel(f"{name} has an invalid wheel, {e}")
raise UnsupportedWheel(f'{name} has an invalid wheel, {e}')
dist = pkg_resources.DistInfoDistribution(
location=wheel.location,
metadata=WheelMetadata(metadata_text, wheel.location),
@ -121,11 +130,11 @@ class Distribution(BaseDistribution):
return cls(dist)
@property
def location(self) -> Optional[str]:
def location(self) -> str | None:
return self._dist.location
@property
def info_location(self) -> Optional[str]:
def info_location(self) -> str | None:
return self._dist.egg_info
@property
@ -170,7 +179,7 @@ class Distribution(BaseDistribution):
def iter_entry_points(self) -> Iterable[BaseEntryPoint]:
for group, entries in self._dist.get_entry_map().items():
for name, entry_point in entries.items():
name, _, value = str(entry_point).partition("=")
name, _, value = str(entry_point).partition('=')
yield EntryPoint(name=name.strip(), value=value.strip(), group=group)
@property
@ -180,9 +189,9 @@ class Distribution(BaseDistribution):
True but `get_metadata()` returns None.
"""
if isinstance(self._dist, pkg_resources.DistInfoDistribution):
metadata_name = "METADATA"
metadata_name = 'METADATA'
else:
metadata_name = "PKG-INFO"
metadata_name = 'PKG-INFO'
try:
metadata = self.read_text(metadata_name)
except FileNotFoundError:
@ -190,8 +199,8 @@ class Distribution(BaseDistribution):
displaying_path = display_path(self.location)
else:
displaying_path = repr(self.location)
logger.warning("No metadata found in %s", displaying_path)
metadata = ""
logger.warning('No metadata found in %s', displaying_path)
metadata = ''
feed_parser = email.parser.FeedParser()
feed_parser.feed(metadata)
return feed_parser.close()
@ -214,10 +223,10 @@ class Environment(BaseEnvironment):
return cls(pkg_resources.working_set)
@classmethod
def from_paths(cls, paths: Optional[List[str]]) -> BaseEnvironment:
def from_paths(cls, paths: list[str] | None) -> BaseEnvironment:
return cls(pkg_resources.WorkingSet(paths))
def _search_distribution(self, name: str) -> Optional[BaseDistribution]:
def _search_distribution(self, name: str) -> BaseDistribution | None:
"""Find a distribution matching the ``name`` in the environment.
This searches from *all* distributions available in the environment, to
@ -229,7 +238,7 @@ class Environment(BaseEnvironment):
return dist
return None
def get_distribution(self, name: str) -> Optional[BaseDistribution]:
def get_distribution(self, name: str) -> BaseDistribution | None:
# Search the distribution by looking through the working set.
dist = self._search_distribution(name)
if dist: