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, 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.background_executor().spawn(async move {
208 match task.await {
209 Ok(worktree) => Ok(worktree),
210 Err(err) => Err(anyhow!("{}", err)),
211 }
212 })
213 }
214
215 fn create_ssh_worktree(
216 &mut self,
217 client: AnyProtoClient,
218 abs_path: impl AsRef<Path>,
219 visible: bool,
220 cx: &mut ModelContext<Self>,
221 ) -> Task<Result<Model<Worktree>, Arc<anyhow::Error>>> {
222 let mut abs_path = abs_path.as_ref().to_string_lossy().to_string();
223 // If we start with `/~` that means the ssh path was something like `ssh://user@host/~/home-dir-folder/`
224 // in which case want to strip the leading the `/`.
225 // On the host-side, the `~` will get expanded.
226 // That's what git does too: https://github.com/libgit2/libgit2/issues/3345#issuecomment-127050850
227 if abs_path.starts_with("/~") {
228 abs_path = abs_path[1..].to_string();
229 }
230 let root_name = PathBuf::from(abs_path.clone())
231 .file_name()
232 .unwrap()
233 .to_string_lossy()
234 .to_string();
235 cx.spawn(|this, mut cx| async move {
236 let response = client
237 .request(proto::AddWorktree {
238 project_id: SSH_PROJECT_ID,
239 path: abs_path.clone(),
240 })
241 .await?;
242
243 if let Some(existing_worktree) = this.read_with(&cx, |this, cx| {
244 this.worktree_for_id(WorktreeId::from_proto(response.worktree_id), cx)
245 })? {
246 return Ok(existing_worktree);
247 }
248
249 let worktree = cx.update(|cx| {
250 Worktree::remote(
251 0,
252 0,
253 proto::WorktreeMetadata {
254 id: response.worktree_id,
255 root_name,
256 visible,
257 abs_path,
258 },
259 client,
260 cx,
261 )
262 })?;
263
264 this.update(&mut cx, |this, cx| this.add(&worktree, cx))?;
265
266 Ok(worktree)
267 })
268 }
269
270 fn create_local_worktree(
271 &mut self,
272 fs: Arc<dyn Fs>,
273 abs_path: impl AsRef<Path>,
274 visible: bool,
275 cx: &mut ModelContext<Self>,
276 ) -> Task<Result<Model<Worktree>, Arc<anyhow::Error>>> {
277 let next_entry_id = self.next_entry_id.clone();
278 let path: Arc<Path> = abs_path.as_ref().into();
279
280 cx.spawn(move |this, mut cx| async move {
281 let worktree = Worktree::local(path.clone(), visible, fs, next_entry_id, &mut cx).await;
282
283 this.update(&mut cx, |project, _| {
284 project.loading_worktrees.remove(&path);
285 })?;
286
287 let worktree = worktree?;
288 this.update(&mut cx, |this, cx| this.add(&worktree, cx))?;
289
290 if visible {
291 cx.update(|cx| {
292 cx.add_recent_document(&path);
293 })
294 .log_err();
295 }
296
297 Ok(worktree)
298 })
299 }
300
301 fn create_dev_server_worktree(
302 &mut self,
303 client: AnyProtoClient,
304 dev_server_project_id: DevServerProjectId,
305 abs_path: impl AsRef<Path>,
306 cx: &mut ModelContext<Self>,
307 ) -> Task<Result<Model<Worktree>, Arc<anyhow::Error>>> {
308 let path: Arc<Path> = abs_path.as_ref().into();
309 let mut paths: Vec<String> = self
310 .visible_worktrees(cx)
311 .map(|worktree| worktree.read(cx).abs_path().to_string_lossy().to_string())
312 .collect();
313 paths.push(path.to_string_lossy().to_string());
314 let request = client.request(proto::UpdateDevServerProject {
315 dev_server_project_id: dev_server_project_id.0,
316 paths,
317 });
318
319 let abs_path = abs_path.as_ref().to_path_buf();
320 cx.spawn(move |project, mut cx| async move {
321 let (tx, rx) = futures::channel::oneshot::channel();
322 let tx = RefCell::new(Some(tx));
323 let Some(project) = project.upgrade() else {
324 return Err(anyhow!("project dropped"))?;
325 };
326 let observer = cx.update(|cx| {
327 cx.observe(&project, move |project, cx| {
328 let abs_path = abs_path.clone();
329 project.update(cx, |project, cx| {
330 if let Some((worktree, _)) = project.find_worktree(&abs_path, cx) {
331 if let Some(tx) = tx.borrow_mut().take() {
332 tx.send(worktree).ok();
333 }
334 }
335 })
336 })
337 })?;
338
339 request.await?;
340 let worktree = rx.await.map_err(|e| anyhow!(e))?;
341 drop(observer);
342 project.update(&mut cx, |project, _| {
343 project.loading_worktrees.remove(&path);
344 })?;
345 Ok(worktree)
346 })
347 }
348
349 #[track_caller]
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.request(update).map(|result| result.is_ok()).await
557 } else {
558 client.send(update).is_ok()
559 }
560 }
561 }
562 });
563 });
564
565 cx.emit(WorktreeStoreEvent::WorktreeUpdateSent(worktree.clone()))
566 }
567
568 anyhow::Ok(())
569 })
570 })
571 .detach_and_log_err(cx);
572 }
573
574 pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
575 self.worktrees()
576 .map(|worktree| {
577 let worktree = worktree.read(cx);
578 proto::WorktreeMetadata {
579 id: worktree.id().to_proto(),
580 root_name: worktree.root_name().into(),
581 visible: worktree.is_visible(),
582 abs_path: worktree.abs_path().to_string_lossy().into(),
583 }
584 })
585 .collect()
586 }
587
588 pub fn shared(
589 &mut self,
590 remote_id: u64,
591 downsteam_client: AnyProtoClient,
592 cx: &mut ModelContext<Self>,
593 ) {
594 self.retain_worktrees = true;
595 self.downstream_client = Some((downsteam_client, remote_id));
596
597 // When shared, retain all worktrees
598 for worktree_handle in self.worktrees.iter_mut() {
599 match worktree_handle {
600 WorktreeHandle::Strong(_) => {}
601 WorktreeHandle::Weak(worktree) => {
602 if let Some(worktree) = worktree.upgrade() {
603 *worktree_handle = WorktreeHandle::Strong(worktree);
604 }
605 }
606 }
607 }
608 self.send_project_updates(cx);
609 }
610
611 pub fn unshared(&mut self, cx: &mut ModelContext<Self>) {
612 self.retain_worktrees = false;
613 self.downstream_client.take();
614
615 // When not shared, only retain the visible worktrees
616 for worktree_handle in self.worktrees.iter_mut() {
617 if let WorktreeHandle::Strong(worktree) = worktree_handle {
618 let is_visible = worktree.update(cx, |worktree, _| {
619 worktree.stop_observing_updates();
620 worktree.is_visible()
621 });
622 if !is_visible {
623 *worktree_handle = WorktreeHandle::Weak(worktree.downgrade());
624 }
625 }
626 }
627 }
628
629 /// search over all worktrees and return buffers that *might* match the search.
630 pub fn find_search_candidates(
631 &self,
632 query: SearchQuery,
633 limit: usize,
634 open_entries: HashSet<ProjectEntryId>,
635 fs: Arc<dyn Fs>,
636 cx: &ModelContext<Self>,
637 ) -> Receiver<ProjectPath> {
638 let snapshots = self
639 .visible_worktrees(cx)
640 .filter_map(|tree| {
641 let tree = tree.read(cx);
642 Some((tree.snapshot(), tree.as_local()?.settings()))
643 })
644 .collect::<Vec<_>>();
645
646 let executor = cx.background_executor().clone();
647
648 // We want to return entries in the order they are in the worktrees, so we have one
649 // thread that iterates over the worktrees (and ignored directories) as necessary,
650 // and pushes a oneshot::Receiver to the output channel and a oneshot::Sender to the filter
651 // channel.
652 // We spawn a number of workers that take items from the filter channel and check the query
653 // against the version of the file on disk.
654 let (filter_tx, filter_rx) = smol::channel::bounded(64);
655 let (output_tx, mut output_rx) = smol::channel::bounded(64);
656 let (matching_paths_tx, matching_paths_rx) = smol::channel::unbounded();
657
658 let input = cx.background_executor().spawn({
659 let fs = fs.clone();
660 let query = query.clone();
661 async move {
662 Self::find_candidate_paths(
663 fs,
664 snapshots,
665 open_entries,
666 query,
667 filter_tx,
668 output_tx,
669 )
670 .await
671 .log_err();
672 }
673 });
674 const MAX_CONCURRENT_FILE_SCANS: usize = 64;
675 let filters = cx.background_executor().spawn(async move {
676 let fs = &fs;
677 let query = &query;
678 executor
679 .scoped(move |scope| {
680 for _ in 0..MAX_CONCURRENT_FILE_SCANS {
681 let filter_rx = filter_rx.clone();
682 scope.spawn(async move {
683 Self::filter_paths(fs, filter_rx, query).await.log_err();
684 })
685 }
686 })
687 .await;
688 });
689 cx.background_executor()
690 .spawn(async move {
691 let mut matched = 0;
692 while let Some(mut receiver) = output_rx.next().await {
693 let Some(path) = receiver.next().await else {
694 continue;
695 };
696 let Ok(_) = matching_paths_tx.send(path).await else {
697 break;
698 };
699 matched += 1;
700 if matched == limit {
701 break;
702 }
703 }
704 drop(input);
705 drop(filters);
706 })
707 .detach();
708 matching_paths_rx
709 }
710
711 fn scan_ignored_dir<'a>(
712 fs: &'a Arc<dyn Fs>,
713 snapshot: &'a worktree::Snapshot,
714 path: &'a Path,
715 query: &'a SearchQuery,
716 include_root: bool,
717 filter_tx: &'a Sender<MatchingEntry>,
718 output_tx: &'a Sender<oneshot::Receiver<ProjectPath>>,
719 ) -> BoxFuture<'a, Result<()>> {
720 async move {
721 let abs_path = snapshot.abs_path().join(path);
722 let Some(mut files) = fs
723 .read_dir(&abs_path)
724 .await
725 .with_context(|| format!("listing ignored path {abs_path:?}"))
726 .log_err()
727 else {
728 return Ok(());
729 };
730
731 let mut results = Vec::new();
732
733 while let Some(Ok(file)) = files.next().await {
734 let Some(metadata) = fs
735 .metadata(&file)
736 .await
737 .with_context(|| format!("fetching fs metadata for {abs_path:?}"))
738 .log_err()
739 .flatten()
740 else {
741 continue;
742 };
743 if metadata.is_symlink || metadata.is_fifo {
744 continue;
745 }
746 results.push((
747 file.strip_prefix(snapshot.abs_path())?.to_path_buf(),
748 !metadata.is_dir,
749 ))
750 }
751 results.sort_by(|(a_path, a_is_file), (b_path, b_is_file)| {
752 compare_paths((a_path, *a_is_file), (b_path, *b_is_file))
753 });
754 for (path, is_file) in results {
755 if is_file {
756 if query.filters_path() {
757 let matched_path = if include_root {
758 let mut full_path = PathBuf::from(snapshot.root_name());
759 full_path.push(&path);
760 query.file_matches(&full_path)
761 } else {
762 query.file_matches(&path)
763 };
764 if !matched_path {
765 continue;
766 }
767 }
768 let (tx, rx) = oneshot::channel();
769 output_tx.send(rx).await?;
770 filter_tx
771 .send(MatchingEntry {
772 respond: tx,
773 worktree_path: snapshot.abs_path().clone(),
774 path: ProjectPath {
775 worktree_id: snapshot.id(),
776 path: Arc::from(path),
777 },
778 })
779 .await?;
780 } else {
781 Self::scan_ignored_dir(
782 fs,
783 snapshot,
784 &path,
785 query,
786 include_root,
787 filter_tx,
788 output_tx,
789 )
790 .await?;
791 }
792 }
793 Ok(())
794 }
795 .boxed()
796 }
797
798 async fn find_candidate_paths(
799 fs: Arc<dyn Fs>,
800 snapshots: Vec<(worktree::Snapshot, WorktreeSettings)>,
801 open_entries: HashSet<ProjectEntryId>,
802 query: SearchQuery,
803 filter_tx: Sender<MatchingEntry>,
804 output_tx: Sender<oneshot::Receiver<ProjectPath>>,
805 ) -> Result<()> {
806 let include_root = snapshots.len() > 1;
807 for (snapshot, settings) in snapshots {
808 let mut entries: Vec<_> = snapshot.entries(query.include_ignored(), 0).collect();
809 entries.sort_by(|a, b| compare_paths((&a.path, a.is_file()), (&b.path, b.is_file())));
810 for entry in entries {
811 if entry.is_dir() && entry.is_ignored {
812 if !settings.is_path_excluded(&entry.path) {
813 Self::scan_ignored_dir(
814 &fs,
815 &snapshot,
816 &entry.path,
817 &query,
818 include_root,
819 &filter_tx,
820 &output_tx,
821 )
822 .await?;
823 }
824 continue;
825 }
826
827 if entry.is_fifo || !entry.is_file() {
828 continue;
829 }
830
831 if query.filters_path() {
832 let matched_path = if include_root {
833 let mut full_path = PathBuf::from(snapshot.root_name());
834 full_path.push(&entry.path);
835 query.file_matches(&full_path)
836 } else {
837 query.file_matches(&entry.path)
838 };
839 if !matched_path {
840 continue;
841 }
842 }
843
844 let (mut tx, rx) = oneshot::channel();
845
846 if open_entries.contains(&entry.id) {
847 tx.send(ProjectPath {
848 worktree_id: snapshot.id(),
849 path: entry.path.clone(),
850 })
851 .await?;
852 } else {
853 filter_tx
854 .send(MatchingEntry {
855 respond: tx,
856 worktree_path: snapshot.abs_path().clone(),
857 path: ProjectPath {
858 worktree_id: snapshot.id(),
859 path: entry.path.clone(),
860 },
861 })
862 .await?;
863 }
864
865 output_tx.send(rx).await?;
866 }
867 }
868 Ok(())
869 }
870
871 async fn filter_paths(
872 fs: &Arc<dyn Fs>,
873 mut input: Receiver<MatchingEntry>,
874 query: &SearchQuery,
875 ) -> Result<()> {
876 while let Some(mut entry) = input.next().await {
877 let abs_path = entry.worktree_path.join(&entry.path.path);
878 let Some(file) = fs.open_sync(&abs_path).await.log_err() else {
879 continue;
880 };
881 if query.detect(file).unwrap_or(false) {
882 entry.respond.send(entry.path).await?
883 }
884 }
885
886 Ok(())
887 }
888
889 pub async fn handle_create_project_entry(
890 this: Model<Self>,
891 envelope: TypedEnvelope<proto::CreateProjectEntry>,
892 mut cx: AsyncAppContext,
893 ) -> Result<proto::ProjectEntryResponse> {
894 let worktree = this.update(&mut cx, |this, cx| {
895 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
896 this.worktree_for_id(worktree_id, cx)
897 .ok_or_else(|| anyhow!("worktree not found"))
898 })??;
899 Worktree::handle_create_entry(worktree, envelope.payload, cx).await
900 }
901
902 pub async fn handle_rename_project_entry(
903 this: Model<Self>,
904 envelope: TypedEnvelope<proto::RenameProjectEntry>,
905 mut cx: AsyncAppContext,
906 ) -> Result<proto::ProjectEntryResponse> {
907 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
908 let worktree = this.update(&mut cx, |this, cx| {
909 this.worktree_for_entry(entry_id, cx)
910 .ok_or_else(|| anyhow!("worktree not found"))
911 })??;
912 Worktree::handle_rename_entry(worktree, envelope.payload, cx).await
913 }
914
915 pub async fn handle_copy_project_entry(
916 this: Model<Self>,
917 envelope: TypedEnvelope<proto::CopyProjectEntry>,
918 mut cx: AsyncAppContext,
919 ) -> Result<proto::ProjectEntryResponse> {
920 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
921 let worktree = this.update(&mut cx, |this, cx| {
922 this.worktree_for_entry(entry_id, cx)
923 .ok_or_else(|| anyhow!("worktree not found"))
924 })??;
925 Worktree::handle_copy_entry(worktree, envelope.payload, cx).await
926 }
927
928 pub async fn handle_delete_project_entry(
929 this: Model<Self>,
930 envelope: TypedEnvelope<proto::DeleteProjectEntry>,
931 mut cx: AsyncAppContext,
932 ) -> Result<proto::ProjectEntryResponse> {
933 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
934 let worktree = this.update(&mut cx, |this, cx| {
935 this.worktree_for_entry(entry_id, cx)
936 .ok_or_else(|| anyhow!("worktree not found"))
937 })??;
938 Worktree::handle_delete_entry(worktree, envelope.payload, cx).await
939 }
940
941 pub async fn handle_expand_project_entry(
942 this: Model<Self>,
943 envelope: TypedEnvelope<proto::ExpandProjectEntry>,
944 mut cx: AsyncAppContext,
945 ) -> Result<proto::ExpandProjectEntryResponse> {
946 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
947 let worktree = this
948 .update(&mut cx, |this, cx| this.worktree_for_entry(entry_id, cx))?
949 .ok_or_else(|| anyhow!("invalid request"))?;
950 Worktree::handle_expand_entry(worktree, envelope.payload, cx).await
951 }
952}
953
954#[derive(Clone)]
955enum WorktreeHandle {
956 Strong(Model<Worktree>),
957 Weak(WeakModel<Worktree>),
958}
959
960impl WorktreeHandle {
961 fn upgrade(&self) -> Option<Model<Worktree>> {
962 match self {
963 WorktreeHandle::Strong(handle) => Some(handle.clone()),
964 WorktreeHandle::Weak(handle) => handle.upgrade(),
965 }
966 }
967}