rura 1.5.0

Interactive TUI pipeline editor built for rapid iteration
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
use crate::rura::RuraCommand;
use anyhow::{Result, anyhow};
use itertools::Itertools;
use log::{debug, info};
use std::io::Write;
use std::process::{Command, Stdio};
use std::thread;
use std::time::SystemTime;

pub trait CmdRunner {
    fn run(&mut self, command: &RuraCommand) -> Result<CmdResult>;
}

pub struct CmdRunners;
impl CmdRunners {
    #[cfg(unix)]
    pub fn new(shell: &str, stdin: Vec<u8>, no_cache: bool) -> Box<dyn CmdRunner> {
        if no_cache {
            Box::new(SplitCmdRunner::new(shell, stdin))
        } else {
            Box::new(CachedCmdRunner::new(shell, stdin))
        }
    }

    #[cfg(windows)]
    pub fn new(shell: &str, stdin: Vec<u8>, _no_cache: bool) -> Box<dyn CmdRunner> {
        Box::new(SimpleCmdRunner::new(shell, stdin))
    }
}

pub struct SplitCmdRunner {
    exec: Box<dyn Exec>,
    stdin: Vec<u8>,
}

impl SplitCmdRunner {
    pub fn new(shell: &str, stdin: Vec<u8>) -> Self {
        Self {
            exec: Box::new(SystemExec {
                shell: shell.into(),
            }),
            stdin,
        }
    }
}

impl CmdRunner for SplitCmdRunner {
    fn run(&mut self, command: &RuraCommand) -> Result<CmdResult> {
        info!("executing commands: '{command:?}'");

        let now = SystemTime::now();

        let mut current_stdin = self.stdin.clone();

        let mut output_opt: Option<Output> = None;

        for (i, subcommand) in command.trimmed().iter().enumerate() {
            debug!("  executing sub command: '{subcommand}'");

            let now_sub = SystemTime::now();

            let output = self.exec.exec(&subcommand, current_stdin.clone())?;

            debug!("    time: {:?}, ", now_sub.elapsed()?);

            if output.ok {
                current_stdin = output.bytes.clone();
                output_opt = Some(output);
            } else {
                debug!("  failed - aborting further execution");
                return Ok(CmdResult {
                    output,
                    failed_subcommand: Some(i),
                });
            }
        }

        if let Some(output) = output_opt {
            let elapsed = now.elapsed()?;
            debug!("command exec took {elapsed:?}");

            Ok(CmdResult {
                output,
                failed_subcommand: None,
            })
        } else {
            Ok(CmdResult {
                output: Output::ok_stdin(self.stdin.clone()),
                failed_subcommand: None,
            })
        }
    }
}

pub struct CachedCmdRunner {
    exec: Box<dyn Exec>,
    stdin: Vec<u8>,
    cache: Vec<Output>,
}

impl CachedCmdRunner {
    pub fn new(shell: &str, stdin: Vec<u8>) -> Self {
        Self {
            exec: Box::new(SystemExec {
                shell: shell.into(),
            }),
            stdin,
            cache: vec![],
        }
    }
}

