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.
15 # Selection of when we want our output to be colored
16 COLOR_IF_TERMINAL, COLOR_ALWAYS, COLOR_NEVER = range(3)
18 # Initially, we are set up to print to the terminal
19 print_test_mode = False
22 # The length of the last line printed without a newline
26 # stackoverflow.com/questions/14693701/how-can-i-remove-the-ansi-escape-sequences-from-a-string-in-python
27 ansi_escape = re.compile(r'\x1b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
30 """A line of text output
33 text: Text line that was printed
34 newline: True to output a newline after the text
35 colour: Text colour to use
37 def __init__(self, text, newline, colour):
39 self.newline = newline
43 return 'newline=%s, colour=%s, text=%s' % (self.newline, self.colour,
46 def CalcAsciiLen(text):
47 """Calculate the length of a string, ignoring any ANSI sequences
49 When displayed on a terminal, ANSI sequences don't take any space, so we
50 need to ignore them when calculating the length of a string.
56 Length of text, after skipping ANSI sequences
58 >>> col = Color(COLOR_ALWAYS)
59 >>> text = col.Color(Color.RED, 'abc')
62 >>> CalcAsciiLen(text)
66 >>> CalcAsciiLen(text)
68 >>> text += col.Color(Color.RED, 'abc')
69 >>> CalcAsciiLen(text)
72 result = ansi_escape.sub('', text)
75 def TrimAsciiLen(text, size):
76 """Trim a string containing ANSI sequences to the given ASCII length
78 The string is trimmed with ANSI sequences being ignored for the length
81 >>> col = Color(COLOR_ALWAYS)
82 >>> text = col.Color(Color.RED, 'abc')
85 >>> CalcAsciiLen(TrimAsciiLen(text, 4))
87 >>> CalcAsciiLen(TrimAsciiLen(text, 2))
90 >>> CalcAsciiLen(TrimAsciiLen(text, 4))
92 >>> text += col.Color(Color.RED, 'ghi')
93 >>> CalcAsciiLen(TrimAsciiLen(text, 7))
96 if CalcAsciiLen(text) < size:
102 # Work through each ANSI sequence in turn
103 for m in ansi_escape.finditer(text):
104 # Find the text before the sequence and add it to our string, making
105 # sure it doesn't overflow
106 before = text[pos:m.start()]
107 toadd = before[:left]
110 # Figure out how much non-ANSI space we have left
113 # Add the ANSI sequence and move to the position immediately after it
115 pos = m.start() + len(m.group())
117 # Deal with text after the last ANSI sequence
125 def Print(text='', newline=True, colour=None, limit_to_line=False):
126 """Handle a line of output to the terminal.
128 In test mode this is recorded in a list. Otherwise it is output to the
133 newline: True to add a new line at the end of the text
134 colour: Colour to use for the text
136 global last_print_len
139 print_test_list.append(PrintLine(text, newline, colour))
143 text = col.Color(colour, text)
146 last_print_len = None
149 cols = shutil.get_terminal_size().columns
150 text = TrimAsciiLen(text, cols)
151 print(text, end='', flush=True)
152 last_print_len = CalcAsciiLen(text)
155 """Clear a previously line that was printed with no newline"""
156 global last_print_len
159 print('\r%s\r' % (' '* last_print_len), end='', flush=True)
160 last_print_len = None
162 def SetPrintTestMode():
163 """Go into test mode, where all printing is recorded"""
164 global print_test_mode
166 print_test_mode = True
168 def GetPrintTestLines():
169 """Get a list of all lines output through Print()
172 A list of PrintLine objects
174 global print_test_list
176 ret = print_test_list
180 def EchoPrintTestLines():
181 """Print out the text lines collected"""
182 for line in print_test_list:
185 print(col.Color(line.colour, line.text), end='')
187 print(line.text, end='')
193 """Conditionally wraps text in ANSI color escape sequences."""
194 BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
196 BRIGHT_START = '\033[1;%dm'
197 NORMAL_START = '\033[22;%dm'
198 BOLD_START = '\033[1m'
201 def __init__(self, colored=COLOR_IF_TERMINAL):
202 """Create a new Color object, optionally disabling color output.
205 enabled: True if color output should be enabled. If False then this
206 class will not add color codes at all.
209 self._enabled = (colored == COLOR_ALWAYS or
210 (colored == COLOR_IF_TERMINAL and
211 os.isatty(sys.stdout.fileno())))
213 self._enabled = False
215 def Start(self, color, bright=True):
216 """Returns a start color code.
219 color: Color to use, .e.g BLACK, RED, etc.
222 If color is enabled, returns an ANSI sequence to start the given
223 color, otherwise returns empty string
226 base = self.BRIGHT_START if bright else self.NORMAL_START
227 return base % (color + 30)
231 """Returns a stop color code.
234 If color is enabled, returns an ANSI color reset sequence,
235 otherwise returns empty string
241 def Color(self, color, text, bright=True):
242 """Returns text with conditionally added color escape sequences.
245 color: Text color -- one of the color constants defined in this
247 text: The text to color.
250 If self._enabled is False, returns the original text. If it's True,
251 returns text with color escape sequences based on the value of
254 if not self._enabled:
256 if color == self.BOLD:
257 start = self.BOLD_START
259 base = self.BRIGHT_START if bright else self.NORMAL_START
260 start = base % (color + 30)
261 return start + text + self.RESET