Configuration

RecipeCratesCategories
configconfigcat-config
confyconfycat-config

config

config config-crates.io config-github config-lib.rs cat-config

config⮳ is a layered configuration repository. It maintains a set of configuration sources, fetches values to populate those, and provides them according to the source's priority.

Config lets you set a set of default parameters and then extend them via merging in configuration from a variety of sources:

  • Files in JSON, TOML, YAML, INI, RON, JSON5; and
  • Environment variables.
  • String literals in well-known formats.
  • Programmatic overrides.
// // COMING SOON

// Testing configurations
#[test]
fn test_config() -> anyhow::Result<(), config::ConfigError> {
    use std::collections::HashMap;

    // The `Environment::source` method can be used when you want to test
    // your code, without the need to change the actual system
    // environment variables.
    let source = config::Environment::default().source(Some({
        let mut env = HashMap::new();
        env.insert("HOST".into(), "1.1.1.1".into());
        env
    }));

    let config = config::Config::builder()
        .add_source(source)
        .build()?
        .try_deserialize::<HashMap<String, String>>()?;

    assert_eq!(config.get("host"), Some(&"1.1.1.1".to_string()));

    Ok(())
}
fn config() -> &'static config::Config {
    // Get or initialize the configuration.
    // (`OnceLock` can be written to only once).
    static CONFIG: std::sync::OnceLock<config::Config> =
        std::sync::OnceLock::new();
    CONFIG.get_or_init(|| {
        config::Config::builder()
            .add_source(config::Environment::with_prefix("APP"))
            .build()
            .unwrap()
    })
}

/// Get a configuration value from the static configuration object
fn get<'a, T: serde::Deserialize<'a>>(
    key: &str,
) -> Result<T, config::ConfigError> {
    config().get::<T>(key)
}

fn main() -> anyhow::Result<()> {
    // Prep: set the environment variable
    unsafe {
        std::env::set_var("APP_PORT", "8080");
    }
    println!("{:?}", get::<String>("port")?);
    unsafe {
        std::env::remove_var("APP_Port");
    }
    Ok(())
}
// Adapted from https://github.com/rust-cli/config-rs/blob/main/examples/static_env.rs

confy

confy confy-crates.io confy-github confy-lib.rs

confy is a Rust crate that simplifies reading and writing TOML or YAML configuration files. It uses serde for easy serialization/deserialization of config structs, handles file I/O, and supports defaults and environment variable overrides.

use serde::Deserialize;
use serde::Serialize;

#[derive(Serialize, Deserialize, Debug)]
struct MyConfig {
    version: u8,
    api_key: String,
}

/// `MyConfig` implements `Default`
impl ::std::default::Default for MyConfig {
    fn default() -> Self {
        Self {
            version: 0,
            api_key: "".into(),
        }
    }
}

fn main() -> Result<(), confy::ConfyError> {
    let cfg: MyConfig = confy::load("my-app-name", None)?;
    // confy::store("my-app-name", None, cfg)?;
    println!("{:?}", cfg);
    Ok(())
}