import sys
from os import environ
import datetime
from typing import Any
if 'DEBUG' in environ:
DEBUG = environ['DEBUG'].split(',')
if '1' in DEBUG:
DEBUG.remove('1')
if 'debug' not in DEBUG:
DEBUG.append('debug')
else:
DEBUG = []
if 'context' in DEBUG:
from inspect import currentframe, getframeinfo
_CONTEXT = 'context' in DEBUG
_COLOR = 'nocolor' not in DEBUG
_TIMESTAMP = 'timestamp' in DEBUG
if 'debug' in DEBUG:
def debug(_msg: Any) -> None:
context = ''
if _CONTEXT:
frame = currentframe()
if frame:
frame = frame.f_back
if frame:
info = getframeinfo(frame)
file = info.filename
if len(file) > 20:
file = '...'+file[-20:]
line = info.lineno
context = f'{file}:{line}: '
timestamp = ''
if _TIMESTAMP:
timestamp = f'{datetime.datetime.now()} '
if _COLOR:
print(f"\x1b[32m\x1b[1mDEBUG\x1b[0m: {timestamp}{context}{_msg}", flush=True)
else:
print(f'DEBUG: {context}{_msg}', flush=True)
debug("Debugging is enabled")
else:
def debug(_msg: Any) -> None:
if _COLOR:
def error(msg: Any) -> None:
sys.stderr.write(f"\x1b[31m\x1b[1mError\x1b[0m\x1b[1m: {msg}\x1b[0m\n")
sys.stderr.flush()
else:
def error(msg: Any) -> None:
sys.stderr.write(f"Error: {msg}\n")
sys.stderr.flush()
if _COLOR:
def note(tag: Any, msg: Any) -> None:
sys.stderr.write(f"\x1b[34m\x1b[1m{tag}\x1b[0m: {msg}\x1b[0m\n")
sys.stderr.flush()
else:
def note(tag: Any, msg: Any) -> None:
sys.stderr.write(f"{tag}: {msg}\n")
sys.stderr.flush()