From dbbad8acfd4ab40775f183de57d47d6e61546faf Mon Sep 17 00:00:00 2001 From: gmega Date: Fri, 20 Jun 2025 16:27:21 -0300 Subject: [PATCH] feat: add start callback call --- src/procmon.bash | 22 +++++++++++++--------- test/test_procmon.bats | 20 ++++++++++++++++---- 2 files changed, 29 insertions(+), 13 deletions(-) diff --git a/src/procmon.bash b/src/procmon.bash index 51ddff2..7c36134 100644 --- a/src/procmon.bash +++ b/src/procmon.bash @@ -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}") diff --git a/test/test_procmon.bats b/test/test_procmon.bats index ad7cfc2..2558b89 100644 --- a/test/test_procmon.bats +++ b/test/test_procmon.bats @@ -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" ] }