[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,5 +1,6 @@
# The following comment should be removed at some point in the future.
# mypy: strict-optional=False
from __future__ import annotations
import contextlib
import errno
@ -14,69 +15,70 @@ import stat
import sys
import urllib.parse
from io import StringIO
from itertools import filterfalse, tee, zip_longest
from itertools import filterfalse
from itertools import tee
from itertools import zip_longest
from types import TracebackType
from typing import (
Any,
BinaryIO,
Callable,
ContextManager,
Iterable,
Iterator,
List,
Optional,
TextIO,
Tuple,
Type,
TypeVar,
cast,
)
from pip._vendor.tenacity import retry, stop_after_delay, wait_fixed
from typing import Any
from typing import BinaryIO
from typing import Callable
from typing import cast
from typing import ContextManager
from typing import Iterable
from typing import Iterator
from typing import List
from typing import Optional
from typing import TextIO
from typing import Tuple
from typing import Type
from typing import TypeVar
from pip import __version__
from pip._internal.exceptions import CommandError
from pip._internal.locations import get_major_minor_version
from pip._internal.utils.compat import WINDOWS
from pip._internal.utils.virtualenv import running_under_virtualenv
from pip._vendor.tenacity import retry
from pip._vendor.tenacity import stop_after_delay
from pip._vendor.tenacity import wait_fixed
__all__ = [
"rmtree",
"display_path",
"backup_dir",
"ask",
"splitext",
"format_size",
"is_installable_dir",
"normalize_path",
"renames",
"get_prog",
"captured_stdout",
"ensure_dir",
"remove_auth_from_url",
'rmtree',
'display_path',
'backup_dir',
'ask',
'splitext',
'format_size',
'is_installable_dir',
'normalize_path',
'renames',
'get_prog',
'captured_stdout',
'ensure_dir',
'remove_auth_from_url',
]
logger = logging.getLogger(__name__)
T = TypeVar("T")
T = TypeVar('T')
ExcInfo = Tuple[Type[BaseException], BaseException, TracebackType]
VersionInfo = Tuple[int, int, int]
NetlocTuple = Tuple[str, Tuple[Optional[str], Optional[str]]]
def get_pip_version() -> str:
pip_pkg_dir = os.path.join(os.path.dirname(__file__), "..", "..")
pip_pkg_dir = os.path.join(os.path.dirname(__file__), '..', '..')
pip_pkg_dir = os.path.abspath(pip_pkg_dir)
return "pip {} from {} (python {})".format(
return 'pip {} from {} (python {})'.format(
__version__,
pip_pkg_dir,
get_major_minor_version(),
)
def normalize_version_info(py_version_info: Tuple[int, ...]) -> Tuple[int, int, int]:
def normalize_version_info(py_version_info: tuple[int, ...]) -> tuple[int, int, int]:
"""
Convert a tuple of ints representing a Python version to one of length
three.
@ -92,7 +94,7 @@ def normalize_version_info(py_version_info: Tuple[int, ...]) -> Tuple[int, int,
elif len(py_version_info) > 3:
py_version_info = py_version_info[:3]
return cast("VersionInfo", py_version_info)
return cast('VersionInfo', py_version_info)
def ensure_dir(path: str) -> None:
@ -108,13 +110,13 @@ def ensure_dir(path: str) -> None:
def get_prog() -> str:
try:
prog = os.path.basename(sys.argv[0])
if prog in ("__main__.py", "-c"):
return f"{sys.executable} -m pip"
if prog in ('__main__.py', '-c'):
return f'{sys.executable} -m pip'
else:
return prog
except (AttributeError, TypeError, IndexError):
pass
return "pip"
return 'pip'
# Retry every half second for up to 3 seconds
@ -149,11 +151,11 @@ def display_path(path: str) -> str:
if possible."""
path = os.path.normcase(os.path.abspath(path))
if path.startswith(os.getcwd() + os.path.sep):
path = "." + path[len(os.getcwd()) :]
path = '.' + path[len(os.getcwd()):]
return path
def backup_dir(dir: str, ext: str = ".bak") -> str:
def backup_dir(dir: str, ext: str = '.bak') -> str:
"""Figure out the name of a directory to back up the given dir to
(adding .bak, .bak2, etc)"""
n = 1
@ -165,7 +167,7 @@ def backup_dir(dir: str, ext: str = ".bak") -> str:
def ask_path_exists(message: str, options: Iterable[str]) -> str:
for action in os.environ.get("PIP_EXISTS_ACTION", "").split():
for action in os.environ.get('PIP_EXISTS_ACTION', '').split():
if action in options:
return action
return ask(message, options)
@ -173,9 +175,9 @@ def ask_path_exists(message: str, options: Iterable[str]) -> str:
def _check_no_input(message: str) -> None:
"""Raise an error if no input is allowed."""
if os.environ.get("PIP_NO_INPUT"):
if os.environ.get('PIP_NO_INPUT'):
raise Exception(
f"No input was expected ($PIP_NO_INPUT set); question: {message}"
f'No input was expected ($PIP_NO_INPUT set); question: {message}',
)
@ -187,8 +189,8 @@ def ask(message: str, options: Iterable[str]) -> str:
response = response.strip().lower()
if response not in options:
print(
"Your response ({!r}) was not one of the expected responses: "
"{}".format(response, ", ".join(options))
'Your response ({!r}) was not one of the expected responses: '
'{}'.format(response, ', '.join(options)),
)
else:
return response
@ -214,26 +216,26 @@ def strtobool(val: str) -> int:
'val' is anything else.
"""
val = val.lower()
if val in ("y", "yes", "t", "true", "on", "1"):
if val in ('y', 'yes', 't', 'true', 'on', '1'):
return 1
elif val in ("n", "no", "f", "false", "off", "0"):
elif val in ('n', 'no', 'f', 'false', 'off', '0'):
return 0
else:
raise ValueError(f"invalid truth value {val!r}")
raise ValueError(f'invalid truth value {val!r}')
def format_size(bytes: float) -> str:
if bytes > 1000 * 1000:
return "{:.1f} MB".format(bytes / 1000.0 / 1000)
return f'{bytes / 1000.0 / 1000:.1f} MB'
elif bytes > 10 * 1000:
return "{} kB".format(int(bytes / 1000))
return f'{int(bytes / 1000)} kB'
elif bytes > 1000:
return "{:.1f} kB".format(bytes / 1000.0)
return f'{bytes / 1000.0:.1f} kB'
else:
return "{} bytes".format(int(bytes))
return f'{int(bytes)} bytes'
def tabulate(rows: Iterable[Iterable[Any]]) -> Tuple[List[str], List[int]]:
def tabulate(rows: Iterable[Iterable[Any]]) -> tuple[list[str], list[int]]:
"""Return a list of formatted rows and a list of column sizes.
For example::
@ -242,8 +244,8 @@ def tabulate(rows: Iterable[Iterable[Any]]) -> Tuple[List[str], List[int]]:
(['foobar 2000', '3735928559'], [10, 4])
"""
rows = [tuple(map(str, row)) for row in rows]
sizes = [max(map(len, col)) for col in zip_longest(*rows, fillvalue="")]
table = [" ".join(map(str.ljust, row, sizes)).rstrip() for row in rows]
sizes = [max(map(len, col)) for col in zip_longest(*rows, fillvalue='')]
table = [' '.join(map(str.ljust, row, sizes)).rstrip() for row in rows]
return table, sizes
@ -257,9 +259,9 @@ def is_installable_dir(path: str) -> bool:
"""
if not os.path.isdir(path):
return False
if os.path.isfile(os.path.join(path, "pyproject.toml")):
if os.path.isfile(os.path.join(path, 'pyproject.toml')):
return True
if os.path.isfile(os.path.join(path, "setup.py")):
if os.path.isfile(os.path.join(path, 'setup.py')):
return True
return False
@ -286,10 +288,10 @@ def normalize_path(path: str, resolve_symlinks: bool = True) -> str:
return os.path.normcase(path)
def splitext(path: str) -> Tuple[str, str]:
def splitext(path: str) -> tuple[str, str]:
"""Like os.path.splitext, but take off .tar too"""
base, ext = posixpath.splitext(path)
if base.lower().endswith(".tar"):
if base.lower().endswith('.tar'):
ext = base[-4:] + ext
base = base[:-4]
return base, ext
@ -334,7 +336,7 @@ class StreamWrapper(StringIO):
orig_stream: TextIO = None
@classmethod
def from_stream(cls, orig_stream: TextIO) -> "StreamWrapper":
def from_stream(cls, orig_stream: TextIO) -> StreamWrapper:
cls.orig_stream = orig_stream
return cls()
@ -369,47 +371,47 @@ def captured_stdout() -> ContextManager[StreamWrapper]:
Taken from Lib/support/__init__.py in the CPython repo.
"""
return captured_output("stdout")
return captured_output('stdout')
def captured_stderr() -> ContextManager[StreamWrapper]:
"""
See captured_stdout().
"""
return captured_output("stderr")
return captured_output('stderr')
# Simulates an enum
def enum(*sequential: Any, **named: Any) -> Type[Any]:
def enum(*sequential: Any, **named: Any) -> type[Any]:
enums = dict(zip(sequential, range(len(sequential))), **named)
reverse = {value: key for key, value in enums.items()}
enums["reverse_mapping"] = reverse
return type("Enum", (), enums)
enums['reverse_mapping'] = reverse
return type('Enum', (), enums)
def build_netloc(host: str, port: Optional[int]) -> str:
def build_netloc(host: str, port: int | None) -> str:
"""
Build a netloc from a host-port pair
"""
if port is None:
return host
if ":" in host:
if ':' in host:
# Only wrap host with square brackets when it is IPv6
host = f"[{host}]"
return f"{host}:{port}"
host = f'[{host}]'
return f'{host}:{port}'
def build_url_from_netloc(netloc: str, scheme: str = "https") -> str:
def build_url_from_netloc(netloc: str, scheme: str = 'https') -> str:
"""
Build a full URL from a netloc.
"""
if netloc.count(":") >= 2 and "@" not in netloc and "[" not in netloc:
if netloc.count(':') >= 2 and '@' not in netloc and '[' not in netloc:
# It must be a bare IPv6 address, so wrap it with brackets.
netloc = f"[{netloc}]"
return f"{scheme}://{netloc}"
netloc = f'[{netloc}]'
return f'{scheme}://{netloc}'
def parse_netloc(netloc: str) -> Tuple[str, Optional[int]]:
def parse_netloc(netloc: str) -> tuple[str, int | None]:
"""
Return the host-port pair from a netloc.
"""
@ -424,19 +426,19 @@ def split_auth_from_netloc(netloc: str) -> NetlocTuple:
Returns: (netloc, (username, password)).
"""
if "@" not in netloc:
if '@' not in netloc:
return netloc, (None, None)
# Split from the right because that's how urllib.parse.urlsplit()
# behaves if more than one @ is present (which can be checked using
# the password attribute of urlsplit()'s return value).
auth, netloc = netloc.rsplit("@", 1)
pw: Optional[str] = None
if ":" in auth:
auth, netloc = netloc.rsplit('@', 1)
pw: str | None = None
if ':' in auth:
# Split from the left because that's how urllib.parse.urlsplit()
# behaves if more than one : is present (which again can be checked
# using the password attribute of the return value)
user, pw = auth.split(":", 1)
user, pw = auth.split(':', 1)
else:
user, pw = auth, None
@ -459,19 +461,19 @@ def redact_netloc(netloc: str) -> str:
if user is None:
return netloc
if password is None:
user = "****"
password = ""
user = '****'
password = ''
else:
user = urllib.parse.quote(user)
password = ":****"
return "{user}{password}@{netloc}".format(
user=user, password=password, netloc=netloc
password = ':****'
return '{user}{password}@{netloc}'.format(
user=user, password=password, netloc=netloc,
)
def _transform_url(
url: str, transform_netloc: Callable[[str], Tuple[Any, ...]]
) -> Tuple[str, NetlocTuple]:
url: str, transform_netloc: Callable[[str], tuple[Any, ...]],
) -> tuple[str, NetlocTuple]:
"""Transform and replace netloc in a url.
transform_netloc is a function taking the netloc and returning a
@ -486,18 +488,18 @@ def _transform_url(
# stripped url
url_pieces = (purl.scheme, netloc_tuple[0], purl.path, purl.query, purl.fragment)
surl = urllib.parse.urlunsplit(url_pieces)
return surl, cast("NetlocTuple", netloc_tuple)
return surl, cast('NetlocTuple', netloc_tuple)
def _get_netloc(netloc: str) -> NetlocTuple:
return split_auth_from_netloc(netloc)
def _redact_netloc(netloc: str) -> Tuple[str]:
def _redact_netloc(netloc: str) -> tuple[str]:
return (redact_netloc(netloc),)
def split_auth_netloc_from_url(url: str) -> Tuple[str, str, Tuple[str, str]]:
def split_auth_netloc_from_url(url: str) -> tuple[str, str, tuple[str, str]]:
"""
Parse a url into separate netloc, auth, and url with no auth.
@ -525,7 +527,7 @@ class HiddenText:
self.redacted = redacted
def __repr__(self) -> str:
return "<HiddenText {!r}>".format(str(self))
return f'<HiddenText {str(self)!r}>'
def __str__(self) -> str:
return self.redacted
@ -541,7 +543,7 @@ class HiddenText:
def hide_value(value: str) -> HiddenText:
return HiddenText(value, redacted="****")
return HiddenText(value, redacted='****')
def hide_url(url: str) -> HiddenText:
@ -556,9 +558,9 @@ def protect_pip_from_modification_on_windows(modifying_pip: bool) -> None:
python -m pip ...
"""
pip_names = [
"pip.exe",
"pip{}.exe".format(sys.version_info[0]),
"pip{}.{}.exe".format(*sys.version_info[:2]),
'pip.exe',
f'pip{sys.version_info[0]}.exe',
'pip{}.{}.exe'.format(*sys.version_info[:2]),
]
# See https://github.com/pypa/pip/issues/1299 for more discussion
@ -567,11 +569,11 @@ def protect_pip_from_modification_on_windows(modifying_pip: bool) -> None:
)
if should_show_use_python_msg:
new_command = [sys.executable, "-m", "pip"] + sys.argv[1:]
new_command = [sys.executable, '-m', 'pip'] + sys.argv[1:]
raise CommandError(
"To modify pip, please run the following command:\n{}".format(
" ".join(new_command)
)
'To modify pip, please run the following command:\n{}'.format(
' '.join(new_command),
),
)
@ -580,12 +582,12 @@ def is_console_interactive() -> bool:
return sys.stdin is not None and sys.stdin.isatty()
def hash_file(path: str, blocksize: int = 1 << 20) -> Tuple[Any, int]:
def hash_file(path: str, blocksize: int = 1 << 20) -> tuple[Any, int]:
"""Return (hash, length) for path using hashlib.sha256()"""
h = hashlib.sha256()
length = 0
with open(path, "rb") as f:
with open(path, 'rb') as f:
for block in read_chunks(f, size=blocksize):
length += len(block)
h.update(block)
@ -604,7 +606,7 @@ def is_wheel_installed() -> bool:
return True
def pairwise(iterable: Iterable[Any]) -> Iterator[Tuple[Any, Any]]:
def pairwise(iterable: Iterable[Any]) -> Iterator[tuple[Any, Any]]:
"""
Return paired elements.
@ -618,7 +620,7 @@ def pairwise(iterable: Iterable[Any]) -> Iterator[Tuple[Any, Any]]:
def partition(
pred: Callable[[T], bool],
iterable: Iterable[T],
) -> Tuple[Iterable[T], Iterable[T]]:
) -> tuple[Iterable[T], Iterable[T]]:
"""
Use a predicate to partition entries into false entries and true entries,
like