Skip to content

Commit 793803e

Browse files
authored
Merge pull request #20 from desultory/dev
add more generic support for formatting
2 parents 39b83fb + c73d5dc commit 793803e

File tree

1 file changed

+37
-9
lines changed

1 file changed

+37
-9
lines changed

src/zenlib/util/colorize.py

Lines changed: 37 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,23 @@
1-
__version__ = "0.2.0"
1+
__version__ = "0.3.0"
22

3+
from dataclasses import dataclass
34
from enum import Enum
45

56
ANSI_START = "\x1b["
67

78

9+
class Formatters(Enum):
10+
BOLD = 1
11+
DIM = 2
12+
ITALIC = 3
13+
UNDERLINE = 4
14+
BLINK = 5
15+
FAST_BLINK = 6
16+
REVERSE = 7
17+
HIDDEN = 8
18+
STRIKETHROUGH = 9
19+
20+
821
class Colors(Enum):
922
RED = 31
1023
GREEN = 32
@@ -15,20 +28,35 @@ class Colors(Enum):
1528
WHITE = 37
1629

1730

31+
@dataclass
1832
class ANSICode:
19-
def __init__(self, code, bright=False, bold=False):
20-
self.code = code
21-
self.bright = bright
22-
self.bold = bold
33+
code: int
34+
bright: bool = False
35+
background: bool = False
36+
bold: bool = False
37+
dim: bool = False
38+
italic: bool = False
39+
underline: bool = False
40+
blink: bool = False
41+
fast_blink: bool = False
42+
reverse: bool = False
43+
hidden: bool = False
44+
strikethrough: bool = False
45+
46+
@property
47+
def formatters(self):
48+
return [str(formatter.value) for formatter in Formatters if getattr(self, formatter.name.lower())]
2349

2450
def __str__(self):
2551
color_code = self.code
2652
color_code += 60 if self.bright else 0
27-
bold_str = ";1" if self.bold else ""
28-
return f"{ANSI_START}{color_code}{bold_str}m"
53+
color_code += 10 if self.background else 0
54+
if formatters := self.formatters:
55+
color_code = f"{color_code};{';'.join(formatters)}"
56+
return f"{ANSI_START}{color_code}m"
2957

3058

31-
def colorize(text: str, color="white", bright=False, bold=False) -> str:
59+
def colorize(text: str, color="white", *args, **kwargs) -> str:
3260
try:
3361
color_code = Colors[color.upper()].value
3462
except (KeyError, AttributeError):
@@ -38,4 +66,4 @@ def colorize(text: str, color="white", bright=False, bold=False) -> str:
3866
raise ValueError(f"Invalid color: {color}")
3967
color_code = int(color)
4068

41-
return f"{ANSICode(color_code, bright, bold)}{text}{ANSICode(0)}"
69+
return f"{ANSICode(color_code, *args, **kwargs)}{text}{ANSICode(0)}"

0 commit comments

Comments
 (0)