Tom Rini | 10e4779 | 2018-05-06 17:58:06 -0400 | [diff] [blame] | 1 | # SPDX-License-Identifier: GPL-2.0+ |
Simon Glass | 2613288 | 2012-01-14 15:12:45 +0000 | [diff] [blame] | 2 | # Copyright (c) 2011 The Chromium OS Authors. |
| 3 | # |
Simon Glass | 2613288 | 2012-01-14 15:12:45 +0000 | [diff] [blame] | 4 | |
| 5 | """Terminal utilities |
| 6 | |
| 7 | This module handles terminal interaction including ANSI color codes. |
| 8 | """ |
| 9 | |
Simon Glass | 14d64e3 | 2025-04-29 07:21:59 -0600 | [diff] [blame] | 10 | from contextlib import contextmanager |
| 11 | from io import StringIO |
Simon Glass | a9f7edb | 2012-12-15 10:42:01 +0000 | [diff] [blame] | 12 | import os |
Simon Glass | 5f9325d | 2020-04-09 15:08:40 -0600 | [diff] [blame] | 13 | import re |
Simon Glass | bbde053 | 2020-04-09 15:08:41 -0600 | [diff] [blame] | 14 | import shutil |
Simon Glass | a9f7edb | 2012-12-15 10:42:01 +0000 | [diff] [blame] | 15 | import sys |
| 16 | |
| 17 | # Selection of when we want our output to be colored |
| 18 | COLOR_IF_TERMINAL, COLOR_ALWAYS, COLOR_NEVER = range(3) |
| 19 | |
Simon Glass | fb35f9f | 2014-09-05 19:00:06 -0600 | [diff] [blame] | 20 | # Initially, we are set up to print to the terminal |
| 21 | print_test_mode = False |
| 22 | print_test_list = [] |
| 23 | |
Simon Glass | 5f9325d | 2020-04-09 15:08:40 -0600 | [diff] [blame] | 24 | # The length of the last line printed without a newline |
| 25 | last_print_len = None |
| 26 | |
| 27 | # credit: |
| 28 | # stackoverflow.com/questions/14693701/how-can-i-remove-the-ansi-escape-sequences-from-a-string-in-python |
| 29 | ansi_escape = re.compile(r'\x1b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])') |
| 30 | |
Simon Glass | e884498 | 2025-04-29 07:22:01 -0600 | [diff] [blame] | 31 | # True if we are capturing console output |
| 32 | CAPTURING = False |
| 33 | |
| 34 | # Set this to False to disable output-capturing globally |
| 35 | USE_CAPTURE = True |
| 36 | |
| 37 | |
Simon Glass | fb35f9f | 2014-09-05 19:00:06 -0600 | [diff] [blame] | 38 | class PrintLine: |
| 39 | """A line of text output |
| 40 | |
| 41 | Members: |
| 42 | text: Text line that was printed |
| 43 | newline: True to output a newline after the text |
| 44 | colour: Text colour to use |
| 45 | """ |
Simon Glass | 3db916d | 2020-10-29 21:46:35 -0600 | [diff] [blame] | 46 | def __init__(self, text, colour, newline=True, bright=True): |
Simon Glass | fb35f9f | 2014-09-05 19:00:06 -0600 | [diff] [blame] | 47 | self.text = text |
| 48 | self.newline = newline |
| 49 | self.colour = colour |
Simon Glass | 3db916d | 2020-10-29 21:46:35 -0600 | [diff] [blame] | 50 | self.bright = bright |
| 51 | |
| 52 | def __eq__(self, other): |
| 53 | return (self.text == other.text and |
| 54 | self.newline == other.newline and |
| 55 | self.colour == other.colour and |
| 56 | self.bright == other.bright) |
Simon Glass | fb35f9f | 2014-09-05 19:00:06 -0600 | [diff] [blame] | 57 | |
| 58 | def __str__(self): |
Simon Glass | 3db916d | 2020-10-29 21:46:35 -0600 | [diff] [blame] | 59 | return ("newline=%s, colour=%s, bright=%d, text='%s'" % |
| 60 | (self.newline, self.colour, self.bright, self.text)) |
| 61 | |
Simon Glass | fb35f9f | 2014-09-05 19:00:06 -0600 | [diff] [blame] | 62 | |
Simon Glass | 0281158 | 2022-01-29 14:14:18 -0700 | [diff] [blame] | 63 | def calc_ascii_len(text): |
Simon Glass | 5f9325d | 2020-04-09 15:08:40 -0600 | [diff] [blame] | 64 | """Calculate the length of a string, ignoring any ANSI sequences |
| 65 | |
Simon Glass | bbde053 | 2020-04-09 15:08:41 -0600 | [diff] [blame] | 66 | When displayed on a terminal, ANSI sequences don't take any space, so we |
| 67 | need to ignore them when calculating the length of a string. |
| 68 | |
Simon Glass | 5f9325d | 2020-04-09 15:08:40 -0600 | [diff] [blame] | 69 | Args: |
| 70 | text: Text to check |
| 71 | |
| 72 | Returns: |
| 73 | Length of text, after skipping ANSI sequences |
| 74 | |
| 75 | >>> col = Color(COLOR_ALWAYS) |
Simon Glass | f45d374 | 2022-01-29 14:14:17 -0700 | [diff] [blame] | 76 | >>> text = col.build(Color.RED, 'abc') |
Simon Glass | 5f9325d | 2020-04-09 15:08:40 -0600 | [diff] [blame] | 77 | >>> len(text) |
| 78 | 14 |
Simon Glass | 0281158 | 2022-01-29 14:14:18 -0700 | [diff] [blame] | 79 | >>> calc_ascii_len(text) |
Simon Glass | 5f9325d | 2020-04-09 15:08:40 -0600 | [diff] [blame] | 80 | 3 |
| 81 | >>> |
| 82 | >>> text += 'def' |
Simon Glass | 0281158 | 2022-01-29 14:14:18 -0700 | [diff] [blame] | 83 | >>> calc_ascii_len(text) |
Simon Glass | 5f9325d | 2020-04-09 15:08:40 -0600 | [diff] [blame] | 84 | 6 |
Simon Glass | f45d374 | 2022-01-29 14:14:17 -0700 | [diff] [blame] | 85 | >>> text += col.build(Color.RED, 'abc') |
Simon Glass | 0281158 | 2022-01-29 14:14:18 -0700 | [diff] [blame] | 86 | >>> calc_ascii_len(text) |
Simon Glass | 5f9325d | 2020-04-09 15:08:40 -0600 | [diff] [blame] | 87 | 9 |
| 88 | """ |
| 89 | result = ansi_escape.sub('', text) |
| 90 | return len(result) |
| 91 | |
Simon Glass | 0281158 | 2022-01-29 14:14:18 -0700 | [diff] [blame] | 92 | def trim_ascii_len(text, size): |
Simon Glass | bbde053 | 2020-04-09 15:08:41 -0600 | [diff] [blame] | 93 | """Trim a string containing ANSI sequences to the given ASCII length |
| 94 | |
| 95 | The string is trimmed with ANSI sequences being ignored for the length |
| 96 | calculation. |
| 97 | |
| 98 | >>> col = Color(COLOR_ALWAYS) |
Simon Glass | f45d374 | 2022-01-29 14:14:17 -0700 | [diff] [blame] | 99 | >>> text = col.build(Color.RED, 'abc') |
Simon Glass | bbde053 | 2020-04-09 15:08:41 -0600 | [diff] [blame] | 100 | >>> len(text) |
| 101 | 14 |
Simon Glass | 0281158 | 2022-01-29 14:14:18 -0700 | [diff] [blame] | 102 | >>> calc_ascii_len(trim_ascii_len(text, 4)) |
Simon Glass | bbde053 | 2020-04-09 15:08:41 -0600 | [diff] [blame] | 103 | 3 |
Simon Glass | 0281158 | 2022-01-29 14:14:18 -0700 | [diff] [blame] | 104 | >>> calc_ascii_len(trim_ascii_len(text, 2)) |
Simon Glass | bbde053 | 2020-04-09 15:08:41 -0600 | [diff] [blame] | 105 | 2 |
| 106 | >>> text += 'def' |
Simon Glass | 0281158 | 2022-01-29 14:14:18 -0700 | [diff] [blame] | 107 | >>> calc_ascii_len(trim_ascii_len(text, 4)) |
Simon Glass | bbde053 | 2020-04-09 15:08:41 -0600 | [diff] [blame] | 108 | 4 |
Simon Glass | f45d374 | 2022-01-29 14:14:17 -0700 | [diff] [blame] | 109 | >>> text += col.build(Color.RED, 'ghi') |
Simon Glass | 0281158 | 2022-01-29 14:14:18 -0700 | [diff] [blame] | 110 | >>> calc_ascii_len(trim_ascii_len(text, 7)) |
Simon Glass | bbde053 | 2020-04-09 15:08:41 -0600 | [diff] [blame] | 111 | 7 |
| 112 | """ |
Simon Glass | 0281158 | 2022-01-29 14:14:18 -0700 | [diff] [blame] | 113 | if calc_ascii_len(text) < size: |
Simon Glass | bbde053 | 2020-04-09 15:08:41 -0600 | [diff] [blame] | 114 | return text |
| 115 | pos = 0 |
| 116 | out = '' |
| 117 | left = size |
| 118 | |
| 119 | # Work through each ANSI sequence in turn |
| 120 | for m in ansi_escape.finditer(text): |
| 121 | # Find the text before the sequence and add it to our string, making |
| 122 | # sure it doesn't overflow |
| 123 | before = text[pos:m.start()] |
| 124 | toadd = before[:left] |
| 125 | out += toadd |
| 126 | |
| 127 | # Figure out how much non-ANSI space we have left |
| 128 | left -= len(toadd) |
| 129 | |
| 130 | # Add the ANSI sequence and move to the position immediately after it |
| 131 | out += m.group() |
| 132 | pos = m.start() + len(m.group()) |
| 133 | |
| 134 | # Deal with text after the last ANSI sequence |
| 135 | after = text[pos:] |
| 136 | toadd = after[:left] |
| 137 | out += toadd |
| 138 | |
| 139 | return out |
| 140 | |
Simon Glass | 5f9325d | 2020-04-09 15:08:40 -0600 | [diff] [blame] | 141 | |
Simon Glass | 2027ddd | 2025-04-29 07:22:02 -0600 | [diff] [blame^] | 142 | def tprint(text='', newline=True, colour=None, limit_to_line=False, |
| 143 | bright=True, back=None, col=None): |
Simon Glass | fb35f9f | 2014-09-05 19:00:06 -0600 | [diff] [blame] | 144 | """Handle a line of output to the terminal. |
| 145 | |
| 146 | In test mode this is recorded in a list. Otherwise it is output to the |
| 147 | terminal. |
| 148 | |
| 149 | Args: |
| 150 | text: Text to print |
| 151 | newline: True to add a new line at the end of the text |
| 152 | colour: Colour to use for the text |
| 153 | """ |
Simon Glass | 5f9325d | 2020-04-09 15:08:40 -0600 | [diff] [blame] | 154 | global last_print_len |
| 155 | |
Simon Glass | fb35f9f | 2014-09-05 19:00:06 -0600 | [diff] [blame] | 156 | if print_test_mode: |
Simon Glass | 3db916d | 2020-10-29 21:46:35 -0600 | [diff] [blame] | 157 | print_test_list.append(PrintLine(text, colour, newline, bright)) |
Simon Glass | fb35f9f | 2014-09-05 19:00:06 -0600 | [diff] [blame] | 158 | else: |
Simon Glass | 2027ddd | 2025-04-29 07:22:02 -0600 | [diff] [blame^] | 159 | if colour is not None: |
| 160 | if not col: |
| 161 | col = Color() |
| 162 | text = col.build(colour, text, bright=bright, back=back) |
Simon Glass | fb35f9f | 2014-09-05 19:00:06 -0600 | [diff] [blame] | 163 | if newline: |
Simon Glass | 82e4c64 | 2020-04-09 15:08:39 -0600 | [diff] [blame] | 164 | print(text) |
Simon Glass | 5f9325d | 2020-04-09 15:08:40 -0600 | [diff] [blame] | 165 | last_print_len = None |
Simon Glass | 9c45a4e | 2016-09-18 16:48:30 -0600 | [diff] [blame] | 166 | else: |
Simon Glass | bbde053 | 2020-04-09 15:08:41 -0600 | [diff] [blame] | 167 | if limit_to_line: |
| 168 | cols = shutil.get_terminal_size().columns |
Simon Glass | 0281158 | 2022-01-29 14:14:18 -0700 | [diff] [blame] | 169 | text = trim_ascii_len(text, cols) |
Simon Glass | 82e4c64 | 2020-04-09 15:08:39 -0600 | [diff] [blame] | 170 | print(text, end='', flush=True) |
Simon Glass | 0281158 | 2022-01-29 14:14:18 -0700 | [diff] [blame] | 171 | last_print_len = calc_ascii_len(text) |
Simon Glass | 5f9325d | 2020-04-09 15:08:40 -0600 | [diff] [blame] | 172 | |
Simon Glass | 0281158 | 2022-01-29 14:14:18 -0700 | [diff] [blame] | 173 | def print_clear(): |
Simon Glass | 5f9325d | 2020-04-09 15:08:40 -0600 | [diff] [blame] | 174 | """Clear a previously line that was printed with no newline""" |
| 175 | global last_print_len |
| 176 | |
| 177 | if last_print_len: |
Simon Glass | c229d32 | 2024-06-23 11:55:15 -0600 | [diff] [blame] | 178 | if print_test_mode: |
| 179 | print_test_list.append(PrintLine(None, None, None, None)) |
| 180 | else: |
| 181 | print('\r%s\r' % (' '* last_print_len), end='', flush=True) |
| 182 | last_print_len = None |
Simon Glass | fb35f9f | 2014-09-05 19:00:06 -0600 | [diff] [blame] | 183 | |
Simon Glass | 0281158 | 2022-01-29 14:14:18 -0700 | [diff] [blame] | 184 | def set_print_test_mode(enable=True): |
Simon Glass | fb35f9f | 2014-09-05 19:00:06 -0600 | [diff] [blame] | 185 | """Go into test mode, where all printing is recorded""" |
| 186 | global print_test_mode |
| 187 | |
Simon Glass | 3db916d | 2020-10-29 21:46:35 -0600 | [diff] [blame] | 188 | print_test_mode = enable |
Simon Glass | 0281158 | 2022-01-29 14:14:18 -0700 | [diff] [blame] | 189 | get_print_test_lines() |
Simon Glass | fb35f9f | 2014-09-05 19:00:06 -0600 | [diff] [blame] | 190 | |
Simon Glass | 0281158 | 2022-01-29 14:14:18 -0700 | [diff] [blame] | 191 | def get_print_test_lines(): |
| 192 | """Get a list of all lines output through tprint() |
Simon Glass | fb35f9f | 2014-09-05 19:00:06 -0600 | [diff] [blame] | 193 | |
| 194 | Returns: |
| 195 | A list of PrintLine objects |
| 196 | """ |
| 197 | global print_test_list |
| 198 | |
| 199 | ret = print_test_list |
| 200 | print_test_list = [] |
| 201 | return ret |
| 202 | |
Simon Glass | 0281158 | 2022-01-29 14:14:18 -0700 | [diff] [blame] | 203 | def echo_print_test_lines(): |
Simon Glass | fb35f9f | 2014-09-05 19:00:06 -0600 | [diff] [blame] | 204 | """Print out the text lines collected""" |
| 205 | for line in print_test_list: |
| 206 | if line.colour: |
| 207 | col = Color() |
Simon Glass | f45d374 | 2022-01-29 14:14:17 -0700 | [diff] [blame] | 208 | print(col.build(line.colour, line.text), end='') |
Simon Glass | fb35f9f | 2014-09-05 19:00:06 -0600 | [diff] [blame] | 209 | else: |
Paul Burton | c393134 | 2016-09-27 16:03:50 +0100 | [diff] [blame] | 210 | print(line.text, end='') |
Simon Glass | fb35f9f | 2014-09-05 19:00:06 -0600 | [diff] [blame] | 211 | if line.newline: |
Paul Burton | c393134 | 2016-09-27 16:03:50 +0100 | [diff] [blame] | 212 | print() |
Simon Glass | fb35f9f | 2014-09-05 19:00:06 -0600 | [diff] [blame] | 213 | |
| 214 | |
Simon Glass | 2613288 | 2012-01-14 15:12:45 +0000 | [diff] [blame] | 215 | class Color(object): |
Simon Glass | 381fad8 | 2014-08-28 09:43:34 -0600 | [diff] [blame] | 216 | """Conditionally wraps text in ANSI color escape sequences.""" |
| 217 | BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8) |
| 218 | BOLD = -1 |
Simon Glass | 2027ddd | 2025-04-29 07:22:02 -0600 | [diff] [blame^] | 219 | BRIGHT_START = '\033[1;%d%sm' |
| 220 | NORMAL_START = '\033[22;%d%sm' |
Simon Glass | 381fad8 | 2014-08-28 09:43:34 -0600 | [diff] [blame] | 221 | BOLD_START = '\033[1m' |
Simon Glass | 2027ddd | 2025-04-29 07:22:02 -0600 | [diff] [blame^] | 222 | BACK_EXTRA = ';%d' |
Simon Glass | 381fad8 | 2014-08-28 09:43:34 -0600 | [diff] [blame] | 223 | RESET = '\033[0m' |
Simon Glass | 2613288 | 2012-01-14 15:12:45 +0000 | [diff] [blame] | 224 | |
Simon Glass | 381fad8 | 2014-08-28 09:43:34 -0600 | [diff] [blame] | 225 | def __init__(self, colored=COLOR_IF_TERMINAL): |
| 226 | """Create a new Color object, optionally disabling color output. |
Simon Glass | 2613288 | 2012-01-14 15:12:45 +0000 | [diff] [blame] | 227 | |
Simon Glass | 381fad8 | 2014-08-28 09:43:34 -0600 | [diff] [blame] | 228 | Args: |
| 229 | enabled: True if color output should be enabled. If False then this |
| 230 | class will not add color codes at all. |
| 231 | """ |
Simon Glass | b0cd341 | 2014-08-28 09:43:35 -0600 | [diff] [blame] | 232 | try: |
| 233 | self._enabled = (colored == COLOR_ALWAYS or |
| 234 | (colored == COLOR_IF_TERMINAL and |
| 235 | os.isatty(sys.stdout.fileno()))) |
| 236 | except: |
| 237 | self._enabled = False |
Simon Glass | 2613288 | 2012-01-14 15:12:45 +0000 | [diff] [blame] | 238 | |
Simon Glass | 2027ddd | 2025-04-29 07:22:02 -0600 | [diff] [blame^] | 239 | def enabled(self): |
| 240 | """Check if colour is enabled |
| 241 | |
| 242 | Return: True if enabled, else False |
| 243 | """ |
| 244 | return self._enabled |
| 245 | |
| 246 | def start(self, color, bright=True, back=None): |
Simon Glass | 381fad8 | 2014-08-28 09:43:34 -0600 | [diff] [blame] | 247 | """Returns a start color code. |
Simon Glass | 2613288 | 2012-01-14 15:12:45 +0000 | [diff] [blame] | 248 | |
Simon Glass | 381fad8 | 2014-08-28 09:43:34 -0600 | [diff] [blame] | 249 | Args: |
| 250 | color: Color to use, .e.g BLACK, RED, etc. |
Simon Glass | 2613288 | 2012-01-14 15:12:45 +0000 | [diff] [blame] | 251 | |
Simon Glass | 381fad8 | 2014-08-28 09:43:34 -0600 | [diff] [blame] | 252 | Returns: |
| 253 | If color is enabled, returns an ANSI sequence to start the given |
| 254 | color, otherwise returns empty string |
| 255 | """ |
| 256 | if self._enabled: |
Simon Glass | 2027ddd | 2025-04-29 07:22:02 -0600 | [diff] [blame^] | 257 | if color == self.BOLD: |
| 258 | return self.BOLD_START |
Simon Glass | 381fad8 | 2014-08-28 09:43:34 -0600 | [diff] [blame] | 259 | base = self.BRIGHT_START if bright else self.NORMAL_START |
Simon Glass | 2027ddd | 2025-04-29 07:22:02 -0600 | [diff] [blame^] | 260 | extra = self.BACK_EXTRA % (back + 40) if back else '' |
| 261 | return base % (color + 30, extra) |
Simon Glass | 381fad8 | 2014-08-28 09:43:34 -0600 | [diff] [blame] | 262 | return '' |
Simon Glass | 2613288 | 2012-01-14 15:12:45 +0000 | [diff] [blame] | 263 | |
Simon Glass | 0281158 | 2022-01-29 14:14:18 -0700 | [diff] [blame] | 264 | def stop(self): |
Anatolij Gustschin | f2bcb32 | 2019-10-27 17:55:04 +0100 | [diff] [blame] | 265 | """Returns a stop color code. |
Simon Glass | 2613288 | 2012-01-14 15:12:45 +0000 | [diff] [blame] | 266 | |
Simon Glass | 381fad8 | 2014-08-28 09:43:34 -0600 | [diff] [blame] | 267 | Returns: |
| 268 | If color is enabled, returns an ANSI color reset sequence, |
| 269 | otherwise returns empty string |
| 270 | """ |
| 271 | if self._enabled: |
| 272 | return self.RESET |
| 273 | return '' |
Simon Glass | 2613288 | 2012-01-14 15:12:45 +0000 | [diff] [blame] | 274 | |
Simon Glass | 2027ddd | 2025-04-29 07:22:02 -0600 | [diff] [blame^] | 275 | def build(self, color, text, bright=True, back=None): |
Simon Glass | 381fad8 | 2014-08-28 09:43:34 -0600 | [diff] [blame] | 276 | """Returns text with conditionally added color escape sequences. |
Simon Glass | 2613288 | 2012-01-14 15:12:45 +0000 | [diff] [blame] | 277 | |
Simon Glass | 381fad8 | 2014-08-28 09:43:34 -0600 | [diff] [blame] | 278 | Keyword arguments: |
| 279 | color: Text color -- one of the color constants defined in this |
| 280 | class. |
| 281 | text: The text to color. |
Simon Glass | 2613288 | 2012-01-14 15:12:45 +0000 | [diff] [blame] | 282 | |
Simon Glass | 381fad8 | 2014-08-28 09:43:34 -0600 | [diff] [blame] | 283 | Returns: |
| 284 | If self._enabled is False, returns the original text. If it's True, |
| 285 | returns text with color escape sequences based on the value of |
| 286 | color. |
| 287 | """ |
| 288 | if not self._enabled: |
| 289 | return text |
Simon Glass | 2027ddd | 2025-04-29 07:22:02 -0600 | [diff] [blame^] | 290 | return self.start(color, bright, back) + text + self.RESET |
Simon Glass | 14d64e3 | 2025-04-29 07:21:59 -0600 | [diff] [blame] | 291 | |
| 292 | |
| 293 | # Use this to suppress stdout/stderr output: |
| 294 | # with terminal.capture() as (stdout, stderr) |
| 295 | # ...do something... |
| 296 | @contextmanager |
| 297 | def capture(): |
Simon Glass | e884498 | 2025-04-29 07:22:01 -0600 | [diff] [blame] | 298 | global CAPTURING |
| 299 | |
Simon Glass | 14d64e3 | 2025-04-29 07:21:59 -0600 | [diff] [blame] | 300 | capture_out, capture_err = StringIO(), StringIO() |
| 301 | old_out, old_err = sys.stdout, sys.stderr |
| 302 | try: |
Simon Glass | e884498 | 2025-04-29 07:22:01 -0600 | [diff] [blame] | 303 | CAPTURING = True |
Simon Glass | 14d64e3 | 2025-04-29 07:21:59 -0600 | [diff] [blame] | 304 | sys.stdout, sys.stderr = capture_out, capture_err |
| 305 | yield capture_out, capture_err |
| 306 | finally: |
| 307 | sys.stdout, sys.stderr = old_out, old_err |
Simon Glass | e884498 | 2025-04-29 07:22:01 -0600 | [diff] [blame] | 308 | CAPTURING = False |
| 309 | if not USE_CAPTURE: |
| 310 | sys.stdout.write(capture_out.getvalue()) |
| 311 | sys.stderr.write(capture_err.getvalue()) |