pipedash_plugin_api/
registry.rs1use std::collections::HashMap;
2
3use crate::metadata::{
4 PluginManifest,
5 PluginMetadata,
6};
7use crate::plugin::Plugin;
8
9struct Registration {
10 plugin: Box<dyn Plugin>,
11 metadata: PluginMetadata,
12 create: fn() -> Box<dyn Plugin>,
13}
14
15pub struct PluginRegistry {
16 plugins: HashMap<String, Registration>,
17}
18
19impl PluginRegistry {
20 pub fn new() -> Self {
21 Self {
22 plugins: HashMap::new(),
23 }
24 }
25
26 pub fn register(&mut self, create: fn() -> Box<dyn Plugin>, manifest: PluginManifest) {
27 let plugin = create();
28 let mut metadata = plugin.metadata().clone();
29 manifest.apply(&mut metadata);
30 self.plugins.insert(
31 manifest.provider_type().to_string(),
32 Registration {
33 plugin,
34 metadata,
35 create,
36 },
37 );
38 }
39
40 pub fn get(&self, provider_type: &str) -> Option<&dyn Plugin> {
41 self.plugins
42 .get(provider_type)
43 .map(|registration| registration.plugin.as_ref())
44 }
45
46 pub fn create(&self, provider_type: &str) -> Option<Box<dyn Plugin>> {
47 self.plugins
48 .get(provider_type)
49 .map(|registration| (registration.create)())
50 }
51
52 pub fn metadata(&self) -> impl Iterator<Item = &PluginMetadata> {
53 self.plugins
54 .values()
55 .map(|registration| ®istration.metadata)
56 }
57
58 pub fn metadata_of(&self, provider_type: &str) -> Option<&PluginMetadata> {
59 self.plugins
60 .get(provider_type)
61 .map(|registration| ®istration.metadata)
62 }
63
64 pub fn is_registered(&self, provider_type: &str) -> bool {
65 self.plugins.contains_key(provider_type)
66 }
67
68 pub fn provider_types(&self) -> Vec<String> {
69 self.plugins.keys().cloned().collect()
70 }
71
72 pub fn count(&self) -> usize {
73 self.plugins.len()
74 }
75}
76
77impl Default for PluginRegistry {
78 fn default() -> Self {
79 Self::new()
80 }
81}
82
83#[cfg(test)]
84mod tests;