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.
This commit is contained in:
Markus Pettersson 2023-10-29 15:46:57 +01:00
parent 4fcc2ac31f
commit 50485e7c3a
2 changed files with 5 additions and 9 deletions

View file

@ -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<serde_json::Error> 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"),

View file

@ -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 {