mxsh 0.1.0

Embeddable POSIX-style shell parser and runtime
Documentation
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
use std::collections::{HashMap, VecDeque};
use std::io;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::thread::JoinHandle;

use super::*;

/// Type alias for in-memory command implementations.
pub type InMemoryCommand =
    Arc<dyn Fn(&[String], &[(String, String)], &Path, SpawnStdio) -> i32 + Send + Sync>;

/// In-memory implementation of the runtime trait for testing.
///
/// External commands are dispatched to registered closures.
pub struct InMemoryRuntime {
    commands: HashMap<String, InMemoryCommand>,
    next_job_id: u32,
    pending: HashMap<u32, JoinHandle<i32>>,
}

impl Clone for InMemoryRuntime {
    fn clone(&self) -> Self {
        Self {
            commands: self.commands.clone(),
            next_job_id: self.next_job_id,
            pending: HashMap::new(),
        }
    }
}

impl std::fmt::Debug for InMemoryRuntime {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("InMemoryRuntime")
            .field("commands_len", &self.commands.len())
            .finish()
    }
}

impl InMemoryRuntime {
    /// Create a new InMemoryRuntime with no registered commands.
    pub fn new() -> Self {
        Self {
            commands: HashMap::new(),
            next_job_id: 1,
            pending: HashMap::new(),
        }
    }

    /// Register an in-memory command implementation.
    pub fn register_command<F>(&mut self, name: &str, command: F)
    where
        F: Fn(&[String], &[(String, String)], &Path, SpawnStdio) -> i32 + Send + Sync + 'static,
    {
        self.commands.insert(name.to_string(), Arc::new(command));
    }
}

impl Default for InMemoryRuntime {
    fn default() -> Self {
        Self::new()
    }
}

impl Runtime for InMemoryRuntime {
    type ForegroundGuard = ();

    fn fork(&self) -> Result<Self, io::Error> {
        Ok(Self {
            commands: self.commands.clone(),
            next_job_id: self.next_job_id,
            pending: HashMap::new(),
        })
    }

    fn spawn_external_command(
        &mut self,
        command: &ExternalCommand,
        stdio: SpawnStdio,
        _close_fds: &[FileDescriptor],
        _mode: SpawnMode,
    ) -> Result<SpawnedProcess, io::Error> {
        fn dup_stage_fd(fd: FileDescriptor) -> (FileDescriptor, bool) {
            if !fd.is_valid() {
                return (fd, false);
            }
            match fd.dup() {
                Ok(dup) => (dup, true),
                Err(_) => (fd, false),
            }
        }

        let argv = command.argv.clone();
        let env = command.env.clone();
        let cwd = command.cwd.clone();
        let (stdin_fd, close_stdin) = dup_stage_fd(stdio.stdin_fd);
        let (stdout_fd, close_stdout) = dup_stage_fd(stdio.stdout_fd);
        let (stderr_fd, close_stderr) = dup_stage_fd(stdio.stderr_fd);
        let stage_stdio = SpawnStdio {
            stdin_fd,
            stdout_fd,
            stderr_fd,
        };
        let maybe_cmd = argv
            .first()
            .and_then(|program| self.commands.get(program))
            .cloned();
        let handle = std::thread::spawn(move || {
            let status = match maybe_cmd {
                Some(cmd) => cmd(&argv, &env, &cwd, stage_stdio),
                None => 127,
            };
            if close_stdin {
                stdin_fd.close();
            }
            if close_stdout {
                stdout_fd.close();
            }
            if close_stderr {
                stderr_fd.close();
            }
            status
        });
        let child = self.next_job_id;
        self.next_job_id += 1;
        self.pending.insert(child, handle);
        Ok(SpawnedProcess {
            handle: ProcessHandle::new(child as u64),
            display_pid: Some(child),
        })
    }

    fn wait_process(
        &mut self,
        process: ProcessHandle,
        mode: WaitMode,
    ) -> Result<ProcessEvent, io::Error> {
        let child = process.as_u64() as u32;
        match mode {
            WaitMode::Poll => {
                let Some(handle) = self.pending.get(&child) else {
                    return Ok(ProcessEvent::Exited(0));
                };
                if !handle.is_finished() {
                    return Ok(ProcessEvent::Running);
                }
                let handle = self
                    .pending
                    .remove(&child)
                    .expect("pending handle should exist");
                Ok(ProcessEvent::Exited(handle.join().unwrap_or(128)))
            }
            WaitMode::Block => {
                let Some(handle) = self.pending.remove(&child) else {
                    return Ok(ProcessEvent::Exited(0));
                };
                Ok(ProcessEvent::Exited(handle.join().unwrap_or(128)))
            }
        }
    }

