pmsh 0.0.1

A custom shell written in Rust
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
use crate::builtins::{handle_builtin, BuiltinResult};
use crate::colors::red;
use crate::functions::Functions;
use crate::history::HistoryManager;
use crate::parser::Command;

use crate::ui;
use crate::variables::Variables;

pub enum ReadlineEvent {
    Line(String),
    Interrupted,
    Eof,
    Other,
}

pub trait LineEditor {
    fn readline(&mut self, prompt: &str) -> ReadlineEvent;
    fn add_history_entry(&mut self, entry: &str);
}

pub trait ExecutorTrait {
    fn execute(
        &self,
        cmd: &Command,
        vars: &mut Variables,
        functions: &mut Functions,
        history_mgr: &HistoryManager,
        command_history: &mut Vec<String>,
        oldpwd: &mut Option<String>,
    ) -> Result<(), String>;
    fn execute_pipeline(
        &self,
        pipeline: &[Command],
        vars: &mut Variables,
        functions: &mut Functions,
        history_mgr: &HistoryManager,
        command_history: &mut Vec<String>,
        oldpwd: &mut Option<String>,
    ) -> Result<(), String>;
}

pub struct RealExecutor;

impl ExecutorTrait for RealExecutor {
    fn execute(
        &self,
        cmd: &Command,
        vars: &mut Variables,
        functions: &mut Functions,
        history_mgr: &HistoryManager,
        command_history: &mut Vec<String>,
        oldpwd: &mut Option<String>,
    ) -> Result<(), String> {
        crate::executor::Executor::execute(
            cmd,
            vars,
            functions,
            history_mgr,
            command_history,
            oldpwd,
        )
    }

    fn execute_pipeline(
        &self,
        pipeline: &[Command],
        vars: &mut Variables,
        functions: &mut Functions,
        history_mgr: &HistoryManager,
        command_history: &mut Vec<String>,
        oldpwd: &mut Option<String>,
    ) -> Result<(), String> {
        crate::executor::Executor::execute_pipeline(
            pipeline,
            vars,
            functions,
            history_mgr,
            command_history,
            oldpwd,
        )
    }
}

#[allow(dead_code)]
pub struct NoOpEditor;
impl LineEditor for NoOpEditor {
    fn readline(&mut self, _prompt: &str) -> ReadlineEvent {
        ReadlineEvent::Eof
    }
    fn add_history_entry(&mut self, _entry: &str) {}
}

#[allow(clippy::too_many_arguments)]
pub fn execute_line<E: ExecutorTrait, L: LineEditor>(
    line: &str,
    editor: &mut L,
    history_mgr: &HistoryManager,
    command_history: &mut Vec<String>,
    executor: &E,
    oldpwd: &mut Option<String>,
    vars: &mut Variables,
    functions: &mut Functions,
) -> bool {
    editor.add_history_entry(line);

    if let Some(pipeline) = Command::parse_pipeline(line) {
        return execute_pipeline_struct(
            &pipeline,
            history_mgr,
            command_history,
            executor,
            oldpwd,
            vars,
            functions,
        );
    }
    true
}

pub fn execute_pipeline_struct<E: ExecutorTrait>(
    pipeline: &[Command],
    history_mgr: &HistoryManager,
    command_history: &mut Vec<String>,
    executor: &E,
    oldpwd: &mut Option<String>,
    vars: &mut Variables,
    functions: &mut Functions,
) -> bool {
    if pipeline.len() == 1 {
        // Single command: check for builtins
        let cmd = &pipeline[0];
        let builtin_res = if let Command::Simple(simple) = cmd {
            handle_builtin(simple, history_mgr, command_history, oldpwd)
        } else {
            Ok(BuiltinResult::NotHandled)
        };

        match builtin_res {
            Ok(BuiltinResult::HandledExit(code)) => std::process::exit(code),
            Ok(BuiltinResult::HandledContinue) => return true,
            Ok(BuiltinResult::SourceFile(path)) => {
                let contents = match std::fs::read_to_string(&path) {
                    Ok(c) => c,
                    Err(e) => {
                        eprintln!("pmsh: source: {}: {}", path, e);
                        return true;
                    }
                };
                // Use parse_script to handle multiline commands correctly
                match Command::parse_script(&contents) {
                    Ok(pipelines) => {
                        for pipeline in pipelines {
                            if !execute_pipeline_struct(
                                &pipeline,
                                history_mgr,
                                command_history,
                                executor,
                                oldpwd,
                                vars,
                                functions,
                            ) {
                                return false;
                            }
                        }
                    }
                    Err(e) => {
                        eprintln!("pmsh: source: error parsing script: {}", e);
                    }
                }
                return true;
            }
            Ok(BuiltinResult::NotHandled) => {
                match executor.execute(cmd, vars, functions, history_mgr, command_history, oldpwd) {
                    Ok(()) => {
                        // History saving is handled by the caller (execute_line) for the full line.
                        // We don't save individual commands from scripts/pipelines here.
                    }
                    Err(e) => eprintln!("pmsh: {}", red(&e.to_string())),
                }
            }
            Err(e) => eprintln!("Builtin error: {}", red(&e.to_string())),
        }
    } else {
        // Pipeline of multiple commands: execute via pipeline
        match executor.execute_pipeline(
            pipeline,
            vars,
            functions,
            history_mgr,
            command_history,
            oldpwd,
        ) {
            Ok(()) => {
                // History saving removed
            }
            Err(e) => eprintln!("pmsh: {}", red(&e.to_string())),
        }
    }
    true
}

