pivotalcli/color.py

54 lines
1.3 KiB
Python
Raw Normal View History

2018-08-17 14:26:46 +00:00
from typing import Any, Optional
class Color:
BLACK = 0
RED = 1
GREEN = 2
YELLOW = 3
BLUE = 4
MAGENTA = 5
CYAN = 6
WHITE = 7
BRIGHT_BLACK = 8
BRIGHT_RED = 9
BRIGHT_GREEN = 10
BRIGHT_YELLOW = 11
BRIGHT_BLUE = 12
BRIGHT_MAGENTA = 13
BRIGHT_CYAN = 14
BRIGHT_WHITE = 15
2019-09-04 14:39:36 +00:00
def __init__(
self, foreground: Optional[int], background: Optional[int] = None
) -> None:
2018-08-17 14:26:46 +00:00
self.foreground = foreground
self.background = background
2019-09-04 14:39:36 +00:00
def print(self, *args: Any, end: str = "\n") -> None:
2018-08-17 14:26:46 +00:00
print(self.format(*args), end=end)
def format(self, *args: Any) -> str:
2019-09-04 14:39:36 +00:00
# Create the color string.
colors = []
2018-08-17 14:26:46 +00:00
if self.foreground is not None:
colors.append(f"38;5;{self.foreground}")
if self.background is not None:
colors.append(f"48;5;{self.background}")
2019-09-04 14:39:36 +00:00
color_str = ";".join(colors)
2018-08-17 14:26:46 +00:00
2019-09-04 14:39:36 +00:00
text = " ".join(str(a) for a in args)
2018-08-17 14:26:46 +00:00
if not text:
2019-09-04 14:39:36 +00:00
return ""
# Reset the color as necessary.
reset = []
if self.foreground is not None:
reset.append("39")
if self.background is not None:
reset.append("49")
reset_str = ";".join(reset)
2018-08-17 14:26:46 +00:00
2019-09-04 14:39:36 +00:00
return f"\033[{color_str}m{text}\033[{reset_str}m"