Skip to main content

crate_plugin_kit/config/
mod.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//!
7//! # Layout
8//!
9//! Naming lives here, because every name is derived from the same few fields and they
10//! have to stay consistent. The paths those names are resolved against — the data dir
11//! and the files inside it — are in `paths`.
12
13use std::collections::BTreeMap;
14use std::path::PathBuf;
15use std::time::Duration;
16
17use crate::error::KitResult;
18
19mod paths;
20
21pub use paths::KitPaths;
22
23/// Default lock wait time.
24pub const DEFAULT_LOCK_TIMEOUT: Duration = Duration::from_secs(30);
25
26/// Every configurable item of a kit instance.
27#[derive(Debug, Clone)]
28pub struct KitConfig {
29    /// Application id. Determines the data dir `~/.{id}`, and is part of the default
30    /// HTTP User-Agent.
31    pub id: String,
32
33    /// File name of the plugin manifest, such as `"bmux-plugin.toml"`.
34    ///
35    /// The `[plugin]` and `[lib]` sections of the manifest are defined by this crate
36    /// (see [`crate::manifest`]). A host may append its own sections to the same file
37    /// (for example bmux's `[detect]`); this crate ignores them.
38    pub manifest_name: String,
39
40    /// Plugin crate name prefix, such as `"bmux-plugin-"`.
41    ///
42    /// `install("cargo")` first expands to `"bmux-plugin-cargo"`; a name that already
43    /// carries the prefix is used as-is.
44    pub crate_prefix: String,
45
46    /// Entry symbol exported by the cdylib, such as `b"bmux_plugin_entry_v1"`.
47    pub entry_symbol: Vec<u8>,
48
49    /// Prefix of the cdylib file name stem, such as `"bmux_plugin_"`.
50    ///
51    /// Concatenated with the crate name minus its prefix, then given the platform
52    /// extension, this yields the actual file name.
53    /// Example: `bmux-plugin-cargo` → `bmux_plugin_` + `cargo` → `libbmux_plugin_cargo.so`.
54    pub lib_stem_prefix: String,
55
56    /// Name of the host's contract crate, such as `"bmux-plugin"`. The generated
57    /// wrapper project depends on it.
58    pub contract_crate: String,
59
60    /// Fallback version requirement for the contract crate, such as `"0.1"`.
61    ///
62    /// Normally unused. The wrapper repeats whatever the plugin crate's own manifest requires
63    /// of the contract crate, which is the only way to guarantee both resolve to one version:
64    /// cargo treats differently-versioned copies as distinct crates, each with its own traits,
65    /// and will not merge them even when a single version satisfies both requirements. This
66    /// value is only consulted when the plugin's manifest declares no such dependency.
67    pub contract_version: String,
68
69    /// Edition used by the generated wrapper project.
70    pub wrapper_edition: String,
71
72    /// Template for the wrapper project's `src/lib.rs`.
73    ///
74    /// `{crate_ident}` is replaced with the plugin crate's ident (`-` becomes `_`).
75    /// Example (bmux): `"bmux_plugin::export!({crate_ident}::create);\n"`
76    pub wrapper_body: String,
77
78    /// Data dir override. `None` = use `~/.{id}`.
79    pub data_dir: Option<PathBuf>,
80
81    /// Timeout for waiting on the install lock.
82    pub lock_timeout: Duration,
83
84    /// Whether to try prebuilt artifacts first when installing.
85    pub prefer_prebuilt: bool,
86
87    /// Override for the target triple. `None` = use the triple injected at compile
88    /// time (see `build.rs`).
89    pub target_triple: Option<String>,
90
91    /// crates.io index address. May point at a mirror.
92    pub registry: String,
93
94    /// Local path overrides: crate name → local directory.
95    ///
96    /// Written into the generated wrapper project as its `[patch.crates-io]`. For
97    /// development use: the wrapper lives under `~/.{id}/build/` and cannot see the
98    /// host project's `.cargo/config.toml`, so local overrides must be passed
99    /// explicitly here. Leave empty in production.
100    pub local_overrides: BTreeMap<String, PathBuf>,
101}
102
103impl KitConfig {
104    /// Starts a config from the minimum amount of information, with conservative
105    /// defaults for the rest.
106    ///
107    /// All defaults are derived from `id` and are mutually consistent — for example
108    /// `id = "myapp"` yields:
109    ///
110    /// | Field | Value |
111    /// | ---- | -- |
112    /// | `manifest_name` | `myapp-plugin.toml` |
113    /// | `crate_prefix` | `myapp-plugin-` |
114    /// | `lib_stem_prefix` | `myapp_plugin_` |
115    /// | `entry_symbol` | `myapp_plugin_entry_v1` |
116    /// | `contract_crate` | `myapp-plugin` |
117    ///
118    /// `wrapper_body` still has to be filled in by hand when the contract crate's path differs
119    /// from the derivation above. `contract_version` does not: it is a fallback, and the wrapper
120    /// normally repeats whatever the plugin crate's own manifest requires.
121    ///
122    /// `entry_symbol` does not need a trailing NUL — `libloading` adds it.
123    pub fn new(id: impl Into<String>) -> Self {
124        let id = id.into();
125        let snake = id.replace('-', "_");
126        Self {
127            manifest_name: format!("{id}-plugin.toml"),
128            crate_prefix: format!("{id}-plugin-"),
129            entry_symbol: format!("{snake}_plugin_entry_v1").into_bytes(),
130            lib_stem_prefix: format!("{snake}_plugin_"),
131            contract_crate: format!("{id}-plugin"),
132            contract_version: "0.1".to_string(),
133            wrapper_edition: "2021".to_string(),
134            wrapper_body: format!("{snake}_plugin::export!({{crate_ident}}::create);\n"),
135            data_dir: None,
136            lock_timeout: DEFAULT_LOCK_TIMEOUT,
137            prefer_prebuilt: true,
138            target_triple: None,
139            registry: "https://crates.io".to_string(),
140            local_overrides: BTreeMap::new(),
141            id,
142        }
143    }
144
145    /// Overrides the data dir.
146    pub fn with_data_dir(mut self, dir: impl Into<PathBuf>) -> Self {
147        self.data_dir = Some(dir.into());
148        self
149    }
150
151    /// Overrides the lock wait time.
152    pub fn with_lock_timeout(mut self, t: Duration) -> Self {
153        self.lock_timeout = t;
154        self
155    }
156
157    /// Target triple of this build. The configured override wins.
158    pub fn effective_target(&self) -> &str {
159        self.target_triple
160            .as_deref()
161            .unwrap_or(crate::TARGET_TRIPLE)
162    }
163
164    /// Normalizes the name passed to `install()` into a full crate name.
165    ///
166    /// A name that already carries the prefix is returned as-is; otherwise the
167    /// prefix is prepended.
168    pub fn normalize_crate_name(&self, name: &str) -> String {
169        if name.starts_with(&self.crate_prefix) {
170            name.to_string()
171        } else {
172            format!("{}{}", self.crate_prefix, name)
173        }
174    }
175
176    /// Derives the cdylib file name stem (without the `lib` prefix and extension)
177    /// from a crate name.
178    ///
179    /// `bmux-plugin-cargo` → `bmux_plugin_cargo`
180    pub fn lib_stem(&self, crate_name: &str) -> String {
181        let tail = crate_name
182            .strip_prefix(&self.crate_prefix)
183            .unwrap_or(crate_name);
184        format!("{}{}", self.lib_stem_prefix, tail.replace('-', "_"))
185    }
186
187    /// Resolves the various paths. Creates directories as needed.
188    pub fn paths(&self) -> KitResult<KitPaths> {
189        KitPaths::resolve(self)
190    }
191}
192
193#[cfg(test)]
194mod tests {
195    use super::*;
196
197    fn cfg() -> KitConfig {
198        KitConfig::new("myapp")
199    }
200
201    #[test]
202    fn new_derives_names_from_the_id() {
203        let c = cfg();
204        assert_eq!(c.id, "myapp");
205        assert_eq!(c.manifest_name, "myapp-plugin.toml");
206        assert_eq!(c.crate_prefix, "myapp-plugin-");
207        assert_eq!(c.lib_stem_prefix, "myapp_plugin_");
208        assert_eq!(c.contract_crate, "myapp-plugin");
209    }
210
211    #[test]
212    fn normalizes_short_and_full_crate_names() {
213        let c = cfg();
214        assert_eq!(c.normalize_crate_name("foo"), "myapp-plugin-foo");
215        // A name that already carries the prefix is returned as-is, otherwise it
216        // would become myapp-plugin-myapp-plugin-foo
217        assert_eq!(
218            c.normalize_crate_name("myapp-plugin-foo"),
219            "myapp-plugin-foo"
220        );
221    }
222
223    #[test]
224    fn derives_lib_stem_from_crate_name() {
225        let c = cfg();
226        assert_eq!(c.lib_stem("myapp-plugin-foo"), "myapp_plugin_foo");
227        // Hyphens become underscores
228        assert_eq!(c.lib_stem("myapp-plugin-a-b"), "myapp_plugin_a_b");
229    }
230
231    #[test]
232    fn target_falls_back_to_compile_time_triple() {
233        let c = cfg();
234        assert_eq!(c.effective_target(), crate::TARGET_TRIPLE);
235
236        let mut overridden = cfg();
237        overridden.target_triple = Some("aarch64-apple-darwin".to_string());
238        assert_eq!(overridden.effective_target(), "aarch64-apple-darwin");
239    }
240
241    #[test]
242    fn with_lock_timeout_replaces_the_default() {
243        let c = cfg().with_lock_timeout(Duration::from_millis(5));
244        assert_eq!(c.lock_timeout, Duration::from_millis(5));
245    }
246}