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', 'info', 'warning', 'error', 'ask']
25 INFO_COLOR = 32 # green
26 WARN_COLOR = 33 # yellow
31 PREFIX_RE = re.compile('^<(.*?)>\s*(.*)')
35 def _color_print(head, color, msg = None, stream = sys.stdout):
38 if color == NO_COLOR or \
39 not stream.isatty() or \
40 os.getenv('ANSI_COLORS_DISABLED') is not None:
43 if head.startswith('\r'):
50 head = '\033[%dm%s:\033[0m ' %(color, head)
52 # ESC cmd to clear line
53 head = '\033[2K' + head
59 stream.write('%s%s' % (head, msg))
63 stream.write('%s ' % head)
67 def _color_perror(head, color, msg):
68 _color_print(head, color, msg, sys.stderr)
70 def _split_msg(head, msg):
71 if msg.startswith('\n'):
72 # means print \n at first
76 elif msg.startswith('\r'):
77 # means print \r at first
81 m = PREFIX_RE.match(msg)
83 head += ' <%s>' % m.group(1)
88 def set_mode(interactive):
96 head, msg = _split_msg('', msg)
97 _color_print(head, NO_COLOR, msg)
100 head, msg = _split_msg('Info', msg)
101 _color_print(head, INFO_COLOR, msg)
104 head, msg = _split_msg('Warning', msg)
105 _color_perror(head, WARN_COLOR, msg)
108 head, msg = _split_msg('Error', msg)
109 _color_perror(head, ERR_COLOR, msg)
112 def ask(msg, default=True):
113 _color_print('Q', ASK_COLOR, '')
120 repl = raw_input(msg)
121 if repl.lower() == 'y':
123 elif repl.lower() == 'n':
129 sys.stdout.write('%s ' % msg)
131 sys.stdout.write('Y\n')
133 sys.stdout.write('N\n')
135 except KeyboardInterrupt:
136 sys.stdout.write('\n')