2020-03-11 14:17:04 -03:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
|
|
|
|
import re
|
|
|
|
import sys
|
|
|
|
import os
|
2020-03-12 04:43:20 -03:00
|
|
|
from enum import Enum
|
|
|
|
from functools import lru_cache
|
2020-03-11 14:17:04 -03:00
|
|
|
|
|
|
|
|
2020-03-12 04:43:20 -03:00
|
|
|
class color(Enum):
|
|
|
|
PURPLE = '\033[95m'
|
|
|
|
CYAN = '\033[96m'
|
|
|
|
DARKCYAN = '\033[36m'
|
|
|
|
BLUE = '\033[94m'
|
|
|
|
GREEN = '\033[92m'
|
|
|
|
YELLOW = '\033[93m'
|
|
|
|
RED = '\033[91m'
|
2020-03-13 14:53:11 -03:00
|
|
|
GRAY = '\033[90m'
|
2020-03-12 04:43:20 -03:00
|
|
|
BOLD = '\033[1m'
|
|
|
|
UNDERLINE = '\033[4m'
|
|
|
|
RESET = '\033[0m'
|
2020-03-11 14:17:04 -03:00
|
|
|
|
2020-03-12 04:43:20 -03:00
|
|
|
|
|
|
|
def colorize(text: str, c: color) -> str:
|
|
|
|
if _supports_color():
|
2020-03-13 06:02:58 -03:00
|
|
|
return str(c.value) + text + color.RESET.value
|
2020-03-12 04:43:20 -03:00
|
|
|
else:
|
|
|
|
return text
|
2020-03-11 14:17:04 -03:00
|
|
|
|
|
|
|
|
2020-03-12 04:43:20 -03:00
|
|
|
def maybe_strip_color(text: str) -> str:
|
2020-03-11 14:17:04 -03:00
|
|
|
"""Remove ANSI and xterm256 color codes.
|
|
|
|
|
|
|
|
From https://stackoverflow.com/a/30500866/8548472
|
|
|
|
"""
|
2020-03-12 04:43:20 -03:00
|
|
|
if not _supports_color():
|
|
|
|
return re.sub(r'\x1b(\[.*?[@-~]|\].*?(\x07|\x1b\\))', '', text)
|
|
|
|
else:
|
|
|
|
return text
|
|
|
|
|
|
|
|
|
2020-03-17 12:44:45 -03:00
|
|
|
@lru_cache()
|
2020-03-12 04:43:20 -03:00
|
|
|
def _supports_color() -> bool:
|
|
|
|
"""Returns True if the running system's terminal supports color.
|
|
|
|
|
|
|
|
From https://stackoverflow.com/a/22254892/8548472
|
|
|
|
"""
|
|
|
|
supported_platform = \
|
|
|
|
(sys.platform != 'Pocket PC') and \
|
|
|
|
(sys.platform != 'win32' or 'ANSICON' in os.environ)
|
|
|
|
|
|
|
|
# isatty is not always implemented.
|
|
|
|
is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty()
|
|
|
|
|
|
|
|
return supported_platform and is_a_tty
|