diff --git a/lib/spack/llnl/util/tty/color.py b/lib/spack/llnl/util/tty/color.py index a471505d34..710196783d 100644 --- a/lib/spack/llnl/util/tty/color.py +++ b/lib/spack/llnl/util/tty/color.py @@ -59,6 +59,7 @@ To output an @, use '@@'. To output a } inside braces, use '}}'. """ +import os import re import sys from contextlib import contextmanager @@ -101,9 +102,29 @@ def __init__(self, message): # Mapping from color arguments to values for tty.set_color color_when_values = {"always": True, "auto": None, "never": False} -# Force color; None: Only color if stdout is a tty -# True: Always colorize output, False: Never colorize output -_force_color = None + +def _color_when_value(when): + """Raise a ValueError for an invalid color setting. + + Valid values are 'always', 'never', and 'auto', or equivalently, + True, False, and None. + """ + if when in color_when_values: + return color_when_values[when] + elif when not in color_when_values.values(): + raise ValueError("Invalid color setting: %s" % when) + return when + + +def _color_from_environ() -> Optional[bool]: + try: + return _color_when_value(os.environ.get("SPACK_COLOR", "auto")) + except ValueError: + return None + + +#: When `None` colorize when stdout is tty, when `True` or `False` always or never colorize resp. +_force_color = _color_from_environ() def try_enable_terminal_color_on_windows(): @@ -164,19 +185,6 @@ def _err_check(result, func, args): debug("Unable to support color on Windows terminal") -def _color_when_value(when): - """Raise a ValueError for an invalid color setting. - - Valid values are 'always', 'never', and 'auto', or equivalently, - True, False, and None. - """ - if when in color_when_values: - return color_when_values[when] - elif when not in color_when_values.values(): - raise ValueError("Invalid color setting: %s" % when) - return when - - def get_color_when(): """Return whether commands should print color or not.""" if _force_color is not None: diff --git a/lib/spack/spack/main.py b/lib/spack/spack/main.py index bff07ccbfb..655fae2f17 100644 --- a/lib/spack/spack/main.py +++ b/lib/spack/spack/main.py @@ -427,7 +427,7 @@ def make_argument_parser(**kwargs): parser.add_argument( "--color", action="store", - default=os.environ.get("SPACK_COLOR", "auto"), + default=None, choices=("always", "never", "auto"), help="when to colorize output (default: auto)", ) @@ -622,7 +622,8 @@ def setup_main_options(args): # with color color.try_enable_terminal_color_on_windows() # when to use color (takes always, auto, or never) - color.set_color_when(args.color) + if args.color is not None: + color.set_color_when(args.color) def allows_unknown_args(command):