Skip to content

Commit

Permalink
feat(bash): use PS0 for preexec hook (#5735)
Browse files Browse the repository at this point in the history
  • Loading branch information
davidkna committed Mar 3, 2024
1 parent 7290c5e commit ae711c0
Showing 1 changed file with 21 additions and 11 deletions.
32 changes: 21 additions & 11 deletions src/init/starship.bash
Expand Up @@ -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
Expand All @@ -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
Expand Down

0 comments on commit ae711c0

Please sign in to comment.