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