task.mk/src/ansi.py

54 lines
1.2 KiB
Python
Raw Normal View History

2022-09-05 12:23:17 -05:00
#% extends "py-script.mk" %#
2022-09-05 17:44:39 -05:00
#% block name %#ansi#% endblock %#
2022-09-05 12:23:17 -05:00
#% block script %#
import os
import sys
color2byte = dict(
black=0,
red=1,
green=2,
yellow=3,
blue=4,
magenta=5,
cyan=6,
white=7,
)
state2byte = dict(
bold=1, faint=2, italic=3, underline=4, blink=5, fast_blink=6, crossed=9
)
def fg(byte):
return 30 + byte
def bg(byte):
return 40 + byte
2022-09-05 17:44:39 -05:00
class Ansi:
2022-09-05 12:23:17 -05:00
"""ANSI color codes"""
2022-09-05 17:44:39 -05:00
def setcode(self, name, escape_code):
2022-09-05 12:23:17 -05:00
if not sys.stdout.isatty() or os.getenv("NO_COLOR", False):
setattr(self, name, "")
else:
setattr(self, name, escape_code)
def __init__(self):
2022-09-05 17:44:39 -05:00
self.setcode("end", "\033[0m")
2022-09-05 12:23:17 -05:00
for name, byte in color2byte.items():
2022-09-05 17:44:39 -05:00
self.setcode(name, f"\033[{fg(byte)}m")
self.setcode(f"b_{name}", f"\033[1;{fg(byte)}m")
self.setcode(f"d_{name}", f"\033[2;{fg(byte)}m")
2022-09-05 12:23:17 -05:00
for bgname, bgbyte in color2byte.items():
2022-09-05 17:44:39 -05:00
self.setcode(f"{name}_on_{bgname}", f"\033[{bg(bgbyte)};{fg(byte)}m")
2022-09-05 12:23:17 -05:00
for name, byte in state2byte.items():
2022-09-05 17:44:39 -05:00
self.setcode(name, f"\033[{byte}m")
2022-09-05 12:23:17 -05:00
2022-09-05 17:44:39 -05:00
a = ansi = Ansi()
2022-09-05 12:23:17 -05:00
#% endblock %#