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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
//! Encapsulation of execution results.
#[cfg(unix)]
use std::os::unix::process::ExitStatusExt;
use crate::{error, processes};
/// Represents the result of executing a command or similar item.
#[derive(Default)]
pub struct ExecutionResult {
/// The control flow transition to apply after execution.
pub next_control_flow: ExecutionControlFlow,
/// The exit code resulting from execution.
pub exit_code: ExecutionExitCode,
}
impl ExecutionResult {
/// Returns a new `ExecutionResult` with the given exit code.
///
/// # Arguments
///
/// * `exit_code` - The exit code of the command.
pub fn new(exit_code: u8) -> Self {
Self {
exit_code: exit_code.into(),
..Self::default()
}
}
/// Returns a new `ExecutionResult` reflecting a process that was stopped.
pub fn stopped() -> Self {
// TODO(jobs): Decide how to sort this out in a platform-independent way.
const SIGTSTP: std::os::raw::c_int = 20;
#[expect(clippy::cast_possible_truncation)]
Self::new(128 + SIGTSTP as u8)
}
/// Returns a new `ExecutionResult` with an exit code of 0.
pub const fn success() -> Self {
Self {
next_control_flow: ExecutionControlFlow::Normal,
exit_code: ExecutionExitCode::Success,
}
}
/// Returns a new `ExecutionResult` with a general error exit code.
pub const fn general_error() -> Self {
Self {
next_control_flow: ExecutionControlFlow::Normal,
exit_code: ExecutionExitCode::GeneralError,
}
}
/// Returns whether the command was successful.
pub const fn is_success(&self) -> bool {
self.exit_code.is_success()
}
/// Returns whether the execution result indicates normal control flow.
/// Returns `false` if there is any control flow transition requested.
pub const fn is_normal_flow(&self) -> bool {
matches!(self.next_control_flow, ExecutionControlFlow::Normal)
}
/// Returns whether the execution result indicates a loop break.
pub const fn is_break(&self) -> bool {
matches!(
self.next_control_flow,
ExecutionControlFlow::BreakLoop { .. }
)
}
/// Returns whether the execution result indicates a loop continue.
pub const fn is_continue(&self) -> bool {
matches!(
self.next_control_flow,
ExecutionControlFlow::ContinueLoop { .. }
)
}
/// Returns whether the execution result indicates an early return
/// from a function or script, or an exit from the shell. Returns `false`
/// otherwise, including loop breaks or continues.
pub const fn is_return_or_exit(&self) -> bool {
matches!(
self.next_control_flow,
ExecutionControlFlow::ReturnFromFunctionOrScript | ExecutionControlFlow::ExitShell
)
}
}
impl From<ExecutionExitCode> for ExecutionResult {
fn from(exit_code: ExecutionExitCode) -> Self {
Self {
next_control_flow: ExecutionControlFlow::Normal,
exit_code,
}
}
}
impl From<ExecutionWaitResult> for ExecutionResult {
fn from(wait_result: ExecutionWaitResult) -> Self {
match wait_result {
ExecutionWaitResult::Completed(result) => result,
// TODO(jobs): We need to job-manage the stopped process.
ExecutionWaitResult::Stopped(..) => Self::stopped(),
}
}
}
impl From<std::process::Output> for ExecutionResult {
fn from(output: std::process::Output) -> Self {
if let Some(code) = output.status.code() {
#[expect(clippy::cast_sign_loss)]
return Self::new((code & 0xFF) as u8);
}
#[cfg(unix)]
if let Some(signal) = output.status.signal() {
#[expect(clippy::cast_sign_loss)]
return Self::new((signal & 0xFF) as u8 + 128);
}
tracing::error!("unhandled process exit");
Self::new(127)
}
}
/// Represents an exit code from execution.
#[derive(Clone, Copy, Default)]
pub enum ExecutionExitCode {
/// Indicates successful execution.
#[default]
Success,
/// Indicates a general error.
GeneralError,
/// Indicates invalid usage.
InvalidUsage,
/// Cannot execute the command.
CannotExecute,
/// Indicates a command or similar item was not found.
NotFound,
/// Indicates execution was interrupted.
Interrupted,
/// Indicates a broken pipe (SIGPIPE) was encountered.
BrokenPipe,
/// Indicates unimplemented functionality was encountered.
Unimplemented,
/// A custom exit code.
Custom(u8),
}
impl ExecutionExitCode {
/// Returns whether the exit code indicates success.
pub const fn is_success(&self) -> bool {
matches!(self, Self::Success)
}
}
impl From<u8> for ExecutionExitCode {
fn from(code: u8) -> Self {
match code {
0 => Self::Success,
1 => Self::GeneralError,
2 => Self::InvalidUsage,
99 => Self::Unimplemented,
126 => Self::CannotExecute,
127 => Self::NotFound,
130 => Self::Interrupted,
141 => Self::BrokenPipe,
code => Self::Custom(code),
}
}
}
impl From<ExecutionExitCode> for u8 {
fn from(code: ExecutionExitCode) -> Self {
Self::from(&code)
}
}
impl From<&ExecutionExitCode> for u8 {
fn from(code: &ExecutionExitCode) -> Self {
match code {
ExecutionExitCode::Success => 0,
ExecutionExitCode::GeneralError => 1,
ExecutionExitCode::InvalidUsage => 2,
ExecutionExitCode::Unimplemented => 99,
ExecutionExitCode::CannotExecute => 126,
ExecutionExitCode::NotFound => 127,
ExecutionExitCode::Interrupted => 130,
ExecutionExitCode::BrokenPipe => 141,
ExecutionExitCode::Custom(code) => *code,
}
}
}
/// Represents a control flow transition to apply.
#[derive(Clone, Copy, Default)]
pub enum ExecutionControlFlow {
/// Continue normal execution.
#[default]
Normal,
/// Break out of an enclosing loop.
BreakLoop {
/// Identifies which level of nested loops to break out of. 0 indicates the innermost loop,
/// 1 indicates the next outer loop, and so on.
levels: usize,
},
/// Continue to the next iteration of an enclosing loop.
ContinueLoop {
/// Identifies which level of nested loops to continue. 0 indicates the innermost loop,
/// 1 indicates the next outer loop, and so on.
levels: usize,
},
/// Return from the current function or script.
ReturnFromFunctionOrScript,
/// Exit the shell.
ExitShell,
}
impl ExecutionControlFlow {
/// Attempts to decrement the loop levels for `BreakLoop` or `ContinueLoop`.
/// If the levels reach zero, transitions to `Normal`. If the control flow is not
/// a loop break or continue, no changes are made.
#[must_use]
pub const fn try_decrement_loop_levels(&self) -> Self {
match self {
Self::BreakLoop { levels: 0 } | Self::ContinueLoop { levels: 0 } => Self::Normal,
Self::BreakLoop { levels } => Self::BreakLoop {
levels: *levels - 1,
},
Self::ContinueLoop { levels } => Self::ContinueLoop {
levels: *levels - 1,
},
control_flow => *control_flow,
}
}
}
/// Represents the result of spawning an execution; captures both execution
/// that immediately returns as well as execution that starts a process
/// asynchronously.
pub enum ExecutionSpawnResult {
/// Indicates that the execution completed.
Completed(ExecutionResult),
/// Indicates that a process was started and had not yet completed.
StartedProcess(processes::ChildProcess),
/// Indicates that a task was started to handle the execution asynchronously.
StartedTask(tokio::task::JoinHandle<Result<ExecutionResult, error::Error>>),
}
impl From<ExecutionResult> for ExecutionSpawnResult {
fn from(result: ExecutionResult) -> Self {
Self::Completed(result)
}
}
impl ExecutionSpawnResult {
/// Waits for the command to complete.
pub async fn wait(self) -> Result<ExecutionWaitResult, error::Error> {
let result = match self {
Self::StartedProcess(mut child) => {
// Wait for the process to exit or for a relevant signal, whichever happens
// first.
match child.wait().await? {
processes::ProcessWaitResult::Completed(output) => {
ExecutionWaitResult::Completed(ExecutionResult::from(output))
}
processes::ProcessWaitResult::Stopped => ExecutionWaitResult::Stopped(child),
}
}
Self::Completed(result) => ExecutionWaitResult::Completed(result),
Self::StartedTask(join_handle) => {
let result = join_handle.await?;
ExecutionWaitResult::Completed(result?)
}
};
Ok(result)
}
pub(crate) async fn poll(self) -> Result<ExecutionWaitResult, error::Error> {
let result = match self {
Self::StartedProcess(child) => ExecutionWaitResult::Stopped(child),
Self::Completed(result) => ExecutionWaitResult::Completed(result),
Self::StartedTask(join_handle) => {
// TODO(jobs): This isn't right.
let result = join_handle.await?;
ExecutionWaitResult::Completed(result?)
}
};
Ok(result)
}
}
/// Represents the result of waiting for an execution to complete.
pub enum ExecutionWaitResult {
/// Indicates that the execution completed.
Completed(ExecutionResult),
/// Indicates that the execution was stopped.
Stopped(processes::ChildProcess),
}