Browse Source

refactoring: add interpret function

main
fdai7375 2 years ago
parent
commit
e9c594ebc2
  1. 29
      src/execute.rs
  2. 8
      src/main.rs

29
src/execute.rs

@ -1,12 +1,29 @@
use std::{
io,
process::{Command, Stdio},
io::{self},
process::{ChildStdout, Command, Stdio},
};
pub fn execute(command: &str, args: &[&str]) -> io::Result<()> {
let mut command = Command::new(command);
command.stdout(Stdio::piped()).args(args);
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()?;
io::copy(&mut handle.stdout.unwrap(), &mut io::stdout())?;
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<()> {
let (command, args) = parse_line(line);
let mut command = Command::new(command);
command.args(args);
let (mut stdout, _) = execute(command, Stdio::null())?;
io::copy(&mut stdout, &mut io::stdout())?;
Ok(())
}

8
src/main.rs

@ -2,8 +2,7 @@ mod execute;
mod parse;
mod prompt;
use execute::execute;
use parse::parse_line;
use execute::interpret;
use rustyline::error::ReadlineError;
use rustyline::{Editor, Result};
@ -19,8 +18,9 @@ fn main() -> Result<()> {
match readline {
Ok(line) => {
let (command, args) = parse_line(&line);
execute(command, &args)?;
if let Err(err) = interpret(&line) {
println!("{}", err);
}
}
Err(ReadlineError::Interrupted) => {
println!("CTRL-C");

Loading…
Cancel
Save