#env-var #yaml-config #variables #config-file #layer #environment #load

configured

Utility to load configuration from well defined layers into any type which can be deserialized by Serde

8 releases (5 breaking)

0.7.1 Nov 5, 2023
0.7.0 Nov 5, 2023
0.6.2 Oct 19, 2023
0.5.0 Oct 12, 2022
0.2.0 Jun 8, 2022

#1963 in Parser implementations

Download history 189/week @ 2024-07-21 197/week @ 2024-07-28 106/week @ 2024-08-04 171/week @ 2024-08-11 137/week @ 2024-08-18 90/week @ 2024-08-25 83/week @ 2024-09-01 122/week @ 2024-09-08 117/week @ 2024-09-15 129/week @ 2024-09-22 101/week @ 2024-09-29 107/week @ 2024-10-06 128/week @ 2024-10-13 213/week @ 2024-10-20 108/week @ 2024-10-27 149/week @ 2024-11-03

608 downloads per month

Custom license

11KB
99 lines

Configured

Crates.io license build

Opinionated utility to load a configuration from well defined layers into any type which can be deserialized by Serde using kebab-case.

First, values from the mandatory default configuration file at <CONFIG_DIR>/default.yaml are loaded.

Then, if the environment variable CONFIG_OVERLAYS is defined, its comma separated overlays (e.g. "prod" or "feat, dev") at <CONFIG_DIR>/<overlay>.yaml are loaded from left to right as overlays, i.e. adding or overwriting already existing values.

Finally environment variables prefixed with <CONFIG_ENV_PREFIX>__ and segments separated by __ (double underscores are used as segment separators to allow for single underscores in segment names) are used as final overlay.

Example

#[derive(Debug, Deserialize)]
#[serde(rename_all = "kebab-case")]
struct Config {
    foo: Foo,
    qux: Qux,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "kebab-case")]
struct Foo {
    bar: String,
    baz: String,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "kebab-case")]
struct Qux {
    quux: String,
    corge_grault: String,
}

#[test]
fn test_load() -> Result<(), Error> {
    env::set_var(CONFIG_DIR, "test-config");
    env::set_var(CONFIG_OVERLAYS, "feat, dev");
    env::set_var("APP__QUX__CORGE_GRAULT", "corge-grault-env");

    let config = Config::load()?;

    assert_eq!(config.foo.bar.as_str(), "bar");
    assert_eq!(config.foo.baz.as_str(), "baz-dev");
    assert_eq!(config.qux.quux.as_str(), "quux-feat");
    assert_eq!(config.qux.corge_grault.as_str(), "corge-grault-env");

    Ok(())
}

Attribution

This utility is built on top of the fantastic Config library.

License

This code is open source software licensed under the Apache 2.0 License.

Dependencies

~2–2.9MB
~61K SLoC