summaryrefslogtreecommitdiffstats
path: root/src/poem/elements/verse.rs
blob: 307ebc881ecf641afce254590bb72b39caa4f085 (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
use super::rune::Rune;
use super::stanza::Stanza;
use super::word::Word;
use crate::poem::Poem;
use libc::{waitpid, WNOHANG};
use std::fs::OpenOptions;
use std::io::{self, Read, Write};
use std::os::unix::process::CommandExt;
use std::path::Path;
use std::process::{Command, Output, Stdio};
use std::sync::{Arc, Mutex};

/// A [Stanza] and it's [meter](Rune)
///
/// In addition to a [Stanza] and a [meter](Rune), this also holds a [bool]
/// value called `couplet`, indicating that it needs to accept input on `STDIN`
/// from the previous [Verse].
#[derive(Debug, Clone)]
pub struct Verse {
    pub stanza: Stanza,
    pub couplet: u8,
    pub io: Vec<Rune>,
    pub ip: Stanza,
    pub op: Stanza,
    pub ep: Stanza,
    pub poems: Vec<Poem>,
    pub meter: Rune,
}

impl Verse {
    /// Create a new [Verse]
    ///
    /// Returns a new [Verse], with an empty [Stanza], a meter of [Rune::None],
    /// and `couplet` set to `false`.
    pub fn new() -> Self {
        Verse {
            stanza: Stanza::new(),
            couplet: 0,
            io: Vec::new(),
            ip: Stanza::new(),
            op: Stanza::new(),
            ep: Stanza::new(),
            poems: Vec::new(),
            meter: Rune::None,
        }
    }

    /// Get the [Verse]'s verb
    ///
    /// Return the program to be forked
    pub fn verb(&self) -> String {
        self.stanza[0].clone()
    }

    /// Get the [Verse]'s clause
    ///
    /// Return program arguments, if they exist
    pub fn clause(&self) -> Option<Vec<String>> {
        match self.stanza.len() {
            0 => None,
            1 => None,
            _ => Some(self.stanza[1..].to_vec()),
        }
    }

    /// Alias to [Verse].stanza.push()
    pub fn push(&mut self, word: String) {
        self.stanza.push(word);
    }

    /// Alias to [Verse].stanza.is_empty()
    pub fn is_empty(&self) -> bool {
        self.stanza.is_empty()
    }

    /// Alias to [Verse].stanza.clear()
    pub fn clear(&mut self) {
        self.stanza.clear();
        self.io.clear();
        self.poems.clear();
    }

    /// Check if the [Verse] contains any internal poems
    pub fn poems(&self) -> bool {
        if self.poems.len() > 0 {
            return true;
        }
        false
    }

    /// Push a word to the [Verse]'s [Stanza]
    ///
    /// Push a word to the [Stanza] after performing a few extra checks, such
    /// as whether or not the word is empty, or if the word should be
    /// interpreted as an environment variable.
    pub fn add(&mut self, word: &mut Word, channel: Option<Rune>) {
        // Do nothing if the stack is empty
        if word.is_empty() {
            return;
        }

        // Push the word
        match channel {
            Some(Rune::Read) => self.ip.push(word.iter().collect()),
            Some(Rune::Write) | Some(Rune::Addendum) => self.op.push(word.iter().collect()),
            Some(Rune::Write2) | Some(Rune::Addendum2) => self.ep.push(word.iter().collect()),
            Some(Rune::WriteAll) | Some(Rune::AddendumAll) => {
                self.op.push(word.iter().collect());
                self.ep.push(word.iter().collect());
            }
            Some(_) | None => self.push(word.iter().collect()),
        }

        // Clear the stack
        word.clear();
    }

    /// 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 seeif 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
    /// ```
    pub 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
    }

    pub fn incant(
        &mut self,
        out: &mut Vec<u8>,
        pids: &mut Arc<Mutex<Vec<i32>>>,
    ) -> Result<i32, io::Error> {
        // Read files into 'out' if Rune::Read is present in the verse's IO
        if self.io.contains(&Rune::Read) {
            // Enable piping on stdin
            self.couplet += 2;

            // Read all files specified after '<' into 'out', since there may
            // also be piped output from the last command
            for path in self.ip.iter() {
                let mut file = OpenOptions::new().read(true).open(path)?;
                let mut contents = String::new();
                file.read_to_string(&mut contents)?;
                out.append(&mut contents.as_bytes().to_vec());
            }
        }

        // Build the command
        let mut command = Command::new(self.verb());
        command.args(self.clause().unwrap_or(vec![]));

        // Determine couplet status
        if self.couplet == 1 {
            // Verse is the left half of a couplet
            command.stdout(Stdio::piped());
        } else if self.couplet == 2 {
            // Verse is the right half of a couplet
            command.stdin(Stdio::piped());
        } else if self.couplet == 3 {
            // Verse is taking in and piping out output
            command.stdout(Stdio::piped());
            command.stdin(Stdio::piped());
        }

        // Setup for other IO
        if self.io.contains(&Rune::Write) || self.io.contains(&Rune::Addendum) {
            command.stdout(Stdio::piped());
        }
        if self.io.contains(&Rune::Write2) || self.io.contains(&Rune::Addendum2) {
            command.stderr(Stdio::piped());
        }
        if self.io.contains(&Rune::WriteAll) || self.io.contains(&Rune::AddendumAll) {
            command.stdout(Stdio::piped());
            command.stderr(Stdio::piped());
        }

        // Detach the process group, if in the [Rune::Quiet] meter
        if self.meter == Rune::Quiet {
            command.process_group(0);
        }

        // Spawn the process
        let mut child = command.spawn()?;

        // Pipe in command, if we're the right side of a couplet
        if self.couplet > 1 {
            let stdin = child.stdin.as_mut().ok_or(io::ErrorKind::BrokenPipe)?;
            stdin.write_all(&out)?;
            out.clear();
        }

        // Determine what to do based on the meter
        let mut output: Output;
        let mut err: Vec<u8> = Vec::new();
        match self.meter {
            Rune::None | Rune::And | Rune::Continue => {
                output = child.wait_with_output()?;
                if self.io.contains(&Rune::Write) || self.io.contains(&Rune::Addendum) {
                    out.append(&mut output.stdout);
                }
                if self.io.contains(&Rune::Write2) || self.io.contains(&Rune::Addendum2) {
                    err.append(&mut output.stderr);
                }
                if self.io.contains(&Rune::WriteAll) || self.io.contains(&Rune::AddendumAll) {
                    out.append(&mut output.stdout);
                    err.append(&mut output.stderr);
                }
            }
            Rune::Couplet => {
                output = child.wait_with_output()?;
                out.append(&mut output.stdout);
                if self.io.contains(&Rune::Write2) || self.io.contains(&Rune::Addendum2) {
                    err.append(&mut output.stderr);
                }
                if self.io.contains(&Rune::WriteAll) || self.io.contains(&Rune::AddendumAll) {
                    err.append(&mut output.stderr);
                }
            }
            Rune::Quiet => {
                println!("[&]  {}", child.id());

                pids.lock().unwrap().push(child.id() as i32);
                let stanza = self.stanza.join(" ").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();
                }

                return Ok(0);
            }
            _ => unreachable!(),
        }

        // Perform IO operations
        let mut oi = 0;
        let mut ei = 0;
        self.io.retain(|rune| *rune != Rune::Read);
        for io in self.io.iter() {
            let (f, f2) = match *io {
                Rune::Write => {
                    oi += 1;
                    (
                        Some(
                            OpenOptions::new()
                                .create(true)
                                .write(true)
                                .open(&self.op[oi - 1])?,
                        ),
                        None,
                    )
                }
                Rune::Write2 => {
                    ei += 1;
                    (
                        None,
                        Some(
                            OpenOptions::new()
                                .create(true)
                                .write(true)
                                .open(&self.ep[ei - 1])?,
                        ),
                    )
                }
                Rune::WriteAll => {
                    oi += 1;
                    ei += 1;
                    (
                        Some(
                            OpenOptions::new()
                                .create(true)
                                .write(true)
                                .open(&self.op[oi - 1])?,
                        ),
                        Some(
                            OpenOptions::new()
                                .create(true)
                                .write(true)
                                .open(&self.ep[ei - 1])?,
                        ),
                    )
                }
                Rune::Addendum => {
                    oi += 1;
                    (
                        Some(
                            OpenOptions::new()
                                .create(true)
                                .append(true)
                                .open(&self.op[oi - 1])?,
                        ),
                        None,
                    )
                }
                Rune::Addendum2 => {
                    ei += 1;
                    (
                        None,
                        Some(
                            OpenOptions::new()
                                .create(true)
                                .append(true)
                                .open(&self.ep[ei - 1])?,
                        ),
                    )
                }
                Rune::AddendumAll => {
                    oi += 1;
                    ei += 1;
                    (
                        Some(
                            OpenOptions::new()
                                .create(true)
                                .append(true)
                                .open(&self.op[oi - 1])?,
                        ),
                        Some(
                            OpenOptions::new()
                                .create(true)
                                .append(true)
                                .open(&self.ep[ei - 1])?,
                        ),
                    )
                }
                _ => unreachable!(),
            };

            match f {
                Some(mut file) => file.write(out)?,
                None => 0,
            };

            match f2 {
                Some(mut file) => file.write(&err)?,
                None => 0,
            };
        }

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

        out.clear();
        err.clear();

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