[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,4 +1,5 @@
"""Base option parser setup"""
from __future__ import annotations
import logging
import optparse
@ -6,11 +7,17 @@ import shutil
import sys
import textwrap
from contextlib import suppress
from typing import Any, Dict, Iterator, List, Tuple
from typing import Any
from typing import Dict
from typing import Iterator
from typing import List
from typing import Tuple
from pip._internal.cli.status_codes import UNKNOWN_ERROR
from pip._internal.configuration import Configuration, ConfigurationError
from pip._internal.utils.misc import redact_auth_from_url, strtobool
from pip._internal.configuration import Configuration
from pip._internal.configuration import ConfigurationError
from pip._internal.utils.misc import redact_auth_from_url
from pip._internal.utils.misc import strtobool
logger = logging.getLogger(__name__)
@ -20,16 +27,16 @@ class PrettyHelpFormatter(optparse.IndentedHelpFormatter):
def __init__(self, *args: Any, **kwargs: Any) -> None:
# help position must be aligned with __init__.parseopts.description
kwargs["max_help_position"] = 30
kwargs["indent_increment"] = 1
kwargs["width"] = shutil.get_terminal_size()[0] - 2
kwargs['max_help_position'] = 30
kwargs['indent_increment'] = 1
kwargs['width'] = shutil.get_terminal_size()[0] - 2
super().__init__(*args, **kwargs)
def format_option_strings(self, option: optparse.Option) -> str:
return self._format_option_strings(option)
def _format_option_strings(
self, option: optparse.Option, mvarfmt: str = " <{}>", optsep: str = ", "
self, option: optparse.Option, mvarfmt: str = ' <{}>', optsep: str = ', ',
) -> str:
"""
Return a comma-separated list of option strings and metavars.
@ -52,49 +59,49 @@ class PrettyHelpFormatter(optparse.IndentedHelpFormatter):
metavar = option.metavar or option.dest.lower()
opts.append(mvarfmt.format(metavar.lower()))
return "".join(opts)
return ''.join(opts)
def format_heading(self, heading: str) -> str:
if heading == "Options":
return ""
return heading + ":\n"
if heading == 'Options':
return ''
return heading + ':\n'
def format_usage(self, usage: str) -> str:
"""
Ensure there is only one newline between usage and the first heading
if there is no description.
"""
msg = "\nUsage: {}\n".format(self.indent_lines(textwrap.dedent(usage), " "))
msg = '\nUsage: {}\n'.format(self.indent_lines(textwrap.dedent(usage), ' '))
return msg
def format_description(self, description: str) -> str:
# leave full control over description to us
if description:
if hasattr(self.parser, "main"):
label = "Commands"
if hasattr(self.parser, 'main'):
label = 'Commands'
else:
label = "Description"
label = 'Description'
# some doc strings have initial newlines, some don't
description = description.lstrip("\n")
description = description.lstrip('\n')
# some doc strings have final newlines and spaces, some don't
description = description.rstrip()
# dedent, then reindent
description = self.indent_lines(textwrap.dedent(description), " ")
description = f"{label}:\n{description}\n"
description = self.indent_lines(textwrap.dedent(description), ' ')
description = f'{label}:\n{description}\n'
return description
else:
return ""
return ''
def format_epilog(self, epilog: str) -> str:
# leave full control over epilog to us
if epilog:
return epilog
else:
return ""
return ''
def indent_lines(self, text: str, indent: str) -> str:
new_lines = [indent + line for line in text.split("\n")]
return "\n".join(new_lines)
new_lines = [indent + line for line in text.split('\n')]
return '\n'.join(new_lines)
class UpdatingDefaultsHelpFormatter(PrettyHelpFormatter):
@ -115,7 +122,7 @@ class UpdatingDefaultsHelpFormatter(PrettyHelpFormatter):
default_values = self.parser.defaults.get(option.dest)
help_text = super().expand_default(option)
if default_values and option.metavar == "URL":
if default_values and option.metavar == 'URL':
if isinstance(default_values, str):
default_values = [default_values]
@ -131,7 +138,7 @@ class UpdatingDefaultsHelpFormatter(PrettyHelpFormatter):
class CustomOptionParser(optparse.OptionParser):
def insert_option_group(
self, idx: int, *args: Any, **kwargs: Any
self, idx: int, *args: Any, **kwargs: Any,
) -> optparse.OptionGroup:
"""Insert an OptionGroup at a given position."""
group = self.add_option_group(*args, **kwargs)
@ -142,7 +149,7 @@ class CustomOptionParser(optparse.OptionParser):
return group
@property
def option_list_all(self) -> List[optparse.Option]:
def option_list_all(self) -> list[optparse.Option]:
"""Get a list of all options, including those in option groups."""
res = self.option_list[:]
for i in self.option_groups:
@ -172,15 +179,15 @@ class ConfigOptionParser(CustomOptionParser):
try:
return option.check_value(key, val)
except optparse.OptionValueError as exc:
print(f"An error occurred during configuration: {exc}")
print(f'An error occurred during configuration: {exc}')
sys.exit(3)
def _get_ordered_configuration_items(self) -> Iterator[Tuple[str, Any]]:
def _get_ordered_configuration_items(self) -> Iterator[tuple[str, Any]]:
# Configuration gives keys in an unordered manner. Order them.
override_order = ["global", self.name, ":env:"]
override_order = ['global', self.name, ':env:']
# Pool the options into different groups
section_items: Dict[str, List[Tuple[str, Any]]] = {
section_items: dict[str, list[tuple[str, Any]]] = {
name: [] for name in override_order
}
for section_key, val in self.config.items():
@ -192,7 +199,7 @@ class ConfigOptionParser(CustomOptionParser):
)
continue
section, key = section_key.split(".", 1)
section, key = section_key.split('.', 1)
if section in override_order:
section_items[section].append((key, val))
@ -201,7 +208,7 @@ class ConfigOptionParser(CustomOptionParser):
for key, val in section_items[section]:
yield key, val
def _update_defaults(self, defaults: Dict[str, Any]) -> Dict[str, Any]:
def _update_defaults(self, defaults: dict[str, Any]) -> dict[str, Any]:
"""Updates the given defaults with values from the config files and
the environ. Does a little special handling for certain types of
options (lists)."""
@ -212,7 +219,7 @@ class ConfigOptionParser(CustomOptionParser):
# Then set the options with those values
for key, val in self._get_ordered_configuration_items():
# '--' because configuration supports only long names
option = self.get_option("--" + key)
option = self.get_option('--' + key)
# Ignore options not present in this parser. E.g. non-globals put
# in [global] by users that want them to apply to all applicable
@ -222,31 +229,31 @@ class ConfigOptionParser(CustomOptionParser):
assert option.dest is not None
if option.action in ("store_true", "store_false"):
if option.action in ('store_true', 'store_false'):
try:
val = strtobool(val)
except ValueError:
self.error(
"{} is not a valid value for {} option, " # noqa
"please specify a boolean value like yes/no, "
"true/false or 1/0 instead.".format(val, key)
'{} is not a valid value for {} option, ' # noqa
'please specify a boolean value like yes/no, '
'true/false or 1/0 instead.'.format(val, key),
)
elif option.action == "count":
elif option.action == 'count':
with suppress(ValueError):
val = strtobool(val)
with suppress(ValueError):
val = int(val)
if not isinstance(val, int) or val < 0:
self.error(
"{} is not a valid value for {} option, " # noqa
"please instead specify either a non-negative integer "
"or a boolean value like yes/no or false/true "
"which is equivalent to 1/0.".format(val, key)
'{} is not a valid value for {} option, ' # noqa
'please instead specify either a non-negative integer '
'or a boolean value like yes/no or false/true '
'which is equivalent to 1/0.'.format(val, key),
)
elif option.action == "append":
elif option.action == 'append':
val = val.split()
val = [self.check_default(option, key, v) for v in val]
elif option.action == "callback":
elif option.action == 'callback':
assert option.callback is not None
late_eval.add(option.dest)
opt_str = option.get_opt_string()
@ -289,4 +296,4 @@ class ConfigOptionParser(CustomOptionParser):
def error(self, msg: str) -> None:
self.print_usage(sys.stderr)
self.exit(UNKNOWN_ERROR, f"{msg}\n")
self.exit(UNKNOWN_ERROR, f'{msg}\n')