Skip to main content

Crate clap_layers

Crate clap_layers 

Source
Expand description

Correct layered configuration for clap.

One derive macro gives a clap application layered configuration with the precedence users actually expect:

PriorityLayerExample
1Explicit CLI flag--port 8080
2Environment varMYAPP_PORT=8080
3Config fileport = 8080 in myapp.toml
4Built-in default#[arg(default_value_t = 3000)]

The subtle part — and the reason this crate exists — is layer 1 versus layer 4. A config-file value must override a clap default, but must lose to a flag the user explicitly typed, even when the typed value happens to equal the default. clap-layers gets this right by reading clap’s ValueSource rather than by wrapping every field in Option<T>, so --help keeps showing real defaults.

§Example

use clap::Parser;
use clap_layers::{Env, Layered};

#[derive(Parser, Layered, Debug)]
#[layered(file = "myapp.toml", env_prefix = "MYAPP")]
struct Config {
    /// Port to listen on
    #[arg(long, default_value_t = 3000)]
    port: u16,
}

// `Config::layered()` reads the real process arguments and environment.
// `layered_from` is the same engine with both injected, which is what makes
// configuration testable:
let env = Env::from_iter([("MYAPP_PORT", "8080")]);

// No flag typed: the environment wins over the default.
let cfg = Config::layered_from(["myapp"], &env)?;
assert_eq!(cfg.port, 8080);

// Flag explicitly typed: it beats the environment.
let cfg = Config::layered_from(["myapp", "--port", "9999"], &env)?;
assert_eq!(cfg.port, 9999);

// Even when the typed value *equals* the default, it is still explicit.
let cfg = Config::layered_from(["myapp", "--port", "3000"], &env)?;
assert_eq!(cfg.port, 3000);

§Reporting errors

LayeredError carries its message in its Display form. Rust prints the Debug form for a Result returned from main, so let cfg = Config::layered()? in main reports Invalid { field: "port", .. } rather than the attributed message. Print it yourself instead:

let cfg = Config::layered().unwrap_or_else(|e| {
    eprintln!("configuration error: {e}");
    std::process::exit(1);
});
configuration error: invalid value 'banana' for 'port' — from environment variable MYAPP_PORT (invalid type: string, expected u16)

§Field types

Values from the environment and config file are decoded with serde, so any field type implementing serde::Deserialize works — including u16, bool, String, Vec<T>, Option<T>, and #[derive(Deserialize)] enums. No FromStr bound is required.

§Per-field control

  • #[layered(no_env)] — never read this field from the environment.
  • #[layered(no_file)] — never read this field from the config file.
  • #[layered(no_cli)] — never expose this field as a CLI flag. Requires #[arg(skip)] so clap leaves the field alone; the macro enforces this.

§Environment variables

The environment layer is only active when env_prefix is set. Without a prefix, a field named path would read the ambient PATH, so clap-layers disables the layer rather than guess. Names are PREFIX_FIELD uppercased: env_prefix = "MYAPP" maps field db_password to MYAPP_DB_PASSWORD.

Re-exports§

pub use clap;

Structs§

Env
A snapshot of environment variables for the environment layer.

Enums§

LayeredError
Errors produced while loading layered configuration.
SourceLayer
Which layer supplied a configuration value.

Traits§

Layered
Load a struct from all configuration layers.

Derive Macros§

Layered
Derive the Layered trait, giving a clap struct layered configuration.