Improved color coding a bit. Added 5 more color options (not usable outside of 256-bit enabled terminals)

This commit is contained in:
Anton Hvornum 2022-03-16 21:21:26 +01:00
parent a6b1cab077
commit ac0162aba7
No known key found for this signature in database
GPG Key ID: F1234C5BA67C59DF
1 changed files with 25 additions and 4 deletions

View File

@ -47,26 +47,47 @@ def supports_color() -> bool:
# Heavily influenced by: https://github.com/django/django/blob/ae8338daf34fd746771e0678081999b656177bae/django/utils/termcolors.py#L13
# Color options here: https://askubuntu.com/questions/528928/how-to-do-underline-bold-italic-strikethrough-color-background-and-size-i
def stylize_output(text: str, *opts :str, **kwargs :Union[str, int, Dict[str, Union[str, int]]]) -> str:
def stylize_output(text: str, *opts :str, **kwargs) -> str:
"""
Adds styling to a text given a set of color arguments.
"""
opt_dict = {'bold': '1', 'italic': '3', 'underscore': '4', 'blink': '5', 'reverse': '7', 'conceal': '8'}
color_names = ('black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white')
foreground = {color_names[x]: '3%s' % x for x in range(8)}
background = {color_names[x]: '4%s' % x for x in range(8)}
colors = {
'black' : '0',
'red' : '1',
'green' : '2',
'yellow' : '3',
'blue' : '4',
'magenta' : '5',
'cyan' : '6',
'white' : '7',
'orange' : '8;5;208', # Extended 256-bit colors (not always supported)
'darkorange' : '8;5;202',# https://www.lihaoyi.com/post/BuildyourownCommandLinewithANSIescapecodes.html#256-colors
'gray' : '8;5;246',
'darkgray' : '8;5;240',
'lightgray' : '8;5;256'
}
foreground = {key: f'3{colors[key]}' for key in colors}
background = {key: f'4{colors[key]}' for key in colors}
reset = '0'
code_list = []
if text == '' and len(opts) == 1 and opts[0] == 'reset':
return '\x1b[%sm' % reset
for k, v in kwargs.items():
if k == 'fg':
code_list.append(foreground[str(v)])
elif k == 'bg':
code_list.append(background[str(v)])
for o in opts:
if o in opt_dict:
code_list.append(opt_dict[o])
if 'noreset' not in opts:
text = '%s\x1b[%sm' % (text or '', reset)
return '%s%s' % (('\x1b[%sm' % ';'.join(code_list)), text or '')