1use std::cell::RefCell;
21use std::collections::BTreeSet;
22use std::marker::PhantomData;
23use std::path::{Path, PathBuf};
24
25use crate::cache::{now_unix, Index, IndexEntry, InstallSource};
26use crate::config::{KitConfig, KitPaths};
27use crate::error::{KitError, KitResult};
28use crate::install::{self, build_host, prebuilt, Installed};
29use crate::loader::{self, LoadedPlugin};
30use crate::lock::FileLock;
31use crate::manifest::PluginManifest;
32use crate::registry::{CrateInfo, CrateSummary, Registry};
33
34#[derive(Debug, Clone)]
36pub struct PluginInfo {
37 pub name: String,
39 pub crate_name: String,
41 pub version: String,
43 pub family: Option<String>,
45 pub abi: Option<u32>,
47 pub dir: PathBuf,
49 pub source: InstallSource,
51}
52
53pub struct CratePluginKit<T> {
57 cfg: KitConfig,
58 paths: KitPaths,
59 registry: Registry,
60 loaded: RefCell<BTreeSet<String>>,
63 _host: PhantomData<fn() -> T>,
66}
67
68impl<T> CratePluginKit<T> {
69 pub fn new(cfg: KitConfig) -> KitResult<Self> {
71 let paths = cfg.paths()?;
72 std::fs::create_dir_all(&paths.plugins)?;
73 std::fs::create_dir_all(&paths.build)?;
74
75 let registry = Registry::new(&cfg);
76
77 Ok(Self {
78 cfg,
79 paths,
80 registry,
81 loaded: RefCell::new(BTreeSet::new()),
82 _host: PhantomData,
83 })
84 }
85
86 pub fn config(&self) -> &KitConfig {
88 &self.cfg
89 }
90
91 pub fn paths(&self) -> &KitPaths {
93 &self.paths
94 }
95
96 pub fn registry(&self) -> &Registry {
98 &self.registry
99 }
100
101 pub fn install(&self, name: &str, version: Option<&str>) -> KitResult<Installed> {
114 let crate_name = self.cfg.normalize_crate_name(name);
115
116 let _lock = self.lock()?;
117
118 let dir = self.paths.plugin_dir(&crate_name);
119 if dir.is_dir() {
120 return Err(KitError::AlreadyInstalled {
121 name: crate_name,
122 path: dir,
123 });
124 }
125
126 let version = self.resolve_version(&crate_name, version)?;
127 let installed = self.install_locked(&crate_name, &version)?;
128 self.record(&installed)?;
129 Ok(installed)
130 }
131
132 pub fn update(&self, name: &str, version: Option<&str>) -> KitResult<Installed> {
134 let crate_name = self.cfg.normalize_crate_name(name);
135
136 let _lock = self.lock()?;
137
138 let version = self.resolve_version(&crate_name, version)?;
139 let installed = self.install_locked(&crate_name, &version)?;
140 self.record(&installed)?;
141 Ok(installed)
142 }
143
144 pub fn uninstall(&self, name: &str) -> KitResult<()> {
154 let crate_name = self.cfg.normalize_crate_name(name);
155
156 let _lock = self.lock()?;
157
158 let dir = self.paths.plugin_dir(&crate_name);
159 if !dir.is_dir() {
160 return Err(KitError::NotInstalled { name: crate_name });
161 }
162
163 if self.loaded.borrow().contains(&crate_name) {
164 return Err(KitError::PluginInUse {
165 name: crate_name.clone(),
166 });
167 }
168
169 std::fs::remove_dir_all(&dir)?;
170
171 let mut idx = Index::load(&self.paths.index_file);
172 idx.remove(&crate_name);
173 idx.save(&self.paths.index_file)?;
174
175 Ok(())
176 }
177
178 pub fn list(&self) -> KitResult<Vec<PluginInfo>> {
186 let idx = Index::load(&self.paths.index_file);
187 let mut out = Vec::new();
188
189 let entries = match std::fs::read_dir(&self.paths.plugins) {
190 Ok(e) => e,
191 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(out),
192 Err(e) => return Err(e.into()),
193 };
194
195 for entry in entries {
196 let entry = entry?;
197 if !entry.file_type()?.is_dir() {
198 continue;
199 }
200 let crate_name = entry.file_name().to_string_lossy().into_owned();
201
202 let manifest_path = entry.path().join(&self.cfg.manifest_name);
205 let Ok(manifest) = PluginManifest::read(&manifest_path) else {
206 continue;
207 };
208
209 let source = idx.get(&crate_name).map(|e| e.source).unwrap_or_default();
210
211 out.push(PluginInfo {
212 name: manifest.plugin.name.clone(),
213 crate_name,
214 version: manifest.plugin.version.clone(),
215 family: manifest.plugin.family.clone(),
216 abi: manifest.plugin.abi,
217 dir: entry.path(),
218 source,
219 });
220 }
221
222 out.sort_by(|a, b| a.crate_name.cmp(&b.crate_name));
223 Ok(out)
224 }
225
226 pub fn manifest_of(&self, name: &str) -> KitResult<PluginManifest> {
228 let crate_name = self.cfg.normalize_crate_name(name);
229 let path = self
230 .paths
231 .manifest_path(&crate_name, &self.cfg.manifest_name);
232 PluginManifest::read(&path)
233 }
234
235 pub fn resolve(&self, name: &str, relative: impl AsRef<Path>) -> PathBuf {
237 let crate_name = self.cfg.normalize_crate_name(name);
238 self.paths.plugin_dir(&crate_name).join(relative)
239 }
240
241 pub fn load(&self, name: &str) -> KitResult<LoadedPlugin<T>> {
247 let crate_name = self.cfg.normalize_crate_name(name);
248
249 let manifest = self.manifest_of(&crate_name)?;
250 let dir = self.paths.plugin_dir(&crate_name);
251 let stem = manifest.effective_lib_stem(&self.cfg, &crate_name);
252 let lib_path = loader::find_library(&dir, &stem)?;
253
254 let plugin = unsafe { loader::open::<T>(&lib_path, &self.cfg.entry_symbol)? };
258
259 self.loaded.borrow_mut().insert(crate_name);
260 Ok(plugin)
261 }
262
263 pub fn search(&self, keyword: &str, limit: usize) -> KitResult<Vec<CrateSummary>> {
267 self.registry.search(keyword, limit)
268 }
269
270 pub fn view(&self, name: &str) -> KitResult<Option<CrateInfo>> {
272 let crate_name = self.cfg.normalize_crate_name(name);
273 self.registry.view(&crate_name)
274 }
275
276 fn lock(&self) -> KitResult<FileLock> {
279 FileLock::acquire(&self.paths.lock_file, self.cfg.lock_timeout)
280 }
281
282 fn resolve_version(&self, crate_name: &str, version: Option<&str>) -> KitResult<String> {
284 if let Some(v) = version {
285 return Ok(v.to_string());
286 }
287 match self.registry.view(crate_name)? {
288 Some(info) if !info.version.is_empty() => Ok(info.version),
289 Some(_) => Err(KitError::Registry(format!(
290 "no usable version of {crate_name} in the registry"
291 ))),
292 None => Err(KitError::Registry(format!(
293 "{crate_name} was not found in the registry"
294 ))),
295 }
296 }
297
298 fn install_locked(&self, crate_name: &str, version: &str) -> KitResult<Installed> {
300 install::remove_dir_if_exists(&self.paths.plugin_dir(crate_name))?;
302
303 if self.cfg.prefer_prebuilt {
304 match prebuilt::try_install(&self.cfg, &self.paths, &self.registry, crate_name, version)
305 {
306 Ok(Some(installed)) => return Ok(installed),
307 Ok(None) => {}
310 Err(_) => {}
314 }
315 }
316
317 build_host::install(&self.cfg, &self.paths, crate_name, version)
318 }
319
320 fn record(&self, installed: &Installed) -> KitResult<()> {
321 let mut idx = Index::load(&self.paths.index_file);
322
323 let abi = PluginManifest::read(
324 &self
325 .paths
326 .manifest_path(&installed.crate_name, &self.cfg.manifest_name),
327 )
328 .ok()
329 .and_then(|m| m.plugin.abi);
330
331 idx.insert(
332 &installed.crate_name,
333 IndexEntry {
334 version: installed.version.clone(),
335 abi,
336 root: installed.dir.clone(),
337 source: installed.source,
338 installed_at: now_unix(),
339 },
340 );
341 idx.save(&self.paths.index_file)
342 }
343}
344
345#[cfg(test)]
346mod tests {
347 use super::*;
348 use std::time::Duration;
349
350 #[repr(C)]
355 struct FakeEntry {
356 abi_version: u32,
357 }
358
359 const MANIFEST: &str = r#"
360[plugin]
361name = "foo"
362version = "0.1.0"
363abi = 1
364family = "node"
365
366[detect]
367strong = ["fake.lock"]
368"#;
369
370 fn kit(root: &Path) -> CratePluginKit<FakeEntry> {
371 let cfg = KitConfig::new("myapp")
372 .with_data_dir(root)
373 .with_lock_timeout(Duration::from_millis(500));
374 CratePluginKit::new(cfg).expect("should build")
375 }
376
377 fn place_plugin(root: &Path, crate_name: &str) -> PathBuf {
379 let dir = root.join("plugins").join(crate_name);
380 std::fs::create_dir_all(&dir).unwrap();
381 std::fs::write(dir.join("myapp-plugin.toml"), MANIFEST).unwrap();
382 dir
383 }
384
385 #[test]
386 fn new_creates_the_data_directories() {
387 let tmp = tempfile::tempdir().unwrap();
388 let root = tmp.path().join("store");
389
390 let k = kit(&root);
391 assert!(
392 k.paths().plugins.is_dir(),
393 "the plugins dir should have been created"
394 );
395 assert!(
396 k.paths().build.is_dir(),
397 "the build dir should have been created"
398 );
399 }
400
401 #[test]
402 fn a_fresh_store_lists_nothing() {
403 let tmp = tempfile::tempdir().unwrap();
404 let k = kit(&tmp.path().join("store"));
405 assert!(k.list().unwrap().is_empty());
406 }
407
408 #[test]
411 fn list_tolerates_a_missing_plugins_directory() {
412 let tmp = tempfile::tempdir().unwrap();
413 let root = tmp.path().join("store");
414 let k = kit(&root);
415
416 std::fs::remove_dir_all(&root).unwrap();
417 assert!(k.list().unwrap().is_empty());
418 }
419
420 #[test]
424 fn list_reads_manifests_from_disk_not_the_cache() {
425 let tmp = tempfile::tempdir().unwrap();
426 let root = tmp.path().join("store");
427 let k = kit(&root);
428
429 place_plugin(&root, "myapp-plugin-foo");
430
431 let all = k.list().unwrap();
432 assert_eq!(all.len(), 1, "the cache is empty but the disk has a plugin");
433 let info = &all[0];
434 assert_eq!(info.name, "foo");
435 assert_eq!(info.crate_name, "myapp-plugin-foo");
436 assert_eq!(info.version, "0.1.0");
437 assert_eq!(info.abi, Some(1));
438 assert_eq!(info.family.as_deref(), Some("node"));
439 assert_eq!(info.source, InstallSource::BuildHost);
441 }
442
443 #[test]
445 fn list_skips_a_directory_with_a_broken_manifest() {
446 let tmp = tempfile::tempdir().unwrap();
447 let root = tmp.path().join("store");
448 let k = kit(&root);
449
450 place_plugin(&root, "myapp-plugin-good");
451 let bad = root.join("plugins").join("myapp-plugin-bad");
452 std::fs::create_dir_all(&bad).unwrap();
453 std::fs::write(bad.join("myapp-plugin.toml"), "this is not toml").unwrap();
454
455 let empty = root.join("plugins").join("myapp-plugin-empty");
457 std::fs::create_dir_all(&empty).unwrap();
458
459 let all = k.list().unwrap();
460 assert_eq!(all.len(), 1, "only the good one should be listed: {all:?}");
461 assert_eq!(all[0].crate_name, "myapp-plugin-good");
462 }
463
464 #[test]
465 fn list_is_sorted_by_crate_name() {
466 let tmp = tempfile::tempdir().unwrap();
467 let root = tmp.path().join("store");
468 let k = kit(&root);
469
470 for name in ["myapp-plugin-c", "myapp-plugin-a", "myapp-plugin-b"] {
471 place_plugin(&root, name);
472 }
473
474 let names: Vec<_> = k
475 .list()
476 .unwrap()
477 .into_iter()
478 .map(|i| i.crate_name)
479 .collect();
480 assert_eq!(
481 names,
482 vec!["myapp-plugin-a", "myapp-plugin-b", "myapp-plugin-c"]
483 );
484 }
485
486 #[test]
487 fn manifest_of_reads_the_plugin() {
488 let tmp = tempfile::tempdir().unwrap();
489 let root = tmp.path().join("store");
490 let k = kit(&root);
491 place_plugin(&root, "myapp-plugin-foo");
492
493 let m = k
494 .manifest_of("foo")
495 .expect("the short name should work too");
496 assert_eq!(m.plugin.name, "foo");
497 assert!(m.extra.contains_key("detect"), "the host's section is kept");
498 }
499
500 #[test]
501 fn manifest_of_reports_a_missing_plugin() {
502 let tmp = tempfile::tempdir().unwrap();
503 let k = kit(&tmp.path().join("store"));
504 assert!(matches!(
505 k.manifest_of("nope"),
506 Err(KitError::ManifestRead { .. })
507 ));
508 }
509
510 #[test]
511 fn uninstall_reports_a_plugin_that_is_not_installed() {
512 let tmp = tempfile::tempdir().unwrap();
513 let k = kit(&tmp.path().join("store"));
514
515 assert!(matches!(
516 k.uninstall("nope"),
517 Err(KitError::NotInstalled { .. })
518 ));
519 }
520
521 #[test]
522 fn uninstall_removes_the_directory() {
523 let tmp = tempfile::tempdir().unwrap();
524 let root = tmp.path().join("store");
525 let k = kit(&root);
526 let dir = place_plugin(&root, "myapp-plugin-foo");
527
528 assert!(dir.is_dir());
529 k.uninstall("foo").expect("should uninstall");
530 assert!(!dir.exists(), "the directory should have been deleted");
531 assert!(k.list().unwrap().is_empty());
532 }
533
534 #[test]
540 fn install_refuses_when_already_installed() {
541 let tmp = tempfile::tempdir().unwrap();
542 let root = tmp.path().join("store");
543 let k = kit(&root);
544 place_plugin(&root, "myapp-plugin-foo");
545
546 match k.install("foo", Some("0.1.0")) {
547 Err(KitError::AlreadyInstalled { name, .. }) => {
548 assert_eq!(name, "myapp-plugin-foo")
549 }
550 other => panic!("expected AlreadyInstalled, got {other:?}"),
551 }
552 }
553
554 #[test]
555 fn resolve_points_into_the_plugin_directory() {
556 let tmp = tempfile::tempdir().unwrap();
557 let root = tmp.path().join("store");
558 let k = kit(&root);
559
560 assert_eq!(
561 k.resolve("foo", "extra.txt"),
562 root.join("plugins")
563 .join("myapp-plugin-foo")
564 .join("extra.txt")
565 );
566 assert_eq!(k.resolve("foo", "x"), k.resolve("myapp-plugin-foo", "x"));
568 }
569
570 #[test]
571 fn config_is_exposed() {
572 let tmp = tempfile::tempdir().unwrap();
573 let k = kit(&tmp.path().join("store"));
574 assert_eq!(k.config().id, "myapp");
575 assert_eq!(k.config().crate_prefix, "myapp-plugin-");
576 }
577}