|
1 # Copyright 2009 the Melange authors. |
|
2 # |
|
3 # Licensed under the Apache License, Version 2.0 (the "License"); |
|
4 # you may not use this file except in compliance with the License. |
|
5 # You may obtain a copy of the License at |
|
6 # |
|
7 # http://www.apache.org/licenses/LICENSE-2.0 |
|
8 # |
|
9 # Unless required by applicable law or agreed to in writing, software |
|
10 # distributed under the License is distributed on an "AS IS" BASIS, |
|
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
|
12 # See the License for the specific language governing permissions and |
|
13 # limitations under the License. |
|
14 |
|
15 """Various utilities. |
|
16 |
|
17 Current contents: |
|
18 - Text colorization using ANSI color codes |
|
19 """ |
|
20 |
|
21 __authors__ = [ |
|
22 # alphabetical order by last name, please |
|
23 '"David Anderson" <dave@natulte.net>', |
|
24 ] |
|
25 |
|
26 # The magic escape sequence understood by modern terminal emulators to |
|
27 # configure fore/background colors and other basic text display |
|
28 # settings. |
|
29 _ANSI_ESCAPE = '\x1b[%dm' |
|
30 |
|
31 |
|
32 # Some intrnal non-color settings that we use. |
|
33 _RESET = 0 # Reset to terminal defaults. |
|
34 _BOLD = 1 # Brighter colors. |
|
35 |
|
36 |
|
37 # ANSI color codes. |
|
38 RED = 31 |
|
39 GREEN = 32 |
|
40 WHITE = 37 |
|
41 |
|
42 |
|
43 def _ansi_escape(code): |
|
44 return _ANSI_ESCAPE % code |
|
45 |
|
46 |
|
47 def colorize(text, color, bold=False): |
|
48 """Colorize some text using ANSI color codes. |
|
49 |
|
50 Note that while ANSI color codes look good in a terminal they look |
|
51 like noise in log files unless viewed in an ANSI color capable |
|
52 viewer (such as 'less -R'). |
|
53 |
|
54 Args: |
|
55 text: The text to colorize. |
|
56 color: One of the color symbols from this module. |
|
57 bold: If True, make the color brighter. |
|
58 |
|
59 Returns: |
|
60 The input text string, appropriately sprinkled with color |
|
61 codes. Colors are reset to terminal defaults after the input |
|
62 text. |
|
63 """ |
|
64 bold = _ansi_escape(_BOLD) if bold else '' |
|
65 return '%s%s%s%s' % (bold, _ansi_escape(color), |
|
66 text, _ansi_escape(_RESET)) |