Skip to content
Snippets Groups Projects
Verified Commit a69e0252 authored by Eduardo Trujillo's avatar Eduardo Trujillo
Browse files

feat(cli): Add init/init_with_config methods to CLI apps

parent 04d12e20
No related branches found
No related tags found
No related merge requests found
......@@ -7,6 +7,9 @@ use thiserror::Error;
use crate::config;
// Exit codes as defined in sysexits.h.
pub const CONFIGURATION_ERROR_EXIT_CODE: i32 = 78;
#[derive(Error, Debug)]
pub enum CliError {
#[error(transparent)]
......@@ -36,6 +39,18 @@ pub trait AppOpts: Parser {
result
}
fn init() -> Self {
match Self::try_init() {
Ok(args) => args,
Err(CliError::ArgParse(err)) => err.exit(),
Err(CliError::Config(err)) => {
log::error!("{}", err);
safe_exit(CONFIGURATION_ERROR_EXIT_CODE);
},
}
}
fn get_log_level_filter(&self) -> Option<LevelFilter> {
None
}
......@@ -57,6 +72,18 @@ pub trait ConfigurableAppOpts<C: DeserializeOwned + Default + Serialize>: AppOpt
Ok((opts, conf))
}
fn init_with_config() -> (Self, C) {
match Self::try_init_with_config() {
Ok(args_and_config) => args_and_config,
Err(CliError::ArgParse(err)) => err.exit(),
Err(CliError::Config(err)) => {
log::error!("{}", err);
safe_exit(CONFIGURATION_ERROR_EXIT_CODE);
},
}
}
fn get_additional_config_paths(&self) -> Vec<PathBuf>;
}
......@@ -102,3 +129,15 @@ pub fn get_log_level_filter_from_verbosity(verbosity: u8) -> Option<log::LevelFi
_ => None,
}
}
/// Flushes stdout/stderr and terminates the current process.
///
/// This is used internally in the library to handle non-critical CLI errors.
pub fn safe_exit(code: i32) -> ! {
use std::io::Write;
let _ = std::io::stdout().lock().flush();
let _ = std::io::stderr().lock().flush();
std::process::exit(code)
}
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment