use clap::Parser;
use serde::de::DeserializeOwned;
use std::fmt::Debug;
#[derive(Parser)]
#[command(name = env!("CARGO_PKG_NAME"))]
#[command(about = "A webserver built with restrepo", long_about = None)]
pub struct ApplicationParameters {
#[clap(
default_value_t = String::from("[::]:8000"),
short,
help = "Specify address for server to listen on."
)]
pub address: String,
#[clap(
short,
help = "Sets log level to debug. WARNING: Might leak sensitive information."
)]
pub debug: bool,
#[clap(
short,
help = "Collect settings from environment variables prefixed by <ENV_PREFIX>."
)]
pub env_prefix: Option<String>,
#[clap(
short,
help = "Collect settings from application configuration file at this path."
)]
pub config_path: Option<String>,
}
impl ApplicationParameters {
pub fn load_app_config<T: DeserializeOwned>(&self) -> anyhow::Result<T> {
let mut cfgbuilder = config::Config::builder();
if let Some(path) = &self.config_path
&& std::fs::metadata(path).is_ok()
{
cfgbuilder = cfgbuilder.add_source(config::File::with_name(path));
}
if let Some(prefix) = &self.env_prefix {
cfgbuilder = cfgbuilder
.add_source(config::Environment::with_prefix(prefix).prefix_separator("_"));
}
let cfg = cfgbuilder.build()?;
Ok(cfg.try_deserialize::<T>()?)
}
}
pub fn handle_application_startup_error<T: ToString + Debug + Send + Sync + 'static>(
e: T,
) -> std::io::Error {
std::io::Error::other(e.to_string())
}