[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,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,
)