1use std::{path::Path, sync::Arc};
2
3use anyhow::Result;
4use collections::HashMap;
5use gpui::{App, Global, ReadGlobal, UpdateGlobal};
6use parking_lot::RwLock;
7use util::ResultExt;
8
9use crate::{Snippet, SnippetKind, file_stem_to_key};
10
11struct GlobalSnippetRegistry(Arc<SnippetRegistry>);
12
13impl Global for GlobalSnippetRegistry {}
14
15#[derive(Default)]
16pub struct SnippetRegistry {
17 snippets: RwLock<HashMap<SnippetKind, Vec<Arc<Snippet>>>>,
18}
19
20impl SnippetRegistry {
21 pub fn global(cx: &App) -> Arc<Self> {
22 GlobalSnippetRegistry::global(cx).0.clone()
23 }
24
25 pub fn try_global(cx: &App) -> Option<Arc<Self>> {
26 cx.try_global::<GlobalSnippetRegistry>()
27 .map(|registry| registry.0.clone())
28 }
29
30 pub fn init_global(cx: &mut App) {
31 GlobalSnippetRegistry::set_global(cx, GlobalSnippetRegistry(Arc::new(Self::new())))
32 }
33
34 pub fn new() -> Self {
35 Self {
36 snippets: RwLock::new(HashMap::default()),
37 }
38 }
39
40 pub fn register_snippets(&self, file_path: &Path, contents: &str) -> Result<()> {
41 let snippets_in_file: crate::format::VsSnippetsFile =
42 serde_json_lenient::from_str(contents)?;
43 let kind = file_path
44 .file_stem()
45 .and_then(|stem| stem.to_str().and_then(file_stem_to_key));
46 let snippets = crate::file_to_snippets(snippets_in_file, file_path);
47 self.snippets
48 .write()
49 .insert(kind, snippets.filter_map(Result::log_err).collect());
50
51 Ok(())
52 }
53
54 pub fn get_snippets(&self, kind: &SnippetKind) -> Vec<Arc<Snippet>> {
55 self.snippets.read().get(kind).cloned().unwrap_or_default()
56 }
57}