summaryrefslogtreecommitdiffstats
path: root/azure/aria/aria-extension-cloudify/src/aria/aria/cli/color.py
blob: d6a4cd6bd8521907ba79581b6a4a1496c6617184 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
Terminal colorization utilities.
"""

from StringIO import StringIO
import atexit
import re

import colorama

from ..utils.formatting import safe_str


def _restore_terminal():
    colorama.deinit()


colorama.init()
atexit.register(_restore_terminal)


class StringStylizer(object):
    def __init__(self, str_, color_spec=None):
        self._str = str_
        self._color_spec = color_spec

    def __repr__(self):
        if self._color_spec:
            return '{schema}{str}{reset}'.format(
                schema=self._color_spec, str=safe_str(self._str), reset=Colors.Style.RESET_ALL)
        return self._str

    def __add__(self, other):
        return safe_str(self) + other

    def __radd__(self, other):
        return other + safe_str(self)

    def color(self, color_spec):
        self._color_spec = color_spec

    def replace(self, old, new, **kwargs):
        self._str = self._str.replace(safe_str(old), safe_str(new), **kwargs)

    def format(self, *args, **kwargs):
        self._str = self._str.format(*args, **kwargs)

    def highlight(self, pattern, schema):
        if pattern is None:
            return
        for match in set(re.findall(re.compile(pattern), self._str)):
            self.replace(match, schema + match + Colors.Style.RESET_ALL + self._color_spec)


def _get_colors(color_type):
    for name in dir(color_type):
        if not name.startswith('_'):
            yield (name.lower(), getattr(color_type, name))


class Colors(object):
    Fore = colorama.Fore
    Back = colorama.Back
    Style = colorama.Style

    _colors = {
        'fore': dict(_get_colors(Fore)),
        'back': dict(_get_colors(Back)),
        'style': dict(_get_colors(Style))
    }


class ColorSpec(object):
    def __init__(self, fore=None, back=None, style=None):
        """
        It is possible to provide fore, back and style arguments. Each could be either the color as
        lowercase letters, or the full color name for Colorama.
        """
        self._kwargs = dict(fore=fore, back=back, style=style)
        self._str = StringIO()
        for type_, colors in Colors._colors.items():
            value = self._kwargs.get(type_, None)
            # the former case is if the value is a string, the latter is in case of an object.
            self._str.write(colors.get(value) or value)

    def __str__(self):
        return self._str.getvalue()

    def __add__(self, other):
        return str(self) + str(other)

    def __radd__(self, other):
        return str(other) + str(self)