config_struct 0.2.0

Create structs from config files at build time.
Documentation

config_struct

This is a library for converting config files into matching source files at build time.

Build Status Crates.io

Usage

This library is intended to be used in a build.rs file, so it needs to be added to [build-dependencies].

[build-dependencies.config_struct]
version = "~0.2.0"
features = ["toml-parsing"]

By default, config_struct is markup-language-agnostic, so include the relevant feature for whatever language your config file is written in. Choices are:

  1. json-parsing
  2. ron-parsing
  3. toml-parsing
  4. yaml-parsing

Now in your build.rs file, add code like the following:

extern crate config_struct;

fn main() {
    config_struct::create_config("config.toml", "src/config.rs", &Default::default());
}

This will take the following config.toml file:

name = "Config name"

... and generate a config.rs file like the following:

// ...
use std::borrow::Cow;

#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(non_camel_case_types)]
pub struct Config {
    pub name: Cow<'static, str>,
}

pub const CONFIG: Config = Config {
    name: Cow::Borrowed("Config name"),
};
// ...

Strings and arrays are represented by Cow types, which allows the entire Config struct to be either heap allocated at runtime, or a compile time constant, as shown above.

Note: By default, config structs derive Serialize and Deserialize. This will only work in your application if you include the serde_derive and serde crates. You can disable deriving those traits in the options if you wish.

Similarly, the loading functions generated by default will require the same serialization crate used in generation. For example, extern crate toml will be required if you generate using "config.toml". These loading functions can also be disabled however.