|
4 | 4 | """ |
5 | 5 | from __future__ import print_function |
6 | 6 |
|
7 | | -from colorclass import Color |
| 7 | +import os |
| 8 | +import platform |
| 9 | + |
| 10 | +DO_COLORS = True |
| 11 | +# !! Windows compatibility for ANSI color codes !! |
| 12 | +# |
| 13 | +# If we're running on windows, we need to run the "color" command to enable |
| 14 | +# ANSI color code support. |
| 15 | +if platform.system() == "Windows": |
| 16 | + ver = platform.version() |
| 17 | + |
| 18 | + if '.' in ver: |
| 19 | + ver = ver.split('.', 1)[0] |
| 20 | + |
| 21 | + try: |
| 22 | + verNum = int(ver) |
| 23 | + except ValueError: |
| 24 | + DO_COLORS = False |
| 25 | + |
| 26 | + # windows 10+ supports ANSI color codes after running the 'color' command to |
| 27 | + # properly set up the command prompt. Older versions of windows do not, and |
| 28 | + # we should not attempt to use them there. |
| 29 | + if verNum >= 10: |
| 30 | + os.system("color") |
| 31 | + else: |
| 32 | + DO_COLORS = False |
| 33 | + |
| 34 | + |
| 35 | +CLEAR_COLOR = "\x1b[0m" |
| 36 | +COLOR_CODE_MAP = { |
| 37 | + "red": "\x1b[31m", |
| 38 | + "green": "\x1b[32m", |
| 39 | + "yellow": "\x1b[33m", |
| 40 | + "black": "\x1b[30m", |
| 41 | + "white": "\x1b[40m", |
| 42 | +} |
| 43 | + |
| 44 | + |
| 45 | +def colorize_string(string, color): |
| 46 | + """ |
| 47 | + Returns the requested string, wrapped in ANSI color codes to colorize it as |
| 48 | + requested. On platforms where colors are not supported, this just returns |
| 49 | + the string passed into it. |
| 50 | + """ |
| 51 | + if not DO_COLORS: |
| 52 | + return string |
| 53 | + |
| 54 | + col = COLOR_CODE_MAP.get(color, CLEAR_COLOR) |
| 55 | + |
| 56 | + return "{}{}{}".format( |
| 57 | + col, string, CLEAR_COLOR, |
| 58 | + ) |
8 | 59 |
|
9 | 60 |
|
10 | 61 | class ModelAttr: |
@@ -51,7 +102,7 @@ def render_value(self, model, colorize=True): |
51 | 102 | # apply colors |
52 | 103 | value = str(value) # just in case |
53 | 104 | color = self.color_map.get(value) or self.color_map['default_'] |
54 | | - value = str(Color('{'+color+'}'+value+'{/'+color+'}')) |
| 105 | + value = colorize_string(value, color) |
55 | 106 |
|
56 | 107 | if value is None: |
57 | 108 | # don't print the word "None" |
|
0 commit comments