RSCONFIG
Simple configuration library to help programs manage their config.
Importing
If just using RSCONFIG, you can do this:
[dependencies]
rsconfig = "0.1.3"
Examples
CommandlineConfig
use rsconfig::CommandlineConfig;
use std::env;
#[derive(Debug)]
struct TestConfig {
test: bool
}
impl CommandlineConfig for TestConfig {
fn from_env_args(args: Vec<String>) -> Self {
Self { test: args.contains(&"--test".to_string()) }
}
}
fn main() {
let args: Vec<String> = env::args().collect();
let mut config = TestConfig::from_env_args(args);
println!("{:?}", config);
config.test = !config.test;
}
YamlConfig
use rsconfig::YamlConfig;
use rsconfig::files;
use yaml_rust;
use std::fs;
#[derive(Debug)]
struct TestConfig {
test: bool
}
impl YamlConfig for TestConfig {
fn from_yaml(yaml: Vec<yaml_rust::Yaml>) -> Self {
Self { test: *&yaml[0]["test"].as_bool().unwrap() }
}
fn save_yaml(&self, path: &str) -> Result<()> {
let mut data = "test: ".to_string();
data.push_str(self.test.to_string().as_str());
fs::write(path, data).unwrap();
Ok(())
}
}
fn main() {
let mut config: TestConfig = files::load_from_yaml();
println!("{:?}", config);
config.test = !config.test;
}
JsonConfig
use rsconfig::JsonConfig;
use rsconfig::files;
use serde_json;
use std::fs;
#[derive(Debug)]
struct TestConfig {
test: bool
}
impl JsonConfig for TestConfig {
fn from_json(val: serde_json::Value) -> Self {
Self { test: val["test"].as_bool().unwrap() }
}
fn save_json(&self, path: &str) -> io::Result<()> {
let data = serde_json::to_string_pretty(&Value::from(self.test)).unwrap();
fs::write(path, data).unwrap();
Ok(())
}
}
fn main() {
let mut config: TestConfig = files::load_from_json();
println!("{:?}", config);
config.test = !config.test;
}
FileConfig
#[derive(Debug)]
struct TestConfig {
test: bool
}
impl YamlConfig for TestConfig {
fn from_yaml(yaml: Vec<yaml_rust::Yaml>) -> Self {
Self { test: *&yaml[0]["test"].as_bool().unwrap() }
}
fn save_yaml(&self, path: &str) -> Result<()> {
let mut data = "test: ".to_string();
data.push_str(self.test.to_string().as_str());
fs::write(path, data).unwrap();
Ok(())
}
}
impl JsonConfig for TestConfig {
fn from_json(val: Value) -> Self {
Self { test: val["test"].as_bool().unwrap() }
}
fn save_json(&self, path: &str) -> io::Result<()> {
let mut m: Hashmap<&str, Value> = Hashmap::new();
m.insert("test", &Value::from(self.test));
let data = serde_json::to_string_pretty(m).unwrap();
fs::write(path, data).unwrap();
Ok(())
}
}
impl FileConfig for TestConfig {}
License
Licensed under either of Apache License, Version 2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.