Attribute Macro cli_settings_derive::cli_settings

source ·
#[cli_settings]
Expand description

Description

Use a derive macro with annotations on your Command Line Interface settings struct to manage the settings of your application:

  • create an instance with default values (provided by annotations)
  • read each possible configuration file, if it exists:
    • update the fields that are defined in the configuration file
  • parse the command line arguments, and update the relevant fields with the provided argument

By using annotations, each field can be configurable via the configuration file(s) and/or the command line.

cli-settings-derive can be seen as a top layer above

  • serde for the file configuration parsing
  • clap for the command line parsing

Usage

  • Define your own configuration structure.
  • Add #[cli_settings] annotation to the struct
  • Add #[cli_settings_file = "xxx"] annotation to provide the annotation(s) for file parsing (serde)
  • Add #[cli_settings_clap = "xxx"] annotation to provide the annotation(s) for argument parsing (clap)
  • For each field, also provide annotations (all are optional)
    • #[cli_settings_default = "xxx"] to set the default value.
    • #[cli_settings_file = "xxx"] to indicate that the field shall be read from the config file(s). The passed string if any will be extra annotation(s) to the file parsing struct.
    • #[cli_settings_clap = "xxx"] to indicate that the field shall be a command line argument. The passed string (if any) will be extra annotation(s) to the command line parsing struct.
  • For each field, provide documentation (with ///) to generate the help message via clap.
  • In your application code, call the Settings::build() method with the list of config files to read and the command line arguments to get your application configuration.

User-defined struct

A user-defined struct can be used as a field in the configuration struct. It shall:

  • be annotated with #[derive(Debug, Clone)] for command line argument parsing
  • be annotated with #[derive(Debug, serde_with::DeserializeFromStr)] for config file parsing
  • implement std::str::FromStr, method from_str() to generate an object instance from the argument string

Enumerations

User-defined enumeration

A user-defined enum can be used as a field in the configuration struct. Add the following annotations to the enum declaration:

  • #[derive(clap::ValueEnum, Clone, Debug)] for command line argument parsing
  • #[derive(serde::Deserialize)]#[serde(rename_all = "lowercase")] for config file parsing
External enumeration

An external enum can be used as a field in the configuration struct. As annotations are not possible on this external enum, the solution is to use a custom parsing function:

  • command line argument parsing
    • define the parsing function, with signature fn parse_field(input: &str) -> Result<FieldType, &'static str>
    • annotate the field to use the parsing function as value_parser: #[cli_settings_clap = "#[arg(short, long, value_parser = parse_field)]"]
  • config file parsing: use serde_with with the following annotation #[cli_settings_file = "#[serde_as(as = \"Option<serde_with::DisplayFromStr>\")]"]

An alternate solution is to wrap the external enumeration in a user-defined struct, as described above.

Clap mandatory arguments

Clap mandatory arguments shall get the extra annotation #[cli_settings_mandatory]. The field type shall implement Default or a default value shall be provided with #[cli_settings_default = "xxx"]. This default value will never been used by the application as clap will terminate with error if the argument is not provided, but is needed for the struct instantiation.

Clap subcommands

Clap subcommands are supported as mandatory arguments, as shown in the example from the repository.

Note: set global = true for fields of the first level parameters that apply to all subcommands, so that parameters can be passed before and after the subcommand.

Basic example

use cli_settings_derive::cli_settings;

#[cli_settings]
#[cli_settings_file = "#[serde_with::serde_as]#[derive(serde::Deserialize)]"]
#[cli_settings_clap = "#[derive(clap::Parser)]#[command(version)]"]
pub struct Settings {
    /// alpha setting explanation
    #[cli_settings_file]
    #[cli_settings_clap = "#[arg(long)]"]
    pub alpha: u32,

    /// beta setting explanation, settable only from command line
    #[cli_settings_default = "\"beta default value\".to_string()"]
    #[cli_settings_clap = "#[arg(short, long)]"]
    pub beta: String,

    /// gamma setting explanation, settable only from config file
    #[cli_settings_default = "1 << 63"]
    #[cli_settings_file]
    pub gamma: u64,
}

fn main() {
    // Get the application configuration
    let cfg = Settings::build(
        vec![
            std::path::PathBuf::from("/path/to/system-config.yml"),
            std::path::PathBuf::from("/path/to/user-config.yml"),
        ],
        std::env::args_os(),
    ).unwrap();
}

Complete example

A more complex example is available in the crate repository, with:

  • clap settings to tune the generated help message (-h)
  • field with custom type and user provided function to parse the value from string
  • local enumeration field
  • external enumeration field
  • clap subcommands