blob: 69c183e85e5286efa49f762be4b000cb57c957f8 [file] [log] [blame]
Tom Rini10e47792018-05-06 17:58:06 -04001# SPDX-License-Identifier: GPL-2.0+
Simon Glass26132882012-01-14 15:12:45 +00002# Copyright (c) 2011 The Chromium OS Authors.
3#
Simon Glass26132882012-01-14 15:12:45 +00004
5"""Terminal utilities
6
7This module handles terminal interaction including ANSI color codes.
8"""
9
Simon Glass14d64e32025-04-29 07:21:59 -060010from contextlib import contextmanager
11from io import StringIO
Simon Glassa9f7edb2012-12-15 10:42:01 +000012import os
Simon Glass5f9325d2020-04-09 15:08:40 -060013import re
Simon Glassbbde0532020-04-09 15:08:41 -060014import shutil
Simon Glasse46c9cf2025-04-29 07:22:03 -060015import subprocess
Simon Glassa9f7edb2012-12-15 10:42:01 +000016import sys
17
18# Selection of when we want our output to be colored
19COLOR_IF_TERMINAL, COLOR_ALWAYS, COLOR_NEVER = range(3)
20
Simon Glassfb35f9f2014-09-05 19:00:06 -060021# Initially, we are set up to print to the terminal
22print_test_mode = False
23print_test_list = []
24
Simon Glass5f9325d2020-04-09 15:08:40 -060025# The length of the last line printed without a newline
26last_print_len = None
27
28# credit:
29# stackoverflow.com/questions/14693701/how-can-i-remove-the-ansi-escape-sequences-from-a-string-in-python
30ansi_escape = re.compile(r'\x1b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
31
Simon Glasse8844982025-04-29 07:22:01 -060032# True if we are capturing console output
33CAPTURING = False
34
35# Set this to False to disable output-capturing globally
36USE_CAPTURE = True
37
38
Simon Glassfb35f9f2014-09-05 19:00:06 -060039class PrintLine:
40 """A line of text output
41
42 Members:
43 text: Text line that was printed
44 newline: True to output a newline after the text
45 colour: Text colour to use
46 """
Simon Glass3db916d2020-10-29 21:46:35 -060047 def __init__(self, text, colour, newline=True, bright=True):
Simon Glassfb35f9f2014-09-05 19:00:06 -060048 self.text = text
49 self.newline = newline
50 self.colour = colour
Simon Glass3db916d2020-10-29 21:46:35 -060051 self.bright = bright
52
53 def __eq__(self, other):
54 return (self.text == other.text and
55 self.newline == other.newline and
56 self.colour == other.colour and
57 self.bright == other.bright)
Simon Glassfb35f9f2014-09-05 19:00:06 -060058
59 def __str__(self):
Simon Glass3db916d2020-10-29 21:46:35 -060060 return ("newline=%s, colour=%s, bright=%d, text='%s'" %
61 (self.newline, self.colour, self.bright, self.text))
62
Simon Glassfb35f9f2014-09-05 19:00:06 -060063
Simon Glass02811582022-01-29 14:14:18 -070064def calc_ascii_len(text):
Simon Glass5f9325d2020-04-09 15:08:40 -060065 """Calculate the length of a string, ignoring any ANSI sequences
66
Simon Glassbbde0532020-04-09 15:08:41 -060067 When displayed on a terminal, ANSI sequences don't take any space, so we
68 need to ignore them when calculating the length of a string.
69
Simon Glass5f9325d2020-04-09 15:08:40 -060070 Args:
71 text: Text to check
72
73 Returns:
74 Length of text, after skipping ANSI sequences
75
76 >>> col = Color(COLOR_ALWAYS)
Simon Glassf45d3742022-01-29 14:14:17 -070077 >>> text = col.build(Color.RED, 'abc')
Simon Glass5f9325d2020-04-09 15:08:40 -060078 >>> len(text)
79 14
Simon Glass02811582022-01-29 14:14:18 -070080 >>> calc_ascii_len(text)
Simon Glass5f9325d2020-04-09 15:08:40 -060081 3
82 >>>
83 >>> text += 'def'
Simon Glass02811582022-01-29 14:14:18 -070084 >>> calc_ascii_len(text)
Simon Glass5f9325d2020-04-09 15:08:40 -060085 6
Simon Glassf45d3742022-01-29 14:14:17 -070086 >>> text += col.build(Color.RED, 'abc')
Simon Glass02811582022-01-29 14:14:18 -070087 >>> calc_ascii_len(text)
Simon Glass5f9325d2020-04-09 15:08:40 -060088 9
89 """
90 result = ansi_escape.sub('', text)
91 return len(result)
92
Simon Glass02811582022-01-29 14:14:18 -070093def trim_ascii_len(text, size):
Simon Glassbbde0532020-04-09 15:08:41 -060094 """Trim a string containing ANSI sequences to the given ASCII length
95
96 The string is trimmed with ANSI sequences being ignored for the length
97 calculation.
98
99 >>> col = Color(COLOR_ALWAYS)
Simon Glassf45d3742022-01-29 14:14:17 -0700100 >>> text = col.build(Color.RED, 'abc')
Simon Glassbbde0532020-04-09 15:08:41 -0600101 >>> len(text)
102 14
Simon Glass02811582022-01-29 14:14:18 -0700103 >>> calc_ascii_len(trim_ascii_len(text, 4))
Simon Glassbbde0532020-04-09 15:08:41 -0600104 3
Simon Glass02811582022-01-29 14:14:18 -0700105 >>> calc_ascii_len(trim_ascii_len(text, 2))
Simon Glassbbde0532020-04-09 15:08:41 -0600106 2
107 >>> text += 'def'
Simon Glass02811582022-01-29 14:14:18 -0700108 >>> calc_ascii_len(trim_ascii_len(text, 4))
Simon Glassbbde0532020-04-09 15:08:41 -0600109 4
Simon Glassf45d3742022-01-29 14:14:17 -0700110 >>> text += col.build(Color.RED, 'ghi')
Simon Glass02811582022-01-29 14:14:18 -0700111 >>> calc_ascii_len(trim_ascii_len(text, 7))
Simon Glassbbde0532020-04-09 15:08:41 -0600112 7
113 """
Simon Glass02811582022-01-29 14:14:18 -0700114 if calc_ascii_len(text) < size:
Simon Glassbbde0532020-04-09 15:08:41 -0600115 return text
116 pos = 0
117 out = ''
118 left = size
119
120 # Work through each ANSI sequence in turn
121 for m in ansi_escape.finditer(text):
122 # Find the text before the sequence and add it to our string, making
123 # sure it doesn't overflow
124 before = text[pos:m.start()]
125 toadd = before[:left]
126 out += toadd
127
128 # Figure out how much non-ANSI space we have left
129 left -= len(toadd)
130
131 # Add the ANSI sequence and move to the position immediately after it
132 out += m.group()
133 pos = m.start() + len(m.group())
134
135 # Deal with text after the last ANSI sequence
136 after = text[pos:]
137 toadd = after[:left]
138 out += toadd
139
140 return out
141
Simon Glass5f9325d2020-04-09 15:08:40 -0600142
Simon Glass2027ddd2025-04-29 07:22:02 -0600143def tprint(text='', newline=True, colour=None, limit_to_line=False,
144 bright=True, back=None, col=None):
Simon Glassfb35f9f2014-09-05 19:00:06 -0600145 """Handle a line of output to the terminal.
146
147 In test mode this is recorded in a list. Otherwise it is output to the
148 terminal.
149
150 Args:
151 text: Text to print
152 newline: True to add a new line at the end of the text
153 colour: Colour to use for the text
154 """
Simon Glass5f9325d2020-04-09 15:08:40 -0600155 global last_print_len
156
Simon Glassfb35f9f2014-09-05 19:00:06 -0600157 if print_test_mode:
Simon Glass3db916d2020-10-29 21:46:35 -0600158 print_test_list.append(PrintLine(text, colour, newline, bright))
Simon Glassfb35f9f2014-09-05 19:00:06 -0600159 else:
Simon Glass2027ddd2025-04-29 07:22:02 -0600160 if colour is not None:
161 if not col:
162 col = Color()
163 text = col.build(colour, text, bright=bright, back=back)
Simon Glassfb35f9f2014-09-05 19:00:06 -0600164 if newline:
Simon Glass82e4c642020-04-09 15:08:39 -0600165 print(text)
Simon Glass5f9325d2020-04-09 15:08:40 -0600166 last_print_len = None
Simon Glass9c45a4e2016-09-18 16:48:30 -0600167 else:
Simon Glassbbde0532020-04-09 15:08:41 -0600168 if limit_to_line:
169 cols = shutil.get_terminal_size().columns
Simon Glass02811582022-01-29 14:14:18 -0700170 text = trim_ascii_len(text, cols)
Simon Glass82e4c642020-04-09 15:08:39 -0600171 print(text, end='', flush=True)
Simon Glass02811582022-01-29 14:14:18 -0700172 last_print_len = calc_ascii_len(text)
Simon Glass5f9325d2020-04-09 15:08:40 -0600173
Simon Glass02811582022-01-29 14:14:18 -0700174def print_clear():
Simon Glass5f9325d2020-04-09 15:08:40 -0600175 """Clear a previously line that was printed with no newline"""
176 global last_print_len
177
178 if last_print_len:
Simon Glassc229d322024-06-23 11:55:15 -0600179 if print_test_mode:
180 print_test_list.append(PrintLine(None, None, None, None))
181 else:
182 print('\r%s\r' % (' '* last_print_len), end='', flush=True)
183 last_print_len = None
Simon Glassfb35f9f2014-09-05 19:00:06 -0600184
Simon Glass02811582022-01-29 14:14:18 -0700185def set_print_test_mode(enable=True):
Simon Glassfb35f9f2014-09-05 19:00:06 -0600186 """Go into test mode, where all printing is recorded"""
187 global print_test_mode
188
Simon Glass3db916d2020-10-29 21:46:35 -0600189 print_test_mode = enable
Simon Glass02811582022-01-29 14:14:18 -0700190 get_print_test_lines()
Simon Glassfb35f9f2014-09-05 19:00:06 -0600191
Simon Glass02811582022-01-29 14:14:18 -0700192def get_print_test_lines():
193 """Get a list of all lines output through tprint()
Simon Glassfb35f9f2014-09-05 19:00:06 -0600194
195 Returns:
196 A list of PrintLine objects
197 """
198 global print_test_list
199
200 ret = print_test_list
201 print_test_list = []
202 return ret
203
Simon Glass02811582022-01-29 14:14:18 -0700204def echo_print_test_lines():
Simon Glassfb35f9f2014-09-05 19:00:06 -0600205 """Print out the text lines collected"""
206 for line in print_test_list:
207 if line.colour:
208 col = Color()
Simon Glassf45d3742022-01-29 14:14:17 -0700209 print(col.build(line.colour, line.text), end='')
Simon Glassfb35f9f2014-09-05 19:00:06 -0600210 else:
Paul Burtonc3931342016-09-27 16:03:50 +0100211 print(line.text, end='')
Simon Glassfb35f9f2014-09-05 19:00:06 -0600212 if line.newline:
Paul Burtonc3931342016-09-27 16:03:50 +0100213 print()
Simon Glassfb35f9f2014-09-05 19:00:06 -0600214
Simon Glasse46c9cf2025-04-29 07:22:03 -0600215def have_terminal():
216 """Check if we have an interactive terminal or not
Simon Glassfb35f9f2014-09-05 19:00:06 -0600217
Simon Glasse46c9cf2025-04-29 07:22:03 -0600218 Returns:
219 bool: true if an interactive terminal is attached
220 """
221 return os.isatty(sys.stdout.fileno())
222
223
224class Color():
Simon Glass381fad82014-08-28 09:43:34 -0600225 """Conditionally wraps text in ANSI color escape sequences."""
226 BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
227 BOLD = -1
Simon Glass2027ddd2025-04-29 07:22:02 -0600228 BRIGHT_START = '\033[1;%d%sm'
229 NORMAL_START = '\033[22;%d%sm'
Simon Glass381fad82014-08-28 09:43:34 -0600230 BOLD_START = '\033[1m'
Simon Glass2027ddd2025-04-29 07:22:02 -0600231 BACK_EXTRA = ';%d'
Simon Glass381fad82014-08-28 09:43:34 -0600232 RESET = '\033[0m'
Simon Glass26132882012-01-14 15:12:45 +0000233
Simon Glass381fad82014-08-28 09:43:34 -0600234 def __init__(self, colored=COLOR_IF_TERMINAL):
235 """Create a new Color object, optionally disabling color output.
Simon Glass26132882012-01-14 15:12:45 +0000236
Simon Glass381fad82014-08-28 09:43:34 -0600237 Args:
238 enabled: True if color output should be enabled. If False then this
239 class will not add color codes at all.
240 """
Simon Glassb0cd3412014-08-28 09:43:35 -0600241 try:
242 self._enabled = (colored == COLOR_ALWAYS or
243 (colored == COLOR_IF_TERMINAL and
244 os.isatty(sys.stdout.fileno())))
245 except:
246 self._enabled = False
Simon Glass26132882012-01-14 15:12:45 +0000247
Simon Glass2027ddd2025-04-29 07:22:02 -0600248 def enabled(self):
249 """Check if colour is enabled
250
251 Return: True if enabled, else False
252 """
253 return self._enabled
254
255 def start(self, color, bright=True, back=None):
Simon Glass381fad82014-08-28 09:43:34 -0600256 """Returns a start color code.
Simon Glass26132882012-01-14 15:12:45 +0000257
Simon Glass381fad82014-08-28 09:43:34 -0600258 Args:
259 color: Color to use, .e.g BLACK, RED, etc.
Simon Glass26132882012-01-14 15:12:45 +0000260
Simon Glass381fad82014-08-28 09:43:34 -0600261 Returns:
262 If color is enabled, returns an ANSI sequence to start the given
263 color, otherwise returns empty string
264 """
265 if self._enabled:
Simon Glass2027ddd2025-04-29 07:22:02 -0600266 if color == self.BOLD:
267 return self.BOLD_START
Simon Glass381fad82014-08-28 09:43:34 -0600268 base = self.BRIGHT_START if bright else self.NORMAL_START
Simon Glass2027ddd2025-04-29 07:22:02 -0600269 extra = self.BACK_EXTRA % (back + 40) if back else ''
270 return base % (color + 30, extra)
Simon Glass381fad82014-08-28 09:43:34 -0600271 return ''
Simon Glass26132882012-01-14 15:12:45 +0000272
Simon Glass02811582022-01-29 14:14:18 -0700273 def stop(self):
Anatolij Gustschinf2bcb322019-10-27 17:55:04 +0100274 """Returns a stop color code.
Simon Glass26132882012-01-14 15:12:45 +0000275
Simon Glass381fad82014-08-28 09:43:34 -0600276 Returns:
277 If color is enabled, returns an ANSI color reset sequence,
278 otherwise returns empty string
279 """
280 if self._enabled:
281 return self.RESET
282 return ''
Simon Glass26132882012-01-14 15:12:45 +0000283
Simon Glass2027ddd2025-04-29 07:22:02 -0600284 def build(self, color, text, bright=True, back=None):
Simon Glass381fad82014-08-28 09:43:34 -0600285 """Returns text with conditionally added color escape sequences.
Simon Glass26132882012-01-14 15:12:45 +0000286
Simon Glass381fad82014-08-28 09:43:34 -0600287 Keyword arguments:
288 color: Text color -- one of the color constants defined in this
289 class.
290 text: The text to color.
Simon Glass26132882012-01-14 15:12:45 +0000291
Simon Glass381fad82014-08-28 09:43:34 -0600292 Returns:
293 If self._enabled is False, returns the original text. If it's True,
294 returns text with color escape sequences based on the value of
295 color.
296 """
297 if not self._enabled:
298 return text
Simon Glass2027ddd2025-04-29 07:22:02 -0600299 return self.start(color, bright, back) + text + self.RESET
Simon Glass14d64e32025-04-29 07:21:59 -0600300
301
302# Use this to suppress stdout/stderr output:
303# with terminal.capture() as (stdout, stderr)
304# ...do something...
305@contextmanager
306def capture():
Simon Glasse8844982025-04-29 07:22:01 -0600307 global CAPTURING
308
Simon Glass14d64e32025-04-29 07:21:59 -0600309 capture_out, capture_err = StringIO(), StringIO()
310 old_out, old_err = sys.stdout, sys.stderr
311 try:
Simon Glasse8844982025-04-29 07:22:01 -0600312 CAPTURING = True
Simon Glass14d64e32025-04-29 07:21:59 -0600313 sys.stdout, sys.stderr = capture_out, capture_err
314 yield capture_out, capture_err
315 finally:
316 sys.stdout, sys.stderr = old_out, old_err
Simon Glasse8844982025-04-29 07:22:01 -0600317 CAPTURING = False
318 if not USE_CAPTURE:
319 sys.stdout.write(capture_out.getvalue())
320 sys.stderr.write(capture_err.getvalue())
Simon Glasse46c9cf2025-04-29 07:22:03 -0600321
322
323@contextmanager
324def pager():
325 """Simple pager for outputting lots of text
326
327 Usage:
328 with terminal.pager():
329 print(...)
330 """
331 proc = None
332 old_stdout = None
333 try:
334 less = os.getenv('PAGER')
335 if not CAPTURING and less != 'none' and have_terminal():
336 if not less:
337 less = 'less -R --quit-if-one-screen'
338 proc = subprocess.Popen(less, stdin=subprocess.PIPE, text=True,
339 shell=True)
340 old_stdout = sys.stdout
341 sys.stdout = proc.stdin
342 yield
343 finally:
344 if proc:
345 sys.stdout = old_stdout
346 proc.communicate()