From 6fe809a2eb8af2c42bca0e30d9ac921147ebeffc Mon Sep 17 00:00:00 2001 From: fdai7451 Date: Sat, 21 Jan 2023 18:51:19 +0100 Subject: [PATCH] refactoring: move error catching match statement to other file --- src/execute.rs | 19 ++++++++++++++++++- src/main.rs | 16 +--------------- 2 files changed, 19 insertions(+), 16 deletions(-) diff --git a/src/execute.rs b/src/execute.rs index d3614db..e641bd2 100644 --- a/src/execute.rs +++ b/src/execute.rs @@ -8,7 +8,24 @@ use crate::error::ShellError; use crate::parse::parse_line; use crate::preprocess::preprocess; -pub fn interpret( +/// This function is not directly in main.rs because it might be called by other function too (eg. +/// when piping commands). +pub fn interpret(line: String, config: &mut BuiltinConfig, ctrlc_recv: Receiver<()>) { + match try_interpret(line, config, ctrlc_recv.clone()) { + Ok(_) | Err(ShellError::Interrupt) | Err(ShellError::EmptyLine) => (), + Err(ShellError::NotFound(cmd)) => { + eprintln!("{}: command not found", cmd.get_program().to_string_lossy()) + } + Err(ShellError::ExecuteFailure(msg)) => { + eprintln!("{}", msg) + } + Err(ShellError::MalformedArgs(args)) => { + eprintln!("Malformed arguments: {}", args) + } + } +} + +pub fn try_interpret( mut line: String, config: &mut BuiltinConfig, ctrlc_recv: Receiver<()>, diff --git a/src/main.rs b/src/main.rs index 8a76ee8..914d7eb 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,7 +6,6 @@ mod preprocess; mod prompt; use crate::builtins::BuiltinConfig; -use crate::error::ShellError; use execute::interpret; use rustyline::config::Configurer; use rustyline::error::ReadlineError; @@ -30,20 +29,7 @@ fn main() -> Result<()> { let readline = rl.readline(&prompt.get_prompt()); match readline { - Ok(line) => match interpret(line, &mut config, ctrlc_recv.clone()) { - Ok(_) => prompt.style = config.prompt_style.clone(), - Err(ShellError::EmptyLine) => continue, - Err(ShellError::NotFound(cmd)) => { - eprintln!("{}: command not found", cmd.get_program().to_string_lossy()) - } - Err(ShellError::ExecuteFailure(msg)) => { - eprintln!("{}", msg) - } - Err(ShellError::MalformedArgs(args)) => { - eprintln!("Malformed arguments: {}", args) - } - Err(ShellError::Interrupt) => continue, - }, + Ok(line) => interpret(line, &mut config, ctrlc_recv.clone()), Err(ReadlineError::Interrupted) => continue, Err(ReadlineError::Eof) => break, Err(err) => {