summaryrefslogtreecommitdiffstats
path: root/src/poem/recite.rs
blob: 23113522fedca3d305e24ced3e6aef01c8bd2ce9 (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
use super::Poem;
use crate::compose::Environment;
use crate::path;
use crate::poem::anthology;
use crate::poem::elements::rune::Rune;
use crate::poem::elements::stanza::Stanza;
use std::env;
use std::{
    io,
    sync::{Arc, Mutex},
};

pub trait Reciteable {
    fn recite(&self, env: &mut Environment) -> Result<Vec<u8>, io::Error>;
}

impl Reciteable for Poem {
    fn recite(&self, env: &mut Environment) -> Result<Vec<u8>, io::Error> {
        // Variable for storing the output of a piped verse
        let mut out: Vec<u8> = Vec::new();

        // Keep track of pids for background processes
        let mut pids: Arc<Mutex<Vec<i32>>> = Arc::new(Mutex::new(Vec::new()));

        // Loop through each verse in the poem
        for verse in self.iter() {
            // Verse may need to be mutable
            let mut verse = verse.clone();

            // Check for environment variables
            for word in verse.stanza.iter_mut() {
                while word.contains("$") {
                    let mut name = vec![];
                    let mut idx = word.chars().position(|c| c == '$').unwrap() + 1;
                    let bytes = word.as_bytes();
                    while idx < word.len() {
                        let c = bytes[idx] as char;
                        if !c.is_alphanumeric() {
                            break;
                        }
                        name.push(c);
                        idx += 1;
                    }
                    let name: String = format!("${}", name.iter().collect::<String>());
                    let envar = name[1..].to_string();
                    let envar = match env::var(envar) {
                        Ok(envar) => envar.to_string(),
                        Err(_) => String::new(),
                    };
                    *word = word.replace(name.as_str(), envar.as_str());
                }

                // For any words in single quotes strings that began with a '$',
                // need to replace the ASCII SO placeholder with the '$' char once
                // more
                *word = word.replace('\x0e', "$");
            }

            // Check if verse is a builtin
            let index = anthology::lookup(&verse.verb());

            // Run interal poems
            let v = verse.clone();
            let mut new_stanza: Option<Stanza> = None;
            if verse.poems() {
                // Collect all the words that have vertical tabs
                let mut wordp_indicies = vec![];
                let wordps = verse
                    .stanza
                    .iter_mut()
                    .enumerate()
                    .filter(|(_, w)| w.contains("\x0b"))
                    .map(|(i, w)| {
                        wordp_indicies.push(i + 1);
                        w
                    })
                    .collect::<Vec<&mut String>>();

                // Loop through each word and replace with the output of the poem
                let mut poems = verse.poems.iter();
                let mut j = 0;
                for wordp in wordps {
                    let times = wordp
                        .chars()
                        .filter(|c| c == &'\x0b')
                        .collect::<String>()
                        .len();
                    for _ in 0..times {
                        let poem = match poems.next() {
                            Some(poem) => poem,
                            None => break, // TODO: Return an error
                        };
                        let mut out = poem.recite(env)?;
                        match out.last() {
                            Some(last) => {
                                if *last == b'\n' {
                                    out.remove(out.len() - 1);
                                }
                            }
                            None => {}
                        }

                        let out = String::from_utf8_lossy(&out);
                        if out.contains("\n") && index.is_none() {
                            let mut out = out.split("\n");
                            let next = out.next().unwrap_or("").trim();
                            *wordp = wordp.replacen("\x0b", next, 1).to_string();
                            let (_, right) = v.stanza.split_at(wordp_indicies[j]);
                            let mut left = vec![];
                            let mut right = right.to_vec();
                            loop {
                                let next = match out.next() {
                                    Some(next) => next,
                                    None => break,
                                }
                                .to_string();
                                left.push(next);
                            }
                            left.append(&mut right);
                            new_stanza = Some(left.clone());
                        } else {
                            *wordp = wordp.replacen("\x0b", &out, 1).to_string();
                        }
                    }
                    j += 1;
                }
            }

            match new_stanza {
                Some(stanza) => {
                    let mut stanza = stanza.clone();
                    verse.stanza.append(&mut stanza);
                }
                None => {}
            };

            // Incant the verse if it's a built-in
            let status = if index.is_some() {
                anthology::incant(&verse, &mut out, index.unwrap(), env)
            } else {
                // Checking for environment variables and running internal
                // poems may mean that the verb is empty now, so check it once
                // more
                // If it is empty, just continue to the next verse
                if !verse.verb().is_empty() {
                    // Check if the verb exists on the PATH
                    // 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(&env.bins) {
                        env.bins = path::refresh();
                        if !verse.spellcheck(&env.bins) {
                            eprintln!("dwvsh: {}: command not found", verse.verb());

                            if verse.meter != Rune::And {
                                continue;
                            }
                        }
                    }
                } else {
                    continue;
                }
                verse.incant(&mut out, &mut pids)?
            };

            // Break from the loop if the meter is not [Rune::Continue], and
            // if the status is not 0
            // For [Rune::Quiet], [Rune::incant_quiet] will always return 0
            if verse.meter != Rune::Continue && status != 0 {
                break;
            }
        }

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