Skip to content

chuchichaestli.utils.ansi

Terminal colouring, for output a person reads rather than a file keeps.

Classes:

Name Description
ANSIShade

Select-graphic-rendition codes, named for how they are meant to read.

Pinned

Keeps one line at the foot of a stream while the rest scroll above it.

Functions:

Name Description
ansi_supported

Whether a stream should be written to in colour.

cli_pbar

Return a progress bar of a given relative length, with its labels.

paint

Wrap text in graphic-rendition codes, or return it unchanged.

ANSIShade

Bases: str, Enum

Select-graphic-rendition codes, named for how they are meant to read.

Pinned

Pinned(stream: TextIO, live: bool = True)

Keeps one line at the foot of a stream while the rest scroll above it.

Attributes:

Name Type Description
line

What is currently pinned, or "" when nothing is.

Constructor.

Parameters:

Name Type Description Default
stream TextIO

Where both the pinned line and the rest are written.

required
live bool

Whether the stream redraws. A file keeps every line it is given, so nothing is pinned to it.

True

Methods:

Name Description
drop

Let go of the pinned line, leaving the cursor on a fresh one.

pin

Hold a line at the foot of the stream, replacing any before it.

scroll

Write a line above whatever is pinned.

Source code in src/chuchichaestli/utils/ansi.py
64
65
66
67
68
69
70
71
72
73
74
def __init__(self, stream: TextIO, live: bool = True):
    """Constructor.

    Args:
        stream: Where both the pinned line and the rest are written.
        live: Whether the stream redraws. A file keeps every line it is
            given, so nothing is pinned to it.
    """
    self.stream = stream
    self.live = live
    self.line = ""

drop

drop() -> None

Let go of the pinned line, leaving the cursor on a fresh one.

Source code in src/chuchichaestli/utils/ansi.py
100
101
102
103
104
105
106
def drop(self) -> None:
    """Let go of the pinned line, leaving the cursor on a fresh one."""
    if not self.live or not self.line:
        return
    self.stream.write(f"{self.ERASE}")
    self.stream.flush()
    self.line = ""

pin

pin(text: str) -> None

Hold a line at the foot of the stream, replacing any before it.

Parameters:

Name Type Description Default
text str

The line to hold.

required
Source code in src/chuchichaestli/utils/ansi.py
88
89
90
91
92
93
94
95
96
97
98
def pin(self, text: str) -> None:
    """Hold a line at the foot of the stream, replacing any before it.

    Args:
        text: The line to hold.
    """
    if not self.live:
        return
    self.line = text
    self.stream.write(f"{self.ERASE}{text}")
    self.stream.flush()

scroll

scroll(text: str) -> None

Write a line above whatever is pinned.

Parameters:

Name Type Description Default
text str

The line to write.

required
Source code in src/chuchichaestli/utils/ansi.py
76
77
78
79
80
81
82
83
84
85
86
def scroll(self, text: str) -> None:
    """Write a line above whatever is pinned.

    Args:
        text: The line to write.
    """
    if not self.live:
        print(text, file=self.stream, flush=True)
        return
    self.stream.write(f"{self.ERASE}{text}\n{self.line}")
    self.stream.flush()

ansi_supported

ansi_supported(stream: IO[str]) -> bool

Whether a stream should be written to in colour.

Honours the NO_COLOR convention, and answers False for anything that is not a terminal, so escape codes never reach a redirected log.

Parameters:

Name Type Description Default
stream IO[str]

Destination the output is headed for.

required
Source code in src/chuchichaestli/utils/ansi.py
28
29
30
31
32
33
34
35
36
37
38
39
def ansi_supported(stream: IO[str]) -> bool:
    """Whether a stream should be written to in colour.

    Honours the `NO_COLOR` convention, and answers `False` for anything that is
    not a terminal, so escape codes never reach a redirected log.

    Args:
        stream: Destination the output is headed for.
    """
    if os.environ.get("NO_COLOR"):
        return False
    return bool(getattr(stream, "isatty", bool)())

cli_pbar

cli_pbar(
    r_fill: float,
    prefix: str | list = "",
    postfix: str | list = "",
    bar_length: int = 60,
    fill_symbol: str = "#",
    empty_symbol: str = "-",
    float_fmt: str = "{:.2f}",
    int_fmt: str = "{:4d}",
) -> str

Return a progress bar of a given relative length, with its labels.

Parameters:

Name Type Description Default
r_fill float

How far along the bar is, between 0 and 1.

required
prefix str | list

Label written before the bar.

''
postfix str | list

Label written after the bar.

''
bar_length int

Width of the bar itself; the labels alone when it is not positive.

60
fill_symbol str

What the filled part is drawn with.

'#'
empty_symbol str

What the rest is drawn with.

'-'
float_fmt str

How floats in the labels are formatted.

'{:.2f}'
int_fmt str

How ints in the labels are formatted.

'{:4d}'
Source code in src/chuchichaestli/utils/ansi.py
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
def cli_pbar(
    r_fill: float,
    prefix: str | list = "",
    postfix: str | list = "",
    bar_length: int = 60,
    fill_symbol: str = "#",
    empty_symbol: str = "-",
    float_fmt: str = "{:.2f}",
    int_fmt: str = "{:4d}",
) -> str:
    """Return a progress bar of a given relative length, with its labels.

    Args:
        r_fill: How far along the bar is, between 0 and 1.
        prefix: Label written before the bar.
        postfix: Label written after the bar.
        bar_length: Width of the bar itself; the labels alone when it is not
            positive.
        fill_symbol: What the filled part is drawn with.
        empty_symbol: What the rest is drawn with.
        float_fmt: How floats in the labels are formatted.
        int_fmt: How ints in the labels are formatted.
    """
    if isinstance(prefix, list | tuple):
        for i, p in enumerate(prefix):
            if isinstance(p, float):
                prefix[i] = float_fmt.format(p)
            elif isinstance(p, int):
                prefix[i] = int_fmt.format(p)
            if not isinstance(prefix[i], str):
                prefix[i] = f"{prefix[i]}"
        prefix = " ".join(prefix)
    if isinstance(postfix, list | tuple):
        for i, p in enumerate(postfix):
            if isinstance(p, float):
                postfix[i] = float_fmt.format(p)
            elif isinstance(p, int):
                postfix[i] = int_fmt.format(p)
            if not isinstance(postfix[i], str):
                postfix[i] = f"{postfix[i]}"
        postfix = " ".join(postfix)
    filled = int(r_fill * bar_length)
    bar = fill_symbol * filled + empty_symbol * (bar_length - filled)
    if bar_length > 0:
        line = f"{prefix} [{bar}] {postfix}"
    else:
        line = f"{prefix}\t{postfix}"
    return line

paint

paint(
    text: str, *shades: ANSIShade, on: bool = True
) -> str

Wrap text in graphic-rendition codes, or return it unchanged.

Parameters:

Name Type Description Default
text str

What to colour.

required
shades ANSIShade

Codes to apply, in order.

()
on bool

Whether to colour at all; False returns text untouched.

True
Source code in src/chuchichaestli/utils/ansi.py
42
43
44
45
46
47
48
49
50
51
52
def paint(text: str, *shades: ANSIShade, on: bool = True) -> str:
    """Wrap text in graphic-rendition codes, or return it unchanged.

    Args:
        text: What to colour.
        shades: Codes to apply, in order.
        on: Whether to colour at all; `False` returns `text` untouched.
    """
    if not on or not shades or not text:
        return text
    return "".join(s.value for s in shades) + text + ANSIShade.RESET.value