summaryrefslogtreecommitdiffstats
path: root/src/main.rs
blob: 3c016e9c0dd55f24dc953805cfbbcbb7b8528d40 (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
use core::fmt;
use ctrlc;
use std::fs;
use std::io::{self, Write};
use std::path::Path;
use std::process::{exit, Command, Stdio};

#[derive(Debug)]
enum Meter {
    None,   // No meter
    Pipe,   // Pipe the output of this command into the next
    Daemon, // 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
}

impl fmt::Display for Meter {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let meter = match self {
            Meter::None => "",
            Meter::Pipe => "|",
            Meter::Daemon => "&",
            Meter::And => "&&",
            Meter::String => ";",
        };

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

#[derive(Debug)]
struct Stanza {
    verb: String,
    clause: Vec<String>,
}

impl Stanza {
    fn new(stanza: Vec<String>) -> Stanza {
        Stanza {
            verb: stanza[0].clone(),
            clause: stanza[1..].to_vec(),
        }
    }

    fn spellcheck(&self, bins: &Vec<String>) -> bool {
        if self.verb.is_empty() {
            return false;
        }

        if !Path::new(self.verb.as_str()).exists() {
            match bins
                .iter()
                .find(|bin| bin.split('/').last().unwrap() == self.verb)
            {
                Some(_) => return true,
                None => return false,
            }
        }

        true
    }
}

#[derive(Debug)]
struct Verse {
    stanza: Stanza,
    meter: Meter,
    stdin: bool,
}

impl Verse {
    fn new(stanza: Stanza, meter: Meter, stdin: bool) -> Verse {
        Verse {
            stanza,
            meter,
            stdin,
        }
    }

    fn spellcheck(&self, bins: &Vec<String>) -> bool {
        self.stanza.spellcheck(bins)
    }

    fn verb(&self) -> String {
        self.stanza.verb.clone()
    }

    fn clause(&self) -> Vec<String> {
        self.stanza.clause.clone()
    }
}

impl fmt::Display for Verse {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} {}", self.verb(), self.clause().join(" "))
    }
}

#[derive(Debug)]
struct Poem {
    verses: Vec<Verse>,
}

impl Poem {
    fn new(verses: Vec<Verse>) -> Poem {
        Poem { verses }
    }

