summaryrefslogtreecommitdiffstats
path: root/src/recite.rs
blob: 12c98ae02caeb05ec63066c240efc2539dd30722 (plain)
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
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
pub mod path;
mod ps;
use crate::{btask, ctask, task};
use core::fmt;
use libc::{waitpid, WNOHANG};
use path::prefresh;
use std::fs::OpenOptions;
use std::io::{self, Read, Write};
use std::os::unix::process::CommandExt;
use std::path::Path;
use std::process::{exit, Command, Stdio};
use std::sync::{Arc, Mutex};

/// Describes the ending of a [Verse]
///
/// The ending of a verse determines how the [Stanza] should be interpreted.
/// For instance, a [Stanza] that is piped needs to have it's `STDOUT`
/// captured (rather than printing out to the terminal), and subsequently sent
/// to the next [Verse] in the [Poem].
///
/// # Values
/// * `None` - A shell command with no additional actions
/// * `Couplet` - Pipe the output of this command into the next (`|`)
/// * `Quiet` - Fork the called process into the background (`&`)
/// * `And` - Run the next command only if this one succeeds (`&&`)
/// * `String` - String commands together on a single line (`;`)
/// * `Read` - Read files into STDIN (`<`)
/// * `Write` - Write STDOUT to a file (`>`)
/// * `Addendum` - Append STDOUT to a file (`>>`)
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
enum Meter {
    None,     // No meter
    Couplet,  // Pipe the output of this command into the next
    Quiet,    // Fork the command into the background
    And,      // Run the next command only if this succeeds
    String,   // Run the next command, even if this doesn't succeed
    Read,     // Read files into STDIN
    Write,    // Send STDOUT to a file
    Addendum, // Append STDOUT to a file
}

impl fmt::Display for Meter {
    /// Determine how to print out a [Meter]
    ///
    /// Each [meter's][Meter] symbol corresponds to it's input.
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let meter = match self {
            Meter::None => "",
            Meter::Couplet => "|",
            Meter::Quiet => "&",
            Meter::And => "&&",
            Meter::String => ";",
            Meter::Read => "<",
            Meter::Write => ">",
            Meter::Addendum => ">>",
        };

        write!(f, "{}", meter)
    }
}

impl Meter {
    /// Recite a verse with [Meter::None]
    ///
    /// Call this function on a [Verse] with a meter of type [Meter::None].
    /// This forks into a child process, calls the `verb` (i.e. program)
    /// that was specified in the [Verse], then waits for that program to
    /// complete. If the last [Verse] piped its contents into `out`, it will
    /// be piped into the STDIN of this [Verse]. If all Rust code is called
    /// successfully, return the exit code of the process. Otherwise, return a
    /// [std::io::Error].
    ///
    /// # Arguments
    /// * `verse: &Verse` - The verse to recite
    /// * `out: &mut String` - A string that may have output from the last command
    fn incant_none(verse: &Verse, out: &mut String) -> Result<i32, io::Error> {
        let child = task!(verse, out);

        let output = child.wait_with_output()?;

        if !output.status.success() {
            return Ok(output.status.code().unwrap_or(-1));
        }

        Ok(output.status.code().unwrap_or(0))
    }

    /// Recite a verse with [Meter::None]
    ///
    /// Call this function on a [Verse] with a meter of type [Meter::None].
    /// This forks into a child process, calls the `verb` (i.e. program)
    /// that was specified in the [Verse], then waits for that program to
    /// complete. If the last [Verse] piped its contents into `out`, it will
    /// be piped into the STDIN of this [Verse]. Then, the contents of this
    /// processes' STDOUT are stored in `out`. If all Rust code is called
    /// successfully, return the exit code of the process. Otherwise, return a
    /// [std::io::Error].
    ///
    /// # Arguments
    /// * `verse: &Verse` - The verse to recite
    /// * `out: &mut String` - A string that may have output from the last command
    fn incant_couplet(verse: &Verse, out: &mut String) -> Result<i32, io::Error> {
        let child = ctask!(verse, out);

        let output = child.wait_with_output()?;

        if !output.status.success() {
            return Ok(output.status.code().unwrap_or(-1));
        }

        out.push_str(
            String::from_utf8_lossy(&output.stdout)
                .into_owned()
                .as_str(),
        );

        Ok(output.status.code().unwrap_or(0))
    }

