config-rs icon indicating copy to clipboard operation
config-rs copied to clipboard

Overwrite a value from toml with env

Open tekjar opened this issue 3 years ago • 1 comments

Hi! I'm trying to overwrite a variable in toml with env variable. Due to restrictions w.r.t underscores, I had to alias a field with serde.

 config::{Config, ConfigError, File, Environment};
use serde::{Serialize,  Deserialize};

#[derive(Debug, Deserialize, Clone)]
pub struct Settings {
    pub name: String,
    pub v4: TlsConfig,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct TlsConfig {
    pub ca_path: String,
    #[serde(alias = "certpath")]
    pub cert_path: String,
    // #[serde(alias = "keypath")]
    pub key_path: String,
}

pub fn main() -> Result<(), ConfigError> {
    std::env::set_var("V4_CERTPATH", "Hello World");

    let s = Config::builder()
        .add_source(File::with_name("default.toml"))
        .add_source(Environment::default().separator("_"))
        .build()?;

    dbg!(&s);
    let v: Settings = s.try_deserialize()?;
    dbg!(v);
    Ok(())
}

This is leading go this error

Error: duplicate field `cert_path`

How do I fix this?

tekjar avatar Aug 23 '22 11:08 tekjar

Interesting! I filed a PR that adds (and hopefully fixes at some point) a test for this in #370

matthiasbeyer avatar Aug 23 '22 11:08 matthiasbeyer

I think I found a reasonable workaround: use "__" (2 '_') as separator. That way the nested struct are appropriately set.

nstinus avatar Sep 19 '23 15:09 nstinus

Okay, I'll close this then. Thanks for reporting back!

matthiasbeyer avatar Sep 20 '23 06:09 matthiasbeyer

Thanks for reporting back!

That wasn't the original reporter btw.

polarathene avatar Oct 20 '23 06:10 polarathene