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
|
use super::verse::Verse;
use crate::iobtask;
use crate::{btask, ctask, task};
use core::fmt;
use libc::waitpid;
use libc::WNOHANG;
use std::fs::OpenOptions;
use std::io::{self, Read, Write};
use std::os::unix::process::CommandExt;
use std::process::{Command, Stdio};
use std::sync::{Arc, Mutex};
/// Describes one or two characters from the input
///
/// [Rune]s are a way to mark special characters from the input string (i.e.
/// poetry). Some [Rune]s are special--as they denote the end of a [Verse]--
/// and are refered to as a Meter. For instance, `Addendum`, `Couplet`,
/// `Quiet`, and `And`, are all meters. Meters also determine how the
/// [Stanza][super::stanza::Stanza] should be interpreted. For instance, a
/// [Stanza][super::stanza::Stanza] that is piped needs to have
/// its `STDOUT` captured (rather than printing out to the terminal), and
/// subsequently sent to the next [Verse] in the [Poem][super::super::Poem].
///
/// # Values
/// * `None` - A shell command with no additional actions (the end of a poem)
/// * `Pause` - The space character, to dilineate words (` `)
/// * `Path` - The forward slash character, to dilineate paths (`/`)
/// * `Remark` - Indicates a single line comment (`#`)
/// * `String` - Interpret all character as one large
/// [Word][super::word::Word] (`'` or `"`)
/// * `Poem` - A subcommand to run first (`\``)
/// * `Read` - Read files into STDIN (`<`)
/// * `Write` - Write STDOUT to a file (`>`)
/// * `Addendum` - Append STDOUT to a file (`>>`)
/// * `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 (`&&`)
/// * `Continue` - String commands together on a single line (`;`)
/// * `Home` - Interpret `~` as `$HOME`
/// * `Else` - Any other character
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum Rune {
None, // No meter (the end of a poem)
Pause, // A space
Path, // A forward slash
Remark, // A comment
String, // Interpret the following as one large [Word]
Poem, // Run a sub-poem before the main one
Read, // Read files into STDIN
Write, // Send STDOUT to a file
Addendum, // Append STDOUT to a file
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
Continue, // Run the next command, even if this doesn't succeed
Home, // Interpret '~' as $HOME
Else, // Any other character
}
impl fmt::Display for Rune {
/// Determine how to print out a [Rune]
///
/// Each [Rune]'s symbol corresponds to its input.
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let rune = match self {
Rune::None => "",
Rune::Pause => " ",
Rune::Path => "/",
Rune::Remark => "#",
Rune::String => "\"",
Rune::Poem => "`",
Rune::Read => "<",
Rune::Write => ">",
Rune::Addendum => ">>",
Rune::Couplet => "|",
Rune::Quiet => "&",
Rune::And => "&&",
Rune::Continue => ";",
Rune::Home => "~",
Rune::Else => "_",
};
write!(f, "{}", rune)
}
}
impl Rune {
// /// Check if a character is a special [Rune]
// pub fn special(rune: char) -> bool {
// match rune {
// ' ' | '/' | '$' | '\'' | '"' | '`' | '<' | '>' | '|' | '&' | ';' | '~' => true,
// _ => false,
// }
// }
/// Recite a verse with [Rune::None]
///
/// Call this function on a [Verse] with a meter of type [Rune::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
pub fn incant_none(verse: &Verse, out: &mut Vec<u8>) -> 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 [Rune::Couplet]
///
/// Call this function on a [Verse] with a meter of type [Rune::Couplet].
/// 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
pub fn incant_couplet(verse: &Verse, out: &mut Vec<u8>) -> Result<i32, io::Error> {
let child = ctask!(verse, out);
let mut output = child.wait_with_output()?;
if !output.status.success() {
return Ok(output.status.code().unwrap_or(-1));
}
out.append(&mut output.stdout);
Ok(output.status.code().unwrap_or(0))
}
/// Recite a verse with [Rune::Quiet]
///
/// Call this function on a [Verse] with a meter of type [Rune::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
pub fn incant_quiet(
verse: &Verse,
out: &mut Vec<u8>,
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.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();
}
Ok(0)
}
/// Alias to [Rune::incant_none]
pub fn incant_and(verse: &Verse, out: &mut Vec<u8>) -> Result<i32, io::Error> {
Rune::incant_none(verse, out)
}
/// Alias to [Rune::incant_none]
pub fn incant_continue(verse: &Verse, out: &mut Vec<u8>) -> Result<i32, io::Error> {
Rune::incant_none(verse, out)
}
/// Recite a verse with [Rune::Read]
///
/// Call this function on a [Verse] with a meter of type [Rune::Read].
/// This reads the specified files into `out`, then makes a call to
/// [Rune::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`
pub fn incant_read(
verse: &mut Verse,
out: &mut Vec<u8>,
pids: &mut Arc<Mutex<Vec<i32>>>,
) -> Result<i32, io::Error> {
// Split the verse from the paths
let paths = verse.split("<");
// 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.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());
}
// Alias incant_<meter>
match verse.meter {
Rune::None => Rune::incant_none(&verse, out),
Rune::Couplet => Rune::incant_couplet(&verse, out),
Rune::Quiet => Rune::incant_quiet(&verse, out, pids),
Rune::And => Rune::incant_and(&verse, out),
Rune::Continue => Rune::incant_continue(&verse, out),
_ => unreachable!(),
}
}
/// Recite a verse with [Rune::Write]
///
/// Call this function on a [Verse] with a meter of type [Rune::Write].
/// This writes the output of the verse into the specified files, after
/// making a call to [Rune::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`
pub fn incant_write(
verse: &mut Verse,
out: &mut Vec<u8>,
pids: &mut Arc<Mutex<Vec<i32>>>,
) -> Result<i32, io::Error> {
// Split the verse from the paths
let mut paths = Arc::new(Mutex::new(verse.split("<")));
// Alias incant_<meter>
// let status = Rune::incant_couplet(&verse, out)?;
let status = match verse.meter {
Rune::None => Rune::incant_couplet(&verse, out)?,
Rune::Couplet => Rune::incant_couplet(&verse, out)?,
Rune::Quiet => Rune::incant_quiet_io(&verse, out, pids, &mut paths)?,
Rune::And => Rune::incant_couplet(&verse, out)?,
Rune::Continue => Rune::incant_couplet(&verse, out)?,
_ => unreachable!(),
};
// Write output to each file specified in the next verse
for path in paths.lock().unwrap().iter() {
let mut file = OpenOptions::new().create(true).write(true).open(path)?;
file.write(out)?;
}
// Clear out
out.clear();
// Return the exit status
Ok(status)
}
/// Recite a verse with [Rune::Addendum]
///
/// Same as [Rune::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`
pub fn incant_addendum(
verse: &mut Verse,
out: &mut Vec<u8>,
pids: &mut Arc<Mutex<Vec<i32>>>,
) -> Result<i32, io::Error> {
// Split the verse from the paths
let mut paths = Arc::new(Mutex::new(verse.split("<")));
// Alias incant_<meter>
// let status = Rune::incant_couplet(&verse, out)?;
let status = match verse.meter {
Rune::None => Rune::incant_couplet(&verse, out)?,
Rune::Couplet => Rune::incant_couplet(&verse, out)?,
Rune::Quiet => Rune::incant_quiet_io(&verse, out, pids, &mut paths)?,
Rune::And => Rune::incant_couplet(&verse, out)?,
Rune::Continue => Rune::incant_couplet(&verse, out)?,
_ => unreachable!(),
};
// Write output to each file specified in the next verse
for path in paths.lock().unwrap().iter() {
let mut file = OpenOptions::new().create(true).append(true).open(path)?;
file.write(out)?;
}
// Clear out
out.clear();
// Return the exit status
Ok(status)
}
/// Same as incant_quiet, except capture STDOUT into `out`
pub fn incant_quiet_io(
verse: &Verse,
out: &mut Vec<u8>,
pids: &mut Arc<Mutex<Vec<i32>>>,
paths: &mut Arc<Mutex<Vec<String>>>,
) -> Result<i32, io::Error> {
let child = Arc::new(Mutex::new(iobtask!(verse, out)));
println!("[&] {}", child.lock().unwrap().id());
pids.lock().unwrap().push(child.lock().unwrap().id() as i32);
let stanza = verse.stanza.join(" ").to_string();
let pids = Arc::clone(pids);
let paths = Arc::clone(paths);
let io = Arc::new(verse.io);
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);
let mut bytes: Vec<u8> = Vec::new();
let mut child = child.lock().unwrap();
child
.stdout
.as_mut()
.unwrap()
.read_to_end(&mut bytes)
.unwrap();
for path in paths.lock().unwrap().iter() {
let file = if io == Rune::Write.into() {
OpenOptions::new().create(true).write(true).open(path)
} else if io == Rune::Addendum.into() {
OpenOptions::new().create(true).append(true).open(path)
} else {
unreachable!();
};
let _ = file.unwrap().write(&bytes);
}
io::stdout().flush().unwrap();
}
}
})
.unwrap();
}
Ok(0)
}
}
|