cli: extract function for top-level error reporting

This will also be reused by custom commands.
This commit is contained in:
Martin von Zweigbergk 2022-09-22 00:12:52 -07:00 committed by Martin von Zweigbergk
parent a7f19b85f8
commit a0dfd4a4a8
2 changed files with 25 additions and 17 deletions

View file

@ -1242,3 +1242,24 @@ pub fn parse_args<'help>(
let command_helper = CommandHelper::new(app, string_args, args.global_args); let command_helper = CommandHelper::new(app, string_args, args.global_args);
Ok((command_helper, matches)) 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
}
}
}

View file

@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // 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::commands::{default_app, run_command};
use jujutsu::config::read_config; use jujutsu::config::read_config;
use jujutsu::ui::Ui; use jujutsu::ui::Ui;
@ -32,24 +32,11 @@ fn main() {
Ok(user_settings) => { Ok(user_settings) => {
let mut ui = Ui::for_terminal(user_settings); let mut ui = Ui::for_terminal(user_settings);
match run(&mut ui) { match run(&mut ui) {
Ok(_) => { Ok(()) => {
std::process::exit(0); std::process::exit(0);
} }
Err(CommandError::UserError(message)) => { Err(err) => {
ui.write_error(&format!("Error: {}\n", message)).unwrap(); std::process::exit(report_command_error(&mut ui, err));
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);
} }
} }
} }