registry.rs

 1use std::sync::Arc;
 2
 3use collections::HashMap;
 4use gpui::{AppContext, Global, ReadGlobal};
 5use parking_lot::RwLock;
 6
 7struct GlobalContextServerRegistry(Arc<ContextServerRegistry>);
 8
 9impl Global for GlobalContextServerRegistry {}
10
11pub struct ContextServerRegistry {
12    registry: RwLock<HashMap<String, Vec<Arc<str>>>>,
13}
14
15impl ContextServerRegistry {
16    pub fn global(cx: &AppContext) -> Arc<Self> {
17        GlobalContextServerRegistry::global(cx).0.clone()
18    }
19
20    pub fn register(cx: &mut AppContext) {
21        cx.set_global(GlobalContextServerRegistry(Arc::new(
22            ContextServerRegistry {
23                registry: RwLock::new(HashMap::default()),
24            },
25        )))
26    }
27
28    pub fn register_command(&self, server_id: String, command_name: &str) {
29        let mut registry = self.registry.write();
30        registry
31            .entry(server_id)
32            .or_default()
33            .push(command_name.into());
34    }
35
36    pub fn unregister_command(&self, server_id: &str, command_name: &str) {
37        let mut registry = self.registry.write();
38        if let Some(commands) = registry.get_mut(server_id) {
39            commands.retain(|name| name.as_ref() != command_name);
40        }
41    }
42
43    pub fn get_commands(&self, server_id: &str) -> Option<Vec<Arc<str>>> {
44        let registry = self.registry.read();
45        registry.get(server_id).cloned()
46    }
47}