Skip to main content

crate_plugin_kit/
manifest.rs

1//! 插件 manifest 的读写。
2//!
3//! # schema
4//!
5//! `[plugin]` 与 `[lib]` 两段由**本 crate** 定义;宿主可以往同一个文件里追加
6//! 自己的段(例如 bmux 的 `[detect]`),本 crate 原样保留、不做解释。
7//!
8//! ```toml
9//! [plugin]
10//! name       = "cargo"
11//! version    = "0.1.0"
12//! abi        = 1                              # 可选,宿主自用
13//! family     = "rust"                         # 可选,宿主自用
14//! repository = "https://github.com/o/r"       # 可选,prebuilt 下载用
15//!
16//! [lib]
17//! stem = "bmux_plugin_cargo"                  # 可选;缺省由 KitConfig 推导
18//!
19//! [detect]                                    # ← 宿主自己的段,本 crate 不碰
20//! strong = ["Cargo.lock"]
21//! weak   = ["Cargo.toml"]
22//! ```
23//!
24//! # manifest 是怎么进到安装目录的
25//!
26//! **插件 crate 的源码根目录里就放一份 `<manifest_name>`**,build-host 安装时
27//! 本 crate 用 `cargo metadata` 定位 crate 源码目录,把这个文件原样拷进安装目录。
28//!
29//! 这样:
30//!
31//! - **单一事实来源** —— detect 信息跟着插件代码走,不会两边不同步;
32//! - **安装后是纯文件** —— 检测阶段只读文件,不需要 `dlopen`;
33//! - **不改 ABI** —— 不需要多导出一个"把 manifest 交出来"的符号。
34
35use std::path::Path;
36
37use serde::{Deserialize, Serialize};
38
39use crate::error::{KitError, KitResult};
40
41/// 解析后的 manifest。
42#[derive(Debug, Clone, Serialize, Deserialize)]
43pub struct PluginManifest {
44    /// `[plugin]` 段。
45    pub plugin: PluginSection,
46
47    /// `[lib]` 段。缺省时由 [`crate::KitConfig::lib_stem`] 推导。
48    #[serde(default, skip_serializing_if = "Option::is_none")]
49    pub lib: Option<LibSection>,
50
51    /// 宿主自己的其它段(`[detect]` 之类),原样保留。
52    #[serde(flatten)]
53    pub extra: toml::Table,
54}
55
56/// manifest 的 `[plugin]` 段。
57#[derive(Debug, Clone, Serialize, Deserialize)]
58pub struct PluginSection {
59    /// 插件名。**这是权威来源** —— 加载后宿主应校验插件自报名是否与它一致。
60    pub name: String,
61
62    /// 插件版本。
63    pub version: String,
64
65    /// 跨边界 ABI 版本。宿主自用,本 crate 只做搬运。
66    #[serde(default, skip_serializing_if = "Option::is_none")]
67    pub abi: Option<u32>,
68
69    /// 生态分组。宿主自用,本 crate 只做搬运。
70    #[serde(default, skip_serializing_if = "Option::is_none")]
71    pub family: Option<String>,
72
73    /// 插件仓库地址。prebuilt 下载时需要它来拼 Release URL。
74    #[serde(default, skip_serializing_if = "Option::is_none")]
75    pub repository: Option<String>,
76
77    /// 人类可读描述。
78    #[serde(default, skip_serializing_if = "Option::is_none")]
79    pub description: Option<String>,
80
81    /// 其它键,原样保留。
82    #[serde(flatten)]
83    pub extra: toml::Table,
84}
85
86/// manifest 的 `[lib]` 段。
87#[derive(Debug, Clone, Default, Serialize, Deserialize)]
88pub struct LibSection {
89    /// cdylib 文件名主干(平台无关,不含 `lib` 前缀与扩展名)。
90    #[serde(default, skip_serializing_if = "Option::is_none")]
91    pub stem: Option<String>,
92
93    /// 其它键,原样保留。
94    #[serde(flatten)]
95    pub extra: toml::Table,
96}
97
98impl PluginManifest {
99    /// 从文件读。
100    pub fn read(path: &Path) -> KitResult<Self> {
101        let text = std::fs::read_to_string(path).map_err(|source| KitError::ManifestRead {
102            path: path.to_path_buf(),
103            source,
104        })?;
105        Self::parse(&text, path)
106    }
107
108    /// 从字符串解析。
109    pub fn parse(text: &str, path: &Path) -> KitResult<Self> {
110        let parsed: Self = toml::from_str(text).map_err(|source| KitError::ManifestParse {
111            path: path.to_path_buf(),
112            source: Box::new(source),
113        })?;
114
115        // 空名字是常见的"文件写坏了"症状,单独报出来比让它一路带下去好。
116        if parsed.plugin.name.trim().is_empty() {
117            return Err(KitError::ManifestMissingField {
118                field: "plugin.name".to_string(),
119                path: path.to_path_buf(),
120            });
121        }
122        if parsed.plugin.version.trim().is_empty() {
123            return Err(KitError::ManifestMissingField {
124                field: "plugin.version".to_string(),
125                path: path.to_path_buf(),
126            });
127        }
128        Ok(parsed)
129    }
130
131    /// 序列化回 TOML 文本。
132    pub fn to_toml(&self) -> KitResult<String> {
133        toml::to_string_pretty(self)
134            .map_err(|e| KitError::Registry(format!("序列化 manifest 失败:{e}")))
135    }
136
137    /// 写到文件。
138    pub fn write(&self, path: &Path) -> KitResult<()> {
139        if let Some(parent) = path.parent() {
140            std::fs::create_dir_all(parent)?;
141        }
142        let text = self.to_toml()?;
143        std::fs::write(path, text)?;
144        Ok(())
145    }
146
147    /// 生效的 cdylib 文件名主干。
148    ///
149    /// 优先用 manifest 里的显式声明;没有就用 `cfg.lib_stem(crate_name)` 推导。
150    pub fn effective_lib_stem(&self, cfg: &crate::KitConfig, crate_name: &str) -> String {
151        self.lib
152            .as_ref()
153            .and_then(|l| l.stem.clone())
154            .unwrap_or_else(|| cfg.lib_stem(crate_name))
155    }
156}
157
158#[cfg(test)]
159mod tests {
160    use super::*;
161    use std::path::Path;
162
163    const SAMPLE: &str = r#"
164[plugin]
165name       = "cargo"
166version    = "0.1.0"
167abi        = 1
168family     = "rust"
169repository = "https://github.com/imba97/bmux-plugin-cargo"
170
171[lib]
172stem = "custom_stem"
173
174[detect]
175strong = ["Cargo.lock"]
176weak   = ["Cargo.toml"]
177"#;
178
179    fn parse(text: &str) -> PluginManifest {
180        PluginManifest::parse(text, Path::new("test.toml")).expect("应当解析成功")
181    }
182
183    #[test]
184    fn parses_the_plugin_section() {
185        let m = parse(SAMPLE);
186        assert_eq!(m.plugin.name, "cargo");
187        assert_eq!(m.plugin.version, "0.1.0");
188        assert_eq!(m.plugin.abi, Some(1));
189        assert_eq!(m.plugin.family.as_deref(), Some("rust"));
190        assert_eq!(
191            m.plugin.repository.as_deref(),
192            Some("https://github.com/imba97/bmux-plugin-cargo")
193        );
194    }
195
196    /// 关键行为:宿主自己的段(这里是 `[detect]`)必须被**原样保留**。
197    /// 这个 crate 不认识它,重写 manifest 时绝不能把它丢掉。
198    #[test]
199    fn preserves_host_defined_sections() {
200        let m = parse(SAMPLE);
201        assert!(m.extra.contains_key("detect"), "extra = {:?}", m.extra);
202    }
203
204    #[test]
205    fn round_trips_through_toml() {
206        let m = parse(SAMPLE);
207        let text = m.to_toml().expect("应当能序列化");
208        let again = PluginManifest::parse(&text, Path::new("again.toml")).expect("应当能读回");
209
210        assert_eq!(again.plugin.name, "cargo");
211        assert_eq!(again.plugin.abi, Some(1));
212        assert_eq!(
213            again.lib.as_ref().and_then(|l| l.stem.clone()).as_deref(),
214            Some("custom_stem")
215        );
216        assert!(again.extra.contains_key("detect"));
217    }
218
219    #[test]
220    fn optional_sections_may_be_absent() {
221        let m = parse(
222            r#"
223[plugin]
224name    = "bare"
225version = "1.0.0"
226"#,
227        );
228        assert!(m.lib.is_none());
229        assert!(m.plugin.abi.is_none());
230        assert!(m.plugin.family.is_none());
231        assert!(m.extra.is_empty());
232    }
233
234    #[test]
235    fn rejects_empty_name() {
236        let err = PluginManifest::parse(
237            "[plugin]\nname = \"\"\nversion = \"1.0.0\"\n",
238            Path::new("t.toml"),
239        );
240        assert!(matches!(err, Err(KitError::ManifestMissingField { .. })));
241    }
242
243    #[test]
244    fn rejects_blank_name() {
245        let err = PluginManifest::parse(
246            "[plugin]\nname = \"   \"\nversion = \"1.0.0\"\n",
247            Path::new("t.toml"),
248        );
249        assert!(matches!(err, Err(KitError::ManifestMissingField { .. })));
250    }
251
252    #[test]
253    fn rejects_empty_version() {
254        let err = PluginManifest::parse(
255            "[plugin]\nname = \"a\"\nversion = \"\"\n",
256            Path::new("t.toml"),
257        );
258        assert!(matches!(err, Err(KitError::ManifestMissingField { .. })));
259    }
260
261    #[test]
262    fn rejects_a_missing_required_section() {
263        let err = PluginManifest::parse("x = 1\n", Path::new("t.toml"));
264        assert!(matches!(err, Err(KitError::ManifestParse { .. })));
265    }
266
267    #[test]
268    fn read_reports_a_missing_file() {
269        let err = PluginManifest::read(Path::new("definitely/not/here.toml"));
270        assert!(matches!(err, Err(KitError::ManifestRead { .. })));
271    }
272
273    #[test]
274    fn effective_stem_prefers_the_manifest_declaration() {
275        let cfg = crate::KitConfig::new("myapp");
276        let m = parse(SAMPLE);
277        assert_eq!(
278            m.effective_lib_stem(&cfg, "myapp-plugin-cargo"),
279            "custom_stem"
280        );
281    }
282
283    #[test]
284    fn effective_stem_derives_when_the_manifest_is_silent() {
285        let cfg = crate::KitConfig::new("myapp");
286        let m = parse("[plugin]\nname = \"cargo\"\nversion = \"0.1.0\"\n");
287        assert_eq!(
288            m.effective_lib_stem(&cfg, "myapp-plugin-cargo"),
289            "myapp_plugin_cargo"
290        );
291    }
292
293    #[test]
294    fn write_then_read_from_disk() {
295        let dir = tempfile::tempdir().unwrap();
296        let path = dir.path().join("nested").join("myapp-plugin.toml");
297
298        let m = parse(SAMPLE);
299        m.write(&path).expect("应当能落盘");
300
301        let back = PluginManifest::read(&path).expect("应当能读回");
302        assert_eq!(back.plugin.name, "cargo");
303        assert!(back.extra.contains_key("detect"));
304    }
305}