1use std::{
2 cell::RefCell,
3 path::{Path, PathBuf},
4 sync::{atomic::AtomicUsize, Arc},
5};
6
7use anyhow::{anyhow, Context as _, Result};
8use client::DevServerProjectId;
9use collections::{HashMap, HashSet};
10use fs::Fs;
11use futures::{
12 future::{BoxFuture, Shared},
13 FutureExt, SinkExt,
14};
15use gpui::{
16 AppContext, AsyncAppContext, EntityId, EventEmitter, Model, ModelContext, Task, WeakModel,
17};
18use postage::oneshot;
19use rpc::{
20 proto::{self, SSH_PROJECT_ID},
21 AnyProtoClient, TypedEnvelope,
22};
23use smol::{
24 channel::{Receiver, Sender},
25 stream::StreamExt,
26};
27use text::ReplicaId;
28use util::{paths::compare_paths, ResultExt};
29use worktree::{Entry, ProjectEntryId, Worktree, WorktreeId, WorktreeSettings};
30
31use crate::{search::SearchQuery, ProjectPath};
32
33struct MatchingEntry {
34 worktree_path: Arc<Path>,
35 path: ProjectPath,
36 respond: oneshot::Sender<ProjectPath>,
37}
38
39pub struct WorktreeStore {
40 next_entry_id: Arc<AtomicUsize>,
41 upstream_client: Option<AnyProtoClient>,
42 downstream_client: Option<AnyProtoClient>,
43 remote_id: u64,
44 dev_server_project_id: Option<DevServerProjectId>,
45 retain_worktrees: bool,
46 worktrees: Vec<WorktreeHandle>,
47 worktrees_reordered: bool,
48 #[allow(clippy::type_complexity)]
49 loading_worktrees:
50 HashMap<Arc<Path>, Shared<Task<Result<Model<Worktree>, Arc<anyhow::Error>>>>>,
51 fs: Arc<dyn Fs>,
52}
53
54pub enum WorktreeStoreEvent {
55 WorktreeAdded(Model<Worktree>),
56 WorktreeRemoved(EntityId, WorktreeId),
57 WorktreeOrderChanged,
58 WorktreeUpdateSent(Model<Worktree>),
59}
60
61impl EventEmitter<WorktreeStoreEvent> for WorktreeStore {}
62
63impl WorktreeStore {
64 pub fn init(client: &AnyProtoClient) {
65 client.add_model_request_handler(Self::handle_create_project_entry);
66 client.add_model_request_handler(Self::handle_rename_project_entry);
67 client.add_model_request_handler(Self::handle_copy_project_entry);
68 client.add_model_request_handler(Self::handle_delete_project_entry);
69 client.add_model_request_handler(Self::handle_expand_project_entry);
70 }
71
72 pub fn new(
73 upstream_client: Option<AnyProtoClient>,
74 retain_worktrees: bool,
75 fs: Arc<dyn Fs>,
76 ) -> Self {
77 Self {
78 next_entry_id: Default::default(),
79 loading_worktrees: Default::default(),
80 dev_server_project_id: None,
81 downstream_client: None,
82 worktrees: Vec::new(),
83 worktrees_reordered: false,
84 retain_worktrees,
85 remote_id: 0,
86 upstream_client,
87 fs,
88 }
89 }
90
91 pub fn set_dev_server_project_id(&mut self, id: DevServerProjectId) {
92 self.dev_server_project_id = Some(id);
93 }
94
95 /// Iterates through all worktrees, including ones that don't appear in the project panel
96 pub fn worktrees(&self) -> impl '_ + DoubleEndedIterator<Item = Model<Worktree>> {
97 self.worktrees
98 .iter()
99 .filter_map(move |worktree| worktree.upgrade())
100 }
101
102 /// Iterates through all user-visible worktrees, the ones that appear in the project panel.
103 pub fn visible_worktrees<'a>(
104 &'a self,
105 cx: &'a AppContext,
106 ) -> impl 'a + DoubleEndedIterator<Item = Model<Worktree>> {
107 self.worktrees()
108 .filter(|worktree| worktree.read(cx).is_visible())
109 }
110
111 pub fn worktree_for_id(&self, id: WorktreeId, cx: &AppContext) -> Option<Model<Worktree>> {
112 self.worktrees()
113 .find(|worktree| worktree.read(cx).id() == id)
114 }
115
116 pub fn worktree_for_entry(
117 &self,
118 entry_id: ProjectEntryId,
119 cx: &AppContext,
120 ) -> Option<Model<Worktree>> {
121 self.worktrees()
122 .find(|worktree| worktree.read(cx).contains_entry(entry_id))
123 }
124
125 pub fn find_worktree(
126 &self,
127 abs_path: &Path,
128 cx: &AppContext,
129 ) -> Option<(Model<Worktree>, PathBuf)> {
130 for tree in self.worktrees() {
131 if let Ok(relative_path) = abs_path.strip_prefix(tree.read(cx).abs_path()) {
132 return Some((tree.clone(), relative_path.into()));
133 }
134 }
135 None
136 }
137
138 pub fn entry_for_id<'a>(
139 &'a self,
140 entry_id: ProjectEntryId,
141 cx: &'a AppContext,
142 ) -> Option<&'a Entry> {
143 self.worktrees()
144 .find_map(|worktree| worktree.read(cx).entry_for_id(entry_id))
145 }
146
147 pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
148 self.worktree_for_id(path.worktree_id, cx)?
149 .read(cx)
150 .entry_for_path(&path.path)
151 .cloned()
152 }
153
154 pub fn create_worktree(
155 &mut self,
156 abs_path: impl AsRef<Path>,
157 visible: bool,
158 cx: &mut ModelContext<Self>,
159 ) -> Task<Result<Model<Worktree>>> {
160 let path: Arc<Path> = abs_path.as_ref().into();
161 if !self.loading_worktrees.contains_key(&path) {
162 let task = if let Some(client) = self.upstream_client.clone() {
163 if let Some(dev_server_project_id) = self.dev_server_project_id {
164 self.create_dev_server_worktree(client, dev_server_project_id, abs_path, cx)
165 } else {
166 self.create_ssh_worktree(client, abs_path, visible, cx)
167 }
168 } else {
169 self.create_local_worktree(abs_path, visible, cx)
170 };
171
172 self.loading_worktrees.insert(path.clone(), task.shared());
173 }
174 let task = self.loading_worktrees.get(&path).unwrap().clone();
175 cx.background_executor().spawn(async move {
176 match task.await {
177 Ok(worktree) => Ok(worktree),
178 Err(err) => Err(anyhow!("{}", err)),
179 }
180 })
181 }
182
183 fn create_ssh_worktree(
184 &mut self,
185 client: AnyProtoClient,
186 abs_path: impl AsRef<Path>,
187 visible: bool,
188 cx: &mut ModelContext<Self>,
189 ) -> Task<Result<Model<Worktree>, Arc<anyhow::Error>>> {
190 let mut abs_path = abs_path.as_ref().to_string_lossy().to_string();
191 // If we start with `/~` that means the ssh path was something like `ssh://user@host/~/home-dir-folder/`
192 // in which case want to strip the leading the `/` and expand the tilde.
193 // That's what git does too: https://github.com/libgit2/libgit2/issues/3345#issuecomment-127050850
194 if abs_path.starts_with("/~") {
195 abs_path = shellexpand::tilde(&abs_path[1..]).to_string();
196 }
197 let root_name = PathBuf::from(abs_path.clone())
198 .file_name()
199 .unwrap()
200 .to_string_lossy()
201 .to_string();
202 cx.spawn(|this, mut cx| async move {
203 let response = client
204 .request(proto::AddWorktree {
205 project_id: SSH_PROJECT_ID,
206 path: abs_path.clone(),
207 })
208 .await?;
209
210 if let Some(existing_worktree) = this.read_with(&cx, |this, cx| {
211 this.worktree_for_id(WorktreeId::from_proto(response.worktree_id), cx)
212 })? {
213 return Ok(existing_worktree);
214 }
215
216 let worktree = cx.update(|cx| {
217 Worktree::remote(
218 0,
219 0,
220 proto::WorktreeMetadata {
221 id: response.worktree_id,
222 root_name,
223 visible,
224 abs_path,
225 },
226 client,
227 cx,
228 )
229 })?;
230
231 this.update(&mut cx, |this, cx| this.add(&worktree, cx))?;
232
233 Ok(worktree)
234 })
235 }
236
237 fn create_local_worktree(
238 &mut self,
239 abs_path: impl AsRef<Path>,
240 visible: bool,
241 cx: &mut ModelContext<Self>,
242 ) -> Task<Result<Model<Worktree>, Arc<anyhow::Error>>> {
243 let fs = self.fs.clone();
244 let next_entry_id = self.next_entry_id.clone();
245 let path: Arc<Path> = abs_path.as_ref().into();
246
247 cx.spawn(move |this, mut cx| async move {
248 let worktree = Worktree::local(path.clone(), visible, fs, next_entry_id, &mut cx).await;
249
250 this.update(&mut cx, |project, _| {
251 project.loading_worktrees.remove(&path);
252 })?;
253
254 let worktree = worktree?;
255 this.update(&mut cx, |this, cx| this.add(&worktree, cx))?;
256
257 if visible {
258 cx.update(|cx| {
259 cx.add_recent_document(&path);
260 })
261 .log_err();
262 }
263
264 Ok(worktree)
265 })
266 }
267
268 fn create_dev_server_worktree(
269 &mut self,
270 client: AnyProtoClient,
271 dev_server_project_id: DevServerProjectId,
272 abs_path: impl AsRef<Path>,
273 cx: &mut ModelContext<Self>,
274 ) -> Task<Result<Model<Worktree>, Arc<anyhow::Error>>> {
275 let path: Arc<Path> = abs_path.as_ref().into();
276 let mut paths: Vec<String> = self
277 .visible_worktrees(cx)
278 .map(|worktree| worktree.read(cx).abs_path().to_string_lossy().to_string())
279 .collect();
280 paths.push(path.to_string_lossy().to_string());
281 let request = client.request(proto::UpdateDevServerProject {
282 dev_server_project_id: dev_server_project_id.0,
283 paths,
284 });
285
286 let abs_path = abs_path.as_ref().to_path_buf();
287 cx.spawn(move |project, mut cx| async move {
288 let (tx, rx) = futures::channel::oneshot::channel();
289 let tx = RefCell::new(Some(tx));
290 let Some(project) = project.upgrade() else {
291 return Err(anyhow!("project dropped"))?;
292 };
293 let observer = cx.update(|cx| {
294 cx.observe(&project, move |project, cx| {
295 let abs_path = abs_path.clone();
296 project.update(cx, |project, cx| {
297 if let Some((worktree, _)) = project.find_worktree(&abs_path, cx) {
298 if let Some(tx) = tx.borrow_mut().take() {
299 tx.send(worktree).ok();
300 }
301 }
302 })
303 })
304 })?;
305
306 request.await?;
307 let worktree = rx.await.map_err(|e| anyhow!(e))?;
308 drop(observer);
309 project.update(&mut cx, |project, _| {
310 project.loading_worktrees.remove(&path);
311 })?;
312 Ok(worktree)
313 })
314 }
315
316 #[track_caller]
317 pub fn add(&mut self, worktree: &Model<Worktree>, cx: &mut ModelContext<Self>) {
318 let worktree_id = worktree.read(cx).id();
319 debug_assert!(self.worktrees().all(|w| w.read(cx).id() != worktree_id));
320
321 let push_strong_handle = self.retain_worktrees || worktree.read(cx).is_visible();
322 let handle = if push_strong_handle {
323 WorktreeHandle::Strong(worktree.clone())
324 } else {
325 WorktreeHandle::Weak(worktree.downgrade())
326 };
327 if self.worktrees_reordered {
328 self.worktrees.push(handle);
329 } else {
330 let i = match self
331 .worktrees
332 .binary_search_by_key(&Some(worktree.read(cx).abs_path()), |other| {
333 other.upgrade().map(|worktree| worktree.read(cx).abs_path())
334 }) {
335 Ok(i) | Err(i) => i,
336 };
337 self.worktrees.insert(i, handle);
338 }
339
340 cx.emit(WorktreeStoreEvent::WorktreeAdded(worktree.clone()));
341 self.send_project_updates(cx);
342
343 let handle_id = worktree.entity_id();
344 cx.observe_release(worktree, move |this, worktree, cx| {
345 cx.emit(WorktreeStoreEvent::WorktreeRemoved(
346 handle_id,
347 worktree.id(),
348 ));
349 this.send_project_updates(cx);
350 })
351 .detach();
352 }
353
354 pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
355 self.worktrees.retain(|worktree| {
356 if let Some(worktree) = worktree.upgrade() {
357 if worktree.read(cx).id() == id_to_remove {
358 cx.emit(WorktreeStoreEvent::WorktreeRemoved(
359 worktree.entity_id(),
360 id_to_remove,
361 ));
362 false
363 } else {
364 true
365 }
366 } else {
367 false
368 }
369 });
370 self.send_project_updates(cx);
371 }
372
373 pub fn set_worktrees_reordered(&mut self, worktrees_reordered: bool) {
374 self.worktrees_reordered = worktrees_reordered;
375 }
376
377 pub fn set_worktrees_from_proto(
378 &mut self,
379 worktrees: Vec<proto::WorktreeMetadata>,
380 replica_id: ReplicaId,
381 cx: &mut ModelContext<Self>,
382 ) -> Result<()> {
383 let mut old_worktrees_by_id = self
384 .worktrees
385 .drain(..)
386 .filter_map(|worktree| {
387 let worktree = worktree.upgrade()?;
388 Some((worktree.read(cx).id(), worktree))
389 })
390 .collect::<HashMap<_, _>>();
391
392 let client = self
393 .upstream_client
394 .clone()
395 .ok_or_else(|| anyhow!("invalid project"))?;
396
397 for worktree in worktrees {
398 if let Some(old_worktree) =
399 old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
400 {
401 let push_strong_handle =
402 self.retain_worktrees || old_worktree.read(cx).is_visible();
403 let handle = if push_strong_handle {
404 WorktreeHandle::Strong(old_worktree.clone())
405 } else {
406 WorktreeHandle::Weak(old_worktree.downgrade())
407 };
408 self.worktrees.push(handle);
409 } else {
410 self.add(
411 &Worktree::remote(self.remote_id, replica_id, worktree, client.clone(), cx),
412 cx,
413 );
414 }
415 }
416 self.send_project_updates(cx);
417
418 Ok(())
419 }
420
421 pub fn move_worktree(
422 &mut self,
423 source: WorktreeId,
424 destination: WorktreeId,
425 cx: &mut ModelContext<Self>,
426 ) -> Result<()> {
427 if source == destination {
428 return Ok(());
429 }
430
431 let mut source_index = None;
432 let mut destination_index = None;
433 for (i, worktree) in self.worktrees.iter().enumerate() {
434 if let Some(worktree) = worktree.upgrade() {
435 let worktree_id = worktree.read(cx).id();
436 if worktree_id == source {
437 source_index = Some(i);
438 if destination_index.is_some() {
439 break;
440 }
441 } else if worktree_id == destination {
442 destination_index = Some(i);
443 if source_index.is_some() {
444 break;
445 }
446 }
447 }
448 }
449
450 let source_index =
451 source_index.with_context(|| format!("Missing worktree for id {source}"))?;
452 let destination_index =
453 destination_index.with_context(|| format!("Missing worktree for id {destination}"))?;
454
455 if source_index == destination_index {
456 return Ok(());
457 }
458
459 let worktree_to_move = self.worktrees.remove(source_index);
460 self.worktrees.insert(destination_index, worktree_to_move);
461 self.worktrees_reordered = true;
462 cx.emit(WorktreeStoreEvent::WorktreeOrderChanged);
463 cx.notify();
464 Ok(())
465 }
466
467 pub fn disconnected_from_host(&mut self, cx: &mut AppContext) {
468 for worktree in &self.worktrees {
469 if let Some(worktree) = worktree.upgrade() {
470 worktree.update(cx, |worktree, _| {
471 if let Some(worktree) = worktree.as_remote_mut() {
472 worktree.disconnected_from_host();
473 }
474 });
475 }
476 }
477 }
478
479 pub fn send_project_updates(&mut self, cx: &mut ModelContext<Self>) {
480 let Some(downstream_client) = self.downstream_client.clone() else {
481 return;
482 };
483 let project_id = self.remote_id;
484
485 let update = proto::UpdateProject {
486 project_id,
487 worktrees: self.worktree_metadata_protos(cx),
488 };
489
490 // collab has bad concurrency guarantees, so we send requests in serial.
491 let update_project = if downstream_client.is_via_collab() {
492 Some(downstream_client.request(update))
493 } else {
494 downstream_client.send(update).log_err();
495 None
496 };
497 cx.spawn(|this, mut cx| async move {
498 if let Some(update_project) = update_project {
499 update_project.await?;
500 }
501
502 this.update(&mut cx, |this, cx| {
503 let worktrees = this.worktrees().collect::<Vec<_>>();
504
505 for worktree in worktrees {
506 worktree.update(cx, |worktree, cx| {
507 let client = downstream_client.clone();
508 worktree.observe_updates(project_id, cx, {
509 move |update| {
510 let client = client.clone();
511 async move {
512 if client.is_via_collab() {
513 client.request(update).map(|result| result.is_ok()).await
514 } else {
515 client.send(update).is_ok()
516 }
517 }
518 }
519 });
520 });
521
522 cx.emit(WorktreeStoreEvent::WorktreeUpdateSent(worktree.clone()))
523 }
524
525 anyhow::Ok(())
526 })
527 })
528 .detach_and_log_err(cx);
529 }
530
531 pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
532 self.worktrees()
533 .map(|worktree| {
534 let worktree = worktree.read(cx);
535 proto::WorktreeMetadata {
536 id: worktree.id().to_proto(),
537 root_name: worktree.root_name().into(),
538 visible: worktree.is_visible(),
539 abs_path: worktree.abs_path().to_string_lossy().into(),
540 }
541 })
542 .collect()
543 }
544
545 pub fn shared(
546 &mut self,
547 remote_id: u64,
548 downsteam_client: AnyProtoClient,
549 cx: &mut ModelContext<Self>,
550 ) {
551 self.retain_worktrees = true;
552 self.remote_id = remote_id;
553 self.downstream_client = Some(downsteam_client);
554
555 // When shared, retain all worktrees
556 for worktree_handle in self.worktrees.iter_mut() {
557 match worktree_handle {
558 WorktreeHandle::Strong(_) => {}
559 WorktreeHandle::Weak(worktree) => {
560 if let Some(worktree) = worktree.upgrade() {
561 *worktree_handle = WorktreeHandle::Strong(worktree);
562 }
563 }
564 }
565 }
566 self.send_project_updates(cx);
567 }
568
569 pub fn unshared(&mut self, cx: &mut ModelContext<Self>) {
570 self.retain_worktrees = false;
571 self.downstream_client.take();
572
573 // When not shared, only retain the visible worktrees
574 for worktree_handle in self.worktrees.iter_mut() {
575 if let WorktreeHandle::Strong(worktree) = worktree_handle {
576 let is_visible = worktree.update(cx, |worktree, _| {
577 worktree.stop_observing_updates();
578 worktree.is_visible()
579 });
580 if !is_visible {
581 *worktree_handle = WorktreeHandle::Weak(worktree.downgrade());
582 }
583 }
584 }
585 }
586
587 /// search over all worktrees and return buffers that *might* match the search.
588 pub fn find_search_candidates(
589 &self,
590 query: SearchQuery,
591 limit: usize,
592 open_entries: HashSet<ProjectEntryId>,
593 fs: Arc<dyn Fs>,
594 cx: &ModelContext<Self>,
595 ) -> Receiver<ProjectPath> {
596 let snapshots = self
597 .visible_worktrees(cx)
598 .filter_map(|tree| {
599 let tree = tree.read(cx);
600 Some((tree.snapshot(), tree.as_local()?.settings()))
601 })
602 .collect::<Vec<_>>();
603
604 let executor = cx.background_executor().clone();
605
606 // We want to return entries in the order they are in the worktrees, so we have one
607 // thread that iterates over the worktrees (and ignored directories) as necessary,
608 // and pushes a oneshot::Receiver to the output channel and a oneshot::Sender to the filter
609 // channel.
610 // We spawn a number of workers that take items from the filter channel and check the query
611 // against the version of the file on disk.
612 let (filter_tx, filter_rx) = smol::channel::bounded(64);
613 let (output_tx, mut output_rx) = smol::channel::bounded(64);
614 let (matching_paths_tx, matching_paths_rx) = smol::channel::unbounded();
615
616 let input = cx.background_executor().spawn({
617 let fs = fs.clone();
618 let query = query.clone();
619 async move {
620 Self::find_candidate_paths(
621 fs,
622 snapshots,
623 open_entries,
624 query,
625 filter_tx,
626 output_tx,
627 )
628 .await
629 .log_err();
630 }
631 });
632 const MAX_CONCURRENT_FILE_SCANS: usize = 64;
633 let filters = cx.background_executor().spawn(async move {
634 let fs = &fs;
635 let query = &query;
636 executor
637 .scoped(move |scope| {
638 for _ in 0..MAX_CONCURRENT_FILE_SCANS {
639 let filter_rx = filter_rx.clone();
640 scope.spawn(async move {
641 Self::filter_paths(fs, filter_rx, query).await.log_err();
642 })
643 }
644 })
645 .await;
646 });
647 cx.background_executor()
648 .spawn(async move {
649 let mut matched = 0;
650 while let Some(mut receiver) = output_rx.next().await {
651 let Some(path) = receiver.next().await else {
652 continue;
653 };
654 let Ok(_) = matching_paths_tx.send(path).await else {
655 break;
656 };
657 matched += 1;
658 if matched == limit {
659 break;
660 }
661 }
662 drop(input);
663 drop(filters);
664 })
665 .detach();
666 matching_paths_rx
667 }
668
669 fn scan_ignored_dir<'a>(
670 fs: &'a Arc<dyn Fs>,
671 snapshot: &'a worktree::Snapshot,
672 path: &'a Path,
673 query: &'a SearchQuery,
674 include_root: bool,
675 filter_tx: &'a Sender<MatchingEntry>,
676 output_tx: &'a Sender<oneshot::Receiver<ProjectPath>>,
677 ) -> BoxFuture<'a, Result<()>> {
678 async move {
679 let abs_path = snapshot.abs_path().join(path);
680 let Some(mut files) = fs
681 .read_dir(&abs_path)
682 .await
683 .with_context(|| format!("listing ignored path {abs_path:?}"))
684 .log_err()
685 else {
686 return Ok(());
687 };
688
689 let mut results = Vec::new();
690
691 while let Some(Ok(file)) = files.next().await {
692 let Some(metadata) = fs
693 .metadata(&file)
694 .await
695 .with_context(|| format!("fetching fs metadata for {abs_path:?}"))
696 .log_err()
697 .flatten()
698 else {
699 continue;
700 };
701 if metadata.is_symlink || metadata.is_fifo {
702 continue;
703 }
704 results.push((
705 file.strip_prefix(snapshot.abs_path())?.to_path_buf(),
706 !metadata.is_dir,
707 ))
708 }
709 results.sort_by(|(a_path, a_is_file), (b_path, b_is_file)| {
710 compare_paths((a_path, *a_is_file), (b_path, *b_is_file))
711 });
712 for (path, is_file) in results {
713 if is_file {
714 if query.filters_path() {
715 let matched_path = if include_root {
716 let mut full_path = PathBuf::from(snapshot.root_name());
717 full_path.push(&path);
718 query.file_matches(&full_path)
719 } else {
720 query.file_matches(&path)
721 };
722 if !matched_path {
723 continue;
724 }
725 }
726 let (tx, rx) = oneshot::channel();
727 output_tx.send(rx).await?;
728 filter_tx
729 .send(MatchingEntry {
730 respond: tx,
731 worktree_path: snapshot.abs_path().clone(),
732 path: ProjectPath {
733 worktree_id: snapshot.id(),
734 path: Arc::from(path),
735 },
736 })
737 .await?;
738 } else {
739 Self::scan_ignored_dir(
740 fs,
741 snapshot,
742 &path,
743 query,
744 include_root,
745 filter_tx,
746 output_tx,
747 )
748 .await?;
749 }
750 }
751 Ok(())
752 }
753 .boxed()
754 }
755
756 async fn find_candidate_paths(
757 fs: Arc<dyn Fs>,
758 snapshots: Vec<(worktree::Snapshot, WorktreeSettings)>,
759 open_entries: HashSet<ProjectEntryId>,
760 query: SearchQuery,
761 filter_tx: Sender<MatchingEntry>,
762 output_tx: Sender<oneshot::Receiver<ProjectPath>>,
763 ) -> Result<()> {
764 let include_root = snapshots.len() > 1;
765 for (snapshot, settings) in snapshots {
766 let mut entries: Vec<_> = snapshot.entries(query.include_ignored(), 0).collect();
767 entries.sort_by(|a, b| compare_paths((&a.path, a.is_file()), (&b.path, b.is_file())));
768 for entry in entries {
769 if entry.is_dir() && entry.is_ignored {
770 if !settings.is_path_excluded(&entry.path) {
771 Self::scan_ignored_dir(
772 &fs,
773 &snapshot,
774 &entry.path,
775 &query,
776 include_root,
777 &filter_tx,
778 &output_tx,
779 )
780 .await?;
781 }
782 continue;
783 }
784
785 if entry.is_fifo || !entry.is_file() {
786 continue;
787 }
788
789 if query.filters_path() {
790 let matched_path = if include_root {
791 let mut full_path = PathBuf::from(snapshot.root_name());
792 full_path.push(&entry.path);
793 query.file_matches(&full_path)
794 } else {
795 query.file_matches(&entry.path)
796 };
797 if !matched_path {
798 continue;
799 }
800 }
801
802 let (mut tx, rx) = oneshot::channel();
803
804 if open_entries.contains(&entry.id) {
805 tx.send(ProjectPath {
806 worktree_id: snapshot.id(),
807 path: entry.path.clone(),
808 })
809 .await?;
810 } else {
811 filter_tx
812 .send(MatchingEntry {
813 respond: tx,
814 worktree_path: snapshot.abs_path().clone(),
815 path: ProjectPath {
816 worktree_id: snapshot.id(),
817 path: entry.path.clone(),
818 },
819 })
820 .await?;
821 }
822
823 output_tx.send(rx).await?;
824 }
825 }
826 Ok(())
827 }
828
829 async fn filter_paths(
830 fs: &Arc<dyn Fs>,
831 mut input: Receiver<MatchingEntry>,
832 query: &SearchQuery,
833 ) -> Result<()> {
834 while let Some(mut entry) = input.next().await {
835 let abs_path = entry.worktree_path.join(&entry.path.path);
836 let Some(file) = fs.open_sync(&abs_path).await.log_err() else {
837 continue;
838 };
839 if query.detect(file).unwrap_or(false) {
840 entry.respond.send(entry.path).await?
841 }
842 }
843
844 Ok(())
845 }
846
847 pub async fn handle_create_project_entry(
848 this: Model<Self>,
849 envelope: TypedEnvelope<proto::CreateProjectEntry>,
850 mut cx: AsyncAppContext,
851 ) -> Result<proto::ProjectEntryResponse> {
852 let worktree = this.update(&mut cx, |this, cx| {
853 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
854 this.worktree_for_id(worktree_id, cx)
855 .ok_or_else(|| anyhow!("worktree not found"))
856 })??;
857 Worktree::handle_create_entry(worktree, envelope.payload, cx).await
858 }
859
860 pub async fn handle_rename_project_entry(
861 this: Model<Self>,
862 envelope: TypedEnvelope<proto::RenameProjectEntry>,
863 mut cx: AsyncAppContext,
864 ) -> Result<proto::ProjectEntryResponse> {
865 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
866 let worktree = this.update(&mut cx, |this, cx| {
867 this.worktree_for_entry(entry_id, cx)
868 .ok_or_else(|| anyhow!("worktree not found"))
869 })??;
870 Worktree::handle_rename_entry(worktree, envelope.payload, cx).await
871 }
872
873 pub async fn handle_copy_project_entry(
874 this: Model<Self>,
875 envelope: TypedEnvelope<proto::CopyProjectEntry>,
876 mut cx: AsyncAppContext,
877 ) -> Result<proto::ProjectEntryResponse> {
878 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
879 let worktree = this.update(&mut cx, |this, cx| {
880 this.worktree_for_entry(entry_id, cx)
881 .ok_or_else(|| anyhow!("worktree not found"))
882 })??;
883 Worktree::handle_copy_entry(worktree, envelope.payload, cx).await
884 }
885
886 pub async fn handle_delete_project_entry(
887 this: Model<Self>,
888 envelope: TypedEnvelope<proto::DeleteProjectEntry>,
889 mut cx: AsyncAppContext,
890 ) -> Result<proto::ProjectEntryResponse> {
891 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
892 let worktree = this.update(&mut cx, |this, cx| {
893 this.worktree_for_entry(entry_id, cx)
894 .ok_or_else(|| anyhow!("worktree not found"))
895 })??;
896 Worktree::handle_delete_entry(worktree, envelope.payload, cx).await
897 }
898
899 pub async fn handle_expand_project_entry(
900 this: Model<Self>,
901 envelope: TypedEnvelope<proto::ExpandProjectEntry>,
902 mut cx: AsyncAppContext,
903 ) -> Result<proto::ExpandProjectEntryResponse> {
904 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
905 let worktree = this
906 .update(&mut cx, |this, cx| this.worktree_for_entry(entry_id, cx))?
907 .ok_or_else(|| anyhow!("invalid request"))?;
908 Worktree::handle_expand_entry(worktree, envelope.payload, cx).await
909 }
910}
911
912#[derive(Clone)]
913enum WorktreeHandle {
914 Strong(Model<Worktree>),
915 Weak(WeakModel<Worktree>),
916}
917
918impl WorktreeHandle {
919 fn upgrade(&self) -> Option<Model<Worktree>> {
920 match self {
921 WorktreeHandle::Strong(handle) => Some(handle.clone()),
922 WorktreeHandle::Weak(handle) => handle.upgrade(),
923 }
924 }
925}