From ae711c0f332f4f24c843e59d6d5783e398e21b38 Mon Sep 17 00:00:00 2001 From: David Knaack Date: Sun, 3 Mar 2024 17:59:23 +0100 Subject: [PATCH] feat(bash): use PS0 for preexec hook (#5735) --- src/init/starship.bash | 32 +++++++++++++++++++++----------- 1 file changed, 21 insertions(+), 11 deletions(-) diff --git a/src/init/starship.bash b/src/init/starship.bash index c59fb5a4a..1e6a972b0 100644 --- a/src/init/starship.bash +++ b/src/init/starship.bash @@ -75,7 +75,7 @@ starship_precmd() { STARSHIP_END_TIME=$(::STARSHIP:: time) STARSHIP_DURATION=$((STARSHIP_END_TIME - STARSHIP_START_TIME)) ARGS+=( --cmd-duration="${STARSHIP_DURATION}") - unset STARSHIP_START_TIME + STARSHIP_START_TIME="" fi PS1="$(::STARSHIP:: prompt "${ARGS[@]}")" if [[ ${BLE_ATTACHED-} ]]; then @@ -98,17 +98,27 @@ elif [[ -n "${bash_preexec_imported:-}" || -n "${__bp_imported:-}" || -n "${pree preexec_functions+=(starship_preexec_all) precmd_functions+=(starship_precmd) else - # We want to avoid destroying an existing DEBUG hook. If we detect one, create - # a new function that runs both the existing function AND our function, then - # re-trap DEBUG to use this new function. This prevents a trap clobber. - dbg_trap="$(trap -p DEBUG | cut -d' ' -f3 | tr -d \')" - if [[ -z "$dbg_trap" ]]; then - trap 'starship_preexec "$_"' DEBUG - elif [[ "$dbg_trap" != 'starship_preexec "$_"' && "$dbg_trap" != 'starship_preexec_all "$_"' ]]; then - starship_preexec_all() { - local PREV_LAST_ARG=$1 ; $dbg_trap; starship_preexec; : "$PREV_LAST_ARG"; + if [[ -n "${BASH_VERSION-}" ]] && [[ "${BASH_VERSINFO[0]}" -gt 4 || ( "${BASH_VERSINFO[0]}" -eq 4 && "${BASH_VERSINFO[1]}" -ge 4 ) ]]; then + starship_preexec_ps0() { + ::STARSHIP:: time } - trap 'starship_preexec_all "$_"' DEBUG + # In order to set STARSHIP_START_TIME use an arithmetic expansion that evaluates to 0 + # To avoid printing anything, use the return value in an ${var:offset:length} substring expansion + # with offset and length evaluating to 0. + PS0='${STARSHIP_START_TIME:$((STARSHIP_START_TIME="$(starship_preexec_ps0)",STARSHIP_PREEXEC_READY=0,0)):0}'"${PS0-}" + else + # We want to avoid destroying an existing DEBUG hook. If we detect one, create + # a new function that runs both the existing function AND our function, then + # re-trap DEBUG to use this new function. This prevents a trap clobber. + dbg_trap="$(trap -p DEBUG | cut -d' ' -f3 | tr -d \')" + if [[ -z "$dbg_trap" ]]; then + trap 'starship_preexec "$_"' DEBUG + elif [[ "$dbg_trap" != 'starship_preexec "$_"' && "$dbg_trap" != 'starship_preexec_all "$_"' ]]; then + starship_preexec_all() { + local PREV_LAST_ARG=$1 ; $dbg_trap; starship_preexec; : "$PREV_LAST_ARG"; + } + trap 'starship_preexec_all "$_"' DEBUG + fi fi # Finally, prepare the precmd function and set up the start time. We will avoid to