mehcode / config-rs

⚙️ Layered configuration system for Rust applications (with strong support for 12-factor applications).
Apache License 2.0
2.43k stars 206 forks source link

Give field in struct another valid name when parsing #405

Open fritzrehde opened 1 year ago

fritzrehde commented 1 year ago

I want to use this crate to parse a toml config file. This is part of my current code:

#[derive(Deserialize)]
pub struct ConfigRawFile {
    command: Option<String>,
    interval: Option<f64>,
    fg: Option<String>,
    bg: Option<String>,
    fg_cursor: Option<String>,
    bg_cursor: Option<String>,
    bg_selected: Option<String>,
    bold: Option<bool>,
    bold_cursor: Option<bool>,
    keybindings: Option<KeybindingsRaw>,
}

fn parse_toml(config_file: &str) -> Result<ConfigRawFile, config::ConfigError> {
    config::Config::builder()
        .add_source(config::File::with_name(config_file))
        .build()?
        .try_deserialize()
}

However, I want to give e.g. bg_cursor a different name that should be read from in the toml file. I would like the toml file to specify "bg+" (which I can't use as a variable name in rust due to the +), and then read that into bg_cursor. Is there an annotation I can use for this (similar to #[arg(long = "bg+", value_name = "COLOR")] in clap)? This would be very useful! Thanks!

matthiasbeyer commented 1 year ago

With serde this would be done with field renames. But there are known issues with those in the config-rs crate, unfortunately. :disappointed:

fritzrehde commented 1 year ago

Usually I could just use #[serde(rename(deserialize = "bg-"))] on the field I have to rename, right? Are there plans to make this work with config-rs? Why does this serde feature not work in config-rs?

fritzrehde commented 1 year ago

I just tried doing what I said in my last comment and it worked just the way I described using config-rs. I am guessing this is because I am parsing toml, so it probably uses the toml crate, which has support for this? Does it work for some parsed languages but not for others?

matthiasbeyer commented 1 year ago

I just tried doing what I said in my last comment and it worked just the way I described using config-rs. I

Nice! There was something in the back of my head about issues this crate has with renames... maybe I was wrong!

NicholasLYang commented 1 year ago

Is there a way to have multiple potential names? Like I want to have userid and user as valid names for the same field.