1 # SPDX-License-Identifier: GPL-2.0+
2 # Copyright (c) 2011 The Chromium OS Authors.
7 This module handles terminal interaction including ANSI color codes.
10 from __future__ import print_function
17 # Selection of when we want our output to be colored
18 COLOR_IF_TERMINAL, COLOR_ALWAYS, COLOR_NEVER = range(3)
20 # Initially, we are set up to print to the terminal
21 print_test_mode = False
24 # The length of the last line printed without a newline
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-?]*[ -/]*[@-~])')
32 """A line of text output
35 text: Text line that was printed
36 newline: True to output a newline after the text
37 colour: Text colour to use
39 def __init__(self, text, newline, colour):
41 self.newline = newline
45 return 'newline=%s, colour=%s, text=%s' % (self.newline, self.colour,
48 def CalcAsciiLen(text):
49 """Calculate the length of a string, ignoring any ANSI sequences
51 When displayed on a terminal, ANSI sequences don't take any space, so we
52 need to ignore them when calculating the length of a string.
58 Length of text, after skipping ANSI sequences
60 >>> col = Color(COLOR_ALWAYS)
61 >>> text = col.Color(Color.RED, 'abc')
64 >>> CalcAsciiLen(text)
68 >>> CalcAsciiLen(text)
70 >>> text += col.Color(Color.RED, 'abc')
71 >>> CalcAsciiLen(text)
74 result = ansi_escape.sub('', text)
77 def TrimAsciiLen(text, size):
78 """Trim a string containing ANSI sequences to the given ASCII length
80 The string is trimmed with ANSI sequences being ignored for the length
83 >>> col = Color(COLOR_ALWAYS)
84 >>> text = col.Color(Color.RED, 'abc')
87 >>> CalcAsciiLen(TrimAsciiLen(text, 4))
89 >>> CalcAsciiLen(TrimAsciiLen(text, 2))
92 >>> CalcAsciiLen(TrimAsciiLen(text, 4))
94 >>> text += col.Color(Color.RED, 'ghi')
95 >>> CalcAsciiLen(TrimAsciiLen(text, 7))
98 if CalcAsciiLen(text) < size:
104 # Work through each ANSI sequence in turn
105 for m in ansi_escape.finditer(text):
106 # Find the text before the sequence and add it to our string, making
107 # sure it doesn't overflow
108 before = text[pos:m.start()]
109 toadd = before[:left]
112 # Figure out how much non-ANSI space we have left
115 # Add the ANSI sequence and move to the position immediately after it
117 pos = m.start() + len(m.group())
119 # Deal with text after the last ANSI sequence
127 def Print(text='', newline=True, colour=None, limit_to_line=False):
128 """Handle a line of output to the terminal.
130 In test mode this is recorded in a list. Otherwise it is output to the
135 newline: True to add a new line at the end of the text
136 colour: Colour to use for the text
138 global last_print_len
141 print_test_list.append(PrintLine(text, newline, colour))
145 text = col.Color(colour, text)
148 last_print_len = None
151 cols = shutil.get_terminal_size().columns
152 text = TrimAsciiLen(text, cols)
153 print(text, end='', flush=True)
154 last_print_len = CalcAsciiLen(text)
157 """Clear a previously line that was printed with no newline"""
158 global last_print_len
161 print('\r%s\r' % (' '* last_print_len), end='', flush=True)
162 last_print_len = None
164 def SetPrintTestMode():
165 """Go into test mode, where all printing is recorded"""
166 global print_test_mode
168 print_test_mode = True
170 def GetPrintTestLines():
171 """Get a list of all lines output through Print()
174 A list of PrintLine objects
176 global print_test_list
178 ret = print_test_list
182 def EchoPrintTestLines():
183 """Print out the text lines collected"""
184 for line in print_test_list:
187 print(col.Color(line.colour, line.text), end='')
189 print(line.text, end='')
195 """Conditionally wraps text in ANSI color escape sequences."""
196 BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
198 BRIGHT_START = '\033[1;%dm'
199 NORMAL_START = '\033[22;%dm'
200 BOLD_START = '\033[1m'
203 def __init__(self, colored=COLOR_IF_TERMINAL):
204 """Create a new Color object, optionally disabling color output.
207 enabled: True if color output should be enabled. If False then this
208 class will not add color codes at all.
211 self._enabled = (colored == COLOR_ALWAYS or
212 (colored == COLOR_IF_TERMINAL and
213 os.isatty(sys.stdout.fileno())))
215 self._enabled = False
217 def Start(self, color, bright=True):
218 """Returns a start color code.
221 color: Color to use, .e.g BLACK, RED, etc.
224 If color is enabled, returns an ANSI sequence to start the given
225 color, otherwise returns empty string
228 base = self.BRIGHT_START if bright else self.NORMAL_START
229 return base % (color + 30)
233 """Returns a stop color code.
236 If color is enabled, returns an ANSI color reset sequence,
237 otherwise returns empty string
243 def Color(self, color, text, bright=True):
244 """Returns text with conditionally added color escape sequences.
247 color: Text color -- one of the color constants defined in this
249 text: The text to color.
252 If self._enabled is False, returns the original text. If it's True,
253 returns text with color escape sequences based on the value of
256 if not self._enabled:
258 if color == self.BOLD:
259 start = self.BOLD_START
261 base = self.BRIGHT_START if bright else self.NORMAL_START
262 start = base % (color + 30)
263 return start + text + self.RESET