    fn wait_display_pid(&mut self, display_pid: u32) -> Result<Option<i32>, io::Error> {
        if !self.pending.contains_key(&display_pid) {
            return Err(io::Error::new(
                io::ErrorKind::NotFound,
                "unknown in-memory display pid",
            ));
        }
        Ok(Some(
            self.wait_child(ProcessHandle::new(display_pid as u64)),
        ))
    }

    fn signal_process_group(
        &mut self,
        _process: ProcessHandle,
        _signal: RuntimeSignal,
    ) -> Result<(), io::Error> {
        Ok(())
    }

    fn claim_foreground(
        &mut self,
        _process: ProcessHandle,
        _tty: FileDescriptor,
    ) -> Result<Self::ForegroundGuard, io::Error> {
        Ok(())
    }

    fn release_foreground(&mut self, _guard: Self::ForegroundGuard) -> Result<(), io::Error> {
        Ok(())
    }

    fn has_command(&self, program: &str) -> bool {
        self.commands.contains_key(program)
    }

    fn resolve_command_path(&self, program: &str, path_var: &str) -> Result<PathBuf, io::Error> {
        if self.commands.contains_key(program) {
            return Ok(PathBuf::from(program));
        }
        super::resolve_command_path(program, path_var)
    }

    fn exec_replace(
        &self,
        _program: &str,
        _argv: &[String],
        _env: &[(String, String)],
        _cwd: &Path,
    ) -> Result<(), io::Error> {
        Err(io::Error::new(
            io::ErrorKind::Unsupported,
            "exec is unavailable in the in-memory runtime",
        ))
    }
}

#[derive(Clone, Debug)]
enum DeterministicSpawn {
    Spawn(DeterministicProcess),
    Fail {
        kind: io::ErrorKind,
        message: String,
    },
}

#[derive(Clone, Debug)]
struct DeterministicProcess {
    handle: ProcessHandle,
    display_pid: Option<u32>,
    poll_events: VecDeque<ProcessEvent>,
    block_events: VecDeque<ProcessEvent>,
    last_event: ProcessEvent,
}

impl DeterministicProcess {
    fn next_event(&mut self, mode: WaitMode) -> ProcessEvent {
        let next = match mode {
            WaitMode::Poll => self.poll_events.pop_front(),
            WaitMode::Block => self.block_events.pop_front(),
        };
        if let Some(event) = next {
            self.last_event = event;
            event
        } else {
            self.last_event
        }
    }

    fn is_terminal(&self) -> bool {
        matches!(
            self.last_event,
            ProcessEvent::Exited(_) | ProcessEvent::Signaled(_)
        )
    }
}

/// Deterministic runtime for testing job lifecycle and job-control behavior.
#[derive(Clone, Debug, Default)]
pub struct DeterministicRuntime {
    next_handle: u64,
    queued_spawns: VecDeque<DeterministicSpawn>,
    processes: HashMap<ProcessHandle, DeterministicProcess>,
    display_to_handle: HashMap<u32, ProcessHandle>,
    recorded_signals: Vec<(ProcessHandle, RuntimeSignal)>,
    foreground_claims: Vec<(ProcessHandle, FileDescriptor)>,
    foreground_releases: usize,
}

impl DeterministicRuntime {
    /// Create an empty deterministic runtime.
    pub fn new() -> Self {
        Self {
            next_handle: 1,
            queued_spawns: VecDeque::new(),
            processes: HashMap::new(),
            display_to_handle: HashMap::new(),
            recorded_signals: Vec::new(),
            foreground_claims: Vec::new(),
            foreground_releases: 0,
        }
    }

    /// Queue one successful spawn with the provided wait events.
    pub fn push_spawn(
        &mut self,
        display_pid: Option<u32>,
        poll_events: impl IntoIterator<Item = ProcessEvent>,
        block_events: impl IntoIterator<Item = ProcessEvent>,
    ) -> ProcessHandle {
        let handle = ProcessHandle::new(self.next_handle);
        self.next_handle += 1;
        let process = DeterministicProcess {
            handle,
            display_pid,
            poll_events: poll_events.into_iter().collect(),
            block_events: block_events.into_iter().collect(),
            last_event: ProcessEvent::Running,
        };
        self.queued_spawns
            .push_back(DeterministicSpawn::Spawn(process));
        handle
    }

