feat: add start callback call

This commit is contained in:
gmega 2025-06-20 16:27:21 -03:00
parent cead3935f8
commit dbbad8acfd
No known key found for this signature in database
GPG Key ID: 6290D34EAD824B18
2 changed files with 29 additions and 13 deletions

View File

@ -17,7 +17,7 @@ source "${LIB_SRC}/utils.bash"
_pm_output=$(clh_output_folder "pm")
_pm_pid=""
declare -A _pm_callbacks
declare -g -A _pm_callbacks
_pm_init_output() {
rm -rf "${_pm_output}" || true
@ -248,14 +248,10 @@ pm_async() {
done
(
_pm_invoke_callback "start" "$proc_type" "$BASHPID"
"${command[@]}"
exit_code=$?
if [ -n "$proc_type" ]; then
# calls the callback for this proc type
if [ -n "${_pm_callbacks[$proc_type]}" ]; then
"${_pm_callbacks[$proc_type]}" "$proc_type" "$BASHPID" "$exit_code"
fi
fi
_pm_invoke_callback "exit" "$proc_type" "$BASHPID" "$exit_code"
pm_job_exit "$exit_code"
) &
pm_track_last_job
@ -263,12 +259,20 @@ pm_async() {
}
pm_register_callback() {
_pm_assert_state_not "running" || return 1
local proc_type="$1" callback="$2"
_pm_callbacks[$proc_type]="$callback"
}
_pm_invoke_callback() {
local event="$1" proc_type="$2" pid="$3" exit_code="$4"
if [ -n "$proc_type" ]; then
# calls the callback for this proc type
if [ -n "${_pm_callbacks[$proc_type]}" ]; then
"${_pm_callbacks[$proc_type]}" "$event" "$proc_type" "$pid" "$exit_code"
fi
fi
}
_pm_list_descendants() {
local parent="$1"
result+=("${parent}")

View File

@ -164,8 +164,14 @@ setup() {
@test "should call lifecycle callbacks when processes start and stop" {
callback() {
local proc_type="$1" pid="$2" exit_code="$3"
touch "${_pm_output}/${pid}-${proc_type}-${exit_code}"
local event="$1" proc_type="$2" pid="$3" exit_code
if [ "$event" = "start" ]; then
touch "${_pm_output}/${pid}-${proc_type}-start"
elif [ "$event" = "exit" ]; then
exit_code="$4"
touch "${_pm_output}/${pid}-${proc_type}-${exit_code}-exit"
fi
}
pm_register_callback "sleepy" "callback"
@ -174,14 +180,20 @@ setup() {
pid1=$(pm_async sleep 0.1 -%- "sleepy")
pid2=$(pm_async sleep 0.1 -%- "sleepy")
pid3=$(pm_async sleep 0.1 -%- "awake")
await "$pid1"
await "$pid2"
await "$pid3"
pm_stop
assert_equal "$(pm_state)" "halted"
assert [ -f "${_pm_output}/${pid1}-sleepy-0" ]
assert [ -f "${_pm_output}/${pid2}-sleepy-0" ]
assert [ -f "${_pm_output}/${pid1}-sleepy-start" ]
assert [ -f "${_pm_output}/${pid1}-sleepy-0-exit" ]
assert [ -f "${_pm_output}/${pid1}-sleepy-start" ]
assert [ -f "${_pm_output}/${pid2}-sleepy-0-exit" ]
assert [ ! -f "${_pm_output}/${pid3}-awake-start" ]
assert [ ! -f "${_pm_output}/${pid3}-awake-0-exit" ]
}