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