#env-var #derive #structs #configuration #config-file #modifying #structure

derive_environment

A Rust library for modifying structs via environment variables

3 releases (stable)

1.1.0 Oct 5, 2023
1.0.0 Sep 20, 2023
0.1.0 Sep 19, 2023

#842 in Rust patterns

Download history 9/week @ 2024-02-16 16/week @ 2024-02-23 1/week @ 2024-03-01 1/week @ 2024-03-08 1/week @ 2024-03-15 45/week @ 2024-03-29 11/week @ 2024-04-05

56 downloads per month

GPL-3.0-or-later

18KB
138 lines

A Rust library for modifying structs via environment variables.

Unlike envy, this does not create a new object. It is used to reconfigure an existing structure (after having parsed it from a config file, for example).

Ignored fields

If a certain field should not be configurable via environment variables, mark it with #[env(ignore)].

Examples

Creating a config structure:

use derive_environment::FromEnv;

#[derive(Default, FromEnv)]
pub struct Config {
    // ...
}

// Creates a base configuration struct to add on to.
// Normally this would be created using `serde` from a config file.
let mut config = Config::default();
// Names the struct "MY_CONFIG", which acts as a prefix.
config.with_env("MY_CONFIG").unwrap();

Nesting fields:

use derive_environment::FromEnv;

#[derive(FromEnv)]
struct ServerConfig {
    port: u16,
}

#[derive(FromEnv)]
pub struct Config {
    server: ServerConfig,
}

Generates:

  • MY_CONFIG_SERVER_PORT

Vector of Nested fields:

use derive_environment::FromEnv;

// `Vec`'s `FromEnv` implementation requires `Default`.
#[derive(Default, FromEnv)]
struct ServerConfig {
    port: u16,
}

#[derive(FromEnv)]
pub struct Config {
    servers: Vec<ServerConfig>,
}

Generates:

  • MY_CONFIG_SERVER_0_PORT

Dependencies

~1.2–2.6MB
~64K SLoC