    /// Recite a verse with [Meter::Quiet]
    ///
    /// Call this function on a [Verse] with a meter of type [Meter::Quiet].
    /// This forks a child process into the background. It then registers a
    /// `SIGCHLD` handler, making sure to do so for each PID in the `pids`
    /// Vec. If the last [Verse] piped its contents into `out`, it will be
    /// piped into the STDIN of this [Verse]. If all Rust code is called
    /// successfully, return the exit code of the process. Otherwise, return a
    /// [std::io::Error].
    ///
    /// # Arguments
    /// * `verse: &Verse` - The verse to recite
    /// * `out: &mut String` - A string that may have output from the last command
    /// * `pids: Arc<Mutex<Vec<i32>>>` - A vector that stores the PIDs of all background processes that belong to the shell
    fn incant_quiet(
        verse: &Verse,
        out: &mut String,
        pids: &mut Arc<Mutex<Vec<i32>>>,
    ) -> Result<i32, io::Error> {
        let child = btask!(verse, out);
        println!("[&]  {}", child.id());

        pids.lock().unwrap().push(child.id() as i32);
        let stanza = verse.stanza.to_string();
        let pids = Arc::clone(pids);

        unsafe {
            signal_hook::low_level::register(signal_hook::consts::SIGCHLD, move || {
                for pid in pids.lock().unwrap().iter() {
                    let mut pid = *pid;
                    let mut status: i32 = 0;
                    pid = waitpid(pid, &mut status, WNOHANG);
                    if pid > 0 {
                        print!("\n[&]  + done    {}", stanza);
                        io::stdout().flush().unwrap();
                    }
                }
            })
            .unwrap();
        }

        Ok(0)
    }

    /// Alias to [Meter::incant_none]
    fn incant_and(verse: &Verse, out: &mut String) -> Result<i32, io::Error> {
        Meter::incant_none(verse, out)
    }

    /// Alias to [Meter::incant_none]
    fn incant_string(verse: &Verse, out: &mut String) -> Result<i32, io::Error> {
        Meter::incant_none(verse, out)
    }

    /// Recite a verse with [Meter::Read]
    ///
    /// Call this function on a [Verse] with a meter of type [Meter::Read].
    /// This reads the specified files into `out`, then makes a call to
    /// [Meter::incant_none] with all the contents of `out`. Anything piped to
    /// this command will appear in `out` first, and any subsequent files will
    /// be appended.
    ///
    /// # Arguments
    /// * `verse: &Verse` - The verse to recite
    /// * `paths: &Verse` - The next verse (i.e. the file paths)
    /// * `out: &mut String` - A string that may have output from the last command,
    ///                        and that will be used to store the contents of the
    ///                        file paths in `next`
    fn incant_read(verse: &Verse, paths: &Verse, out: &mut String) -> Result<i32, io::Error> {
        // Read all file specified in the next verse into 'out', since there
        // may also be piped output from the last command
        for path in paths.stanza().iter() {
            let mut file = OpenOptions::new().read(true).open(path)?;
            let mut contents = String::new();
            file.read_to_string(&mut contents)?;
            out.push_str(contents.as_str());
        }

        // Alias incant_none
        Meter::incant_none(verse, out)
    }

    /// Recite a verse with [Meter::Write]
    ///
    /// Call this function on a [Verse] with a meter of type [Meter::Write].
    /// This writes the output of the verse into the specified files, after
    /// making a call to [Meter::incant_couplet].
    ///
    /// # Arguments
    /// * `verse: &Verse` - The verse to recite
    /// * `paths: &Verse` - The next verse (i.e. the file paths)
    /// * `out: &mut String` - A string that may have output from the last command,
    ///                        and that will be used to store the contents of the
    ///                        file paths in `next`
    fn incant_write(verse: &Verse, paths: &Verse, out: &mut String) -> Result<i32, io::Error> {
        // Alias incant_couplet
        let status = Meter::incant_couplet(verse, out)?;

        // Write output to each file specified in the next verse
        for path in paths.stanza().iter() {
            let mut file = OpenOptions::new().create(true).write(true).open(path)?;
            file.write(out.as_bytes())?;
        }

        // Clear out
        out.clear();

        // Return the exit status
        Ok(status)
    }

    /// Recite a verse with [Meter::Addendum]
    ///
    /// Same as [Meter::Write], except it appends to the file(s) specified,
    /// instead of overwriting them.
    ///
    /// # Arguments
    /// * `verse: &Verse` - The verse to recite
    /// * `paths: &Verse` - The next verse (i.e. the file paths)
    /// * `out: &mut String` - A string that may have output from the last command,
    ///                        and that will be used to store the contents of the
    ///                        file paths in `next`
    fn incant_addendum(verse: &Verse, paths: &Verse, out: &mut String) -> Result<i32, io::Error> {
        // Alias incant_couplet
        let status = Meter::incant_couplet(verse, out)?;

        // Write output to each file specified in the next verse
        for path in paths.stanza().iter() {
            let mut file = OpenOptions::new().create(true).append(true).open(path)?;
            file.write(out.as_bytes())?;
        }

        // Clear out
        out.clear();

        // Return the exit status
        Ok(status)
    }
}

