1use std::{
2 path::{Path, PathBuf},
3 pin::pin,
4 sync::{atomic::AtomicUsize, Arc},
5};
6
7use anyhow::{anyhow, Context as _, Result};
8use collections::{HashMap, HashSet};
9use fs::Fs;
10use futures::{
11 future::{BoxFuture, Shared},
12 FutureExt, SinkExt,
13};
14use gpui::{
15 AppContext, AsyncAppContext, EntityId, EventEmitter, Model, ModelContext, Task, WeakModel,
16};
17use postage::oneshot;
18use rpc::{
19 proto::{self, SSH_PROJECT_ID},
20 AnyProtoClient, ErrorExt, TypedEnvelope,
21};
22use smol::{
23 channel::{Receiver, Sender},
24 stream::StreamExt,
25};
26use text::ReplicaId;
27use util::{paths::SanitizedPath, ResultExt};
28use worktree::{Entry, ProjectEntryId, Worktree, WorktreeId, WorktreeSettings};
29
30use crate::{search::SearchQuery, LspStore, ProjectPath};
31
32struct MatchingEntry {
33 worktree_path: Arc<Path>,
34 path: ProjectPath,
35 respond: oneshot::Sender<ProjectPath>,
36}
37
38enum WorktreeStoreState {
39 Local {
40 fs: Arc<dyn Fs>,
41 },
42 Remote {
43 upstream_client: AnyProtoClient,
44 upstream_project_id: u64,
45 },
46}
47
48pub struct WorktreeStore {
49 next_entry_id: Arc<AtomicUsize>,
50 downstream_client: Option<(AnyProtoClient, u64)>,
51 retain_worktrees: bool,
52 worktrees: Vec<WorktreeHandle>,
53 worktrees_reordered: bool,
54 #[allow(clippy::type_complexity)]
55 loading_worktrees:
56 HashMap<SanitizedPath, Shared<Task<Result<Model<Worktree>, Arc<anyhow::Error>>>>>,
57 state: WorktreeStoreState,
58}
59
60pub enum WorktreeStoreEvent {
61 WorktreeAdded(Model<Worktree>),
62 WorktreeRemoved(EntityId, WorktreeId),
63 WorktreeReleased(EntityId, WorktreeId),
64 WorktreeOrderChanged,
65 WorktreeUpdateSent(Model<Worktree>),
66}
67
68impl EventEmitter<WorktreeStoreEvent> for WorktreeStore {}
69
70impl WorktreeStore {
71 pub fn init(client: &AnyProtoClient) {
72 client.add_model_request_handler(Self::handle_create_project_entry);
73 client.add_model_request_handler(Self::handle_copy_project_entry);
74 client.add_model_request_handler(Self::handle_delete_project_entry);
75 client.add_model_request_handler(Self::handle_expand_project_entry);
76 client.add_model_request_handler(Self::handle_git_branches);
77 client.add_model_request_handler(Self::handle_update_branch);
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 ) -> Self {
97 Self {
98 next_entry_id: Default::default(),
99 loading_worktrees: Default::default(),
100 downstream_client: None,
101 worktrees: Vec::new(),
102 worktrees_reordered: false,
103 retain_worktrees,
104 state: WorktreeStoreState::Remote {
105 upstream_client,
106 upstream_project_id,
107 },
108 }
109 }
110
111 /// Iterates through all worktrees, including ones that don't appear in the project panel
112 pub fn worktrees(&self) -> impl '_ + DoubleEndedIterator<Item = Model<Worktree>> {
113 self.worktrees
114 .iter()
115 .filter_map(move |worktree| worktree.upgrade())
116 }
117
118 /// Iterates through all user-visible worktrees, the ones that appear in the project panel.
119 pub fn visible_worktrees<'a>(
120 &'a self,
121 cx: &'a AppContext,
122 ) -> impl 'a + DoubleEndedIterator<Item = Model<Worktree>> {
123 self.worktrees()
124 .filter(|worktree| worktree.read(cx).is_visible())
125 }
126
127 pub fn worktree_for_id(&self, id: WorktreeId, cx: &AppContext) -> Option<Model<Worktree>> {
128 self.worktrees()
129 .find(|worktree| worktree.read(cx).id() == id)
130 }
131
132 pub fn current_branch(&self, repository: ProjectPath, cx: &AppContext) -> Option<Arc<str>> {
133 self.worktree_for_id(repository.worktree_id, cx)?
134 .read(cx)
135 .git_entry(repository.path)?
136 .branch()
137 }
138
139 pub fn worktree_for_entry(
140 &self,
141 entry_id: ProjectEntryId,
142 cx: &AppContext,
143 ) -> Option<Model<Worktree>> {
144 self.worktrees()
145 .find(|worktree| worktree.read(cx).contains_entry(entry_id))
146 }
147
148 pub fn find_worktree(
149 &self,
150 abs_path: impl Into<SanitizedPath>,
151 cx: &AppContext,
152 ) -> Option<(Model<Worktree>, PathBuf)> {
153 let abs_path: SanitizedPath = abs_path.into();
154 for tree in self.worktrees() {
155 if let Ok(relative_path) = abs_path.as_path().strip_prefix(tree.read(cx).abs_path()) {
156 return Some((tree.clone(), relative_path.into()));
157 }
158 }
159 None
160 }
161
162 pub fn find_or_create_worktree(
163 &mut self,
164 abs_path: impl AsRef<Path>,
165 visible: bool,
166 cx: &mut ModelContext<Self>,
167 ) -> Task<Result<(Model<Worktree>, PathBuf)>> {
168 let abs_path = abs_path.as_ref();
169 if let Some((tree, relative_path)) = self.find_worktree(abs_path, cx) {
170 Task::ready(Ok((tree, relative_path)))
171 } else {
172 let worktree = self.create_worktree(abs_path, visible, cx);
173 cx.background_executor()
174 .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
175 }
176 }
177
178 pub fn entry_for_id<'a>(
179 &'a self,
180 entry_id: ProjectEntryId,
181 cx: &'a AppContext,
182 ) -> Option<&'a Entry> {
183 self.worktrees()
184 .find_map(|worktree| worktree.read(cx).entry_for_id(entry_id))
185 }
186
187 pub fn worktree_and_entry_for_id<'a>(
188 &'a self,
189 entry_id: ProjectEntryId,
190 cx: &'a AppContext,
191 ) -> Option<(Model<Worktree>, &'a Entry)> {
192 self.worktrees().find_map(|worktree| {
193 worktree
194 .read(cx)
195 .entry_for_id(entry_id)
196 .map(|e| (worktree.clone(), e))
197 })
198 }
199
200 pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
201 self.worktree_for_id(path.worktree_id, cx)?
202 .read(cx)
203 .entry_for_path(&path.path)
204 .cloned()
205 }
206
207 pub fn create_worktree(
208 &mut self,
209 abs_path: impl Into<SanitizedPath>,
210 visible: bool,
211 cx: &mut ModelContext<Self>,
212 ) -> Task<Result<Model<Worktree>>> {
213 let abs_path: SanitizedPath = abs_path.into();
214 if !self.loading_worktrees.contains_key(&abs_path) {
215 let task = match &self.state {
216 WorktreeStoreState::Remote {
217 upstream_client, ..
218 } => {
219 if upstream_client.is_via_collab() {
220 Task::ready(Err(Arc::new(anyhow!("cannot create worktrees via collab"))))
221 } else {
222 self.create_ssh_worktree(
223 upstream_client.clone(),
224 abs_path.clone(),
225 visible,
226 cx,
227 )
228 }
229 }
230 WorktreeStoreState::Local { fs } => {
231 self.create_local_worktree(fs.clone(), abs_path.clone(), visible, cx)
232 }
233 };
234
235 self.loading_worktrees
236 .insert(abs_path.clone(), task.shared());
237 }
238 let task = self.loading_worktrees.get(&abs_path).unwrap().clone();
239 cx.spawn(|this, mut cx| async move {
240 let result = task.await;
241 this.update(&mut cx, |this, _| this.loading_worktrees.remove(&abs_path))
242 .ok();
243 match result {
244 Ok(worktree) => Ok(worktree),
245 Err(err) => Err((*err).cloned()),
246 }
247 })
248 }
249
250 fn create_ssh_worktree(
251 &mut self,
252 client: AnyProtoClient,
253 abs_path: impl Into<SanitizedPath>,
254 visible: bool,
255 cx: &mut ModelContext<Self>,
256 ) -> Task<Result<Model<Worktree>, Arc<anyhow::Error>>> {
257 let mut abs_path = Into::<SanitizedPath>::into(abs_path).to_string();
258 // If we start with `/~` that means the ssh path was something like `ssh://user@host/~/home-dir-folder/`
259 // in which case want to strip the leading the `/`.
260 // On the host-side, the `~` will get expanded.
261 // That's what git does too: https://github.com/libgit2/libgit2/issues/3345#issuecomment-127050850
262 if abs_path.starts_with("/~") {
263 abs_path = abs_path[1..].to_string();
264 }
265 if abs_path.is_empty() || abs_path == "/" {
266 abs_path = "~/".to_string();
267 }
268 cx.spawn(|this, mut cx| async move {
269 let this = this.upgrade().context("Dropped worktree store")?;
270
271 let response = client
272 .request(proto::AddWorktree {
273 project_id: SSH_PROJECT_ID,
274 path: abs_path.clone(),
275 visible,
276 })
277 .await?;
278
279 if let Some(existing_worktree) = this.read_with(&cx, |this, cx| {
280 this.worktree_for_id(WorktreeId::from_proto(response.worktree_id), cx)
281 })? {
282 return Ok(existing_worktree);
283 }
284
285 let root_name = PathBuf::from(&response.canonicalized_path)
286 .file_name()
287 .map(|n| n.to_string_lossy().to_string())
288 .unwrap_or(response.canonicalized_path.to_string());
289
290 let worktree = cx.update(|cx| {
291 Worktree::remote(
292 SSH_PROJECT_ID,
293 0,
294 proto::WorktreeMetadata {
295 id: response.worktree_id,
296 root_name,
297 visible,
298 abs_path: response.canonicalized_path,
299 },
300 client,
301 cx,
302 )
303 })?;
304
305 this.update(&mut cx, |this, cx| {
306 this.add(&worktree, cx);
307 })?;
308 Ok(worktree)
309 })
310 }
311
312 fn create_local_worktree(
313 &mut self,
314 fs: Arc<dyn Fs>,
315 abs_path: impl Into<SanitizedPath>,
316 visible: bool,
317 cx: &mut ModelContext<Self>,
318 ) -> Task<Result<Model<Worktree>, Arc<anyhow::Error>>> {
319 let next_entry_id = self.next_entry_id.clone();
320 let path: SanitizedPath = abs_path.into();
321
322 cx.spawn(move |this, mut cx| async move {
323 let worktree = Worktree::local(path.clone(), visible, fs, next_entry_id, &mut cx).await;
324
325 let worktree = worktree?;
326
327 this.update(&mut cx, |this, cx| this.add(&worktree, cx))?;
328
329 if visible {
330 cx.update(|cx| {
331 cx.add_recent_document(path.as_path());
332 })
333 .log_err();
334 }
335
336 Ok(worktree)
337 })
338 }
339
340 pub fn add(&mut self, worktree: &Model<Worktree>, cx: &mut ModelContext<Self>) {
341 let worktree_id = worktree.read(cx).id();
342 debug_assert!(self.worktrees().all(|w| w.read(cx).id() != worktree_id));
343
344 let push_strong_handle = self.retain_worktrees || worktree.read(cx).is_visible();
345 let handle = if push_strong_handle {
346 WorktreeHandle::Strong(worktree.clone())
347 } else {
348 WorktreeHandle::Weak(worktree.downgrade())
349 };
350 if self.worktrees_reordered {
351 self.worktrees.push(handle);
352 } else {
353 let i = match self
354 .worktrees
355 .binary_search_by_key(&Some(worktree.read(cx).abs_path()), |other| {
356 other.upgrade().map(|worktree| worktree.read(cx).abs_path())
357 }) {
358 Ok(i) | Err(i) => i,
359 };
360 self.worktrees.insert(i, handle);
361 }
362
363 cx.emit(WorktreeStoreEvent::WorktreeAdded(worktree.clone()));
364 self.send_project_updates(cx);
365
366 let handle_id = worktree.entity_id();
367 cx.observe_release(worktree, move |this, worktree, cx| {
368 cx.emit(WorktreeStoreEvent::WorktreeReleased(
369 handle_id,
370 worktree.id(),
371 ));
372 cx.emit(WorktreeStoreEvent::WorktreeRemoved(
373 handle_id,
374 worktree.id(),
375 ));
376 this.send_project_updates(cx);
377 })
378 .detach();
379 }
380
381 pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
382 self.worktrees.retain(|worktree| {
383 if let Some(worktree) = worktree.upgrade() {
384 if worktree.read(cx).id() == id_to_remove {
385 cx.emit(WorktreeStoreEvent::WorktreeRemoved(
386 worktree.entity_id(),
387 id_to_remove,
388 ));
389 false
390 } else {
391 true
392 }
393 } else {
394 false
395 }
396 });
397 self.send_project_updates(cx);
398 }
399
400 pub fn set_worktrees_reordered(&mut self, worktrees_reordered: bool) {
401 self.worktrees_reordered = worktrees_reordered;
402 }
403
404 fn upstream_client(&self) -> Option<(AnyProtoClient, u64)> {
405 match &self.state {
406 WorktreeStoreState::Remote {
407 upstream_client,
408 upstream_project_id,
409 ..
410 } => Some((upstream_client.clone(), *upstream_project_id)),
411 WorktreeStoreState::Local { .. } => None,
412 }
413 }
414
415 pub fn set_worktrees_from_proto(
416 &mut self,
417 worktrees: Vec<proto::WorktreeMetadata>,
418 replica_id: ReplicaId,
419 cx: &mut ModelContext<Self>,
420 ) -> Result<()> {
421 let mut old_worktrees_by_id = self
422 .worktrees
423 .drain(..)
424 .filter_map(|worktree| {
425 let worktree = worktree.upgrade()?;
426 Some((worktree.read(cx).id(), worktree))
427 })
428 .collect::<HashMap<_, _>>();
429
430 let (client, project_id) = self
431 .upstream_client()
432 .clone()
433 .ok_or_else(|| anyhow!("invalid project"))?;
434
435 for worktree in worktrees {
436 if let Some(old_worktree) =
437 old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
438 {
439 let push_strong_handle =
440 self.retain_worktrees || old_worktree.read(cx).is_visible();
441 let handle = if push_strong_handle {
442 WorktreeHandle::Strong(old_worktree.clone())
443 } else {
444 WorktreeHandle::Weak(old_worktree.downgrade())
445 };
446 self.worktrees.push(handle);
447 } else {
448 self.add(
449 &Worktree::remote(project_id, replica_id, worktree, client.clone(), cx),
450 cx,
451 );
452 }
453 }
454 self.send_project_updates(cx);
455
456 Ok(())
457 }
458
459 pub fn move_worktree(
460 &mut self,
461 source: WorktreeId,
462 destination: WorktreeId,
463 cx: &mut ModelContext<Self>,
464 ) -> Result<()> {
465 if source == destination {
466 return Ok(());
467 }
468
469 let mut source_index = None;
470 let mut destination_index = None;
471 for (i, worktree) in self.worktrees.iter().enumerate() {
472 if let Some(worktree) = worktree.upgrade() {
473 let worktree_id = worktree.read(cx).id();
474 if worktree_id == source {
475 source_index = Some(i);
476 if destination_index.is_some() {
477 break;
478 }
479 } else if worktree_id == destination {
480 destination_index = Some(i);
481 if source_index.is_some() {
482 break;
483 }
484 }
485 }
486 }
487
488 let source_index =
489 source_index.with_context(|| format!("Missing worktree for id {source}"))?;
490 let destination_index =
491 destination_index.with_context(|| format!("Missing worktree for id {destination}"))?;
492
493 if source_index == destination_index {
494 return Ok(());
495 }
496
497 let worktree_to_move = self.worktrees.remove(source_index);
498 self.worktrees.insert(destination_index, worktree_to_move);
499 self.worktrees_reordered = true;
500 cx.emit(WorktreeStoreEvent::WorktreeOrderChanged);
501 cx.notify();
502 Ok(())
503 }
504
505 pub fn disconnected_from_host(&mut self, cx: &mut AppContext) {
506 for worktree in &self.worktrees {
507 if let Some(worktree) = worktree.upgrade() {
508 worktree.update(cx, |worktree, _| {
509 if let Some(worktree) = worktree.as_remote_mut() {
510 worktree.disconnected_from_host();
511 }
512 });
513 }
514 }
515 }
516
517 pub fn send_project_updates(&mut self, cx: &mut ModelContext<Self>) {
518 let Some((downstream_client, project_id)) = self.downstream_client.clone() else {
519 return;
520 };
521
522 let update = proto::UpdateProject {
523 project_id,
524 worktrees: self.worktree_metadata_protos(cx),
525 };
526
527 // collab has bad concurrency guarantees, so we send requests in serial.
528 let update_project = if downstream_client.is_via_collab() {
529 Some(downstream_client.request(update))
530 } else {
531 downstream_client.send(update).log_err();
532 None
533 };
534 cx.spawn(|this, mut cx| async move {
535 if let Some(update_project) = update_project {
536 update_project.await?;
537 }
538
539 this.update(&mut cx, |this, cx| {
540 let worktrees = this.worktrees().collect::<Vec<_>>();
541
542 for worktree in worktrees {
543 worktree.update(cx, |worktree, cx| {
544 let client = downstream_client.clone();
545 worktree.observe_updates(project_id, cx, {
546 move |update| {
547 let client = client.clone();
548 async move {
549 if client.is_via_collab() {
550 client
551 .request(update)
552 .map(|result| result.log_err().is_some())
553 .await
554 } else {
555 client.send(update).log_err().is_some()
556 }
557 }
558 }
559 });
560 });
561
562 cx.emit(WorktreeStoreEvent::WorktreeUpdateSent(worktree.clone()))
563 }
564
565 anyhow::Ok(())
566 })
567 })
568 .detach_and_log_err(cx);
569 }
570
571 pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
572 self.worktrees()
573 .map(|worktree| {
574 let worktree = worktree.read(cx);
575 proto::WorktreeMetadata {
576 id: worktree.id().to_proto(),
577 root_name: worktree.root_name().into(),
578 visible: worktree.is_visible(),
579 abs_path: worktree.abs_path().to_string_lossy().into(),
580 }
581 })
582 .collect()
583 }
584
585 pub fn shared(
586 &mut self,
587 remote_id: u64,
588 downstream_client: AnyProtoClient,
589 cx: &mut ModelContext<Self>,
590 ) {
591 self.retain_worktrees = true;
592 self.downstream_client = Some((downstream_client, remote_id));
593
594 // When shared, retain all worktrees
595 for worktree_handle in self.worktrees.iter_mut() {
596 match worktree_handle {
597 WorktreeHandle::Strong(_) => {}
598 WorktreeHandle::Weak(worktree) => {
599 if let Some(worktree) = worktree.upgrade() {
600 *worktree_handle = WorktreeHandle::Strong(worktree);
601 }
602 }
603 }
604 }
605 self.send_project_updates(cx);
606 }
607
608 pub fn unshared(&mut self, cx: &mut ModelContext<Self>) {
609 self.retain_worktrees = false;
610 self.downstream_client.take();
611
612 // When not shared, only retain the visible worktrees
613 for worktree_handle in self.worktrees.iter_mut() {
614 if let WorktreeHandle::Strong(worktree) = worktree_handle {
615 let is_visible = worktree.update(cx, |worktree, _| {
616 worktree.stop_observing_updates();
617 worktree.is_visible()
618 });
619 if !is_visible {
620 *worktree_handle = WorktreeHandle::Weak(worktree.downgrade());
621 }
622 }
623 }
624 }
625
626 /// search over all worktrees and return buffers that *might* match the search.
627 pub fn find_search_candidates(
628 &self,
629 query: SearchQuery,
630 limit: usize,
631 open_entries: HashSet<ProjectEntryId>,
632 fs: Arc<dyn Fs>,
633 cx: &ModelContext<Self>,
634 ) -> Receiver<ProjectPath> {
635 let snapshots = self
636 .visible_worktrees(cx)
637 .filter_map(|tree| {
638 let tree = tree.read(cx);
639 Some((tree.snapshot(), tree.as_local()?.settings()))
640 })
641 .collect::<Vec<_>>();
642
643 let executor = cx.background_executor().clone();
644
645 // We want to return entries in the order they are in the worktrees, so we have one
646 // thread that iterates over the worktrees (and ignored directories) as necessary,
647 // and pushes a oneshot::Receiver to the output channel and a oneshot::Sender to the filter
648 // channel.
649 // We spawn a number of workers that take items from the filter channel and check the query
650 // against the version of the file on disk.
651 let (filter_tx, filter_rx) = smol::channel::bounded(64);
652 let (output_tx, output_rx) = smol::channel::bounded(64);
653 let (matching_paths_tx, matching_paths_rx) = smol::channel::unbounded();
654
655 let input = cx.background_executor().spawn({
656 let fs = fs.clone();
657 let query = query.clone();
658 async move {
659 Self::find_candidate_paths(
660 fs,
661 snapshots,
662 open_entries,
663 query,
664 filter_tx,
665 output_tx,
666 )
667 .await
668 .log_err();
669 }
670 });
671 const MAX_CONCURRENT_FILE_SCANS: usize = 64;
672 let filters = cx.background_executor().spawn(async move {
673 let fs = &fs;
674 let query = &query;
675 executor
676 .scoped(move |scope| {
677 for _ in 0..MAX_CONCURRENT_FILE_SCANS {
678 let filter_rx = filter_rx.clone();
679 scope.spawn(async move {
680 Self::filter_paths(fs, filter_rx, query).await.log_err();
681 })
682 }
683 })
684 .await;
685 });
686 cx.background_executor()
687 .spawn(async move {
688 let mut matched = 0;
689 while let Ok(mut receiver) = output_rx.recv().await {
690 let Some(path) = receiver.next().await else {
691 continue;
692 };
693 let Ok(_) = matching_paths_tx.send(path).await else {
694 break;
695 };
696 matched += 1;
697 if matched == limit {
698 break;
699 }
700 }
701 drop(input);
702 drop(filters);
703 })
704 .detach();
705 matching_paths_rx
706 }
707
708 fn scan_ignored_dir<'a>(
709 fs: &'a Arc<dyn Fs>,
710 snapshot: &'a worktree::Snapshot,
711 path: &'a Path,
712 query: &'a SearchQuery,
713 include_root: bool,
714 filter_tx: &'a Sender<MatchingEntry>,
715 output_tx: &'a Sender<oneshot::Receiver<ProjectPath>>,
716 ) -> BoxFuture<'a, Result<()>> {
717 async move {
718 let abs_path = snapshot.abs_path().join(path);
719 let Some(mut files) = fs
720 .read_dir(&abs_path)
721 .await
722 .with_context(|| format!("listing ignored path {abs_path:?}"))
723 .log_err()
724 else {
725 return Ok(());
726 };
727
728 let mut results = Vec::new();
729
730 while let Some(Ok(file)) = files.next().await {
731 let Some(metadata) = fs
732 .metadata(&file)
733 .await
734 .with_context(|| format!("fetching fs metadata for {abs_path:?}"))
735 .log_err()
736 .flatten()
737 else {
738 continue;
739 };
740 if metadata.is_symlink || metadata.is_fifo {
741 continue;
742 }
743 results.push((
744 file.strip_prefix(snapshot.abs_path())?.to_path_buf(),
745 !metadata.is_dir,
746 ))
747 }
748 results.sort_by(|(a_path, _), (b_path, _)| a_path.cmp(b_path));
749 for (path, is_file) in results {
750 if is_file {
751 if query.filters_path() {
752 let matched_path = if include_root {
753 let mut full_path = PathBuf::from(snapshot.root_name());
754 full_path.push(&path);
755 query.file_matches(&full_path)
756 } else {
757 query.file_matches(&path)
758 };
759 if !matched_path {
760 continue;
761 }
762 }
763 let (tx, rx) = oneshot::channel();
764 output_tx.send(rx).await?;
765 filter_tx
766 .send(MatchingEntry {
767 respond: tx,
768 worktree_path: snapshot.abs_path().clone(),
769 path: ProjectPath {
770 worktree_id: snapshot.id(),
771 path: Arc::from(path),
772 },
773 })
774 .await?;
775 } else {
776 Self::scan_ignored_dir(
777 fs,
778 snapshot,
779 &path,
780 query,
781 include_root,
782 filter_tx,
783 output_tx,
784 )
785 .await?;
786 }
787 }
788 Ok(())
789 }
790 .boxed()
791 }
792
793 async fn find_candidate_paths(
794 fs: Arc<dyn Fs>,
795 snapshots: Vec<(worktree::Snapshot, WorktreeSettings)>,
796 open_entries: HashSet<ProjectEntryId>,
797 query: SearchQuery,
798 filter_tx: Sender<MatchingEntry>,
799 output_tx: Sender<oneshot::Receiver<ProjectPath>>,
800 ) -> Result<()> {
801 let include_root = snapshots.len() > 1;
802 for (snapshot, settings) in snapshots {
803 for entry in snapshot.entries(query.include_ignored(), 0) {
804 if entry.is_dir() && entry.is_ignored {
805 if !settings.is_path_excluded(&entry.path) {
806 Self::scan_ignored_dir(
807 &fs,
808 &snapshot,
809 &entry.path,
810 &query,
811 include_root,
812 &filter_tx,
813 &output_tx,
814 )
815 .await?;
816 }
817 continue;
818 }
819
820 if entry.is_fifo || !entry.is_file() {
821 continue;
822 }
823
824 if query.filters_path() {
825 let matched_path = if include_root {
826 let mut full_path = PathBuf::from(snapshot.root_name());
827 full_path.push(&entry.path);
828 query.file_matches(&full_path)
829 } else {
830 query.file_matches(&entry.path)
831 };
832 if !matched_path {
833 continue;
834 }
835 }
836
837 let (mut tx, rx) = oneshot::channel();
838
839 if open_entries.contains(&entry.id) {
840 tx.send(ProjectPath {
841 worktree_id: snapshot.id(),
842 path: entry.path.clone(),
843 })
844 .await?;
845 } else {
846 filter_tx
847 .send(MatchingEntry {
848 respond: tx,
849 worktree_path: snapshot.abs_path().clone(),
850 path: ProjectPath {
851 worktree_id: snapshot.id(),
852 path: entry.path.clone(),
853 },
854 })
855 .await?;
856 }
857
858 output_tx.send(rx).await?;
859 }
860 }
861 Ok(())
862 }
863
864 pub fn branches(
865 &self,
866 project_path: ProjectPath,
867 cx: &AppContext,
868 ) -> Task<Result<Vec<git::repository::Branch>>> {
869 let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) else {
870 return Task::ready(Err(anyhow!("No worktree found for ProjectPath")));
871 };
872
873 match worktree.read(cx) {
874 Worktree::Local(local_worktree) => {
875 let branches = util::maybe!({
876 let worktree_error = |error| {
877 format!(
878 "{} for worktree {}",
879 error,
880 local_worktree.abs_path().to_string_lossy()
881 )
882 };
883
884 let entry = local_worktree
885 .git_entry(project_path.path)
886 .with_context(|| worktree_error("No git entry found"))?;
887
888 let repo = local_worktree
889 .get_local_repo(&entry)
890 .with_context(|| worktree_error("No repository found"))?
891 .repo()
892 .clone();
893
894 repo.branches()
895 });
896
897 Task::ready(branches)
898 }
899 Worktree::Remote(remote_worktree) => {
900 let request = remote_worktree.client().request(proto::GitBranches {
901 project_id: remote_worktree.project_id(),
902 repository: Some(proto::ProjectPath {
903 worktree_id: project_path.worktree_id.to_proto(),
904 path: project_path.path.to_string_lossy().to_string(), // Root path
905 }),
906 });
907
908 cx.background_executor().spawn(async move {
909 let response = request.await?;
910
911 let branches = response
912 .branches
913 .into_iter()
914 .map(|proto_branch| git::repository::Branch {
915 is_head: proto_branch.is_head,
916 name: proto_branch.name.into(),
917 unix_timestamp: proto_branch
918 .unix_timestamp
919 .map(|timestamp| timestamp as i64),
920 })
921 .collect();
922
923 Ok(branches)
924 })
925 }
926 }
927 }
928
929 pub fn update_or_create_branch(
930 &self,
931 repository: ProjectPath,
932 new_branch: String,
933 cx: &AppContext,
934 ) -> Task<Result<()>> {
935 let Some(worktree) = self.worktree_for_id(repository.worktree_id, cx) else {
936 return Task::ready(Err(anyhow!("No worktree found for ProjectPath")));
937 };
938
939 match worktree.read(cx) {
940 Worktree::Local(local_worktree) => {
941 let result = util::maybe!({
942 let worktree_error = |error| {
943 format!(
944 "{} for worktree {}",
945 error,
946 local_worktree.abs_path().to_string_lossy()
947 )
948 };
949
950 let entry = local_worktree
951 .git_entry(repository.path)
952 .with_context(|| worktree_error("No git entry found"))?;
953
954 let repo = local_worktree
955 .get_local_repo(&entry)
956 .with_context(|| worktree_error("No repository found"))?
957 .repo()
958 .clone();
959
960 if !repo.branch_exits(&new_branch)? {
961 repo.create_branch(&new_branch)?;
962 }
963
964 repo.change_branch(&new_branch)?;
965
966 Ok(())
967 });
968
969 Task::ready(result)
970 }
971 Worktree::Remote(remote_worktree) => {
972 let request = remote_worktree.client().request(proto::UpdateGitBranch {
973 project_id: remote_worktree.project_id(),
974 repository: Some(proto::ProjectPath {
975 worktree_id: repository.worktree_id.to_proto(),
976 path: repository.path.to_string_lossy().to_string(), // Root path
977 }),
978 branch_name: new_branch,
979 });
980
981 cx.background_executor().spawn(async move {
982 request.await?;
983 Ok(())
984 })
985 }
986 }
987 }
988
989 async fn filter_paths(
990 fs: &Arc<dyn Fs>,
991 mut input: Receiver<MatchingEntry>,
992 query: &SearchQuery,
993 ) -> Result<()> {
994 let mut input = pin!(input);
995 while let Some(mut entry) = input.next().await {
996 let abs_path = entry.worktree_path.join(&entry.path.path);
997 let Some(file) = fs.open_sync(&abs_path).await.log_err() else {
998 continue;
999 };
1000 if query.detect(file).unwrap_or(false) {
1001 entry.respond.send(entry.path).await?
1002 }
1003 }
1004
1005 Ok(())
1006 }
1007
1008 pub async fn handle_create_project_entry(
1009 this: Model<Self>,
1010 envelope: TypedEnvelope<proto::CreateProjectEntry>,
1011 mut cx: AsyncAppContext,
1012 ) -> Result<proto::ProjectEntryResponse> {
1013 let worktree = this.update(&mut cx, |this, cx| {
1014 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
1015 this.worktree_for_id(worktree_id, cx)
1016 .ok_or_else(|| anyhow!("worktree not found"))
1017 })??;
1018 Worktree::handle_create_entry(worktree, envelope.payload, cx).await
1019 }
1020
1021 pub async fn handle_rename_project_entry(
1022 this: Model<super::Project>,
1023 envelope: TypedEnvelope<proto::RenameProjectEntry>,
1024 mut cx: AsyncAppContext,
1025 ) -> Result<proto::ProjectEntryResponse> {
1026 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
1027 let (worktree_id, worktree, old_path, is_dir) = this
1028 .update(&mut cx, |this, cx| {
1029 this.worktree_store
1030 .read(cx)
1031 .worktree_and_entry_for_id(entry_id, cx)
1032 .map(|(worktree, entry)| {
1033 (
1034 worktree.read(cx).id(),
1035 worktree,
1036 entry.path.clone(),
1037 entry.is_dir(),
1038 )
1039 })
1040 })?
1041 .ok_or_else(|| anyhow!("worktree not found"))?;
1042 let (old_abs_path, new_abs_path) = {
1043 let root_path = worktree.update(&mut cx, |this, _| this.abs_path())?;
1044 (
1045 root_path.join(&old_path),
1046 root_path.join(&envelope.payload.new_path),
1047 )
1048 };
1049 let lsp_store = this
1050 .update(&mut cx, |this, _| this.lsp_store())?
1051 .downgrade();
1052 LspStore::will_rename_entry(
1053 lsp_store,
1054 worktree_id,
1055 &old_abs_path,
1056 &new_abs_path,
1057 is_dir,
1058 cx.clone(),
1059 )
1060 .await;
1061 let response = Worktree::handle_rename_entry(worktree, envelope.payload, cx.clone()).await;
1062 this.update(&mut cx, |this, cx| {
1063 this.lsp_store().read(cx).did_rename_entry(
1064 worktree_id,
1065 &old_abs_path,
1066 &new_abs_path,
1067 is_dir,
1068 );
1069 })
1070 .ok();
1071 response
1072 }
1073
1074 pub async fn handle_copy_project_entry(
1075 this: Model<Self>,
1076 envelope: TypedEnvelope<proto::CopyProjectEntry>,
1077 mut cx: AsyncAppContext,
1078 ) -> Result<proto::ProjectEntryResponse> {
1079 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
1080 let worktree = this.update(&mut cx, |this, cx| {
1081 this.worktree_for_entry(entry_id, cx)
1082 .ok_or_else(|| anyhow!("worktree not found"))
1083 })??;
1084 Worktree::handle_copy_entry(worktree, envelope.payload, cx).await
1085 }
1086
1087 pub async fn handle_delete_project_entry(
1088 this: Model<Self>,
1089 envelope: TypedEnvelope<proto::DeleteProjectEntry>,
1090 mut cx: AsyncAppContext,
1091 ) -> Result<proto::ProjectEntryResponse> {
1092 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
1093 let worktree = this.update(&mut cx, |this, cx| {
1094 this.worktree_for_entry(entry_id, cx)
1095 .ok_or_else(|| anyhow!("worktree not found"))
1096 })??;
1097 Worktree::handle_delete_entry(worktree, envelope.payload, cx).await
1098 }
1099
1100 pub async fn handle_expand_project_entry(
1101 this: Model<Self>,
1102 envelope: TypedEnvelope<proto::ExpandProjectEntry>,
1103 mut cx: AsyncAppContext,
1104 ) -> Result<proto::ExpandProjectEntryResponse> {
1105 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
1106 let worktree = this
1107 .update(&mut cx, |this, cx| this.worktree_for_entry(entry_id, cx))?
1108 .ok_or_else(|| anyhow!("invalid request"))?;
1109 Worktree::handle_expand_entry(worktree, envelope.payload, cx).await
1110 }
1111
1112 pub async fn handle_git_branches(
1113 this: Model<Self>,
1114 branches: TypedEnvelope<proto::GitBranches>,
1115 cx: AsyncAppContext,
1116 ) -> Result<proto::GitBranchesResponse> {
1117 let project_path = branches
1118 .payload
1119 .repository
1120 .clone()
1121 .context("Invalid GitBranches call")?;
1122 let project_path = ProjectPath {
1123 worktree_id: WorktreeId::from_proto(project_path.worktree_id),
1124 path: Path::new(&project_path.path).into(),
1125 };
1126
1127 let branches = this
1128 .read_with(&cx, |this, cx| this.branches(project_path, cx))?
1129 .await?;
1130
1131 Ok(proto::GitBranchesResponse {
1132 branches: branches
1133 .into_iter()
1134 .map(|branch| proto::Branch {
1135 is_head: branch.is_head,
1136 name: branch.name.to_string(),
1137 unix_timestamp: branch.unix_timestamp.map(|timestamp| timestamp as u64),
1138 })
1139 .collect(),
1140 })
1141 }
1142
1143 pub async fn handle_update_branch(
1144 this: Model<Self>,
1145 update_branch: TypedEnvelope<proto::UpdateGitBranch>,
1146 cx: AsyncAppContext,
1147 ) -> Result<proto::Ack> {
1148 let project_path = update_branch
1149 .payload
1150 .repository
1151 .clone()
1152 .context("Invalid GitBranches call")?;
1153 let project_path = ProjectPath {
1154 worktree_id: WorktreeId::from_proto(project_path.worktree_id),
1155 path: Path::new(&project_path.path).into(),
1156 };
1157 let new_branch = update_branch.payload.branch_name;
1158
1159 this.read_with(&cx, |this, cx| {
1160 this.update_or_create_branch(project_path, new_branch, cx)
1161 })?
1162 .await?;
1163
1164 Ok(proto::Ack {})
1165 }
1166}
1167
1168#[derive(Clone, Debug)]
1169enum WorktreeHandle {
1170 Strong(Model<Worktree>),
1171 Weak(WeakModel<Worktree>),
1172}
1173
1174impl WorktreeHandle {
1175 fn upgrade(&self) -> Option<Model<Worktree>> {
1176 match self {
1177 WorktreeHandle::Strong(handle) => Some(handle.clone()),
1178 WorktreeHandle::Weak(handle) => handle.upgrade(),
1179 }
1180 }
1181}