Skip to main content

crate_plugin_kit/
config.rs

1//! [`KitConfig`]: parametrizes every host-application-specific name used by a kit
2//! instance.
3//!
4//! No host application name is hardcoded anywhere in this crate. Everything like
5//! `bmux` / `bmux-plugin.toml` / `bmux_plugin_entry_v1` is supplied here.
6
7use std::collections::BTreeMap;
8use std::path::PathBuf;
9use std::time::Duration;
10
11use crate::error::{KitError, KitResult};
12
13/// Default lock wait time.
14pub const DEFAULT_LOCK_TIMEOUT: Duration = Duration::from_secs(30);
15
16/// Every configurable item of a kit instance.
17#[derive(Debug, Clone)]
18pub struct KitConfig {
19    /// Application id. Determines the data dir `~/.{id}`, and is part of the default
20    /// HTTP User-Agent.
21    pub id: String,
22
23    /// File name of the plugin manifest, such as `"bmux-plugin.toml"`.
24    ///
25    /// The `[plugin]` and `[lib]` sections of the manifest are defined by this crate
26    /// (see [`crate::manifest`]). A host may append its own sections to the same file
27    /// (for example bmux's `[detect]`); this crate ignores them.
28    pub manifest_name: String,
29
30    /// Plugin crate name prefix, such as `"bmux-plugin-"`.
31    ///
32    /// `install("cargo")` first expands to `"bmux-plugin-cargo"`; a name that already
33    /// carries the prefix is used as-is.
34    pub crate_prefix: String,
35
36    /// Entry symbol exported by the cdylib, such as `b"bmux_plugin_entry_v1"`.
37    pub entry_symbol: Vec<u8>,
38
39    /// Prefix of the cdylib file name stem, such as `"bmux_plugin_"`.
40    ///
41    /// Concatenated with the crate name minus its prefix, then given the platform
42    /// extension, this yields the actual file name.
43    /// Example: `bmux-plugin-cargo` → `bmux_plugin_` + `cargo` → `libbmux_plugin_cargo.so`.
44    pub lib_stem_prefix: String,
45
46    /// Name of the host's contract crate, such as `"bmux-plugin"`. The generated
47    /// wrapper project depends on it.
48    pub contract_crate: String,
49
50    /// Version requirement for the contract crate, such as `"0.1"`.
51    pub contract_version: String,
52
53    /// Edition used by the generated wrapper project.
54    pub wrapper_edition: String,
55
56    /// Template for the wrapper project's `src/lib.rs`.
57    ///
58    /// `{crate_ident}` is replaced with the plugin crate's ident (`-` becomes `_`).
59    /// Example (bmux): `"bmux_plugin::export!({crate_ident}::create);\n"`
60    pub wrapper_body: String,
61
62    /// Data dir override. `None` = use `~/.{id}`.
63    pub data_dir: Option<PathBuf>,
64
65    /// Timeout for waiting on the install lock.
66    pub lock_timeout: Duration,
67
68    /// Whether to try prebuilt artifacts first when installing.
69    pub prefer_prebuilt: bool,
70
71    /// Override for the target triple. `None` = use the triple injected at compile
72    /// time (see `build.rs`).
73    pub target_triple: Option<String>,
74
75    /// crates.io index address. May point at a mirror.
76    pub registry: String,
77
78    /// Local path overrides: crate name → local directory.
79    ///
80    /// Written into the generated wrapper project as its `[patch.crates-io]`. For
81    /// development use: the wrapper lives under `~/.{id}/build/` and cannot see the
82    /// host project's `.cargo/config.toml`, so local overrides must be passed
83    /// explicitly here. Leave empty in production.
84    pub local_overrides: BTreeMap<String, PathBuf>,
85}
86
87impl KitConfig {
88    /// Starts a config from the minimum amount of information, with conservative
89    /// defaults for the rest.
90    ///
91    /// All defaults are derived from `id` and are mutually consistent — for example
92    /// `id = "myapp"` yields:
93    ///
94    /// | Field | Value |
95    /// | ---- | -- |
96    /// | `manifest_name` | `myapp-plugin.toml` |
97    /// | `crate_prefix` | `myapp-plugin-` |
98    /// | `lib_stem_prefix` | `myapp_plugin_` |
99    /// | `entry_symbol` | `myapp_plugin_entry_v1` |
100    /// | `contract_crate` | `myapp-plugin` |
101    ///
102    /// `wrapper_body` (its paths come from the host's contract crate) and
103    /// `contract_version` still have to be filled in by hand.
104    ///
105    /// `entry_symbol` does not need a trailing NUL — `libloading` adds it.
106    pub fn new(id: impl Into<String>) -> Self {
107        let id = id.into();
108        let snake = id.replace('-', "_");
109        Self {
110            manifest_name: format!("{id}-plugin.toml"),
111            crate_prefix: format!("{id}-plugin-"),
112            entry_symbol: format!("{snake}_plugin_entry_v1").into_bytes(),
113            lib_stem_prefix: format!("{snake}_plugin_"),
114            contract_crate: format!("{id}-plugin"),
115            contract_version: "0.1".to_string(),
116            wrapper_edition: "2021".to_string(),
117            wrapper_body: format!("{snake}_plugin::export!({{crate_ident}}::create);\n"),
118            data_dir: None,
119            lock_timeout: DEFAULT_LOCK_TIMEOUT,
120            prefer_prebuilt: true,
121            target_triple: None,
122            registry: "https://crates.io".to_string(),
123            local_overrides: BTreeMap::new(),
124            id,
125        }
126    }
127
128    /// Overrides the data dir.
129    pub fn with_data_dir(mut self, dir: impl Into<PathBuf>) -> Self {
130        self.data_dir = Some(dir.into());
131        self
132    }
133
134    /// Overrides the lock wait time.
135    pub fn with_lock_timeout(mut self, t: Duration) -> Self {
136        self.lock_timeout = t;
137        self
138    }
139
140    /// Target triple of this build. The configured override wins.
141    pub fn effective_target(&self) -> &str {
142        self.target_triple
143            .as_deref()
144            .unwrap_or(crate::TARGET_TRIPLE)
145    }
146
147    /// Normalizes the name passed to `install()` into a full crate name.
148    ///
149    /// A name that already carries the prefix is returned as-is; otherwise the
150    /// prefix is prepended.
151    pub fn normalize_crate_name(&self, name: &str) -> String {
152        if name.starts_with(&self.crate_prefix) {
153            name.to_string()
154        } else {
155            format!("{}{}", self.crate_prefix, name)
156        }
157    }
158
159    /// Derives the cdylib file name stem (without the `lib` prefix and extension)
160    /// from a crate name.
161    ///
162    /// `bmux-plugin-cargo` → `bmux_plugin_cargo`
163    pub fn lib_stem(&self, crate_name: &str) -> String {
164        let tail = crate_name
165            .strip_prefix(&self.crate_prefix)
166            .unwrap_or(crate_name);
167        format!("{}{}", self.lib_stem_prefix, tail.replace('-', "_"))
168    }
169
170    /// Resolves the various paths. Creates directories as needed.
171    pub fn paths(&self) -> KitResult<KitPaths> {
172        let root = match &self.data_dir {
173            Some(d) => d.clone(),
174            None => default_data_dir(&self.id)?,
175        };
176        Ok(KitPaths {
177            plugins: root.join("plugins"),
178            build: root.join("build"),
179            lock_file: root.join(".lock"),
180            index_file: root.join("plugins").join(".plugins.json"),
181            root,
182        })
183    }
184}
185
186/// Default data dir `~/.{id}`, as determined by `directories`.
187fn default_data_dir(id: &str) -> KitResult<PathBuf> {
188    let home = directories::UserDirs::new()
189        .map(|d| d.home_dir().to_path_buf())
190        .ok_or(KitError::NoDataDir)?;
191    Ok(home.join(format!(".{id}")))
192}
193
194/// All paths the kit uses.
195#[derive(Debug, Clone)]
196pub struct KitPaths {
197    /// `<data-dir>` itself.
198    pub root: PathBuf,
199    /// Install dir of installed plugins, `<root>/plugins`.
200    pub plugins: PathBuf,
201    /// build-host scaffolding directory, `<root>/build`.
202    pub build: PathBuf,
203    /// Install exclusive lock file, `<root>/.lock`.
204    pub lock_file: PathBuf,
205    /// Install record cache, `<root>/plugins/.plugins.json`.
206    pub index_file: PathBuf,
207}
208
209impl KitPaths {
210    /// Install dir of one plugin, `<plugins>/<crate_name>`.
211    pub fn plugin_dir(&self, crate_name: &str) -> PathBuf {
212        self.plugins.join(crate_name)
213    }
214
215    /// Manifest path of one plugin.
216    pub fn manifest_path(&self, crate_name: &str, manifest_name: &str) -> PathBuf {
217        self.plugin_dir(crate_name).join(manifest_name)
218    }
219
220    /// build-host scaffolding directory of one plugin.
221    pub fn build_dir(&self, crate_name: &str) -> PathBuf {
222        self.build.join(crate_name)
223    }
224}
225
226#[cfg(test)]
227mod tests {
228    use super::*;
229
230    fn cfg() -> KitConfig {
231        KitConfig::new("myapp")
232    }
233
234    #[test]
235    fn new_derives_names_from_the_id() {
236        let c = cfg();
237        assert_eq!(c.id, "myapp");
238        assert_eq!(c.manifest_name, "myapp-plugin.toml");
239        assert_eq!(c.crate_prefix, "myapp-plugin-");
240        assert_eq!(c.lib_stem_prefix, "myapp_plugin_");
241        assert_eq!(c.contract_crate, "myapp-plugin");
242    }
243
244    #[test]
245    fn normalizes_short_and_full_crate_names() {
246        let c = cfg();
247        assert_eq!(c.normalize_crate_name("foo"), "myapp-plugin-foo");
248        // A name that already carries the prefix is returned as-is, otherwise it
249        // would become myapp-plugin-myapp-plugin-foo
250        assert_eq!(
251            c.normalize_crate_name("myapp-plugin-foo"),
252            "myapp-plugin-foo"
253        );
254    }
255
256    #[test]
257    fn derives_lib_stem_from_crate_name() {
258        let c = cfg();
259        assert_eq!(c.lib_stem("myapp-plugin-foo"), "myapp_plugin_foo");
260        // Hyphens become underscores
261        assert_eq!(c.lib_stem("myapp-plugin-a-b"), "myapp_plugin_a_b");
262    }
263
264    #[test]
265    fn target_falls_back_to_compile_time_triple() {
266        let c = cfg();
267        assert_eq!(c.effective_target(), crate::TARGET_TRIPLE);
268
269        let mut overridden = cfg();
270        overridden.target_triple = Some("aarch64-apple-darwin".to_string());
271        assert_eq!(overridden.effective_target(), "aarch64-apple-darwin");
272    }
273
274    #[test]
275    fn paths_honour_the_data_dir_override() {
276        let root = PathBuf::from("some").join("dir");
277        let c = cfg().with_data_dir(&root);
278        let p = c.paths().expect("must not touch HOME when overridden");
279
280        assert_eq!(p.root, root);
281        assert_eq!(p.plugins, root.join("plugins"));
282        assert_eq!(p.build, root.join("build"));
283        assert_eq!(p.lock_file, root.join(".lock"));
284        assert_eq!(p.index_file, root.join("plugins").join(".plugins.json"));
285    }
286
287    #[test]
288    fn plugin_paths_sit_under_the_plugins_dir() {
289        let root = PathBuf::from("some").join("dir");
290        let c = cfg().with_data_dir(&root);
291        let p = c.paths().unwrap();
292
293        assert_eq!(
294            p.plugin_dir("myapp-plugin-foo"),
295            root.join("plugins").join("myapp-plugin-foo")
296        );
297        assert_eq!(
298            p.build_dir("myapp-plugin-foo"),
299            root.join("build").join("myapp-plugin-foo")
300        );
301        assert_eq!(
302            p.manifest_path("myapp-plugin-foo", "myapp-plugin.toml"),
303            root.join("plugins")
304                .join("myapp-plugin-foo")
305                .join("myapp-plugin.toml")
306        );
307    }
308
309    #[test]
310    fn with_lock_timeout_replaces_the_default() {
311        let c = cfg().with_lock_timeout(Duration::from_millis(5));
312        assert_eq!(c.lock_timeout, Duration::from_millis(5));
313    }
314}