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