/// Holds a program to be called
///
/// This is simply the first word in a full command [String], dilineated via
/// whitespace.
type Verb = String;

/// Holds arguments to a program
///
/// This is a list of all the words that come after the [Verb], dilineated via
/// whitespace.
type Clause = Vec<String>;

/// Holds the interpreted elements of a [Verse]
///
/// Each [Stanza] has two parts, a [Verb] and a [Clause]. The [Verb] is the
/// program, or path to the program to call, while the [Clause] contains
/// arguments to pass to that program.
#[derive(Debug)]
struct Stanza {
    verb: Verb,
    clause: Clause,
}

impl fmt::Display for Stanza {
    /// Print out a [Stanza]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} {}", self.verb, self.clause.join(" "))
    }
}

impl Stanza {
    /// Create a new [Stanza]
    ///
    /// Returns a new [Stanza] built from a `Vec<String>`. The first element of
    /// the vector becomes the [Verb], while the remainder of the vector
    /// becomes the [Clause].
    ///
    /// # Arguments
    /// `stanza: Vec<String>` - The full command split into individual strings
    ///                         via whitespace
    ///
    /// # Examples
    /// ```
    /// // Input: cargo build --release
    /// let command = vec!["cargo", "build", "--release"]
    ///               .into_iter()
    ///               .map(String::from)
    ///               .collect<Vec<String>>();
    /// let stanza = Stanza::new(command);
    /// println!("{}", stanza.verb);
    /// println!("{:?}", stanza.clause);
    ///
    /// ```
    fn new(stanza: Vec<String>) -> Stanza {
        Stanza {
            verb: stanza[0].to_owned(),
            clause: stanza[1..].to_vec(),
        }
    }

    /// Check if the [Verb] exists in the `$PATH`
    ///
    /// First checks if the [Verb] is a relative or full path. If it is, check
    /// whether or not it exists. If it does exist, return true, otherwise see
    /// if the [Verb] is cached in our list of binaries. Search is done in
    /// $PATH order.
    ///
    /// # Examples
    /// ```
    /// let bins = vec!["cargo", "ruby", "cat"]
    ///            .into_iter()
    ///            .map(String::from)
    ///            .collect<Vec<String>>();
    ///
    /// let command_success = vec!["cargo", "build", "--release"]
    ///                       .into_iter()
    ///                       .map(String::from)
    ///                       .collect<Vec<String>>();
    ///
    /// let command_fail = vec!["make", "-j8"]
    ///                    .into_iter()
    ///                    .map(String::from)
    ///                    .collect<Vec<String>>();
    ///
    /// let stanza_success = Stanza::new(command_success);
    /// let stanza_fail = Stanza::new(command_fail);
    ///
    /// stanza_success.spellcheck(bins) // -> true
    /// stanza_fail.spellcheck(bins) // -> false
    /// ```
    fn spellcheck(&self, bins: &Vec<String>) -> bool {
        // An empty verb (i.e. the empty string) cannot be a program, so
        // return false
        // Thanks to the parsing in Poem::read, however, it's
        // unlikely for this to happen
        if self.verb.is_empty() {
            return false;
        }

        // Only search the $PATH if a full or relative path was not given, or
        // if the path given does not exist
        if !Path::new(self.verb.as_str()).exists() {
            // Try to find a binary in our path with the same name as the verb
            // Searches in $PATH order
            match bins
                .iter()
                .find(|bin| bin.split('/').last().unwrap() == self.verb)
            {
                Some(_) => return true,
                None => return false,
            }
        }

        // Return true if the full path or relative path exists
        true
    }
}

/// Holds a [Stanza] and its [Meter]
///
/// In addition to a [Stanza] and a [Meter], [verse's][Verse] also hold a bool
/// value called `couplet`, indicating that it needs to accept input on `STDIN`
/// from the previous [Verse].
#[derive(Debug)]
struct Verse {
    stanza: Stanza,
    meter: Meter,
    couplet: bool,
    rw: bool,
}

