[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

@ -10,35 +10,41 @@ Some terminology:
- variant
A single word describing where the configuration key-value pair came from
"""
from __future__ import annotations
import configparser
import locale
import os
import sys
from typing import Any, Dict, Iterable, List, NewType, Optional, Tuple
from typing import Any
from typing import Dict
from typing import Iterable
from typing import List
from typing import NewType
from typing import Optional
from typing import Tuple
from pip._internal.exceptions import (
ConfigurationError,
ConfigurationFileCouldNotBeLoaded,
)
from pip._internal.exceptions import ConfigurationError
from pip._internal.exceptions import ConfigurationFileCouldNotBeLoaded
from pip._internal.utils import appdirs
from pip._internal.utils.compat import WINDOWS
from pip._internal.utils.logging import getLogger
from pip._internal.utils.misc import ensure_dir, enum
from pip._internal.utils.misc import ensure_dir
from pip._internal.utils.misc import enum
RawConfigParser = configparser.RawConfigParser # Shorthand
Kind = NewType("Kind", str)
Kind = NewType('Kind', str)
CONFIG_BASENAME = "pip.ini" if WINDOWS else "pip.conf"
ENV_NAMES_IGNORED = "version", "help"
CONFIG_BASENAME = 'pip.ini' if WINDOWS else 'pip.conf'
ENV_NAMES_IGNORED = 'version', 'help'
# The kinds of configurations there are.
kinds = enum(
USER="user", # User Specific
GLOBAL="global", # System Wide
SITE="site", # [Virtual] Environment Specific
ENV="env", # from PIP_CONFIG_FILE
ENV_VAR="env-var", # from Environment Variables
USER='user', # User Specific
GLOBAL='global', # System Wide
SITE='site', # [Virtual] Environment Specific
ENV='env', # from PIP_CONFIG_FILE
ENV_VAR='env-var', # from Environment Variables
)
OVERRIDE_ORDER = kinds.GLOBAL, kinds.USER, kinds.SITE, kinds.ENV, kinds.ENV_VAR
VALID_LOAD_ONLY = kinds.USER, kinds.GLOBAL, kinds.SITE
@ -49,34 +55,34 @@ logger = getLogger(__name__)
# NOTE: Maybe use the optionx attribute to normalize keynames.
def _normalize_name(name: str) -> str:
"""Make a name consistent regardless of source (environment or file)"""
name = name.lower().replace("_", "-")
if name.startswith("--"):
name = name.lower().replace('_', '-')
if name.startswith('--'):
name = name[2:] # only prefer long opts
return name
def _disassemble_key(name: str) -> List[str]:
if "." not in name:
def _disassemble_key(name: str) -> list[str]:
if '.' not in name:
error_message = (
"Key does not contain dot separated section and key. "
'Key does not contain dot separated section and key. '
"Perhaps you wanted to use 'global.{}' instead?"
).format(name)
raise ConfigurationError(error_message)
return name.split(".", 1)
return name.split('.', 1)
def get_configuration_files() -> Dict[Kind, List[str]]:
def get_configuration_files() -> dict[Kind, list[str]]:
global_config_files = [
os.path.join(path, CONFIG_BASENAME) for path in appdirs.site_config_dirs("pip")
os.path.join(path, CONFIG_BASENAME) for path in appdirs.site_config_dirs('pip')
]
site_config_file = os.path.join(sys.prefix, CONFIG_BASENAME)
legacy_config_file = os.path.join(
os.path.expanduser("~"),
"pip" if WINDOWS else ".pip",
os.path.expanduser('~'),
'pip' if WINDOWS else '.pip',
CONFIG_BASENAME,
)
new_config_file = os.path.join(appdirs.user_config_dir("pip"), CONFIG_BASENAME)
new_config_file = os.path.join(appdirs.user_config_dir('pip'), CONFIG_BASENAME)
return {
kinds.GLOBAL: global_config_files,
kinds.SITE: [site_config_file],
@ -98,26 +104,26 @@ class Configuration:
and the data stored is also nice.
"""
def __init__(self, isolated: bool, load_only: Optional[Kind] = None) -> None:
def __init__(self, isolated: bool, load_only: Kind | None = None) -> None:
super().__init__()
if load_only is not None and load_only not in VALID_LOAD_ONLY:
raise ConfigurationError(
"Got invalid value for load_only - should be one of {}".format(
", ".join(map(repr, VALID_LOAD_ONLY))
)
'Got invalid value for load_only - should be one of {}'.format(
', '.join(map(repr, VALID_LOAD_ONLY)),
),
)
self.isolated = isolated
self.load_only = load_only
# Because we keep track of where we got the data from
self._parsers: Dict[Kind, List[Tuple[str, RawConfigParser]]] = {
self._parsers: dict[Kind, list[tuple[str, RawConfigParser]]] = {
variant: [] for variant in OVERRIDE_ORDER
}
self._config: Dict[Kind, Dict[str, Any]] = {
self._config: dict[Kind, dict[str, Any]] = {
variant: {} for variant in OVERRIDE_ORDER
}
self._modified_parsers: List[Tuple[str, RawConfigParser]] = []
self._modified_parsers: list[tuple[str, RawConfigParser]] = []
def load(self) -> None:
"""Loads configuration from configuration files and environment"""
@ -125,16 +131,16 @@ class Configuration:
if not self.isolated:
self._load_environment_vars()
def get_file_to_edit(self) -> Optional[str]:
def get_file_to_edit(self) -> str | None:
"""Returns the file with highest priority in configuration"""
assert self.load_only is not None, "Need to be specified a file to be editing"
assert self.load_only is not None, 'Need to be specified a file to be editing'
try:
return self._get_parser_to_modify()[0]
except IndexError:
return None
def items(self) -> Iterable[Tuple[str, Any]]:
def items(self) -> Iterable[tuple[str, Any]]:
"""Returns key-value pairs like dict.items() representing the loaded
configuration
"""
@ -145,7 +151,7 @@ class Configuration:
try:
return self._dictionary[key]
except KeyError:
raise ConfigurationError(f"No such key - {key}")
raise ConfigurationError(f'No such key - {key}')
def set_value(self, key: str, value: Any) -> None:
"""Modify a value in the configuration."""
@ -171,7 +177,7 @@ class Configuration:
assert self.load_only
if key not in self._config[self.load_only]:
raise ConfigurationError(f"No such key - {key}")
raise ConfigurationError(f'No such key - {key}')
fname, parser = self._get_parser_to_modify()
@ -182,7 +188,7 @@ class Configuration:
):
# The option was not removed.
raise ConfigurationError(
"Fatal Internal error [id=1]. Please report as a bug."
'Fatal Internal error [id=1]. Please report as a bug.',
)
# The section may be empty after the option was removed.
@ -197,12 +203,12 @@ class Configuration:
self._ensure_have_load_only()
for fname, parser in self._modified_parsers:
logger.info("Writing to %s", fname)
logger.info('Writing to %s', fname)
# Ensure directory exists.
ensure_dir(os.path.dirname(fname))
with open(fname, "w") as f:
with open(fname, 'w') as f:
parser.write(f)
#
@ -211,11 +217,11 @@ class Configuration:
def _ensure_have_load_only(self) -> None:
if self.load_only is None:
raise ConfigurationError("Needed a specific file to be modifying.")
logger.debug("Will be working with %s variant only", self.load_only)
raise ConfigurationError('Needed a specific file to be modifying.')
logger.debug('Will be working with %s variant only', self.load_only)
@property
def _dictionary(self) -> Dict[str, Any]:
def _dictionary(self) -> dict[str, Any]:
"""A dictionary representing the loaded configuration."""
# NOTE: Dictionaries are not populated if not loaded. So, conditionals
# are not needed here.
@ -231,8 +237,8 @@ class Configuration:
config_files = dict(self.iter_config_files())
if config_files[kinds.ENV][0:1] == [os.devnull]:
logger.debug(
"Skipping loading configuration files due to "
"environment's PIP_CONFIG_FILE being os.devnull"
'Skipping loading configuration files due to '
"environment's PIP_CONFIG_FILE being os.devnull",
)
return
@ -272,7 +278,7 @@ class Configuration:
except UnicodeDecodeError:
# See https://github.com/pypa/pip/issues/4963
raise ConfigurationFileCouldNotBeLoaded(
reason=f"contains invalid {locale_encoding} characters",
reason=f'contains invalid {locale_encoding} characters',
fname=fname,
)
except configparser.Error as error:
@ -283,12 +289,12 @@ class Configuration:
def _load_environment_vars(self) -> None:
"""Loads configuration from environment variables"""
self._config[kinds.ENV_VAR].update(
self._normalized_keys(":env:", self.get_environ_vars())
self._normalized_keys(':env:', self.get_environ_vars()),
)
def _normalized_keys(
self, section: str, items: Iterable[Tuple[str, Any]]
) -> Dict[str, Any]:
self, section: str, items: Iterable[tuple[str, Any]],
) -> dict[str, Any]:
"""Normalizes items to construct a dictionary with normalized keys.
This routine is where the names become keys and are made the same
@ -296,20 +302,20 @@ class Configuration:
"""
normalized = {}
for name, val in items:
key = section + "." + _normalize_name(name)
key = section + '.' + _normalize_name(name)
normalized[key] = val
return normalized
def get_environ_vars(self) -> Iterable[Tuple[str, str]]:
def get_environ_vars(self) -> Iterable[tuple[str, str]]:
"""Returns a generator with all environmental vars with prefix PIP_"""
for key, val in os.environ.items():
if key.startswith("PIP_"):
if key.startswith('PIP_'):
name = key[4:].lower()
if name not in ENV_NAMES_IGNORED:
yield name, val
# XXX: This is patched in the tests.
def iter_config_files(self) -> Iterable[Tuple[Kind, List[str]]]:
def iter_config_files(self) -> Iterable[tuple[Kind, list[str]]]:
"""Yields variant and configuration files associated with it.
This should be treated like items of a dictionary.
@ -317,7 +323,7 @@ class Configuration:
# SMELL: Move the conditions out of this function
# environment variables have the lowest priority
config_file = os.environ.get("PIP_CONFIG_FILE", None)
config_file = os.environ.get('PIP_CONFIG_FILE', None)
if config_file is not None:
yield kinds.ENV, [config_file]
else:
@ -339,18 +345,18 @@ class Configuration:
# finally virtualenv configuration first trumping others
yield kinds.SITE, config_files[kinds.SITE]
def get_values_in_config(self, variant: Kind) -> Dict[str, Any]:
def get_values_in_config(self, variant: Kind) -> dict[str, Any]:
"""Get values present in a config file"""
return self._config[variant]
def _get_parser_to_modify(self) -> Tuple[str, RawConfigParser]:
def _get_parser_to_modify(self) -> tuple[str, RawConfigParser]:
# Determine which parser to modify
assert self.load_only
parsers = self._parsers[self.load_only]
if not parsers:
# This should not happen if everything works correctly.
raise ConfigurationError(
"Fatal Internal error [id=2]. Please report as a bug."
'Fatal Internal error [id=2]. Please report as a bug.',
)
# Use the highest priority parser.
@ -363,4 +369,4 @@ class Configuration:
self._modified_parsers.append(file_parser_tuple)
def __repr__(self) -> str:
return f"{self.__class__.__name__}({self._dictionary!r})"
return f'{self.__class__.__name__}({self._dictionary!r})'