pmsh 0.1.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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
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, vars)
        } 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"),
        }
    }

    #[test]
    fn test_repl_interrupted_event() {
        let events = vec![
            ReadlineEvent::Interrupted,
            ReadlineEvent::Line("echo fine".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(),
        );

        let calls = executor.calls.borrow();
        assert_eq!(calls.len(), 1);
        if let Command::Simple(cmd) = &calls[0] {
            assert_eq!(cmd.name, "echo");
        } else {
            panic!("Expected Simple command");
        }
    }

    #[test]
    fn test_repl_other_event() {
        let events = vec![
            ReadlineEvent::Other,
            ReadlineEvent::Line("echo never_reached".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();

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

        let calls = executor.calls.borrow();
        assert!(calls.is_empty()); // Should break on Other event
    }

    #[test]
    fn test_execute_line_empty() {
        let mgr = HistoryManager::new().unwrap_or_else(|_| HistoryManager::default());
        let mut history: Vec<String> = Vec::new();
        let executor = MockExecutor::new();
        let mut oldpwd = None;
        let mut vars = Variables::new();
        let mut functions = Functions::new();
        let mut editor = MockEditor::new(vec![]);

        // Empty line should not call executor
        let result = execute_line(
            "",
            &mut editor,
            &mgr,
            &mut history,
            &executor,
            &mut oldpwd,
            &mut vars,
            &mut functions,
        );
        // Should return true (continue the REPL)
        assert!(result);
        assert!(executor.calls.borrow().is_empty());
    }

    #[test]
    #[serial_test::serial]
    fn test_execute_line_source_file() {
        let tmp = tempfile::NamedTempFile::new().unwrap();
        let tmp_path = tmp.path().to_string_lossy().to_string();
        std::fs::write(&tmp_path, "echo from_source\n").unwrap();

        let mgr = HistoryManager::new().unwrap_or_else(|_| HistoryManager::default());
        let mut history: Vec<String> = Vec::new();
        let executor = MockExecutor::new();
        let mut oldpwd = None;
        let mut vars = Variables::new();
        let mut functions = Functions::new();
        let mut editor = MockEditor::new(vec![]);

        let line = format!("source {}", tmp_path);
        let result = execute_line(
            &line,
            &mut editor,
            &mgr,
            &mut history,
            &executor,
            &mut oldpwd,
            &mut vars,
            &mut functions,
        );
        assert!(result);
        // executor should have been called with the echo command from the source file
        let calls = executor.calls.borrow();
        assert_eq!(calls.len(), 1);
        if let Command::Simple(c) = &calls[0] {
            assert_eq!(c.name, "echo");
        } else {
            panic!("Expected simple command");
        }
    }

    #[test]
    fn test_execute_line_source_file_not_found() {
        let mgr = HistoryManager::new().unwrap_or_else(|_| HistoryManager::default());
        let mut history: Vec<String> = Vec::new();
        let executor = MockExecutor::new();
        let mut oldpwd = None;
        let mut vars = Variables::new();
        let mut functions = Functions::new();
        let mut editor = MockEditor::new(vec![]);

        // Sourcing a non-existent file should handle gracefully
        let result = execute_line(
            "source /nonexistent/file.sh",
            &mut editor,
            &mgr,
            &mut history,
            &executor,
            &mut oldpwd,
            &mut vars,
            &mut functions,
        );
        // Should return true (continue REPL) even on error
        assert!(result);
        // executor should NOT have been called
        assert!(executor.calls.borrow().is_empty());
    }

    #[test]
    fn test_execute_pipeline_struct_non_simple() {
        let mgr = HistoryManager::new().unwrap_or_else(|_| HistoryManager::default());
        let mut history: Vec<String> = Vec::new();
        let executor = MockExecutor::new();
        let mut oldpwd = None;
        let mut vars = Variables::new();
        let mut functions = Functions::new();

        // A Subshell command in the pipeline should go through execute_pipeline
        let pipeline = vec![Command::Subshell(vec![vec![Command::Simple(
            crate::parser::SimpleCommand {
                name: "echo".into(),
                args: vec!["subshell_test".into()],
                assignments: vec![],
            },
        )]])];

        let result = execute_pipeline_struct(
            &pipeline,
            &mgr,
            &mut history,
            &executor,
            &mut oldpwd,
            &mut vars,
            &mut functions,
        );
        assert!(result);
    }

    #[test]
    #[serial_test::serial]
    fn test_execute_pipeline_struct_source() {
        let tmp = tempfile::NamedTempFile::new().unwrap();
        let tmp_path = tmp.path().to_string_lossy().to_string();
        std::fs::write(&tmp_path, "echo sourced_cmd\n").unwrap();

        let mgr = HistoryManager::new().unwrap_or_else(|_| HistoryManager::default());
        let mut history: Vec<String> = Vec::new();
        let executor = MockExecutor::new();
        let mut oldpwd = None;
        let mut vars = Variables::new();
        let mut functions = Functions::new();

        let pipeline = vec![Command::Simple(crate::parser::SimpleCommand {
            name: "source".into(),
            args: vec![tmp_path],
            assignments: vec![],
        })];

        let result = execute_pipeline_struct(
            &pipeline,
            &mgr,
            &mut history,
            &executor,
            &mut oldpwd,
            &mut vars,
            &mut functions,
        );
        assert!(result);

        let calls = executor.calls.borrow();
        assert_eq!(calls.len(), 1);
        if let Command::Simple(c) = &calls[0] {
            assert_eq!(c.name, "echo");
        } else {
            panic!("Expected simple command from sourced file");
        }
    }

    #[test]
    fn test_execute_pipeline_struct_source_not_found() {
        let mgr = HistoryManager::new().unwrap_or_else(|_| HistoryManager::default());
        let mut history: Vec<String> = Vec::new();
        let executor = MockExecutor::new();
        let mut oldpwd = None;
        let mut vars = Variables::new();
        let mut functions = Functions::new();

        let pipeline = vec![Command::Simple(crate::parser::SimpleCommand {
            name: "source".into(),
            args: vec!["/nonexistent/path.sh".to_string()],
            assignments: vec![],
        })];

        let result = execute_pipeline_struct(
            &pipeline,
            &mgr,
            &mut history,
            &executor,
            &mut oldpwd,
            &mut vars,
            &mut functions,
        );
        // Should still return true (continue REPL even on error)
        assert!(result);
        assert!(executor.calls.borrow().is_empty());
    }

    #[test]
    fn test_execute_pipeline_struct_executor_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("command 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 mgr = HistoryManager::new().unwrap_or_else(|_| HistoryManager::default());
        let mut history: Vec<String> = Vec::new();
        let executor = FailingExecutor;
        let mut oldpwd = None;
        let mut vars = Variables::new();
        let mut functions = Functions::new();

        // Single command - executor error
        let pipeline = vec![Command::Simple(crate::parser::SimpleCommand {
            name: "some_cmd".into(),
            args: vec![],
            assignments: vec![],
        })];
        let result = execute_pipeline_struct(
            &pipeline,
            &mgr,
            &mut history,
            &executor,
            &mut oldpwd,
            &mut vars,
            &mut functions,
        );
        assert!(result); // even on error, the REPL continues

        // Multiple commands pipeline -- executor_pipeline error
        let multi_pipeline = vec![
            Command::Simple(crate::parser::SimpleCommand {
                name: "cmd1".into(),
                args: vec![],
                assignments: vec![],
            }),
            Command::Simple(crate::parser::SimpleCommand {
                name: "cmd2".into(),
                args: vec![],
                assignments: vec![],
            }),
        ];
        let result = execute_pipeline_struct(
            &multi_pipeline,
            &mgr,
            &mut history,
            &executor,
            &mut oldpwd,
            &mut vars,
            &mut functions,
        );
        assert!(result);
    }

    #[test]
    fn test_execute_pipeline_struct_builtins_through_pipeline() {
        let mgr = HistoryManager::new().unwrap_or_else(|_| HistoryManager::default());
        let mut history: Vec<String> = Vec::new();
        let executor = MockExecutor::new();
        let mut oldpwd = None;
        let mut vars = Variables::new();
        let mut functions = Functions::new();

        // complete -W wordlist mycmd
        let pipeline = vec![Command::Simple(crate::parser::SimpleCommand {
            name: "complete".into(),
            args: vec!["-W".into(), "foo bar".into(), "mycmd".into()],
            assignments: vec![],
        })];
        let result = execute_pipeline_struct(
            &pipeline,
            &mgr,
            &mut history,
            &executor,
            &mut oldpwd,
            &mut vars,
            &mut functions,
        );
        assert!(result);

        // compgen -W wordlist -- word
        let pipeline = vec![Command::Simple(crate::parser::SimpleCommand {
            name: "compgen".into(),
            args: vec!["-W".into(), "hello world".into(), "--".into(), "hel".into()],
            assignments: vec![],
        })];
        let result = execute_pipeline_struct(
            &pipeline,
            &mgr,
            &mut history,
            &executor,
            &mut oldpwd,
            &mut vars,
            &mut functions,
        );
        assert!(result);

        // version (no args)
        let pipeline = vec![Command::Simple(crate::parser::SimpleCommand {
            name: "version".into(),
            args: vec![],
            assignments: vec![],
        })];
        let result = execute_pipeline_struct(
            &pipeline,
            &mgr,
            &mut history,
            &executor,
            &mut oldpwd,
            &mut vars,
            &mut functions,
        );
        assert!(result);
    }

    #[test]
    fn test_execute_line_with_builtin_handled_continue() {
        let mgr = HistoryManager::new().unwrap_or_else(|_| HistoryManager::default());
        let mut history: Vec<String> = Vec::new();
        let executor = MockExecutor::new();
        let mut oldpwd = None;
        let mut vars = Variables::new();
        let mut functions = Functions::new();
        let mut editor = MockEditor::new(vec![]);

        // Calling complete through execute_line
        let result = execute_line(
            "complete -W \"start stop\" myservice",
            &mut editor,
            &mgr,
            &mut history,
            &executor,
            &mut oldpwd,
            &mut vars,
            &mut functions,
        );
        assert!(result);
        // executor should not have been called since it's a builtin
        assert!(executor.calls.borrow().is_empty());
    }
}