This commit introduces a global --no-color command-line option,
extending its functionality beyond the diff plugin. It also adds
support for the NO_COLOR environment variable. Both enable users to
disable colored output across all plugins without requiring colorlog
to be uninstalled. Additionally, this change provides control over the
output color for the lock plugin, which was not previously possible.
For consistency, the implementation aligns with colorlog's behavior of
checking for the mere presence of the NO_COLOR environment variable,
rather than adhering to
no-color.org's recommendation of checking for a
non-empty string. Overriding this would require colorlog version 6.6
or higher.
When neither the command-line argument nor the environment variable
disables color, kas will independently check isatty for both stdout and
stderr to determine if color should be used.
Since colorlog is not an optional dependency anymore, use it's no_color
option instead of manually creating a different formatter when no_color
is enabled.
Signed-off-by: Tamino Larisch <
tamino....@siemens.com>
---
docs/userguide/environment-variables.inc | 3 +++
kas-container | 2 +-
kas/context.py | 8 +++++-
kas/kas.py | 33 ++++++++++++++----------
kas/plugins/diff.py | 12 +++------
kas/plugins/lock.py | 5 ++--
6 files changed, 37 insertions(+), 26 deletions(-)
diff --git a/docs/userguide/environment-variables.inc b/docs/userguide/environment-variables.inc
index 42ede08..c9dad43 100644
--- a/docs/userguide/environment-variables.inc
+++ b/docs/userguide/environment-variables.inc
@@ -245,6 +245,9 @@ overwritten using the ``env`` section of the config file.
| (C,K) | and install buildtools. If not set, kas will use |
| | ``KAS_BUILD_DIR/buildtools`` as the default path.|
+--------------------------+--------------------------------------------------+
+| NO_COLOR (C,K,E) | Prevents the addition of ANSI color to all output|
+| | when this variable is present. |
++--------------------------+--------------------------------------------------+
.. |aws_cred| replace:: ``AWS_ROLE_ARN``
``AWS_SHARED_CREDENTIALS_FILE``
diff --git a/kas-container b/kas-container
index d00dc93..aa1839d 100755
--- a/kas-container
+++ b/kas-container
@@ -770,7 +770,7 @@ for var in TERM KAS_DISTRO KAS_MACHINE KAS_TARGET KAS_TASK KAS_CLONE_DEPTH \
KAS_PREMIRRORS DISTRO_APT_PREMIRRORS BB_NUMBER_THREADS PARALLEL_MAKE \
GIT_CREDENTIAL_USEHTTPPATH \
BB_HASHSERVE BB_HASHSERVE_UPSTREAM \
- TZ; do
+ NO_COLOR TZ; do
if [ -n "$(eval echo \$${var})" ]; then
set -- "$@" -e "${var}=$(eval echo \"\$${var}\")"
fi
diff --git a/kas/context.py b/kas/context.py
index 41bd761..465518a 100644
--- a/kas/context.py
+++ b/kas/context.py
@@ -91,6 +91,7 @@ class Context:
if not clone_depth.isdigit():
raise KasUserError('KAS_CLONE_DEPTH must be a number')
self.repo_clone_depth = max(int(clone_depth), 0)
+ self.args = args
self.setup_initial_environ()
self.check_container_call()
# Register the paths that kas created and exclusively owns
@@ -99,7 +100,6 @@ class Context:
self.managed_paths.add(self.__kas_build_dir)
self.keyhandler = {}
self.config = None
- self.args = args
self.unpinned_repo_warnings = True
def setup_initial_environ(self):
@@ -130,6 +130,8 @@ class Context:
val = os.environ.get(key, None)
if val:
self.environ[key] = val
+ if self.args.no_color:
+ self.environ['NO_COLOR'] = '1'
# make remote containers environment available in kas
if self.managed_env == ManagedEnvironment.VSCODE_REMOTE_CONTAINERS:
@@ -190,6 +192,10 @@ class Context:
def update(self):
return getattr(self.args, 'update', None)
+ @property
+ def no_color(self):
+ return getattr(self.args, 'no_color', False)
+
@property
def managed_env(self):
return self._get_managed_env()
diff --git a/kas/kas.py b/kas/kas.py
index c2b65a4..1b40076 100644
--- a/kas/kas.py
+++ b/kas/kas.py
@@ -47,7 +47,7 @@ __copyright__ = 'Copyright (c) Siemens AG, 2017-2018'
DEFAULT_LOG_LEVEL = 'info'
-def create_logger():
+def create_logger(no_color=False):
"""
Setup the logging environment
"""
@@ -55,17 +55,15 @@ def create_logger():
set_global_loglevel(DEFAULT_LOG_LEVEL.upper())
format_str = '%(asctime)s - %(levelname)-8s - %(message)s'
date_format = '%Y-%m-%d %H:%M:%S'
- if os.isatty(2):
- cformat = '%(log_color)s' + format_str
- colors = {'DEBUG': 'reset',
- 'INFO': 'reset',
- 'WARNING': 'bold_yellow',
- 'ERROR': 'bold_red',
- 'CRITICAL': 'bold_red'}
- formatter = colorlog.ColoredFormatter(cformat, date_format,
- log_colors=colors)
- else:
- formatter = logging.Formatter(format_str, date_format)
+ cformat = '%(log_color)s' + format_str
+ colors = {'DEBUG': 'reset',
+ 'INFO': 'reset',
+ 'WARNING': 'bold_yellow',
+ 'ERROR': 'bold_red',
+ 'CRITICAL': 'bold_red'}
+ formatter = colorlog.ColoredFormatter(cformat, date_format,
+ log_colors=colors,
+ no_color=no_color)
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
log.addHandler(stream_handler)
@@ -158,6 +156,10 @@ def kas_get_argparser():
default=f'{DEFAULT_LOG_LEVEL}',
help=f'Set log level (default: {DEFAULT_LOG_LEVEL})')
+ parser.add_argument('--no-color',
+ action='store_true',
+ help='Disable colors for all outputs')
+
subparser = parser.add_subparsers(dest='cmd')
for plugin in plugins.all():
@@ -191,11 +193,14 @@ def kas(argv):
"""
The actual main entry point of kas.
"""
- create_logger()
-
parser = kas_get_argparser()
args = parser.parse_args(argv)
+ create_logger(args.no_color or not sys.stderr.isatty())
+ args.no_color = args.no_color \
+ or "NO_COLOR" in os.environ \
+ or not sys.stdout.isatty()
+
if args.log_level:
set_global_loglevel(args.log_level.upper())
diff --git a/kas/plugins/diff.py b/kas/plugins/diff.py
index aad48bc..ad25743 100644
--- a/kas/plugins/diff.py
+++ b/kas/plugins/diff.py
@@ -37,7 +37,7 @@
import json
import difflib
-from kas.context import create_global_context
+from kas.context import create_global_context, get_context
from kas.config import Config
from kas.libcmds import Macro
from kas.libkas import setup_parser_common_args
@@ -72,9 +72,6 @@ class Diff:
action='store_true',
help='Use git oneline output for differing '
'commits.')
- parser.add_argument('--no-color',
- action='store_true',
- help='Disable colored highlighting of diffs.')
parser.add_argument('--commit-only',
action='store_true',
help='This will not display the differences in '
@@ -119,7 +116,7 @@ class Diff:
@staticmethod
def formatting_diff_output(oldfile, newfile, diff_output, oneline,
- no_color, commit_only, content_only):
+ commit_only, content_only):
"""
Format the diff output.
"""
@@ -147,7 +144,7 @@ class Diff:
else:
print(f"{' ' * 8}{line}", end='')
- if no_color:
+ if get_context().no_color:
COLORS_OLD = ''
COLORS_NEW = ''
COLORS_COMMIT = ''
@@ -268,8 +265,7 @@ class Diff:
else:
Diff.formatting_diff_output(args.config1, args.config2,
diff_output, args.oneline,
- args.no_color, args.commit_only,
- args.content_only)
+ args.commit_only, args.content_only)
__KAS_PLUGINS__ = [Diff]
diff --git a/kas/plugins/lock.py b/kas/plugins/lock.py
index 2d947c8..be76d2a 100644
--- a/kas/plugins/lock.py
+++ b/kas/plugins/lock.py
@@ -76,7 +76,7 @@
import logging
import os
from dataclasses import dataclass
-from kas.context import create_global_context
+from kas.context import create_global_context, get_context
from kas.config import Config
from kas.includehandler import ConfigFile
from kas.libcmds import Macro
@@ -118,8 +118,9 @@ class Lock:
except RepoRefError as e:
logging.warning(e)
return
+ no_color = get_context().no_color
Diff.formatting_diff_output(
- None, None, {'vcs': diff}, True, False, True, False)
+ None, None, {'vcs': diff}, True, no_color, True, False)
def _update_lockfile(self, lockfile, repos_to_lock, update_only, args):
"""
--
2.39.5