Skip to content

Commit

Permalink
Colorize: Granularly wrap each given stream with Colorama (#1506)
Browse files Browse the repository at this point in the history
* #1245 Colorize: Granularly wrap each given stream with Colorama instead of doing a global Colorama init

Signed-off-by: Erwan Leroy <herronelou@gmail.com>

* #1245 Re-introduce warning comment about Colorama init

Signed-off-by: Erwan Leroy <herronelou@gmail.com>

---------

Signed-off-by: Erwan Leroy <herronelou@gmail.com>
  • Loading branch information
herronelou authored Sep 11, 2023
1 parent c49611c commit 6ea5b67
Showing 1 changed file with 16 additions and 14 deletions.
30 changes: 16 additions & 14 deletions src/rez/utils/colorize.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,17 @@
from rez.vendor import colorama
from rez.config import config

# Important - we don't want to init Colorama at startup,
# because colorama prints a RESET_ALL character at exit. This in turn adds
# unexpected output when capturing the output of a command run in a
# ResolvedContext, for example.
# While we're not initializing colorama at all anymore, this comment is left
# in case someone thought about putting it back: Make sure to do it lazily.

_initialised = False


def _init_colorama():
global _initialised
if not _initialised:
colorama.init()
_initialised = True
def colorama_wrap(stream):
""" Wrap the stream with colorama so that it can display colors on any OS """
return colorama.initialise.wrap_stream(stream, convert=None, strip=None, autoreset=False, wrap=True)


def stream_is_tty(stream):
Expand Down Expand Up @@ -222,12 +224,6 @@ def _color(str_, fore_color=None, back_color=None, styles=None):
if not config.get("color_enabled", False):
return str_

# lazily init colorama. This is important - we don't want to init at startup,
# because colorama prints a RESET_ALL character atexit. This in turn adds
# unexpected output when capturing the output of a command run in a
# ResolvedContext, for example.
_init_colorama()

colored = ""
if not styles:
styles = []
Expand Down Expand Up @@ -271,6 +267,10 @@ class ColorizedStreamHandler(logging.StreamHandler):
0: notset,
}

def __init__(self, stream=None):
super(ColorizedStreamHandler, self).__init__(stream)
self.stream = colorama_wrap(self.stream)

@property
def is_tty(self):
"""Return true if the stream associated with this handler is a tty
Expand Down Expand Up @@ -315,11 +315,13 @@ def emit(self, record):

class Printer(object):
def __init__(self, buf=sys.stdout):
self.buf = buf
self.colorize = (
config.get("color_enabled", False) == "force"
or stream_is_tty(buf)
)
if self.colorize:
buf = colorama_wrap(buf)
self.buf = buf

def __call__(self, msg='', style=None):
print(self.get(msg, style), file=self.buf)
Expand Down

0 comments on commit 6ea5b67

Please sign in to comment.