File: console.py

package info (click to toggle)
python-easydev 0.10.1%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 504 kB
  • sloc: python: 2,130; javascript: 49; makefile: 13
file content (134 lines) | stat: -rw-r--r-- 3,377 bytes parent folder | download
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# -*- python -*-
# -*- coding: utf-8 -*-
#
#  This file is part of the easydev software
#  It is a modified version of console.py from the sphinx software
#
#  Copyright (c) 2011-2014
#
#  File author(s): Thomas Cokelaer <cokelaer@gmail.com>
#
#  Distributed under the GPLv3 License.
#  See accompanying file LICENSE.txt or copy at
#      http://www.gnu.org/licenses/gpl-3.0.html
#
#  Website: https://github.com/cokelaer/easydev
#  Documentation: http://packages.python.org/easydev
#
##############################################################################
"""Format colored consoled output. Modified from sphinx.util.console"""
import os
import sys


__all__ = ["color_terminal", "get_terminal_width", "term_width_line"]


from easydev.platform import is_windows


if is_windows() is True: #pragma: no cover
    import colorama
    colorama.init()

# colors and other functions from the attributes codes are added dynamically to
# this __all__ variable
codes = {}

def get_terminal_width():
    """Returns the current terminal width"""
    try:
        import termios, fcntl, struct
        call = fcntl.ioctl(0, termios.TIOCGWINSZ,
                           struct.pack('hhhh', 0, 0, 0, 0))
        _, width = struct.unpack('hhhh', call)[:2]
        terminal_width = width
    except (SystemExit, KeyboardInterrupt): #pragma: no cover
        raise
    except:
        # FALLBACK
        terminal_width = int(os.environ.get('COLUMNS', 80)) - 1
    return terminal_width


def term_width_line(text):
    """prints pruned version of the input text (limited to terminal width)

    :param str text:
    :return str text:
    """
    _tw = get_terminal_width()
    if not codes:
        # if no coloring, don't output fancy backspaces
        return text + '\n'
    else:
        return text.ljust(_tw) + '\r'

def color_terminal():
    """Does terminal allows coloring

    :return: boolean"""
    if not hasattr(sys.stdout, 'isatty'):
        return False
    if not sys.stdout.isatty():
        return False
    if 'COLORTERM' in os.environ: #pragma: no cover
        return True
    term = os.environ.get('TERM', 'dumb').lower()
    if term in ('xterm', 'linux') or 'color' in term:
        return True
    return False


def __nocolor(): #pragma: no cover
    """set color codes off"""
    codes.clear()

def __coloron(): #pragma: no cover
    """Set color codes on"""
    codes.update(_orig_codes)

def _colorize(name, text):
    return codes.get(name, '') + text + codes.get('reset', '')

def _create_color_func(name):
    def inner(text):
        return _colorize(name, text)
    globals()[name] = inner

_attrs = {
    'reset':     '39;49;00m',
    'bold':      '01m',
    'faint':     '02m',
    'standout':  '03m',
    'underline': '04m',
    'blink':     '05m',
}

for _name, _value in _attrs.items():
    codes[_name] = '\x1b[' + _value

_colors = [
    ('black',     'darkgray'),
    ('darkred',   'red'),
    ('darkgreen', 'green'),
    ('brown',     'yellow'),
    ('darkblue',  'blue'),
    ('purple',    'fuchsia'),
    ('turquoise', 'teal'),
    ('lightgray', 'white'),
]

for i, (dark, light) in enumerate(_colors):
    codes[dark] = '\x1b[%im' % (i+30)
    codes[light] = '\x1b[%i;01m' % (i+30)

_orig_codes = codes.copy()

for _name in codes:
    _create_color_func(_name)

# dynamically set the colors
for x in codes.keys():
    __all__.append(x)