pub fn run_repl_with_state<E: ExecutorTrait, L: LineEditor>(
    editor: &mut L,
    history_mgr: &HistoryManager,
    command_history: &mut Vec<String>,
    executor: &E,
    mut oldpwd: Option<String>,
    mut vars: Variables,
    mut functions: Functions,
) {
    // REPL: Read-Eval-Print Loop
    loop {
        // Read a line from the user
        let event = editor.readline(&ui::format_prompt());

        // Evaluate the line and print output or handle errors
        match event {
            ReadlineEvent::Line(line) => {
                if !execute_line(
                    &line,
                    editor,
                    history_mgr,
                    command_history,
                    executor,
                    &mut oldpwd,
                    &mut vars,
                    &mut functions,
                ) {
                    break;
                }
            }
            ReadlineEvent::Interrupted => {
                println!("^C");
                continue;
            }
            ReadlineEvent::Eof => {
                if let Err(e) = history_mgr.save(command_history) {
                    eprintln!("Warning: Could not save history: {}", e);
                }
                println!("^D");
                break;
            }
            ReadlineEvent::Other => {
                // treat as generic error and break
                break;
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    struct MockEditor {
        events: std::collections::VecDeque<ReadlineEvent>,
        history: Vec<String>,
    }

    impl MockEditor {
        fn new(events: Vec<ReadlineEvent>) -> Self {
            Self {
                events: events.into(),
                history: Vec::new(),
            }
        }
    }

    impl LineEditor for MockEditor {
        fn readline(&mut self, _prompt: &str) -> ReadlineEvent {
            self.events.pop_front().unwrap_or(ReadlineEvent::Eof)
        }

        fn add_history_entry(&mut self, entry: &str) {
            self.history.push(entry.to_string());
        }
    }

    struct MockExecutor {
        calls: std::cell::RefCell<Vec<Command>>,
    }

    impl MockExecutor {
        fn new() -> Self {
            Self {
                calls: Default::default(),
            }
        }
    }

    impl ExecutorTrait for MockExecutor {
        fn execute(
            &self,
            cmd: &Command,
            _vars: &mut Variables,
            _functions: &mut Functions,
            _history_mgr: &HistoryManager,
            _command_history: &mut Vec<String>,
            _oldpwd: &mut Option<String>,
        ) -> Result<(), String> {
            self.calls.borrow_mut().push(cmd.clone());
            Ok(())
        }

        fn execute_pipeline(
            &self,
            pipeline: &[Command],
            _vars: &mut Variables,
            _functions: &mut Functions,
            _history_mgr: &HistoryManager,
            _command_history: &mut Vec<String>,
            _oldpwd: &mut Option<String>,
        ) -> Result<(), String> {
            for cmd in pipeline {
                self.calls.borrow_mut().push(cmd.clone());
            }
            Ok(())
        }
    }

    #[test]
    fn test_repl_executes_command_and_exits_on_eof() {
        let events = vec![
            ReadlineEvent::Line("echo hello".to_string()),
            ReadlineEvent::Eof,
        ];
        let mut editor = MockEditor::new(events);

        let mgr = HistoryManager::new().unwrap_or_else(|_| HistoryManager::default());
        let mut history: Vec<String> = Vec::new();

        let executor = MockExecutor::new();

        run_repl_with_state(
            &mut editor,
            &mgr,
            &mut history,
            &executor,
            None,
            Variables::new(),
            Functions::new(),
        );

        // executor should have been called once with echo
        // executor should have been called once with echo
        let calls = executor.calls.borrow();
        assert_eq!(calls.len(), 1);
        if let Command::Simple(cmd) = &calls[0] {
            assert_eq!(cmd.name, "echo");
            assert_eq!(cmd.args, vec!["hello".to_string()]);
        } else {
            panic!("Expected Simple command");
        }
    }

    #[test]
    fn test_repl_executes_pipeline() {
        let events = vec![
            ReadlineEvent::Line("echo hello | wc -w".to_string()),
            ReadlineEvent::Eof,
        ];
        let mut editor = MockEditor::new(events);

        let mgr = HistoryManager::new().unwrap_or_else(|_| HistoryManager::default());
        let mut history: Vec<String> = Vec::new();

        let executor = MockExecutor::new();

        run_repl_with_state(
            &mut editor,
            &mgr,
            &mut history,
            &executor,
            None,
            Variables::new(),
            Functions::new(),
        );

        // executor's execute_pipeline should have been called with 2 commands
        // executor's execute_pipeline should have been called with 2 commands
        let calls = executor.calls.borrow();
        assert_eq!(calls.len(), 2);
        if let Command::Simple(cmd) = &calls[0] {
            assert_eq!(cmd.name, "echo");
            assert_eq!(cmd.args, vec!["hello".to_string()]);
        } else {
            panic!("Expected Simple command");
        }
        if let Command::Simple(cmd) = &calls[1] {
            assert_eq!(cmd.name, "wc");
            assert_eq!(cmd.args, vec!["-w".to_string()]);
        } else {
            panic!("Expected Simple command");
        }
    }

    #[test]
    #[serial_test::serial]
    fn test_repl_builtins_flow() {
        // create tmp dir to cd into
        let tmp = tempfile::TempDir::new().unwrap();
        let tmp_path = tmp.path().to_string_lossy().to_string();

        // events: cd tmp; history; exit
        let events = vec![
            ReadlineEvent::Line(format!("cd {}", tmp_path)),
            ReadlineEvent::Line("history".to_string()),
            ReadlineEvent::Line("exit".to_string()),
        ];

        let mut editor = MockEditor::new(events);

        let mgr = HistoryManager::new().unwrap_or_else(|_| HistoryManager::default());
        let mut history: Vec<String> = Vec::new();

        let executor = MockExecutor::new();

        let orig = std::env::current_dir().unwrap();
        run_repl_with_state(
            &mut editor,
            &mgr,
            &mut history,
            &executor,
            None,
            Variables::new(),
            Functions::new(),
        );

        // ensure history recorded the cd entry and restore cwd
        assert!(history.iter().any(|h| h.starts_with("cd ")));
        let _ = std::env::set_current_dir(orig);
    }

    #[test]
    #[serial_test::serial]
    fn test_repl_executor_error_does_not_save_history() {
        // Simulate an executor that returns an error
        struct FailingExecutor;
        impl ExecutorTrait for FailingExecutor {
            fn execute(
                &self,
                _cmd: &Command,
                _vars: &mut Variables,
                _functions: &mut Functions,
                _history_mgr: &HistoryManager,
                _command_history: &mut Vec<String>,
                _oldpwd: &mut Option<String>,
            ) -> Result<(), String> {
                Err("execution failed".to_string())
            }

            fn execute_pipeline(
                &self,
                _pipeline: &[Command],
                _vars: &mut Variables,
                _functions: &mut Functions,
                _history_mgr: &HistoryManager,
                _command_history: &mut Vec<String>,
                _oldpwd: &mut Option<String>,
            ) -> Result<(), String> {
                Err("pipeline failed".to_string())
            }
        }

        let events = vec![
            ReadlineEvent::Line("nonexistent arg".to_string()),
            ReadlineEvent::Eof,
        ];
        let mut editor = MockEditor::new(events);

        // ensure history is written to a temp HOME so add_entry/save won't interfere with real HOME
        let tmp_home = tempfile::TempDir::new().unwrap();
        let original = std::env::var("HOME").ok();
        std::env::set_var("HOME", tmp_home.path().to_string_lossy().as_ref());

        let mgr = HistoryManager::new().unwrap_or_else(|_| HistoryManager::default());
        let mut history: Vec<String> = Vec::new();

        let exec = FailingExecutor;
        run_repl_with_state(
            &mut editor,
            &mgr,
            &mut history,
            &exec,
            None,
            Variables::new(),
            Functions::new(),
        );

        // executor failed so history should not contain the failed command
        assert!(history.is_empty());

        match original {
            Some(v) => std::env::set_var("HOME", v),
            None => std::env::remove_var("HOME"),
        }
    }
}