配置系统
插件通过实现 Config trait 定义自己的配置结构体,核心自动处理 TOML 文件的加载、保存和版本升级。
定义配置
rust
use foxcore_api::Config;
use serde::{Serialize, Deserialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct MyPluginConfig {
/// 配置文件版本
pub version: u32,
/// 功能开关
pub enabled: bool,
/// 冷却时间(秒)
pub cooldown: u32,
}
impl Default for MyPluginConfig {
fn default() -> Self {
Self {
version: 1,
enabled: true,
cooldown: 60,
}
}
}
impl Config for MyPluginConfig {
fn version() -> u32 { 1 }
fn file_name() -> &'static str { "my_plugin.toml" }
}定义规则
| 规则 | 说明 |
|---|---|
#[serde(default)] | 必须放在 struct 级别,确保缺失字段自动填充默认值 |
Default impl | 必须手动实现,定义每个字段的默认值 |
Config::version() | 配置版本号,新增字段时 +1 |
Config::file_name() | 配置文件名 |
自动生成默认配置
使用 toml-example 的 TomlExample derive 宏,doc comment 自动转为 TOML 注释:
rust
use toml_example::TomlExample;
#[derive(Debug, Clone, Serialize, Deserialize, TomlExample)]
#[serde(default)]
pub struct MyPluginConfig {
/// 配置文件版本,请勿手动修改
#[toml_example(default = 1)]
pub version: u32,
/// 功能开关
#[toml_example(default = true)]
pub enabled: bool,
}在 Adapter 的 default_config() 方法中返回:
rust
fn default_config(&self) -> String {
MyPluginConfig::toml_example()
}核心首次加载插件时自动生成带注释的配置文件。
配置文件位置
配置文件位于 config/plugins/<名称>.toml。首次启动时自动生成,用户编辑后重启生效。
版本升级
当需要给配置新增字段时:
- 在 struct 中添加新字段
- 更新
Defaultimpl - 将
Config::version()返回值 +1
核心会自动补全缺失字段并保留用户已有的值。
Config trait
rust
pub trait Config: Serialize + DeserializeOwned + Default + Clone {
fn version() -> u32;
fn file_name() -> &'static str;
}