Skip to content

Commit

Permalink
feat(debug): Add color and line numbers to debug
Browse files Browse the repository at this point in the history
- [x] feat(debug): ✨ add color to PS4 prompt
  - [x] use `strftime(3)` formatting
  - [x] standardise timestamps to UTC
  - [x] save and restore TZ if sourced
- [x] perf(log): ⚡️ use `printf` to remove fork() to date in
  - [x] perf(debug): do not `xtrace` log function
- [x] refactor(err_report): 🔨 prevent potential ERR trap recursion
- [x] style(): 🚨 shellcheck linting to pass CI
- [x] docs(README): 👥 add @virgilwashere to authors
- [x] docs(changelog): 📝 changelog entries for debug mode

- [x] ✅ `main-debug-ps4` scenario and fixture

- kvz#103
- kvz#105
- kvz#107

----

PR created with `GitHub Pull Request` inside `vscode` 😁
  • Loading branch information
virgilwashere committed Jun 28, 2019
1 parent 7b7d31a commit 7f144c6
Show file tree
Hide file tree
Showing 8 changed files with 282 additions and 19 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ Released: TBA.
- [x] Fix typo in FAQ (#92, @gmasse)
- [x] Fix Travis CI failure on src/templater.sh (@gmasse)
- [x] Add magic variable which contains full command invocation
- [x] Add line numbers and colour mode to debug mode (#103, #105, @virgilwashere)
- [x] Fix Travis CI failure with `shellcheck` on src/main.sh (#103, #107 @virgilwashere)

## v2.3.0

Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,7 @@ We are looking for endorsements! Are you also using b3bp? [Let us know](https://
- [Giovanni Saponaro](https://github.com/gsaponaro) (feedback)
- [Germain Masse](https://github.com/gmasse)
- [A. G. Madi](https://github.com/warpengineer)
- [Virgil](https://github.com/virgilwashere)

## License

Expand Down
17 changes: 11 additions & 6 deletions example.sh
Original file line number Diff line number Diff line change
Expand Up @@ -72,11 +72,21 @@ __b3bp_err_report() {
### Command-line argument switches (like -d for debugmode, -h for showing helppage)
##############################################################################

# no color mode
if [[ "${arg_n:?}" = "1" ]]; then
NO_COLOR="true"
fi

# debug mode
if [[ "${arg_d:?}" = "1" ]]; then
set -o xtrace
PS4='+(${BASH_SOURCE}:${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }'
LOG_LEVEL="7"
if [[ "${NO_COLOR:-}" = "true" ]]; then
# [!] Don't change to double quotes
export PS4='+\011\t ${BASH_SOURCE}:${LINENO} \011 ${FUNCNAME[0]:+${FUNCNAME[0]}:\011 }'
else
export PS4='+\011\e[1;30m\D{%F %T %Z} \e[1;34m${BASH_SOURCE}\e[0m:\e[1;36m${LINENO}\e[0m \011 ${FUNCNAME[0]:+\e[0;35m${FUNCNAME[0]}\e[1;30m()\e[0m:\011 }'
fi
# Enable error backtracing
trap '__b3bp_err_report "${FUNCNAME:-.}" ${LINENO}' ERR
fi
Expand All @@ -86,11 +96,6 @@ if [[ "${arg_v:?}" = "1" ]]; then
set -o verbose
fi

# no color mode
if [[ "${arg_n:?}" = "1" ]]; then
NO_COLOR="true"
fi

# help mode
if [[ "${arg_h:?}" = "1" ]]; then
# Help exists with code 1
Expand Down
74 changes: 62 additions & 12 deletions main.sh
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ fi
__dir="$(cd "$(dirname "${BASH_SOURCE[${__b3bp_tmp_source_idx:-0}]}")" && pwd)"
__file="${__dir}/$(basename "${BASH_SOURCE[${__b3bp_tmp_source_idx:-0}]}")"
__base="$(basename "${__file}" .sh)"
__invocation="$(printf %q "${__file}")$((($#)) && printf ' %q' "$@" || true)"
# shellcheck disable=SC2034
__invocation="$( printf %q "${__file}")$( { (($#)) && printf ' %q' "$@"; } || true)"

# Define the environment variables (and their defaults) that this script depends on
LOG_LEVEL="${LOG_LEVEL:-6}" # 7 = debug -> 0 = emergency
Expand All @@ -58,6 +59,11 @@ NO_COLOR="${NO_COLOR:-}" # true = disable color. otherwise autodetected
##############################################################################

function __b3bp_log () {
# limit xtrace debug logging of the logging
if [[ -o xtrace ]]; then
local __b3bp_tmp_xtrace=1
set +o xtrace
fi
local log_level="${1}"
shift

Expand All @@ -79,11 +85,10 @@ function __b3bp_log () {
local color_emergency="\\x1b[1;4;5;33;41m"

local colorvar="color_${log_level}"

local color="${!colorvar:-${color_error}}"
local color_reset="\\x1b[0m"

if [[ "${NO_COLOR:-}" = "true" ]] || ( [[ "${TERM:-}" != "xterm"* ]] && [[ "${TERM:-}" != "screen"* ]] ) || [[ ! -t 2 ]]; then
if [[ "${NO_COLOR:-}" = "true" ]] || { [[ "${TERM:-}" != "xterm"* ]] && [[ "${TERM:-}" != "screen"* ]]; } || [[ ! -t 2 ]]; then
if [[ "${NO_COLOR:-}" != "false" ]]; then
# Don't use colors on pipes or non-recognized terminals
color=""; color_reset=""
Expand All @@ -92,12 +97,15 @@ function __b3bp_log () {

# all remaining arguments are to be printed
local log_line=""

while IFS=$'\n' read -r log_line; do
echo -e "$(date -u +"%Y-%m-%d %H:%M:%S UTC") ${color}$(printf "[%9s]" "${log_level}")${color_reset} ${log_line}" 1>&2
TZ=UTC echo -e "$(date -u +"%F %T %Z")" "${color}$(printf "[%9s]" "${log_level}")${color_reset} ${log_line}" 1>&2
done <<< "${@:-}"
# turn xtrace back on if we disabled it
((${__b3bp_tmp_xtrace:-})) && set -o xtrace
unset -v __b3bp_tmp_xtrace
}


function emergency () { __b3bp_log emergency "${@}"; exit 1; }
function alert () { [[ "${LOG_LEVEL:-0}" -ge 1 ]] && __b3bp_log alert "${@}"; true; }
function critical () { [[ "${LOG_LEVEL:-0}" -ge 2 ]] && __b3bp_log critical "${@}"; true; }
Expand Down Expand Up @@ -318,6 +326,9 @@ fi
##############################################################################

function __b3bp_cleanup_before_exit () {
if ! ((__i_am_main_script)); then
[[ -v __b3bp_tmp_tz ]] && TZ="${__b3bp_tmp_tz-}"
fi
info "Cleaning up. Done"
}
trap __b3bp_cleanup_before_exit EXIT
Expand All @@ -326,7 +337,13 @@ trap __b3bp_cleanup_before_exit EXIT
__b3bp_err_report() {
local error_code
error_code=${?}
error "Error in ${__file} in function ${1} on line ${2}"
# Disable the trap handler to prevent potential recursion
trap - ERR
# Consider any further errors non-fatal to ensure we run to completion
set +o errexit
set +o pipefail
error "Error in ${__file} in function ${1} on or around line ${2}"
# Exit with failure status
exit ${error_code}
}
# Uncomment the following line for always providing an error backtrace
Expand All @@ -336,11 +353,49 @@ __b3bp_err_report() {
### Command-line argument switches (like -d for debugmode, -h for showing helppage)
##############################################################################

# no color mode
if [[ "${arg_n:?}" = "1" ]]; then
NO_COLOR="true"
fi

# debug mode
if [[ "${arg_d:?}" = "1" ]]; then
set -o xtrace
PS4='+(${BASH_SOURCE}:${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }'
LOG_LEVEL="7"

### PS4 - Debug prompt string (when using `set -o xtrace`)
##############################################################################

# When debugging a shell script via `set -x` or `set -o xtrace`
# this tricked-out prompt is used.
#
# The first character (+) is used and repeated for stack depth (subshells).
# Then insert a tab (\011), a timestamp (\D) in strftime(3),
# (source)filename, line number and function name
# And finally, the actual line of code.
# %F Equivalent to %Y-%m-%d (the ISO 8601 date format). (C99)
# %T The time in 24-hour notation (%H:%M:%S). (SU)
# %Z The timezone name or abbreviation.
#+ 2019-06-27 23:45:21 UTC ./main.sh:299 main(): help 'Option -f (--file) requires an argument'
#+ 2019-06-27 23:45:21 UTC ./main.sh:116 help(): echo ''

if [[ ! "${TZ-}" = "UTC" ]]; then
declare TZ
# save TZ if we are sourced
if ! ((__i_am_main_script)); then
declare __b3bp_tmp_tz
__b3bp_tmp_tz="${TZ-}"
fi
debug "Setting timezone to UTC for standardised logging"
TZ="UTC"
fi
if [[ "${NO_COLOR:-}" = "true" ]]; then
# [!] Don't change to double quotes
export PS4='+\011\t ${BASH_SOURCE}:${LINENO} \011 ${FUNCNAME[0]:+${FUNCNAME[0]}:\011 }'
else
# the 'debug-so-fancy' coloured version. no double quotes here either
export PS4='+\011\e[1;30m\D{%F %T %Z} \e[1;34m${BASH_SOURCE}\e[0m:\e[1;36m${LINENO}\e[0m \011 ${FUNCNAME[0]:+\e[0;35m${FUNCNAME[0]}\e[1;30m()\e[0m:\011 }'
fi
# Enable error backtracing
trap '__b3bp_err_report "${FUNCNAME:-.}" ${LINENO}' ERR
fi
Expand All @@ -350,11 +405,6 @@ if [[ "${arg_v:?}" = "1" ]]; then
set -o verbose
fi

# no color mode
if [[ "${arg_n:?}" = "1" ]]; then
NO_COLOR="true"
fi

# help mode
if [[ "${arg_h:?}" = "1" ]]; then
# Help exists with code 1
Expand Down
2 changes: 1 addition & 1 deletion test/acceptance.sh
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ while IFS=$'\n' read -r scenario; do
"${curFile}"
fi
if grep -q 'ACCPTST:STDIO_REPLACE_DATETIMES' "${curFile}"; then
# Such as: 2016-02-10 15:38:44.420094
# Such as: 2019-06-27 23:45:21
"${cmdSed}" -i \
-r 's@[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}@{datetime}@g' \
"${curFile}"
Expand Down
1 change: 1 addition & 0 deletions test/fixture/main-debug-ps4.exitcode
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
1
Loading

0 comments on commit 7f144c6

Please sign in to comment.