From 0282ec4c06ba0c64be86caced1c911878196ac71 Mon Sep 17 00:00:00 2001 From: Robert Kaussow Date: Thu, 21 Mar 2019 16:05:55 +0100 Subject: [PATCH] add basic colorama implementation --- ansiblelater/utils/__init__.py | 33 +++++++++++++++++++++++++-------- 1 file changed, 25 insertions(+), 8 deletions(-) diff --git a/ansiblelater/utils/__init__.py b/ansiblelater/utils/__init__.py index 208b540..cc3bc11 100644 --- a/ansiblelater/utils/__init__.py +++ b/ansiblelater/utils/__init__.py @@ -6,39 +6,56 @@ import os import subprocess import sys import re +import colorama from distutils.version import LooseVersion +from ansible.module_utils.parsing.convert_bool import boolean as to_bool try: import ConfigParser as configparser except ImportError: import configparser -try: - from ansible.utils.color import stringc -except ImportError: - from ansible.color import stringc +# try: +# from ansible.utils.color import stringc +# except ImportError: +# from ansible.color import stringc # from yamlhelper import * +def should_do_markup(): + py_colors = os.environ.get('PY_COLORS', None) + if py_colors is not None: + return to_bool(py_colors, strict=False) + + return sys.stdout.isatty() and os.environ.get('TERM') != 'dumb' + + +colorama.init(autoreset=True, strip=not should_do_markup()) + + def abort(message, file=sys.stderr): - print(stringc("FATAL: %s" % message, 'red'), file=file) + return color_text(colorama.Fore.RED, "FATAL: {}".format(message)) sys.exit(1) def error(message, file=sys.stderr): - print(stringc("ERROR: %s" % message, 'red'), file=file) + return color_text(colorama.Fore.RED, "ERROR: {}".format(message)) def warn(message, settings, file=sys.stdout): if settings.log_level <= logging.WARNING: - print(stringc("WARN: %s" % message, 'yellow'), file=file) + return color_text(colorama.Fore.YELLOW, "WARN: {}".format(message)) def info(message, settings, file=sys.stdout): if settings.log_level <= logging.INFO: - print(stringc("INFO: %s" % message, 'green'), file=file) + return color_text(colorama.Fore.BLUE, "INFO: {}".format(message)) + + +def color_text(color, msg): + print('{}{}{}'.format(color, msg, colorama.Style.RESET_ALL)) def count_spaces(c_string):