Clap and Serde derive

With the [clap_serde] procedural macro both clap and serde can be derived from a struct.
Then the struct can be parsed from clap and serde sources as in a layered config: the last
source has the precedence.
Args::from(serde_parsed)
.merge_clap();
In the snippet the precedence is:
- Command line from clap;
- Config file from serde;
- Default values.
Example
In this example we define a struct which derives both clap and serde.
The struct has various parameter type and also various attributes on its fields.
Finally we parse the structure from a YAML file with serde and then from command line with
clap. The arguments from clap will override those from serde; the default value will be used if
no source contained the field.
use clap_serde_derive::{
clap::{self, ArgAction},
clap_serde, ClapSerde,
};
#[clap_serde]
#[derive(Debug)]
#[clap(author, version, about)]
pub struct Args {
pub input: Vec<std::path::PathBuf>,
#[clap(short, long)]
name: String,
#[default(13)]
#[serde(skip_deserializing)]
#[clap(long = "num")]
pub clap_num: u32,
#[serde(rename = "number")]
#[clap(skip)]
pub serde_num: u32,
#[clap_serde]
#[clap(flatten)]
pub suboptions: SubConfig,
}
#[clap_serde]
#[derive(Debug)]
pub struct SubConfig {
#[default(true)]
#[clap(long = "no-flag", action = ArgAction::SetFalse)]
pub flag: bool,
}
let args = Args::from(serde_yaml::from_str::<<Args as ClapSerde>::Opt>("number: 12").unwrap())
.merge_clap();
assert_eq!(
serde_yaml::to_string(&args).unwrap(),
serde_yaml::to_string(&Args {
serde_num: 12,
clap_num: 13,
..Args::default()
})
.unwrap(),
);
Config path from command line
You can easily take the config file path from command line in this way.
use std::{fs::File, io::BufReader};
use clap_serde_derive::{
clap::{self, ArgAction, Parser},
clap_serde, ClapSerde,
};
#[derive(Parser)]
#[clap(author, version, about)]
struct Args {
input: Vec<std::path::PathBuf>,
#[clap(short, long = "config", default_value = "config.yml")]
config_path: std::path::PathBuf,
#[clap(flatten)]
pub config: <Config as ClapSerde>::Opt,
}
#[clap_serde]
struct Config {
#[clap(short, long)]
name: String,
}
let mut args = Args::parse();
let config = if let Ok(f) = File::open(&args.config_path) {
match serde_yaml::from_reader::<_, <Config as ClapSerde>::Opt>(BufReader::new(f)) {
Ok(config) => Config::from(config).merge(&mut args.config),
Err(err) => panic!("Error in configuration file:\n{}", err),
}
} else {
Config::from(&mut args.config)
};