Created
November 18, 2018 10:04
-
-
Save OwenChia/0851230a419d07a08e9664048c0dac01 to your computer and use it in GitHub Desktop.
shell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::env; | |
use std::io::{self, Write}; | |
use std::path::Path; | |
use std::process::{Command, Stdio, Child}; | |
fn main() { | |
loop { | |
print!("> "); | |
io::stdout().flush().unwrap(); | |
let mut input = String::new(); | |
io::stdin().read_line(&mut input).unwrap(); | |
if input == "" { | |
println!("exit"); | |
return; | |
} else if input.trim() == "" { | |
continue; | |
} | |
let mut commands = input.trim().split(" | ").peekable(); | |
let mut previous_command = None; | |
while let Some(command) = commands.next() { | |
let mut parts = command.trim().split_whitespace(); | |
let command = parts.next().unwrap(); | |
let args = parts; | |
match command { | |
"cd" => { | |
let new_dir = args.peekable().peek().map_or("/", |x| *x); | |
let root = Path::new(new_dir); | |
if let Err(e) = env::set_current_dir(&root) { | |
eprintln!("{}", e); | |
} | |
}, | |
"exit" => return, | |
command => { | |
let stdin = previous_command | |
.map_or( | |
Stdio::inherit(), | |
|output: Child| Stdio::from(output.stdout.unwrap()) | |
); | |
let stdout = if commands.peek().is_some() { | |
Stdio::piped() | |
} else { | |
Stdio::inherit() | |
}; | |
let output = Command::new(command) | |
.args(args) | |
.stdin(stdin) | |
.stdout(stdout) | |
.spawn(); | |
match output { | |
Ok(mut output) => { previous_command = Some(output); }, | |
Err(e) => { | |
previous_command = None; | |
eprintln!("{}", e); | |
}, | |
}; | |
} | |
} | |
} | |
if let Some(mut final_command) = previous_command { | |
final_command.wait().unwrap(); | |
} | |
} | |
} | |
// vim: set fdm=syntax fdl=2 : |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment