From 3ed823485252f62a2ce832262dedfb1e81d32efb Mon Sep 17 00:00:00 2001 From: Jan Klattenhoff Date: Wed, 28 Aug 2024 12:17:44 +0200 Subject: [PATCH] feat: add support for 'cd' command in REPL loop --- src/main.rs | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/src/main.rs b/src/main.rs index d43b637..46a2036 100644 --- a/src/main.rs +++ b/src/main.rs @@ -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; - let mut child = Command::new(command) - .args(args) - .spawn() - .unwrap(); + 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(); + child.wait(); + } + } } } -