impl CmdRunner for CachedCmdRunner {
    fn run(&mut self, command: &RuraCommand) -> Result<CmdResult> {
        info!("executing: '{command:?}'");

        if command.is_empty() {
            return Ok(CmdResult {
                output: Output::ok_stdin(self.stdin.clone()),
                failed_subcommand: None,
            });
        }

        let now = SystemTime::now();

        let mut skip_cache = false;

        for (i, subcommand) in command.trimmed().iter().enumerate() {
            let cached = self.cache.get(i);

            if let Some(c) = cached
                && !skip_cache
                && c.command == Some(subcommand.into())
            {
                debug!("  using cached output for command: '{subcommand:?}'");
                continue;
            }

            let current_stdin;

            if i > 0 {
                if let Some(c) = self.cache.get(i - 1) {
                    current_stdin = c.bytes.clone();
                } else {
                    current_stdin = self.stdin.clone();
                }
            } else {
                current_stdin = self.stdin.clone();
            }

            // starting from the first non-cached command, we don't want to use cache for any further commands
            skip_cache = true;
            self.cache.truncate(i);

            debug!("  executing sub command: '{subcommand}'");

            let now_sub = SystemTime::now();

            let output = self.exec.exec(&subcommand, current_stdin.clone())?;

            debug!("    time: {:?}, ", now_sub.elapsed()?);

            if output.ok {
                self.cache.push(output);
            } else {
                debug!("  failed - aborting further execution");
                return Ok(CmdResult {
                    output,
                    failed_subcommand: Some(i),
                });
            }
        }

        // Keep all following items in cache since user might have called for instance
        // "until cursor prev" action so the full command might be still called
        // with all subcommands

        let cached_commands = self
            .cache
            .iter()
            .map(|c| c.command.clone())
            .flatten()
            .collect_vec();

        debug!("  cached commands: {:?}", cached_commands);

        let elapsed = now.elapsed()?;
        debug!("  command exec took {elapsed:?}");

        Ok(CmdResult {
            output: self.cache.get(command.len() - 1).unwrap().clone(),
            failed_subcommand: None,
        })
    }
}

#[allow(dead_code)]
pub struct SimpleCmdRunner {
    exec: Box<dyn Exec>,
    stdin: Vec<u8>,
}

impl SimpleCmdRunner {
    #[allow(dead_code)]
    pub fn new(shell: &str, stdin: Vec<u8>) -> Self {
        Self {
            exec: Box::new(SystemExec {
                shell: shell.into(),
            }),
            stdin,
        }
    }
}

impl CmdRunner for SimpleCmdRunner {
    fn run(&mut self, command: &RuraCommand) -> Result<CmdResult> {
        info!("executing: '{command:?}'");

        if command.is_empty() {
            return Ok(CmdResult {
                output: Output::ok_stdin(self.stdin.clone()),
                failed_subcommand: None,
            });
        }

        let now = SystemTime::now();

        let output = self.exec.exec(&command.to_string(), self.stdin.clone())?;

        let elapsed = now.elapsed()?;
        debug!("command exec took {elapsed:?}");

        Ok(CmdResult {
            output,
            failed_subcommand: None,
        })
    }
}

trait Exec {
    fn exec(&self, command: &str, stdin: Vec<u8>) -> Result<Output>;
}

struct SystemExec {
    shell: String,
}

impl Exec for SystemExec {
    fn exec(&self, command: &str, stdin: Vec<u8>) -> Result<Output> {
        let mut cmd = build_command(&self.shell, command);

        let mut child = cmd
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .map_err(|e| anyhow!("Failed to spawn command [{cmd:?}]: {e}"))?;

        let mut child_stdin = child
            .stdin
            .take()
            .ok_or(anyhow!("Failed to take stdin handle"))?;

        thread::spawn(move || {
            let _ = child_stdin.write_all(&stdin);
        });

        if let Ok(output) = child.wait_with_output() {
            if output.status.success() {
                Ok(Output::ok_command(&command, output.stdout))
            } else {
                Ok(Output::err_command(
                    &command,
                    output.stderr,
                    output.status.code(),
                ))
            }
        } else {
            Ok(Output::err_command(
                &command,
                "Failed to execute command".bytes().collect_vec(),
                None,
            ))
        }
    }
}

#[cfg(unix)]
fn build_command(shell: &str, command: &str) -> Command {
    let mut cmd = Command::new("/usr/bin/env");
    cmd.args([shell, "-c", command]);
    cmd
}

#[cfg(windows)]
fn build_command(shell: &str, command: &str) -> Command {
    let mut cmd = Command::new(shell);
    cmd.env("NO_COLOR", "1");
    cmd.arg("-NonInteractive");
    cmd.arg("-NoProfile");
    cmd.arg("-NoLogo");
    cmd.args(["/C", &command]);
    cmd
}

