kutil_cli/run/
run.rs

1use super::exit::*;
2
3use {
4    anstream::eprintln,
5    owo_colors::OwoColorize,
6    std::{fmt, process::*},
7};
8
9//
10// Runner
11//
12
13/// A replacement for `main`.
14pub type Runner<ErrorT> = fn() -> Result<(), ErrorT>;
15
16/// Runs a [Runner], handling a returned [Exit].
17///
18/// If the exit has a goodbye message, it will be printed to stderr. If
19/// the exit code is an error (non-zero) it will be in red.
20///
21/// Non-exit errors will be displayed in red.
22///
23/// Designed to be the only content for your `main` function. The
24/// good stuff should go into your [Runner].
25pub fn run<ErrorT>(run: Runner<ErrorT>) -> ExitCode
26where
27    ErrorT: HasExit + fmt::Display,
28{
29    match run() {
30        Ok(_) => ExitCode::SUCCESS,
31
32        Err(error) => match error.get_exit() {
33            Some(exit) => {
34                if let Some(message) = &exit.message {
35                    if exit.code == 0 {
36                        eprintln!("{}", message);
37                    } else {
38                        eprintln!("{}", message.red());
39                    }
40                }
41                ExitCode::from(exit.code)
42            }
43
44            _ => {
45                eprintln!("{}", error.red());
46                ExitCode::FAILURE
47            }
48        },
49    }
50}