[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,28 +1,30 @@
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
# For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt
"""Config file for coverage.py"""
from __future__ import annotations
import collections
import configparser
import copy
import os
import os.path
import re
from typing import (
Any, Callable, Iterable, Union,
)
from typing import Any
from typing import Callable
from typing import Iterable
from typing import Union
from coverage.exceptions import ConfigError
from coverage.misc import isolate_module, human_sorted_items, substitute_variables
from coverage.tomlconfig import TomlConfigParser, TomlDecodeError
from coverage.types import (
TConfigurable, TConfigSectionIn, TConfigValueIn, TConfigSectionOut,
TConfigValueOut, TPluginConfig,
)
from coverage.misc import human_sorted_items
from coverage.misc import isolate_module
from coverage.misc import substitute_variables
from coverage.tomlconfig import TomlConfigParser
from coverage.tomlconfig import TomlDecodeError
from coverage.types import TConfigSectionIn
from coverage.types import TConfigSectionOut
from coverage.types import TConfigurable
from coverage.types import TConfigValueIn
from coverage.types import TConfigValueOut
from coverage.types import TPluginConfig
os = isolate_module(os)
@ -39,17 +41,17 @@ class HandyConfigParser(configparser.ConfigParser):
"""
super().__init__(interpolation=None)
self.section_prefixes = ["coverage:"]
self.section_prefixes = ['coverage:']
if our_file:
self.section_prefixes.append("")
self.section_prefixes.append('')
def read( # type: ignore[override]
def read( # type: ignore[override]
self,
filenames: Iterable[str],
encoding_unused: str | None = None,
) -> list[str]:
"""Read a file name as UTF-8 configuration data."""
return super().read(filenames, encoding="utf-8")
return super().read(filenames, encoding='utf-8')
def real_section(self, section: str) -> str | None:
"""Get the actual name of a section."""
@ -73,7 +75,7 @@ class HandyConfigParser(configparser.ConfigParser):
real_section = self.real_section(section)
if real_section is not None:
return super().options(real_section)
raise ConfigError(f"No section: {section!r}")
raise ConfigError(f'No section: {section!r}')
def get_section(self, section: str) -> TConfigSectionOut:
"""Get the contents of a section, as a dictionary."""
@ -82,7 +84,7 @@ class HandyConfigParser(configparser.ConfigParser):
d[opt] = self.get(section, opt)
return d
def get(self, section: str, option: str, *args: Any, **kwargs: Any) -> str: # type: ignore
def get(self, section: str, option: str, *args: Any, **kwargs: Any) -> str: # type: ignore
"""Get a value, replacing environment variables also.
The arguments are the same as `ConfigParser.get`, but in the found
@ -97,7 +99,7 @@ class HandyConfigParser(configparser.ConfigParser):
if super().has_option(real_section, option):
break
else:
raise ConfigError(f"No option {option!r} in section: {section!r}")
raise ConfigError(f'No option {option!r} in section: {section!r}')
v: str = super().get(real_section, option, *args, **kwargs)
v = substitute_variables(v, os.environ)
@ -114,8 +116,8 @@ class HandyConfigParser(configparser.ConfigParser):
"""
value_list = self.get(section, option)
values = []
for value_line in value_list.split("\n"):
for value in value_line.split(","):
for value_line in value_list.split('\n'):
for value in value_line.split(','):
value = value.strip()
if value:
values.append(value)
@ -138,7 +140,7 @@ class HandyConfigParser(configparser.ConfigParser):
re.compile(value)
except re.error as e:
raise ConfigError(
f"Invalid [{section}].{option} value {value!r}: {e}",
f'Invalid [{section}].{option} value {value!r}: {e}',
) from e
if value:
value_list.append(value)
@ -150,20 +152,20 @@ TConfigParser = Union[HandyConfigParser, TomlConfigParser]
# The default line exclusion regexes.
DEFAULT_EXCLUDE = [
r"#\s*(pragma|PRAGMA)[:\s]?\s*(no|NO)\s*(cover|COVER)",
r'#\s*(pragma|PRAGMA)[:\s]?\s*(no|NO)\s*(cover|COVER)',
]
# The default partial branch regexes, to be modified by the user.
DEFAULT_PARTIAL = [
r"#\s*(pragma|PRAGMA)[:\s]?\s*(no|NO)\s*(branch|BRANCH)",
r'#\s*(pragma|PRAGMA)[:\s]?\s*(no|NO)\s*(branch|BRANCH)',
]
# The default partial branch regexes, based on Python semantics.
# These are any Python branching constructs that can't actually execute all
# their branches.
DEFAULT_PARTIAL_ALWAYS = [
"while (True|1|False|0):",
"if (True|1|False|0):",
'while (True|1|False|0):',
'if (True|1|False|0):',
]
@ -197,7 +199,7 @@ class CoverageConfig(TConfigurable, TPluginConfig):
self.concurrency: list[str] = []
self.context: str | None = None
self.cover_pylib = False
self.data_file = ".coverage"
self.data_file = '.coverage'
self.debug: list[str] = []
self.debug_file: str | None = None
self.disable_warnings: list[str] = []
@ -233,23 +235,23 @@ class CoverageConfig(TConfigurable, TPluginConfig):
# Defaults for [html]
self.extra_css: str | None = None
self.html_dir = "htmlcov"
self.html_dir = 'htmlcov'
self.html_skip_covered: bool | None = None
self.html_skip_empty: bool | None = None
self.html_title = "Coverage report"
self.html_title = 'Coverage report'
self.show_contexts = False
# Defaults for [xml]
self.xml_output = "coverage.xml"
self.xml_output = 'coverage.xml'
self.xml_package_depth = 99
# Defaults for [json]
self.json_output = "coverage.json"
self.json_output = 'coverage.json'
self.json_pretty_print = False
self.json_show_contexts = False
# Defaults for [lcov]
self.lcov_output = "coverage.lcov"
self.lcov_output = 'coverage.lcov'
# Defaults for [paths]
self.paths: dict[str, list[str]] = {}
@ -258,9 +260,9 @@ class CoverageConfig(TConfigurable, TPluginConfig):
self.plugin_options: dict[str, TConfigSectionOut] = {}
MUST_BE_LIST = {
"debug", "concurrency", "plugins",
"report_omit", "report_include",
"run_omit", "run_include",
'debug', 'concurrency', 'plugins',
'report_omit', 'report_include',
'run_omit', 'run_include',
}
def from_args(self, **kwargs: TConfigValueIn) -> None:
@ -286,7 +288,7 @@ class CoverageConfig(TConfigurable, TPluginConfig):
"""
_, ext = os.path.splitext(filename)
cp: TConfigParser
if ext == ".toml":
if ext == '.toml':
cp = TomlConfigParser(our_file)
else:
cp = HandyConfigParser(our_file)
@ -314,7 +316,7 @@ class CoverageConfig(TConfigurable, TPluginConfig):
# Check that there are no unrecognized options.
all_options = collections.defaultdict(set)
for option_spec in self.CONFIG_FILE_OPTIONS:
section, option = option_spec[1].split(":")
section, option = option_spec[1].split(':')
all_options[section].add(option)
for section, options in all_options.items():
@ -328,9 +330,9 @@ class CoverageConfig(TConfigurable, TPluginConfig):
)
# [paths] is special
if cp.has_section("paths"):
for option in cp.options("paths"):
self.paths[option] = cp.getlist("paths", option)
if cp.has_section('paths'):
for option in cp.options('paths'):
self.paths[option] = cp.getlist('paths', option)
any_set = True
# plugins can have options
@ -349,7 +351,7 @@ class CoverageConfig(TConfigurable, TPluginConfig):
if used:
self.config_file = os.path.abspath(filename)
with open(filename, "rb") as f:
with open(filename, 'rb') as f:
self._config_contents = f.read()
return used
@ -358,7 +360,7 @@ class CoverageConfig(TConfigurable, TPluginConfig):
"""Return a copy of the configuration."""
return copy.deepcopy(self)
CONCURRENCY_CHOICES = {"thread", "gevent", "greenlet", "eventlet", "multiprocessing"}
CONCURRENCY_CHOICES = {'thread', 'gevent', 'greenlet', 'eventlet', 'multiprocessing'}
CONFIG_FILE_OPTIONS = [
# These are *args for _set_attr_from_config_option:
@ -370,64 +372,64 @@ class CoverageConfig(TConfigurable, TPluginConfig):
# configuration value from the file.
# [run]
("branch", "run:branch", "boolean"),
("command_line", "run:command_line"),
("concurrency", "run:concurrency", "list"),
("context", "run:context"),
("cover_pylib", "run:cover_pylib", "boolean"),
("data_file", "run:data_file"),
("debug", "run:debug", "list"),
("debug_file", "run:debug_file"),
("disable_warnings", "run:disable_warnings", "list"),
("dynamic_context", "run:dynamic_context"),
("parallel", "run:parallel", "boolean"),
("plugins", "run:plugins", "list"),
("relative_files", "run:relative_files", "boolean"),
("run_include", "run:include", "list"),
("run_omit", "run:omit", "list"),
("sigterm", "run:sigterm", "boolean"),
("source", "run:source", "list"),
("source_pkgs", "run:source_pkgs", "list"),
("timid", "run:timid", "boolean"),
("_crash", "run:_crash"),
('branch', 'run:branch', 'boolean'),
('command_line', 'run:command_line'),
('concurrency', 'run:concurrency', 'list'),
('context', 'run:context'),
('cover_pylib', 'run:cover_pylib', 'boolean'),
('data_file', 'run:data_file'),
('debug', 'run:debug', 'list'),
('debug_file', 'run:debug_file'),
('disable_warnings', 'run:disable_warnings', 'list'),
('dynamic_context', 'run:dynamic_context'),
('parallel', 'run:parallel', 'boolean'),
('plugins', 'run:plugins', 'list'),
('relative_files', 'run:relative_files', 'boolean'),
('run_include', 'run:include', 'list'),
('run_omit', 'run:omit', 'list'),
('sigterm', 'run:sigterm', 'boolean'),
('source', 'run:source', 'list'),
('source_pkgs', 'run:source_pkgs', 'list'),
('timid', 'run:timid', 'boolean'),
('_crash', 'run:_crash'),
# [report]
("exclude_list", "report:exclude_lines", "regexlist"),
("exclude_also", "report:exclude_also", "regexlist"),
("fail_under", "report:fail_under", "float"),
("format", "report:format"),
("ignore_errors", "report:ignore_errors", "boolean"),
("include_namespace_packages", "report:include_namespace_packages", "boolean"),
("partial_always_list", "report:partial_branches_always", "regexlist"),
("partial_list", "report:partial_branches", "regexlist"),
("precision", "report:precision", "int"),
("report_contexts", "report:contexts", "list"),
("report_include", "report:include", "list"),
("report_omit", "report:omit", "list"),
("show_missing", "report:show_missing", "boolean"),
("skip_covered", "report:skip_covered", "boolean"),
("skip_empty", "report:skip_empty", "boolean"),
("sort", "report:sort"),
('exclude_list', 'report:exclude_lines', 'regexlist'),
('exclude_also', 'report:exclude_also', 'regexlist'),
('fail_under', 'report:fail_under', 'float'),
('format', 'report:format'),
('ignore_errors', 'report:ignore_errors', 'boolean'),
('include_namespace_packages', 'report:include_namespace_packages', 'boolean'),
('partial_always_list', 'report:partial_branches_always', 'regexlist'),
('partial_list', 'report:partial_branches', 'regexlist'),
('precision', 'report:precision', 'int'),
('report_contexts', 'report:contexts', 'list'),
('report_include', 'report:include', 'list'),
('report_omit', 'report:omit', 'list'),
('show_missing', 'report:show_missing', 'boolean'),
('skip_covered', 'report:skip_covered', 'boolean'),
('skip_empty', 'report:skip_empty', 'boolean'),
('sort', 'report:sort'),
# [html]
("extra_css", "html:extra_css"),
("html_dir", "html:directory"),
("html_skip_covered", "html:skip_covered", "boolean"),
("html_skip_empty", "html:skip_empty", "boolean"),
("html_title", "html:title"),
("show_contexts", "html:show_contexts", "boolean"),
('extra_css', 'html:extra_css'),
('html_dir', 'html:directory'),
('html_skip_covered', 'html:skip_covered', 'boolean'),
('html_skip_empty', 'html:skip_empty', 'boolean'),
('html_title', 'html:title'),
('show_contexts', 'html:show_contexts', 'boolean'),
# [xml]
("xml_output", "xml:output"),
("xml_package_depth", "xml:package_depth", "int"),
('xml_output', 'xml:output'),
('xml_package_depth', 'xml:package_depth', 'int'),
# [json]
("json_output", "json:output"),
("json_pretty_print", "json:pretty_print", "boolean"),
("json_show_contexts", "json:show_contexts", "boolean"),
('json_output', 'json:output'),
('json_pretty_print', 'json:pretty_print', 'boolean'),
('json_show_contexts', 'json:show_contexts', 'boolean'),
# [lcov]
("lcov_output", "lcov:output"),
('lcov_output', 'lcov:output'),
]
def _set_attr_from_config_option(
@ -435,16 +437,16 @@ class CoverageConfig(TConfigurable, TPluginConfig):
cp: TConfigParser,
attr: str,
where: str,
type_: str = "",
type_: str = '',
) -> bool:
"""Set an attribute on self if it exists in the ConfigParser.
Returns True if the attribute was set.
"""
section, option = where.split(":")
section, option = where.split(':')
if cp.has_option(section, option):
method = getattr(cp, "get" + type_)
method = getattr(cp, 'get' + type_)
setattr(self, attr, method(section, option))
return True
return False
@ -464,7 +466,7 @@ class CoverageConfig(TConfigurable, TPluginConfig):
"""
# Special-cased options.
if option_name == "paths":
if option_name == 'paths':
self.paths = value # type: ignore[assignment]
return
@ -476,13 +478,13 @@ class CoverageConfig(TConfigurable, TPluginConfig):
return
# See if it's a plugin option.
plugin_name, _, key = option_name.partition(":")
plugin_name, _, key = option_name.partition(':')
if key and plugin_name in self.plugins:
self.plugin_options.setdefault(plugin_name, {})[key] = value # type: ignore[index]
self.plugin_options.setdefault(plugin_name, {})[key] = value # type: ignore[index]
return
# If we get here, we didn't find the option.
raise ConfigError(f"No such option: {option_name!r}")
raise ConfigError(f'No such option: {option_name!r}')
def get_option(self, option_name: str) -> TConfigValueOut | None:
"""Get an option from the configuration.
@ -495,7 +497,7 @@ class CoverageConfig(TConfigurable, TPluginConfig):
"""
# Special-cased options.
if option_name == "paths":
if option_name == 'paths':
return self.paths # type: ignore[return-value]
# Check all the hard-coded options.
@ -505,12 +507,12 @@ class CoverageConfig(TConfigurable, TPluginConfig):
return getattr(self, attr) # type: ignore[no-any-return]
# See if it's a plugin option.
plugin_name, _, key = option_name.partition(":")
plugin_name, _, key = option_name.partition(':')
if key and plugin_name in self.plugins:
return self.plugin_options.get(plugin_name, {}).get(key)
# If we get here, we didn't find the option.
raise ConfigError(f"No such option: {option_name!r}")
raise ConfigError(f'No such option: {option_name!r}')
def post_process_file(self, path: str) -> str:
"""Make final adjustments to a file path to make it usable."""
@ -530,7 +532,7 @@ class CoverageConfig(TConfigurable, TPluginConfig):
def debug_info(self) -> list[tuple[str, Any]]:
"""Make a list of (name, value) pairs for writing debug info."""
return human_sorted_items(
(k, v) for k, v in self.__dict__.items() if not k.startswith("_")
(k, v) for k, v in self.__dict__.items() if not k.startswith('_')
)
@ -543,24 +545,24 @@ def config_files_to_try(config_file: bool | str) -> list[tuple[str, bool, bool]]
# Some API users were specifying ".coveragerc" to mean the same as
# True, so make it so.
if config_file == ".coveragerc":
if config_file == '.coveragerc':
config_file = True
specified_file = (config_file is not True)
if not specified_file:
# No file was specified. Check COVERAGE_RCFILE.
rcfile = os.getenv("COVERAGE_RCFILE")
rcfile = os.getenv('COVERAGE_RCFILE')
if rcfile:
config_file = rcfile
specified_file = True
if not specified_file:
# Still no file specified. Default to .coveragerc
config_file = ".coveragerc"
config_file = '.coveragerc'
assert isinstance(config_file, str)
files_to_try = [
(config_file, True, specified_file),
("setup.cfg", False, False),
("tox.ini", False, False),
("pyproject.toml", False, False),
('setup.cfg', False, False),
('tox.ini', False, False),
('pyproject.toml', False, False),
]
return files_to_try
@ -601,13 +603,13 @@ def read_coverage_config(
raise ConfigError(f"Couldn't read {fname!r} as a config file")
# 3) from environment variables:
env_data_file = os.getenv("COVERAGE_FILE")
env_data_file = os.getenv('COVERAGE_FILE')
if env_data_file:
config.data_file = env_data_file
# $set_env.py: COVERAGE_DEBUG - Debug options: https://coverage.rtfd.io/cmd.html#debug
debugs = os.getenv("COVERAGE_DEBUG")
debugs = os.getenv('COVERAGE_DEBUG')
if debugs:
config.debug.extend(d.strip() for d in debugs.split(","))
config.debug.extend(d.strip() for d in debugs.split(','))
# 4) from constructor arguments:
config.from_args(**kwargs)