4个版本
0.1.3 | 2024年5月8日 |
---|---|
0.1.2 | 2024年3月10日 |
0.1.1 | 2024年2月17日 |
0.1.0 | 2024年2月17日 |
#135 in 配置
每月411次下载
115KB
3K SLoC
BakuninConfig
Rust应用程序的分层配置。
关于
它是为了提供一种从不同来源搜索和加载配置并将其合并为单个配置值的方法而创建的。它使用serde进行配置值的序列化和反序列化,这意味着您可以使用serde支持的任何格式来存储配置。默认情况下,它支持JSON、JSON5、TOML和YAML。它采用插槽系统合并配置值,从0到u64::MAX,其中最后一个具有优先级。
用法
// the default value for our configurations
let default_value = value_map! {
path: "some/path/to/dir",
delay: 1000,
enabled: true,
log: value_map! {
level: "info",
file: "log.txt"
}
};
// create a new configuration builder from the default value
let mut builder = ConfigBuilder::from_base(default_value.clone())?;
// Create the root config file path
let root_file: PathBuf = ConfigFileFinder::for_file(".app-config".to_string()) // will search for files .app-config.{ext}
.with_os_folder(OSFolder::UserHome) // will search in the user home directory: /home/user/
.with_os_folder(OSFolder::Config) // will search in the user config directory: /home/user/.config/
.with_os_folder(OSFolder::AppConfig("myapp".to_string())) // will search in the user config directory: /home/user/.config/myapp/
.with_supported_extensions() // will search for files with the supported extensions: .json, .json5, .toml, .yaml, .yml
.find_or_first(); // will search for the first file that exists, if none is found, will return the first path
.unwrap();
let config_file = ConfigFile::new(root_file)
.with_init(default_value) // Will create the file with the default value if it does not exist
// add the root config file to the builder, first available means that will be added in the first slot available
builder.add_config_file(config_file, Priority::FirstAvailable)?;
// Will use environment variables to override the configuration values, ex: MY_APP_path will override the path value
builder.environment("MY_APP")?;
let config: Value = builder.build();
#[derive(Serialize, Deserialize)]
/// Logger configuration
pub struct LoggerConfig {
pub level: String,
pub file: String,
}
// Deserialize the configuration value into a LoggerConfig
let log = config.get("log").deserialize::<LoggerConfig>().unwrap();
// Get the path value as a string
let path = config.get("path").try_into_String().unwrap(); // Will panic if the value is not a string
// Get the delay value as a u64
let delay: u64 = config.get("delay").try_into().unwrap(); // Will panic if the value is not a valid u64
依赖项
~3–13MB
~119K SLoC