Skip to main content

bashkit/interpreter/
state.rs

1//! Interpreter state types
2
3/// Control flow signals from commands like break, continue, return
4#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
5pub enum ControlFlow {
6    #[default]
7    None,
8    /// Break out of a loop (with optional level count)
9    Break(u32),
10    /// Continue to next iteration (with optional level count)
11    Continue(u32),
12    /// Return from a function (with exit code)
13    Return(i32),
14}
15
16/// Result of executing a bash script.
17#[derive(Debug, Clone, Default)]
18pub struct ExecResult {
19    /// Standard output
20    pub stdout: String,
21    /// Standard error
22    pub stderr: String,
23    /// Exit code
24    pub exit_code: i32,
25    /// Control flow signal (break, continue, return)
26    pub control_flow: ControlFlow,
27}
28
29impl ExecResult {
30    /// Create a successful result with the given stdout.
31    pub fn ok(stdout: impl Into<String>) -> Self {
32        Self {
33            stdout: stdout.into(),
34            stderr: String::new(),
35            exit_code: 0,
36            control_flow: ControlFlow::None,
37        }
38    }
39
40    /// Create a failed result with the given stderr.
41    pub fn err(stderr: impl Into<String>, exit_code: i32) -> Self {
42        Self {
43            stdout: String::new(),
44            stderr: stderr.into(),
45            exit_code,
46            control_flow: ControlFlow::None,
47        }
48    }
49
50    /// Create a result with stdout and custom exit code.
51    pub fn with_code(stdout: impl Into<String>, exit_code: i32) -> Self {
52        Self {
53            stdout: stdout.into(),
54            stderr: String::new(),
55            exit_code,
56            control_flow: ControlFlow::None,
57        }
58    }
59
60    /// Create a result with a control flow signal
61    pub fn with_control_flow(control_flow: ControlFlow) -> Self {
62        Self {
63            stdout: String::new(),
64            stderr: String::new(),
65            exit_code: 0,
66            control_flow,
67        }
68    }
69
70    /// Check if the result indicates success.
71    pub fn is_success(&self) -> bool {
72        self.exit_code == 0
73    }
74}