From 568f6aecd04b6957a91a7fa7435d890e16108dd9 Mon Sep 17 00:00:00 2001 From: Ricardo Pardini Date: Wed, 30 Nov 2022 13:20:17 +0100 Subject: [PATCH] armbian-next: logging: helpers for handling special logging if stdout is a terminal (user-interactive) - introduce `if_user_on_terminal_and_not_logging_add()`; - also the opposite, `if_user_not_on_terminal_or_is_logging_add()` - unset `CURRENT_LOGGING_SECTION` when exiting a logging section - introduce `do_with_logging_unless_user_terminal()` --- lib/functions/logging/logging.sh | 46 ++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/lib/functions/logging/logging.sh b/lib/functions/logging/logging.sh index 4215e0984..3223e86fe 100644 --- a/lib/functions/logging/logging.sh +++ b/lib/functions/logging/logging.sh @@ -75,6 +75,7 @@ function finish_logging_section() { else display_alert "" " in $((SECONDS - CURRENT_LOGGING_SECTION_START))s" "group" fi + unset CURRENT_LOGGING_SECTION # clear this var, so we can detect if we're in a section or not later. } function do_with_logging() { @@ -116,6 +117,51 @@ function do_with_logging() { return 0 } +function do_with_logging_unless_user_terminal() { + # Is user on a terminal? If so, don't log, just show on screen. + if [[ -t 1 ]]; then + display_alert "User is on a terminal, not logging output" "terminal" "debug" + "$@" + else + display_alert "User is not on a terminal, logging output" "terminal" "debug" + do_with_logging "$@" + fi +} + +# usage example: +# declare -a verbose_params=() && if_user_on_terminal_and_not_logging_add verbose_params "--verbose" "--progress" +# echo "here is the verbose params: ${verbose_params[*]}" +function if_user_on_terminal_and_not_logging_add() { + # Is user on a terminal? if not, do nothing. + if [[ ! -t 1 ]]; then + return 0 + fi + # are we running under a logging section? if so, do nothing. + if [[ -n "${CURRENT_LOGGING_SECTION}" ]]; then + return 0 + fi + # If we're here, we're on a terminal and not logging. + declare -n _add_to="$1" # nameref to an array; can't use '-a' here + shift + _add_to+=("$@") + return 0 +} + +function if_user_not_on_terminal_or_is_logging_add() { + # Is user on a terminal? if yes, do nothing. + if [[ -t 1 ]]; then + return 0 + fi + # are we running under a logging section? if not, do nothing. + if [[ -z "${CURRENT_LOGGING_SECTION}" ]]; then + return 0 + fi + declare -n _add_to_inverse="$1" # nameref to an array; can't use '-a' here + shift + _add_to_inverse+=("$@") + return 0 +} + # This takes LOG_ASSET, which can and should include an extension. function do_with_log_asset() { # @TODO: check that CURRENT_LOGGING_COUNTER is set, otherwise crazy?