Skip to content

Instantly share code, notes, and snippets.

@OwenChia
Created November 18, 2018 10:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OwenChia/0851230a419d07a08e9664048c0dac01 to your computer and use it in GitHub Desktop.
Save OwenChia/0851230a419d07a08e9664048c0dac01 to your computer and use it in GitHub Desktop.
shell
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