Skip to content

Commit

Permalink
Fix bug where TRAP_POINTER was incorrect
Browse files Browse the repository at this point in the history
  • Loading branch information
andsens committed Jan 21, 2025
1 parent cef58d8 commit 0db2a56
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 6 deletions.
12 changes: 12 additions & 0 deletions trap.bats
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,15 @@ last command'
kill -s USR2 \$BASHPID
")" ''
}

@test 'trap_remove removes correct entry in array' {
assert_equal "$(bash -ec "source $BATS_TEST_DIRNAME/trap.sh
trap_append \"echo 'should not run'\" USR2
trap1=\$TRAP_POINTER
trap_append \"echo 'should run'\" USR2
trap_remove \$trap1
trap_append \"echo 'should not run either'\" USR2
trap_remove \$TRAP_POINTER
kill -s USR2 \$BASHPID
")" 'should run'
}
14 changes: 8 additions & 6 deletions trap.sh
Original file line number Diff line number Diff line change
Expand Up @@ -26,20 +26,22 @@ trap_run() {

trap_prepend() {
trap_init
local cmd=$1 signal=$2 trap_cmd
# shellcheck disable=SC2034
TRAP_POINTER=p${#TRAP_PREPEND_CMDS[@]}
local cmd=$1 signal=$2 keys
TRAP_PREPEND_CMDS+=("$signal $cmd")
keys=("${!TRAP_PREPEND_CMDS[@]}")
# shellcheck disable=SC2034
TRAP_POINTER=p${keys[-1]}
# shellcheck disable=SC2064
trap "trap_run $signal" "$signal"
}

trap_append() {
trap_init
local cmd=$1 signal=$2 trap_cmd
# shellcheck disable=SC2034
TRAP_POINTER=a${#TRAP_APPEND_CMDS[@]}
local cmd=$1 signal=$2 keys
TRAP_APPEND_CMDS+=("$signal $cmd")
keys=("${!TRAP_APPEND_CMDS[@]}")
# shellcheck disable=SC2034
TRAP_POINTER=a${keys[-1]}
# shellcheck disable=SC2064
trap "trap_run $signal" "$signal"
}
Expand Down

0 comments on commit 0db2a56

Please sign in to comment.