[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 @@
"""Helper functions for writing to terminals and files."""
from __future__ import annotations
import os
import shutil
@ -26,16 +27,16 @@ def get_terminal_width() -> int:
def should_do_markup(file: TextIO) -> bool:
if os.environ.get("PY_COLORS") == "1":
if os.environ.get('PY_COLORS') == '1':
return True
if os.environ.get("PY_COLORS") == "0":
if os.environ.get('PY_COLORS') == '0':
return False
if os.environ.get("NO_COLOR"):
if os.environ.get('NO_COLOR'):
return False
if os.environ.get("FORCE_COLOR"):
if os.environ.get('FORCE_COLOR'):
return True
return (
hasattr(file, "isatty") and file.isatty() and os.environ.get("TERM") != "dumb"
hasattr(file, 'isatty') and file.isatty() and os.environ.get('TERM') != 'dumb'
)
@ -64,10 +65,10 @@ class TerminalWriter:
invert=7,
)
def __init__(self, file: Optional[TextIO] = None) -> None:
def __init__(self, file: TextIO | None = None) -> None:
if file is None:
file = sys.stdout
if hasattr(file, "isatty") and file.isatty() and sys.platform == "win32":
if hasattr(file, 'isatty') and file.isatty() and sys.platform == 'win32':
try:
import colorama
except ImportError:
@ -77,8 +78,8 @@ class TerminalWriter:
assert file is not None
self._file = file
self.hasmarkup = should_do_markup(file)
self._current_line = ""
self._terminal_width: Optional[int] = None
self._current_line = ''
self._terminal_width: int | None = None
self.code_highlight = True
@property
@ -99,25 +100,25 @@ class TerminalWriter:
def markup(self, text: str, **markup: bool) -> str:
for name in markup:
if name not in self._esctable:
raise ValueError(f"unknown markup: {name!r}")
raise ValueError(f'unknown markup: {name!r}')
if self.hasmarkup:
esc = [self._esctable[name] for name, on in markup.items() if on]
if esc:
text = "".join("\x1b[%sm" % cod for cod in esc) + text + "\x1b[0m"
text = ''.join('\x1b[%sm' % cod for cod in esc) + text + '\x1b[0m'
return text
def sep(
self,
sepchar: str,
title: Optional[str] = None,
fullwidth: Optional[int] = None,
title: str | None = None,
fullwidth: int | None = None,
**markup: bool,
) -> None:
if fullwidth is None:
fullwidth = self.fullwidth
# The goal is to have the line be as long as possible
# under the condition that len(line) <= fullwidth.
if sys.platform == "win32":
if sys.platform == 'win32':
# If we print in the last column on windows we are on a
# new line but there is no way to verify/neutralize this
# (we may not know the exact line width).
@ -130,7 +131,7 @@ class TerminalWriter:
# N <= (fullwidth - len(title) - 2) // (2*len(sepchar))
N = max((fullwidth - len(title) - 2) // (2 * len(sepchar)), 1)
fill = sepchar * N
line = f"{fill} {title} {fill}"
line = f'{fill} {title} {fill}'
else:
# we want len(sepchar)*N <= fullwidth
# i.e. N <= fullwidth // len(sepchar)
@ -145,8 +146,8 @@ class TerminalWriter:
def write(self, msg: str, *, flush: bool = False, **markup: bool) -> None:
if msg:
current_line = msg.rsplit("\n", 1)[-1]
if "\n" in msg:
current_line = msg.rsplit('\n', 1)[-1]
if '\n' in msg:
self._current_line = current_line
else:
self._current_line += current_line
@ -162,15 +163,15 @@ class TerminalWriter:
# When the Unicode situation improves we should consider
# letting the error propagate instead of masking it (see #7475
# for one brief attempt).
msg = msg.encode("unicode-escape").decode("ascii")
msg = msg.encode('unicode-escape').decode('ascii')
self._file.write(msg)
if flush:
self.flush()
def line(self, s: str = "", **markup: bool) -> None:
def line(self, s: str = '', **markup: bool) -> None:
self.write(s, **markup)
self.write("\n")
self.write('\n')
def flush(self) -> None:
self._file.flush()
@ -184,17 +185,17 @@ class TerminalWriter:
"""
if indents and len(indents) != len(lines):
raise ValueError(
f"indents size ({len(indents)}) should have same size as lines ({len(lines)})"
f'indents size ({len(indents)}) should have same size as lines ({len(lines)})',
)
if not indents:
indents = [""] * len(lines)
source = "\n".join(lines)
indents = [''] * len(lines)
source = '\n'.join(lines)
new_lines = self._highlight(source).splitlines()
for indent, new_line in zip(indents, new_lines):
self.line(indent + new_line)
def _highlight(
self, source: str, lexer: Literal["diff", "python"] = "python"
self, source: str, lexer: Literal['diff', 'python'] = 'python',
) -> str:
"""Highlight the given source if we have markup support."""
from _pytest.config.exceptions import UsageError
@ -205,9 +206,9 @@ class TerminalWriter:
try:
from pygments.formatters.terminal import TerminalFormatter
if lexer == "python":
if lexer == 'python':
from pygments.lexers.python import PythonLexer as Lexer
elif lexer == "diff":
elif lexer == 'diff':
from pygments.lexers.diff import DiffLexer as Lexer
from pygments import highlight
import pygments.util
@ -219,30 +220,30 @@ class TerminalWriter:
source,
Lexer(),
TerminalFormatter(
bg=os.getenv("PYTEST_THEME_MODE", "dark"),
style=os.getenv("PYTEST_THEME"),
bg=os.getenv('PYTEST_THEME_MODE', 'dark'),
style=os.getenv('PYTEST_THEME'),
),
)
# pygments terminal formatter may add a newline when there wasn't one.
# We don't want this, remove.
if highlighted[-1] == "\n" and source[-1] != "\n":
if highlighted[-1] == '\n' and source[-1] != '\n':
highlighted = highlighted[:-1]
# Some lexers will not set the initial color explicitly
# which may lead to the previous color being propagated to the
# start of the expression, so reset first.
return "\x1b[0m" + highlighted
return '\x1b[0m' + highlighted
except pygments.util.ClassNotFound as e:
raise UsageError(
"PYTEST_THEME environment variable had an invalid value: '{}'. "
"Only valid pygment styles are allowed.".format(
os.getenv("PYTEST_THEME")
)
'Only valid pygment styles are allowed.'.format(
os.getenv('PYTEST_THEME'),
),
) from e
except pygments.util.OptionError as e:
raise UsageError(
"PYTEST_THEME_MODE environment variable had an invalid value: '{}'. "
"The only allowed values are 'dark' and 'light'.".format(
os.getenv("PYTEST_THEME_MODE")
)
os.getenv('PYTEST_THEME_MODE'),
),
) from e