pub struct CmdResult {
    pub output: Output,
    pub failed_subcommand: Option<usize>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Output {
    pub command: Option<String>,
    pub lines: Vec<String>,
    pub bytes: Vec<u8>,
    pub status_code: Option<i32>,
    pub ok: bool,
}

impl Output {
    pub fn ok_command(command: &str, bytes: Vec<u8>) -> Self {
        Self {
            command: Some(command.into()),
            lines: Self::lines(&String::from_utf8_lossy(&bytes)),
            bytes,
            status_code: Some(0),
            ok: true,
        }
    }

    pub fn err_command(command: &str, bytes: Vec<u8>, status_code: Option<i32>) -> Self {
        Self {
            command: Some(command.into()),
            lines: Self::lines(&String::from_utf8_lossy(&bytes)),
            bytes,
            status_code,
            ok: false,
        }
    }

    pub fn ok_stdin(bytes: Vec<u8>) -> Self {
        Self {
            command: None,
            lines: Self::lines(&String::from_utf8_lossy(&bytes)),
            bytes,
            status_code: Some(0),
            ok: true,
        }
    }

    pub fn err_stdin(bytes: Vec<u8>) -> Self {
        Self {
            command: None,
            lines: Self::lines(&String::from_utf8_lossy(&bytes)),
            bytes,
            status_code: None,
            ok: false,
        }
    }

    pub fn len(&self) -> usize {
        self.lines.len()
    }

