Skip to main content

clash_brush_core/shell/
traps.rs

1//! Trap handling for the shell.
2
3use crate::{ExecutionResult, ProcessGroupPolicy, error};
4
5impl<SE: crate::extensions::ShellExtensions> crate::Shell<SE> {
6    /// Runs any exit steps for the shell.
7    pub async fn on_exit(&mut self) -> Result<(), error::Error> {
8        self.invoke_exit_trap_handler_if_registered().await?;
9
10        Ok(())
11    }
12
13    async fn invoke_exit_trap_handler_if_registered(
14        &mut self,
15    ) -> Result<ExecutionResult, error::Error> {
16        let Some(handler) = self
17            .traps
18            .get_handler(crate::traps::TrapSignal::Exit)
19            .cloned()
20        else {
21            return Ok(ExecutionResult::success());
22        };
23
24        // TODO(traps): Confirm whether trap handlers should be executed in the same process group.
25        let mut params = self.default_exec_params();
26        params.process_group_policy = ProcessGroupPolicy::SameProcessGroup;
27
28        let orig_last_exit_status = self.last_exit_status;
29
30        self.enter_trap_handler(Some(&handler));
31
32        let result = self
33            .run_string(&handler.command, &handler.source_info, &params)
34            .await;
35
36        self.leave_trap_handler();
37        self.last_exit_status = orig_last_exit_status;
38
39        result
40    }
41}