    fn recite(&self, paths: &Vec<&Path>, bins: &mut Vec<String>) -> bool {
        // println!("{:#?}", self);
        let mut out: String = String::new();

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

            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;
                    }
                }
            }

            if !verse.spellcheck(bins) {
                *bins = prefresh(paths);
                if !verse.spellcheck(bins) {
                    println!("dwvsh: {}: command not found", verse.verb());
                    continue;
                }
            }

            if verse.stdin {
                match verse.meter {
                    Meter::Pipe => {
                        let mut child = Command::new(verse.verb())
                            .args(verse.clause())
                            .stdin(Stdio::piped())
                            .stdout(Stdio::piped())
                            .spawn()
                            .expect("dwvsh: error 0");

                        let stdin = child.stdin.as_mut().expect("dwvsh: error 6");
                        stdin.write_all(&out.as_bytes()).expect("dwvsh: error 7");
                        out.clear();

                        let output = child.wait_with_output().unwrap();
                        // out = String::from_utf8_lossy(&output.stdout).to_string();
                        out = String::from_utf8(output.stdout).unwrap();
                    }
                    Meter::Daemon => {
                        let mut child = Command::new(verse.verb())
                            .args(verse.clause())
                            .stdin(Stdio::piped())
                            .spawn()
                            .expect("dwvsh: error 1");

                        let stdin = child.stdin.as_mut().expect("dwvsh: error 8");
                        stdin.write_all(&out.as_bytes()).expect("dwvsh: error 9");
                        out.clear();

                        print!("[f] {}", child.id());
                        // let p = prompt.to_owned();
                        std::thread::spawn(move || {
                            child.wait().unwrap();
                            println!("[f] +done {}", child.id());
                            io::stdout().flush().unwrap();
                        });
                    }
                    Meter::String => {
                        let mut child = Command::new(verse.verb())
                            .args(verse.clause())
                            .spawn()
                            .expect("dwvsh: error 5");

                        let stdin = child.stdin.as_mut().expect("dwvsh: error 8");
                        stdin.write_all(&out.as_bytes()).expect("dwvsh: error 9");
                        out.clear();

                        child.wait().unwrap();
                    }
                    Meter::And | Meter::None => {
                        let mut child = Command::new(verse.verb())
                            .args(verse.clause())
                            .stdin(Stdio::piped())
                            .spawn()
                            .expect("dwvsh: error 2");

                        let stdin = child.stdin.as_mut().expect("dwvsh: error 10");
                        stdin.write_all(&out.as_bytes()).expect("dwvsh: error 11");
                        out.clear();

                        if !child.wait().unwrap().success() {
                            break;
                        }
                    }
                };
            } else {
                match verse.meter {
                    Meter::Pipe => {
                        let child = Command::new(verse.verb())
                            .args(verse.clause())
                            .stdout(Stdio::piped())
                            .spawn()
                            .expect("dwvsh: error 3");

                        let output = child.wait_with_output().unwrap();
                        out = String::from_utf8_lossy(&output.stdout).to_string();
                        // out = String::from_utf8(output.stdout).unwrap();
                    }
                    Meter::Daemon => {
                        let mut child = Command::new(verse.verb())
                            .args(verse.clause())
                            .spawn()
                            .expect("dwvsh: error 4");

                        println!("[f] {}", child.id());
                        std::thread::spawn(move || {
                            child.wait().unwrap();
                            print!("[f] +done {}\n", child.id());
                            io::stdout().flush().unwrap();
                        });
                    }
                    Meter::String => {
                        let mut child = Command::new(verse.verb())
                            .args(verse.clause())
                            .spawn()
                            .expect("dwvsh: error 5");

                        child.wait().unwrap();
                    }
                    Meter::And | Meter::None => {
                        let mut child = Command::new(verse.verb())
                            .args(verse.clause())
                            .spawn()
                            .expect("dwvsh: error 5");

                        if !child.wait().unwrap().success() {
                            break;
                        }
                    }
                };
            }
        }

        true
    }
}

fn read(poetry: String) -> Option<Poem> {
    let mut chars = poetry.chars();
    let mut verses: Vec<Verse> = Vec::new();
    let mut stanza: Vec<String> = Vec::new();
    let mut word: Vec<char> = Vec::new();
    let mut prev: Option<&Verse> = None;

    loop {
        let char = chars.next();

        let pipe = match prev {
            Some(prev) => match prev.meter {
                Meter::Pipe => true,
                Meter::Daemon | Meter::And | Meter::String | Meter::None => false,
            },
            None => false,
        };

        let metered = match prev {
            Some(prev) => match prev.meter {
                Meter::Pipe | Meter::Daemon | Meter::And | Meter::String => true,
                Meter::None => false,
            },
            None => false,
        };

        match char {
            Some(meter)
                if (meter == '|' || meter == '&' || meter == ';')
                    && metered
                    && stanza.is_empty() =>
            {
                println!("dwvsh: parse error");
                return None;
            }
            Some(meter) if meter == '|' => {
                if !word.is_empty() {
                    stanza.push(word.iter().collect());
                }
                verses.push(Verse::new(Stanza::new(stanza.clone()), Meter::Pipe, pipe));
                stanza = Vec::new();
                word.clear();
            }
            Some(meter) if meter == '&' => {
                if !word.is_empty() {
                    stanza.push(word.iter().collect());
                }

                match chars.clone().peekable().peek() {
                    Some(c) if c == &'&' => {
                        chars.next();
                        verses.push(Verse::new(Stanza::new(stanza.clone()), Meter::And, pipe));
                    }
                    Some(_) => {
                        verses.push(Verse::new(Stanza::new(stanza.clone()), Meter::Daemon, pipe));
                    }
                    None => {
                        verses.push(Verse::new(Stanza::new(stanza.clone()), Meter::Daemon, pipe));
                    }
                }

                stanza = Vec::new();
                word.clear();
            }
            Some(meter) if meter == ';' => {
                if !word.is_empty() {
                    stanza.push(word.iter().collect());
                }
                verses.push(Verse::new(Stanza::new(stanza.clone()), Meter::String, pipe));
                stanza = Vec::new();
                word.clear();
            }
            Some(char) if char == ' ' => {
                if !word.is_empty() {
                    stanza.push(word.iter().collect());
                    word.clear();
                }
            }
            Some(char) => {
                word.push(char);
            }
            None => {
                if !word.is_empty() {
                    stanza.push(word.iter().collect());
                }
                if !stanza.is_empty() {
                    verses.push(Verse::new(Stanza::new(stanza.clone()), Meter::None, pipe));
                }
                break;
            }
        }

        prev = match verses.last() {
            Some(verse) => Some(verse),
            None => None,
        };
    }

    Some(Poem::new(verses))
}

