config-rs
config-rs copied to clipboard
Give field in struct another valid name when parsing
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!
With serde this would be done with field renames. But there are known issues with those in the config-rs crate, unfortunately. :disappointed:
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?
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?
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!
Is there a way to have multiple potential names? Like I want to have userid and user as valid names for the same field.