1pub mod fs;
2mod ignore;
3mod worktree;
4
5use anyhow::{anyhow, Result};
6use client::{proto, Client, PeerId, TypedEnvelope, User, UserStore};
7use clock::ReplicaId;
8use collections::HashMap;
9use futures::Future;
10use fuzzy::{PathMatch, PathMatchCandidate, PathMatchCandidateSet};
11use gpui::{
12 AppContext, AsyncAppContext, Entity, ModelContext, ModelHandle, MutableAppContext, Task,
13};
14use language::{Buffer, DiagnosticEntry, LanguageRegistry};
15use lsp::DiagnosticSeverity;
16use postage::{prelude::Stream, watch};
17use std::{
18 path::Path,
19 sync::{atomic::AtomicBool, Arc},
20};
21use util::{ResultExt, TryFutureExt as _};
22
23pub use fs::*;
24pub use worktree::*;
25
26pub struct Project {
27 worktrees: Vec<ModelHandle<Worktree>>,
28 active_entry: Option<ProjectEntry>,
29 languages: Arc<LanguageRegistry>,
30 client: Arc<client::Client>,
31 user_store: ModelHandle<UserStore>,
32 fs: Arc<dyn Fs>,
33 client_state: ProjectClientState,
34 collaborators: HashMap<PeerId, Collaborator>,
35 subscriptions: Vec<client::Subscription>,
36}
37
38enum ProjectClientState {
39 Local {
40 is_shared: bool,
41 remote_id_tx: watch::Sender<Option<u64>>,
42 remote_id_rx: watch::Receiver<Option<u64>>,
43 _maintain_remote_id_task: Task<Option<()>>,
44 },
45 Remote {
46 sharing_has_stopped: bool,
47 remote_id: u64,
48 replica_id: ReplicaId,
49 },
50}
51
52#[derive(Clone, Debug)]
53pub struct Collaborator {
54 pub user: Arc<User>,
55 pub peer_id: PeerId,
56 pub replica_id: ReplicaId,
57}
58
59#[derive(Debug)]
60pub enum Event {
61 ActiveEntryChanged(Option<ProjectEntry>),
62 WorktreeRemoved(usize),
63 DiagnosticsUpdated(ProjectPath),
64}
65
66#[derive(Clone, Debug, Eq, PartialEq, Hash)]
67pub struct ProjectPath {
68 pub worktree_id: usize,
69 pub path: Arc<Path>,
70}
71
72#[derive(Clone)]
73pub struct DiagnosticSummary {
74 pub error_count: usize,
75 pub warning_count: usize,
76 pub info_count: usize,
77 pub hint_count: usize,
78}
79
80impl DiagnosticSummary {
81 fn new<'a, T: 'a>(diagnostics: impl IntoIterator<Item = &'a DiagnosticEntry<T>>) -> Self {
82 let mut this = Self {
83 error_count: 0,
84 warning_count: 0,
85 info_count: 0,
86 hint_count: 0,
87 };
88
89 for entry in diagnostics {
90 if entry.diagnostic.is_primary {
91 match entry.diagnostic.severity {
92 DiagnosticSeverity::ERROR => this.error_count += 1,
93 DiagnosticSeverity::WARNING => this.warning_count += 1,
94 DiagnosticSeverity::INFORMATION => this.info_count += 1,
95 DiagnosticSeverity::HINT => this.hint_count += 1,
96 _ => {}
97 }
98 }
99 }
100
101 this
102 }
103}
104
105#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
106pub struct ProjectEntry {
107 pub worktree_id: usize,
108 pub entry_id: usize,
109}
110
111impl Project {
112 pub fn local(
113 client: Arc<Client>,
114 user_store: ModelHandle<UserStore>,
115 languages: Arc<LanguageRegistry>,
116 fs: Arc<dyn Fs>,
117 cx: &mut MutableAppContext,
118 ) -> ModelHandle<Self> {
119 cx.add_model(|cx: &mut ModelContext<Self>| {
120 let (remote_id_tx, remote_id_rx) = watch::channel();
121 let _maintain_remote_id_task = cx.spawn_weak({
122 let rpc = client.clone();
123 move |this, mut cx| {
124 async move {
125 let mut status = rpc.status();
126 while let Some(status) = status.recv().await {
127 if let Some(this) = this.upgrade(&cx) {
128 let remote_id = if let client::Status::Connected { .. } = status {
129 let response = rpc.request(proto::RegisterProject {}).await?;
130 Some(response.project_id)
131 } else {
132 None
133 };
134
135 if let Some(project_id) = remote_id {
136 let mut registrations = Vec::new();
137 this.read_with(&cx, |this, cx| {
138 for worktree in &this.worktrees {
139 let worktree_id = worktree.id() as u64;
140 let worktree = worktree.read(cx).as_local().unwrap();
141 registrations.push(rpc.request(
142 proto::RegisterWorktree {
143 project_id,
144 worktree_id,
145 root_name: worktree.root_name().to_string(),
146 authorized_logins: worktree.authorized_logins(),
147 },
148 ));
149 }
150 });
151 for registration in registrations {
152 registration.await?;
153 }
154 }
155 this.update(&mut cx, |this, cx| this.set_remote_id(remote_id, cx));
156 }
157 }
158 Ok(())
159 }
160 .log_err()
161 }
162 });
163
164 Self {
165 worktrees: Default::default(),
166 collaborators: Default::default(),
167 client_state: ProjectClientState::Local {
168 is_shared: false,
169 remote_id_tx,
170 remote_id_rx,
171 _maintain_remote_id_task,
172 },
173 subscriptions: Vec::new(),
174 active_entry: None,
175 languages,
176 client,
177 user_store,
178 fs,
179 }
180 })
181 }
182
183 pub async fn remote(
184 remote_id: u64,
185 client: Arc<Client>,
186 user_store: ModelHandle<UserStore>,
187 languages: Arc<LanguageRegistry>,
188 fs: Arc<dyn Fs>,
189 cx: &mut AsyncAppContext,
190 ) -> Result<ModelHandle<Self>> {
191 client.authenticate_and_connect(&cx).await?;
192
193 let response = client
194 .request(proto::JoinProject {
195 project_id: remote_id,
196 })
197 .await?;
198
199 let replica_id = response.replica_id as ReplicaId;
200
201 let mut worktrees = Vec::new();
202 for worktree in response.worktrees {
203 worktrees.push(
204 Worktree::remote(
205 remote_id,
206 replica_id,
207 worktree,
208 client.clone(),
209 user_store.clone(),
210 languages.clone(),
211 cx,
212 )
213 .await?,
214 );
215 }
216
217 let user_ids = response
218 .collaborators
219 .iter()
220 .map(|peer| peer.user_id)
221 .collect();
222 user_store
223 .update(cx, |user_store, cx| user_store.load_users(user_ids, cx))
224 .await?;
225 let mut collaborators = HashMap::default();
226 for message in response.collaborators {
227 let collaborator = Collaborator::from_proto(message, &user_store, cx).await?;
228 collaborators.insert(collaborator.peer_id, collaborator);
229 }
230
231 Ok(cx.add_model(|cx| Self {
232 worktrees,
233 active_entry: None,
234 collaborators,
235 languages,
236 user_store,
237 fs,
238 subscriptions: vec![
239 client.subscribe_to_entity(remote_id, cx, Self::handle_unshare_project),
240 client.subscribe_to_entity(remote_id, cx, Self::handle_add_collaborator),
241 client.subscribe_to_entity(remote_id, cx, Self::handle_remove_collaborator),
242 client.subscribe_to_entity(remote_id, cx, Self::handle_share_worktree),
243 client.subscribe_to_entity(remote_id, cx, Self::handle_unregister_worktree),
244 client.subscribe_to_entity(remote_id, cx, Self::handle_update_worktree),
245 client.subscribe_to_entity(remote_id, cx, Self::handle_update_buffer),
246 client.subscribe_to_entity(remote_id, cx, Self::handle_buffer_saved),
247 ],
248 client,
249 client_state: ProjectClientState::Remote {
250 sharing_has_stopped: false,
251 remote_id,
252 replica_id,
253 },
254 }))
255 }
256
257 fn set_remote_id(&mut self, remote_id: Option<u64>, cx: &mut ModelContext<Self>) {
258 if let ProjectClientState::Local { remote_id_tx, .. } = &mut self.client_state {
259 *remote_id_tx.borrow_mut() = remote_id;
260 }
261
262 self.subscriptions.clear();
263 if let Some(remote_id) = remote_id {
264 let client = &self.client;
265 self.subscriptions.extend([
266 client.subscribe_to_entity(remote_id, cx, Self::handle_open_buffer),
267 client.subscribe_to_entity(remote_id, cx, Self::handle_close_buffer),
268 client.subscribe_to_entity(remote_id, cx, Self::handle_add_collaborator),
269 client.subscribe_to_entity(remote_id, cx, Self::handle_remove_collaborator),
270 client.subscribe_to_entity(remote_id, cx, Self::handle_update_worktree),
271 client.subscribe_to_entity(remote_id, cx, Self::handle_update_buffer),
272 client.subscribe_to_entity(remote_id, cx, Self::handle_save_buffer),
273 client.subscribe_to_entity(remote_id, cx, Self::handle_buffer_saved),
274 ]);
275 }
276 }
277
278 pub fn remote_id(&self) -> Option<u64> {
279 match &self.client_state {
280 ProjectClientState::Local { remote_id_rx, .. } => *remote_id_rx.borrow(),
281 ProjectClientState::Remote { remote_id, .. } => Some(*remote_id),
282 }
283 }
284
285 pub fn next_remote_id(&self) -> impl Future<Output = u64> {
286 let mut id = None;
287 let mut watch = None;
288 match &self.client_state {
289 ProjectClientState::Local { remote_id_rx, .. } => watch = Some(remote_id_rx.clone()),
290 ProjectClientState::Remote { remote_id, .. } => id = Some(*remote_id),
291 }
292
293 async move {
294 if let Some(id) = id {
295 return id;
296 }
297 let mut watch = watch.unwrap();
298 loop {
299 let id = *watch.borrow();
300 if let Some(id) = id {
301 return id;
302 }
303 watch.recv().await;
304 }
305 }
306 }
307
308 pub fn replica_id(&self) -> ReplicaId {
309 match &self.client_state {
310 ProjectClientState::Local { .. } => 0,
311 ProjectClientState::Remote { replica_id, .. } => *replica_id,
312 }
313 }
314
315 pub fn collaborators(&self) -> &HashMap<PeerId, Collaborator> {
316 &self.collaborators
317 }
318
319 pub fn worktrees(&self) -> &[ModelHandle<Worktree>] {
320 &self.worktrees
321 }
322
323 pub fn worktree_for_id(&self, id: usize, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
324 self.worktrees
325 .iter()
326 .find(|worktree| worktree.read(cx).id() == id)
327 .cloned()
328 }
329
330 pub fn share(&self, cx: &mut ModelContext<Self>) -> Task<anyhow::Result<()>> {
331 let rpc = self.client.clone();
332 cx.spawn(|this, mut cx| async move {
333 let project_id = this.update(&mut cx, |this, _| {
334 if let ProjectClientState::Local {
335 is_shared,
336 remote_id_rx,
337 ..
338 } = &mut this.client_state
339 {
340 *is_shared = true;
341 remote_id_rx
342 .borrow()
343 .ok_or_else(|| anyhow!("no project id"))
344 } else {
345 Err(anyhow!("can't share a remote project"))
346 }
347 })?;
348
349 rpc.request(proto::ShareProject { project_id }).await?;
350 let mut tasks = Vec::new();
351 this.update(&mut cx, |this, cx| {
352 for worktree in &this.worktrees {
353 worktree.update(cx, |worktree, cx| {
354 let worktree = worktree.as_local_mut().unwrap();
355 tasks.push(worktree.share(project_id, cx));
356 });
357 }
358 });
359 for task in tasks {
360 task.await?;
361 }
362 this.update(&mut cx, |_, cx| cx.notify());
363 Ok(())
364 })
365 }
366
367 pub fn unshare(&self, cx: &mut ModelContext<Self>) -> Task<anyhow::Result<()>> {
368 let rpc = self.client.clone();
369 cx.spawn(|this, mut cx| async move {
370 let project_id = this.update(&mut cx, |this, _| {
371 if let ProjectClientState::Local {
372 is_shared,
373 remote_id_rx,
374 ..
375 } = &mut this.client_state
376 {
377 *is_shared = false;
378 remote_id_rx
379 .borrow()
380 .ok_or_else(|| anyhow!("no project id"))
381 } else {
382 Err(anyhow!("can't share a remote project"))
383 }
384 })?;
385
386 rpc.send(proto::UnshareProject { project_id }).await?;
387 this.update(&mut cx, |this, cx| {
388 this.collaborators.clear();
389 cx.notify()
390 });
391 Ok(())
392 })
393 }
394
395 pub fn is_read_only(&self) -> bool {
396 match &self.client_state {
397 ProjectClientState::Local { .. } => false,
398 ProjectClientState::Remote {
399 sharing_has_stopped,
400 ..
401 } => *sharing_has_stopped,
402 }
403 }
404
405 pub fn is_local(&self) -> bool {
406 match &self.client_state {
407 ProjectClientState::Local { .. } => true,
408 ProjectClientState::Remote { .. } => false,
409 }
410 }
411
412 pub fn open_buffer(
413 &self,
414 path: ProjectPath,
415 cx: &mut ModelContext<Self>,
416 ) -> Task<Result<ModelHandle<Buffer>>> {
417 if let Some(worktree) = self.worktree_for_id(path.worktree_id, cx) {
418 worktree.update(cx, |worktree, cx| worktree.open_buffer(path.path, cx))
419 } else {
420 cx.spawn(|_, _| async move { Err(anyhow!("no such worktree")) })
421 }
422 }
423
424 pub fn is_shared(&self) -> bool {
425 match &self.client_state {
426 ProjectClientState::Local { is_shared, .. } => *is_shared,
427 ProjectClientState::Remote { .. } => false,
428 }
429 }
430
431 pub fn add_local_worktree(
432 &mut self,
433 abs_path: impl AsRef<Path>,
434 cx: &mut ModelContext<Self>,
435 ) -> Task<Result<ModelHandle<Worktree>>> {
436 let fs = self.fs.clone();
437 let client = self.client.clone();
438 let user_store = self.user_store.clone();
439 let languages = self.languages.clone();
440 let path = Arc::from(abs_path.as_ref());
441 cx.spawn(|project, mut cx| async move {
442 let worktree =
443 Worktree::open_local(client.clone(), user_store, path, fs, languages, &mut cx)
444 .await?;
445
446 let (remote_project_id, is_shared) = project.update(&mut cx, |project, cx| {
447 project.add_worktree(worktree.clone(), cx);
448 (project.remote_id(), project.is_shared())
449 });
450
451 if let Some(project_id) = remote_project_id {
452 let worktree_id = worktree.id() as u64;
453 let register_message = worktree.update(&mut cx, |worktree, _| {
454 let worktree = worktree.as_local_mut().unwrap();
455 proto::RegisterWorktree {
456 project_id,
457 worktree_id,
458 root_name: worktree.root_name().to_string(),
459 authorized_logins: worktree.authorized_logins(),
460 }
461 });
462 client.request(register_message).await?;
463 if is_shared {
464 worktree
465 .update(&mut cx, |worktree, cx| {
466 worktree.as_local_mut().unwrap().share(project_id, cx)
467 })
468 .await?;
469 }
470 }
471
472 Ok(worktree)
473 })
474 }
475
476 fn add_worktree(&mut self, worktree: ModelHandle<Worktree>, cx: &mut ModelContext<Self>) {
477 cx.observe(&worktree, |_, _, cx| cx.notify()).detach();
478 cx.subscribe(&worktree, |_, worktree, event, cx| match event {
479 worktree::Event::DiagnosticsUpdated(path) => {
480 cx.emit(Event::DiagnosticsUpdated(ProjectPath {
481 worktree_id: worktree.id(),
482 path: path.clone(),
483 }));
484 }
485 })
486 .detach();
487 self.worktrees.push(worktree);
488 cx.notify();
489 }
490
491 pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
492 let new_active_entry = entry.and_then(|project_path| {
493 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
494 let entry = worktree.read(cx).entry_for_path(project_path.path)?;
495 Some(ProjectEntry {
496 worktree_id: project_path.worktree_id,
497 entry_id: entry.id,
498 })
499 });
500 if new_active_entry != self.active_entry {
501 self.active_entry = new_active_entry;
502 cx.emit(Event::ActiveEntryChanged(new_active_entry));
503 }
504 }
505
506 pub fn diagnose(&self, cx: &mut ModelContext<Self>) {
507 for worktree_handle in &self.worktrees {
508 if let Some(worktree) = worktree_handle.read(cx).as_local() {
509 for language in worktree.languages() {
510 if let Some(provider) = language.diagnostic_provider().cloned() {
511 let worktree_path = worktree.abs_path().clone();
512 let worktree_handle = worktree_handle.downgrade();
513 cx.spawn_weak(|_, mut cx| async move {
514 let diagnostics = provider.diagnose(worktree_path).await.log_err()?;
515 let worktree_handle = worktree_handle.upgrade(&cx)?;
516 worktree_handle.update(&mut cx, |worktree, cx| {
517 for (path, diagnostics) in diagnostics {
518 worktree
519 .update_diagnostics_from_provider(
520 path.into(),
521 diagnostics,
522 cx,
523 )
524 .log_err()?;
525 }
526 Some(())
527 })
528 })
529 .detach();
530 }
531 }
532 }
533 }
534 }
535
536 pub fn diagnostic_summaries<'a>(
537 &'a self,
538 cx: &'a AppContext,
539 ) -> impl Iterator<Item = (ProjectPath, DiagnosticSummary)> + 'a {
540 self.worktrees.iter().flat_map(move |worktree| {
541 let worktree_id = worktree.id();
542 worktree
543 .read(cx)
544 .diagnostic_summaries()
545 .map(move |(path, summary)| (ProjectPath { worktree_id, path }, summary))
546 })
547 }
548
549 pub fn active_entry(&self) -> Option<ProjectEntry> {
550 self.active_entry
551 }
552
553 // RPC message handlers
554
555 fn handle_unshare_project(
556 &mut self,
557 _: TypedEnvelope<proto::UnshareProject>,
558 _: Arc<Client>,
559 cx: &mut ModelContext<Self>,
560 ) -> Result<()> {
561 if let ProjectClientState::Remote {
562 sharing_has_stopped,
563 ..
564 } = &mut self.client_state
565 {
566 *sharing_has_stopped = true;
567 self.collaborators.clear();
568 cx.notify();
569 Ok(())
570 } else {
571 unreachable!()
572 }
573 }
574
575 fn handle_add_collaborator(
576 &mut self,
577 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
578 _: Arc<Client>,
579 cx: &mut ModelContext<Self>,
580 ) -> Result<()> {
581 let user_store = self.user_store.clone();
582 let collaborator = envelope
583 .payload
584 .collaborator
585 .take()
586 .ok_or_else(|| anyhow!("empty collaborator"))?;
587
588 cx.spawn(|this, mut cx| {
589 async move {
590 let collaborator =
591 Collaborator::from_proto(collaborator, &user_store, &mut cx).await?;
592 this.update(&mut cx, |this, cx| {
593 this.collaborators
594 .insert(collaborator.peer_id, collaborator);
595 cx.notify();
596 });
597 Ok(())
598 }
599 .log_err()
600 })
601 .detach();
602
603 Ok(())
604 }
605
606 fn handle_remove_collaborator(
607 &mut self,
608 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
609 _: Arc<Client>,
610 cx: &mut ModelContext<Self>,
611 ) -> Result<()> {
612 let peer_id = PeerId(envelope.payload.peer_id);
613 let replica_id = self
614 .collaborators
615 .remove(&peer_id)
616 .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
617 .replica_id;
618 for worktree in &self.worktrees {
619 worktree.update(cx, |worktree, cx| {
620 worktree.remove_collaborator(peer_id, replica_id, cx);
621 })
622 }
623 Ok(())
624 }
625
626 fn handle_share_worktree(
627 &mut self,
628 envelope: TypedEnvelope<proto::ShareWorktree>,
629 client: Arc<Client>,
630 cx: &mut ModelContext<Self>,
631 ) -> Result<()> {
632 let remote_id = self.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
633 let replica_id = self.replica_id();
634 let worktree = envelope
635 .payload
636 .worktree
637 .ok_or_else(|| anyhow!("invalid worktree"))?;
638 let user_store = self.user_store.clone();
639 let languages = self.languages.clone();
640 cx.spawn(|this, mut cx| {
641 async move {
642 let worktree = Worktree::remote(
643 remote_id, replica_id, worktree, client, user_store, languages, &mut cx,
644 )
645 .await?;
646 this.update(&mut cx, |this, cx| this.add_worktree(worktree, cx));
647 Ok(())
648 }
649 .log_err()
650 })
651 .detach();
652 Ok(())
653 }
654
655 fn handle_unregister_worktree(
656 &mut self,
657 envelope: TypedEnvelope<proto::UnregisterWorktree>,
658 _: Arc<Client>,
659 cx: &mut ModelContext<Self>,
660 ) -> Result<()> {
661 self.worktrees.retain(|worktree| {
662 worktree.read(cx).as_remote().unwrap().remote_id() != envelope.payload.worktree_id
663 });
664 cx.notify();
665 Ok(())
666 }
667
668 fn handle_update_worktree(
669 &mut self,
670 envelope: TypedEnvelope<proto::UpdateWorktree>,
671 _: Arc<Client>,
672 cx: &mut ModelContext<Self>,
673 ) -> Result<()> {
674 if let Some(worktree) = self.worktree_for_id(envelope.payload.worktree_id as usize, cx) {
675 worktree.update(cx, |worktree, cx| {
676 let worktree = worktree.as_remote_mut().unwrap();
677 worktree.update_from_remote(envelope, cx)
678 })?;
679 }
680 Ok(())
681 }
682
683 pub fn handle_update_buffer(
684 &mut self,
685 envelope: TypedEnvelope<proto::UpdateBuffer>,
686 _: Arc<Client>,
687 cx: &mut ModelContext<Self>,
688 ) -> Result<()> {
689 if let Some(worktree) = self.worktree_for_id(envelope.payload.worktree_id as usize, cx) {
690 worktree.update(cx, |worktree, cx| {
691 worktree.handle_update_buffer(envelope, cx)
692 })?;
693 }
694 Ok(())
695 }
696
697 pub fn handle_save_buffer(
698 &mut self,
699 envelope: TypedEnvelope<proto::SaveBuffer>,
700 rpc: Arc<Client>,
701 cx: &mut ModelContext<Self>,
702 ) -> Result<()> {
703 if let Some(worktree) = self.worktree_for_id(envelope.payload.worktree_id as usize, cx) {
704 worktree.update(cx, |worktree, cx| {
705 worktree.handle_save_buffer(envelope, rpc, cx)
706 })?;
707 }
708 Ok(())
709 }
710
711 pub fn handle_open_buffer(
712 &mut self,
713 envelope: TypedEnvelope<proto::OpenBuffer>,
714 rpc: Arc<Client>,
715 cx: &mut ModelContext<Self>,
716 ) -> anyhow::Result<()> {
717 if let Some(worktree) = self.worktree_for_id(envelope.payload.worktree_id as usize, cx) {
718 return worktree.update(cx, |worktree, cx| {
719 worktree.handle_open_buffer(envelope, rpc, cx)
720 });
721 } else {
722 Err(anyhow!("no such worktree"))
723 }
724 }
725
726 pub fn handle_close_buffer(
727 &mut self,
728 envelope: TypedEnvelope<proto::CloseBuffer>,
729 rpc: Arc<Client>,
730 cx: &mut ModelContext<Self>,
731 ) -> anyhow::Result<()> {
732 if let Some(worktree) = self.worktree_for_id(envelope.payload.worktree_id as usize, cx) {
733 worktree.update(cx, |worktree, cx| {
734 worktree.handle_close_buffer(envelope, rpc, cx)
735 })?;
736 }
737 Ok(())
738 }
739
740 pub fn handle_buffer_saved(
741 &mut self,
742 envelope: TypedEnvelope<proto::BufferSaved>,
743 _: Arc<Client>,
744 cx: &mut ModelContext<Self>,
745 ) -> Result<()> {
746 if let Some(worktree) = self.worktree_for_id(envelope.payload.worktree_id as usize, cx) {
747 worktree.update(cx, |worktree, cx| {
748 worktree.handle_buffer_saved(envelope, cx)
749 })?;
750 }
751 Ok(())
752 }
753
754 pub fn match_paths<'a>(
755 &self,
756 query: &'a str,
757 include_ignored: bool,
758 smart_case: bool,
759 max_results: usize,
760 cancel_flag: &'a AtomicBool,
761 cx: &AppContext,
762 ) -> impl 'a + Future<Output = Vec<PathMatch>> {
763 let include_root_name = self.worktrees.len() > 1;
764 let candidate_sets = self
765 .worktrees
766 .iter()
767 .map(|worktree| CandidateSet {
768 snapshot: worktree.read(cx).snapshot(),
769 include_ignored,
770 include_root_name,
771 })
772 .collect::<Vec<_>>();
773
774 let background = cx.background().clone();
775 async move {
776 fuzzy::match_paths(
777 candidate_sets.as_slice(),
778 query,
779 smart_case,
780 max_results,
781 cancel_flag,
782 background,
783 )
784 .await
785 }
786 }
787}
788
789struct CandidateSet {
790 snapshot: Snapshot,
791 include_ignored: bool,
792 include_root_name: bool,
793}
794
795impl<'a> PathMatchCandidateSet<'a> for CandidateSet {
796 type Candidates = CandidateSetIter<'a>;
797
798 fn id(&self) -> usize {
799 self.snapshot.id()
800 }
801
802 fn len(&self) -> usize {
803 if self.include_ignored {
804 self.snapshot.file_count()
805 } else {
806 self.snapshot.visible_file_count()
807 }
808 }
809
810 fn prefix(&self) -> Arc<str> {
811 if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
812 self.snapshot.root_name().into()
813 } else if self.include_root_name {
814 format!("{}/", self.snapshot.root_name()).into()
815 } else {
816 "".into()
817 }
818 }
819
820 fn candidates(&'a self, start: usize) -> Self::Candidates {
821 CandidateSetIter {
822 traversal: self.snapshot.files(self.include_ignored, start),
823 }
824 }
825}
826
827struct CandidateSetIter<'a> {
828 traversal: Traversal<'a>,
829}
830
831impl<'a> Iterator for CandidateSetIter<'a> {
832 type Item = PathMatchCandidate<'a>;
833
834 fn next(&mut self) -> Option<Self::Item> {
835 self.traversal.next().map(|entry| {
836 if let EntryKind::File(char_bag) = entry.kind {
837 PathMatchCandidate {
838 path: &entry.path,
839 char_bag,
840 }
841 } else {
842 unreachable!()
843 }
844 })
845 }
846}
847
848impl Entity for Project {
849 type Event = Event;
850
851 fn release(&mut self, cx: &mut gpui::MutableAppContext) {
852 match &self.client_state {
853 ProjectClientState::Local { remote_id_rx, .. } => {
854 if let Some(project_id) = *remote_id_rx.borrow() {
855 let rpc = self.client.clone();
856 cx.spawn(|_| async move {
857 if let Err(err) = rpc.send(proto::UnregisterProject { project_id }).await {
858 log::error!("error unregistering project: {}", err);
859 }
860 })
861 .detach();
862 }
863 }
864 ProjectClientState::Remote { remote_id, .. } => {
865 let rpc = self.client.clone();
866 let project_id = *remote_id;
867 cx.spawn(|_| async move {
868 if let Err(err) = rpc.send(proto::LeaveProject { project_id }).await {
869 log::error!("error leaving project: {}", err);
870 }
871 })
872 .detach();
873 }
874 }
875 }
876}
877
878impl Collaborator {
879 fn from_proto(
880 message: proto::Collaborator,
881 user_store: &ModelHandle<UserStore>,
882 cx: &mut AsyncAppContext,
883 ) -> impl Future<Output = Result<Self>> {
884 let user = user_store.update(cx, |user_store, cx| {
885 user_store.fetch_user(message.user_id, cx)
886 });
887
888 async move {
889 Ok(Self {
890 peer_id: PeerId(message.peer_id),
891 user: user.await?,
892 replica_id: message.replica_id as ReplicaId,
893 })
894 }
895 }
896}
897
898#[cfg(test)]
899mod tests {
900 use super::*;
901 use client::{http::ServerResponse, test::FakeHttpClient};
902 use fs::RealFs;
903 use gpui::TestAppContext;
904 use language::LanguageRegistry;
905 use serde_json::json;
906 use std::{os::unix, path::PathBuf};
907 use util::test::temp_tree;
908
909 #[gpui::test]
910 async fn test_populate_and_search(mut cx: gpui::TestAppContext) {
911 let dir = temp_tree(json!({
912 "root": {
913 "apple": "",
914 "banana": {
915 "carrot": {
916 "date": "",
917 "endive": "",
918 }
919 },
920 "fennel": {
921 "grape": "",
922 }
923 }
924 }));
925
926 let root_link_path = dir.path().join("root_link");
927 unix::fs::symlink(&dir.path().join("root"), &root_link_path).unwrap();
928 unix::fs::symlink(
929 &dir.path().join("root/fennel"),
930 &dir.path().join("root/finnochio"),
931 )
932 .unwrap();
933
934 let project = build_project(&mut cx);
935
936 let tree = project
937 .update(&mut cx, |project, cx| {
938 project.add_local_worktree(&root_link_path, cx)
939 })
940 .await
941 .unwrap();
942
943 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
944 .await;
945 cx.read(|cx| {
946 let tree = tree.read(cx);
947 assert_eq!(tree.file_count(), 5);
948 assert_eq!(
949 tree.inode_for_path("fennel/grape"),
950 tree.inode_for_path("finnochio/grape")
951 );
952 });
953
954 let cancel_flag = Default::default();
955 let results = project
956 .read_with(&cx, |project, cx| {
957 project.match_paths("bna", false, false, 10, &cancel_flag, cx)
958 })
959 .await;
960 assert_eq!(
961 results
962 .into_iter()
963 .map(|result| result.path)
964 .collect::<Vec<Arc<Path>>>(),
965 vec![
966 PathBuf::from("banana/carrot/date").into(),
967 PathBuf::from("banana/carrot/endive").into(),
968 ]
969 );
970 }
971
972 #[gpui::test]
973 async fn test_search_worktree_without_files(mut cx: gpui::TestAppContext) {
974 let dir = temp_tree(json!({
975 "root": {
976 "dir1": {},
977 "dir2": {
978 "dir3": {}
979 }
980 }
981 }));
982
983 let project = build_project(&mut cx);
984 let tree = project
985 .update(&mut cx, |project, cx| {
986 project.add_local_worktree(&dir.path(), cx)
987 })
988 .await
989 .unwrap();
990
991 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
992 .await;
993
994 let cancel_flag = Default::default();
995 let results = project
996 .read_with(&cx, |project, cx| {
997 project.match_paths("dir", false, false, 10, &cancel_flag, cx)
998 })
999 .await;
1000
1001 assert!(results.is_empty());
1002 }
1003
1004 fn build_project(cx: &mut TestAppContext) -> ModelHandle<Project> {
1005 let languages = Arc::new(LanguageRegistry::new());
1006 let fs = Arc::new(RealFs);
1007 let client = client::Client::new();
1008 let http_client = FakeHttpClient::new(|_| async move { Ok(ServerResponse::new(404)) });
1009 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
1010 cx.update(|cx| Project::local(client, user_store, languages, fs, cx))
1011 }
1012}