Debian Codegraph @

lib/ansible/utils/color.py

raw
1 # (c) 2012-2014, Michael DeHaan <[email protected]>
2 #
3 # This file is part of Ansible
4 #
5 # Ansible is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Ansible is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
17 from __future__ import annotations
18
19 import re
20 import sys
21
22 from ansible import constants as C
23
24 ANSIBLE_COLOR = True
25 if C.ANSIBLE_NOCOLOR:
26 ANSIBLE_COLOR = False
27 elif not hasattr(sys.stdout, 'isatty') or not sys.stdout.isatty():
28 ANSIBLE_COLOR = False
29 else:
30 try:
31 import curses
32 curses.setupterm()
33 if curses.tigetnum('colors') < 0:
34 ANSIBLE_COLOR = False
35 except ImportError:
36 # curses library was not found
37 pass
38 except curses.error:
39 # curses returns an error (e.g. could not find terminal)
40 ANSIBLE_COLOR = False
41
42 if C.ANSIBLE_FORCE_COLOR:
43 ANSIBLE_COLOR = True
44
45 # --- begin "pretty"
46 #
47 # pretty - A miniature library that provides a Python print and stdout
48 # wrapper that makes colored terminal text easier to use (e.g. without
49 # having to mess around with ANSI escape sequences). This code is public
50 # domain - there is no license except that you must leave this header.
51 #
52 # Copyright (C) 2008 Brian Nez <thedude at bri1 dot com>
53
54
55 def parsecolor(color):
56 """SGR parameter string for the specified color name."""
57 matches = re.match(r"color(?P<color>[0-9]+)"
58 r"|(?P<rgb>rgb(?P<red>[0-5])(?P<green>[0-5])(?P<blue>[0-5]))"
59 r"|gray(?P<gray>[0-9]+)", color)
60 if not matches:
61 return C.COLOR_CODES[color]
62 if matches.group('color'):
63 return u'38;5;%d' % int(matches.group('color'))
64 if matches.group('rgb'):
65 return u'38;5;%d' % (16 + 36 * int(matches.group('red')) +
66 6 * int(matches.group('green')) +
67 int(matches.group('blue')))
68 if matches.group('gray'):
69 return u'38;5;%d' % (232 + int(matches.group('gray')))
70
71
72 def stringc(text, color, wrap_nonvisible_chars=False):
73 """String in color."""
74
75 if ANSIBLE_COLOR:
76 color_code = parsecolor(color)
77 fmt = u"\033[%sm%s\033[0m"
78 if wrap_nonvisible_chars:
79 # This option is provided for use in cases when the
80 # formatting of a command line prompt is needed, such as
81 # `ansible-console`. As said in `readline` sources:
82 # readline/display.c:321
83 # /* Current implementation:
84 # \001 (^A) start non-visible characters
85 # \002 (^B) end non-visible characters
86 # all characters except \001 and \002 (following a \001) are copied to
87 # the returned string; all characters except those between \001 and
88 # \002 are assumed to be `visible'. */
89 fmt = u"\001\033[%sm\002%s\001\033[0m\002"
90 return u"\n".join([fmt % (color_code, t) for t in text.split(u'\n')])
91 else:
92 return text
93
94
95 def colorize(lead, num, color):
96 """ Print 'lead' = 'num' in 'color' """
97 s = u"%s=%-4s" % (lead, str(num))
98 if num != 0 and ANSIBLE_COLOR and color is not None:
99 s = stringc(s, color)
100 return s
101
102
103 def hostcolor(host, stats, color=True):
104 if ANSIBLE_COLOR and color:
105 if stats['failures'] != 0 or stats['unreachable'] != 0:
106 return u"%-37s" % stringc(host, C.COLOR_ERROR)
107 elif stats['changed'] != 0:
108 return u"%-37s" % stringc(host, C.COLOR_CHANGED)
109 else:
110 return u"%-37s" % stringc(host, C.COLOR_OK)
111 return u"%-26s" % host