From a0dfd4a4a851127ed3ad8737ab29dd34965ae4d2 Mon Sep 17 00:00:00 2001 From: Martin von Zweigbergk Date: Thu, 22 Sep 2022 00:12:52 -0700 Subject: [PATCH] cli: extract function for top-level error reporting This will also be reused by custom commands. --- src/cli_util.rs | 21 +++++++++++++++++++++ src/main.rs | 21 ++++----------------- 2 files changed, 25 insertions(+), 17 deletions(-) diff --git a/src/cli_util.rs b/src/cli_util.rs index 6e59cc01b..a6676c6a1 100644 --- a/src/cli_util.rs +++ b/src/cli_util.rs @@ -1242,3 +1242,24 @@ pub fn parse_args<'help>( let command_helper = CommandHelper::new(app, string_args, args.global_args); Ok((command_helper, matches)) } + +// TODO: Return std::process::ExitCode instead, once our MSRV is >= 1.61 +#[must_use] +pub fn report_command_error(ui: &mut Ui, err: CommandError) -> i32 { + match err { + CommandError::UserError(message) => { + ui.write_error(&format!("Error: {}\n", message)).unwrap(); + 1 + } + CommandError::CliError(message) => { + ui.write_error(&format!("Error: {}\n", message)).unwrap(); + 2 + } + CommandError::BrokenPipe => std::process::exit(3), + CommandError::InternalError(message) => { + ui.write_error(&format!("Internal error: {}\n", message)) + .unwrap(); + 255 + } + } +} diff --git a/src/main.rs b/src/main.rs index cf2d76c32..058aa4655 100644 --- a/src/main.rs +++ b/src/main.rs @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use jujutsu::cli_util::{parse_args, CommandError}; +use jujutsu::cli_util::{parse_args, report_command_error, CommandError}; use jujutsu::commands::{default_app, run_command}; use jujutsu::config::read_config; use jujutsu::ui::Ui; @@ -32,24 +32,11 @@ fn main() { Ok(user_settings) => { let mut ui = Ui::for_terminal(user_settings); match run(&mut ui) { - Ok(_) => { + Ok(()) => { std::process::exit(0); } - Err(CommandError::UserError(message)) => { - ui.write_error(&format!("Error: {}\n", message)).unwrap(); - std::process::exit(1); - } - Err(CommandError::CliError(message)) => { - ui.write_error(&format!("Error: {}\n", message)).unwrap(); - std::process::exit(2); - } - Err(CommandError::BrokenPipe) => { - std::process::exit(3); - } - Err(CommandError::InternalError(message)) => { - ui.write_error(&format!("Internal error: {}\n", message)) - .unwrap(); - std::process::exit(255); + Err(err) => { + std::process::exit(report_command_error(&mut ui, err)); } } }