Repository navigation
Expand file tree
/
Copy pathconsole_marks.py
More file actions
59 lines (48 loc) · 2.42 KB
/
Copy pathconsole_marks.py
File metadata and controls
59 lines (48 loc) · 2.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
"""Status glyphs that survive the terminal they are printed to.
Rich substitutes ASCII box characters when a stream's encoding cannot
represent them, but it does not touch CELL TEXT: a glyph written into a
table cell reaches the terminal's codec unchanged, and a code page that
lacks it raises ``UnicodeEncodeError`` instead of printing (#1910 on
``cgr doctor``, #1914 on the query result table -- both reported from a
CP950 Windows terminal).
Shared rather than private to one caller, because the two sites must not
drift: a reader who learns that ``PASS``/``FAIL`` means pass/fail in one
table should not meet a different pair in the next. The marks themselves
live in ``constants/health.py``, defined once for both tables.
"""
from __future__ import annotations
from codebase_rag import constants as cs
__all__ = ["status_mark"]
def _can_encode(text: str, encoding: str | None) -> bool:
"""Whether `encoding` can represent `text`.
``None`` is NOT what a Rich console reports for a capture stream --
measured, ``Console.encoding`` normalises a missing or empty stream
encoding to ``"utf-8"``, so a ``StringIO`` capture and a stream whose
``.encoding`` is ``None`` both arrive here as ``"utf-8"``. The
``None`` arm is the contract for a caller that is not a Rich console
and has no encoding to offer; an unknown stream is not evidence
against the glyph, so it keeps it.
"""
if encoding is None:
return True
try:
text.encode(encoding)
except (LookupError, UnicodeEncodeError):
# LookupError: an encoding name Python does not know. Unreadable is
# not the same as unrepresentable, but both mean this glyph cannot
# be shown to be safe, and the ASCII pair always is.
return False
return True
def status_mark(passed: bool, encoding: str | None) -> str:
"""``✓``/``✗`` when `encoding` can carry them, ``PASS``/``FAIL``
when it cannot.
Both marks are tested, not just the one being returned: a terminal that
can encode one and not the other would otherwise produce a column that
mixes the two alphabets, and the pair is meant to be read together.
"""
glyphs_usable = _can_encode(cs.HEALTH_MARK_PASS, encoding) and _can_encode(
cs.HEALTH_MARK_FAIL, encoding
)
if glyphs_usable:
return cs.HEALTH_MARK_PASS if passed else cs.HEALTH_MARK_FAIL
return cs.HEALTH_MARK_PASS_ASCII if passed else cs.HEALTH_MARK_FAIL_ASCII