From 3e7a95660f82683d23599db434386424c5cd2ee5 Mon Sep 17 00:00:00 2001 From: Noah Gorny Date: Tue, 23 Jun 2020 15:42:22 +0300 Subject: [PATCH] lib: Add _has_colors function and use it in log output --- lib/appearance.bash | 10 ++++++++++ lib/log.bash | 11 ++++++----- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/lib/appearance.bash b/lib/appearance.bash index 6d0ef2ff..d684332f 100644 --- a/lib/appearance.bash +++ b/lib/appearance.bash @@ -1,5 +1,15 @@ #!/usr/bin/env bash +function _has_colors() +{ + # Check that stdout is a terminal + test -t 1 || return 1 + + ncolors=$(tput colors) + test -n "$ncolors" && test "$ncolors" -ge 8 || return 1 + return 0 +} + # colored ls export LSCOLORS='Gxfxcxdxdxegedabagacad' diff --git a/lib/log.bash b/lib/log.bash index dc9a544a..8f954359 100644 --- a/lib/log.bash +++ b/lib/log.bash @@ -7,10 +7,11 @@ export BASH_IT_LOG_LEVEL_ALL=3 function _log_general() { _about 'Internal function used for logging' - _param '1: message to log' + _param '1: color of the message' + _param '2: message to log' _group 'log' - echo -e "$1${echo_normal}" + _has_colors && echo -e "$1$2${echo_normal}" || echo -e "$2" } function _log_debug() @@ -21,7 +22,7 @@ function _log_debug() _group 'log' [[ "$BASH_IT_LOG_LEVEL" -ge $BASH_IT_LOG_LEVEL_ALL ]] || return - _log_general "${echo_green}DEBUG: $1" + _log_general "${echo_green}" "DEBUG: $1" } function _log_warning() @@ -32,7 +33,7 @@ function _log_warning() _group 'log' [[ "$BASH_IT_LOG_LEVEL" -ge $BASH_IT_LOG_LEVEL_WARNING ]] || return - _log_general "${echo_yellow} WARN: $1" + _log_general "${echo_yellow}" " WARN: $1" } function _log_error() @@ -43,5 +44,5 @@ function _log_error() _group 'log' [[ "$BASH_IT_LOG_LEVEL" -ge $BASH_IT_LOG_LEVEL_ERROR ]] || return - _log_general "${echo_red}ERROR: $1" + _log_general "${echo_red}" "ERROR: $1" }