impl fmt::Display for Verse {
    /// Print out a [Verse]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{} {} {}",
            self.verb(),
            self.clause().join(" "),
            self.meter
        )
    }
}

impl Verse {
    /// Create a new [Verse]
    ///
    /// Returns a new [Verse] built from a [Stanza], a [Meter], and a `couplet`
    /// indicator. See [Poem::read] for more details on how these are
    /// constructed.
    fn new(stanza: Stanza, meter: Meter, couplet: bool, rw: bool) -> Verse {
        Verse {
            stanza,
            meter,
            couplet,
            rw,
        }
    }

    /// Alias to [Stanza::spellcheck]
    fn spellcheck(&self, bins: &Vec<String>) -> bool {
        self.stanza.spellcheck(bins)
    }

    /// Alias to [stanza's][Stanza] `verb`
    fn verb(&self) -> String {
        self.stanza.verb.clone()
    }

    /// Alias to [stanza's][Stanza] `clause`
    fn clause(&self) -> Vec<String> {
        self.stanza.clause.clone()
    }

    /// Return the entire [stanza][Stanza]
    fn stanza(&self) -> Vec<String> {
        let mut list = vec![self.stanza.verb.clone()];
        list.extend(self.stanza.clause.clone());
        list
    }

    /// Check if this verse is piping output
    fn couplet(verse: Option<&Verse>) -> bool {
        match verse {
            Some(verse) => match verse.meter {
                Meter::Couplet => true,
                Meter::None
                | Meter::Quiet
                | Meter::And
                | Meter::String
                | Meter::Read
                | Meter::Write
                | Meter::Addendum => false,
            },
            None => false,
        }
    }

    /// Check if this verse is reading from or writing to a file
    fn rw(verse: Option<&Verse>) -> bool {
        match verse {
            Some(verse) => match verse.meter {
                Meter::Read | Meter::Write | Meter::Addendum => true,
                Meter::None | Meter::Couplet | Meter::Quiet | Meter::And | Meter::String => false,
            },
            None => false,
        }
    }

    /// Check if this verse has a meter
    fn cadence(verse: Option<&Verse>) -> bool {
        match verse {
            Some(verse) => match verse.meter {
                Meter::Couplet
                | Meter::Quiet
                | Meter::And
                | Meter::String
                | Meter::Read
                | Meter::Write
                | Meter::Addendum => true,
                Meter::None => false,
            },
            None => false,
        }
    }
}

/// An entire shell command parsed into [verse's][Verse]
///
/// A [Poem] is the structure that contains a full shell command/program. It
/// may be composed of one or many [verse's][Verse].
#[derive(Debug)]
pub struct Poem {
    verses: Vec<Verse>,
}

impl Poem {
    /// Create a new [Poem]
    ///
    /// Returns a new [Poem] built from a list of [verse's][Verse].
    fn new(verses: Vec<Verse>) -> Poem {
        Poem { verses }
    }

