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