| 1 |
"""Helper functions for writing to terminals and files.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
from collections.abc import Sequence |
| 6 |
import os |
| 7 |
import shutil |
| 8 |
import sys |
| 9 |
from typing import final |
| 10 |
from typing import Literal |
| 11 |
from typing import TextIO |
| 12 |
|
| 13 |
import pygments |
| 14 |
from pygments.formatters.terminal import TerminalFormatter |
| 15 |
from pygments.lexer import Lexer |
| 16 |
from pygments.lexers.diff import DiffLexer |
| 17 |
from pygments.lexers.python import PythonLexer |
| 18 |
|
| 19 |
from ..compat import assert_never |
| 20 |
from .wcwidth import wcswidth |
| 21 |
|
| 22 |
|
| 23 |
# This code was initially copied from py 1.8.1, file _io/terminalwriter.py. |
| 24 |
|
| 25 |
|
| 26 |
def get_terminal_width() -> int: |
| 27 |
width, _ = shutil.get_terminal_size(fallback=(80, 24)) |
| 28 |
|
| 29 |
# The Windows get_terminal_size may be bogus, let's sanify a bit. |
| 30 |
if width < 40: |
| 31 |
width = 80 |
| 32 |
|
| 33 |
return width |
| 34 |
|
| 35 |
|
| 36 |
def should_do_markup(file: TextIO) -> bool: |
| 37 |
if os.environ.get("PY_COLORS") == "1": |
| 38 |
return True |
| 39 |
if os.environ.get("PY_COLORS") == "0": |
| 40 |
return False |
| 41 |
if os.environ.get("NO_COLOR"): |
| 42 |
return False |
| 43 |
if os.environ.get("FORCE_COLOR"): |
| 44 |
return True |
| 45 |
return ( |
| 46 |
hasattr(file, "isatty") and file.isatty() and os.environ.get("TERM") != "dumb" |
| 47 |
) |
| 48 |
|
| 49 |
|
| 50 |
@final |
| 51 |
class TerminalWriter: |
| 52 |
_esctable = dict( |
| 53 |
black=30, |
| 54 |
red=31, |
| 55 |
green=32, |
| 56 |
yellow=33, |
| 57 |
blue=34, |
| 58 |
purple=35, |
| 59 |
cyan=36, |
| 60 |
white=37, |
| 61 |
Black=40, |
| 62 |
Red=41, |
| 63 |
Green=42, |
| 64 |
Yellow=43, |
| 65 |
Blue=44, |
| 66 |
Purple=45, |
| 67 |
Cyan=46, |
| 68 |
White=47, |
| 69 |
bold=1, |
| 70 |
light=2, |
| 71 |
blink=5, |
| 72 |
invert=7, |
| 73 |
) |
| 74 |
|
| 75 |
def __init__(self, file: TextIO | None = None) -> None: |
| 76 |
if file is None: |
| 77 |
file = sys.stdout |
| 78 |
if hasattr(file, "isatty") and file.isatty() and sys.platform == "win32": |
| 79 |
try: |
| 80 |
import colorama |
| 81 |
except ImportError: |
| 82 |
pass |
| 83 |
else: |
| 84 |
file = colorama.AnsiToWin32(file).stream |
| 85 |
assert file is not None |
| 86 |
self._file = file |
| 87 |
self.hasmarkup = should_do_markup(file) |
| 88 |
self._current_line = "" |
| 89 |
self._terminal_width: int | None = None |
| 90 |
self.code_highlight = True |
| 91 |
|
| 92 |
@property |
| 93 |
def fullwidth(self) -> int: |
| 94 |
if self._terminal_width is not None: |
| 95 |
return self._terminal_width |
| 96 |
return get_terminal_width() |
| 97 |
|
| 98 |
@fullwidth.setter |
| 99 |
def fullwidth(self, value: int) -> None: |
| 100 |
self._terminal_width = value |
| 101 |
|
| 102 |
@property |
| 103 |
def width_of_current_line(self) -> int: |
| 104 |
"""Return an estimate of the width so far in the current line.""" |
| 105 |
return wcswidth(self._current_line) |
| 106 |
|
| 107 |
def markup(self, text: str, **markup: bool) -> str: |
| 108 |
for name in markup: |
| 109 |
if name not in self._esctable: |
| 110 |
raise ValueError(f"unknown markup: {name!r}") |
| 111 |
if self.hasmarkup: |
| 112 |
esc = [self._esctable[name] for name, on in markup.items() if on] |
| 113 |
if esc: |
| 114 |
text = "".join(f"\x1b[{cod}m" for cod in esc) + text + "\x1b[0m" |
| 115 |
return text |
| 116 |
|
| 117 |
def sep( |
| 118 |
self, |
| 119 |
sepchar: str, |
| 120 |
title: str | None = None, |
| 121 |
fullwidth: int | None = None, |
| 122 |
**markup: bool, |
| 123 |
) -> None: |
| 124 |
if fullwidth is None: |
| 125 |
fullwidth = self.fullwidth |
| 126 |
# The goal is to have the line be as long as possible |
| 127 |
# under the condition that len(line) <= fullwidth. |
| 128 |
if sys.platform == "win32": |
| 129 |
# If we print in the last column on windows we are on a |
| 130 |
# new line but there is no way to verify/neutralize this |
| 131 |
# (we may not know the exact line width). |
| 132 |
# So let's be defensive to avoid empty lines in the output. |
| 133 |
fullwidth -= 1 |
| 134 |
if title is not None: |
| 135 |
# we want 2 + 2*len(fill) + len(title) <= fullwidth |
| 136 |
# i.e. 2 + 2*len(sepchar)*N + len(title) <= fullwidth |
| 137 |
# 2*len(sepchar)*N <= fullwidth - len(title) - 2 |
| 138 |
# N <= (fullwidth - len(title) - 2) // (2*len(sepchar)) |
| 139 |
N = max((fullwidth - len(title) - 2) // (2 * len(sepchar)), 1) |
| 140 |
fill = sepchar * N |
| 141 |
line = f"{fill} {title} {fill}" |
| 142 |
else: |
| 143 |
# we want len(sepchar)*N <= fullwidth |
| 144 |
# i.e. N <= fullwidth // len(sepchar) |
| 145 |
line = sepchar * (fullwidth // len(sepchar)) |
| 146 |
# In some situations there is room for an extra sepchar at the right, |
| 147 |
# in particular if we consider that with a sepchar like "_ " the |
| 148 |
# trailing space is not important at the end of the line. |
| 149 |
if len(line) + len(sepchar.rstrip()) <= fullwidth: |
| 150 |
line += sepchar.rstrip() |
| 151 |
|
| 152 |
self.line(line, **markup) |
| 153 |
|
| 154 |
def write(self, msg: str, *, flush: bool = False, **markup: bool) -> None: |
| 155 |
if msg: |
| 156 |
current_line = msg.rsplit("\n", 1)[-1] |
| 157 |
if "\n" in msg: |
| 158 |
self._current_line = current_line |
| 159 |
else: |
| 160 |
self._current_line += current_line |
| 161 |
|
| 162 |
msg = self.markup(msg, **markup) |
| 163 |
|
| 164 |
self.write_raw(msg, flush=flush) |
| 165 |
|
| 166 |
def write_raw(self, msg: str, *, flush: bool = False) -> None: |
| 167 |
try: |
| 168 |
self._file.write(msg) |
| 169 |
except UnicodeEncodeError: |
| 170 |
# Some environments don't support printing general Unicode |
| 171 |
# strings, due to misconfiguration or otherwise; in that case, |
| 172 |
# print the string escaped to ASCII. |
| 173 |
# When the Unicode situation improves we should consider |
| 174 |
# letting the error propagate instead of masking it (see #7475 |
| 175 |
# for one brief attempt). |
| 176 |
msg = msg.encode("unicode-escape").decode("ascii") |
| 177 |
self._file.write(msg) |
| 178 |
|
| 179 |
if flush: |
| 180 |
self.flush() |
| 181 |
|
| 182 |
def line(self, s: str = "", **markup: bool) -> None: |
| 183 |
self.write(s, **markup) |
| 184 |
self.write("\n") |
| 185 |
|
| 186 |
def flush(self) -> None: |
| 187 |
self._file.flush() |
| 188 |
|
| 189 |
def _write_source(self, lines: Sequence[str], indents: Sequence[str] = ()) -> None: |
| 190 |
"""Write lines of source code possibly highlighted. |
| 191 |
|
| 192 |
Keeping this private for now because the API is clunky. We should discuss how |
| 193 |
to evolve the terminal writer so we can have more precise color support, for example |
| 194 |
being able to write part of a line in one color and the rest in another, and so on. |
| 195 |
""" |
| 196 |
if indents and len(indents) != len(lines): |
| 197 |
raise ValueError( |
| 198 |
f"indents size ({len(indents)}) should have same size as lines ({len(lines)})" |
| 199 |
) |
| 200 |
if not indents: |
| 201 |
indents = [""] * len(lines) |
| 202 |
source = "\n".join(lines) |
| 203 |
new_lines = self._highlight(source).splitlines() |
| 204 |
# Would be better to strict=True but that fails some CI jobs. |
| 205 |
for indent, new_line in zip(indents, new_lines, strict=False): |
| 206 |
self.line(indent + new_line) |
| 207 |
|
| 208 |
def _get_pygments_lexer(self, lexer: Literal["python", "diff"]) -> Lexer: |
| 209 |
if lexer == "python": |
| 210 |
return PythonLexer() |
| 211 |
elif lexer == "diff": |
| 212 |
return DiffLexer() |
| 213 |
else: |
| 214 |
assert_never(lexer) |
| 215 |
|
| 216 |
def _get_pygments_formatter(self) -> TerminalFormatter: |
| 217 |
from _pytest.config.exceptions import UsageError |
| 218 |
|
| 219 |
theme = os.getenv("PYTEST_THEME") |
| 220 |
theme_mode = os.getenv("PYTEST_THEME_MODE", "dark") |
| 221 |
|
| 222 |
try: |
| 223 |
return TerminalFormatter(bg=theme_mode, style=theme) |
| 224 |
except pygments.util.ClassNotFound as e: |
| 225 |
raise UsageError( |
| 226 |
f"PYTEST_THEME environment variable has an invalid value: '{theme}'. " |
| 227 |
"Hint: See available pygments styles with `pygmentize -L styles`." |
| 228 |
) from e |
| 229 |
except pygments.util.OptionError as e: |
| 230 |
raise UsageError( |
| 231 |
f"PYTEST_THEME_MODE environment variable has an invalid value: '{theme_mode}'. " |
| 232 |
"The allowed values are 'dark' (default) and 'light'." |
| 233 |
) from e |
| 234 |
|
| 235 |
def _highlight( |
| 236 |
self, source: str, lexer: Literal["diff", "python"] = "python" |
| 237 |
) -> str: |
| 238 |
"""Highlight the given source if we have markup support.""" |
| 239 |
if not source or not self.hasmarkup or not self.code_highlight: |
| 240 |
return source |
| 241 |
|
| 242 |
pygments_lexer = self._get_pygments_lexer(lexer) |
| 243 |
pygments_formatter = self._get_pygments_formatter() |
| 244 |
|
| 245 |
highlighted: str = pygments.highlight( |
| 246 |
source, pygments_lexer, pygments_formatter |
| 247 |
) |
| 248 |
# pygments terminal formatter may add a newline when there wasn't one. |
| 249 |
# We don't want this, remove. |
| 250 |
if highlighted[-1] == "\n" and source[-1] != "\n": |
| 251 |
highlighted = highlighted[:-1] |
| 252 |
|
| 253 |
# Some lexers will not set the initial color explicitly |
| 254 |
# which may lead to the previous color being propagated to the |
| 255 |
# start of the expression, so reset first. |
| 256 |
highlighted = "\x1b[0m" + highlighted |
| 257 |
|
| 258 |
return highlighted |