    fn lines(input: &str) -> Vec<String> {
        input.lines().map(|a| a.into()).collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::cell::RefCell;
    use std::rc::Rc;

    struct MockExec {
        calls: Rc<RefCell<Vec<(String, String)>>>,
    }

    impl Exec for MockExec {
        fn exec(&self, command: &str, stdin: Vec<u8>) -> Result<Output> {
            self.calls.borrow_mut().push((
                command.into(),
                String::from_utf8_lossy(stdin.as_slice()).into(),
            ));
            if command.ends_with("err") {
                Ok(Output::err_command_str(
                    command,
                    &format!("{}-output", command),
                    Some(1),
                ))
            } else {
                Ok(Output::ok_command_str(
                    command,
                    &format!("{}-output", command),
                ))
            }
        }
    }

    mod simple_runner {
        use crate::cmd_runner::tests::MockExec;
        use crate::cmd_runner::{CmdRunner, Exec, Output, SimpleCmdRunner};
        use std::cell::RefCell;
        use std::rc::Rc;

        fn simple_runner(exec: Box<dyn Exec>, stdin: Vec<u8>) -> SimpleCmdRunner {
            SimpleCmdRunner { exec, stdin }
        }

        #[test]
        fn test_ok_command() {
            let calls = Rc::new(RefCell::new(vec![]));
            let mock_exec = MockExec {
                calls: calls.clone(),
            };
            let mut runner = simple_runner(Box::new(mock_exec), "stdin".into());

            let result = runner.run(&"echo hello".into()).unwrap();

            assert_eq!(
                result.output,
                Output::ok_command_str("echo hello", "echo hello-output")
            )
        }

        #[test]
        fn test_run_empty_command() {
            let calls = Rc::new(RefCell::new(vec![]));
            let mock_exec = MockExec {
                calls: calls.clone(),
            };
            let mut runner = simple_runner(Box::new(mock_exec), "stdin".into());

            let result = runner.run(&vec![].into()).unwrap();

            assert_eq!(result.output, Output::ok_stdin_str("stdin"))
        }
    }

    mod split_runner {
        use crate::cmd_runner::tests::MockExec;
        use crate::cmd_runner::{CmdRunner, Exec, Output, SplitCmdRunner};
        use std::cell::RefCell;
        use std::rc::Rc;

        fn runner(exec: Box<dyn Exec>, stdin: Vec<u8>) -> SplitCmdRunner {
            SplitCmdRunner { exec, stdin }
        }

        #[test]
        fn test_run_empty_command() {
            let calls = Rc::new(RefCell::new(vec![]));
            let mock_exec = MockExec {
                calls: calls.clone(),
            };
            let mut runner = runner(Box::new(mock_exec), "stdin".into());

            let result = runner.run(&vec![].into()).unwrap();

            assert_eq!(result.output, Output::ok_stdin_str("stdin"));

            assert_eq!(*calls.borrow(), vec![])
        }

        #[test]
        fn test_cmd_runner_calling_three_subcommands() {
            let calls = Rc::new(RefCell::new(vec![]));
            let mock_exec = MockExec {
                calls: calls.clone(),
            };
            let mut runner = runner(Box::new(mock_exec), "stdin".into());

            let result = runner
                .run(&vec!["cmd1".into(), "cmd2".into(), "cmd3".into()].into())
                .unwrap();

            // output of the last called command
            assert_eq!(result.output, Output::ok_command_str("cmd3", "cmd3-output"));

            // input for the command is the output of the previous command
            assert_eq!(
                *calls.borrow(),
                vec![
                    ("cmd1".into(), "stdin".into()),
                    ("cmd2".into(), "cmd1-output".into()),
                    ("cmd3".into(), "cmd2-output".into()),
                ]
            );
        }

        #[test]
        fn test_cmd_runner_errors() {
            let calls = Rc::new(RefCell::new(vec![]));
            let mock_exec = MockExec {
                calls: calls.clone(),
            };
            let mut runner = runner(Box::new(mock_exec), "stdin".into());

            let result = runner
                .run(&vec!["cmd1".into(), "cmd2err".into(), "cmd3".into()].into())
                .unwrap();

            // output of the last called command
            assert_eq!(
                result.output,
                Output::err_command_str("cmd2err", "cmd2err-output", Some(1))
            );
        }
    }

    mod cached_runner {
        use crate::cmd_runner::tests::MockExec;
        use crate::cmd_runner::{CachedCmdRunner, CmdRunner, Exec, Output};
        use std::cell::RefCell;
        use std::rc::Rc;

        fn cached_runner(exec: Box<dyn Exec>, stdin: Vec<u8>) -> CachedCmdRunner {
            CachedCmdRunner {
                exec,
                stdin,
                cache: vec![],
            }
        }

        #[test]
        fn test_run_empty_command_cached() {
            let calls = Rc::new(RefCell::new(vec![]));
            let mock_exec = MockExec {
                calls: calls.clone(),
            };
            let mut runner = cached_runner(Box::new(mock_exec), "stdin".into());

            let result = runner.run(&vec![].into()).unwrap();

            assert_eq!(result.output, Output::ok_stdin_str("stdin"))
        }

        #[test]
        fn test_cmd_runner_calling_three_subcommands() {
            let calls = Rc::new(RefCell::new(vec![]));
            let mock_exec = MockExec {
                calls: calls.clone(),
            };
            let mut runner = cached_runner(Box::new(mock_exec), "stdin".into());

            let result = runner
                .run(&vec!["cmd1".into(), "cmd2".into(), "cmd3".into()].into())
                .unwrap();

            // output of the last called command
            assert_eq!(result.output, Output::ok_command_str("cmd3", "cmd3-output"));

            // input for the command is the output of the previous command
            assert_eq!(
                *calls.borrow(),
                vec![
                    ("cmd1".into(), "stdin".into()),
                    ("cmd2".into(), "cmd1-output".into()),
                    ("cmd3".into(), "cmd2-output".into()),
                ]
            );

            // all commands are cached
            assert_eq!(
                runner.cache,
                vec![
                    Output::ok_command_str("cmd1", "cmd1-output"),
                    Output::ok_command_str("cmd2", "cmd2-output"),
                    Output::ok_command_str("cmd3", "cmd3-output")
                ]
            );
        }

        #[test]
        fn test_cmd_runner_shorter_command() {
            let calls = Rc::new(RefCell::new(vec![]));
            let mock_exec = MockExec {
                calls: calls.clone(),
            };
            let mut runner = cached_runner(Box::new(mock_exec), "stdin".into());

            let _init_run = runner
                .run(&vec!["cmd1".into(), "cmd2".into(), "cmd3".into()].into())
                .unwrap();

            calls.borrow_mut().clear();

            // second run
            let result = runner.run(&vec!["cmd1".into()].into()).unwrap();

            // output of the last called command - cmd3
            assert_eq!(result.output, Output::ok_command_str("cmd1", "cmd1-output"));

            // no calls since the command is cached
            assert_eq!(*calls.borrow(), vec![]);

            // all commands are still cached
            assert_eq!(
                runner.cache,
                vec![
                    Output::ok_command_str("cmd1", "cmd1-output"),
                    Output::ok_command_str("cmd2", "cmd2-output"),
                    Output::ok_command_str("cmd3", "cmd3-output")
                ]
            );
        }

        #[test]
        fn test_cmd_runner_extended_command() {
            let calls = Rc::new(RefCell::new(vec![]));
            let mock_exec = MockExec {
                calls: calls.clone(),
            };
            let mut runner = cached_runner(Box::new(mock_exec), "stdin".into());

            let _init_run = runner
                .run(&vec!["cmd1".into(), "cmd2".into()].into())
                .unwrap();

            calls.borrow_mut().clear();

            // second run for less commands - keep whole cache
            let result = runner
                .run(&vec!["cmd1".into(), "cmd2".into(), "cmd3".into(), "cmd4".into()].into())
                .unwrap();

            // output of the last called command
            assert_eq!(result.output, Output::ok_command_str("cmd4", "cmd4-output"));

            // only cmd3 is called since is's the only one not cached
            assert_eq!(
                *calls.borrow(),
                vec![
                    ("cmd3".into(), "cmd2-output".into()),
                    ("cmd4".into(), "cmd3-output".into()),
                ]
            );

            // all commands are still cached
            assert_eq!(
                runner.cache,
                vec![
                    Output::ok_command_str("cmd1", "cmd1-output"),
                    Output::ok_command_str("cmd2", "cmd2-output"),
                    Output::ok_command_str("cmd3", "cmd3-output"),
                    Output::ok_command_str("cmd4", "cmd4-output")
                ]
            );
        }

        #[test]
        fn test_cmd_runner_modified_in_the_middle() {
            let calls = Rc::new(RefCell::new(vec![]));
            let mock_exec = MockExec {
                calls: calls.clone(),
            };
            let mut runner = cached_runner(Box::new(mock_exec), "stdin".into());

            let _init_run = runner
                .run(&vec!["cmd1".into(), "cmd2".into(), "cmd3".into()].into())
                .unwrap();
            calls.borrow_mut().clear();

            // second run for shorter command - keep whole cache
            let result = runner
                .run(&vec!["cmd1".into(), "cmd2mod".into()].into())
                .unwrap();

            // output of the last called command
            assert_eq!(
                result.output,
                Output::ok_command_str("cmd2mod", "cmd2mod-output")
            );

            // cmd2mod is called since it's modified
            assert_eq!(
                *calls.borrow(),
                vec![("cmd2mod".into(), "cmd1-output".into()),]
            );

            // cmd2 replaced with cmd2mod and cmd3 removed since it's invalid after modified command
            assert_eq!(
                runner.cache,
                vec![
                    Output::ok_command_str("cmd1", "cmd1-output"),
                    Output::ok_command_str("cmd2mod", "cmd2mod-output"),
                ]
            );
        }

        #[test]
        fn test_cmd_runner_modified_in_the_middle_and_extended() {
            let calls = Rc::new(RefCell::new(vec![]));
            let mock_exec = MockExec {
                calls: calls.clone(),
            };
            let mut runner = cached_runner(Box::new(mock_exec), "stdin".into());

            let _init_run = runner
                .run(&vec!["cmd1".into(), "cmd2".into(), "cmd3".into()].into())
                .unwrap();
            calls.borrow_mut().clear();

            // second run for shorter command - keep whole cache
            let result = runner
                .run(&vec!["cmd1".into(), "cmd2mod".into(), "cmd3".into()].into())
                .unwrap();

            // output of the last called command
            assert_eq!(result.output, Output::ok_command_str("cmd3", "cmd3-output"));

            // cmd2mod is called since it's modified
            // cmd3 is also called because it was after modified command
            assert_eq!(
                *calls.borrow(),
                vec![
                    ("cmd2mod".into(), "cmd1-output".into()),
                    ("cmd3".into(), "cmd2mod-output".into()),
                ]
            );

            // cmd2 replaced with cmd2mod and cmd3 replaced with updated output
            assert_eq!(
                runner.cache,
                vec![
                    Output::ok_command_str("cmd1", "cmd1-output"),
                    Output::ok_command_str("cmd2mod", "cmd2mod-output"),
                    Output::ok_command_str("cmd3", "cmd3-output"),
                ]
            );
        }

        #[test]
        fn test_cmd_runner_errors() {
            let calls = Rc::new(RefCell::new(vec![]));
            let mock_exec = MockExec {
                calls: calls.clone(),
            };
            let mut runner = cached_runner(Box::new(mock_exec), "stdin".into());

            let result = runner
                .run(&vec!["cmd1".into(), "cmd2err".into(), "cmd3".into()].into())
                .unwrap();

            // output of the last called command
            assert_eq!(
                result.output,
                Output::err_command_str("cmd2err", "cmd2err-output", Some(1))
            );

            // cmd2mod is called since it's modified
            // cmd3 is also called because it was after modified command
            assert_eq!(
                *calls.borrow(),
                vec![
                    ("cmd1".into(), "stdin".into()),
                    ("cmd2err".into(), "cmd1-output".into()),
                ]
            );

            // only cmd1 is cached since it didn't fail
            assert_eq!(
                runner.cache,
                vec![Output::ok_command_str("cmd1", "cmd1-output"),]
            );
        }

        #[test]
        fn test_cmd_runner_errors_clear_cache() {
            let calls = Rc::new(RefCell::new(vec![]));
            let mock_exec = MockExec {
                calls: calls.clone(),
            };
            let mut runner = cached_runner(Box::new(mock_exec), "stdin".into());

            let _init_run = runner
                .run(&vec!["cmd1".into(), "cmd2".into(), "cmd3".into()].into())
                .unwrap();
            calls.borrow_mut().clear();

            let result = runner
                .run(&vec!["cmd1".into(), "cmd2err".into(), "cmd3".into()].into())
                .unwrap();

            assert_eq!(
                result.output,
                Output::err_command_str("cmd2err", "cmd2err-output", Some(1))
            );

            // cmd1 not called because it's cached
            assert_eq!(
                *calls.borrow(),
                vec![("cmd2err".into(), "cmd1-output".into()),]
            );

            // only cmd1 is cached since it didn't fail
            // entry for cmd3 is cleared because cmd2err failed before
            assert_eq!(
                runner.cache,
                vec![Output::ok_command_str("cmd1", "cmd1-output"),]
            );
        }
    }
}

#[cfg(test)]
impl Output {
    pub fn ok_command_str(command: &str, str: &str) -> Self {
        Self {
            command: Some(command.into()),
            lines: Self::lines(str),
            bytes: str.as_bytes().to_vec(),
            status_code: Some(0),
            ok: true,
        }
    }

    pub fn err_command_str(command: &str, str: &str, status_code: Option<i32>) -> Self {
        Self {
            command: Some(command.into()),
            lines: Self::lines(str),
            bytes: str.as_bytes().to_vec(),
            status_code,
            ok: false,
        }
    }

    pub fn ok_stdin_str(str: &str) -> Self {
        Self {
            command: None,
            lines: Self::lines(str),
            bytes: str.as_bytes().to_vec(),
            status_code: Some(0),
            ok: true,
        }
    }

    pub fn err_stdin_str(str: &str) -> Self {
        Self {
            command: None,
            lines: Self::lines(str),
            bytes: str.as_bytes().to_vec(),
            status_code: None,
            ok: false,
        }
    }
}