feat: add support for 'cd' command in REPL loop

This commit is contained in:
Jan Gleytenhoover 2024-08-28 12:17:44 +02:00
parent f73c10d6eb
commit 3ed8234852
Signed by: jank
GPG Key ID: B267751B8AE29EFE

@ -1,9 +1,7 @@
use std::{io::{stdin, stdout, Write}, process::Command};
use std::{env, io::{stdin, stdout, Write}, path::Path, process::Command};
fn main(){
loop {
// use the `>` character as the prompt
// need to explicitly flush this to ensure it prints before read_line
print!("> ");
stdout().flush();
@ -14,13 +12,23 @@ fn main(){
let command = parts.next().unwrap();
let args = parts;
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);
}
},
command => {
let mut child = Command::new(command)
.args(args)
.spawn()
.unwrap();
// don't accept another command until this one completes
child.wait();
}
}
}
}