Skip to main content

crate_plugin_kit/
manifest.rs

1//! Reading and writing the plugin manifest.
2//!
3//! # schema
4//!
5//! The `[plugin]` and `[lib]` sections are defined by this crate; a host may append
6//! its own sections to the same file (for example bmux's `[detect]`), which this crate
7//! preserves verbatim and does not interpret.
8//!
9//! ```toml
10//! [plugin]
11//! name       = "cargo"
12//! version    = "0.1.0"
13//! abi        = 1                              # optional, for the host's own use
14//! family     = "rust"                         # optional, for the host's own use
15//! repository = "https://github.com/o/r"       # optional, used for prebuilt downloads
16//!
17//! [lib]
18//! stem = "bmux_plugin_cargo"                  # optional; derived from KitConfig by default
19//!
20//! [detect]                                    # <- the host's own section, untouched by this crate
21//! strong = ["Cargo.lock"]
22//! weak   = ["Cargo.toml"]
23//! ```
24//!
25//! # How the manifest reaches the install dir
26//!
27//! The plugin crate's source root holds a copy of `<manifest_name>`. During a
28//! build-host install this crate uses `cargo metadata` to locate the crate source dir
29//! and copies that file verbatim into the install dir, so there is a single source of
30//! truth and no extra exported symbol is needed.
31
32use std::path::Path;
33
34use serde::{Deserialize, Serialize};
35
36use crate::error::{KitError, KitResult};
37
38/// A parsed manifest.
39#[derive(Debug, Clone, Serialize, Deserialize)]
40pub struct PluginManifest {
41    /// The `[plugin]` section.
42    pub plugin: PluginSection,
43
44    /// The `[lib]` section. Derived from [`crate::KitConfig::lib_stem`] when absent.
45    #[serde(default, skip_serializing_if = "Option::is_none")]
46    pub lib: Option<LibSection>,
47
48    /// Any other sections belonging to the host (`[detect]` and the like), preserved
49    /// verbatim.
50    #[serde(flatten)]
51    pub extra: toml::Table,
52}
53
54/// The `[plugin]` section of a manifest.
55#[derive(Debug, Clone, Serialize, Deserialize)]
56pub struct PluginSection {
57    /// Plugin name. This is the authoritative source — after loading, a host should
58    /// check that the plugin's self-declared name matches it.
59    pub name: String,
60
61    /// Plugin version.
62    pub version: String,
63
64    /// Cross-boundary ABI version. For the host's own use; this crate only moves it
65    /// around.
66    #[serde(default, skip_serializing_if = "Option::is_none")]
67    pub abi: Option<u32>,
68
69    /// Ecosystem family. For the host's own use; this crate only moves it around.
70    #[serde(default, skip_serializing_if = "Option::is_none")]
71    pub family: Option<String>,
72
73    /// Plugin repository URL. Needed when downloading a prebuilt, to build the release
74    /// URL.
75    #[serde(default, skip_serializing_if = "Option::is_none")]
76    pub repository: Option<String>,
77
78    /// Human-readable description.
79    #[serde(default, skip_serializing_if = "Option::is_none")]
80    pub description: Option<String>,
81
82    /// Any other keys, preserved verbatim.
83    #[serde(flatten)]
84    pub extra: toml::Table,
85}
86
87/// The `[lib]` section of a manifest.
88#[derive(Debug, Clone, Default, Serialize, Deserialize)]
89pub struct LibSection {
90    /// cdylib file name stem (platform-independent, without the `lib` prefix and the
91    /// extension).
92    #[serde(default, skip_serializing_if = "Option::is_none")]
93    pub stem: Option<String>,
94
95    /// Any other keys, preserved verbatim.
96    #[serde(flatten)]
97    pub extra: toml::Table,
98}
99
100impl PluginManifest {
101    /// Reads from a file.
102    pub fn read(path: &Path) -> KitResult<Self> {
103        let text = std::fs::read_to_string(path).map_err(|source| KitError::ManifestRead {
104            path: path.to_path_buf(),
105            source,
106        })?;
107        Self::parse(&text, path)
108    }
109
110    /// Parses from a string.
111    pub fn parse(text: &str, path: &Path) -> KitResult<Self> {
112        let parsed: Self = toml::from_str(text).map_err(|source| KitError::ManifestParse {
113            path: path.to_path_buf(),
114            source: Box::new(source),
115        })?;
116
117        // An empty name is a common symptom of a broken file; reporting it here beats
118        // letting it travel on.
119        if parsed.plugin.name.trim().is_empty() {
120            return Err(KitError::ManifestMissingField {
121                field: "plugin.name".to_string(),
122                path: path.to_path_buf(),
123            });
124        }
125        if parsed.plugin.version.trim().is_empty() {
126            return Err(KitError::ManifestMissingField {
127                field: "plugin.version".to_string(),
128                path: path.to_path_buf(),
129            });
130        }
131        Ok(parsed)
132    }
133
134    /// Serializes back to TOML text.
135    pub fn to_toml(&self) -> KitResult<String> {
136        toml::to_string_pretty(self)
137            .map_err(|e| KitError::Registry(format!("failed to serialize manifest: {e}")))
138    }
139
140    /// Writes to a file.
141    pub fn write(&self, path: &Path) -> KitResult<()> {
142        if let Some(parent) = path.parent() {
143            std::fs::create_dir_all(parent)?;
144        }
145        let text = self.to_toml()?;
146        std::fs::write(path, text)?;
147        Ok(())
148    }
149
150    /// The effective cdylib file name stem.
151    ///
152    /// An explicit declaration in the manifest wins; otherwise it is derived with
153    /// `cfg.lib_stem(crate_name)`.
154    pub fn effective_lib_stem(&self, cfg: &crate::KitConfig, crate_name: &str) -> String {
155        self.lib
156            .as_ref()
157            .and_then(|l| l.stem.clone())
158            .unwrap_or_else(|| cfg.lib_stem(crate_name))
159    }
160}
161
162#[cfg(test)]
163mod tests {
164    use super::*;
165    use std::path::Path;
166
167    const SAMPLE: &str = r#"
168[plugin]
169name       = "cargo"
170version    = "0.1.0"
171abi        = 1
172family     = "rust"
173repository = "https://github.com/imba97/bmux-plugin-cargo"
174
175[lib]
176stem = "custom_stem"
177
178[detect]
179strong = ["Cargo.lock"]
180weak   = ["Cargo.toml"]
181"#;
182
183    fn parse(text: &str) -> PluginManifest {
184        PluginManifest::parse(text, Path::new("test.toml")).expect("should parse")
185    }
186
187    #[test]
188    fn parses_the_plugin_section() {
189        let m = parse(SAMPLE);
190        assert_eq!(m.plugin.name, "cargo");
191        assert_eq!(m.plugin.version, "0.1.0");
192        assert_eq!(m.plugin.abi, Some(1));
193        assert_eq!(m.plugin.family.as_deref(), Some("rust"));
194        assert_eq!(
195            m.plugin.repository.as_deref(),
196            Some("https://github.com/imba97/bmux-plugin-cargo")
197        );
198    }
199
200    /// Key behavior: a host-defined section (here `[detect]`) must be preserved
201    /// verbatim. This crate does not understand it, and rewriting the manifest must
202    /// never drop it.
203    #[test]
204    fn preserves_host_defined_sections() {
205        let m = parse(SAMPLE);
206        assert!(m.extra.contains_key("detect"), "extra = {:?}", m.extra);
207    }
208
209    #[test]
210    fn round_trips_through_toml() {
211        let m = parse(SAMPLE);
212        let text = m.to_toml().expect("should serialize");
213        let again =
214            PluginManifest::parse(&text, Path::new("again.toml")).expect("should read back");
215
216        assert_eq!(again.plugin.name, "cargo");
217        assert_eq!(again.plugin.abi, Some(1));
218        assert_eq!(
219            again.lib.as_ref().and_then(|l| l.stem.clone()).as_deref(),
220            Some("custom_stem")
221        );
222        assert!(again.extra.contains_key("detect"));
223    }
224
225    #[test]
226    fn optional_sections_may_be_absent() {
227        let m = parse(
228            r#"
229[plugin]
230name    = "bare"
231version = "1.0.0"
232"#,
233        );
234        assert!(m.lib.is_none());
235        assert!(m.plugin.abi.is_none());
236        assert!(m.plugin.family.is_none());
237        assert!(m.extra.is_empty());
238    }
239
240    #[test]
241    fn rejects_empty_name() {
242        let err = PluginManifest::parse(
243            "[plugin]\nname = \"\"\nversion = \"1.0.0\"\n",
244            Path::new("t.toml"),
245        );
246        assert!(matches!(err, Err(KitError::ManifestMissingField { .. })));
247    }
248
249    #[test]
250    fn rejects_blank_name() {
251        let err = PluginManifest::parse(
252            "[plugin]\nname = \"   \"\nversion = \"1.0.0\"\n",
253            Path::new("t.toml"),
254        );
255        assert!(matches!(err, Err(KitError::ManifestMissingField { .. })));
256    }
257
258    #[test]
259    fn rejects_empty_version() {
260        let err = PluginManifest::parse(
261            "[plugin]\nname = \"a\"\nversion = \"\"\n",
262            Path::new("t.toml"),
263        );
264        assert!(matches!(err, Err(KitError::ManifestMissingField { .. })));
265    }
266
267    #[test]
268    fn rejects_a_missing_required_section() {
269        let err = PluginManifest::parse("x = 1\n", Path::new("t.toml"));
270        assert!(matches!(err, Err(KitError::ManifestParse { .. })));
271    }
272
273    #[test]
274    fn read_reports_a_missing_file() {
275        let err = PluginManifest::read(Path::new("definitely/not/here.toml"));
276        assert!(matches!(err, Err(KitError::ManifestRead { .. })));
277    }
278
279    #[test]
280    fn effective_stem_prefers_the_manifest_declaration() {
281        let cfg = crate::KitConfig::new("myapp");
282        let m = parse(SAMPLE);
283        assert_eq!(
284            m.effective_lib_stem(&cfg, "myapp-plugin-cargo"),
285            "custom_stem"
286        );
287    }
288
289    #[test]
290    fn effective_stem_derives_when_the_manifest_is_silent() {
291        let cfg = crate::KitConfig::new("myapp");
292        let m = parse("[plugin]\nname = \"cargo\"\nversion = \"0.1.0\"\n");
293        assert_eq!(
294            m.effective_lib_stem(&cfg, "myapp-plugin-cargo"),
295            "myapp_plugin_cargo"
296        );
297    }
298
299    #[test]
300    fn write_then_read_from_disk() {
301        let dir = tempfile::tempdir().unwrap();
302        let path = dir.path().join("nested").join("myapp-plugin.toml");
303
304        let m = parse(SAMPLE);
305        m.write(&path).expect("should write to disk");
306
307        let back = PluginManifest::read(&path).expect("should read back");
308        assert_eq!(back.plugin.name, "cargo");
309        assert!(back.extra.contains_key("detect"));
310    }
311}