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 | 0281158 | 2022-01-29 14:14:18 -0700 | [diff] [blame] | 142 | def tprint(text='', newline=True, colour=None, limit_to_line=False, bright=True): |
Simon Glass | fb35f9f | 2014-09-05 19:00:06 -0600 | [diff] [blame] | 143 | """Handle a line of output to the terminal. |
| 144 | |
| 145 | In test mode this is recorded in a list. Otherwise it is output to the |
| 146 | terminal. |
| 147 | |
| 148 | Args: |
| 149 | text: Text to print |
| 150 | newline: True to add a new line at the end of the text |
| 151 | colour: Colour to use for the text |
| 152 | """ |
Simon Glass | 5f9325d | 2020-04-09 15:08:40 -0600 | [diff] [blame] | 153 | global last_print_len |
| 154 | |
Simon Glass | fb35f9f | 2014-09-05 19:00:06 -0600 | [diff] [blame] | 155 | if print_test_mode: |
Simon Glass | 3db916d | 2020-10-29 21:46:35 -0600 | [diff] [blame] | 156 | print_test_list.append(PrintLine(text, colour, newline, bright)) |
Simon Glass | fb35f9f | 2014-09-05 19:00:06 -0600 | [diff] [blame] | 157 | else: |
| 158 | if colour: |
| 159 | col = Color() |
Simon Glass | f45d374 | 2022-01-29 14:14:17 -0700 | [diff] [blame] | 160 | text = col.build(colour, text, bright=bright) |
Simon Glass | fb35f9f | 2014-09-05 19:00:06 -0600 | [diff] [blame] | 161 | if newline: |
Simon Glass | 82e4c64 | 2020-04-09 15:08:39 -0600 | [diff] [blame] | 162 | print(text) |
Simon Glass | 5f9325d | 2020-04-09 15:08:40 -0600 | [diff] [blame] | 163 | last_print_len = None |
Simon Glass | 9c45a4e | 2016-09-18 16:48:30 -0600 | [diff] [blame] | 164 | else: |
Simon Glass | bbde053 | 2020-04-09 15:08:41 -0600 | [diff] [blame] | 165 | if limit_to_line: |
| 166 | cols = shutil.get_terminal_size().columns |
Simon Glass | 0281158 | 2022-01-29 14:14:18 -0700 | [diff] [blame] | 167 | text = trim_ascii_len(text, cols) |
Simon Glass | 82e4c64 | 2020-04-09 15:08:39 -0600 | [diff] [blame] | 168 | print(text, end='', flush=True) |
Simon Glass | 0281158 | 2022-01-29 14:14:18 -0700 | [diff] [blame] | 169 | last_print_len = calc_ascii_len(text) |
Simon Glass | 5f9325d | 2020-04-09 15:08:40 -0600 | [diff] [blame] | 170 | |
Simon Glass | 0281158 | 2022-01-29 14:14:18 -0700 | [diff] [blame] | 171 | def print_clear(): |
Simon Glass | 5f9325d | 2020-04-09 15:08:40 -0600 | [diff] [blame] | 172 | """Clear a previously line that was printed with no newline""" |
| 173 | global last_print_len |
| 174 | |
| 175 | if last_print_len: |
Simon Glass | c229d32 | 2024-06-23 11:55:15 -0600 | [diff] [blame] | 176 | if print_test_mode: |
| 177 | print_test_list.append(PrintLine(None, None, None, None)) |
| 178 | else: |
| 179 | print('\r%s\r' % (' '* last_print_len), end='', flush=True) |
| 180 | last_print_len = None |
Simon Glass | fb35f9f | 2014-09-05 19:00:06 -0600 | [diff] [blame] | 181 | |
Simon Glass | 0281158 | 2022-01-29 14:14:18 -0700 | [diff] [blame] | 182 | def set_print_test_mode(enable=True): |
Simon Glass | fb35f9f | 2014-09-05 19:00:06 -0600 | [diff] [blame] | 183 | """Go into test mode, where all printing is recorded""" |
| 184 | global print_test_mode |
| 185 | |
Simon Glass | 3db916d | 2020-10-29 21:46:35 -0600 | [diff] [blame] | 186 | print_test_mode = enable |
Simon Glass | 0281158 | 2022-01-29 14:14:18 -0700 | [diff] [blame] | 187 | get_print_test_lines() |
Simon Glass | fb35f9f | 2014-09-05 19:00:06 -0600 | [diff] [blame] | 188 | |
Simon Glass | 0281158 | 2022-01-29 14:14:18 -0700 | [diff] [blame] | 189 | def get_print_test_lines(): |
| 190 | """Get a list of all lines output through tprint() |
Simon Glass | fb35f9f | 2014-09-05 19:00:06 -0600 | [diff] [blame] | 191 | |
| 192 | Returns: |
| 193 | A list of PrintLine objects |
| 194 | """ |
| 195 | global print_test_list |
| 196 | |
| 197 | ret = print_test_list |
| 198 | print_test_list = [] |
| 199 | return ret |
| 200 | |
Simon Glass | 0281158 | 2022-01-29 14:14:18 -0700 | [diff] [blame] | 201 | def echo_print_test_lines(): |
Simon Glass | fb35f9f | 2014-09-05 19:00:06 -0600 | [diff] [blame] | 202 | """Print out the text lines collected""" |
| 203 | for line in print_test_list: |
| 204 | if line.colour: |
| 205 | col = Color() |
Simon Glass | f45d374 | 2022-01-29 14:14:17 -0700 | [diff] [blame] | 206 | print(col.build(line.colour, line.text), end='') |
Simon Glass | fb35f9f | 2014-09-05 19:00:06 -0600 | [diff] [blame] | 207 | else: |
Paul Burton | c393134 | 2016-09-27 16:03:50 +0100 | [diff] [blame] | 208 | print(line.text, end='') |
Simon Glass | fb35f9f | 2014-09-05 19:00:06 -0600 | [diff] [blame] | 209 | if line.newline: |
Paul Burton | c393134 | 2016-09-27 16:03:50 +0100 | [diff] [blame] | 210 | print() |
Simon Glass | fb35f9f | 2014-09-05 19:00:06 -0600 | [diff] [blame] | 211 | |
| 212 | |
Simon Glass | 2613288 | 2012-01-14 15:12:45 +0000 | [diff] [blame] | 213 | class Color(object): |
Simon Glass | 381fad8 | 2014-08-28 09:43:34 -0600 | [diff] [blame] | 214 | """Conditionally wraps text in ANSI color escape sequences.""" |
| 215 | BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8) |
| 216 | BOLD = -1 |
| 217 | BRIGHT_START = '\033[1;%dm' |
| 218 | NORMAL_START = '\033[22;%dm' |
| 219 | BOLD_START = '\033[1m' |
| 220 | RESET = '\033[0m' |
Simon Glass | 2613288 | 2012-01-14 15:12:45 +0000 | [diff] [blame] | 221 | |
Simon Glass | 381fad8 | 2014-08-28 09:43:34 -0600 | [diff] [blame] | 222 | def __init__(self, colored=COLOR_IF_TERMINAL): |
| 223 | """Create a new Color object, optionally disabling color output. |
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 | Args: |
| 226 | enabled: True if color output should be enabled. If False then this |
| 227 | class will not add color codes at all. |
| 228 | """ |
Simon Glass | b0cd341 | 2014-08-28 09:43:35 -0600 | [diff] [blame] | 229 | try: |
| 230 | self._enabled = (colored == COLOR_ALWAYS or |
| 231 | (colored == COLOR_IF_TERMINAL and |
| 232 | os.isatty(sys.stdout.fileno()))) |
| 233 | except: |
| 234 | self._enabled = False |
Simon Glass | 2613288 | 2012-01-14 15:12:45 +0000 | [diff] [blame] | 235 | |
Simon Glass | 0281158 | 2022-01-29 14:14:18 -0700 | [diff] [blame] | 236 | def start(self, color, bright=True): |
Simon Glass | 381fad8 | 2014-08-28 09:43:34 -0600 | [diff] [blame] | 237 | """Returns a start color code. |
Simon Glass | 2613288 | 2012-01-14 15:12:45 +0000 | [diff] [blame] | 238 | |
Simon Glass | 381fad8 | 2014-08-28 09:43:34 -0600 | [diff] [blame] | 239 | Args: |
| 240 | color: Color to use, .e.g BLACK, RED, etc. |
Simon Glass | 2613288 | 2012-01-14 15:12:45 +0000 | [diff] [blame] | 241 | |
Simon Glass | 381fad8 | 2014-08-28 09:43:34 -0600 | [diff] [blame] | 242 | Returns: |
| 243 | If color is enabled, returns an ANSI sequence to start the given |
| 244 | color, otherwise returns empty string |
| 245 | """ |
| 246 | if self._enabled: |
| 247 | base = self.BRIGHT_START if bright else self.NORMAL_START |
| 248 | return base % (color + 30) |
| 249 | return '' |
Simon Glass | 2613288 | 2012-01-14 15:12:45 +0000 | [diff] [blame] | 250 | |
Simon Glass | 0281158 | 2022-01-29 14:14:18 -0700 | [diff] [blame] | 251 | def stop(self): |
Anatolij Gustschin | f2bcb32 | 2019-10-27 17:55:04 +0100 | [diff] [blame] | 252 | """Returns a stop color code. |
Simon Glass | 2613288 | 2012-01-14 15:12:45 +0000 | [diff] [blame] | 253 | |
Simon Glass | 381fad8 | 2014-08-28 09:43:34 -0600 | [diff] [blame] | 254 | Returns: |
| 255 | If color is enabled, returns an ANSI color reset sequence, |
| 256 | otherwise returns empty string |
| 257 | """ |
| 258 | if self._enabled: |
| 259 | return self.RESET |
| 260 | return '' |
Simon Glass | 2613288 | 2012-01-14 15:12:45 +0000 | [diff] [blame] | 261 | |
Simon Glass | f45d374 | 2022-01-29 14:14:17 -0700 | [diff] [blame] | 262 | def build(self, color, text, bright=True): |
Simon Glass | 381fad8 | 2014-08-28 09:43:34 -0600 | [diff] [blame] | 263 | """Returns text with conditionally added color escape sequences. |
Simon Glass | 2613288 | 2012-01-14 15:12:45 +0000 | [diff] [blame] | 264 | |
Simon Glass | 381fad8 | 2014-08-28 09:43:34 -0600 | [diff] [blame] | 265 | Keyword arguments: |
| 266 | color: Text color -- one of the color constants defined in this |
| 267 | class. |
| 268 | text: The text to color. |
Simon Glass | 2613288 | 2012-01-14 15:12:45 +0000 | [diff] [blame] | 269 | |
Simon Glass | 381fad8 | 2014-08-28 09:43:34 -0600 | [diff] [blame] | 270 | Returns: |
| 271 | If self._enabled is False, returns the original text. If it's True, |
| 272 | returns text with color escape sequences based on the value of |
| 273 | color. |
| 274 | """ |
| 275 | if not self._enabled: |
| 276 | return text |
| 277 | if color == self.BOLD: |
| 278 | start = self.BOLD_START |
| 279 | else: |
| 280 | base = self.BRIGHT_START if bright else self.NORMAL_START |
| 281 | start = base % (color + 30) |
| 282 | return start + text + self.RESET |
Simon Glass | 14d64e3 | 2025-04-29 07:21:59 -0600 | [diff] [blame] | 283 | |
| 284 | |
| 285 | # Use this to suppress stdout/stderr output: |
| 286 | # with terminal.capture() as (stdout, stderr) |
| 287 | # ...do something... |
| 288 | @contextmanager |
| 289 | def capture(): |
Simon Glass | e884498 | 2025-04-29 07:22:01 -0600 | [diff] [blame^] | 290 | global CAPTURING |
| 291 | |
Simon Glass | 14d64e3 | 2025-04-29 07:21:59 -0600 | [diff] [blame] | 292 | capture_out, capture_err = StringIO(), StringIO() |
| 293 | old_out, old_err = sys.stdout, sys.stderr |
| 294 | try: |
Simon Glass | e884498 | 2025-04-29 07:22:01 -0600 | [diff] [blame^] | 295 | CAPTURING = True |
Simon Glass | 14d64e3 | 2025-04-29 07:21:59 -0600 | [diff] [blame] | 296 | sys.stdout, sys.stderr = capture_out, capture_err |
| 297 | yield capture_out, capture_err |
| 298 | finally: |
| 299 | sys.stdout, sys.stderr = old_out, old_err |
Simon Glass | e884498 | 2025-04-29 07:22:01 -0600 | [diff] [blame^] | 300 | CAPTURING = False |
| 301 | if not USE_CAPTURE: |
| 302 | sys.stdout.write(capture_out.getvalue()) |
| 303 | sys.stderr.write(capture_err.getvalue()) |