#struct #helper #file #configuration #error #configuraiton #loading-saving

configurable

简单助手,用于将结构体加载/保存到 $XDG 目录中的文件

3 个版本

0.3.5 2020年3月31日
0.3.4 2019年5月8日
0.3.3 2019年5月8日

#1646编码

0BSD 许可证

17KB
124

configurable

Crates.io doc.rs CircleCI Crates.io

此crate提供了一套函数,用于将结构体加载/保存到操作系统精确位置的toml文件

正常配置(例如,将某物保存到CONFIG_DIR中的toml文件)

use configurable::{Configurable, Config, Data, Error, LoadState};
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize)]
struct MyConfiguration {
    name: String,
    attempts: u32,
    force: bool,
}

impl Default for MyConfiguration {
    fn default() -> Self {
        Self {
            name: "Foobar".into(),
            attempts: 3,
            force: false,
        }
    }
}

impl Config for MyConfiguration {}

impl Configurable for MyConfiguration {
    const ORGANIZATION: &'static str = "museun";
    const APPLICATION: &'static str = "foobar";
    const NAME: &'static str = "config.toml";

    fn ensure_dir() -> Result<std::path::PathBuf, Error> {
        <Self as Config>::ensure_dir()
    }
}

“数据”配置(例如,将某物保存到DATA_DIR中的json文件)

use configurable::{Configurable, Config, Data, Error, LoadState};
use serde::{Serialize, Deserialize};
#[derive(Default, Serialize, Deserialize)]
struct MyData {
    #[serde(flatten)]
    data: std::collections::HashMap<String, String>
}


impl Data for MyData {}

impl Configurable for MyData {
    const ORGANIZATION: &'static str = "museun";
    const APPLICATION: &'static str = "foobar";
    const NAME: &'static str = "data.json";

    fn ensure_dir() -> Result<std::path::PathBuf, Error> {
        <Self as Data>::ensure_dir()
    }
}

加载数据

fn load_my_stuff() -> Something {
    use configurable::Configuable;
    // this tries to load the configuration ot creates a default instance of it
    match match Something::load_or_default() {
        Ok(data) => data,
        Err(err) => {
            eprintln!("cannot load configuration: {}", err);
            std::process::exit(1)
        }
    } {
        // it was successfully loaded
        configurable::LoadState::Loaded(this) => this,
        // it was defaulted
        configurable::LoadState::Default(this) => {
            eprintln!(
                "a default configuration was created at: {}",
                Something::path().unwrap().display()
            );
            std::process::exit(1)
        }
    }
}

依赖项

~1.5–2.6MB
~47K SLoC