2432a2ba87
This forces Dotbot to produce colored output, regardless of whether it is outputting to a TTY. This is useful to support use cases such as piping colored Dotbot output into another program for formatting (e.g. I want to indent the output as part of a larger installation script); this was not previously easy to do as this would cause the output to lose its colored formatting. This option cannot be provided at the same time as the existing `--no-color` option, as there's no logical interpretation of what effect providing both of these should have. As part of this change I've refactored some existing code determining whether output should be colored to where options are parsed, as this made this change simpler and I think it makes sense for all this logic to be performed in the same place.
62 lines
1.7 KiB
Python
62 lines
1.7 KiB
Python
from ..util.singleton import Singleton
|
|
from ..util.compat import with_metaclass
|
|
from .color import Color
|
|
from .level import Level
|
|
|
|
class Messenger(with_metaclass(Singleton, object)):
|
|
def __init__(self, level = Level.LOWINFO):
|
|
self.set_level(level)
|
|
self.use_color(True)
|
|
|
|
def set_level(self, level):
|
|
self._level = level
|
|
|
|
def use_color(self, yesno):
|
|
self._use_color = yesno
|
|
|
|
def log(self, level, message):
|
|
if (level >= self._level):
|
|
print('%s%s%s' % (self._color(level), message, self._reset()))
|
|
|
|
def debug(self, message):
|
|
self.log(Level.DEBUG, message)
|
|
|
|
def lowinfo(self, message):
|
|
self.log(Level.LOWINFO, message)
|
|
|
|
def info(self, message):
|
|
self.log(Level.INFO, message)
|
|
|
|
def warning(self, message):
|
|
self.log(Level.WARNING, message)
|
|
|
|
def error(self, message):
|
|
self.log(Level.ERROR, message)
|
|
|
|
def _color(self, level):
|
|
'''
|
|
Get a color (terminal escape sequence) according to a level.
|
|
'''
|
|
if not self._use_color:
|
|
return ''
|
|
elif level < Level.DEBUG:
|
|
return ''
|
|
elif Level.DEBUG <= level < Level.LOWINFO:
|
|
return Color.YELLOW
|
|
elif Level.LOWINFO <= level < Level.INFO:
|
|
return Color.BLUE
|
|
elif Level.INFO <= level < Level.WARNING:
|
|
return Color.GREEN
|
|
elif Level.WARNING <= level < Level.ERROR:
|
|
return Color.MAGENTA
|
|
elif Level.ERROR <= level:
|
|
return Color.RED
|
|
|
|
def _reset(self):
|
|
'''
|
|
Get a reset color (terminal escape sequence).
|
|
'''
|
|
if not self._use_color:
|
|
return ''
|
|
else:
|
|
return Color.RESET
|