Browse Source

feat: rework command execution

main
fdai7381 2 years ago
parent
commit
ba58935c95
  1. 41
      src/execute.rs
  2. 10
      src/main.rs

41
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; use crate::parse::parse_line;
pub fn execute<S: Into<Stdio>>(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 (keyword, args) = parse_line(line);
let mut command = Command::new(keyword); let mut command = Command::new(keyword);
command.args(args); command.args(args);
let (mut stdout, _) = execute(command, Stdio::null())?;
io::copy(&mut stdout, &mut io::stdout())?;
execute(command)?;
Ok(()) 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())),
}
}

10
src/main.rs

@ -3,6 +3,7 @@ mod execute;
mod parse; mod parse;
mod prompt; mod prompt;
use crate::error::ShellError;
use execute::interpret; use execute::interpret;
use rustyline::error::ReadlineError; use rustyline::error::ReadlineError;
use rustyline::{Editor, Result}; use rustyline::{Editor, Result};
@ -18,11 +19,12 @@ fn main() -> Result<()> {
let readline = rl.readline(&prompt.get_prompt()); let readline = rl.readline(&prompt.get_prompt());
match readline { 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) => { Err(ReadlineError::Interrupted) => {
break; break;
} }

Loading…
Cancel
Save