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

Give field in struct another valid name when parsing

Open fritzrehde opened this issue 2 years ago • 5 comments

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!

fritzrehde avatar Dec 15 '22 15:12 fritzrehde

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

matthiasbeyer avatar Dec 15 '22 16:12 matthiasbeyer

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 avatar Dec 19 '22 19:12 fritzrehde

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?

fritzrehde avatar Dec 19 '22 19:12 fritzrehde

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!

matthiasbeyer avatar Dec 20 '22 08:12 matthiasbeyer

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

NicholasLYang avatar Jan 18 '23 18:01 NicholasLYang