[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,37 +1,37 @@
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
# For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt
"""Miscellaneous stuff for coverage.py."""
from __future__ import annotations
import contextlib
import datetime
import errno
import hashlib
import importlib
import importlib.util
import inspect
import locale
import os
import os.path
import re
import sys
import types
from types import ModuleType
from typing import (
Any, Callable, IO, Iterable, Iterator, Mapping, NoReturn, Sequence, TypeVar,
)
from typing import Any
from typing import Callable
from typing import IO
from typing import Iterable
from typing import Iterator
from typing import Mapping
from typing import NoReturn
from typing import Sequence
from typing import TypeVar
from coverage import env
from coverage.exceptions import * # pylint: disable=wildcard-import
from coverage.exceptions import CoverageException
from coverage.types import TArc
# In 6.0, the exceptions moved from misc.py to exceptions.py. But a number of
# other packages were importing the exceptions from misc, so import them here.
# pylint: disable=unused-wildcard-import
from coverage.exceptions import * # pylint: disable=wildcard-import
ISOLATED_MODULES: dict[ModuleType, ModuleType] = {}
@ -54,11 +54,13 @@ def isolate_module(mod: ModuleType) -> ModuleType:
setattr(new_mod, name, value)
return ISOLATED_MODULES[mod]
os = isolate_module(os)
class SysModuleSaver:
"""Saves the contents of sys.modules, and removes new modules later."""
def __init__(self) -> None:
self.old_modules = set(sys.modules)
@ -111,13 +113,14 @@ def nice_pair(pair: TArc) -> str:
"""
start, end = pair
if start == end:
return "%d" % start
return '%d' % start
else:
return "%d-%d" % (start, end)
return '%d-%d' % (start, end)
TSelf = TypeVar("TSelf")
TRetVal = TypeVar("TRetVal")
TSelf = TypeVar('TSelf')
TRetVal = TypeVar('TRetVal')
def expensive(fn: Callable[[TSelf], TRetVal]) -> Callable[[TSelf], TRetVal]:
"""A decorator to indicate that a method shouldn't be called more than once.
@ -127,7 +130,7 @@ def expensive(fn: Callable[[TSelf], TRetVal]) -> Callable[[TSelf], TRetVal]:
"""
if env.TESTING:
attr = "_once_" + fn.__name__
attr = '_once_' + fn.__name__
def _wrapper(self: TSelf) -> TRetVal:
if hasattr(self, attr):
@ -153,7 +156,7 @@ def join_regex(regexes: Iterable[str]) -> str:
if len(regexes) == 1:
return regexes[0]
else:
return "|".join(f"(?:{r})" for r in regexes)
return '|'.join(f'(?:{r})' for r in regexes)
def file_be_gone(path: str) -> None:
@ -184,8 +187,8 @@ def output_encoding(outfile: IO[str] | None = None) -> str:
if outfile is None:
outfile = sys.stdout
encoding = (
getattr(outfile, "encoding", None) or
getattr(sys.__stdout__, "encoding", None) or
getattr(outfile, 'encoding', None) or
getattr(sys.__stdout__, 'encoding', None) or
locale.getpreferredencoding()
)
return encoding
@ -193,20 +196,21 @@ def output_encoding(outfile: IO[str] | None = None) -> str:
class Hasher:
"""Hashes Python data for fingerprinting."""
def __init__(self) -> None:
self.hash = hashlib.new("sha3_256")
self.hash = hashlib.new('sha3_256')
def update(self, v: Any) -> None:
"""Add `v` to the hash, recursively if needed."""
self.hash.update(str(type(v)).encode("utf-8"))
self.hash.update(str(type(v)).encode('utf-8'))
if isinstance(v, str):
self.hash.update(v.encode("utf-8"))
self.hash.update(v.encode('utf-8'))
elif isinstance(v, bytes):
self.hash.update(v)
elif v is None:
pass
elif isinstance(v, (int, float)):
self.hash.update(str(v).encode("utf-8"))
self.hash.update(str(v).encode('utf-8'))
elif isinstance(v, (tuple, list)):
for e in v:
self.update(e)
@ -217,14 +221,14 @@ class Hasher:
self.update(v[k])
else:
for k in dir(v):
if k.startswith("__"):
if k.startswith('__'):
continue
a = getattr(v, k)
if inspect.isroutine(a):
continue
self.update(k)
self.update(a)
self.hash.update(b".")
self.hash.update(b'.')
def hexdigest(self) -> str:
"""Retrieve the hex digest of the hash."""
@ -233,16 +237,16 @@ class Hasher:
def _needs_to_implement(that: Any, func_name: str) -> NoReturn:
"""Helper to raise NotImplementedError in interface stubs."""
if hasattr(that, "_coverage_plugin_name"):
thing = "Plugin"
if hasattr(that, '_coverage_plugin_name'):
thing = 'Plugin'
name = that._coverage_plugin_name
else:
thing = "Class"
thing = 'Class'
klass = that.__class__
name = f"{klass.__module__}.{klass.__name__}"
name = f'{klass.__module__}.{klass.__name__}'
raise NotImplementedError(
f"{thing} {name!r} needs to implement {func_name}()",
f'{thing} {name!r} needs to implement {func_name}()',
)
@ -253,6 +257,7 @@ class DefaultValue:
and Sphinx output.
"""
def __init__(self, display_as: str) -> None:
self.display_as = display_as
@ -291,21 +296,21 @@ def substitute_variables(text: str, variables: Mapping[str, str]) -> str:
)
"""
dollar_groups = ("dollar", "word1", "word2")
dollar_groups = ('dollar', 'word1', 'word2')
def dollar_replace(match: re.Match[str]) -> str:
"""Called for each $replacement."""
# Only one of the dollar_groups will have matched, just get its text.
word = next(g for g in match.group(*dollar_groups) if g) # pragma: always breaks
if word == "$":
return "$"
if word == '$':
return '$'
elif word in variables:
return variables[word]
elif match["strict"]:
msg = f"Variable {word} is undefined: {text!r}"
elif match['strict']:
msg = f'Variable {word} is undefined: {text!r}'
raise CoverageException(msg)
else:
return match["defval"]
return match['defval']
text = re.sub(dollar_pattern, dollar_replace, text)
return text
@ -314,7 +319,7 @@ def substitute_variables(text: str, variables: Mapping[str, str]) -> str:
def format_local_datetime(dt: datetime.datetime) -> str:
"""Return a string with local timezone representing the date.
"""
return dt.astimezone().strftime("%Y-%m-%d %H:%M %z")
return dt.astimezone().strftime('%Y-%m-%d %H:%M %z')
def import_local_file(modname: str, modfile: str | None = None) -> ModuleType:
@ -326,7 +331,7 @@ def import_local_file(modname: str, modfile: str | None = None) -> ModuleType:
"""
if modfile is None:
modfile = modname + ".py"
modfile = modname + '.py'
spec = importlib.util.spec_from_file_location(modname, modfile)
assert spec is not None
mod = importlib.util.module_from_spec(spec)
@ -352,7 +357,8 @@ def _human_key(s: str) -> tuple[list[str | int], str]:
except ValueError:
return s
return ([tryint(c) for c in re.split(r"(\d+)", s)], s)
return ([tryint(c) for c in re.split(r'(\d+)', s)], s)
def human_sorted(strings: Iterable[str]) -> list[str]:
"""Sort the given iterable of strings the way that humans expect.
@ -364,7 +370,9 @@ def human_sorted(strings: Iterable[str]) -> list[str]:
"""
return sorted(strings, key=_human_key)
SortableItem = TypeVar("SortableItem", bound=Sequence[Any])
SortableItem = TypeVar('SortableItem', bound=Sequence[Any])
def human_sorted_items(
items: Iterable[SortableItem],
@ -380,7 +388,7 @@ def human_sorted_items(
return sorted(items, key=lambda item: (_human_key(item[0]), *item[1:]), reverse=reverse)
def plural(n: int, thing: str = "", things: str = "") -> str:
def plural(n: int, thing: str = '', things: str = '') -> str:
"""Pluralize a word.
If n is 1, return thing. Otherwise return things, or thing+s.
@ -388,7 +396,7 @@ def plural(n: int, thing: str = "", things: str = "") -> str:
if n == 1:
return thing
else:
return things or (thing + "s")
return things or (thing + 's')
def stdout_link(text: str, url: str) -> str:
@ -397,7 +405,7 @@ def stdout_link(text: str, url: str) -> str:
If attached to a terminal, use escape sequences. Otherwise, just return
the text.
"""
if hasattr(sys.stdout, "isatty") and sys.stdout.isatty():
return f"\033]8;;{url}\a{text}\033]8;;\a"
if hasattr(sys.stdout, 'isatty') and sys.stdout.isatty():
return f'\033]8;;{url}\a{text}\033]8;;\a'
else:
return text