/// Refresh the shell's $PATH
///
/// This function caches all valid paths within within the directories
/// specified.
///
/// # Arguments
/// * `paths` - A reference to a vector that holds a list to the shell $PATHs
///
/// # Returns
/// * `bins: Vec<String>` - A new cache of all valid file paths in $PATH
///
/// # Examples
/// ```
/// let paths = vec!["/bin"];
/// let paths = paths.into_iter().map(Path::new).collect();
/// let mut bins = prefresh(&paths);
/// ...
/// // A situation occurs where the $PATH needs to be refreshed
/// bins = prefresh(&paths)
/// ```
fn prefresh(paths: &Vec<&Path>) -> Vec<String> {
    let mut bins: Vec<String> = Vec::new();

    for path in paths {
        let files = fs::read_dir(path).expect(
            format!(
                "dwvsh: error: unable to read the contents of {}",
                path.display().to_string()
            )
            .as_str(),
        );

        for file in files {
            bins.push(file.unwrap().path().display().to_string());
        }
    }

    bins
}

/// Starts the main shell loop
///
/// # Arguments
/// * `paths` - A reference to a vector that holds a list to the shell $PATHs
/// * `prompt` - A string slice indicating the shell's prompt
///
/// # Examples
/// ```
/// fn main() {
///     let paths = vec!["/bin"];
///     let paths = paths.into_iter().map(Path::new).collect();
///     let prompt = "|> ";
///     ...
///     repl(&paths, prompt);
/// }
/// ```
fn repl(paths: &Vec<&Path>, prompt: &str) {
    // Initial path refresh on startup
    let mut bins: Vec<String> = prefresh(paths);

    // Main shell loop
    loop {
        // Output the prompt
        io::stdout().flush().unwrap();
        print!("{}", prompt);
        io::stdout().flush().unwrap();

        // Wait for user input
        let mut poetry = String::new();
        let bytes = io::stdin()
            .read_line(&mut poetry)
            .expect("dwvsh: error: unable to evaluate the input string");

        // Check if we've reached EOF (i.e. <C-d>)
        if bytes == 0 {
            println!("");
            break;
        }

        // Trim the input
        let poetry = String::from(poetry.trim());

        // Skip parsing if there is no poetry
        if !poetry.is_empty() {
            // Parse a poem
            let poem = read(poetry);
            match poem {
                Some(poem) => {
                    // poem.recite(paths, &mut bins, prompt);
                    poem.recite(paths, &mut bins);
                }
                None => {}
            }
        }
    }
}

/// Shell entry
///
/// Shell setup and entry
fn main() {
    // Define paths
    // TODO: Hardcoded path should only be the fallback
    let paths = vec![
        "/bin",
        "/sbin",
        "/usr/bin",
        "/usr/sbin",
        "/usr/local/bin",
        "/usr/local/sbin",
    ];
    let paths = paths.into_iter().map(Path::new).collect();

    // Set the prompt
    let prompt = "|> ";

    // Handle signals
    ctrlc::set_handler(move || {
        print!("\n{}", prompt);
        io::stdout().flush().unwrap();
    })
    .expect("dwvsh: signals: unable to set sigint handler");

    // let poem = read("eza -la".to_string());
    // for line in poem.verses.iter().zip(poem.meters) {
    //     let (verse, meter) = line;
    //     println!("{}: {}", meter, verse);
    // }

    // Begin evaluating commands
    repl(&paths, prompt);
}