    /// Recite a [Poem] (run the shell command(s)/program)
    ///
    /// This function attempts to call each [Verse] in the [Poem], in the order
    /// that it was inputted/parsed.
    ///
    /// # Arguments
    /// * `path` - A list of directories from the $PATH environment variable
    ///            Needed in case we need to refresh the $PATH
    /// * `bins` - A list of binaries cached from the $PATH, used for searching
    ///            for a program that matches the verb in each [Verse]
    ///
    /// # Returns
    /// * `true` - If the entire [Poem] was recited without fault
    /// * `false` - If any [Verse] of the [Poem] was invalid
    ///
    /// # Examples
    /// ```
    /// let poetry = "ps aux | grep dwvsh".to_string();
    /// let poem = Poem::read(poetry);
    ///
    /// match poem {
    ///     Some(poem) => { poem.recite(path, &mut bins); }
    ///     None => {}
    /// }
    /// ```
    pub fn recite(&self, path: &Vec<&Path>, bins: &mut Vec<String>) -> Result<(), io::Error> {
        // Variable for storing the output of a piped verse
        let mut out: String = String::new();
        let mut pids: Arc<Mutex<Vec<i32>>> = Arc::new(Mutex::new(Vec::new()));

        // Loop through each verse in the poem
        for (i, verse) in self.verses.iter().enumerate() {
            // Don't perform any actions on a verse if it's for Meter::Read or
            // Meter::Write
            if verse.rw {
                continue;
            }

            // Check if user wants to exit the shell
            if verse.verb() == "exit" || verse.verb() == "quit" {
                exit(0);
            }

            // Check if the user wants to change directories
            if verse.verb() == "cd" {
                let path: String;
                if verse.clause().is_empty() {
                    path = env!("HOME").to_string();
                } else {
                    path = verse.clause().first().unwrap().to_owned();
                }

                match std::env::set_current_dir(&path) {
                    Ok(_) => continue,
                    Err(_) => {
                        println!("cd: unable to change into {}", path);
                        continue;
                    }
                }
            }

            // Check if the verb exists
            // If it doesn't exist, try refreshing the binary cache, and check
            // again
            // If it still doesn't exist, print an error
            if !verse.spellcheck(bins) {
                *bins = prefresh(path);
                if !verse.spellcheck(bins) {
                    println!("dwvsh: {}: command not found", verse.verb());
                    continue;
                }
            }

            let mut meter = verse.meter;

            // Incant the verse, based on its meter
            let status = match meter {
                Meter::None => Meter::incant_none(verse, &mut out)?,
                Meter::Couplet => Meter::incant_couplet(verse, &mut out)?,
                Meter::Quiet => Meter::incant_quiet(verse, &mut out, &mut pids)?,
                Meter::And => Meter::incant_and(verse, &mut out)?,
                Meter::String => Meter::incant_string(verse, &mut out)?,
                Meter::Read => {
                    // The parser will detect if a Read/Write/Addendum is
                    // missing a list of files, meaning we should always
                    // be able to access verses at i + 1
                    let status = match Meter::incant_read(verse, &self.verses[i + 1], &mut out) {
                        Ok(status) => status,
                        Err(e) => {
                            eprintln!("dwvsh: {}", e.to_string().to_lowercase());
                            meter = self.verses[i + 1].meter;
                            1
                        }
                    };

                    status
                }
                Meter::Write => {
                    // The parser will detect if a Read/Write/Addendum is
                    // missing a list of files, meaning we should always
                    // be able to access verses at i + 1
                    let status = match Meter::incant_write(verse, &self.verses[i + 1], &mut out) {
                        Ok(status) => status,
                        Err(e) => {
                            eprintln!("dwvsh: {}", e.to_string().to_lowercase());
                            meter = self.verses[i + 1].meter;
                            1
                        }
                    };

                    status
                }
                Meter::Addendum => {
                    // The parser will detect if a Read/Write/Addendum is
                    // missing a list of files, meaning we should always
                    // be able to access verses at i + 1
                    let status = match Meter::incant_addendum(verse, &self.verses[i + 1], &mut out)
                    {
                        Ok(status) => status,
                        Err(e) => {
                            eprintln!("dwvsh: {}", e.to_string().to_lowercase());
                            meter = self.verses[i + 1].meter;
                            1
                        }
                    };

                    status
                }
            };

            // Don't continue reciting if there was an error, unless the meter
            // is String (indicating that errors should be ignored)
            if meter != Meter::String && status != 0 {
                break;
            }
        }

        // If we've successfully exited the loop, then all verse's were
        // properly recited
        Ok(())
    }

