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 /// Fallback version requirement for the contract crate, such as `"0.1"`.
51 ///
52 /// Normally unused. The wrapper repeats whatever the plugin crate's own manifest requires
53 /// of the contract crate, which is the only way to guarantee both resolve to one version:
54 /// cargo treats differently-versioned copies as distinct crates, each with its own traits,
55 /// and will not merge them even when a single version satisfies both requirements. This
56 /// value is only consulted when the plugin's manifest declares no such dependency.
57 pub contract_version: String,
58
59 /// Edition used by the generated wrapper project.
60 pub wrapper_edition: String,
61
62 /// Template for the wrapper project's `src/lib.rs`.
63 ///
64 /// `{crate_ident}` is replaced with the plugin crate's ident (`-` becomes `_`).
65 /// Example (bmux): `"bmux_plugin::export!({crate_ident}::create);\n"`
66 pub wrapper_body: String,
67
68 /// Data dir override. `None` = use `~/.{id}`.
69 pub data_dir: Option<PathBuf>,
70
71 /// Timeout for waiting on the install lock.
72 pub lock_timeout: Duration,
73
74 /// Whether to try prebuilt artifacts first when installing.
75 pub prefer_prebuilt: bool,
76
77 /// Override for the target triple. `None` = use the triple injected at compile
78 /// time (see `build.rs`).
79 pub target_triple: Option<String>,
80
81 /// crates.io index address. May point at a mirror.
82 pub registry: String,
83
84 /// Local path overrides: crate name → local directory.
85 ///
86 /// Written into the generated wrapper project as its `[patch.crates-io]`. For
87 /// development use: the wrapper lives under `~/.{id}/build/` and cannot see the
88 /// host project's `.cargo/config.toml`, so local overrides must be passed
89 /// explicitly here. Leave empty in production.
90 pub local_overrides: BTreeMap<String, PathBuf>,
91}
92
93impl KitConfig {
94 /// Starts a config from the minimum amount of information, with conservative
95 /// defaults for the rest.
96 ///
97 /// All defaults are derived from `id` and are mutually consistent — for example
98 /// `id = "myapp"` yields:
99 ///
100 /// | Field | Value |
101 /// | ---- | -- |
102 /// | `manifest_name` | `myapp-plugin.toml` |
103 /// | `crate_prefix` | `myapp-plugin-` |
104 /// | `lib_stem_prefix` | `myapp_plugin_` |
105 /// | `entry_symbol` | `myapp_plugin_entry_v1` |
106 /// | `contract_crate` | `myapp-plugin` |
107 ///
108 /// `wrapper_body` still has to be filled in by hand when the contract crate's path differs
109 /// from the derivation above. `contract_version` does not: it is a fallback, and the wrapper
110 /// normally repeats whatever the plugin crate's own manifest requires.
111 ///
112 /// `entry_symbol` does not need a trailing NUL — `libloading` adds it.
113 pub fn new(id: impl Into<String>) -> Self {
114 let id = id.into();
115 let snake = id.replace('-', "_");
116 Self {
117 manifest_name: format!("{id}-plugin.toml"),
118 crate_prefix: format!("{id}-plugin-"),
119 entry_symbol: format!("{snake}_plugin_entry_v1").into_bytes(),
120 lib_stem_prefix: format!("{snake}_plugin_"),
121 contract_crate: format!("{id}-plugin"),
122 contract_version: "0.1".to_string(),
123 wrapper_edition: "2021".to_string(),
124 wrapper_body: format!("{snake}_plugin::export!({{crate_ident}}::create);\n"),
125 data_dir: None,
126 lock_timeout: DEFAULT_LOCK_TIMEOUT,
127 prefer_prebuilt: true,
128 target_triple: None,
129 registry: "https://crates.io".to_string(),
130 local_overrides: BTreeMap::new(),
131 id,
132 }
133 }
134
135 /// Overrides the data dir.
136 pub fn with_data_dir(mut self, dir: impl Into<PathBuf>) -> Self {
137 self.data_dir = Some(dir.into());
138 self
139 }
140
141 /// Overrides the lock wait time.
142 pub fn with_lock_timeout(mut self, t: Duration) -> Self {
143 self.lock_timeout = t;
144 self
145 }
146
147 /// Target triple of this build. The configured override wins.
148 pub fn effective_target(&self) -> &str {
149 self.target_triple
150 .as_deref()
151 .unwrap_or(crate::TARGET_TRIPLE)
152 }
153
154 /// Normalizes the name passed to `install()` into a full crate name.
155 ///
156 /// A name that already carries the prefix is returned as-is; otherwise the
157 /// prefix is prepended.
158 pub fn normalize_crate_name(&self, name: &str) -> String {
159 if name.starts_with(&self.crate_prefix) {
160 name.to_string()
161 } else {
162 format!("{}{}", self.crate_prefix, name)
163 }
164 }
165
166 /// Derives the cdylib file name stem (without the `lib` prefix and extension)
167 /// from a crate name.
168 ///
169 /// `bmux-plugin-cargo` → `bmux_plugin_cargo`
170 pub fn lib_stem(&self, crate_name: &str) -> String {
171 let tail = crate_name
172 .strip_prefix(&self.crate_prefix)
173 .unwrap_or(crate_name);
174 format!("{}{}", self.lib_stem_prefix, tail.replace('-', "_"))
175 }
176
177 /// Resolves the various paths. Creates directories as needed.
178 pub fn paths(&self) -> KitResult<KitPaths> {
179 let root = match &self.data_dir {
180 Some(d) => d.clone(),
181 None => default_data_dir(&self.id)?,
182 };
183 Ok(KitPaths {
184 plugins: root.join("plugins"),
185 build: root.join("build"),
186 lock_file: root.join(".lock"),
187 index_file: root.join("plugins").join(".plugins.json"),
188 root,
189 })
190 }
191}
192
193/// Default data dir `~/.{id}`, as determined by `directories`.
194fn default_data_dir(id: &str) -> KitResult<PathBuf> {
195 let home = directories::UserDirs::new()
196 .map(|d| d.home_dir().to_path_buf())
197 .ok_or(KitError::NoDataDir)?;
198 Ok(home.join(format!(".{id}")))
199}
200
201/// All paths the kit uses.
202#[derive(Debug, Clone)]
203pub struct KitPaths {
204 /// `<data-dir>` itself.
205 pub root: PathBuf,
206 /// Install dir of installed plugins, `<root>/plugins`.
207 pub plugins: PathBuf,
208 /// build-host scaffolding directory, `<root>/build`.
209 pub build: PathBuf,
210 /// Install exclusive lock file, `<root>/.lock`.
211 pub lock_file: PathBuf,
212 /// Install record cache, `<root>/plugins/.plugins.json`.
213 pub index_file: PathBuf,
214}
215
216impl KitPaths {
217 /// Install dir of one plugin, `<plugins>/<crate_name>`.
218 pub fn plugin_dir(&self, crate_name: &str) -> PathBuf {
219 self.plugins.join(crate_name)
220 }
221
222 /// Manifest path of one plugin.
223 pub fn manifest_path(&self, crate_name: &str, manifest_name: &str) -> PathBuf {
224 self.plugin_dir(crate_name).join(manifest_name)
225 }
226
227 /// build-host scaffolding directory of one plugin.
228 pub fn build_dir(&self, crate_name: &str) -> PathBuf {
229 self.build.join(crate_name)
230 }
231}
232
233#[cfg(test)]
234mod tests {
235 use super::*;
236
237 fn cfg() -> KitConfig {
238 KitConfig::new("myapp")
239 }
240
241 #[test]
242 fn new_derives_names_from_the_id() {
243 let c = cfg();
244 assert_eq!(c.id, "myapp");
245 assert_eq!(c.manifest_name, "myapp-plugin.toml");
246 assert_eq!(c.crate_prefix, "myapp-plugin-");
247 assert_eq!(c.lib_stem_prefix, "myapp_plugin_");
248 assert_eq!(c.contract_crate, "myapp-plugin");
249 }
250
251 #[test]
252 fn normalizes_short_and_full_crate_names() {
253 let c = cfg();
254 assert_eq!(c.normalize_crate_name("foo"), "myapp-plugin-foo");
255 // A name that already carries the prefix is returned as-is, otherwise it
256 // would become myapp-plugin-myapp-plugin-foo
257 assert_eq!(
258 c.normalize_crate_name("myapp-plugin-foo"),
259 "myapp-plugin-foo"
260 );
261 }
262
263 #[test]
264 fn derives_lib_stem_from_crate_name() {
265 let c = cfg();
266 assert_eq!(c.lib_stem("myapp-plugin-foo"), "myapp_plugin_foo");
267 // Hyphens become underscores
268 assert_eq!(c.lib_stem("myapp-plugin-a-b"), "myapp_plugin_a_b");
269 }
270
271 #[test]
272 fn target_falls_back_to_compile_time_triple() {
273 let c = cfg();
274 assert_eq!(c.effective_target(), crate::TARGET_TRIPLE);
275
276 let mut overridden = cfg();
277 overridden.target_triple = Some("aarch64-apple-darwin".to_string());
278 assert_eq!(overridden.effective_target(), "aarch64-apple-darwin");
279 }
280
281 #[test]
282 fn paths_honour_the_data_dir_override() {
283 let root = PathBuf::from("some").join("dir");
284 let c = cfg().with_data_dir(&root);
285 let p = c.paths().expect("must not touch HOME when overridden");
286
287 assert_eq!(p.root, root);
288 assert_eq!(p.plugins, root.join("plugins"));
289 assert_eq!(p.build, root.join("build"));
290 assert_eq!(p.lock_file, root.join(".lock"));
291 assert_eq!(p.index_file, root.join("plugins").join(".plugins.json"));
292 }
293
294 #[test]
295 fn plugin_paths_sit_under_the_plugins_dir() {
296 let root = PathBuf::from("some").join("dir");
297 let c = cfg().with_data_dir(&root);
298 let p = c.paths().unwrap();
299
300 assert_eq!(
301 p.plugin_dir("myapp-plugin-foo"),
302 root.join("plugins").join("myapp-plugin-foo")
303 );
304 assert_eq!(
305 p.build_dir("myapp-plugin-foo"),
306 root.join("build").join("myapp-plugin-foo")
307 );
308 assert_eq!(
309 p.manifest_path("myapp-plugin-foo", "myapp-plugin.toml"),
310 root.join("plugins")
311 .join("myapp-plugin-foo")
312 .join("myapp-plugin.toml")
313 );
314 }
315
316 #[test]
317 fn with_lock_timeout_replaces_the_default() {
318 let c = cfg().with_lock_timeout(Duration::from_millis(5));
319 assert_eq!(c.lock_timeout, Duration::from_millis(5));
320 }
321}