-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtraps.bash
114 lines (97 loc) · 2.42 KB
/
traps.bash
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#!/usr/bin/env bash
traps__exit_trap=()
traps__err_trap=()
traps__int_trap=()
traps__err_ignore=0
traps__set_up=0
import log
traps::add_exit_trap() {
local handler=$1
traps::_init
traps__exit_trap=( "$handler" "${traps__exit_trap[@]}" )
}
traps::add_err_trap() {
local handler=$1
traps::_init
traps__err_trap=( "$handler" "${traps__err_trap[@]}" )
}
traps::add_int_trap() {
local handler=$1
traps::_init
traps__int_trap=( "$handler" "${traps__int_trap[@]}" )
}
traps::_handle_exit() {
log::debug "Handling EXIT traps"
for cb in "${traps__exit_trap[@]}";do
$cb
done
if [ -z "$BASH_LIB_UNDER_TEST" ];then
exit
fi
}
traps::_handle_int() {
log::debug "Handling INT traps"
for cb in "${traps__int_trap[@]}";do
$cb
done
if [ -z "$BASH_LIB_UNDER_TEST" ];then
exit
fi
}
traps::_handle_err() {
local err=$?
log::debug "Handling ERR traps"
if [ "$traps__err_ignore" = "1" ];then
return 0
fi
for cb in "${traps__err_trap[@]}";do
$cb "$err"
done
}
traps::_init() {
if [ "$BASHPID" != "$traps__set_up" ];then
log::debug "Setting up traps for $BASHPID"
traps__set_up=$BASHPID
traps__exit_trap=()
traps__int_trap=()
fi
if [ -z "$BASH_LIB_UNDER_TEST" ];then
trap traps::_handle_exit EXIT TERM
trap traps::_handle_err ERR
trap traps::_handle_int INT
fi
}
traps::ignore_err_start() {
traps__err_ignore=1
}
traps::ignore_err_end() {
traps__err_ignore=0
}
traps_test::_example_handler_1() {
traps_test__handled1=yes
}
traps_test::_example_handler_2() {
traps_test__handled2=yes
}
traps_test::handling_exit_traps() {
traps_test__handled1=no
traps_test__handled2=no
traps::add_exit_trap traps_test::_example_handler_1
traps::add_exit_trap traps_test::_example_handler_2
traps::_handle_exit
unit::assert_eq "$traps_test__handled1" yes
unit::assert_eq "$traps_test__handled2" yes
}
traps_test::handling_int_traps() {
traps_test__handled1=no
traps_test__handled2=no
traps::add_int_trap traps_test::_example_handler_1
traps::add_int_trap traps_test::_example_handler_2
traps::_handle_int
unit::assert_eq "$traps_test__handled1" yes
unit::assert_eq "$traps_test__handled2" yes
}
traps_test::all() {
unit::test traps_test::handling_exit_traps
unit::test traps_test::handling_int_traps
}