    /// Parse a [Poem] from a raw [String] input
    ///
    /// Takes a shell command/program and converts it to a machine-runnable
    /// [Poem]. If there is a parse error, [Poem::read] may [Option]ally return
    /// `None`. As of now, there is no support for multiline programs, unless
    /// newlines (`\n`) were to be swapped out for semicolons (`;`) before
    /// calling this function. See [Poem::recite] for how each [Verse] in a
    /// [Poem] is called.
    ///
    /// # Examples
    /// ```
    /// let poetry = "ps aux | grep dwvsh".to_string();
    /// let poem = Poem::read(poetry);
    /// ```
    pub fn read(poetry: String) -> Option<Poem> {
        // Need to loop through each char in the input string, since some
        // characters aren't whitespace dilineated (`;`, `&`, etc.)
        //
        // Need to keep track of the previous verse, since it might haver
        // a Meter of Couplet, meaning that we need to set couplet on the
        // current verse
        let mut chars = poetry.chars();
        let mut verses: Vec<Verse> = Vec::new(); // Accumulate verses
        let mut stanza: Vec<String> = Vec::new(); // Stack for each stanza
        let mut word: Vec<char> = Vec::new(); // Stack for each word
        let mut prev: Option<&Verse> = None; // The previous verse
        let mut i: usize = 0; // Keep track of our index into chars

        // Parse from left to right
        loop {
            // Get the next character in the input string
            let char = chars.next();

            // Do something depending on what the character is
            match char {
                // Print an error, and return None if a Meter was used without
                // a Stanza before it
                Some(meter)
                    if ((meter == '|' || meter == '&')
                        && Verse::cadence(prev)
                        && stanza.is_empty())
                        || ((meter == '|' || meter == '&') && i == 0) =>
                {
                    eprintln!(
                        "dwvsh: parse error: verse must have a stanza: rune {} at column {}",
                        meter, i
                    );
                    return None;
                }

                // The character represents the Couplet Meter
                Some(meter) if meter == '|' => {
                    // If there are chars on the word stack, push that word
                    // onto the stanza
                    if !word.is_empty() {
                        stanza.push(word.iter().collect());
                    }

                    // A meter indicates the end of a verse
                    verses.push(Verse::new(
                        Stanza::new(stanza.clone()),
                        Meter::Couplet,
                        Verse::couplet(prev),
                        Verse::rw(prev),
                    ));

                    // Clear the stacks
                    stanza.clear();
                    word.clear();
                }

                // The character represents the Quiet (or And) Meter
                Some(meter) if meter == '&' => {
                    // If there are chars on the word stack, push that word
                    // onto the stanza
                    if !word.is_empty() {
                        stanza.push(word.iter().collect());
                    }

                    // Need to peek at the next character, since '&' can mean
                    // Meter::Quiet, or '&&' can mean Meter::And
                    match chars.clone().peekable().peek() {
                        // Indicated Meter::And
                        Some(c) if c == &'&' => {
                            // Pop the next character from the input string
                            // (since we know what it is)
                            chars.next();

                            // A meter indicates the end of a verse
                            verses.push(Verse::new(
                                Stanza::new(stanza.clone()),
                                Meter::And,
                                Verse::couplet(prev),
                                Verse::rw(prev),
                            ));
                        }

                        // Indicates Meter::Quiet
                        Some(_) => {
                            // A meter indicates the end of a verse
                            verses.push(Verse::new(
                                Stanza::new(stanza.clone()),
                                Meter::Quiet,
                                Verse::couplet(prev),
                                Verse::rw(prev),
                            ));
                        }

                        // Indicated the end of the input
                        None => {
                            // The end of input also indicates the end of a
                            // verse
                            verses.push(Verse::new(
                                Stanza::new(stanza.clone()),
                                Meter::Quiet,
                                Verse::couplet(prev),
                                Verse::rw(prev),
                            ));

                            // We can break out of the loop here, since it's
                            // the end of the raw input
                            break;
                        }
                    }

                    // Clear the stacks
                    stanza.clear();
                    word.clear();
                }

                // The character represents the String Meter
                Some(meter) if meter == ';' => {
                    // If there are chars on the word stack, push that word
                    // onto the stanza
                    if !word.is_empty() {
                        stanza.push(word.iter().collect());
                    }

                    // Check if the last verse was a meter of Read, Write, or
                    // Addendum, and throw an error if it is
                    if Verse::rw(prev) && stanza.is_empty() {
                        let rw = match prev.unwrap().meter {
                            Meter::Read => "read",
                            Meter::Write => "write",
                            Meter::Addendum => "append",
                            _ => "",
                        };
                        eprintln!("dwvsh: parse error: no {} file(s) specified", rw);
                        return None;
                    }

                    // A meter indicates the end of a verse
                    if !stanza.is_empty() {
                        verses.push(Verse::new(
                            Stanza::new(stanza.clone()),
                            Meter::String,
                            Verse::couplet(prev),
                            Verse::rw(prev),
                        ));
                    }

                    // Clear the stacks
                    stanza.clear();
                    word.clear();
                }

                // The character represents the Read Meter
                Some(meter) if meter == '<' => {
                    // If there are chars on the word stack, push that word
                    // onto the stanza
                    if !word.is_empty() {
                        stanza.push(word.iter().collect());
                    }

                    // A meter indicates the end of a verse
                    verses.push(Verse::new(
                        Stanza::new(stanza.clone()),
                        Meter::Read,
                        true,
                        Verse::rw(prev),
                    ));

                    // Clear the stacks
                    stanza.clear();
                    word.clear();
                }

                // The character represents the Write Meter
                Some(meter) if meter == '>' => {
                    // If there are chars on the word stack, push that word
                    // onto the stanza
                    if !word.is_empty() {
                        stanza.push(word.iter().collect());
                    }

                    // Check if the last verse was a meter of Read, Write, or
                    // Addendum, and throw an error if it is
                    if Verse::rw(prev) && stanza.is_empty() {
                        let rw = match prev.unwrap().meter {
                            Meter::Read => "read",
                            Meter::Write => "write",
                            Meter::Addendum => "append",
                            _ => "",
                        };
                        eprintln!("dwvsh: parse error: no {} file(s) specified", rw);
                        return None;
                    }

                    // Need to peek at the next character, since '>' can mean
                    // Meter::Write, or '>>' can mean Meter::Addendum
                    match chars.clone().peekable().peek() {
                        // Indicated Meter::Addendum
                        Some(c) if c == &'>' => {
                            // Pop the next character from the input string
                            // (since we know what it is)
                            chars.next();

                            // A meter indicates the end of a verse
                            verses.push(Verse::new(
                                Stanza::new(stanza.clone()),
                                Meter::Addendum,
                                Verse::couplet(prev),
                                Verse::rw(prev),
                            ));
                        }

                        // Indicates Meter::Write
                        Some(_) => {
                            // A meter indicates the end of a verse
                            verses.push(Verse::new(
                                Stanza::new(stanza.clone()),
                                Meter::Write,
                                Verse::couplet(prev),
                                Verse::rw(prev),
                            ));
                        }

                        // Indicated the end of the input
                        None => {
                            // A meter indicates the end of a verse
                            verses.push(Verse::new(
                                Stanza::new(stanza.clone()),
                                Meter::Write,
                                Verse::couplet(prev),
                                Verse::rw(prev),
                            ));

                            // We can break out of the loop here, since it's
                            // the end of the raw input
                        }
                    }

                    // Clear the stacks
                    stanza.clear();
                    word.clear();
                }

                // The character is a newline (may happen if parsing from a file)
                Some(char) if char == '\n' => {
                    // If there are chars on the word stack, push that word
                    // onto the stanza
                    if !word.is_empty() {
                        stanza.push(word.iter().collect());
                    }

                    // A newline indicates the end of a verse
                    if !stanza.is_empty() {
                        verses.push(Verse::new(
                            Stanza::new(stanza.clone()),
                            Meter::String,
                            Verse::couplet(prev),
                            Verse::rw(prev),
                        ));
                    }

                    // Clear the stacks
                    stanza.clear();
                    word.clear();
                }

                // The character is whitespace
                Some(char) if char == ' ' || char == '\t' => {
                    // If there are chars on the word stack, push that word
                    // onto the stanza
                    if !word.is_empty() {
                        stanza.push(word.iter().collect());
                        word.clear();
                    }
                }

                // The character is any other utf8 glyph
                Some(char) => {
                    // Add the character onto the current word stack
                    word.push(char);
                }

                // Indicates the end of the list of characters
                None => {
                    // Always push the last word onto the stanza
                    if !word.is_empty() {
                        stanza.push(word.iter().collect());
                    }

                    // Check if the last verse was a meter of Read, Write, or
                    // Addendum, and throw an error if it is
                    if Verse::rw(prev) && stanza.is_empty() {
                        let rw = match prev.unwrap().meter {
                            Meter::Read => "read",
                            Meter::Write => "write",
                            Meter::Addendum => "append",
                            _ => "",
                        };
                        eprintln!("dwvsh: parse error: no {} file(s) specified", rw);
                        return None;
                    }

                    // Only push the stanza into a verse if it contains
                    // any words
                    if !stanza.is_empty() {
                        verses.push(Verse::new(
                            Stanza::new(stanza.clone()),
                            Meter::None,
                            Verse::couplet(prev),
                            Verse::rw(prev),
                        ));
                    }

                    // Break from the loop, since we are out of chars
                    break;
                }
            }

            // Set previous verse to the verse that was just pushed at the end
            // of each loop
            prev = match verses.last() {
                Some(verse) => Some(verse),
                None => None,
            };

            // Increment the index
            i += 1;
        }

        // Return the (parsed) poem
        Some(Poem::new(verses))
    }
}

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

    #[test]
    fn it_parses_a_verse_with_no_meter() {
        let poem = Poem::read("cargo build --release".to_string());
        assert!(poem.is_some());
        let poem = poem.unwrap();
        assert_eq!(poem.verses.first().unwrap().verb(), "cargo");
    }

    #[test]
    fn it_parses_a_verse_with_the_couplet_meter() {
        let poem = Poem::read("ls -la | lolcat".to_string());
        assert!(poem.is_some());
        let poem = poem.unwrap();
        assert_eq!(poem.verses.first().unwrap().verb(), "ls");
        assert_eq!(poem.verses.first().unwrap().meter, Meter::Couplet);
    }

    #[test]
    fn it_parses_a_verse_with_the_quiet_meter() {
        let poem = Poem::read("sleep 20 &".to_string());
        assert!(poem.is_some());
        let poem = poem.unwrap();
        assert_eq!(poem.verses.first().unwrap().verb(), "sleep");
        assert_eq!(poem.verses.first().unwrap().meter, Meter::Quiet);
    }

    #[test]
    fn it_parses_a_verse_with_the_and_meter() {
        let poem = Poem::read("sleep 2 && ls -la".to_string());
        assert!(poem.is_some());
        let poem = poem.unwrap();
        assert_eq!(poem.verses.first().unwrap().verb(), "sleep");
        assert_eq!(poem.verses.first().unwrap().meter, Meter::And);
    }

    #[test]
    fn it_parses_a_verse_with_the_string_meter() {
        let poem = Poem::read("sleep 2; ls -la".to_string());
        assert!(poem.is_some());
        let poem = poem.unwrap();
        assert_eq!(poem.verses.first().unwrap().verb(), "sleep");
        assert_eq!(poem.verses.first().unwrap().meter, Meter::String);
    }

    #[test]
    fn it_parses_a_complex_verse_with_lots_of_different_meters() {
        let poem = Poem::read("ls -la | lolcat && echo hello | lolcat && sleep 2 &".to_string());
        assert!(poem.is_some());
        let mut verses = poem.unwrap().verses.into_iter();

        let verse = verses.next().unwrap();
        assert_eq!(verse.verb(), "ls");
        assert_eq!(verse.clause(), vec!["-la".to_string()]);
        assert_eq!(verse.meter, Meter::Couplet);

        let verse = verses.next().unwrap();
        assert_eq!(verse.verb(), "lolcat");
        assert_eq!(verse.meter, Meter::And);

        let verse = verses.next().unwrap();
        assert_eq!(verse.verb(), "echo");
        assert_eq!(verse.clause(), vec!["hello".to_string()]);
        assert_eq!(verse.meter, Meter::Couplet);

        let verse = verses.next().unwrap();
        assert_eq!(verse.verb(), "lolcat");
        assert_eq!(verse.meter, Meter::And);

        let verse = verses.next().unwrap();
        assert_eq!(verse.verb(), "sleep");
        assert_eq!(verse.clause(), vec!["2".to_string()]);
        assert_eq!(verse.meter, Meter::Quiet);
    }

    #[test]
    fn it_parses_the_string_meter_without_a_stanza() {
        let poem = Poem::read(";;;;;;;".to_string());
        assert!(poem.is_some());
    }

    #[test]
    fn it_errors_if_the_couplet_meter_is_used_without_a_stanza() {
        let poem = Poem::read("|".to_string());
        assert!(poem.is_none());
    }

    #[test]
    fn it_errors_if_the_quiet_meter_is_used_without_a_stanza() {
        let poem = Poem::read("&".to_string());
        assert!(poem.is_none());
    }

    #[test]
    fn it_errors_if_the_and_meter_is_used_without_a_stanza() {
        let poem = Poem::read("&&".to_string());
        assert!(poem.is_none());
    }

    #[test]
    fn it_parses_a_file() {
        let file = r"
            ps aux | lolcat
            sleep 2
        ";

        let poem = Poem::read(file.to_string());
        assert!(poem.is_some());

        let poem = poem.unwrap();
        assert_eq!(poem.verses.len(), 3);

        let mut verses = poem.verses.into_iter();

        let verse = verses.next().unwrap();
        assert_eq!(verse.verb(), "ps");
        assert_eq!(verse.clause(), vec!["aux".to_string()]);
        assert_eq!(verse.meter, Meter::Couplet);

        let verse = verses.next().unwrap();
        assert_eq!(verse.verb(), "lolcat");
        assert_eq!(verse.meter, Meter::String);

        let verse = verses.next().unwrap();
        assert_eq!(verse.verb(), "sleep");
        assert_eq!(verse.clause(), vec!["2".to_string()]);
        assert_eq!(verse.meter, Meter::String);
    }

    #[test]
    fn it_parses_a_longer_file() {
        let file = r"
            ps aux | lolcat
            sleep 2
            ps aux | lolcat
            sleep 2

            echo hello there
            export PATH=$PATH:~/.local/bin

            ps aux | lolcat && lolcat src/main.rs
            fortune | cowsay | lolcat

            wc -l src/**/*.rs | lolcat; ls -la | grep git
        ";

        let poem = Poem::read(file.to_string());
        assert!(poem.is_some());

        let poem = poem.unwrap();
        assert_eq!(poem.verses.len(), 18);
    }
}