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 println!(
513 "worktree. is_local: {:?}, is_remote: {:?}",
514 worktree.is_local(),
515 worktree.is_remote()
516 );
517 if let Some(worktree) = worktree.as_remote_mut() {
518 worktree.disconnected_from_host();
519 }
520 });
521 }
522 }
523 }
524
525 pub fn send_project_updates(&mut self, cx: &mut ModelContext<Self>) {
526 let Some((downstream_client, project_id)) = self.downstream_client.clone() else {
527 return;
528 };
529
530 let update = proto::UpdateProject {
531 project_id,
532 worktrees: self.worktree_metadata_protos(cx),
533 };
534
535 // collab has bad concurrency guarantees, so we send requests in serial.
536 let update_project = if downstream_client.is_via_collab() {
537 Some(downstream_client.request(update))
538 } else {
539 downstream_client.send(update).log_err();
540 None
541 };
542 cx.spawn(|this, mut cx| async move {
543 if let Some(update_project) = update_project {
544 update_project.await?;
545 }
546
547 this.update(&mut cx, |this, cx| {
548 let worktrees = this.worktrees().collect::<Vec<_>>();
549
550 for worktree in worktrees {
551 worktree.update(cx, |worktree, cx| {
552 let client = downstream_client.clone();
553 worktree.observe_updates(project_id, cx, {
554 move |update| {
555 let client = client.clone();
556 async move {
557 if client.is_via_collab() {
558 client
559 .request(update)
560 .map(|result| result.log_err().is_some())
561 .await
562 } else {
563 client.send(update).log_err().is_some()
564 }
565 }
566 }
567 });
568 });
569
570 cx.emit(WorktreeStoreEvent::WorktreeUpdateSent(worktree.clone()))
571 }
572
573 anyhow::Ok(())
574 })
575 })
576 .detach_and_log_err(cx);
577 }
578
579 pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
580 self.worktrees()
581 .map(|worktree| {
582 let worktree = worktree.read(cx);
583 proto::WorktreeMetadata {
584 id: worktree.id().to_proto(),
585 root_name: worktree.root_name().into(),
586 visible: worktree.is_visible(),
587 abs_path: worktree.abs_path().to_string_lossy().into(),
588 }
589 })
590 .collect()
591 }
592
593 pub fn shared(
594 &mut self,
595 remote_id: u64,
596 downsteam_client: AnyProtoClient,
597 cx: &mut ModelContext<Self>,
598 ) {
599 self.retain_worktrees = true;
600 self.downstream_client = Some((downsteam_client, remote_id));
601
602 // When shared, retain all worktrees
603 for worktree_handle in self.worktrees.iter_mut() {
604 match worktree_handle {
605 WorktreeHandle::Strong(_) => {}
606 WorktreeHandle::Weak(worktree) => {
607 if let Some(worktree) = worktree.upgrade() {
608 *worktree_handle = WorktreeHandle::Strong(worktree);
609 }
610 }
611 }
612 }
613 self.send_project_updates(cx);
614 }
615
616 pub fn unshared(&mut self, cx: &mut ModelContext<Self>) {
617 self.retain_worktrees = false;
618 self.downstream_client.take();
619
620 // When not shared, only retain the visible worktrees
621 for worktree_handle in self.worktrees.iter_mut() {
622 if let WorktreeHandle::Strong(worktree) = worktree_handle {
623 let is_visible = worktree.update(cx, |worktree, _| {
624 worktree.stop_observing_updates();
625 worktree.is_visible()
626 });
627 if !is_visible {
628 *worktree_handle = WorktreeHandle::Weak(worktree.downgrade());
629 }
630 }
631 }
632 }
633
634 /// search over all worktrees and return buffers that *might* match the search.
635 pub fn find_search_candidates(
636 &self,
637 query: SearchQuery,
638 limit: usize,
639 open_entries: HashSet<ProjectEntryId>,
640 fs: Arc<dyn Fs>,
641 cx: &ModelContext<Self>,
642 ) -> Receiver<ProjectPath> {
643 let snapshots = self
644 .visible_worktrees(cx)
645 .filter_map(|tree| {
646 let tree = tree.read(cx);
647 Some((tree.snapshot(), tree.as_local()?.settings()))
648 })
649 .collect::<Vec<_>>();
650
651 let executor = cx.background_executor().clone();
652
653 // We want to return entries in the order they are in the worktrees, so we have one
654 // thread that iterates over the worktrees (and ignored directories) as necessary,
655 // and pushes a oneshot::Receiver to the output channel and a oneshot::Sender to the filter
656 // channel.
657 // We spawn a number of workers that take items from the filter channel and check the query
658 // against the version of the file on disk.
659 let (filter_tx, filter_rx) = smol::channel::bounded(64);
660 let (output_tx, mut output_rx) = smol::channel::bounded(64);
661 let (matching_paths_tx, matching_paths_rx) = smol::channel::unbounded();
662
663 let input = cx.background_executor().spawn({
664 let fs = fs.clone();
665 let query = query.clone();
666 async move {
667 Self::find_candidate_paths(
668 fs,
669 snapshots,
670 open_entries,
671 query,
672 filter_tx,
673 output_tx,
674 )
675 .await
676 .log_err();
677 }
678 });
679 const MAX_CONCURRENT_FILE_SCANS: usize = 64;
680 let filters = cx.background_executor().spawn(async move {
681 let fs = &fs;
682 let query = &query;
683 executor
684 .scoped(move |scope| {
685 for _ in 0..MAX_CONCURRENT_FILE_SCANS {
686 let filter_rx = filter_rx.clone();
687 scope.spawn(async move {
688 Self::filter_paths(fs, filter_rx, query).await.log_err();
689 })
690 }
691 })
692 .await;
693 });
694 cx.background_executor()
695 .spawn(async move {
696 let mut matched = 0;
697 while let Some(mut receiver) = output_rx.next().await {
698 let Some(path) = receiver.next().await else {
699 continue;
700 };
701 let Ok(_) = matching_paths_tx.send(path).await else {
702 break;
703 };
704 matched += 1;
705 if matched == limit {
706 break;
707 }
708 }
709 drop(input);
710 drop(filters);
711 })
712 .detach();
713 matching_paths_rx
714 }
715
716 fn scan_ignored_dir<'a>(
717 fs: &'a Arc<dyn Fs>,
718 snapshot: &'a worktree::Snapshot,
719 path: &'a Path,
720 query: &'a SearchQuery,
721 include_root: bool,
722 filter_tx: &'a Sender<MatchingEntry>,
723 output_tx: &'a Sender<oneshot::Receiver<ProjectPath>>,
724 ) -> BoxFuture<'a, Result<()>> {
725 async move {
726 let abs_path = snapshot.abs_path().join(path);
727 let Some(mut files) = fs
728 .read_dir(&abs_path)
729 .await
730 .with_context(|| format!("listing ignored path {abs_path:?}"))
731 .log_err()
732 else {
733 return Ok(());
734 };
735
736 let mut results = Vec::new();
737
738 while let Some(Ok(file)) = files.next().await {
739 let Some(metadata) = fs
740 .metadata(&file)
741 .await
742 .with_context(|| format!("fetching fs metadata for {abs_path:?}"))
743 .log_err()
744 .flatten()
745 else {
746 continue;
747 };
748 if metadata.is_symlink || metadata.is_fifo {
749 continue;
750 }
751 results.push((
752 file.strip_prefix(snapshot.abs_path())?.to_path_buf(),
753 !metadata.is_dir,
754 ))
755 }
756 results.sort_by(|(a_path, a_is_file), (b_path, b_is_file)| {
757 compare_paths((a_path, *a_is_file), (b_path, *b_is_file))
758 });
759 for (path, is_file) in results {
760 if is_file {
761 if query.filters_path() {
762 let matched_path = if include_root {
763 let mut full_path = PathBuf::from(snapshot.root_name());
764 full_path.push(&path);
765 query.file_matches(&full_path)
766 } else {
767 query.file_matches(&path)
768 };
769 if !matched_path {
770 continue;
771 }
772 }
773 let (tx, rx) = oneshot::channel();
774 output_tx.send(rx).await?;
775 filter_tx
776 .send(MatchingEntry {
777 respond: tx,
778 worktree_path: snapshot.abs_path().clone(),
779 path: ProjectPath {
780 worktree_id: snapshot.id(),
781 path: Arc::from(path),
782 },
783 })
784 .await?;
785 } else {
786 Self::scan_ignored_dir(
787 fs,
788 snapshot,
789 &path,
790 query,
791 include_root,
792 filter_tx,
793 output_tx,
794 )
795 .await?;
796 }
797 }
798 Ok(())
799 }
800 .boxed()
801 }
802
803 async fn find_candidate_paths(
804 fs: Arc<dyn Fs>,
805 snapshots: Vec<(worktree::Snapshot, WorktreeSettings)>,
806 open_entries: HashSet<ProjectEntryId>,
807 query: SearchQuery,
808 filter_tx: Sender<MatchingEntry>,
809 output_tx: Sender<oneshot::Receiver<ProjectPath>>,
810 ) -> Result<()> {
811 let include_root = snapshots.len() > 1;
812 for (snapshot, settings) in snapshots {
813 let mut entries: Vec<_> = snapshot.entries(query.include_ignored(), 0).collect();
814 entries.sort_by(|a, b| compare_paths((&a.path, a.is_file()), (&b.path, b.is_file())));
815 for entry in entries {
816 if entry.is_dir() && entry.is_ignored {
817 if !settings.is_path_excluded(&entry.path) {
818 Self::scan_ignored_dir(
819 &fs,
820 &snapshot,
821 &entry.path,
822 &query,
823 include_root,
824 &filter_tx,
825 &output_tx,
826 )
827 .await?;
828 }
829 continue;
830 }
831
832 if entry.is_fifo || !entry.is_file() {
833 continue;
834 }
835
836 if query.filters_path() {
837 let matched_path = if include_root {
838 let mut full_path = PathBuf::from(snapshot.root_name());
839 full_path.push(&entry.path);
840 query.file_matches(&full_path)
841 } else {
842 query.file_matches(&entry.path)
843 };
844 if !matched_path {
845 continue;
846 }
847 }
848
849 let (mut tx, rx) = oneshot::channel();
850
851 if open_entries.contains(&entry.id) {
852 tx.send(ProjectPath {
853 worktree_id: snapshot.id(),
854 path: entry.path.clone(),
855 })
856 .await?;
857 } else {
858 filter_tx
859 .send(MatchingEntry {
860 respond: tx,
861 worktree_path: snapshot.abs_path().clone(),
862 path: ProjectPath {
863 worktree_id: snapshot.id(),
864 path: entry.path.clone(),
865 },
866 })
867 .await?;
868 }
869
870 output_tx.send(rx).await?;
871 }
872 }
873 Ok(())
874 }
875
876 async fn filter_paths(
877 fs: &Arc<dyn Fs>,
878 mut input: Receiver<MatchingEntry>,
879 query: &SearchQuery,
880 ) -> Result<()> {
881 while let Some(mut entry) = input.next().await {
882 let abs_path = entry.worktree_path.join(&entry.path.path);
883 let Some(file) = fs.open_sync(&abs_path).await.log_err() else {
884 continue;
885 };
886 if query.detect(file).unwrap_or(false) {
887 entry.respond.send(entry.path).await?
888 }
889 }
890
891 Ok(())
892 }
893
894 pub async fn handle_create_project_entry(
895 this: Model<Self>,
896 envelope: TypedEnvelope<proto::CreateProjectEntry>,
897 mut cx: AsyncAppContext,
898 ) -> Result<proto::ProjectEntryResponse> {
899 let worktree = this.update(&mut cx, |this, cx| {
900 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
901 this.worktree_for_id(worktree_id, cx)
902 .ok_or_else(|| anyhow!("worktree not found"))
903 })??;
904 Worktree::handle_create_entry(worktree, envelope.payload, cx).await
905 }
906
907 pub async fn handle_rename_project_entry(
908 this: Model<Self>,
909 envelope: TypedEnvelope<proto::RenameProjectEntry>,
910 mut cx: AsyncAppContext,
911 ) -> Result<proto::ProjectEntryResponse> {
912 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
913 let worktree = this.update(&mut cx, |this, cx| {
914 this.worktree_for_entry(entry_id, cx)
915 .ok_or_else(|| anyhow!("worktree not found"))
916 })??;
917 Worktree::handle_rename_entry(worktree, envelope.payload, cx).await
918 }
919
920 pub async fn handle_copy_project_entry(
921 this: Model<Self>,
922 envelope: TypedEnvelope<proto::CopyProjectEntry>,
923 mut cx: AsyncAppContext,
924 ) -> Result<proto::ProjectEntryResponse> {
925 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
926 let worktree = this.update(&mut cx, |this, cx| {
927 this.worktree_for_entry(entry_id, cx)
928 .ok_or_else(|| anyhow!("worktree not found"))
929 })??;
930 Worktree::handle_copy_entry(worktree, envelope.payload, cx).await
931 }
932
933 pub async fn handle_delete_project_entry(
934 this: Model<Self>,
935 envelope: TypedEnvelope<proto::DeleteProjectEntry>,
936 mut cx: AsyncAppContext,
937 ) -> Result<proto::ProjectEntryResponse> {
938 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
939 let worktree = this.update(&mut cx, |this, cx| {
940 this.worktree_for_entry(entry_id, cx)
941 .ok_or_else(|| anyhow!("worktree not found"))
942 })??;
943 Worktree::handle_delete_entry(worktree, envelope.payload, cx).await
944 }
945
946 pub async fn handle_expand_project_entry(
947 this: Model<Self>,
948 envelope: TypedEnvelope<proto::ExpandProjectEntry>,
949 mut cx: AsyncAppContext,
950 ) -> Result<proto::ExpandProjectEntryResponse> {
951 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
952 let worktree = this
953 .update(&mut cx, |this, cx| this.worktree_for_entry(entry_id, cx))?
954 .ok_or_else(|| anyhow!("invalid request"))?;
955 Worktree::handle_expand_entry(worktree, envelope.payload, cx).await
956 }
957}
958
959#[derive(Clone)]
960enum WorktreeHandle {
961 Strong(Model<Worktree>),
962 Weak(WeakModel<Worktree>),
963}
964
965impl WorktreeHandle {
966 fn upgrade(&self) -> Option<Model<Worktree>> {
967 match self {
968 WorktreeHandle::Strong(handle) => Some(handle.clone()),
969 WorktreeHandle::Weak(handle) => handle.upgrade(),
970 }
971 }
972}