2 # vim: ai ts=4 sts=4 et sw=4
4 # Copyright (c) 2009 Intel Corporation
6 # This program is free software; you can redistribute it and/or modify it
7 # under the terms of the GNU General Public License as published by the Free
8 # Software Foundation; version 2 of the License
10 # This program is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc., 59
17 # Temple Place - Suite 330, Boston, MA 02111-1307, USA.
22 __ALL__ = ['set_mode', 'set_loglevel', 'raw' 'debug', 'verbose', 'info', 'warning', 'error', 'ask']
25 INFO_COLOR = 32 # green
26 WARN_COLOR = 33 # yellow
31 PREFIX_RE = re.compile('^<(.*?)>\s*(.*)')
43 def _color_print(head, color, msg = None, stream = sys.stdout, level = 'normal'):
45 if LOG_LEVELS[level] > LOG_LEVEL:
50 if color == NO_COLOR or \
51 not stream.isatty() or \
52 os.getenv('ANSI_COLORS_DISABLED') is not None:
55 if head.startswith('\r'):
62 head = '\033[%dm%s:\033[0m ' %(color, head)
64 # ESC cmd to clear line
65 head = '\033[2K' + head
69 if head.startswith('\r'):
74 stream.write('%s%s' % (head, msg))
80 def _color_perror(head, color, msg, level = 'normal'):
81 _color_print(head, color, msg, sys.stderr, level)
83 def _split_msg(head, msg):
84 if isinstance(msg, list):
85 msg = '\n'.join(map(str, msg))
87 if msg.startswith('\n'):
88 # means print \n at first
92 elif msg.startswith('\r'):
93 # means print \r at first
97 m = PREFIX_RE.match(msg)
99 head += ' <%s>' % m.group(1)
104 def set_loglevel(level):
106 if level not in LOG_LEVELS:
110 LOG_LEVEL = LOG_LEVELS[level]
112 def set_mode(interactive):
122 sys.stdout.write(msg)
123 sys.stdout.write('\n')
126 head, msg = _split_msg('Info', msg)
127 _color_print(head, INFO_COLOR, msg)
130 head, msg = _split_msg('Verbose', msg)
131 _color_print(head, INFO_COLOR, msg, level = 'verbose')
134 head, msg = _split_msg('Warning', msg)
135 _color_perror(head, WARN_COLOR, msg)
138 head, msg = _split_msg('Debug', msg)
139 _color_perror(head, ERR_COLOR, msg, level = 'debug')
142 head, msg = _split_msg('Error', msg)
143 _color_perror(head, ERR_COLOR, msg)
146 def ask(msg, default=True):
147 _color_print('Q', ASK_COLOR, '')
154 repl = raw_input(msg)
155 if repl.lower() == 'y':
157 elif repl.lower() == 'n':
163 sys.stdout.write('%s ' % msg)
165 sys.stdout.write('Y\n')
167 sys.stdout.write('N\n')
169 except KeyboardInterrupt:
170 sys.stdout.write('\n')