Skip to main content

endpoint_libs/libs/
config.rs

1use clap::Parser;
2use eyre::*;
3use serde::de::DeserializeOwned;
4use serde_json::Value;
5use std::fmt::Debug;
6use std::path::PathBuf;
7
8#[derive(Parser)]
9#[clap(author, version, about, long_about = None)]
10struct CliArgument {
11    /// The path to config file
12    #[arg(
13        short,
14        long,
15        value_name = "FILE",
16        default_value = "etc/config.json",
17        env = "CONFIG"
18    )]
19    config: PathBuf,
20    /// The path to config file
21    #[clap(long)]
22    config_entry: Option<String>,
23}
24
25pub fn load_config<Config: DeserializeOwned + Debug>(mut service_name: String) -> Result<Config> {
26    let args: CliArgument = CliArgument::parse();
27
28    let config = std::fs::read_to_string(&args.config)?;
29    let mut config: Value = serde_json::from_str(&config)?;
30    if let Some(entry) = args.config_entry {
31        service_name = entry;
32    }
33    let service_config = config
34        .get_mut(&service_name)
35        .ok_or_else(|| eyre!("Service {} not found in config", service_name))?
36        .clone();
37    let root = config.as_object_mut().unwrap();
38    for (k, v) in service_config.as_object().unwrap() {
39        root.insert(k.clone(), v.clone());
40    }
41    root.remove(&service_name);
42    root.insert("name".to_string(), Value::String(service_name.clone()));
43    let config: Config = serde_json::from_value(config)?;
44    println!("App config {config:#?}");
45    Ok(config)
46}