feat: implement command piping in shell program
All checks were successful
Release / Release (push) Successful in 37s

This commit is contained in:
Jan Gleytenhoover 2024-08-28 12:31:16 +02:00
parent 3ed8234852
commit 797f401cf3
Signed by: jank
GPG Key ID: B267751B8AE29EFE

@ -1,4 +1,4 @@
use std::{env, io::{stdin, stdout, Write}, path::Path, process::Command};
use std::{env, io::{stdin, stdout, Write}, path::Path, process::{Child, Command, Stdio}};
fn main(){
loop {
@ -8,27 +8,66 @@ fn main(){
let mut input = String::new();
stdin().read_line(&mut input).unwrap();
let mut parts = input.trim().split_whitespace();
let command = parts.next().unwrap();
let args = parts;
// must be peekable so we know when we are on the last command
let mut commands = input.trim().split(" | ").peekable();
let mut previous_command = None;
match command {
"cd" => {
// default to '/' as new directory if one was not provided
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);
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);
}
previous_command = None;
},
"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() {
// there is another command piped behind this one
// prepare to send output to the next command
Stdio::piped()
} else {
// there are no more commands piped behind this one
// send output to shell stdout
Stdio::inherit()
};
let output = Command::new(command)
.args(args)
.stdin(stdin)
.stdout(stdout)
.spawn();
match output {
Ok(output) => { previous_command = Some(output); },
Err(e) => {
previous_command = None;
eprintln!("{}", e);
},
};
}
},
command => {
let mut child = Command::new(command)
.args(args)
.spawn()
.unwrap();
child.wait();
}
}
if let Some(mut final_command) = previous_command {
// block until the final command has finished
final_command.wait();
}
}
}