1use std::path::{Path, PathBuf};
2use std::sync::Arc;
3
4use anyhow::{anyhow, bail, Result};
5use collections::{BTreeMap, HashMap, HashSet};
6use futures::{self, future, Future, FutureExt};
7use gpui::{AppContext, AsyncAppContext, Model, ModelContext, SharedString, Task, WeakView};
8use language::Buffer;
9use project::{ProjectPath, Worktree};
10use rope::Rope;
11use text::BufferId;
12use workspace::Workspace;
13
14use crate::context::{
15 Context, ContextBuffer, ContextId, ContextSnapshot, DirectoryContext, FetchedUrlContext,
16 FileContext, ThreadContext,
17};
18use crate::thread::{Thread, ThreadId};
19
20pub struct ContextStore {
21 workspace: WeakView<Workspace>,
22 context: Vec<Context>,
23 // TODO: If an EntityId is used for all context types (like BufferId), can remove ContextId.
24 next_context_id: ContextId,
25 files: BTreeMap<BufferId, ContextId>,
26 directories: HashMap<PathBuf, ContextId>,
27 threads: HashMap<ThreadId, ContextId>,
28 fetched_urls: HashMap<String, ContextId>,
29}
30
31impl ContextStore {
32 pub fn new(workspace: WeakView<Workspace>) -> Self {
33 Self {
34 workspace,
35 context: Vec::new(),
36 next_context_id: ContextId(0),
37 files: BTreeMap::default(),
38 directories: HashMap::default(),
39 threads: HashMap::default(),
40 fetched_urls: HashMap::default(),
41 }
42 }
43
44 pub fn snapshot<'a>(
45 &'a self,
46 cx: &'a AppContext,
47 ) -> impl Iterator<Item = ContextSnapshot> + 'a {
48 self.context()
49 .iter()
50 .flat_map(|context| context.snapshot(cx))
51 }
52
53 pub fn context(&self) -> &Vec<Context> {
54 &self.context
55 }
56
57 pub fn clear(&mut self) {
58 self.context.clear();
59 self.files.clear();
60 self.directories.clear();
61 self.threads.clear();
62 self.fetched_urls.clear();
63 }
64
65 pub fn add_file_from_path(
66 &mut self,
67 project_path: ProjectPath,
68 cx: &mut ModelContext<Self>,
69 ) -> Task<Result<()>> {
70 let workspace = self.workspace.clone();
71
72 let Some(project) = workspace
73 .upgrade()
74 .map(|workspace| workspace.read(cx).project().clone())
75 else {
76 return Task::ready(Err(anyhow!("failed to read project")));
77 };
78
79 cx.spawn(|this, mut cx| async move {
80 let open_buffer_task = project.update(&mut cx, |project, cx| {
81 project.open_buffer(project_path.clone(), cx)
82 })?;
83
84 let buffer_model = open_buffer_task.await?;
85 let buffer_id = this.update(&mut cx, |_, cx| buffer_model.read(cx).remote_id())?;
86
87 let already_included = this.update(&mut cx, |this, _cx| {
88 match this.will_include_buffer(buffer_id, &project_path.path) {
89 Some(FileInclusion::Direct(context_id)) => {
90 this.remove_context(context_id);
91 true
92 }
93 Some(FileInclusion::InDirectory(_)) => true,
94 None => false,
95 }
96 })?;
97
98 if already_included {
99 return anyhow::Ok(());
100 }
101
102 let (buffer_info, text_task) = this.update(&mut cx, |_, cx| {
103 let buffer = buffer_model.read(cx);
104 collect_buffer_info_and_text(
105 project_path.path.clone(),
106 buffer_model,
107 buffer,
108 cx.to_async(),
109 )
110 })?;
111
112 let text = text_task.await;
113
114 this.update(&mut cx, |this, _cx| {
115 this.insert_file(make_context_buffer(buffer_info, text));
116 })?;
117
118 anyhow::Ok(())
119 })
120 }
121
122 pub fn add_file_from_buffer(
123 &mut self,
124 buffer_model: Model<Buffer>,
125 cx: &mut ModelContext<Self>,
126 ) -> Task<Result<()>> {
127 cx.spawn(|this, mut cx| async move {
128 let (buffer_info, text_task) = this.update(&mut cx, |_, cx| {
129 let buffer = buffer_model.read(cx);
130 let Some(file) = buffer.file() else {
131 return Err(anyhow!("Buffer has no path."));
132 };
133 Ok(collect_buffer_info_and_text(
134 file.path().clone(),
135 buffer_model,
136 buffer,
137 cx.to_async(),
138 ))
139 })??;
140
141 let text = text_task.await;
142
143 this.update(&mut cx, |this, _cx| {
144 this.insert_file(make_context_buffer(buffer_info, text))
145 })?;
146
147 anyhow::Ok(())
148 })
149 }
150
151 pub fn insert_file(&mut self, context_buffer: ContextBuffer) {
152 let id = self.next_context_id.post_inc();
153 self.files.insert(context_buffer.id, id);
154 self.context
155 .push(Context::File(FileContext { id, context_buffer }));
156 }
157
158 pub fn add_directory(
159 &mut self,
160 project_path: ProjectPath,
161 cx: &mut ModelContext<Self>,
162 ) -> Task<Result<()>> {
163 let workspace = self.workspace.clone();
164 let Some(project) = workspace
165 .upgrade()
166 .map(|workspace| workspace.read(cx).project().clone())
167 else {
168 return Task::ready(Err(anyhow!("failed to read project")));
169 };
170
171 let already_included = if let Some(context_id) = self.includes_directory(&project_path.path)
172 {
173 self.remove_context(context_id);
174 true
175 } else {
176 false
177 };
178 if already_included {
179 return Task::ready(Ok(()));
180 }
181
182 let worktree_id = project_path.worktree_id;
183 cx.spawn(|this, mut cx| async move {
184 let worktree = project.update(&mut cx, |project, cx| {
185 project
186 .worktree_for_id(worktree_id, cx)
187 .ok_or_else(|| anyhow!("no worktree found for {worktree_id:?}"))
188 })??;
189
190 let files = worktree.update(&mut cx, |worktree, _cx| {
191 collect_files_in_path(worktree, &project_path.path)
192 })?;
193
194 let open_buffers_task = project.update(&mut cx, |project, cx| {
195 let tasks = files.iter().map(|file_path| {
196 project.open_buffer(
197 ProjectPath {
198 worktree_id,
199 path: file_path.clone(),
200 },
201 cx,
202 )
203 });
204 future::join_all(tasks)
205 })?;
206
207 let buffers = open_buffers_task.await;
208
209 let mut buffer_infos = Vec::new();
210 let mut text_tasks = Vec::new();
211 this.update(&mut cx, |_, cx| {
212 for (path, buffer_model) in files.into_iter().zip(buffers) {
213 let buffer_model = buffer_model?;
214 let buffer = buffer_model.read(cx);
215 let (buffer_info, text_task) =
216 collect_buffer_info_and_text(path, buffer_model, buffer, cx.to_async());
217 buffer_infos.push(buffer_info);
218 text_tasks.push(text_task);
219 }
220 anyhow::Ok(())
221 })??;
222
223 let buffer_texts = future::join_all(text_tasks).await;
224 let context_buffers = buffer_infos
225 .into_iter()
226 .zip(buffer_texts)
227 .map(|(info, text)| make_context_buffer(info, text))
228 .collect::<Vec<_>>();
229
230 if context_buffers.is_empty() {
231 bail!("No text files found in {}", &project_path.path.display());
232 }
233
234 this.update(&mut cx, |this, _| {
235 this.insert_directory(&project_path.path, context_buffers);
236 })?;
237
238 anyhow::Ok(())
239 })
240 }
241
242 pub fn insert_directory(&mut self, path: &Path, context_buffers: Vec<ContextBuffer>) {
243 let id = self.next_context_id.post_inc();
244 self.directories.insert(path.to_path_buf(), id);
245
246 self.context.push(Context::Directory(DirectoryContext::new(
247 id,
248 path,
249 context_buffers,
250 )));
251 }
252
253 pub fn add_thread(&mut self, thread: Model<Thread>, cx: &mut ModelContext<Self>) {
254 if let Some(context_id) = self.includes_thread(&thread.read(cx).id()) {
255 self.remove_context(context_id);
256 } else {
257 self.insert_thread(thread, cx);
258 }
259 }
260
261 pub fn insert_thread(&mut self, thread: Model<Thread>, cx: &AppContext) {
262 let id = self.next_context_id.post_inc();
263 let text = thread.read(cx).text().into();
264
265 self.threads.insert(thread.read(cx).id().clone(), id);
266 self.context
267 .push(Context::Thread(ThreadContext { id, thread, text }));
268 }
269
270 pub fn insert_fetched_url(&mut self, url: String, text: impl Into<SharedString>) {
271 let id = self.next_context_id.post_inc();
272
273 self.fetched_urls.insert(url.clone(), id);
274 self.context.push(Context::FetchedUrl(FetchedUrlContext {
275 id,
276 url: url.into(),
277 text: text.into(),
278 }));
279 }
280
281 pub fn remove_context(&mut self, id: ContextId) {
282 let Some(ix) = self.context.iter().position(|context| context.id() == id) else {
283 return;
284 };
285
286 match self.context.remove(ix) {
287 Context::File(_) => {
288 self.files.retain(|_, context_id| *context_id != id);
289 }
290 Context::Directory(_) => {
291 self.directories.retain(|_, context_id| *context_id != id);
292 }
293 Context::FetchedUrl(_) => {
294 self.fetched_urls.retain(|_, context_id| *context_id != id);
295 }
296 Context::Thread(_) => {
297 self.threads.retain(|_, context_id| *context_id != id);
298 }
299 }
300 }
301
302 /// Returns whether the buffer is already included directly in the context, or if it will be
303 /// included in the context via a directory. Directory inclusion is based on paths rather than
304 /// buffer IDs as the directory will be re-scanned.
305 pub fn will_include_buffer(&self, buffer_id: BufferId, path: &Path) -> Option<FileInclusion> {
306 if let Some(context_id) = self.files.get(&buffer_id) {
307 return Some(FileInclusion::Direct(*context_id));
308 }
309
310 self.will_include_file_path_via_directory(path)
311 }
312
313 /// Returns whether this file path is already included directly in the context, or if it will be
314 /// included in the context via a directory.
315 pub fn will_include_file_path(&self, path: &Path, cx: &AppContext) -> Option<FileInclusion> {
316 if !self.files.is_empty() {
317 let found_file_context = self.context.iter().find(|context| match &context {
318 Context::File(file_context) => {
319 let buffer = file_context.context_buffer.buffer.read(cx);
320 if let Some(file_path) = buffer_path_log_err(buffer) {
321 *file_path == *path
322 } else {
323 false
324 }
325 }
326 _ => false,
327 });
328 if let Some(context) = found_file_context {
329 return Some(FileInclusion::Direct(context.id()));
330 }
331 }
332
333 self.will_include_file_path_via_directory(path)
334 }
335
336 fn will_include_file_path_via_directory(&self, path: &Path) -> Option<FileInclusion> {
337 if self.directories.is_empty() {
338 return None;
339 }
340
341 let mut buf = path.to_path_buf();
342
343 while buf.pop() {
344 if let Some(_) = self.directories.get(&buf) {
345 return Some(FileInclusion::InDirectory(buf));
346 }
347 }
348
349 None
350 }
351
352 pub fn includes_directory(&self, path: &Path) -> Option<ContextId> {
353 self.directories.get(path).copied()
354 }
355
356 pub fn includes_thread(&self, thread_id: &ThreadId) -> Option<ContextId> {
357 self.threads.get(thread_id).copied()
358 }
359
360 pub fn includes_url(&self, url: &str) -> Option<ContextId> {
361 self.fetched_urls.get(url).copied()
362 }
363
364 /// Replaces the context that matches the ID of the new context, if any match.
365 fn replace_context(&mut self, new_context: Context) {
366 let id = new_context.id();
367 for context in self.context.iter_mut() {
368 if context.id() == id {
369 *context = new_context;
370 break;
371 }
372 }
373 }
374
375 pub fn file_paths(&self, cx: &AppContext) -> HashSet<PathBuf> {
376 self.context
377 .iter()
378 .filter_map(|context| match context {
379 Context::File(file) => {
380 let buffer = file.context_buffer.buffer.read(cx);
381 buffer_path_log_err(buffer).map(|p| p.to_path_buf())
382 }
383 Context::Directory(_) | Context::FetchedUrl(_) | Context::Thread(_) => None,
384 })
385 .collect()
386 }
387
388 pub fn thread_ids(&self) -> HashSet<ThreadId> {
389 self.threads.keys().cloned().collect()
390 }
391}
392
393pub enum FileInclusion {
394 Direct(ContextId),
395 InDirectory(PathBuf),
396}
397
398// ContextBuffer without text.
399struct BufferInfo {
400 buffer_model: Model<Buffer>,
401 id: BufferId,
402 version: clock::Global,
403}
404
405fn make_context_buffer(info: BufferInfo, text: SharedString) -> ContextBuffer {
406 ContextBuffer {
407 id: info.id,
408 buffer: info.buffer_model,
409 version: info.version,
410 text,
411 }
412}
413
414fn collect_buffer_info_and_text(
415 path: Arc<Path>,
416 buffer_model: Model<Buffer>,
417 buffer: &Buffer,
418 cx: AsyncAppContext,
419) -> (BufferInfo, Task<SharedString>) {
420 let buffer_info = BufferInfo {
421 id: buffer.remote_id(),
422 buffer_model,
423 version: buffer.version(),
424 };
425 // Important to collect version at the same time as content so that staleness logic is correct.
426 let content = buffer.as_rope().clone();
427 let text_task = cx
428 .background_executor()
429 .spawn(async move { to_fenced_codeblock(&path, content) });
430 (buffer_info, text_task)
431}
432
433pub fn buffer_path_log_err(buffer: &Buffer) -> Option<Arc<Path>> {
434 if let Some(file) = buffer.file() {
435 Some(file.path().clone())
436 } else {
437 log::error!("Buffer that had a path unexpectedly no longer has a path.");
438 None
439 }
440}
441
442fn to_fenced_codeblock(path: &Path, content: Rope) -> SharedString {
443 let path_extension = path.extension().and_then(|ext| ext.to_str());
444 let path_string = path.to_string_lossy();
445 let capacity = 3
446 + path_extension.map_or(0, |extension| extension.len() + 1)
447 + path_string.len()
448 + 1
449 + content.len()
450 + 5;
451 let mut buffer = String::with_capacity(capacity);
452
453 buffer.push_str("```");
454
455 if let Some(extension) = path_extension {
456 buffer.push_str(extension);
457 buffer.push(' ');
458 }
459 buffer.push_str(&path_string);
460
461 buffer.push('\n');
462 for chunk in content.chunks() {
463 buffer.push_str(&chunk);
464 }
465
466 if !buffer.ends_with('\n') {
467 buffer.push('\n');
468 }
469
470 buffer.push_str("```\n");
471
472 debug_assert!(
473 buffer.len() == capacity - 1 || buffer.len() == capacity,
474 "to_fenced_codeblock calculated capacity of {}, but length was {}",
475 capacity,
476 buffer.len(),
477 );
478
479 buffer.into()
480}
481
482fn collect_files_in_path(worktree: &Worktree, path: &Path) -> Vec<Arc<Path>> {
483 let mut files = Vec::new();
484
485 for entry in worktree.child_entries(path) {
486 if entry.is_dir() {
487 files.extend(collect_files_in_path(worktree, &entry.path));
488 } else if entry.is_file() {
489 files.push(entry.path.clone());
490 }
491 }
492
493 files
494}
495
496pub fn refresh_context_store_text(
497 context_store: Model<ContextStore>,
498 cx: &AppContext,
499) -> impl Future<Output = ()> {
500 let mut tasks = Vec::new();
501 for context in &context_store.read(cx).context {
502 match context {
503 Context::File(file_context) => {
504 let context_store = context_store.clone();
505 if let Some(task) = refresh_file_text(context_store, file_context, cx) {
506 tasks.push(task);
507 }
508 }
509 Context::Directory(directory_context) => {
510 let context_store = context_store.clone();
511 if let Some(task) = refresh_directory_text(context_store, directory_context, cx) {
512 tasks.push(task);
513 }
514 }
515 Context::Thread(thread_context) => {
516 let context_store = context_store.clone();
517 tasks.push(refresh_thread_text(context_store, thread_context, cx));
518 }
519 // Intentionally omit refreshing fetched URLs as it doesn't seem all that useful,
520 // and doing the caching properly could be tricky (unless it's already handled by
521 // the HttpClient?).
522 Context::FetchedUrl(_) => {}
523 }
524 }
525
526 future::join_all(tasks).map(|_| ())
527}
528
529fn refresh_file_text(
530 context_store: Model<ContextStore>,
531 file_context: &FileContext,
532 cx: &AppContext,
533) -> Option<Task<()>> {
534 let id = file_context.id;
535 let task = refresh_context_buffer(&file_context.context_buffer, cx);
536 if let Some(task) = task {
537 Some(cx.spawn(|mut cx| async move {
538 let context_buffer = task.await;
539 context_store
540 .update(&mut cx, |context_store, _| {
541 let new_file_context = FileContext { id, context_buffer };
542 context_store.replace_context(Context::File(new_file_context));
543 })
544 .ok();
545 }))
546 } else {
547 None
548 }
549}
550
551fn refresh_directory_text(
552 context_store: Model<ContextStore>,
553 directory_context: &DirectoryContext,
554 cx: &AppContext,
555) -> Option<Task<()>> {
556 let mut stale = false;
557 let futures = directory_context
558 .context_buffers
559 .iter()
560 .map(|context_buffer| {
561 if let Some(refresh_task) = refresh_context_buffer(context_buffer, cx) {
562 stale = true;
563 future::Either::Left(refresh_task)
564 } else {
565 future::Either::Right(future::ready((*context_buffer).clone()))
566 }
567 })
568 .collect::<Vec<_>>();
569
570 if !stale {
571 return None;
572 }
573
574 let context_buffers = future::join_all(futures);
575
576 let id = directory_context.snapshot.id;
577 let path = directory_context.path.clone();
578 Some(cx.spawn(|mut cx| async move {
579 let context_buffers = context_buffers.await;
580 context_store
581 .update(&mut cx, |context_store, _| {
582 let new_directory_context = DirectoryContext::new(id, &path, context_buffers);
583 context_store.replace_context(Context::Directory(new_directory_context));
584 })
585 .ok();
586 }))
587}
588
589fn refresh_thread_text(
590 context_store: Model<ContextStore>,
591 thread_context: &ThreadContext,
592 cx: &AppContext,
593) -> Task<()> {
594 let id = thread_context.id;
595 let thread = thread_context.thread.clone();
596 cx.spawn(move |mut cx| async move {
597 context_store
598 .update(&mut cx, |context_store, cx| {
599 let text = thread.read(cx).text().into();
600 context_store.replace_context(Context::Thread(ThreadContext { id, thread, text }));
601 })
602 .ok();
603 })
604}
605
606fn refresh_context_buffer(
607 context_buffer: &ContextBuffer,
608 cx: &AppContext,
609) -> Option<impl Future<Output = ContextBuffer>> {
610 let buffer = context_buffer.buffer.read(cx);
611 let path = buffer_path_log_err(buffer)?;
612 if buffer.version.changed_since(&context_buffer.version) {
613 let (buffer_info, text_task) = collect_buffer_info_and_text(
614 path,
615 context_buffer.buffer.clone(),
616 buffer,
617 cx.to_async(),
618 );
619 Some(text_task.map(move |text| make_context_buffer(buffer_info, text)))
620 } else {
621 None
622 }
623}