8 releases

0.3.1 Oct 25, 2024
0.3.0 Oct 11, 2024
0.2.4 Apr 20, 2024
0.2.2 Mar 5, 2024
0.1.0 Feb 27, 2024

#1933 in Parser implementations

Download history 29/week @ 2024-07-24 10/week @ 2024-07-31 1/week @ 2024-09-11 7/week @ 2024-09-18 24/week @ 2024-09-25 2/week @ 2024-10-02 139/week @ 2024-10-09 12/week @ 2024-10-16 112/week @ 2024-10-23 8/week @ 2024-10-30

137 downloads per month

MIT license

19KB
347 lines

config-rs

a simple tool to adapt different configuration file format

plan

  • intergrate with toml, yaml, json. ...

usage

First, we need to add serde and xcfg to our Cargo.toml:

cargo add serde -F derive
cargo add xcfg -F full

Then, we can use XCfg to load configuration from different file formats:

use serde::{Deserialize, Serialize};
use xcfg::XCfg;

#[derive(Debug, Serialize, Deserialize, XCfg)]
struct Config {
    name: String,
    age: u32,
}

fn main() {
    let config = Config::load("config")
        .expect("Failed to load config.[toml|yaml|yml|json]")
        .into_inner();
    println!("{:?}", config);
}

This example is also available in the example directory. You can clone this repo and run the example:

cd example && cargo r --example full --features full

lib.rs:

xcfg_rs is a simple configuration file loader and saver.

Example

use serde::{Deserialize, Serialize};
use xcfg::XCfg;
#[derive(XCfg, Serialize, Deserialize, PartialEq, Debug, Clone)]
pub struct Test {
    a: i32,
    b: Vec<i32>,
    sub: SubTest,
}
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub struct SubTest {
    c: Vec<String>,
}
let test = Test {
    a: 1,
    b: vec![0, 1, 2],
    sub: SubTest {
        c: vec!["ab".to_string(), "cd".to_string()],
    },
};
let path = "./test.toml";
test.save(path).unwrap();
assert_eq!(Test::load(path).unwrap().into_inner(), test);
std::fs::remove_file(path).unwrap();

Dependencies

~0.5–1.6MB
~34K SLoC