14 """The module contains helpers to enable color output in terminals.
16 Use this to log resources dumped as a structured document (f.e. YAML),
17 and enable colorful syntax highlighting.
19 TODO(sergiitk): This can be used to output protobuf responses formatted as JSON.
22 from typing
import Optional
24 from absl
import flags
26 import pygments.formatter
27 import pygments.formatters.other
28 import pygments.formatters.terminal
29 import pygments.formatters.terminal256
31 import pygments.lexers.data
32 import pygments.styles
35 STYLE_ANSI_16 =
'ansi16'
37 ALL_COLOR_STYLES = [STYLE_ANSI_16] + list(pygments.styles.get_all_styles())
40 COLOR = flags.DEFINE_bool(
"color", default=
True, help=
'Colorize the output')
41 COLOR_STYLE = flags.DEFINE_enum(
44 enum_values=ALL_COLOR_STYLES,
45 help=(
'Color styles for terminals supporting 256 colors. '
46 f
'Use {STYLE_ANSI_16} style for terminals supporting 8/16 colors'))
48 logger = logging.getLogger(__name__)
51 Lexer = pygments.lexer.Lexer
52 YamlLexer = pygments.lexers.data.YamlLexer
53 Formatter = pygments.formatter.Formatter
54 NullFormatter = pygments.formatters.other.NullFormatter
55 TerminalFormatter = pygments.formatters.terminal.TerminalFormatter
56 Terminal256Formatter = pygments.formatters.terminal256.Terminal256Formatter
63 color_style: Optional[str] =
None
68 color: Optional[bool] =
None,
69 color_style: Optional[str] =
None):
71 self.
color = color
if color
is not None else COLOR.value
74 color_style = color_style
if color_style
else COLOR_STYLE.value
75 if color_style
not in ALL_COLOR_STYLES:
76 raise ValueError(f
'Unrecognized color style {color_style}, '
77 f
'valid styles: {ALL_COLOR_STYLES}')
78 if color_style == STYLE_ANSI_16:
95 color: Optional[bool] =
None,
96 color_style: Optional[str] =
None):
99 color_style=color_style)