From 94de64080a48c4ad5cfff4ed059e475ab7a8e284 Mon Sep 17 00:00:00 2001 From: fdai7375 Date: Tue, 17 Jan 2023 09:09:55 +0100 Subject: [PATCH] feat: add command execution --- src/execute.rs | 12 ++++++++++++ src/main.rs | 7 ++++--- src/parse.rs | 21 ++++----------------- 3 files changed, 20 insertions(+), 20 deletions(-) create mode 100644 src/execute.rs diff --git a/src/execute.rs b/src/execute.rs new file mode 100644 index 0000000..e361677 --- /dev/null +++ b/src/execute.rs @@ -0,0 +1,12 @@ +use std::{ + io, + process::{Command, Stdio}, +}; + +pub fn execute(command: &str, args: &[&str]) -> io::Result<()> { + let mut command = Command::new(command); + command.stdout(Stdio::piped()).args(args); + let handle = command.spawn()?; + io::copy(&mut handle.stdout.unwrap(), &mut io::stdout())?; + Ok(()) +} diff --git a/src/main.rs b/src/main.rs index 8fb89de..f499e02 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,8 @@ +mod execute; mod parse; mod prompt; +use execute::execute; use parse::parse_line; use rustyline::error::ReadlineError; use rustyline::{Editor, Result}; @@ -17,9 +19,8 @@ fn main() -> Result<()> { match readline { Ok(line) => { - if let Err(e) = parse_line(&line) { - println!("{}", e) - } + let (command, args) = parse_line(&line); + execute(command, &args)?; } Err(ReadlineError::Interrupted) => { println!("CTRL-C"); diff --git a/src/parse.rs b/src/parse.rs index b973d43..cda4f05 100644 --- a/src/parse.rs +++ b/src/parse.rs @@ -1,22 +1,9 @@ -use std::{ - io::{self, Write}, - process::Command, -}; - -pub fn parse_line(line: &str) -> io::Result<()> { +pub fn parse_line(line: &str) -> (&str, Vec<&str>) { let tokens = line.trim().split(' ').collect::>(); - let mut args: &[&str] = &[]; + let mut args: Vec<&str> = Vec::new(); let command = tokens[0]; if tokens.len() > 1 { - args = &tokens[1..]; + args = tokens[1..].to_vec(); } - let mut command = Command::new(command); - - command.args(args); - - let output = command.output()?; - - io::stderr().write_all(&output.stderr)?; - io::stdout().write_all(&output.stdout)?; - Ok(()) + (command, args) }