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 |
#2086 in Parser implementations
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