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