From 50485e7c3a691c38b90a46f9cff422722f22b73d Mon Sep 17 00:00:00 2001 From: Markus Pettersson Date: Sun, 29 Oct 2023 15:46:57 +0100 Subject: [PATCH] Return result of `Command::execute` directly from `main` Since `Result` implements `Termination` (https://doc.rust-lang.org/std/process/trait.Termination.html), the result of `Command::execute` can be returned from `main` directly. If an `FF2MpvError` error would be propagated to `main`, it will be printed using `eprintln` just as before, and the program will terminate with an appropriate exit code: https://doc.rust-lang.org/std/process/struct.ExitCode.html#associatedconstant.FAILURE The only caveat is that `FF2MpvError` has to implement `Debug`, but instead of deriving it I cheated a bit and re-used the existing `Display` implementation to preserve the format of the error messages. --- src/error.rs | 4 ++-- src/main.rs | 10 +++------- 2 files changed, 5 insertions(+), 9 deletions(-) diff --git a/src/error.rs b/src/error.rs index d39c5fa..48bbe38 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,6 +1,6 @@ use std::io; use std::fmt; -use std::fmt::Display; +use std::fmt::Debug; pub enum FF2MpvError { NoConfig, @@ -20,7 +20,7 @@ impl From for FF2MpvError { } } -impl Display for FF2MpvError { +impl Debug for FF2MpvError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::NoConfig => write!(f, "Config doesn't exist"), diff --git a/src/main.rs b/src/main.rs index 1fbc2a9..5517014 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,18 +1,14 @@ use std::env; -use std::process; -use ff2mpv_rust::command::Command; +use ff2mpv_rust::{command::Command, error::FF2MpvError}; -fn main() { +fn main() -> Result<(), FF2MpvError> { let mut args = env::args(); args.next(); // Skip binary path let command_name = args.next().unwrap_or_default(); let command = get_command(&command_name); - if let Err(e) = command.execute() { - eprintln!("{e}"); - process::exit(-1); - } + command.execute() } fn get_command(name: &str) -> Command { -- 2.39.2