Skip to main content

crate_plugin_kit/
config.rs

1//! [`KitConfig`]:把一个 kit 实例里所有跟宿主应用相关的名字参数化。
2//!
3//! **本 crate 里没有任何一处硬编码具体宿主应用的名字。**
4//! 所有 `bmux` / `bmux-plugin.toml` / `bmux_plugin_entry_v1` 之类的东西,
5//! 都由这里提供。
6
7use std::collections::BTreeMap;
8use std::path::PathBuf;
9use std::time::Duration;
10
11use crate::error::{KitError, KitResult};
12
13/// 默认的锁等待时间。
14pub const DEFAULT_LOCK_TIMEOUT: Duration = Duration::from_secs(30);
15
16/// 一个 kit 实例的全部可配置项。
17#[derive(Debug, Clone)]
18pub struct KitConfig {
19    /// 应用 id。决定数据目录 `~/.{id}`,也用作默认的 HTTP User-Agent 一部分。
20    pub id: String,
21
22    /// 插件 manifest 的文件名,如 `"bmux-plugin.toml"`。
23    ///
24    /// manifest 的 `[plugin]` / `[lib]` 两段由本 crate 定义(见 [`crate::manifest`])。
25    /// 宿主可以往同一个文件里追加自己的段(例如 bmux 的 `[detect]`),本 crate 会原样忽略。
26    pub manifest_name: String,
27
28    /// 插件 crate 名前缀,如 `"bmux-plugin-"`。
29    ///
30    /// `install("cargo")` 会先补成 `"bmux-plugin-cargo"`;已经带前缀的原样使用。
31    pub crate_prefix: String,
32
33    /// cdylib 导出的入口符号,如 `b"bmux_plugin_entry_v1"`。
34    pub entry_symbol: Vec<u8>,
35
36    /// cdylib 文件名主干前缀,如 `"bmux_plugin_"`。
37    ///
38    /// 与「crate 名去掉前缀」拼接后,再加平台扩展名,得到实际文件名。
39    /// 例:`bmux-plugin-cargo` → `bmux_plugin_` + `cargo` → `libbmux_plugin_cargo.so`。
40    pub lib_stem_prefix: String,
41
42    /// 宿主的**契约 crate** 名,如 `"bmux-plugin"`。生成的 wrapper 工程要依赖它。
43    pub contract_crate: String,
44
45    /// 契约 crate 的版本要求,如 `"0.1"`。
46    pub contract_version: String,
47
48    /// 生成的 wrapper 工程使用的 edition。
49    pub wrapper_edition: String,
50
51    /// wrapper 工程 `src/lib.rs` 的内容模板。
52    ///
53    /// `{crate_ident}` 会被替换成插件 crate 的 ident(`-` 换成 `_`)。
54    /// 例(bmux):`"bmux_plugin::export!({crate_ident}::create);\n"`
55    pub wrapper_body: String,
56
57    /// 数据目录覆盖。`None` = 用 `~/.{id}`。
58    pub data_dir: Option<PathBuf>,
59
60    /// 等待安装锁的超时时间。
61    pub lock_timeout: Duration,
62
63    /// 安装时是否优先尝试 prebuilt 产物。
64    pub prefer_prebuilt: bool,
65
66    /// 覆盖 target triple。`None` = 用编译期注入的 `TARGET`(见 `build.rs`)。
67    pub target_triple: Option<String>,
68
69    /// crates.io 索引地址。可以指向镜像。
70    pub registry: String,
71
72    /// 本地路径覆盖:crate 名 → 本地目录。
73    ///
74    /// 生成 wrapper 工程时会写成它的 `[patch.crates-io]`。**开发期用** ——
75    /// wrapper 住在 `~/.{id}/build/` 下,读不到宿主项目里的 `.cargo/config.toml`,
76    /// 所以本地联调必须在这里显式指路。生产环境留空。
77    pub local_overrides: BTreeMap<String, PathBuf>,
78}
79
80impl KitConfig {
81    /// 用最少的信息起一个配置,其余字段给保守默认值。
82    ///
83    /// 默认值全部由 `id` 推导,并且**互相自洽** —— 例如 `id = "myapp"` 会得到:
84    ///
85    /// | 字段 | 值 |
86    /// | ---- | -- |
87    /// | `manifest_name` | `myapp-plugin.toml` |
88    /// | `crate_prefix` | `myapp-plugin-` |
89    /// | `lib_stem_prefix` | `myapp_plugin_` |
90    /// | `entry_symbol` | `myapp_plugin_entry_v1` |
91    /// | `contract_crate` | `myapp-plugin` |
92    ///
93    /// 仍然要自己填的是 `wrapper_body`(它引用的路径来自宿主的契约 crate)和
94    /// `contract_version`。
95    ///
96    /// `entry_symbol` 不需要以 NUL 结尾 —— `libloading` 会自己补。
97    pub fn new(id: impl Into<String>) -> Self {
98        let id = id.into();
99        let snake = id.replace('-', "_");
100        Self {
101            manifest_name: format!("{id}-plugin.toml"),
102            crate_prefix: format!("{id}-plugin-"),
103            entry_symbol: format!("{snake}_plugin_entry_v1").into_bytes(),
104            lib_stem_prefix: format!("{snake}_plugin_"),
105            contract_crate: format!("{id}-plugin"),
106            contract_version: "0.1".to_string(),
107            wrapper_edition: "2021".to_string(),
108            wrapper_body: format!("{snake}_plugin::export!({{crate_ident}}::create);\n"),
109            data_dir: None,
110            lock_timeout: DEFAULT_LOCK_TIMEOUT,
111            prefer_prebuilt: true,
112            target_triple: None,
113            registry: "https://crates.io".to_string(),
114            local_overrides: BTreeMap::new(),
115            id,
116        }
117    }
118
119    /// 覆盖数据目录。
120    pub fn with_data_dir(mut self, dir: impl Into<PathBuf>) -> Self {
121        self.data_dir = Some(dir.into());
122        self
123    }
124
125    /// 覆盖锁等待时间。
126    pub fn with_lock_timeout(mut self, t: Duration) -> Self {
127        self.lock_timeout = t;
128        self
129    }
130
131    /// 本次构建的 target triple。优先用配置里的覆盖值。
132    pub fn effective_target(&self) -> &str {
133        self.target_triple
134            .as_deref()
135            .unwrap_or(crate::TARGET_TRIPLE)
136    }
137
138    /// 把 `install()` 收到的名字规范成完整 crate 名。
139    ///
140    /// 已带前缀的原样返回;否则补前缀。
141    pub fn normalize_crate_name(&self, name: &str) -> String {
142        if name.starts_with(&self.crate_prefix) {
143            name.to_string()
144        } else {
145            format!("{}{}", self.crate_prefix, name)
146        }
147    }
148
149    /// 由 crate 名推出 cdylib 文件名主干(不含 `lib` 前缀与扩展名)。
150    ///
151    /// `bmux-plugin-cargo` → `bmux_plugin_cargo`
152    pub fn lib_stem(&self, crate_name: &str) -> String {
153        let tail = crate_name
154            .strip_prefix(&self.crate_prefix)
155            .unwrap_or(crate_name);
156        format!("{}{}", self.lib_stem_prefix, tail.replace('-', "_"))
157    }
158
159    /// 解析出各项路径。会按需创建目录。
160    pub fn paths(&self) -> KitResult<KitPaths> {
161        let root = match &self.data_dir {
162            Some(d) => d.clone(),
163            None => default_data_dir(&self.id)?,
164        };
165        Ok(KitPaths {
166            plugins: root.join("plugins"),
167            build: root.join("build"),
168            lock_file: root.join(".lock"),
169            index_file: root.join("plugins").join(".plugins.json"),
170            root,
171        })
172    }
173}
174
175/// 由 `directories` 决定的默认数据目录 `~/.{id}`。
176fn default_data_dir(id: &str) -> KitResult<PathBuf> {
177    let home = directories::UserDirs::new()
178        .map(|d| d.home_dir().to_path_buf())
179        .ok_or(KitError::NoDataDir)?;
180    Ok(home.join(format!(".{id}")))
181}
182
183/// kit 用到的所有路径。
184#[derive(Debug, Clone)]
185pub struct KitPaths {
186    /// `<data-dir>` 本身。
187    pub root: PathBuf,
188    /// 已安装插件的目录,`<root>/plugins`。
189    pub plugins: PathBuf,
190    /// build-host 脚手架目录,`<root>/build`。
191    pub build: PathBuf,
192    /// 安装排他锁文件,`<root>/.lock`。
193    pub lock_file: PathBuf,
194    /// 安装记录缓存,`<root>/plugins/.plugins.json`。
195    pub index_file: PathBuf,
196}
197
198impl KitPaths {
199    /// 某个插件的安装目录,`<plugins>/<crate_name>`。
200    pub fn plugin_dir(&self, crate_name: &str) -> PathBuf {
201        self.plugins.join(crate_name)
202    }
203
204    /// 某个插件的 manifest 路径。
205    pub fn manifest_path(&self, crate_name: &str, manifest_name: &str) -> PathBuf {
206        self.plugin_dir(crate_name).join(manifest_name)
207    }
208
209    /// 某个插件的 build-host 脚手架目录。
210    pub fn build_dir(&self, crate_name: &str) -> PathBuf {
211        self.build.join(crate_name)
212    }
213}
214
215#[cfg(test)]
216mod tests {
217    use super::*;
218
219    fn cfg() -> KitConfig {
220        KitConfig::new("myapp")
221    }
222
223    #[test]
224    fn new_derives_names_from_the_id() {
225        let c = cfg();
226        assert_eq!(c.id, "myapp");
227        assert_eq!(c.manifest_name, "myapp-plugin.toml");
228        assert_eq!(c.crate_prefix, "myapp-plugin-");
229        assert_eq!(c.lib_stem_prefix, "myapp_plugin_");
230        assert_eq!(c.contract_crate, "myapp-plugin");
231    }
232
233    #[test]
234    fn normalizes_short_and_full_crate_names() {
235        let c = cfg();
236        assert_eq!(c.normalize_crate_name("foo"), "myapp-plugin-foo");
237        // 已经带前缀的原样返回 —— 否则会变成 myapp-plugin-myapp-plugin-foo
238        assert_eq!(
239            c.normalize_crate_name("myapp-plugin-foo"),
240            "myapp-plugin-foo"
241        );
242    }
243
244    #[test]
245    fn derives_lib_stem_from_crate_name() {
246        let c = cfg();
247        assert_eq!(c.lib_stem("myapp-plugin-foo"), "myapp_plugin_foo");
248        // 短横线要换成下划线
249        assert_eq!(c.lib_stem("myapp-plugin-a-b"), "myapp_plugin_a_b");
250    }
251
252    #[test]
253    fn target_falls_back_to_compile_time_triple() {
254        let c = cfg();
255        assert_eq!(c.effective_target(), crate::TARGET_TRIPLE);
256
257        let mut overridden = cfg();
258        overridden.target_triple = Some("aarch64-apple-darwin".to_string());
259        assert_eq!(overridden.effective_target(), "aarch64-apple-darwin");
260    }
261
262    #[test]
263    fn paths_honour_the_data_dir_override() {
264        let root = PathBuf::from("some").join("dir");
265        let c = cfg().with_data_dir(&root);
266        let p = c.paths().expect("override 时不该碰 HOME");
267
268        assert_eq!(p.root, root);
269        assert_eq!(p.plugins, root.join("plugins"));
270        assert_eq!(p.build, root.join("build"));
271        assert_eq!(p.lock_file, root.join(".lock"));
272        assert_eq!(p.index_file, root.join("plugins").join(".plugins.json"));
273    }
274
275    #[test]
276    fn plugin_paths_sit_under_the_plugins_dir() {
277        let root = PathBuf::from("some").join("dir");
278        let c = cfg().with_data_dir(&root);
279        let p = c.paths().unwrap();
280
281        assert_eq!(
282            p.plugin_dir("myapp-plugin-foo"),
283            root.join("plugins").join("myapp-plugin-foo")
284        );
285        assert_eq!(
286            p.build_dir("myapp-plugin-foo"),
287            root.join("build").join("myapp-plugin-foo")
288        );
289        assert_eq!(
290            p.manifest_path("myapp-plugin-foo", "myapp-plugin.toml"),
291            root.join("plugins")
292                .join("myapp-plugin-foo")
293                .join("myapp-plugin.toml")
294        );
295    }
296
297    #[test]
298    fn with_lock_timeout_replaces_the_default() {
299        let c = cfg().with_lock_timeout(Duration::from_millis(5));
300        assert_eq!(c.lock_timeout, Duration::from_millis(5));
301    }
302}