    /// Queue one failed spawn.
    pub fn push_spawn_error(&mut self, kind: io::ErrorKind, message: impl Into<String>) {
        self.queued_spawns.push_back(DeterministicSpawn::Fail {
            kind,
            message: message.into(),
        });
    }

    /// Return the semantic signals recorded so far.
    pub fn recorded_signals(&self) -> &[(ProcessHandle, RuntimeSignal)] {
        &self.recorded_signals
    }

    /// Return the foreground claims recorded so far.
    pub fn foreground_claims(&self) -> &[(ProcessHandle, FileDescriptor)] {
        &self.foreground_claims
    }

    /// Return the number of foreground releases performed so far.
    pub fn foreground_releases(&self) -> usize {
        self.foreground_releases
    }
}

impl Runtime for DeterministicRuntime {
    type ForegroundGuard = (ProcessHandle, FileDescriptor);

    fn fork(&self) -> Result<Self, io::Error> {
        Ok(Self {
            next_handle: self.next_handle,
            queued_spawns: VecDeque::new(),
            processes: HashMap::new(),
            display_to_handle: HashMap::new(),
            recorded_signals: Vec::new(),
            foreground_claims: Vec::new(),
            foreground_releases: 0,
        })
    }

    fn spawn_external_command(
        &mut self,
        _command: &ExternalCommand,
        _stdio: SpawnStdio,
        _close_fds: &[FileDescriptor],
        _mode: SpawnMode,
    ) -> Result<SpawnedProcess, io::Error> {
        match self.queued_spawns.pop_front() {
            Some(DeterministicSpawn::Spawn(process)) => {
                let display_pid = process.display_pid;
                let handle = process.handle;
                if let Some(display_pid) = display_pid {
                    self.display_to_handle.insert(display_pid, handle);
                }
                self.processes.insert(handle, process);
                Ok(SpawnedProcess {
                    handle,
                    display_pid,
                })
            }
            Some(DeterministicSpawn::Fail { kind, message }) => Err(io::Error::new(kind, message)),
            None => Err(io::Error::new(
                io::ErrorKind::NotFound,
                "no queued deterministic spawn",
            )),
        }
    }

    fn wait_process(
        &mut self,
        process: ProcessHandle,
        mode: WaitMode,
    ) -> Result<ProcessEvent, io::Error> {
        let Some(proc_state) = self.processes.get_mut(&process) else {
            return Err(io::Error::new(
                io::ErrorKind::NotFound,
                "unknown deterministic process handle",
            ));
        };
        let event = proc_state.next_event(mode);
        let finished = proc_state.is_terminal();
        let finished_display_pid = proc_state.display_pid;
        if finished {
            if let Some(display_pid) = finished_display_pid {
                self.display_to_handle.remove(&display_pid);
            }
            self.processes.remove(&process);
        }
        Ok(event)
    }

    fn wait_display_pid(&mut self, display_pid: u32) -> Result<Option<i32>, io::Error> {
        let handle = *self.display_to_handle.get(&display_pid).ok_or_else(|| {
            io::Error::new(io::ErrorKind::NotFound, "unknown deterministic display pid")
        })?;
        Ok(Some(self.wait_child(handle)))
    }

    fn signal_process_group(
        &mut self,
        process: ProcessHandle,
        signal: RuntimeSignal,
    ) -> Result<(), io::Error> {
        self.recorded_signals.push((process, signal));
        Ok(())
    }

    fn claim_foreground(
        &mut self,
        process: ProcessHandle,
        tty: FileDescriptor,
    ) -> Result<Self::ForegroundGuard, io::Error> {
        self.foreground_claims.push((process, tty));
        Ok((process, tty))
    }

    fn release_foreground(&mut self, _guard: Self::ForegroundGuard) -> Result<(), io::Error> {
        self.foreground_releases += 1;
        Ok(())
    }

    fn resolve_command_path(&self, program: &str, _path_var: &str) -> Result<PathBuf, io::Error> {
        Ok(PathBuf::from(program))
    }

    fn exec_replace(
        &self,
        _program: &str,
        _argv: &[String],
        _env: &[(String, String)],
        _cwd: &Path,
    ) -> Result<(), io::Error> {
        Err(io::Error::new(
            io::ErrorKind::Unsupported,
            "exec is unavailable in the deterministic runtime",
        ))
    }
}