Crate config

source ·
Expand description

More Configuration   CI Crates.io MIT licensed

More Configuration is a configuration library for Rust.

You may be looking for:

Features

This crate provides the following features:

  • default - Abstractions for configuration, including the std features
  • std - Standard configuration implementation
  • async - Use configuration in an asynchronous context
  • mem - An in-memory configuration source
  • env - An environment variables configuration source
  • cmd - A command-line argument configuration source
  • json - A *.json file configuration source
  • xml - A *.xml file configuration source
  • ini - An *.ini file configuration source
  • chained - Chain multiple configuration sources
  • binder - Bind a configuration to strongly-typed values and structs

Configuration in Action

Consider the following demo.json file:

{
  "text": "Hello world!",
  "demo": true,
  "clients": [{
    "region": "us-west",
    "url": "https://tempuri.org"
  }]
}

The configuration can be loaded, merged, and accessed from multiple sources:

use config::{*, ext::*};

fn main() {
    let config = DefaultConfigurationBuilder::new()
        .add_in_memory(&[("Demo", "false")])
        .add_json_file("demo.json".is().optional())
        .add_env_vars()
        .add_command_line()
        .build()
        .unwrap();
    
    if let Some(demo) = config.get("demo") {
      if demo.as_str() == "true" {
        println!("{}", config.get("Text").unwrap().as_str());
        println!("{}", config.get("Clients:0:Region").unwrap().as_str());
        return;
      }
    }
    
    println!("Not a demo!");
}

Raw configuration values can be used, but they are much more interesting when we data bind them to strongly-typed values:

use serde::Deserialize;

#[derive(Default, Deserialize)]
struct Client {
    region: String,
    url: String,
}

#[derive(Default, Deserialize)]
struct AppOptions {
    text: String,
    demo: bool,
    clients: Vec<Client>,
}
use config::{*, ext::*};

fn main() {
    let config = DefaultConfigurationBuilder::new()
        .add_json_file("demo.json")
        .build()
        .unwrap();
    let app: AppOptions = config.reify();
    
    if app.demo {
        println!("{}", &config.text);
        println!("{}", &config.clients[0].region);
        return;
    }
    
    println!("Not a demo!");
}

License

This project is licensed under the MIT license.

Re-exports

Modules

  • Contains configuration extension methods.
  • Contains configuration utility functions.

Structs

Enums

Traits

Type Aliases

  • Represents a configuration load result.
  • Represents a configuration reload result.
  • Represents the type alias for a configuration value.