From ba58935c953811f877ad4d4f4895cc10d67d9e06 Mon Sep 17 00:00:00 2001 From: fdai7381 Date: Tue, 17 Jan 2023 20:15:32 +0100 Subject: [PATCH] feat: rework command execution --- src/execute.rs | 41 ++++++++++++++++++++--------------------- src/main.rs | 10 ++++++---- 2 files changed, 26 insertions(+), 25 deletions(-) diff --git a/src/execute.rs b/src/execute.rs index 43bd632..bfce3d2 100644 --- a/src/execute.rs +++ b/src/execute.rs @@ -1,29 +1,28 @@ -use std::{ - io::{self}, - process::{ChildStdout, Command, Stdio}, -}; +use std::process::Command; +use crate::error::ShellError; +use crate::error::ShellError::Execute; use crate::parse::parse_line; -pub fn execute>(mut command: Command, stdin: S) -> io::Result<(ChildStdout, Stdio)> { - command.stdin(stdin); - command.stdout(Stdio::piped()); - - let handle = command.spawn()?; - - let stdout = handle.stdout.unwrap(); - let stderr = match handle.stderr { - Some(err) => Stdio::from(err), - None => Stdio::null(), - }; - Ok((stdout, stderr)) -} - -pub fn interpret(line: &str) -> io::Result<()> { +pub fn interpret(line: &str) -> Result<(), ShellError> { let (keyword, args) = parse_line(line); + let mut command = Command::new(keyword); command.args(args); - let (mut stdout, _) = execute(command, Stdio::null())?; - io::copy(&mut stdout, &mut io::stdout())?; + + execute(command)?; + Ok(()) } + +fn execute(mut command: Command) -> Result<(), ShellError> { + match command.spawn() { + Ok(mut child) => { + if let Err(err) = child.wait() { + return Err(Execute(err.to_string())); + } + Ok(()) + } + Err(err) => Err(Execute(err.to_string())), + } +} diff --git a/src/main.rs b/src/main.rs index bff60ff..a8ebe92 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,6 +3,7 @@ mod execute; mod parse; mod prompt; +use crate::error::ShellError; use execute::interpret; use rustyline::error::ReadlineError; use rustyline::{Editor, Result}; @@ -18,11 +19,12 @@ fn main() -> Result<()> { let readline = rl.readline(&prompt.get_prompt()); match readline { - Ok(line) => { - if let Err(err) = interpret(&line) { - println!("{}", err); + Ok(line) => match interpret(&line) { + Ok(_) => {} + Err(ShellError::Execute(err)) => { + eprintln!("{}", err) } - } + }, Err(ReadlineError::Interrupted) => { break; }