Browse Source

feat: rework command execution

main
fdai7381 2 years ago
committed by fdai7451
parent
commit
9ce1beb1db
  1. 39
      src/execute.rs
  2. 10
      src/main.rs

39
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());
pub fn interpret(line: &str) -> Result<(), ShellError> {
let (keyword, args) = parse_line(line);
let mut command = Command::new(keyword);
command.args(args);
let handle = command.spawn()?;
execute(command)?;
let stdout = handle.stdout.unwrap();
let stderr = match handle.stderr {
Some(err) => Stdio::from(err),
None => Stdio::null(),
};
Ok((stdout, stderr))
Ok(())
} }
pub fn interpret(line: &str) -> io::Result<()> {
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())?;
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(()) 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