worktree_store.rs

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