1 # Copyright (c) 2011 The Chromium OS Authors.
3 # See file CREDITS for list of people who contributed to this
6 # This program is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU General Public License as
8 # published by the Free Software Foundation; either version 2 of
9 # the License, or (at your option) any later version.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston,
24 This module handles terminal interaction including ANSI color codes.
28 """Conditionally wraps text in ANSI color escape sequences."""
29 BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
31 COLOR_START = '\033[1;%dm'
32 BOLD_START = '\033[1m'
35 def __init__(self, enabled=True):
36 """Create a new Color object, optionally disabling color output.
39 enabled: True if color output should be enabled. If False then this
40 class will not add color codes at all.
42 self._enabled = enabled
44 def Start(self, color):
45 """Returns a start color code.
48 color: Color to use, .e.g BLACK, RED, etc.
51 If color is enabled, returns an ANSI sequence to start the given color,
52 otherwise returns empty string
55 return self.COLOR_START % (color + 30)
59 """Retruns a stop color code.
62 If color is enabled, returns an ANSI color reset sequence, otherwise
69 def Color(self, color, text):
70 """Returns text with conditionally added color escape sequences.
73 color: Text color -- one of the color constants defined in this class.
74 text: The text to color.
77 If self._enabled is False, returns the original text. If it's True,
78 returns text with color escape sequences based on the value of color.
82 if color == self.BOLD:
83 start = self.BOLD_START
85 start = self.COLOR_START % (color + 30)
86 return start + text + self.RESET