1mod format;
2mod registry;
3
4use std::{
5 path::{Path, PathBuf},
6 sync::Arc,
7 time::Duration,
8};
9
10use anyhow::Result;
11use collections::{BTreeMap, BTreeSet, HashMap};
12use format::VSSnippetsFile;
13use fs::Fs;
14use futures::stream::StreamExt;
15use gpui::{AppContext, AsyncAppContext, Context, Model, ModelContext, Task, WeakModel};
16pub use registry::*;
17use util::ResultExt;
18
19pub fn init(cx: &mut AppContext) {
20 SnippetRegistry::init_global(cx);
21}
22
23// Is `None` if the snippet file is global.
24type SnippetKind = Option<String>;
25fn file_stem_to_key(stem: &str) -> SnippetKind {
26 if stem == "snippets" {
27 None
28 } else {
29 Some(stem.to_owned())
30 }
31}
32
33fn file_to_snippets(file_contents: VSSnippetsFile) -> Vec<Arc<Snippet>> {
34 let mut snippets = vec![];
35 for (prefix, snippet) in file_contents.snippets {
36 let prefixes = snippet
37 .prefix
38 .map_or_else(move || vec![prefix], |prefixes| prefixes.into());
39 let description = snippet
40 .description
41 .map(|description| description.to_string());
42 let body = snippet.body.to_string();
43 if snippet::Snippet::parse(&body).log_err().is_none() {
44 continue;
45 };
46 snippets.push(Arc::new(Snippet {
47 body,
48 prefix: prefixes,
49 description,
50 }));
51 }
52 snippets
53}
54// Snippet with all of the metadata
55#[derive(Debug)]
56pub struct Snippet {
57 pub prefix: Vec<String>,
58 pub body: String,
59 pub description: Option<String>,
60}
61
62async fn process_updates(
63 this: WeakModel<SnippetProvider>,
64 entries: Vec<PathBuf>,
65 mut cx: AsyncAppContext,
66) -> Result<()> {
67 let fs = this.update(&mut cx, |this, _| this.fs.clone())?;
68 for entry_path in entries {
69 if !entry_path
70 .extension()
71 .map_or(false, |extension| extension == "json")
72 {
73 continue;
74 }
75 let entry_metadata = fs.metadata(&entry_path).await;
76 // Entry could have been removed, in which case we should no longer show completions for it.
77 let entry_exists = entry_metadata.is_ok();
78 if entry_metadata.map_or(false, |entry| entry.map_or(false, |e| e.is_dir)) {
79 // Don't process dirs.
80 continue;
81 }
82 let Some(stem) = entry_path.file_stem().and_then(|s| s.to_str()) else {
83 continue;
84 };
85 let key = file_stem_to_key(stem);
86
87 let contents = if entry_exists {
88 fs.load(&entry_path).await.ok()
89 } else {
90 None
91 };
92
93 this.update(&mut cx, move |this, _| {
94 let snippets_of_kind = this.snippets.entry(key).or_default();
95 if entry_exists {
96 let Some(file_contents) = contents else {
97 return;
98 };
99 let Ok(as_json) = serde_json::from_str::<VSSnippetsFile>(&file_contents) else {
100 return;
101 };
102 let snippets = file_to_snippets(as_json);
103 *snippets_of_kind.entry(entry_path).or_default() = snippets;
104 } else {
105 snippets_of_kind.remove(&entry_path);
106 }
107 })?;
108 }
109 Ok(())
110}
111
112async fn initial_scan(
113 this: WeakModel<SnippetProvider>,
114 path: Arc<Path>,
115 mut cx: AsyncAppContext,
116) -> Result<()> {
117 let fs = this.update(&mut cx, |this, _| this.fs.clone())?;
118 let entries = fs.read_dir(&path).await;
119 if let Ok(entries) = entries {
120 let entries = entries
121 .collect::<Vec<_>>()
122 .await
123 .into_iter()
124 .collect::<Result<Vec<_>>>()?;
125 process_updates(this, entries, cx).await?;
126 }
127 Ok(())
128}
129
130pub struct SnippetProvider {
131 fs: Arc<dyn Fs>,
132 snippets: HashMap<SnippetKind, BTreeMap<PathBuf, Vec<Arc<Snippet>>>>,
133}
134
135impl SnippetProvider {
136 pub fn new(
137 fs: Arc<dyn Fs>,
138 dirs_to_watch: BTreeSet<PathBuf>,
139 cx: &mut AppContext,
140 ) -> Model<Self> {
141 cx.new_model(move |cx| {
142 let mut this = Self {
143 fs,
144 snippets: Default::default(),
145 };
146
147 let mut task_handles = vec![];
148 for dir in dirs_to_watch {
149 task_handles.push(this.watch_directory(&dir, cx));
150 }
151 cx.spawn(|_, _| async move {
152 futures::future::join_all(task_handles).await;
153 })
154 .detach();
155
156 this
157 })
158 }
159
160 /// Add directory to be watched for content changes
161 fn watch_directory(&mut self, path: &Path, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
162 let path: Arc<Path> = Arc::from(path);
163
164 cx.spawn(|this, mut cx| async move {
165 let fs = this.update(&mut cx, |this, _| this.fs.clone())?;
166 let watched_path = path.clone();
167 let watcher = fs.watch(&watched_path, Duration::from_secs(1));
168 initial_scan(this.clone(), path, cx.clone()).await?;
169
170 let (mut entries, _) = watcher.await;
171 while let Some(entries) = entries.next().await {
172 process_updates(
173 this.clone(),
174 entries.into_iter().map(|event| event.path).collect(),
175 cx.clone(),
176 )
177 .await?;
178 }
179 Ok(())
180 })
181 }
182
183 fn lookup_snippets<'a>(
184 &'a self,
185 language: &'a SnippetKind,
186 cx: &AppContext,
187 ) -> Vec<Arc<Snippet>> {
188 let mut user_snippets: Vec<_> = self
189 .snippets
190 .get(language)
191 .cloned()
192 .unwrap_or_default()
193 .into_iter()
194 .flat_map(|(_, snippets)| snippets.into_iter())
195 .collect();
196
197 let Some(registry) = SnippetRegistry::try_global(cx) else {
198 return user_snippets;
199 };
200
201 let registry_snippets = registry.get_snippets(language);
202 user_snippets.extend(registry_snippets);
203
204 user_snippets
205 }
206
207 pub fn snippets_for(&self, language: SnippetKind, cx: &AppContext) -> Vec<Arc<Snippet>> {
208 let mut requested_snippets = self.lookup_snippets(&language, cx);
209
210 if language.is_some() {
211 // Look up global snippets as well.
212 requested_snippets.extend(self.lookup_snippets(&None, cx));
213 }
214 requested_snippets
215 }
216}