1mod conflict_set;
2pub mod git_traversal;
3
4use crate::{
5 ProjectEnvironment, ProjectItem, ProjectPath,
6 buffer_store::{BufferStore, BufferStoreEvent},
7 worktree_store::{WorktreeStore, WorktreeStoreEvent},
8};
9use anyhow::{Context as _, Result, anyhow, bail};
10use askpass::AskPassDelegate;
11use buffer_diff::{BufferDiff, BufferDiffEvent};
12use client::ProjectId;
13use collections::HashMap;
14pub use conflict_set::{ConflictRegion, ConflictSet, ConflictSetSnapshot, ConflictSetUpdate};
15use fs::Fs;
16use futures::{
17 FutureExt, StreamExt,
18 channel::{mpsc, oneshot},
19 future::{self, Shared},
20 stream::FuturesOrdered,
21};
22use git::{
23 BuildPermalinkParams, GitHostingProviderRegistry, WORK_DIRECTORY_REPO_PATH,
24 blame::Blame,
25 parse_git_remote_url,
26 repository::{
27 Branch, CommitDetails, CommitDiff, CommitFile, CommitOptions, DiffType, FetchOptions,
28 GitRepository, GitRepositoryCheckpoint, PushOptions, Remote, RemoteCommandOutput, RepoPath,
29 ResetMode, UpstreamTrackingStatus,
30 },
31 status::{
32 FileStatus, GitSummary, StatusCode, TrackedStatus, UnmergedStatus, UnmergedStatusCode,
33 },
34};
35use gpui::{
36 App, AppContext, AsyncApp, Context, Entity, EventEmitter, SharedString, Subscription, Task,
37 WeakEntity,
38};
39use language::{
40 Buffer, BufferEvent, Language, LanguageRegistry,
41 proto::{deserialize_version, serialize_version},
42};
43use parking_lot::Mutex;
44use postage::stream::Stream as _;
45use rpc::{
46 AnyProtoClient, TypedEnvelope,
47 proto::{self, FromProto, SSH_PROJECT_ID, ToProto, git_reset, split_repository_update},
48};
49use serde::Deserialize;
50use std::{
51 cmp::Ordering,
52 collections::{BTreeSet, VecDeque},
53 future::Future,
54 mem,
55 ops::Range,
56 path::{Path, PathBuf},
57 sync::{
58 Arc,
59 atomic::{self, AtomicU64},
60 },
61 time::Instant,
62};
63use sum_tree::{Edit, SumTree, TreeSet};
64use text::{Bias, BufferId};
65use util::{ResultExt, debug_panic, post_inc};
66use worktree::{
67 File, PathChange, PathKey, PathProgress, PathSummary, PathTarget, ProjectEntryId,
68 UpdatedGitRepositoriesSet, UpdatedGitRepository, Worktree,
69};
70
71pub struct GitStore {
72 state: GitStoreState,
73 buffer_store: Entity<BufferStore>,
74 worktree_store: Entity<WorktreeStore>,
75 repositories: HashMap<RepositoryId, Entity<Repository>>,
76 active_repo_id: Option<RepositoryId>,
77 #[allow(clippy::type_complexity)]
78 loading_diffs:
79 HashMap<(BufferId, DiffKind), Shared<Task<Result<Entity<BufferDiff>, Arc<anyhow::Error>>>>>,
80 diffs: HashMap<BufferId, Entity<BufferGitState>>,
81 shared_diffs: HashMap<proto::PeerId, HashMap<BufferId, SharedDiffs>>,
82 _subscriptions: Vec<Subscription>,
83}
84
85#[derive(Default)]
86struct SharedDiffs {
87 unstaged: Option<Entity<BufferDiff>>,
88 uncommitted: Option<Entity<BufferDiff>>,
89}
90
91struct BufferGitState {
92 unstaged_diff: Option<WeakEntity<BufferDiff>>,
93 uncommitted_diff: Option<WeakEntity<BufferDiff>>,
94 conflict_set: Option<WeakEntity<ConflictSet>>,
95 recalculate_diff_task: Option<Task<Result<()>>>,
96 reparse_conflict_markers_task: Option<Task<Result<()>>>,
97 language: Option<Arc<Language>>,
98 language_registry: Option<Arc<LanguageRegistry>>,
99 conflict_updated_futures: Vec<oneshot::Sender<()>>,
100 recalculating_tx: postage::watch::Sender<bool>,
101
102 /// These operation counts are used to ensure that head and index text
103 /// values read from the git repository are up-to-date with any hunk staging
104 /// operations that have been performed on the BufferDiff.
105 ///
106 /// The operation count is incremented immediately when the user initiates a
107 /// hunk stage/unstage operation. Then, upon finishing writing the new index
108 /// text do disk, the `operation count as of write` is updated to reflect
109 /// the operation count that prompted the write.
110 hunk_staging_operation_count: usize,
111 hunk_staging_operation_count_as_of_write: usize,
112
113 head_text: Option<Arc<String>>,
114 index_text: Option<Arc<String>>,
115 head_changed: bool,
116 index_changed: bool,
117 language_changed: bool,
118}
119
120#[derive(Clone, Debug)]
121enum DiffBasesChange {
122 SetIndex(Option<String>),
123 SetHead(Option<String>),
124 SetEach {
125 index: Option<String>,
126 head: Option<String>,
127 },
128 SetBoth(Option<String>),
129}
130
131#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
132enum DiffKind {
133 Unstaged,
134 Uncommitted,
135}
136
137enum GitStoreState {
138 Local {
139 next_repository_id: Arc<AtomicU64>,
140 downstream: Option<LocalDownstreamState>,
141 project_environment: Entity<ProjectEnvironment>,
142 fs: Arc<dyn Fs>,
143 },
144 Ssh {
145 upstream_client: AnyProtoClient,
146 upstream_project_id: ProjectId,
147 downstream: Option<(AnyProtoClient, ProjectId)>,
148 },
149 Remote {
150 upstream_client: AnyProtoClient,
151 upstream_project_id: ProjectId,
152 },
153}
154
155enum DownstreamUpdate {
156 UpdateRepository(RepositorySnapshot),
157 RemoveRepository(RepositoryId),
158}
159
160struct LocalDownstreamState {
161 client: AnyProtoClient,
162 project_id: ProjectId,
163 updates_tx: mpsc::UnboundedSender<DownstreamUpdate>,
164 _task: Task<Result<()>>,
165}
166
167#[derive(Clone, Debug)]
168pub struct GitStoreCheckpoint {
169 checkpoints_by_work_dir_abs_path: HashMap<Arc<Path>, GitRepositoryCheckpoint>,
170}
171
172#[derive(Clone, Debug, PartialEq, Eq)]
173pub struct StatusEntry {
174 pub repo_path: RepoPath,
175 pub status: FileStatus,
176}
177
178impl StatusEntry {
179 fn to_proto(&self) -> proto::StatusEntry {
180 let simple_status = match self.status {
181 FileStatus::Ignored | FileStatus::Untracked => proto::GitStatus::Added as i32,
182 FileStatus::Unmerged { .. } => proto::GitStatus::Conflict as i32,
183 FileStatus::Tracked(TrackedStatus {
184 index_status,
185 worktree_status,
186 }) => tracked_status_to_proto(if worktree_status != StatusCode::Unmodified {
187 worktree_status
188 } else {
189 index_status
190 }),
191 };
192
193 proto::StatusEntry {
194 repo_path: self.repo_path.as_ref().to_proto(),
195 simple_status,
196 status: Some(status_to_proto(self.status)),
197 }
198 }
199}
200
201impl TryFrom<proto::StatusEntry> for StatusEntry {
202 type Error = anyhow::Error;
203
204 fn try_from(value: proto::StatusEntry) -> Result<Self, Self::Error> {
205 let repo_path = RepoPath(Arc::<Path>::from_proto(value.repo_path));
206 let status = status_from_proto(value.simple_status, value.status)?;
207 Ok(Self { repo_path, status })
208 }
209}
210
211impl sum_tree::Item for StatusEntry {
212 type Summary = PathSummary<GitSummary>;
213
214 fn summary(&self, _: &<Self::Summary as sum_tree::Summary>::Context) -> Self::Summary {
215 PathSummary {
216 max_path: self.repo_path.0.clone(),
217 item_summary: self.status.summary(),
218 }
219 }
220}
221
222impl sum_tree::KeyedItem for StatusEntry {
223 type Key = PathKey;
224
225 fn key(&self) -> Self::Key {
226 PathKey(self.repo_path.0.clone())
227 }
228}
229
230#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
231pub struct RepositoryId(pub u64);
232
233#[derive(Clone, Debug, Default, PartialEq, Eq)]
234pub struct MergeDetails {
235 pub conflicted_paths: TreeSet<RepoPath>,
236 pub message: Option<SharedString>,
237 pub heads: Vec<Option<SharedString>>,
238}
239
240#[derive(Clone, Debug, PartialEq, Eq)]
241pub struct RepositorySnapshot {
242 pub id: RepositoryId,
243 pub statuses_by_path: SumTree<StatusEntry>,
244 pub work_directory_abs_path: Arc<Path>,
245 pub branch: Option<Branch>,
246 pub head_commit: Option<CommitDetails>,
247 pub scan_id: u64,
248 pub merge: MergeDetails,
249 pub remote_origin_url: Option<String>,
250 pub remote_upstream_url: Option<String>,
251}
252
253type JobId = u64;
254
255#[derive(Clone, Debug, PartialEq, Eq)]
256pub struct JobInfo {
257 pub start: Instant,
258 pub message: SharedString,
259}
260
261pub struct Repository {
262 this: WeakEntity<Self>,
263 snapshot: RepositorySnapshot,
264 commit_message_buffer: Option<Entity<Buffer>>,
265 git_store: WeakEntity<GitStore>,
266 // For a local repository, holds paths that have had worktree events since the last status scan completed,
267 // and that should be examined during the next status scan.
268 paths_needing_status_update: BTreeSet<RepoPath>,
269 job_sender: mpsc::UnboundedSender<GitJob>,
270 active_jobs: HashMap<JobId, JobInfo>,
271 job_id: JobId,
272 askpass_delegates: Arc<Mutex<HashMap<u64, AskPassDelegate>>>,
273 latest_askpass_id: u64,
274}
275
276impl std::ops::Deref for Repository {
277 type Target = RepositorySnapshot;
278
279 fn deref(&self) -> &Self::Target {
280 &self.snapshot
281 }
282}
283
284#[derive(Clone)]
285pub enum RepositoryState {
286 Local {
287 backend: Arc<dyn GitRepository>,
288 environment: Arc<HashMap<String, String>>,
289 },
290 Remote {
291 project_id: ProjectId,
292 client: AnyProtoClient,
293 },
294}
295
296#[derive(Clone, Debug)]
297pub enum RepositoryEvent {
298 Updated { full_scan: bool, new_instance: bool },
299 MergeHeadsChanged,
300}
301
302#[derive(Clone, Debug)]
303pub struct JobsUpdated;
304
305#[derive(Debug)]
306pub enum GitStoreEvent {
307 ActiveRepositoryChanged(Option<RepositoryId>),
308 RepositoryUpdated(RepositoryId, RepositoryEvent, bool),
309 RepositoryAdded(RepositoryId),
310 RepositoryRemoved(RepositoryId),
311 IndexWriteError(anyhow::Error),
312 JobsUpdated,
313 ConflictsUpdated,
314}
315
316impl EventEmitter<RepositoryEvent> for Repository {}
317impl EventEmitter<JobsUpdated> for Repository {}
318impl EventEmitter<GitStoreEvent> for GitStore {}
319
320pub struct GitJob {
321 job: Box<dyn FnOnce(RepositoryState, &mut AsyncApp) -> Task<()>>,
322 key: Option<GitJobKey>,
323}
324
325#[derive(PartialEq, Eq)]
326enum GitJobKey {
327 WriteIndex(RepoPath),
328 ReloadBufferDiffBases,
329 RefreshStatuses,
330 ReloadGitState,
331}
332
333impl GitStore {
334 pub fn local(
335 worktree_store: &Entity<WorktreeStore>,
336 buffer_store: Entity<BufferStore>,
337 environment: Entity<ProjectEnvironment>,
338 fs: Arc<dyn Fs>,
339 cx: &mut Context<Self>,
340 ) -> Self {
341 Self::new(
342 worktree_store.clone(),
343 buffer_store,
344 GitStoreState::Local {
345 next_repository_id: Arc::new(AtomicU64::new(1)),
346 downstream: None,
347 project_environment: environment,
348 fs,
349 },
350 cx,
351 )
352 }
353
354 pub fn remote(
355 worktree_store: &Entity<WorktreeStore>,
356 buffer_store: Entity<BufferStore>,
357 upstream_client: AnyProtoClient,
358 project_id: ProjectId,
359 cx: &mut Context<Self>,
360 ) -> Self {
361 Self::new(
362 worktree_store.clone(),
363 buffer_store,
364 GitStoreState::Remote {
365 upstream_client,
366 upstream_project_id: project_id,
367 },
368 cx,
369 )
370 }
371
372 pub fn ssh(
373 worktree_store: &Entity<WorktreeStore>,
374 buffer_store: Entity<BufferStore>,
375 upstream_client: AnyProtoClient,
376 cx: &mut Context<Self>,
377 ) -> Self {
378 Self::new(
379 worktree_store.clone(),
380 buffer_store,
381 GitStoreState::Ssh {
382 upstream_client,
383 upstream_project_id: ProjectId(SSH_PROJECT_ID),
384 downstream: None,
385 },
386 cx,
387 )
388 }
389
390 fn new(
391 worktree_store: Entity<WorktreeStore>,
392 buffer_store: Entity<BufferStore>,
393 state: GitStoreState,
394 cx: &mut Context<Self>,
395 ) -> Self {
396 let _subscriptions = vec![
397 cx.subscribe(&worktree_store, Self::on_worktree_store_event),
398 cx.subscribe(&buffer_store, Self::on_buffer_store_event),
399 ];
400
401 GitStore {
402 state,
403 buffer_store,
404 worktree_store,
405 repositories: HashMap::default(),
406 active_repo_id: None,
407 _subscriptions,
408 loading_diffs: HashMap::default(),
409 shared_diffs: HashMap::default(),
410 diffs: HashMap::default(),
411 }
412 }
413
414 pub fn init(client: &AnyProtoClient) {
415 client.add_entity_request_handler(Self::handle_get_remotes);
416 client.add_entity_request_handler(Self::handle_get_branches);
417 client.add_entity_request_handler(Self::handle_get_default_branch);
418 client.add_entity_request_handler(Self::handle_change_branch);
419 client.add_entity_request_handler(Self::handle_create_branch);
420 client.add_entity_request_handler(Self::handle_git_init);
421 client.add_entity_request_handler(Self::handle_push);
422 client.add_entity_request_handler(Self::handle_pull);
423 client.add_entity_request_handler(Self::handle_fetch);
424 client.add_entity_request_handler(Self::handle_stage);
425 client.add_entity_request_handler(Self::handle_unstage);
426 client.add_entity_request_handler(Self::handle_stash);
427 client.add_entity_request_handler(Self::handle_stash_pop);
428 client.add_entity_request_handler(Self::handle_commit);
429 client.add_entity_request_handler(Self::handle_reset);
430 client.add_entity_request_handler(Self::handle_show);
431 client.add_entity_request_handler(Self::handle_load_commit_diff);
432 client.add_entity_request_handler(Self::handle_checkout_files);
433 client.add_entity_request_handler(Self::handle_open_commit_message_buffer);
434 client.add_entity_request_handler(Self::handle_set_index_text);
435 client.add_entity_request_handler(Self::handle_askpass);
436 client.add_entity_request_handler(Self::handle_check_for_pushed_commits);
437 client.add_entity_request_handler(Self::handle_git_diff);
438 client.add_entity_request_handler(Self::handle_open_unstaged_diff);
439 client.add_entity_request_handler(Self::handle_open_uncommitted_diff);
440 client.add_entity_message_handler(Self::handle_update_diff_bases);
441 client.add_entity_request_handler(Self::handle_get_permalink_to_line);
442 client.add_entity_request_handler(Self::handle_blame_buffer);
443 client.add_entity_message_handler(Self::handle_update_repository);
444 client.add_entity_message_handler(Self::handle_remove_repository);
445 client.add_entity_request_handler(Self::handle_git_clone);
446 }
447
448 pub fn is_local(&self) -> bool {
449 matches!(self.state, GitStoreState::Local { .. })
450 }
451
452 pub fn shared(&mut self, project_id: u64, client: AnyProtoClient, cx: &mut Context<Self>) {
453 match &mut self.state {
454 GitStoreState::Ssh {
455 downstream: downstream_client,
456 ..
457 } => {
458 for repo in self.repositories.values() {
459 let update = repo.read(cx).snapshot.initial_update(project_id);
460 for update in split_repository_update(update) {
461 client.send(update).log_err();
462 }
463 }
464 *downstream_client = Some((client, ProjectId(project_id)));
465 }
466 GitStoreState::Local {
467 downstream: downstream_client,
468 ..
469 } => {
470 let mut snapshots = HashMap::default();
471 let (updates_tx, mut updates_rx) = mpsc::unbounded();
472 for repo in self.repositories.values() {
473 updates_tx
474 .unbounded_send(DownstreamUpdate::UpdateRepository(
475 repo.read(cx).snapshot.clone(),
476 ))
477 .ok();
478 }
479 *downstream_client = Some(LocalDownstreamState {
480 client: client.clone(),
481 project_id: ProjectId(project_id),
482 updates_tx,
483 _task: cx.spawn(async move |this, cx| {
484 cx.background_spawn(async move {
485 while let Some(update) = updates_rx.next().await {
486 match update {
487 DownstreamUpdate::UpdateRepository(snapshot) => {
488 if let Some(old_snapshot) = snapshots.get_mut(&snapshot.id)
489 {
490 let update =
491 snapshot.build_update(old_snapshot, project_id);
492 *old_snapshot = snapshot;
493 for update in split_repository_update(update) {
494 client.send(update)?;
495 }
496 } else {
497 let update = snapshot.initial_update(project_id);
498 for update in split_repository_update(update) {
499 client.send(update)?;
500 }
501 snapshots.insert(snapshot.id, snapshot);
502 }
503 }
504 DownstreamUpdate::RemoveRepository(id) => {
505 client.send(proto::RemoveRepository {
506 project_id,
507 id: id.to_proto(),
508 })?;
509 }
510 }
511 }
512 anyhow::Ok(())
513 })
514 .await
515 .ok();
516 this.update(cx, |this, _| {
517 if let GitStoreState::Local {
518 downstream: downstream_client,
519 ..
520 } = &mut this.state
521 {
522 downstream_client.take();
523 } else {
524 unreachable!("unshared called on remote store");
525 }
526 })
527 }),
528 });
529 }
530 GitStoreState::Remote { .. } => {
531 debug_panic!("shared called on remote store");
532 }
533 }
534 }
535
536 pub fn unshared(&mut self, _cx: &mut Context<Self>) {
537 match &mut self.state {
538 GitStoreState::Local {
539 downstream: downstream_client,
540 ..
541 } => {
542 downstream_client.take();
543 }
544 GitStoreState::Ssh {
545 downstream: downstream_client,
546 ..
547 } => {
548 downstream_client.take();
549 }
550 GitStoreState::Remote { .. } => {
551 debug_panic!("unshared called on remote store");
552 }
553 }
554 self.shared_diffs.clear();
555 }
556
557 pub(crate) fn forget_shared_diffs_for(&mut self, peer_id: &proto::PeerId) {
558 self.shared_diffs.remove(peer_id);
559 }
560
561 pub fn active_repository(&self) -> Option<Entity<Repository>> {
562 self.active_repo_id
563 .as_ref()
564 .map(|id| self.repositories[&id].clone())
565 }
566
567 pub fn open_unstaged_diff(
568 &mut self,
569 buffer: Entity<Buffer>,
570 cx: &mut Context<Self>,
571 ) -> Task<Result<Entity<BufferDiff>>> {
572 let buffer_id = buffer.read(cx).remote_id();
573 if let Some(diff_state) = self.diffs.get(&buffer_id) {
574 if let Some(unstaged_diff) = diff_state
575 .read(cx)
576 .unstaged_diff
577 .as_ref()
578 .and_then(|weak| weak.upgrade())
579 {
580 if let Some(task) =
581 diff_state.update(cx, |diff_state, _| diff_state.wait_for_recalculation())
582 {
583 return cx.background_executor().spawn(async move {
584 task.await;
585 Ok(unstaged_diff)
586 });
587 }
588 return Task::ready(Ok(unstaged_diff));
589 }
590 }
591
592 let Some((repo, repo_path)) =
593 self.repository_and_path_for_buffer_id(buffer.read(cx).remote_id(), cx)
594 else {
595 return Task::ready(Err(anyhow!("failed to find git repository for buffer")));
596 };
597
598 let task = self
599 .loading_diffs
600 .entry((buffer_id, DiffKind::Unstaged))
601 .or_insert_with(|| {
602 let staged_text = repo.update(cx, |repo, cx| {
603 repo.load_staged_text(buffer_id, repo_path, cx)
604 });
605 cx.spawn(async move |this, cx| {
606 Self::open_diff_internal(
607 this,
608 DiffKind::Unstaged,
609 staged_text.await.map(DiffBasesChange::SetIndex),
610 buffer,
611 cx,
612 )
613 .await
614 .map_err(Arc::new)
615 })
616 .shared()
617 })
618 .clone();
619
620 cx.background_spawn(async move { task.await.map_err(|e| anyhow!("{e}")) })
621 }
622
623 pub fn open_uncommitted_diff(
624 &mut self,
625 buffer: Entity<Buffer>,
626 cx: &mut Context<Self>,
627 ) -> Task<Result<Entity<BufferDiff>>> {
628 let buffer_id = buffer.read(cx).remote_id();
629
630 if let Some(diff_state) = self.diffs.get(&buffer_id) {
631 if let Some(uncommitted_diff) = diff_state
632 .read(cx)
633 .uncommitted_diff
634 .as_ref()
635 .and_then(|weak| weak.upgrade())
636 {
637 if let Some(task) =
638 diff_state.update(cx, |diff_state, _| diff_state.wait_for_recalculation())
639 {
640 return cx.background_executor().spawn(async move {
641 task.await;
642 Ok(uncommitted_diff)
643 });
644 }
645 return Task::ready(Ok(uncommitted_diff));
646 }
647 }
648
649 let Some((repo, repo_path)) =
650 self.repository_and_path_for_buffer_id(buffer.read(cx).remote_id(), cx)
651 else {
652 return Task::ready(Err(anyhow!("failed to find git repository for buffer")));
653 };
654
655 let task = self
656 .loading_diffs
657 .entry((buffer_id, DiffKind::Uncommitted))
658 .or_insert_with(|| {
659 let changes = repo.update(cx, |repo, cx| {
660 repo.load_committed_text(buffer_id, repo_path, cx)
661 });
662
663 cx.spawn(async move |this, cx| {
664 Self::open_diff_internal(this, DiffKind::Uncommitted, changes.await, buffer, cx)
665 .await
666 .map_err(Arc::new)
667 })
668 .shared()
669 })
670 .clone();
671
672 cx.background_spawn(async move { task.await.map_err(|e| anyhow!("{e}")) })
673 }
674
675 async fn open_diff_internal(
676 this: WeakEntity<Self>,
677 kind: DiffKind,
678 texts: Result<DiffBasesChange>,
679 buffer_entity: Entity<Buffer>,
680 cx: &mut AsyncApp,
681 ) -> Result<Entity<BufferDiff>> {
682 let diff_bases_change = match texts {
683 Err(e) => {
684 this.update(cx, |this, cx| {
685 let buffer = buffer_entity.read(cx);
686 let buffer_id = buffer.remote_id();
687 this.loading_diffs.remove(&(buffer_id, kind));
688 })?;
689 return Err(e);
690 }
691 Ok(change) => change,
692 };
693
694 this.update(cx, |this, cx| {
695 let buffer = buffer_entity.read(cx);
696 let buffer_id = buffer.remote_id();
697 let language = buffer.language().cloned();
698 let language_registry = buffer.language_registry();
699 let text_snapshot = buffer.text_snapshot();
700 this.loading_diffs.remove(&(buffer_id, kind));
701
702 let git_store = cx.weak_entity();
703 let diff_state = this
704 .diffs
705 .entry(buffer_id)
706 .or_insert_with(|| cx.new(|_| BufferGitState::new(git_store)));
707
708 let diff = cx.new(|cx| BufferDiff::new(&text_snapshot, cx));
709
710 cx.subscribe(&diff, Self::on_buffer_diff_event).detach();
711 diff_state.update(cx, |diff_state, cx| {
712 diff_state.language = language;
713 diff_state.language_registry = language_registry;
714
715 match kind {
716 DiffKind::Unstaged => diff_state.unstaged_diff = Some(diff.downgrade()),
717 DiffKind::Uncommitted => {
718 let unstaged_diff = if let Some(diff) = diff_state.unstaged_diff() {
719 diff
720 } else {
721 let unstaged_diff = cx.new(|cx| BufferDiff::new(&text_snapshot, cx));
722 diff_state.unstaged_diff = Some(unstaged_diff.downgrade());
723 unstaged_diff
724 };
725
726 diff.update(cx, |diff, _| diff.set_secondary_diff(unstaged_diff));
727 diff_state.uncommitted_diff = Some(diff.downgrade())
728 }
729 }
730
731 diff_state.diff_bases_changed(text_snapshot, Some(diff_bases_change), cx);
732 let rx = diff_state.wait_for_recalculation();
733
734 anyhow::Ok(async move {
735 if let Some(rx) = rx {
736 rx.await;
737 }
738 Ok(diff)
739 })
740 })
741 })??
742 .await
743 }
744
745 pub fn get_unstaged_diff(&self, buffer_id: BufferId, cx: &App) -> Option<Entity<BufferDiff>> {
746 let diff_state = self.diffs.get(&buffer_id)?;
747 diff_state.read(cx).unstaged_diff.as_ref()?.upgrade()
748 }
749
750 pub fn get_uncommitted_diff(
751 &self,
752 buffer_id: BufferId,
753 cx: &App,
754 ) -> Option<Entity<BufferDiff>> {
755 let diff_state = self.diffs.get(&buffer_id)?;
756 diff_state.read(cx).uncommitted_diff.as_ref()?.upgrade()
757 }
758
759 pub fn open_conflict_set(
760 &mut self,
761 buffer: Entity<Buffer>,
762 cx: &mut Context<Self>,
763 ) -> Entity<ConflictSet> {
764 log::debug!("open conflict set");
765 let buffer_id = buffer.read(cx).remote_id();
766
767 if let Some(git_state) = self.diffs.get(&buffer_id) {
768 if let Some(conflict_set) = git_state
769 .read(cx)
770 .conflict_set
771 .as_ref()
772 .and_then(|weak| weak.upgrade())
773 {
774 let conflict_set = conflict_set.clone();
775 let buffer_snapshot = buffer.read(cx).text_snapshot();
776
777 git_state.update(cx, |state, cx| {
778 let _ = state.reparse_conflict_markers(buffer_snapshot, cx);
779 });
780
781 return conflict_set;
782 }
783 }
784
785 let is_unmerged = self
786 .repository_and_path_for_buffer_id(buffer_id, cx)
787 .map_or(false, |(repo, path)| {
788 repo.read(cx).snapshot.has_conflict(&path)
789 });
790 let git_store = cx.weak_entity();
791 let buffer_git_state = self
792 .diffs
793 .entry(buffer_id)
794 .or_insert_with(|| cx.new(|_| BufferGitState::new(git_store)));
795 let conflict_set = cx.new(|cx| ConflictSet::new(buffer_id, is_unmerged, cx));
796
797 self._subscriptions
798 .push(cx.subscribe(&conflict_set, |_, _, _, cx| {
799 cx.emit(GitStoreEvent::ConflictsUpdated);
800 }));
801
802 buffer_git_state.update(cx, |state, cx| {
803 state.conflict_set = Some(conflict_set.downgrade());
804 let buffer_snapshot = buffer.read(cx).text_snapshot();
805 let _ = state.reparse_conflict_markers(buffer_snapshot, cx);
806 });
807
808 conflict_set
809 }
810
811 pub fn project_path_git_status(
812 &self,
813 project_path: &ProjectPath,
814 cx: &App,
815 ) -> Option<FileStatus> {
816 let (repo, repo_path) = self.repository_and_path_for_project_path(project_path, cx)?;
817 Some(repo.read(cx).status_for_path(&repo_path)?.status)
818 }
819
820 pub fn checkpoint(&self, cx: &mut App) -> Task<Result<GitStoreCheckpoint>> {
821 let mut work_directory_abs_paths = Vec::new();
822 let mut checkpoints = Vec::new();
823 for repository in self.repositories.values() {
824 repository.update(cx, |repository, _| {
825 work_directory_abs_paths.push(repository.snapshot.work_directory_abs_path.clone());
826 checkpoints.push(repository.checkpoint().map(|checkpoint| checkpoint?));
827 });
828 }
829
830 cx.background_executor().spawn(async move {
831 let checkpoints = future::try_join_all(checkpoints).await?;
832 Ok(GitStoreCheckpoint {
833 checkpoints_by_work_dir_abs_path: work_directory_abs_paths
834 .into_iter()
835 .zip(checkpoints)
836 .collect(),
837 })
838 })
839 }
840
841 pub fn restore_checkpoint(
842 &self,
843 checkpoint: GitStoreCheckpoint,
844 cx: &mut App,
845 ) -> Task<Result<()>> {
846 let repositories_by_work_dir_abs_path = self
847 .repositories
848 .values()
849 .map(|repo| (repo.read(cx).snapshot.work_directory_abs_path.clone(), repo))
850 .collect::<HashMap<_, _>>();
851
852 let mut tasks = Vec::new();
853 for (work_dir_abs_path, checkpoint) in checkpoint.checkpoints_by_work_dir_abs_path {
854 if let Some(repository) = repositories_by_work_dir_abs_path.get(&work_dir_abs_path) {
855 let restore = repository.update(cx, |repository, _| {
856 repository.restore_checkpoint(checkpoint)
857 });
858 tasks.push(async move { restore.await? });
859 }
860 }
861 cx.background_spawn(async move {
862 future::try_join_all(tasks).await?;
863 Ok(())
864 })
865 }
866
867 /// Compares two checkpoints, returning true if they are equal.
868 pub fn compare_checkpoints(
869 &self,
870 left: GitStoreCheckpoint,
871 mut right: GitStoreCheckpoint,
872 cx: &mut App,
873 ) -> Task<Result<bool>> {
874 let repositories_by_work_dir_abs_path = self
875 .repositories
876 .values()
877 .map(|repo| (repo.read(cx).snapshot.work_directory_abs_path.clone(), repo))
878 .collect::<HashMap<_, _>>();
879
880 let mut tasks = Vec::new();
881 for (work_dir_abs_path, left_checkpoint) in left.checkpoints_by_work_dir_abs_path {
882 if let Some(right_checkpoint) = right
883 .checkpoints_by_work_dir_abs_path
884 .remove(&work_dir_abs_path)
885 {
886 if let Some(repository) = repositories_by_work_dir_abs_path.get(&work_dir_abs_path)
887 {
888 let compare = repository.update(cx, |repository, _| {
889 repository.compare_checkpoints(left_checkpoint, right_checkpoint)
890 });
891
892 tasks.push(async move { compare.await? });
893 }
894 } else {
895 return Task::ready(Ok(false));
896 }
897 }
898 cx.background_spawn(async move {
899 Ok(future::try_join_all(tasks)
900 .await?
901 .into_iter()
902 .all(|result| result))
903 })
904 }
905
906 /// Blames a buffer.
907 pub fn blame_buffer(
908 &self,
909 buffer: &Entity<Buffer>,
910 version: Option<clock::Global>,
911 cx: &mut App,
912 ) -> Task<Result<Option<Blame>>> {
913 let buffer = buffer.read(cx);
914 let Some((repo, repo_path)) =
915 self.repository_and_path_for_buffer_id(buffer.remote_id(), cx)
916 else {
917 return Task::ready(Err(anyhow!("failed to find a git repository for buffer")));
918 };
919 let content = match &version {
920 Some(version) => buffer.rope_for_version(version).clone(),
921 None => buffer.as_rope().clone(),
922 };
923 let version = version.unwrap_or(buffer.version());
924 let buffer_id = buffer.remote_id();
925
926 let rx = repo.update(cx, |repo, _| {
927 repo.send_job(None, move |state, _| async move {
928 match state {
929 RepositoryState::Local { backend, .. } => backend
930 .blame(repo_path.clone(), content)
931 .await
932 .with_context(|| format!("Failed to blame {:?}", repo_path.0))
933 .map(Some),
934 RepositoryState::Remote { project_id, client } => {
935 let response = client
936 .request(proto::BlameBuffer {
937 project_id: project_id.to_proto(),
938 buffer_id: buffer_id.into(),
939 version: serialize_version(&version),
940 })
941 .await?;
942 Ok(deserialize_blame_buffer_response(response))
943 }
944 }
945 })
946 });
947
948 cx.spawn(|_: &mut AsyncApp| async move { rx.await? })
949 }
950
951 pub fn get_permalink_to_line(
952 &self,
953 buffer: &Entity<Buffer>,
954 selection: Range<u32>,
955 cx: &mut App,
956 ) -> Task<Result<url::Url>> {
957 let Some(file) = File::from_dyn(buffer.read(cx).file()) else {
958 return Task::ready(Err(anyhow!("buffer has no file")));
959 };
960
961 let Some((repo, repo_path)) = self.repository_and_path_for_project_path(
962 &(file.worktree.read(cx).id(), file.path.clone()).into(),
963 cx,
964 ) else {
965 // If we're not in a Git repo, check whether this is a Rust source
966 // file in the Cargo registry (presumably opened with go-to-definition
967 // from a normal Rust file). If so, we can put together a permalink
968 // using crate metadata.
969 if buffer
970 .read(cx)
971 .language()
972 .is_none_or(|lang| lang.name() != "Rust".into())
973 {
974 return Task::ready(Err(anyhow!("no permalink available")));
975 }
976 let Some(file_path) = file.worktree.read(cx).absolutize(&file.path).ok() else {
977 return Task::ready(Err(anyhow!("no permalink available")));
978 };
979 return cx.spawn(async move |cx| {
980 let provider_registry = cx.update(GitHostingProviderRegistry::default_global)?;
981 get_permalink_in_rust_registry_src(provider_registry, file_path, selection)
982 .context("no permalink available")
983 });
984
985 // TODO remote case
986 };
987
988 let buffer_id = buffer.read(cx).remote_id();
989 let branch = repo.read(cx).branch.clone();
990 let remote = branch
991 .as_ref()
992 .and_then(|b| b.upstream.as_ref())
993 .and_then(|b| b.remote_name())
994 .unwrap_or("origin")
995 .to_string();
996
997 let rx = repo.update(cx, |repo, _| {
998 repo.send_job(None, move |state, cx| async move {
999 match state {
1000 RepositoryState::Local { backend, .. } => {
1001 let origin_url = backend
1002 .remote_url(&remote)
1003 .with_context(|| format!("remote \"{remote}\" not found"))?;
1004
1005 let sha = backend.head_sha().await.context("reading HEAD SHA")?;
1006
1007 let provider_registry =
1008 cx.update(GitHostingProviderRegistry::default_global)?;
1009
1010 let (provider, remote) =
1011 parse_git_remote_url(provider_registry, &origin_url)
1012 .context("parsing Git remote URL")?;
1013
1014 let path = repo_path.to_str().with_context(|| {
1015 format!("converting repo path {repo_path:?} to string")
1016 })?;
1017
1018 Ok(provider.build_permalink(
1019 remote,
1020 BuildPermalinkParams {
1021 sha: &sha,
1022 path,
1023 selection: Some(selection),
1024 },
1025 ))
1026 }
1027 RepositoryState::Remote { project_id, client } => {
1028 let response = client
1029 .request(proto::GetPermalinkToLine {
1030 project_id: project_id.to_proto(),
1031 buffer_id: buffer_id.into(),
1032 selection: Some(proto::Range {
1033 start: selection.start as u64,
1034 end: selection.end as u64,
1035 }),
1036 })
1037 .await?;
1038
1039 url::Url::parse(&response.permalink).context("failed to parse permalink")
1040 }
1041 }
1042 })
1043 });
1044 cx.spawn(|_: &mut AsyncApp| async move { rx.await? })
1045 }
1046
1047 fn downstream_client(&self) -> Option<(AnyProtoClient, ProjectId)> {
1048 match &self.state {
1049 GitStoreState::Local {
1050 downstream: downstream_client,
1051 ..
1052 } => downstream_client
1053 .as_ref()
1054 .map(|state| (state.client.clone(), state.project_id)),
1055 GitStoreState::Ssh {
1056 downstream: downstream_client,
1057 ..
1058 } => downstream_client.clone(),
1059 GitStoreState::Remote { .. } => None,
1060 }
1061 }
1062
1063 fn upstream_client(&self) -> Option<AnyProtoClient> {
1064 match &self.state {
1065 GitStoreState::Local { .. } => None,
1066 GitStoreState::Ssh {
1067 upstream_client, ..
1068 }
1069 | GitStoreState::Remote {
1070 upstream_client, ..
1071 } => Some(upstream_client.clone()),
1072 }
1073 }
1074
1075 fn on_worktree_store_event(
1076 &mut self,
1077 worktree_store: Entity<WorktreeStore>,
1078 event: &WorktreeStoreEvent,
1079 cx: &mut Context<Self>,
1080 ) {
1081 let GitStoreState::Local {
1082 project_environment,
1083 downstream,
1084 next_repository_id,
1085 fs,
1086 } = &self.state
1087 else {
1088 return;
1089 };
1090
1091 match event {
1092 WorktreeStoreEvent::WorktreeUpdatedEntries(worktree_id, updated_entries) => {
1093 if let Some(worktree) = self
1094 .worktree_store
1095 .read(cx)
1096 .worktree_for_id(*worktree_id, cx)
1097 {
1098 let paths_by_git_repo =
1099 self.process_updated_entries(&worktree, updated_entries, cx);
1100 let downstream = downstream
1101 .as_ref()
1102 .map(|downstream| downstream.updates_tx.clone());
1103 cx.spawn(async move |_, cx| {
1104 let paths_by_git_repo = paths_by_git_repo.await;
1105 for (repo, paths) in paths_by_git_repo {
1106 repo.update(cx, |repo, cx| {
1107 repo.paths_changed(paths, downstream.clone(), cx);
1108 })
1109 .ok();
1110 }
1111 })
1112 .detach();
1113 }
1114 }
1115 WorktreeStoreEvent::WorktreeUpdatedGitRepositories(worktree_id, changed_repos) => {
1116 let Some(worktree) = worktree_store.read(cx).worktree_for_id(*worktree_id, cx)
1117 else {
1118 return;
1119 };
1120 if !worktree.read(cx).is_visible() {
1121 log::debug!(
1122 "not adding repositories for local worktree {:?} because it's not visible",
1123 worktree.read(cx).abs_path()
1124 );
1125 return;
1126 }
1127 self.update_repositories_from_worktree(
1128 project_environment.clone(),
1129 next_repository_id.clone(),
1130 downstream
1131 .as_ref()
1132 .map(|downstream| downstream.updates_tx.clone()),
1133 changed_repos.clone(),
1134 fs.clone(),
1135 cx,
1136 );
1137 self.local_worktree_git_repos_changed(worktree, changed_repos, cx);
1138 }
1139 _ => {}
1140 }
1141 }
1142
1143 fn on_repository_event(
1144 &mut self,
1145 repo: Entity<Repository>,
1146 event: &RepositoryEvent,
1147 cx: &mut Context<Self>,
1148 ) {
1149 let id = repo.read(cx).id;
1150 let repo_snapshot = repo.read(cx).snapshot.clone();
1151 for (buffer_id, diff) in self.diffs.iter() {
1152 if let Some((buffer_repo, repo_path)) =
1153 self.repository_and_path_for_buffer_id(*buffer_id, cx)
1154 {
1155 if buffer_repo == repo {
1156 diff.update(cx, |diff, cx| {
1157 if let Some(conflict_set) = &diff.conflict_set {
1158 let conflict_status_changed =
1159 conflict_set.update(cx, |conflict_set, cx| {
1160 let has_conflict = repo_snapshot.has_conflict(&repo_path);
1161 conflict_set.set_has_conflict(has_conflict, cx)
1162 })?;
1163 if conflict_status_changed {
1164 let buffer_store = self.buffer_store.read(cx);
1165 if let Some(buffer) = buffer_store.get(*buffer_id) {
1166 let _ = diff.reparse_conflict_markers(
1167 buffer.read(cx).text_snapshot(),
1168 cx,
1169 );
1170 }
1171 }
1172 }
1173 anyhow::Ok(())
1174 })
1175 .ok();
1176 }
1177 }
1178 }
1179 cx.emit(GitStoreEvent::RepositoryUpdated(
1180 id,
1181 event.clone(),
1182 self.active_repo_id == Some(id),
1183 ))
1184 }
1185
1186 fn on_jobs_updated(&mut self, _: Entity<Repository>, _: &JobsUpdated, cx: &mut Context<Self>) {
1187 cx.emit(GitStoreEvent::JobsUpdated)
1188 }
1189
1190 /// Update our list of repositories and schedule git scans in response to a notification from a worktree,
1191 fn update_repositories_from_worktree(
1192 &mut self,
1193 project_environment: Entity<ProjectEnvironment>,
1194 next_repository_id: Arc<AtomicU64>,
1195 updates_tx: Option<mpsc::UnboundedSender<DownstreamUpdate>>,
1196 updated_git_repositories: UpdatedGitRepositoriesSet,
1197 fs: Arc<dyn Fs>,
1198 cx: &mut Context<Self>,
1199 ) {
1200 let mut removed_ids = Vec::new();
1201 for update in updated_git_repositories.iter() {
1202 if let Some((id, existing)) = self.repositories.iter().find(|(_, repo)| {
1203 let existing_work_directory_abs_path =
1204 repo.read(cx).work_directory_abs_path.clone();
1205 Some(&existing_work_directory_abs_path)
1206 == update.old_work_directory_abs_path.as_ref()
1207 || Some(&existing_work_directory_abs_path)
1208 == update.new_work_directory_abs_path.as_ref()
1209 }) {
1210 if let Some(new_work_directory_abs_path) =
1211 update.new_work_directory_abs_path.clone()
1212 {
1213 existing.update(cx, |existing, cx| {
1214 existing.snapshot.work_directory_abs_path = new_work_directory_abs_path;
1215 existing.schedule_scan(updates_tx.clone(), cx);
1216 });
1217 } else {
1218 removed_ids.push(*id);
1219 }
1220 } else if let UpdatedGitRepository {
1221 new_work_directory_abs_path: Some(work_directory_abs_path),
1222 dot_git_abs_path: Some(dot_git_abs_path),
1223 repository_dir_abs_path: Some(repository_dir_abs_path),
1224 common_dir_abs_path: Some(common_dir_abs_path),
1225 ..
1226 } = update
1227 {
1228 let id = RepositoryId(next_repository_id.fetch_add(1, atomic::Ordering::Release));
1229 let git_store = cx.weak_entity();
1230 let repo = cx.new(|cx| {
1231 let mut repo = Repository::local(
1232 id,
1233 work_directory_abs_path.clone(),
1234 dot_git_abs_path.clone(),
1235 repository_dir_abs_path.clone(),
1236 common_dir_abs_path.clone(),
1237 project_environment.downgrade(),
1238 fs.clone(),
1239 git_store,
1240 cx,
1241 );
1242 repo.schedule_scan(updates_tx.clone(), cx);
1243 repo
1244 });
1245 self._subscriptions
1246 .push(cx.subscribe(&repo, Self::on_repository_event));
1247 self._subscriptions
1248 .push(cx.subscribe(&repo, Self::on_jobs_updated));
1249 self.repositories.insert(id, repo);
1250 cx.emit(GitStoreEvent::RepositoryAdded(id));
1251 self.active_repo_id.get_or_insert_with(|| {
1252 cx.emit(GitStoreEvent::ActiveRepositoryChanged(Some(id)));
1253 id
1254 });
1255 }
1256 }
1257
1258 for id in removed_ids {
1259 if self.active_repo_id == Some(id) {
1260 self.active_repo_id = None;
1261 cx.emit(GitStoreEvent::ActiveRepositoryChanged(None));
1262 }
1263 self.repositories.remove(&id);
1264 if let Some(updates_tx) = updates_tx.as_ref() {
1265 updates_tx
1266 .unbounded_send(DownstreamUpdate::RemoveRepository(id))
1267 .ok();
1268 }
1269 }
1270 }
1271
1272 fn on_buffer_store_event(
1273 &mut self,
1274 _: Entity<BufferStore>,
1275 event: &BufferStoreEvent,
1276 cx: &mut Context<Self>,
1277 ) {
1278 match event {
1279 BufferStoreEvent::BufferAdded(buffer) => {
1280 cx.subscribe(&buffer, |this, buffer, event, cx| {
1281 if let BufferEvent::LanguageChanged = event {
1282 let buffer_id = buffer.read(cx).remote_id();
1283 if let Some(diff_state) = this.diffs.get(&buffer_id) {
1284 diff_state.update(cx, |diff_state, cx| {
1285 diff_state.buffer_language_changed(buffer, cx);
1286 });
1287 }
1288 }
1289 })
1290 .detach();
1291 }
1292 BufferStoreEvent::SharedBufferClosed(peer_id, buffer_id) => {
1293 if let Some(diffs) = self.shared_diffs.get_mut(peer_id) {
1294 diffs.remove(buffer_id);
1295 }
1296 }
1297 BufferStoreEvent::BufferDropped(buffer_id) => {
1298 self.diffs.remove(&buffer_id);
1299 for diffs in self.shared_diffs.values_mut() {
1300 diffs.remove(buffer_id);
1301 }
1302 }
1303
1304 _ => {}
1305 }
1306 }
1307
1308 pub fn recalculate_buffer_diffs(
1309 &mut self,
1310 buffers: Vec<Entity<Buffer>>,
1311 cx: &mut Context<Self>,
1312 ) -> impl Future<Output = ()> + use<> {
1313 let mut futures = Vec::new();
1314 for buffer in buffers {
1315 if let Some(diff_state) = self.diffs.get_mut(&buffer.read(cx).remote_id()) {
1316 let buffer = buffer.read(cx).text_snapshot();
1317 diff_state.update(cx, |diff_state, cx| {
1318 diff_state.recalculate_diffs(buffer.clone(), cx);
1319 futures.extend(diff_state.wait_for_recalculation().map(FutureExt::boxed));
1320 });
1321 futures.push(diff_state.update(cx, |diff_state, cx| {
1322 diff_state
1323 .reparse_conflict_markers(buffer, cx)
1324 .map(|_| {})
1325 .boxed()
1326 }));
1327 }
1328 }
1329 async move {
1330 futures::future::join_all(futures).await;
1331 }
1332 }
1333
1334 fn on_buffer_diff_event(
1335 &mut self,
1336 diff: Entity<buffer_diff::BufferDiff>,
1337 event: &BufferDiffEvent,
1338 cx: &mut Context<Self>,
1339 ) {
1340 if let BufferDiffEvent::HunksStagedOrUnstaged(new_index_text) = event {
1341 let buffer_id = diff.read(cx).buffer_id;
1342 if let Some(diff_state) = self.diffs.get(&buffer_id) {
1343 let hunk_staging_operation_count = diff_state.update(cx, |diff_state, _| {
1344 diff_state.hunk_staging_operation_count += 1;
1345 diff_state.hunk_staging_operation_count
1346 });
1347 if let Some((repo, path)) = self.repository_and_path_for_buffer_id(buffer_id, cx) {
1348 let recv = repo.update(cx, |repo, cx| {
1349 log::debug!("hunks changed for {}", path.display());
1350 repo.spawn_set_index_text_job(
1351 path,
1352 new_index_text.as_ref().map(|rope| rope.to_string()),
1353 Some(hunk_staging_operation_count),
1354 cx,
1355 )
1356 });
1357 let diff = diff.downgrade();
1358 cx.spawn(async move |this, cx| {
1359 if let Ok(Err(error)) = cx.background_spawn(recv).await {
1360 diff.update(cx, |diff, cx| {
1361 diff.clear_pending_hunks(cx);
1362 })
1363 .ok();
1364 this.update(cx, |_, cx| cx.emit(GitStoreEvent::IndexWriteError(error)))
1365 .ok();
1366 }
1367 })
1368 .detach();
1369 }
1370 }
1371 }
1372 }
1373
1374 fn local_worktree_git_repos_changed(
1375 &mut self,
1376 worktree: Entity<Worktree>,
1377 changed_repos: &UpdatedGitRepositoriesSet,
1378 cx: &mut Context<Self>,
1379 ) {
1380 log::debug!("local worktree repos changed");
1381 debug_assert!(worktree.read(cx).is_local());
1382
1383 for repository in self.repositories.values() {
1384 repository.update(cx, |repository, cx| {
1385 let repo_abs_path = &repository.work_directory_abs_path;
1386 if changed_repos.iter().any(|update| {
1387 update.old_work_directory_abs_path.as_ref() == Some(&repo_abs_path)
1388 || update.new_work_directory_abs_path.as_ref() == Some(&repo_abs_path)
1389 }) {
1390 repository.reload_buffer_diff_bases(cx);
1391 }
1392 });
1393 }
1394 }
1395
1396 pub fn repositories(&self) -> &HashMap<RepositoryId, Entity<Repository>> {
1397 &self.repositories
1398 }
1399
1400 pub fn status_for_buffer_id(&self, buffer_id: BufferId, cx: &App) -> Option<FileStatus> {
1401 let (repo, path) = self.repository_and_path_for_buffer_id(buffer_id, cx)?;
1402 let status = repo.read(cx).snapshot.status_for_path(&path)?;
1403 Some(status.status)
1404 }
1405
1406 pub fn repository_and_path_for_buffer_id(
1407 &self,
1408 buffer_id: BufferId,
1409 cx: &App,
1410 ) -> Option<(Entity<Repository>, RepoPath)> {
1411 let buffer = self.buffer_store.read(cx).get(buffer_id)?;
1412 let project_path = buffer.read(cx).project_path(cx)?;
1413 self.repository_and_path_for_project_path(&project_path, cx)
1414 }
1415
1416 pub fn repository_and_path_for_project_path(
1417 &self,
1418 path: &ProjectPath,
1419 cx: &App,
1420 ) -> Option<(Entity<Repository>, RepoPath)> {
1421 let abs_path = self.worktree_store.read(cx).absolutize(path, cx)?;
1422 self.repositories
1423 .values()
1424 .filter_map(|repo| {
1425 let repo_path = repo.read(cx).abs_path_to_repo_path(&abs_path)?;
1426 Some((repo.clone(), repo_path))
1427 })
1428 .max_by_key(|(repo, _)| repo.read(cx).work_directory_abs_path.clone())
1429 }
1430
1431 pub fn git_init(
1432 &self,
1433 path: Arc<Path>,
1434 fallback_branch_name: String,
1435 cx: &App,
1436 ) -> Task<Result<()>> {
1437 match &self.state {
1438 GitStoreState::Local { fs, .. } => {
1439 let fs = fs.clone();
1440 cx.background_executor()
1441 .spawn(async move { fs.git_init(&path, fallback_branch_name) })
1442 }
1443 GitStoreState::Ssh {
1444 upstream_client,
1445 upstream_project_id: project_id,
1446 ..
1447 }
1448 | GitStoreState::Remote {
1449 upstream_client,
1450 upstream_project_id: project_id,
1451 ..
1452 } => {
1453 let client = upstream_client.clone();
1454 let project_id = *project_id;
1455 cx.background_executor().spawn(async move {
1456 client
1457 .request(proto::GitInit {
1458 project_id: project_id.0,
1459 abs_path: path.to_string_lossy().to_string(),
1460 fallback_branch_name,
1461 })
1462 .await?;
1463 Ok(())
1464 })
1465 }
1466 }
1467 }
1468
1469 pub fn git_clone(
1470 &self,
1471 repo: String,
1472 path: impl Into<Arc<std::path::Path>>,
1473 cx: &App,
1474 ) -> Task<Result<()>> {
1475 let path = path.into();
1476 match &self.state {
1477 GitStoreState::Local { fs, .. } => {
1478 let fs = fs.clone();
1479 cx.background_executor()
1480 .spawn(async move { fs.git_clone(&repo, &path).await })
1481 }
1482 GitStoreState::Ssh {
1483 upstream_client,
1484 upstream_project_id,
1485 ..
1486 } => {
1487 let request = upstream_client.request(proto::GitClone {
1488 project_id: upstream_project_id.0,
1489 abs_path: path.to_string_lossy().to_string(),
1490 remote_repo: repo,
1491 });
1492
1493 cx.background_spawn(async move {
1494 let result = request.await?;
1495
1496 match result.success {
1497 true => Ok(()),
1498 false => Err(anyhow!("Git Clone failed")),
1499 }
1500 })
1501 }
1502 GitStoreState::Remote { .. } => {
1503 Task::ready(Err(anyhow!("Git Clone isn't supported for remote users")))
1504 }
1505 }
1506 }
1507
1508 async fn handle_update_repository(
1509 this: Entity<Self>,
1510 envelope: TypedEnvelope<proto::UpdateRepository>,
1511 mut cx: AsyncApp,
1512 ) -> Result<()> {
1513 this.update(&mut cx, |this, cx| {
1514 let mut update = envelope.payload;
1515
1516 let id = RepositoryId::from_proto(update.id);
1517 let client = this
1518 .upstream_client()
1519 .context("no upstream client")?
1520 .clone();
1521
1522 let mut is_new = false;
1523 let repo = this.repositories.entry(id).or_insert_with(|| {
1524 is_new = true;
1525 let git_store = cx.weak_entity();
1526 cx.new(|cx| {
1527 Repository::remote(
1528 id,
1529 Path::new(&update.abs_path).into(),
1530 ProjectId(update.project_id),
1531 client,
1532 git_store,
1533 cx,
1534 )
1535 })
1536 });
1537 if is_new {
1538 this._subscriptions
1539 .push(cx.subscribe(&repo, Self::on_repository_event))
1540 }
1541
1542 repo.update(cx, {
1543 let update = update.clone();
1544 |repo, cx| repo.apply_remote_update(update, is_new, cx)
1545 })?;
1546
1547 this.active_repo_id.get_or_insert_with(|| {
1548 cx.emit(GitStoreEvent::ActiveRepositoryChanged(Some(id)));
1549 id
1550 });
1551
1552 if let Some((client, project_id)) = this.downstream_client() {
1553 update.project_id = project_id.to_proto();
1554 client.send(update).log_err();
1555 }
1556 Ok(())
1557 })?
1558 }
1559
1560 async fn handle_remove_repository(
1561 this: Entity<Self>,
1562 envelope: TypedEnvelope<proto::RemoveRepository>,
1563 mut cx: AsyncApp,
1564 ) -> Result<()> {
1565 this.update(&mut cx, |this, cx| {
1566 let mut update = envelope.payload;
1567 let id = RepositoryId::from_proto(update.id);
1568 this.repositories.remove(&id);
1569 if let Some((client, project_id)) = this.downstream_client() {
1570 update.project_id = project_id.to_proto();
1571 client.send(update).log_err();
1572 }
1573 if this.active_repo_id == Some(id) {
1574 this.active_repo_id = None;
1575 cx.emit(GitStoreEvent::ActiveRepositoryChanged(None));
1576 }
1577 cx.emit(GitStoreEvent::RepositoryRemoved(id));
1578 })
1579 }
1580
1581 async fn handle_git_init(
1582 this: Entity<Self>,
1583 envelope: TypedEnvelope<proto::GitInit>,
1584 cx: AsyncApp,
1585 ) -> Result<proto::Ack> {
1586 let path: Arc<Path> = PathBuf::from(envelope.payload.abs_path).into();
1587 let name = envelope.payload.fallback_branch_name;
1588 cx.update(|cx| this.read(cx).git_init(path, name, cx))?
1589 .await?;
1590
1591 Ok(proto::Ack {})
1592 }
1593
1594 async fn handle_git_clone(
1595 this: Entity<Self>,
1596 envelope: TypedEnvelope<proto::GitClone>,
1597 cx: AsyncApp,
1598 ) -> Result<proto::GitCloneResponse> {
1599 let path: Arc<Path> = PathBuf::from(envelope.payload.abs_path).into();
1600 let repo_name = envelope.payload.remote_repo;
1601 let result = cx
1602 .update(|cx| this.read(cx).git_clone(repo_name, path, cx))?
1603 .await;
1604
1605 Ok(proto::GitCloneResponse {
1606 success: result.is_ok(),
1607 })
1608 }
1609
1610 async fn handle_fetch(
1611 this: Entity<Self>,
1612 envelope: TypedEnvelope<proto::Fetch>,
1613 mut cx: AsyncApp,
1614 ) -> Result<proto::RemoteMessageResponse> {
1615 let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
1616 let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;
1617 let fetch_options = FetchOptions::from_proto(envelope.payload.remote);
1618 let askpass_id = envelope.payload.askpass_id;
1619
1620 let askpass = make_remote_delegate(
1621 this,
1622 envelope.payload.project_id,
1623 repository_id,
1624 askpass_id,
1625 &mut cx,
1626 );
1627
1628 let remote_output = repository_handle
1629 .update(&mut cx, |repository_handle, cx| {
1630 repository_handle.fetch(fetch_options, askpass, cx)
1631 })?
1632 .await??;
1633
1634 Ok(proto::RemoteMessageResponse {
1635 stdout: remote_output.stdout,
1636 stderr: remote_output.stderr,
1637 })
1638 }
1639
1640 async fn handle_push(
1641 this: Entity<Self>,
1642 envelope: TypedEnvelope<proto::Push>,
1643 mut cx: AsyncApp,
1644 ) -> Result<proto::RemoteMessageResponse> {
1645 let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
1646 let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;
1647
1648 let askpass_id = envelope.payload.askpass_id;
1649 let askpass = make_remote_delegate(
1650 this,
1651 envelope.payload.project_id,
1652 repository_id,
1653 askpass_id,
1654 &mut cx,
1655 );
1656
1657 let options = envelope
1658 .payload
1659 .options
1660 .as_ref()
1661 .map(|_| match envelope.payload.options() {
1662 proto::push::PushOptions::SetUpstream => git::repository::PushOptions::SetUpstream,
1663 proto::push::PushOptions::Force => git::repository::PushOptions::Force,
1664 });
1665
1666 let branch_name = envelope.payload.branch_name.into();
1667 let remote_name = envelope.payload.remote_name.into();
1668
1669 let remote_output = repository_handle
1670 .update(&mut cx, |repository_handle, cx| {
1671 repository_handle.push(branch_name, remote_name, options, askpass, cx)
1672 })?
1673 .await??;
1674 Ok(proto::RemoteMessageResponse {
1675 stdout: remote_output.stdout,
1676 stderr: remote_output.stderr,
1677 })
1678 }
1679
1680 async fn handle_pull(
1681 this: Entity<Self>,
1682 envelope: TypedEnvelope<proto::Pull>,
1683 mut cx: AsyncApp,
1684 ) -> Result<proto::RemoteMessageResponse> {
1685 let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
1686 let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;
1687 let askpass_id = envelope.payload.askpass_id;
1688 let askpass = make_remote_delegate(
1689 this,
1690 envelope.payload.project_id,
1691 repository_id,
1692 askpass_id,
1693 &mut cx,
1694 );
1695
1696 let branch_name = envelope.payload.branch_name.into();
1697 let remote_name = envelope.payload.remote_name.into();
1698
1699 let remote_message = repository_handle
1700 .update(&mut cx, |repository_handle, cx| {
1701 repository_handle.pull(branch_name, remote_name, askpass, cx)
1702 })?
1703 .await??;
1704
1705 Ok(proto::RemoteMessageResponse {
1706 stdout: remote_message.stdout,
1707 stderr: remote_message.stderr,
1708 })
1709 }
1710
1711 async fn handle_stage(
1712 this: Entity<Self>,
1713 envelope: TypedEnvelope<proto::Stage>,
1714 mut cx: AsyncApp,
1715 ) -> Result<proto::Ack> {
1716 let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
1717 let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;
1718
1719 let entries = envelope
1720 .payload
1721 .paths
1722 .into_iter()
1723 .map(PathBuf::from)
1724 .map(RepoPath::new)
1725 .collect();
1726
1727 repository_handle
1728 .update(&mut cx, |repository_handle, cx| {
1729 repository_handle.stage_entries(entries, cx)
1730 })?
1731 .await?;
1732 Ok(proto::Ack {})
1733 }
1734
1735 async fn handle_unstage(
1736 this: Entity<Self>,
1737 envelope: TypedEnvelope<proto::Unstage>,
1738 mut cx: AsyncApp,
1739 ) -> Result<proto::Ack> {
1740 let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
1741 let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;
1742
1743 let entries = envelope
1744 .payload
1745 .paths
1746 .into_iter()
1747 .map(PathBuf::from)
1748 .map(RepoPath::new)
1749 .collect();
1750
1751 repository_handle
1752 .update(&mut cx, |repository_handle, cx| {
1753 repository_handle.unstage_entries(entries, cx)
1754 })?
1755 .await?;
1756
1757 Ok(proto::Ack {})
1758 }
1759
1760 async fn handle_stash(
1761 this: Entity<Self>,
1762 envelope: TypedEnvelope<proto::Stash>,
1763 mut cx: AsyncApp,
1764 ) -> Result<proto::Ack> {
1765 let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
1766 let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;
1767
1768 let entries = envelope
1769 .payload
1770 .paths
1771 .into_iter()
1772 .map(PathBuf::from)
1773 .map(RepoPath::new)
1774 .collect();
1775
1776 repository_handle
1777 .update(&mut cx, |repository_handle, cx| {
1778 repository_handle.stash_entries(entries, cx)
1779 })?
1780 .await?;
1781
1782 Ok(proto::Ack {})
1783 }
1784
1785 async fn handle_stash_pop(
1786 this: Entity<Self>,
1787 envelope: TypedEnvelope<proto::StashPop>,
1788 mut cx: AsyncApp,
1789 ) -> Result<proto::Ack> {
1790 let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
1791 let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;
1792
1793 repository_handle
1794 .update(&mut cx, |repository_handle, cx| {
1795 repository_handle.stash_pop(cx)
1796 })?
1797 .await?;
1798
1799 Ok(proto::Ack {})
1800 }
1801
1802 async fn handle_set_index_text(
1803 this: Entity<Self>,
1804 envelope: TypedEnvelope<proto::SetIndexText>,
1805 mut cx: AsyncApp,
1806 ) -> Result<proto::Ack> {
1807 let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
1808 let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;
1809 let repo_path = RepoPath::from_str(&envelope.payload.path);
1810
1811 repository_handle
1812 .update(&mut cx, |repository_handle, cx| {
1813 repository_handle.spawn_set_index_text_job(
1814 repo_path,
1815 envelope.payload.text,
1816 None,
1817 cx,
1818 )
1819 })?
1820 .await??;
1821 Ok(proto::Ack {})
1822 }
1823
1824 async fn handle_commit(
1825 this: Entity<Self>,
1826 envelope: TypedEnvelope<proto::Commit>,
1827 mut cx: AsyncApp,
1828 ) -> Result<proto::Ack> {
1829 let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
1830 let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;
1831
1832 let message = SharedString::from(envelope.payload.message);
1833 let name = envelope.payload.name.map(SharedString::from);
1834 let email = envelope.payload.email.map(SharedString::from);
1835 let options = envelope.payload.options.unwrap_or_default();
1836
1837 repository_handle
1838 .update(&mut cx, |repository_handle, cx| {
1839 repository_handle.commit(
1840 message,
1841 name.zip(email),
1842 CommitOptions {
1843 amend: options.amend,
1844 signoff: options.signoff,
1845 },
1846 cx,
1847 )
1848 })?
1849 .await??;
1850 Ok(proto::Ack {})
1851 }
1852
1853 async fn handle_get_remotes(
1854 this: Entity<Self>,
1855 envelope: TypedEnvelope<proto::GetRemotes>,
1856 mut cx: AsyncApp,
1857 ) -> Result<proto::GetRemotesResponse> {
1858 let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
1859 let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;
1860
1861 let branch_name = envelope.payload.branch_name;
1862
1863 let remotes = repository_handle
1864 .update(&mut cx, |repository_handle, _| {
1865 repository_handle.get_remotes(branch_name)
1866 })?
1867 .await??;
1868
1869 Ok(proto::GetRemotesResponse {
1870 remotes: remotes
1871 .into_iter()
1872 .map(|remotes| proto::get_remotes_response::Remote {
1873 name: remotes.name.to_string(),
1874 })
1875 .collect::<Vec<_>>(),
1876 })
1877 }
1878
1879 async fn handle_get_branches(
1880 this: Entity<Self>,
1881 envelope: TypedEnvelope<proto::GitGetBranches>,
1882 mut cx: AsyncApp,
1883 ) -> Result<proto::GitBranchesResponse> {
1884 let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
1885 let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;
1886
1887 let branches = repository_handle
1888 .update(&mut cx, |repository_handle, _| repository_handle.branches())?
1889 .await??;
1890
1891 Ok(proto::GitBranchesResponse {
1892 branches: branches
1893 .into_iter()
1894 .map(|branch| branch_to_proto(&branch))
1895 .collect::<Vec<_>>(),
1896 })
1897 }
1898 async fn handle_get_default_branch(
1899 this: Entity<Self>,
1900 envelope: TypedEnvelope<proto::GetDefaultBranch>,
1901 mut cx: AsyncApp,
1902 ) -> Result<proto::GetDefaultBranchResponse> {
1903 let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
1904 let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;
1905
1906 let branch = repository_handle
1907 .update(&mut cx, |repository_handle, _| {
1908 repository_handle.default_branch()
1909 })?
1910 .await??
1911 .map(Into::into);
1912
1913 Ok(proto::GetDefaultBranchResponse { branch })
1914 }
1915 async fn handle_create_branch(
1916 this: Entity<Self>,
1917 envelope: TypedEnvelope<proto::GitCreateBranch>,
1918 mut cx: AsyncApp,
1919 ) -> Result<proto::Ack> {
1920 let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
1921 let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;
1922 let branch_name = envelope.payload.branch_name;
1923
1924 repository_handle
1925 .update(&mut cx, |repository_handle, _| {
1926 repository_handle.create_branch(branch_name)
1927 })?
1928 .await??;
1929
1930 Ok(proto::Ack {})
1931 }
1932
1933 async fn handle_change_branch(
1934 this: Entity<Self>,
1935 envelope: TypedEnvelope<proto::GitChangeBranch>,
1936 mut cx: AsyncApp,
1937 ) -> Result<proto::Ack> {
1938 let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
1939 let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;
1940 let branch_name = envelope.payload.branch_name;
1941
1942 repository_handle
1943 .update(&mut cx, |repository_handle, _| {
1944 repository_handle.change_branch(branch_name)
1945 })?
1946 .await??;
1947
1948 Ok(proto::Ack {})
1949 }
1950
1951 async fn handle_show(
1952 this: Entity<Self>,
1953 envelope: TypedEnvelope<proto::GitShow>,
1954 mut cx: AsyncApp,
1955 ) -> Result<proto::GitCommitDetails> {
1956 let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
1957 let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;
1958
1959 let commit = repository_handle
1960 .update(&mut cx, |repository_handle, _| {
1961 repository_handle.show(envelope.payload.commit)
1962 })?
1963 .await??;
1964 Ok(proto::GitCommitDetails {
1965 sha: commit.sha.into(),
1966 message: commit.message.into(),
1967 commit_timestamp: commit.commit_timestamp,
1968 author_email: commit.author_email.into(),
1969 author_name: commit.author_name.into(),
1970 })
1971 }
1972
1973 async fn handle_load_commit_diff(
1974 this: Entity<Self>,
1975 envelope: TypedEnvelope<proto::LoadCommitDiff>,
1976 mut cx: AsyncApp,
1977 ) -> Result<proto::LoadCommitDiffResponse> {
1978 let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
1979 let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;
1980
1981 let commit_diff = repository_handle
1982 .update(&mut cx, |repository_handle, _| {
1983 repository_handle.load_commit_diff(envelope.payload.commit)
1984 })?
1985 .await??;
1986 Ok(proto::LoadCommitDiffResponse {
1987 files: commit_diff
1988 .files
1989 .into_iter()
1990 .map(|file| proto::CommitFile {
1991 path: file.path.to_string(),
1992 old_text: file.old_text,
1993 new_text: file.new_text,
1994 })
1995 .collect(),
1996 })
1997 }
1998
1999 async fn handle_reset(
2000 this: Entity<Self>,
2001 envelope: TypedEnvelope<proto::GitReset>,
2002 mut cx: AsyncApp,
2003 ) -> Result<proto::Ack> {
2004 let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
2005 let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;
2006
2007 let mode = match envelope.payload.mode() {
2008 git_reset::ResetMode::Soft => ResetMode::Soft,
2009 git_reset::ResetMode::Mixed => ResetMode::Mixed,
2010 };
2011
2012 repository_handle
2013 .update(&mut cx, |repository_handle, cx| {
2014 repository_handle.reset(envelope.payload.commit, mode, cx)
2015 })?
2016 .await??;
2017 Ok(proto::Ack {})
2018 }
2019
2020 async fn handle_checkout_files(
2021 this: Entity<Self>,
2022 envelope: TypedEnvelope<proto::GitCheckoutFiles>,
2023 mut cx: AsyncApp,
2024 ) -> Result<proto::Ack> {
2025 let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
2026 let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;
2027 let paths = envelope
2028 .payload
2029 .paths
2030 .iter()
2031 .map(|s| RepoPath::from_str(s))
2032 .collect();
2033
2034 repository_handle
2035 .update(&mut cx, |repository_handle, cx| {
2036 repository_handle.checkout_files(&envelope.payload.commit, paths, cx)
2037 })?
2038 .await??;
2039 Ok(proto::Ack {})
2040 }
2041
2042 async fn handle_open_commit_message_buffer(
2043 this: Entity<Self>,
2044 envelope: TypedEnvelope<proto::OpenCommitMessageBuffer>,
2045 mut cx: AsyncApp,
2046 ) -> Result<proto::OpenBufferResponse> {
2047 let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
2048 let repository = Self::repository_for_request(&this, repository_id, &mut cx)?;
2049 let buffer = repository
2050 .update(&mut cx, |repository, cx| {
2051 repository.open_commit_buffer(None, this.read(cx).buffer_store.clone(), cx)
2052 })?
2053 .await?;
2054
2055 let buffer_id = buffer.read_with(&cx, |buffer, _| buffer.remote_id())?;
2056 this.update(&mut cx, |this, cx| {
2057 this.buffer_store.update(cx, |buffer_store, cx| {
2058 buffer_store
2059 .create_buffer_for_peer(
2060 &buffer,
2061 envelope.original_sender_id.unwrap_or(envelope.sender_id),
2062 cx,
2063 )
2064 .detach_and_log_err(cx);
2065 })
2066 })?;
2067
2068 Ok(proto::OpenBufferResponse {
2069 buffer_id: buffer_id.to_proto(),
2070 })
2071 }
2072
2073 async fn handle_askpass(
2074 this: Entity<Self>,
2075 envelope: TypedEnvelope<proto::AskPassRequest>,
2076 mut cx: AsyncApp,
2077 ) -> Result<proto::AskPassResponse> {
2078 let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
2079 let repository = Self::repository_for_request(&this, repository_id, &mut cx)?;
2080
2081 let delegates = cx.update(|cx| repository.read(cx).askpass_delegates.clone())?;
2082 let Some(mut askpass) = delegates.lock().remove(&envelope.payload.askpass_id) else {
2083 debug_panic!("no askpass found");
2084 anyhow::bail!("no askpass found");
2085 };
2086
2087 let response = askpass.ask_password(envelope.payload.prompt).await?;
2088
2089 delegates
2090 .lock()
2091 .insert(envelope.payload.askpass_id, askpass);
2092
2093 Ok(proto::AskPassResponse { response })
2094 }
2095
2096 async fn handle_check_for_pushed_commits(
2097 this: Entity<Self>,
2098 envelope: TypedEnvelope<proto::CheckForPushedCommits>,
2099 mut cx: AsyncApp,
2100 ) -> Result<proto::CheckForPushedCommitsResponse> {
2101 let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
2102 let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;
2103
2104 let branches = repository_handle
2105 .update(&mut cx, |repository_handle, _| {
2106 repository_handle.check_for_pushed_commits()
2107 })?
2108 .await??;
2109 Ok(proto::CheckForPushedCommitsResponse {
2110 pushed_to: branches
2111 .into_iter()
2112 .map(|commit| commit.to_string())
2113 .collect(),
2114 })
2115 }
2116
2117 async fn handle_git_diff(
2118 this: Entity<Self>,
2119 envelope: TypedEnvelope<proto::GitDiff>,
2120 mut cx: AsyncApp,
2121 ) -> Result<proto::GitDiffResponse> {
2122 let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
2123 let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;
2124 let diff_type = match envelope.payload.diff_type() {
2125 proto::git_diff::DiffType::HeadToIndex => DiffType::HeadToIndex,
2126 proto::git_diff::DiffType::HeadToWorktree => DiffType::HeadToWorktree,
2127 };
2128
2129 let mut diff = repository_handle
2130 .update(&mut cx, |repository_handle, cx| {
2131 repository_handle.diff(diff_type, cx)
2132 })?
2133 .await??;
2134 const ONE_MB: usize = 1_000_000;
2135 if diff.len() > ONE_MB {
2136 diff = diff.chars().take(ONE_MB).collect()
2137 }
2138
2139 Ok(proto::GitDiffResponse { diff })
2140 }
2141
2142 async fn handle_open_unstaged_diff(
2143 this: Entity<Self>,
2144 request: TypedEnvelope<proto::OpenUnstagedDiff>,
2145 mut cx: AsyncApp,
2146 ) -> Result<proto::OpenUnstagedDiffResponse> {
2147 let buffer_id = BufferId::new(request.payload.buffer_id)?;
2148 let diff = this
2149 .update(&mut cx, |this, cx| {
2150 let buffer = this.buffer_store.read(cx).get(buffer_id)?;
2151 Some(this.open_unstaged_diff(buffer, cx))
2152 })?
2153 .context("missing buffer")?
2154 .await?;
2155 this.update(&mut cx, |this, _| {
2156 let shared_diffs = this
2157 .shared_diffs
2158 .entry(request.original_sender_id.unwrap_or(request.sender_id))
2159 .or_default();
2160 shared_diffs.entry(buffer_id).or_default().unstaged = Some(diff.clone());
2161 })?;
2162 let staged_text = diff.read_with(&cx, |diff, _| diff.base_text_string())?;
2163 Ok(proto::OpenUnstagedDiffResponse { staged_text })
2164 }
2165
2166 async fn handle_open_uncommitted_diff(
2167 this: Entity<Self>,
2168 request: TypedEnvelope<proto::OpenUncommittedDiff>,
2169 mut cx: AsyncApp,
2170 ) -> Result<proto::OpenUncommittedDiffResponse> {
2171 let buffer_id = BufferId::new(request.payload.buffer_id)?;
2172 let diff = this
2173 .update(&mut cx, |this, cx| {
2174 let buffer = this.buffer_store.read(cx).get(buffer_id)?;
2175 Some(this.open_uncommitted_diff(buffer, cx))
2176 })?
2177 .context("missing buffer")?
2178 .await?;
2179 this.update(&mut cx, |this, _| {
2180 let shared_diffs = this
2181 .shared_diffs
2182 .entry(request.original_sender_id.unwrap_or(request.sender_id))
2183 .or_default();
2184 shared_diffs.entry(buffer_id).or_default().uncommitted = Some(diff.clone());
2185 })?;
2186 diff.read_with(&cx, |diff, cx| {
2187 use proto::open_uncommitted_diff_response::Mode;
2188
2189 let unstaged_diff = diff.secondary_diff();
2190 let index_snapshot = unstaged_diff.and_then(|diff| {
2191 let diff = diff.read(cx);
2192 diff.base_text_exists().then(|| diff.base_text())
2193 });
2194
2195 let mode;
2196 let staged_text;
2197 let committed_text;
2198 if diff.base_text_exists() {
2199 let committed_snapshot = diff.base_text();
2200 committed_text = Some(committed_snapshot.text());
2201 if let Some(index_text) = index_snapshot {
2202 if index_text.remote_id() == committed_snapshot.remote_id() {
2203 mode = Mode::IndexMatchesHead;
2204 staged_text = None;
2205 } else {
2206 mode = Mode::IndexAndHead;
2207 staged_text = Some(index_text.text());
2208 }
2209 } else {
2210 mode = Mode::IndexAndHead;
2211 staged_text = None;
2212 }
2213 } else {
2214 mode = Mode::IndexAndHead;
2215 committed_text = None;
2216 staged_text = index_snapshot.as_ref().map(|buffer| buffer.text());
2217 }
2218
2219 proto::OpenUncommittedDiffResponse {
2220 committed_text,
2221 staged_text,
2222 mode: mode.into(),
2223 }
2224 })
2225 }
2226
2227 async fn handle_update_diff_bases(
2228 this: Entity<Self>,
2229 request: TypedEnvelope<proto::UpdateDiffBases>,
2230 mut cx: AsyncApp,
2231 ) -> Result<()> {
2232 let buffer_id = BufferId::new(request.payload.buffer_id)?;
2233 this.update(&mut cx, |this, cx| {
2234 if let Some(diff_state) = this.diffs.get_mut(&buffer_id) {
2235 if let Some(buffer) = this.buffer_store.read(cx).get(buffer_id) {
2236 let buffer = buffer.read(cx).text_snapshot();
2237 diff_state.update(cx, |diff_state, cx| {
2238 diff_state.handle_base_texts_updated(buffer, request.payload, cx);
2239 })
2240 }
2241 }
2242 })
2243 }
2244
2245 async fn handle_blame_buffer(
2246 this: Entity<Self>,
2247 envelope: TypedEnvelope<proto::BlameBuffer>,
2248 mut cx: AsyncApp,
2249 ) -> Result<proto::BlameBufferResponse> {
2250 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
2251 let version = deserialize_version(&envelope.payload.version);
2252 let buffer = this.read_with(&cx, |this, cx| {
2253 this.buffer_store.read(cx).get_existing(buffer_id)
2254 })??;
2255 buffer
2256 .update(&mut cx, |buffer, _| {
2257 buffer.wait_for_version(version.clone())
2258 })?
2259 .await?;
2260 let blame = this
2261 .update(&mut cx, |this, cx| {
2262 this.blame_buffer(&buffer, Some(version), cx)
2263 })?
2264 .await?;
2265 Ok(serialize_blame_buffer_response(blame))
2266 }
2267
2268 async fn handle_get_permalink_to_line(
2269 this: Entity<Self>,
2270 envelope: TypedEnvelope<proto::GetPermalinkToLine>,
2271 mut cx: AsyncApp,
2272 ) -> Result<proto::GetPermalinkToLineResponse> {
2273 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
2274 // let version = deserialize_version(&envelope.payload.version);
2275 let selection = {
2276 let proto_selection = envelope
2277 .payload
2278 .selection
2279 .context("no selection to get permalink for defined")?;
2280 proto_selection.start as u32..proto_selection.end as u32
2281 };
2282 let buffer = this.read_with(&cx, |this, cx| {
2283 this.buffer_store.read(cx).get_existing(buffer_id)
2284 })??;
2285 let permalink = this
2286 .update(&mut cx, |this, cx| {
2287 this.get_permalink_to_line(&buffer, selection, cx)
2288 })?
2289 .await?;
2290 Ok(proto::GetPermalinkToLineResponse {
2291 permalink: permalink.to_string(),
2292 })
2293 }
2294
2295 fn repository_for_request(
2296 this: &Entity<Self>,
2297 id: RepositoryId,
2298 cx: &mut AsyncApp,
2299 ) -> Result<Entity<Repository>> {
2300 this.read_with(cx, |this, _| {
2301 this.repositories
2302 .get(&id)
2303 .context("missing repository handle")
2304 .cloned()
2305 })?
2306 }
2307
2308 pub fn repo_snapshots(&self, cx: &App) -> HashMap<RepositoryId, RepositorySnapshot> {
2309 self.repositories
2310 .iter()
2311 .map(|(id, repo)| (*id, repo.read(cx).snapshot.clone()))
2312 .collect()
2313 }
2314
2315 fn process_updated_entries(
2316 &self,
2317 worktree: &Entity<Worktree>,
2318 updated_entries: &[(Arc<Path>, ProjectEntryId, PathChange)],
2319 cx: &mut App,
2320 ) -> Task<HashMap<Entity<Repository>, Vec<RepoPath>>> {
2321 let mut repo_paths = self
2322 .repositories
2323 .values()
2324 .map(|repo| (repo.read(cx).work_directory_abs_path.clone(), repo.clone()))
2325 .collect::<Vec<_>>();
2326 let mut entries: Vec<_> = updated_entries
2327 .iter()
2328 .map(|(path, _, _)| path.clone())
2329 .collect();
2330 entries.sort();
2331 let worktree = worktree.read(cx);
2332
2333 let entries = entries
2334 .into_iter()
2335 .filter_map(|path| worktree.absolutize(&path).ok())
2336 .collect::<Arc<[_]>>();
2337
2338 let executor = cx.background_executor().clone();
2339 cx.background_executor().spawn(async move {
2340 repo_paths.sort_by(|lhs, rhs| lhs.0.cmp(&rhs.0));
2341 let mut paths_by_git_repo = HashMap::<_, Vec<_>>::default();
2342 let mut tasks = FuturesOrdered::new();
2343 for (repo_path, repo) in repo_paths.into_iter().rev() {
2344 let entries = entries.clone();
2345 let task = executor.spawn(async move {
2346 // Find all repository paths that belong to this repo
2347 let mut ix = entries.partition_point(|path| path < &*repo_path);
2348 if ix == entries.len() {
2349 return None;
2350 };
2351
2352 let mut paths = vec![];
2353 // All paths prefixed by a given repo will constitute a continuous range.
2354 while let Some(path) = entries.get(ix)
2355 && let Some(repo_path) =
2356 RepositorySnapshot::abs_path_to_repo_path_inner(&repo_path, &path)
2357 {
2358 paths.push((repo_path, ix));
2359 ix += 1;
2360 }
2361 Some((repo, paths))
2362 });
2363 tasks.push_back(task);
2364 }
2365
2366 // Now, let's filter out the "duplicate" entries that were processed by multiple distinct repos.
2367 let mut path_was_used = vec![false; entries.len()];
2368 let tasks = tasks.collect::<Vec<_>>().await;
2369 // Process tasks from the back: iterating backwards allows us to see more-specific paths first.
2370 // We always want to assign a path to it's innermost repository.
2371 for t in tasks {
2372 let Some((repo, paths)) = t else {
2373 continue;
2374 };
2375 let entry = paths_by_git_repo.entry(repo).or_default();
2376 for (repo_path, ix) in paths {
2377 if path_was_used[ix] {
2378 continue;
2379 }
2380 path_was_used[ix] = true;
2381 entry.push(repo_path);
2382 }
2383 }
2384
2385 paths_by_git_repo
2386 })
2387 }
2388}
2389
2390impl BufferGitState {
2391 fn new(_git_store: WeakEntity<GitStore>) -> Self {
2392 Self {
2393 unstaged_diff: Default::default(),
2394 uncommitted_diff: Default::default(),
2395 recalculate_diff_task: Default::default(),
2396 language: Default::default(),
2397 language_registry: Default::default(),
2398 recalculating_tx: postage::watch::channel_with(false).0,
2399 hunk_staging_operation_count: 0,
2400 hunk_staging_operation_count_as_of_write: 0,
2401 head_text: Default::default(),
2402 index_text: Default::default(),
2403 head_changed: Default::default(),
2404 index_changed: Default::default(),
2405 language_changed: Default::default(),
2406 conflict_updated_futures: Default::default(),
2407 conflict_set: Default::default(),
2408 reparse_conflict_markers_task: Default::default(),
2409 }
2410 }
2411
2412 fn buffer_language_changed(&mut self, buffer: Entity<Buffer>, cx: &mut Context<Self>) {
2413 self.language = buffer.read(cx).language().cloned();
2414 self.language_changed = true;
2415 let _ = self.recalculate_diffs(buffer.read(cx).text_snapshot(), cx);
2416 }
2417
2418 fn reparse_conflict_markers(
2419 &mut self,
2420 buffer: text::BufferSnapshot,
2421 cx: &mut Context<Self>,
2422 ) -> oneshot::Receiver<()> {
2423 let (tx, rx) = oneshot::channel();
2424
2425 let Some(conflict_set) = self
2426 .conflict_set
2427 .as_ref()
2428 .and_then(|conflict_set| conflict_set.upgrade())
2429 else {
2430 return rx;
2431 };
2432
2433 let old_snapshot = conflict_set.read_with(cx, |conflict_set, _| {
2434 if conflict_set.has_conflict {
2435 Some(conflict_set.snapshot())
2436 } else {
2437 None
2438 }
2439 });
2440
2441 if let Some(old_snapshot) = old_snapshot {
2442 self.conflict_updated_futures.push(tx);
2443 self.reparse_conflict_markers_task = Some(cx.spawn(async move |this, cx| {
2444 let (snapshot, changed_range) = cx
2445 .background_spawn(async move {
2446 let new_snapshot = ConflictSet::parse(&buffer);
2447 let changed_range = old_snapshot.compare(&new_snapshot, &buffer);
2448 (new_snapshot, changed_range)
2449 })
2450 .await;
2451 this.update(cx, |this, cx| {
2452 if let Some(conflict_set) = &this.conflict_set {
2453 conflict_set
2454 .update(cx, |conflict_set, cx| {
2455 conflict_set.set_snapshot(snapshot, changed_range, cx);
2456 })
2457 .ok();
2458 }
2459 let futures = std::mem::take(&mut this.conflict_updated_futures);
2460 for tx in futures {
2461 tx.send(()).ok();
2462 }
2463 })
2464 }))
2465 }
2466
2467 rx
2468 }
2469
2470 fn unstaged_diff(&self) -> Option<Entity<BufferDiff>> {
2471 self.unstaged_diff.as_ref().and_then(|set| set.upgrade())
2472 }
2473
2474 fn uncommitted_diff(&self) -> Option<Entity<BufferDiff>> {
2475 self.uncommitted_diff.as_ref().and_then(|set| set.upgrade())
2476 }
2477
2478 fn handle_base_texts_updated(
2479 &mut self,
2480 buffer: text::BufferSnapshot,
2481 message: proto::UpdateDiffBases,
2482 cx: &mut Context<Self>,
2483 ) {
2484 use proto::update_diff_bases::Mode;
2485
2486 let Some(mode) = Mode::from_i32(message.mode) else {
2487 return;
2488 };
2489
2490 let diff_bases_change = match mode {
2491 Mode::HeadOnly => DiffBasesChange::SetHead(message.committed_text),
2492 Mode::IndexOnly => DiffBasesChange::SetIndex(message.staged_text),
2493 Mode::IndexMatchesHead => DiffBasesChange::SetBoth(message.committed_text),
2494 Mode::IndexAndHead => DiffBasesChange::SetEach {
2495 index: message.staged_text,
2496 head: message.committed_text,
2497 },
2498 };
2499
2500 self.diff_bases_changed(buffer, Some(diff_bases_change), cx);
2501 }
2502
2503 pub fn wait_for_recalculation(&mut self) -> Option<impl Future<Output = ()> + use<>> {
2504 if *self.recalculating_tx.borrow() {
2505 let mut rx = self.recalculating_tx.subscribe();
2506 return Some(async move {
2507 loop {
2508 let is_recalculating = rx.recv().await;
2509 if is_recalculating != Some(true) {
2510 break;
2511 }
2512 }
2513 });
2514 } else {
2515 None
2516 }
2517 }
2518
2519 fn diff_bases_changed(
2520 &mut self,
2521 buffer: text::BufferSnapshot,
2522 diff_bases_change: Option<DiffBasesChange>,
2523 cx: &mut Context<Self>,
2524 ) {
2525 match diff_bases_change {
2526 Some(DiffBasesChange::SetIndex(index)) => {
2527 self.index_text = index.map(|mut index| {
2528 text::LineEnding::normalize(&mut index);
2529 Arc::new(index)
2530 });
2531 self.index_changed = true;
2532 }
2533 Some(DiffBasesChange::SetHead(head)) => {
2534 self.head_text = head.map(|mut head| {
2535 text::LineEnding::normalize(&mut head);
2536 Arc::new(head)
2537 });
2538 self.head_changed = true;
2539 }
2540 Some(DiffBasesChange::SetBoth(text)) => {
2541 let text = text.map(|mut text| {
2542 text::LineEnding::normalize(&mut text);
2543 Arc::new(text)
2544 });
2545 self.head_text = text.clone();
2546 self.index_text = text;
2547 self.head_changed = true;
2548 self.index_changed = true;
2549 }
2550 Some(DiffBasesChange::SetEach { index, head }) => {
2551 self.index_text = index.map(|mut index| {
2552 text::LineEnding::normalize(&mut index);
2553 Arc::new(index)
2554 });
2555 self.index_changed = true;
2556 self.head_text = head.map(|mut head| {
2557 text::LineEnding::normalize(&mut head);
2558 Arc::new(head)
2559 });
2560 self.head_changed = true;
2561 }
2562 None => {}
2563 }
2564
2565 self.recalculate_diffs(buffer, cx)
2566 }
2567
2568 fn recalculate_diffs(&mut self, buffer: text::BufferSnapshot, cx: &mut Context<Self>) {
2569 *self.recalculating_tx.borrow_mut() = true;
2570
2571 let language = self.language.clone();
2572 let language_registry = self.language_registry.clone();
2573 let unstaged_diff = self.unstaged_diff();
2574 let uncommitted_diff = self.uncommitted_diff();
2575 let head = self.head_text.clone();
2576 let index = self.index_text.clone();
2577 let index_changed = self.index_changed;
2578 let head_changed = self.head_changed;
2579 let language_changed = self.language_changed;
2580 let prev_hunk_staging_operation_count = self.hunk_staging_operation_count_as_of_write;
2581 let index_matches_head = match (self.index_text.as_ref(), self.head_text.as_ref()) {
2582 (Some(index), Some(head)) => Arc::ptr_eq(index, head),
2583 (None, None) => true,
2584 _ => false,
2585 };
2586 self.recalculate_diff_task = Some(cx.spawn(async move |this, cx| {
2587 log::debug!(
2588 "start recalculating diffs for buffer {}",
2589 buffer.remote_id()
2590 );
2591
2592 let mut new_unstaged_diff = None;
2593 if let Some(unstaged_diff) = &unstaged_diff {
2594 new_unstaged_diff = Some(
2595 BufferDiff::update_diff(
2596 unstaged_diff.clone(),
2597 buffer.clone(),
2598 index,
2599 index_changed,
2600 language_changed,
2601 language.clone(),
2602 language_registry.clone(),
2603 cx,
2604 )
2605 .await?,
2606 );
2607 }
2608
2609 let mut new_uncommitted_diff = None;
2610 if let Some(uncommitted_diff) = &uncommitted_diff {
2611 new_uncommitted_diff = if index_matches_head {
2612 new_unstaged_diff.clone()
2613 } else {
2614 Some(
2615 BufferDiff::update_diff(
2616 uncommitted_diff.clone(),
2617 buffer.clone(),
2618 head,
2619 head_changed,
2620 language_changed,
2621 language.clone(),
2622 language_registry.clone(),
2623 cx,
2624 )
2625 .await?,
2626 )
2627 }
2628 }
2629
2630 let cancel = this.update(cx, |this, _| {
2631 // This checks whether all pending stage/unstage operations
2632 // have quiesced (i.e. both the corresponding write and the
2633 // read of that write have completed). If not, then we cancel
2634 // this recalculation attempt to avoid invalidating pending
2635 // state too quickly; another recalculation will come along
2636 // later and clear the pending state once the state of the index has settled.
2637 if this.hunk_staging_operation_count > prev_hunk_staging_operation_count {
2638 *this.recalculating_tx.borrow_mut() = false;
2639 true
2640 } else {
2641 false
2642 }
2643 })?;
2644 if cancel {
2645 log::debug!(
2646 concat!(
2647 "aborting recalculating diffs for buffer {}",
2648 "due to subsequent hunk operations",
2649 ),
2650 buffer.remote_id()
2651 );
2652 return Ok(());
2653 }
2654
2655 let unstaged_changed_range = if let Some((unstaged_diff, new_unstaged_diff)) =
2656 unstaged_diff.as_ref().zip(new_unstaged_diff.clone())
2657 {
2658 unstaged_diff.update(cx, |diff, cx| {
2659 if language_changed {
2660 diff.language_changed(cx);
2661 }
2662 diff.set_snapshot(new_unstaged_diff, &buffer, cx)
2663 })?
2664 } else {
2665 None
2666 };
2667
2668 if let Some((uncommitted_diff, new_uncommitted_diff)) =
2669 uncommitted_diff.as_ref().zip(new_uncommitted_diff.clone())
2670 {
2671 uncommitted_diff.update(cx, |diff, cx| {
2672 if language_changed {
2673 diff.language_changed(cx);
2674 }
2675 diff.set_snapshot_with_secondary(
2676 new_uncommitted_diff,
2677 &buffer,
2678 unstaged_changed_range,
2679 true,
2680 cx,
2681 );
2682 })?;
2683 }
2684
2685 log::debug!(
2686 "finished recalculating diffs for buffer {}",
2687 buffer.remote_id()
2688 );
2689
2690 if let Some(this) = this.upgrade() {
2691 this.update(cx, |this, _| {
2692 this.index_changed = false;
2693 this.head_changed = false;
2694 this.language_changed = false;
2695 *this.recalculating_tx.borrow_mut() = false;
2696 })?;
2697 }
2698
2699 Ok(())
2700 }));
2701 }
2702}
2703
2704fn make_remote_delegate(
2705 this: Entity<GitStore>,
2706 project_id: u64,
2707 repository_id: RepositoryId,
2708 askpass_id: u64,
2709 cx: &mut AsyncApp,
2710) -> AskPassDelegate {
2711 AskPassDelegate::new(cx, move |prompt, tx, cx| {
2712 this.update(cx, |this, cx| {
2713 let Some((client, _)) = this.downstream_client() else {
2714 return;
2715 };
2716 let response = client.request(proto::AskPassRequest {
2717 project_id,
2718 repository_id: repository_id.to_proto(),
2719 askpass_id,
2720 prompt,
2721 });
2722 cx.spawn(async move |_, _| {
2723 tx.send(response.await?.response).ok();
2724 anyhow::Ok(())
2725 })
2726 .detach_and_log_err(cx);
2727 })
2728 .log_err();
2729 })
2730}
2731
2732impl RepositoryId {
2733 pub fn to_proto(self) -> u64 {
2734 self.0
2735 }
2736
2737 pub fn from_proto(id: u64) -> Self {
2738 RepositoryId(id)
2739 }
2740}
2741
2742impl RepositorySnapshot {
2743 fn empty(id: RepositoryId, work_directory_abs_path: Arc<Path>) -> Self {
2744 Self {
2745 id,
2746 statuses_by_path: Default::default(),
2747 work_directory_abs_path,
2748 branch: None,
2749 head_commit: None,
2750 scan_id: 0,
2751 merge: Default::default(),
2752 remote_origin_url: None,
2753 remote_upstream_url: None,
2754 }
2755 }
2756
2757 fn initial_update(&self, project_id: u64) -> proto::UpdateRepository {
2758 proto::UpdateRepository {
2759 branch_summary: self.branch.as_ref().map(branch_to_proto),
2760 head_commit_details: self.head_commit.as_ref().map(commit_details_to_proto),
2761 updated_statuses: self
2762 .statuses_by_path
2763 .iter()
2764 .map(|entry| entry.to_proto())
2765 .collect(),
2766 removed_statuses: Default::default(),
2767 current_merge_conflicts: self
2768 .merge
2769 .conflicted_paths
2770 .iter()
2771 .map(|repo_path| repo_path.to_proto())
2772 .collect(),
2773 project_id,
2774 id: self.id.to_proto(),
2775 abs_path: self.work_directory_abs_path.to_proto(),
2776 entry_ids: vec![self.id.to_proto()],
2777 scan_id: self.scan_id,
2778 is_last_update: true,
2779 }
2780 }
2781
2782 fn build_update(&self, old: &Self, project_id: u64) -> proto::UpdateRepository {
2783 let mut updated_statuses: Vec<proto::StatusEntry> = Vec::new();
2784 let mut removed_statuses: Vec<String> = Vec::new();
2785
2786 let mut new_statuses = self.statuses_by_path.iter().peekable();
2787 let mut old_statuses = old.statuses_by_path.iter().peekable();
2788
2789 let mut current_new_entry = new_statuses.next();
2790 let mut current_old_entry = old_statuses.next();
2791 loop {
2792 match (current_new_entry, current_old_entry) {
2793 (Some(new_entry), Some(old_entry)) => {
2794 match new_entry.repo_path.cmp(&old_entry.repo_path) {
2795 Ordering::Less => {
2796 updated_statuses.push(new_entry.to_proto());
2797 current_new_entry = new_statuses.next();
2798 }
2799 Ordering::Equal => {
2800 if new_entry.status != old_entry.status {
2801 updated_statuses.push(new_entry.to_proto());
2802 }
2803 current_old_entry = old_statuses.next();
2804 current_new_entry = new_statuses.next();
2805 }
2806 Ordering::Greater => {
2807 removed_statuses.push(old_entry.repo_path.as_ref().to_proto());
2808 current_old_entry = old_statuses.next();
2809 }
2810 }
2811 }
2812 (None, Some(old_entry)) => {
2813 removed_statuses.push(old_entry.repo_path.as_ref().to_proto());
2814 current_old_entry = old_statuses.next();
2815 }
2816 (Some(new_entry), None) => {
2817 updated_statuses.push(new_entry.to_proto());
2818 current_new_entry = new_statuses.next();
2819 }
2820 (None, None) => break,
2821 }
2822 }
2823
2824 proto::UpdateRepository {
2825 branch_summary: self.branch.as_ref().map(branch_to_proto),
2826 head_commit_details: self.head_commit.as_ref().map(commit_details_to_proto),
2827 updated_statuses,
2828 removed_statuses,
2829 current_merge_conflicts: self
2830 .merge
2831 .conflicted_paths
2832 .iter()
2833 .map(|path| path.as_ref().to_proto())
2834 .collect(),
2835 project_id,
2836 id: self.id.to_proto(),
2837 abs_path: self.work_directory_abs_path.to_proto(),
2838 entry_ids: vec![],
2839 scan_id: self.scan_id,
2840 is_last_update: true,
2841 }
2842 }
2843
2844 pub fn status(&self) -> impl Iterator<Item = StatusEntry> + '_ {
2845 self.statuses_by_path.iter().cloned()
2846 }
2847
2848 pub fn status_summary(&self) -> GitSummary {
2849 self.statuses_by_path.summary().item_summary
2850 }
2851
2852 pub fn status_for_path(&self, path: &RepoPath) -> Option<StatusEntry> {
2853 self.statuses_by_path
2854 .get(&PathKey(path.0.clone()), &())
2855 .cloned()
2856 }
2857
2858 pub fn abs_path_to_repo_path(&self, abs_path: &Path) -> Option<RepoPath> {
2859 Self::abs_path_to_repo_path_inner(&self.work_directory_abs_path, abs_path)
2860 }
2861
2862 #[inline]
2863 fn abs_path_to_repo_path_inner(
2864 work_directory_abs_path: &Path,
2865 abs_path: &Path,
2866 ) -> Option<RepoPath> {
2867 abs_path
2868 .strip_prefix(&work_directory_abs_path)
2869 .map(RepoPath::from)
2870 .ok()
2871 }
2872
2873 pub fn had_conflict_on_last_merge_head_change(&self, repo_path: &RepoPath) -> bool {
2874 self.merge.conflicted_paths.contains(&repo_path)
2875 }
2876
2877 pub fn has_conflict(&self, repo_path: &RepoPath) -> bool {
2878 let had_conflict_on_last_merge_head_change =
2879 self.merge.conflicted_paths.contains(&repo_path);
2880 let has_conflict_currently = self
2881 .status_for_path(&repo_path)
2882 .map_or(false, |entry| entry.status.is_conflicted());
2883 had_conflict_on_last_merge_head_change || has_conflict_currently
2884 }
2885
2886 /// This is the name that will be displayed in the repository selector for this repository.
2887 pub fn display_name(&self) -> SharedString {
2888 self.work_directory_abs_path
2889 .file_name()
2890 .unwrap_or_default()
2891 .to_string_lossy()
2892 .to_string()
2893 .into()
2894 }
2895}
2896
2897impl MergeDetails {
2898 async fn load(
2899 backend: &Arc<dyn GitRepository>,
2900 status: &SumTree<StatusEntry>,
2901 prev_snapshot: &RepositorySnapshot,
2902 ) -> Result<(MergeDetails, bool)> {
2903 log::debug!("load merge details");
2904 let message = backend.merge_message().await;
2905 let heads = backend
2906 .revparse_batch(vec![
2907 "MERGE_HEAD".into(),
2908 "CHERRY_PICK_HEAD".into(),
2909 "REBASE_HEAD".into(),
2910 "REVERT_HEAD".into(),
2911 "APPLY_HEAD".into(),
2912 ])
2913 .await
2914 .log_err()
2915 .unwrap_or_default()
2916 .into_iter()
2917 .map(|opt| opt.map(SharedString::from))
2918 .collect::<Vec<_>>();
2919 let merge_heads_changed = heads != prev_snapshot.merge.heads;
2920 let conflicted_paths = if merge_heads_changed {
2921 let current_conflicted_paths = TreeSet::from_ordered_entries(
2922 status
2923 .iter()
2924 .filter(|entry| entry.status.is_conflicted())
2925 .map(|entry| entry.repo_path.clone()),
2926 );
2927
2928 // It can happen that we run a scan while a lengthy merge is in progress
2929 // that will eventually result in conflicts, but before those conflicts
2930 // are reported by `git status`. Since for the moment we only care about
2931 // the merge heads state for the purposes of tracking conflicts, don't update
2932 // this state until we see some conflicts.
2933 if heads.iter().any(Option::is_some)
2934 && !prev_snapshot.merge.heads.iter().any(Option::is_some)
2935 && current_conflicted_paths.is_empty()
2936 {
2937 log::debug!("not updating merge heads because no conflicts found");
2938 return Ok((
2939 MergeDetails {
2940 message: message.map(SharedString::from),
2941 ..prev_snapshot.merge.clone()
2942 },
2943 false,
2944 ));
2945 }
2946
2947 current_conflicted_paths
2948 } else {
2949 prev_snapshot.merge.conflicted_paths.clone()
2950 };
2951 let details = MergeDetails {
2952 conflicted_paths,
2953 message: message.map(SharedString::from),
2954 heads,
2955 };
2956 Ok((details, merge_heads_changed))
2957 }
2958}
2959
2960impl Repository {
2961 pub fn snapshot(&self) -> RepositorySnapshot {
2962 self.snapshot.clone()
2963 }
2964
2965 fn local(
2966 id: RepositoryId,
2967 work_directory_abs_path: Arc<Path>,
2968 dot_git_abs_path: Arc<Path>,
2969 repository_dir_abs_path: Arc<Path>,
2970 common_dir_abs_path: Arc<Path>,
2971 project_environment: WeakEntity<ProjectEnvironment>,
2972 fs: Arc<dyn Fs>,
2973 git_store: WeakEntity<GitStore>,
2974 cx: &mut Context<Self>,
2975 ) -> Self {
2976 let snapshot = RepositorySnapshot::empty(id, work_directory_abs_path.clone());
2977 Repository {
2978 this: cx.weak_entity(),
2979 git_store,
2980 snapshot,
2981 commit_message_buffer: None,
2982 askpass_delegates: Default::default(),
2983 paths_needing_status_update: Default::default(),
2984 latest_askpass_id: 0,
2985 job_sender: Repository::spawn_local_git_worker(
2986 work_directory_abs_path,
2987 dot_git_abs_path,
2988 repository_dir_abs_path,
2989 common_dir_abs_path,
2990 project_environment,
2991 fs,
2992 cx,
2993 ),
2994 job_id: 0,
2995 active_jobs: Default::default(),
2996 }
2997 }
2998
2999 fn remote(
3000 id: RepositoryId,
3001 work_directory_abs_path: Arc<Path>,
3002 project_id: ProjectId,
3003 client: AnyProtoClient,
3004 git_store: WeakEntity<GitStore>,
3005 cx: &mut Context<Self>,
3006 ) -> Self {
3007 let snapshot = RepositorySnapshot::empty(id, work_directory_abs_path);
3008 Self {
3009 this: cx.weak_entity(),
3010 snapshot,
3011 commit_message_buffer: None,
3012 git_store,
3013 paths_needing_status_update: Default::default(),
3014 job_sender: Self::spawn_remote_git_worker(project_id, client, cx),
3015 askpass_delegates: Default::default(),
3016 latest_askpass_id: 0,
3017 active_jobs: Default::default(),
3018 job_id: 0,
3019 }
3020 }
3021
3022 pub fn git_store(&self) -> Option<Entity<GitStore>> {
3023 self.git_store.upgrade()
3024 }
3025
3026 fn reload_buffer_diff_bases(&mut self, cx: &mut Context<Self>) {
3027 let this = cx.weak_entity();
3028 let git_store = self.git_store.clone();
3029 let _ = self.send_keyed_job(
3030 Some(GitJobKey::ReloadBufferDiffBases),
3031 None,
3032 |state, mut cx| async move {
3033 let RepositoryState::Local { backend, .. } = state else {
3034 log::error!("tried to recompute diffs for a non-local repository");
3035 return Ok(());
3036 };
3037
3038 let Some(this) = this.upgrade() else {
3039 return Ok(());
3040 };
3041
3042 let repo_diff_state_updates = this.update(&mut cx, |this, cx| {
3043 git_store.update(cx, |git_store, cx| {
3044 git_store
3045 .diffs
3046 .iter()
3047 .filter_map(|(buffer_id, diff_state)| {
3048 let buffer_store = git_store.buffer_store.read(cx);
3049 let buffer = buffer_store.get(*buffer_id)?;
3050 let file = File::from_dyn(buffer.read(cx).file())?;
3051 let abs_path =
3052 file.worktree.read(cx).absolutize(&file.path).ok()?;
3053 let repo_path = this.abs_path_to_repo_path(&abs_path)?;
3054 log::debug!(
3055 "start reload diff bases for repo path {}",
3056 repo_path.0.display()
3057 );
3058 diff_state.update(cx, |diff_state, _| {
3059 let has_unstaged_diff = diff_state
3060 .unstaged_diff
3061 .as_ref()
3062 .is_some_and(|diff| diff.is_upgradable());
3063 let has_uncommitted_diff = diff_state
3064 .uncommitted_diff
3065 .as_ref()
3066 .is_some_and(|set| set.is_upgradable());
3067
3068 Some((
3069 buffer,
3070 repo_path,
3071 has_unstaged_diff.then(|| diff_state.index_text.clone()),
3072 has_uncommitted_diff.then(|| diff_state.head_text.clone()),
3073 ))
3074 })
3075 })
3076 .collect::<Vec<_>>()
3077 })
3078 })??;
3079
3080 let buffer_diff_base_changes = cx
3081 .background_spawn(async move {
3082 let mut changes = Vec::new();
3083 for (buffer, repo_path, current_index_text, current_head_text) in
3084 &repo_diff_state_updates
3085 {
3086 let index_text = if current_index_text.is_some() {
3087 backend.load_index_text(repo_path.clone()).await
3088 } else {
3089 None
3090 };
3091 let head_text = if current_head_text.is_some() {
3092 backend.load_committed_text(repo_path.clone()).await
3093 } else {
3094 None
3095 };
3096
3097 let change =
3098 match (current_index_text.as_ref(), current_head_text.as_ref()) {
3099 (Some(current_index), Some(current_head)) => {
3100 let index_changed =
3101 index_text.as_ref() != current_index.as_deref();
3102 let head_changed =
3103 head_text.as_ref() != current_head.as_deref();
3104 if index_changed && head_changed {
3105 if index_text == head_text {
3106 Some(DiffBasesChange::SetBoth(head_text))
3107 } else {
3108 Some(DiffBasesChange::SetEach {
3109 index: index_text,
3110 head: head_text,
3111 })
3112 }
3113 } else if index_changed {
3114 Some(DiffBasesChange::SetIndex(index_text))
3115 } else if head_changed {
3116 Some(DiffBasesChange::SetHead(head_text))
3117 } else {
3118 None
3119 }
3120 }
3121 (Some(current_index), None) => {
3122 let index_changed =
3123 index_text.as_ref() != current_index.as_deref();
3124 index_changed
3125 .then_some(DiffBasesChange::SetIndex(index_text))
3126 }
3127 (None, Some(current_head)) => {
3128 let head_changed =
3129 head_text.as_ref() != current_head.as_deref();
3130 head_changed.then_some(DiffBasesChange::SetHead(head_text))
3131 }
3132 (None, None) => None,
3133 };
3134
3135 changes.push((buffer.clone(), change))
3136 }
3137 changes
3138 })
3139 .await;
3140
3141 git_store.update(&mut cx, |git_store, cx| {
3142 for (buffer, diff_bases_change) in buffer_diff_base_changes {
3143 let buffer_snapshot = buffer.read(cx).text_snapshot();
3144 let buffer_id = buffer_snapshot.remote_id();
3145 let Some(diff_state) = git_store.diffs.get(&buffer_id) else {
3146 continue;
3147 };
3148
3149 let downstream_client = git_store.downstream_client();
3150 diff_state.update(cx, |diff_state, cx| {
3151 use proto::update_diff_bases::Mode;
3152
3153 if let Some((diff_bases_change, (client, project_id))) =
3154 diff_bases_change.clone().zip(downstream_client)
3155 {
3156 let (staged_text, committed_text, mode) = match diff_bases_change {
3157 DiffBasesChange::SetIndex(index) => {
3158 (index, None, Mode::IndexOnly)
3159 }
3160 DiffBasesChange::SetHead(head) => (None, head, Mode::HeadOnly),
3161 DiffBasesChange::SetEach { index, head } => {
3162 (index, head, Mode::IndexAndHead)
3163 }
3164 DiffBasesChange::SetBoth(text) => {
3165 (None, text, Mode::IndexMatchesHead)
3166 }
3167 };
3168 client
3169 .send(proto::UpdateDiffBases {
3170 project_id: project_id.to_proto(),
3171 buffer_id: buffer_id.to_proto(),
3172 staged_text,
3173 committed_text,
3174 mode: mode as i32,
3175 })
3176 .log_err();
3177 }
3178
3179 diff_state.diff_bases_changed(buffer_snapshot, diff_bases_change, cx);
3180 });
3181 }
3182 })
3183 },
3184 );
3185 }
3186
3187 pub fn send_job<F, Fut, R>(
3188 &mut self,
3189 status: Option<SharedString>,
3190 job: F,
3191 ) -> oneshot::Receiver<R>
3192 where
3193 F: FnOnce(RepositoryState, AsyncApp) -> Fut + 'static,
3194 Fut: Future<Output = R> + 'static,
3195 R: Send + 'static,
3196 {
3197 self.send_keyed_job(None, status, job)
3198 }
3199
3200 fn send_keyed_job<F, Fut, R>(
3201 &mut self,
3202 key: Option<GitJobKey>,
3203 status: Option<SharedString>,
3204 job: F,
3205 ) -> oneshot::Receiver<R>
3206 where
3207 F: FnOnce(RepositoryState, AsyncApp) -> Fut + 'static,
3208 Fut: Future<Output = R> + 'static,
3209 R: Send + 'static,
3210 {
3211 let (result_tx, result_rx) = futures::channel::oneshot::channel();
3212 let job_id = post_inc(&mut self.job_id);
3213 let this = self.this.clone();
3214 self.job_sender
3215 .unbounded_send(GitJob {
3216 key,
3217 job: Box::new(move |state, cx: &mut AsyncApp| {
3218 let job = job(state, cx.clone());
3219 cx.spawn(async move |cx| {
3220 if let Some(s) = status.clone() {
3221 this.update(cx, |this, cx| {
3222 this.active_jobs.insert(
3223 job_id,
3224 JobInfo {
3225 start: Instant::now(),
3226 message: s.clone(),
3227 },
3228 );
3229
3230 cx.notify();
3231 })
3232 .ok();
3233 }
3234 let result = job.await;
3235
3236 this.update(cx, |this, cx| {
3237 this.active_jobs.remove(&job_id);
3238 cx.notify();
3239 })
3240 .ok();
3241
3242 result_tx.send(result).ok();
3243 })
3244 }),
3245 })
3246 .ok();
3247 result_rx
3248 }
3249
3250 pub fn set_as_active_repository(&self, cx: &mut Context<Self>) {
3251 let Some(git_store) = self.git_store.upgrade() else {
3252 return;
3253 };
3254 let entity = cx.entity();
3255 git_store.update(cx, |git_store, cx| {
3256 let Some((&id, _)) = git_store
3257 .repositories
3258 .iter()
3259 .find(|(_, handle)| *handle == &entity)
3260 else {
3261 return;
3262 };
3263 git_store.active_repo_id = Some(id);
3264 cx.emit(GitStoreEvent::ActiveRepositoryChanged(Some(id)));
3265 });
3266 }
3267
3268 pub fn cached_status(&self) -> impl '_ + Iterator<Item = StatusEntry> {
3269 self.snapshot.status()
3270 }
3271
3272 pub fn repo_path_to_project_path(&self, path: &RepoPath, cx: &App) -> Option<ProjectPath> {
3273 let git_store = self.git_store.upgrade()?;
3274 let worktree_store = git_store.read(cx).worktree_store.read(cx);
3275 let abs_path = self.snapshot.work_directory_abs_path.join(&path.0);
3276 let (worktree, relative_path) = worktree_store.find_worktree(abs_path, cx)?;
3277 Some(ProjectPath {
3278 worktree_id: worktree.read(cx).id(),
3279 path: relative_path.into(),
3280 })
3281 }
3282
3283 pub fn project_path_to_repo_path(&self, path: &ProjectPath, cx: &App) -> Option<RepoPath> {
3284 let git_store = self.git_store.upgrade()?;
3285 let worktree_store = git_store.read(cx).worktree_store.read(cx);
3286 let abs_path = worktree_store.absolutize(path, cx)?;
3287 self.snapshot.abs_path_to_repo_path(&abs_path)
3288 }
3289
3290 pub fn contains_sub_repo(&self, other: &Entity<Self>, cx: &App) -> bool {
3291 other
3292 .read(cx)
3293 .snapshot
3294 .work_directory_abs_path
3295 .starts_with(&self.snapshot.work_directory_abs_path)
3296 }
3297
3298 pub fn open_commit_buffer(
3299 &mut self,
3300 languages: Option<Arc<LanguageRegistry>>,
3301 buffer_store: Entity<BufferStore>,
3302 cx: &mut Context<Self>,
3303 ) -> Task<Result<Entity<Buffer>>> {
3304 let id = self.id;
3305 if let Some(buffer) = self.commit_message_buffer.clone() {
3306 return Task::ready(Ok(buffer));
3307 }
3308 let this = cx.weak_entity();
3309
3310 let rx = self.send_job(None, move |state, mut cx| async move {
3311 let Some(this) = this.upgrade() else {
3312 bail!("git store was dropped");
3313 };
3314 match state {
3315 RepositoryState::Local { .. } => {
3316 this.update(&mut cx, |_, cx| {
3317 Self::open_local_commit_buffer(languages, buffer_store, cx)
3318 })?
3319 .await
3320 }
3321 RepositoryState::Remote { project_id, client } => {
3322 let request = client.request(proto::OpenCommitMessageBuffer {
3323 project_id: project_id.0,
3324 repository_id: id.to_proto(),
3325 });
3326 let response = request.await.context("requesting to open commit buffer")?;
3327 let buffer_id = BufferId::new(response.buffer_id)?;
3328 let buffer = buffer_store
3329 .update(&mut cx, |buffer_store, cx| {
3330 buffer_store.wait_for_remote_buffer(buffer_id, cx)
3331 })?
3332 .await?;
3333 if let Some(language_registry) = languages {
3334 let git_commit_language =
3335 language_registry.language_for_name("Git Commit").await?;
3336 buffer.update(&mut cx, |buffer, cx| {
3337 buffer.set_language(Some(git_commit_language), cx);
3338 })?;
3339 }
3340 this.update(&mut cx, |this, _| {
3341 this.commit_message_buffer = Some(buffer.clone());
3342 })?;
3343 Ok(buffer)
3344 }
3345 }
3346 });
3347
3348 cx.spawn(|_, _: &mut AsyncApp| async move { rx.await? })
3349 }
3350
3351 fn open_local_commit_buffer(
3352 language_registry: Option<Arc<LanguageRegistry>>,
3353 buffer_store: Entity<BufferStore>,
3354 cx: &mut Context<Self>,
3355 ) -> Task<Result<Entity<Buffer>>> {
3356 cx.spawn(async move |repository, cx| {
3357 let buffer = buffer_store
3358 .update(cx, |buffer_store, cx| buffer_store.create_buffer(cx))?
3359 .await?;
3360
3361 if let Some(language_registry) = language_registry {
3362 let git_commit_language = language_registry.language_for_name("Git Commit").await?;
3363 buffer.update(cx, |buffer, cx| {
3364 buffer.set_language(Some(git_commit_language), cx);
3365 })?;
3366 }
3367
3368 repository.update(cx, |repository, _| {
3369 repository.commit_message_buffer = Some(buffer.clone());
3370 })?;
3371 Ok(buffer)
3372 })
3373 }
3374
3375 pub fn checkout_files(
3376 &mut self,
3377 commit: &str,
3378 paths: Vec<RepoPath>,
3379 _cx: &mut App,
3380 ) -> oneshot::Receiver<Result<()>> {
3381 let commit = commit.to_string();
3382 let id = self.id;
3383
3384 self.send_job(
3385 Some(format!("git checkout {}", commit).into()),
3386 move |git_repo, _| async move {
3387 match git_repo {
3388 RepositoryState::Local {
3389 backend,
3390 environment,
3391 ..
3392 } => {
3393 backend
3394 .checkout_files(commit, paths, environment.clone())
3395 .await
3396 }
3397 RepositoryState::Remote { project_id, client } => {
3398 client
3399 .request(proto::GitCheckoutFiles {
3400 project_id: project_id.0,
3401 repository_id: id.to_proto(),
3402 commit,
3403 paths: paths
3404 .into_iter()
3405 .map(|p| p.to_string_lossy().to_string())
3406 .collect(),
3407 })
3408 .await?;
3409
3410 Ok(())
3411 }
3412 }
3413 },
3414 )
3415 }
3416
3417 pub fn reset(
3418 &mut self,
3419 commit: String,
3420 reset_mode: ResetMode,
3421 _cx: &mut App,
3422 ) -> oneshot::Receiver<Result<()>> {
3423 let commit = commit.to_string();
3424 let id = self.id;
3425
3426 self.send_job(None, move |git_repo, _| async move {
3427 match git_repo {
3428 RepositoryState::Local {
3429 backend,
3430 environment,
3431 ..
3432 } => backend.reset(commit, reset_mode, environment).await,
3433 RepositoryState::Remote { project_id, client } => {
3434 client
3435 .request(proto::GitReset {
3436 project_id: project_id.0,
3437 repository_id: id.to_proto(),
3438 commit,
3439 mode: match reset_mode {
3440 ResetMode::Soft => git_reset::ResetMode::Soft.into(),
3441 ResetMode::Mixed => git_reset::ResetMode::Mixed.into(),
3442 },
3443 })
3444 .await?;
3445
3446 Ok(())
3447 }
3448 }
3449 })
3450 }
3451
3452 pub fn show(&mut self, commit: String) -> oneshot::Receiver<Result<CommitDetails>> {
3453 let id = self.id;
3454 self.send_job(None, move |git_repo, _cx| async move {
3455 match git_repo {
3456 RepositoryState::Local { backend, .. } => backend.show(commit).await,
3457 RepositoryState::Remote { project_id, client } => {
3458 let resp = client
3459 .request(proto::GitShow {
3460 project_id: project_id.0,
3461 repository_id: id.to_proto(),
3462 commit,
3463 })
3464 .await?;
3465
3466 Ok(CommitDetails {
3467 sha: resp.sha.into(),
3468 message: resp.message.into(),
3469 commit_timestamp: resp.commit_timestamp,
3470 author_email: resp.author_email.into(),
3471 author_name: resp.author_name.into(),
3472 })
3473 }
3474 }
3475 })
3476 }
3477
3478 pub fn load_commit_diff(&mut self, commit: String) -> oneshot::Receiver<Result<CommitDiff>> {
3479 let id = self.id;
3480 self.send_job(None, move |git_repo, cx| async move {
3481 match git_repo {
3482 RepositoryState::Local { backend, .. } => backend.load_commit(commit, cx).await,
3483 RepositoryState::Remote {
3484 client, project_id, ..
3485 } => {
3486 let response = client
3487 .request(proto::LoadCommitDiff {
3488 project_id: project_id.0,
3489 repository_id: id.to_proto(),
3490 commit,
3491 })
3492 .await?;
3493 Ok(CommitDiff {
3494 files: response
3495 .files
3496 .into_iter()
3497 .map(|file| CommitFile {
3498 path: Path::new(&file.path).into(),
3499 old_text: file.old_text,
3500 new_text: file.new_text,
3501 })
3502 .collect(),
3503 })
3504 }
3505 }
3506 })
3507 }
3508
3509 fn buffer_store(&self, cx: &App) -> Option<Entity<BufferStore>> {
3510 Some(self.git_store.upgrade()?.read(cx).buffer_store.clone())
3511 }
3512
3513 pub fn stage_entries(
3514 &self,
3515 entries: Vec<RepoPath>,
3516 cx: &mut Context<Self>,
3517 ) -> Task<anyhow::Result<()>> {
3518 if entries.is_empty() {
3519 return Task::ready(Ok(()));
3520 }
3521 let id = self.id;
3522
3523 let mut save_futures = Vec::new();
3524 if let Some(buffer_store) = self.buffer_store(cx) {
3525 buffer_store.update(cx, |buffer_store, cx| {
3526 for path in &entries {
3527 let Some(project_path) = self.repo_path_to_project_path(path, cx) else {
3528 continue;
3529 };
3530 if let Some(buffer) = buffer_store.get_by_path(&project_path) {
3531 if buffer
3532 .read(cx)
3533 .file()
3534 .map_or(false, |file| file.disk_state().exists())
3535 {
3536 save_futures.push(buffer_store.save_buffer(buffer, cx));
3537 }
3538 }
3539 }
3540 })
3541 }
3542
3543 cx.spawn(async move |this, cx| {
3544 for save_future in save_futures {
3545 save_future.await?;
3546 }
3547
3548 this.update(cx, |this, _| {
3549 this.send_job(None, move |git_repo, _cx| async move {
3550 match git_repo {
3551 RepositoryState::Local {
3552 backend,
3553 environment,
3554 ..
3555 } => backend.stage_paths(entries, environment.clone()).await,
3556 RepositoryState::Remote { project_id, client } => {
3557 client
3558 .request(proto::Stage {
3559 project_id: project_id.0,
3560 repository_id: id.to_proto(),
3561 paths: entries
3562 .into_iter()
3563 .map(|repo_path| repo_path.as_ref().to_proto())
3564 .collect(),
3565 })
3566 .await
3567 .context("sending stage request")?;
3568
3569 Ok(())
3570 }
3571 }
3572 })
3573 })?
3574 .await??;
3575
3576 Ok(())
3577 })
3578 }
3579
3580 pub fn unstage_entries(
3581 &self,
3582 entries: Vec<RepoPath>,
3583 cx: &mut Context<Self>,
3584 ) -> Task<anyhow::Result<()>> {
3585 if entries.is_empty() {
3586 return Task::ready(Ok(()));
3587 }
3588 let id = self.id;
3589
3590 let mut save_futures = Vec::new();
3591 if let Some(buffer_store) = self.buffer_store(cx) {
3592 buffer_store.update(cx, |buffer_store, cx| {
3593 for path in &entries {
3594 let Some(project_path) = self.repo_path_to_project_path(path, cx) else {
3595 continue;
3596 };
3597 if let Some(buffer) = buffer_store.get_by_path(&project_path) {
3598 if buffer
3599 .read(cx)
3600 .file()
3601 .map_or(false, |file| file.disk_state().exists())
3602 {
3603 save_futures.push(buffer_store.save_buffer(buffer, cx));
3604 }
3605 }
3606 }
3607 })
3608 }
3609
3610 cx.spawn(async move |this, cx| {
3611 for save_future in save_futures {
3612 save_future.await?;
3613 }
3614
3615 this.update(cx, |this, _| {
3616 this.send_job(None, move |git_repo, _cx| async move {
3617 match git_repo {
3618 RepositoryState::Local {
3619 backend,
3620 environment,
3621 ..
3622 } => backend.unstage_paths(entries, environment).await,
3623 RepositoryState::Remote { project_id, client } => {
3624 client
3625 .request(proto::Unstage {
3626 project_id: project_id.0,
3627 repository_id: id.to_proto(),
3628 paths: entries
3629 .into_iter()
3630 .map(|repo_path| repo_path.as_ref().to_proto())
3631 .collect(),
3632 })
3633 .await
3634 .context("sending unstage request")?;
3635
3636 Ok(())
3637 }
3638 }
3639 })
3640 })?
3641 .await??;
3642
3643 Ok(())
3644 })
3645 }
3646
3647 pub fn stage_all(&self, cx: &mut Context<Self>) -> Task<anyhow::Result<()>> {
3648 let to_stage = self
3649 .cached_status()
3650 .filter(|entry| !entry.status.staging().is_fully_staged())
3651 .map(|entry| entry.repo_path.clone())
3652 .collect();
3653 self.stage_entries(to_stage, cx)
3654 }
3655
3656 pub fn unstage_all(&self, cx: &mut Context<Self>) -> Task<anyhow::Result<()>> {
3657 let to_unstage = self
3658 .cached_status()
3659 .filter(|entry| entry.status.staging().has_staged())
3660 .map(|entry| entry.repo_path.clone())
3661 .collect();
3662 self.unstage_entries(to_unstage, cx)
3663 }
3664
3665 pub fn stash_all(&mut self, cx: &mut Context<Self>) -> Task<anyhow::Result<()>> {
3666 let to_stash = self
3667 .cached_status()
3668 .map(|entry| entry.repo_path.clone())
3669 .collect();
3670
3671 self.stash_entries(to_stash, cx)
3672 }
3673
3674 pub fn stash_entries(
3675 &mut self,
3676 entries: Vec<RepoPath>,
3677 cx: &mut Context<Self>,
3678 ) -> Task<anyhow::Result<()>> {
3679 let id = self.id;
3680
3681 cx.spawn(async move |this, cx| {
3682 this.update(cx, |this, _| {
3683 this.send_job(None, move |git_repo, _cx| async move {
3684 match git_repo {
3685 RepositoryState::Local {
3686 backend,
3687 environment,
3688 ..
3689 } => backend.stash_paths(entries, environment).await,
3690 RepositoryState::Remote { project_id, client } => {
3691 client
3692 .request(proto::Stash {
3693 project_id: project_id.0,
3694 repository_id: id.to_proto(),
3695 paths: entries
3696 .into_iter()
3697 .map(|repo_path| repo_path.as_ref().to_proto())
3698 .collect(),
3699 })
3700 .await
3701 .context("sending stash request")?;
3702 Ok(())
3703 }
3704 }
3705 })
3706 })?
3707 .await??;
3708 Ok(())
3709 })
3710 }
3711
3712 pub fn stash_pop(&mut self, cx: &mut Context<Self>) -> Task<anyhow::Result<()>> {
3713 let id = self.id;
3714 cx.spawn(async move |this, cx| {
3715 this.update(cx, |this, _| {
3716 this.send_job(None, move |git_repo, _cx| async move {
3717 match git_repo {
3718 RepositoryState::Local {
3719 backend,
3720 environment,
3721 ..
3722 } => backend.stash_pop(environment).await,
3723 RepositoryState::Remote { project_id, client } => {
3724 client
3725 .request(proto::StashPop {
3726 project_id: project_id.0,
3727 repository_id: id.to_proto(),
3728 })
3729 .await
3730 .context("sending stash pop request")?;
3731 Ok(())
3732 }
3733 }
3734 })
3735 })?
3736 .await??;
3737 Ok(())
3738 })
3739 }
3740
3741 pub fn commit(
3742 &mut self,
3743 message: SharedString,
3744 name_and_email: Option<(SharedString, SharedString)>,
3745 options: CommitOptions,
3746 _cx: &mut App,
3747 ) -> oneshot::Receiver<Result<()>> {
3748 let id = self.id;
3749
3750 self.send_job(Some("git commit".into()), move |git_repo, _cx| async move {
3751 match git_repo {
3752 RepositoryState::Local {
3753 backend,
3754 environment,
3755 ..
3756 } => {
3757 backend
3758 .commit(message, name_and_email, options, environment)
3759 .await
3760 }
3761 RepositoryState::Remote { project_id, client } => {
3762 let (name, email) = name_and_email.unzip();
3763 client
3764 .request(proto::Commit {
3765 project_id: project_id.0,
3766 repository_id: id.to_proto(),
3767 message: String::from(message),
3768 name: name.map(String::from),
3769 email: email.map(String::from),
3770 options: Some(proto::commit::CommitOptions {
3771 amend: options.amend,
3772 signoff: options.signoff,
3773 }),
3774 })
3775 .await
3776 .context("sending commit request")?;
3777
3778 Ok(())
3779 }
3780 }
3781 })
3782 }
3783
3784 pub fn fetch(
3785 &mut self,
3786 fetch_options: FetchOptions,
3787 askpass: AskPassDelegate,
3788 _cx: &mut App,
3789 ) -> oneshot::Receiver<Result<RemoteCommandOutput>> {
3790 let askpass_delegates = self.askpass_delegates.clone();
3791 let askpass_id = util::post_inc(&mut self.latest_askpass_id);
3792 let id = self.id;
3793
3794 self.send_job(Some("git fetch".into()), move |git_repo, cx| async move {
3795 match git_repo {
3796 RepositoryState::Local {
3797 backend,
3798 environment,
3799 ..
3800 } => backend.fetch(fetch_options, askpass, environment, cx).await,
3801 RepositoryState::Remote { project_id, client } => {
3802 askpass_delegates.lock().insert(askpass_id, askpass);
3803 let _defer = util::defer(|| {
3804 let askpass_delegate = askpass_delegates.lock().remove(&askpass_id);
3805 debug_assert!(askpass_delegate.is_some());
3806 });
3807
3808 let response = client
3809 .request(proto::Fetch {
3810 project_id: project_id.0,
3811 repository_id: id.to_proto(),
3812 askpass_id,
3813 remote: fetch_options.to_proto(),
3814 })
3815 .await
3816 .context("sending fetch request")?;
3817
3818 Ok(RemoteCommandOutput {
3819 stdout: response.stdout,
3820 stderr: response.stderr,
3821 })
3822 }
3823 }
3824 })
3825 }
3826
3827 pub fn push(
3828 &mut self,
3829 branch: SharedString,
3830 remote: SharedString,
3831 options: Option<PushOptions>,
3832 askpass: AskPassDelegate,
3833 cx: &mut Context<Self>,
3834 ) -> oneshot::Receiver<Result<RemoteCommandOutput>> {
3835 let askpass_delegates = self.askpass_delegates.clone();
3836 let askpass_id = util::post_inc(&mut self.latest_askpass_id);
3837 let id = self.id;
3838
3839 let args = options
3840 .map(|option| match option {
3841 PushOptions::SetUpstream => " --set-upstream",
3842 PushOptions::Force => " --force-with-lease",
3843 })
3844 .unwrap_or("");
3845
3846 let updates_tx = self
3847 .git_store()
3848 .and_then(|git_store| match &git_store.read(cx).state {
3849 GitStoreState::Local { downstream, .. } => downstream
3850 .as_ref()
3851 .map(|downstream| downstream.updates_tx.clone()),
3852 _ => None,
3853 });
3854
3855 let this = cx.weak_entity();
3856 self.send_job(
3857 Some(format!("git push {} {} {}", args, branch, remote).into()),
3858 move |git_repo, mut cx| async move {
3859 match git_repo {
3860 RepositoryState::Local {
3861 backend,
3862 environment,
3863 ..
3864 } => {
3865 let result = backend
3866 .push(
3867 branch.to_string(),
3868 remote.to_string(),
3869 options,
3870 askpass,
3871 environment.clone(),
3872 cx.clone(),
3873 )
3874 .await;
3875 if result.is_ok() {
3876 let branches = backend.branches().await?;
3877 let branch = branches.into_iter().find(|branch| branch.is_head);
3878 log::info!("head branch after scan is {branch:?}");
3879 let snapshot = this.update(&mut cx, |this, cx| {
3880 this.snapshot.branch = branch;
3881 let snapshot = this.snapshot.clone();
3882 cx.emit(RepositoryEvent::Updated {
3883 full_scan: false,
3884 new_instance: false,
3885 });
3886 snapshot
3887 })?;
3888 if let Some(updates_tx) = updates_tx {
3889 updates_tx
3890 .unbounded_send(DownstreamUpdate::UpdateRepository(snapshot))
3891 .ok();
3892 }
3893 }
3894 result
3895 }
3896 RepositoryState::Remote { project_id, client } => {
3897 askpass_delegates.lock().insert(askpass_id, askpass);
3898 let _defer = util::defer(|| {
3899 let askpass_delegate = askpass_delegates.lock().remove(&askpass_id);
3900 debug_assert!(askpass_delegate.is_some());
3901 });
3902 let response = client
3903 .request(proto::Push {
3904 project_id: project_id.0,
3905 repository_id: id.to_proto(),
3906 askpass_id,
3907 branch_name: branch.to_string(),
3908 remote_name: remote.to_string(),
3909 options: options.map(|options| match options {
3910 PushOptions::Force => proto::push::PushOptions::Force,
3911 PushOptions::SetUpstream => {
3912 proto::push::PushOptions::SetUpstream
3913 }
3914 }
3915 as i32),
3916 })
3917 .await
3918 .context("sending push request")?;
3919
3920 Ok(RemoteCommandOutput {
3921 stdout: response.stdout,
3922 stderr: response.stderr,
3923 })
3924 }
3925 }
3926 },
3927 )
3928 }
3929
3930 pub fn pull(
3931 &mut self,
3932 branch: SharedString,
3933 remote: SharedString,
3934 askpass: AskPassDelegate,
3935 _cx: &mut App,
3936 ) -> oneshot::Receiver<Result<RemoteCommandOutput>> {
3937 let askpass_delegates = self.askpass_delegates.clone();
3938 let askpass_id = util::post_inc(&mut self.latest_askpass_id);
3939 let id = self.id;
3940
3941 self.send_job(
3942 Some(format!("git pull {} {}", remote, branch).into()),
3943 move |git_repo, cx| async move {
3944 match git_repo {
3945 RepositoryState::Local {
3946 backend,
3947 environment,
3948 ..
3949 } => {
3950 backend
3951 .pull(
3952 branch.to_string(),
3953 remote.to_string(),
3954 askpass,
3955 environment.clone(),
3956 cx,
3957 )
3958 .await
3959 }
3960 RepositoryState::Remote { project_id, client } => {
3961 askpass_delegates.lock().insert(askpass_id, askpass);
3962 let _defer = util::defer(|| {
3963 let askpass_delegate = askpass_delegates.lock().remove(&askpass_id);
3964 debug_assert!(askpass_delegate.is_some());
3965 });
3966 let response = client
3967 .request(proto::Pull {
3968 project_id: project_id.0,
3969 repository_id: id.to_proto(),
3970 askpass_id,
3971 branch_name: branch.to_string(),
3972 remote_name: remote.to_string(),
3973 })
3974 .await
3975 .context("sending pull request")?;
3976
3977 Ok(RemoteCommandOutput {
3978 stdout: response.stdout,
3979 stderr: response.stderr,
3980 })
3981 }
3982 }
3983 },
3984 )
3985 }
3986
3987 fn spawn_set_index_text_job(
3988 &mut self,
3989 path: RepoPath,
3990 content: Option<String>,
3991 hunk_staging_operation_count: Option<usize>,
3992 cx: &mut Context<Self>,
3993 ) -> oneshot::Receiver<anyhow::Result<()>> {
3994 let id = self.id;
3995 let this = cx.weak_entity();
3996 let git_store = self.git_store.clone();
3997 self.send_keyed_job(
3998 Some(GitJobKey::WriteIndex(path.clone())),
3999 None,
4000 move |git_repo, mut cx| async move {
4001 log::debug!("start updating index text for buffer {}", path.display());
4002 match git_repo {
4003 RepositoryState::Local {
4004 backend,
4005 environment,
4006 ..
4007 } => {
4008 backend
4009 .set_index_text(path.clone(), content, environment.clone())
4010 .await?;
4011 }
4012 RepositoryState::Remote { project_id, client } => {
4013 client
4014 .request(proto::SetIndexText {
4015 project_id: project_id.0,
4016 repository_id: id.to_proto(),
4017 path: path.as_ref().to_proto(),
4018 text: content,
4019 })
4020 .await?;
4021 }
4022 }
4023 log::debug!("finish updating index text for buffer {}", path.display());
4024
4025 if let Some(hunk_staging_operation_count) = hunk_staging_operation_count {
4026 let project_path = this
4027 .read_with(&cx, |this, cx| this.repo_path_to_project_path(&path, cx))
4028 .ok()
4029 .flatten();
4030 git_store.update(&mut cx, |git_store, cx| {
4031 let buffer_id = git_store
4032 .buffer_store
4033 .read(cx)
4034 .get_by_path(&project_path?)?
4035 .read(cx)
4036 .remote_id();
4037 let diff_state = git_store.diffs.get(&buffer_id)?;
4038 diff_state.update(cx, |diff_state, _| {
4039 diff_state.hunk_staging_operation_count_as_of_write =
4040 hunk_staging_operation_count;
4041 });
4042 Some(())
4043 })?;
4044 }
4045 Ok(())
4046 },
4047 )
4048 }
4049
4050 pub fn get_remotes(
4051 &mut self,
4052 branch_name: Option<String>,
4053 ) -> oneshot::Receiver<Result<Vec<Remote>>> {
4054 let id = self.id;
4055 self.send_job(None, move |repo, _cx| async move {
4056 match repo {
4057 RepositoryState::Local { backend, .. } => backend.get_remotes(branch_name).await,
4058 RepositoryState::Remote { project_id, client } => {
4059 let response = client
4060 .request(proto::GetRemotes {
4061 project_id: project_id.0,
4062 repository_id: id.to_proto(),
4063 branch_name,
4064 })
4065 .await?;
4066
4067 let remotes = response
4068 .remotes
4069 .into_iter()
4070 .map(|remotes| git::repository::Remote {
4071 name: remotes.name.into(),
4072 })
4073 .collect();
4074
4075 Ok(remotes)
4076 }
4077 }
4078 })
4079 }
4080
4081 pub fn branches(&mut self) -> oneshot::Receiver<Result<Vec<Branch>>> {
4082 let id = self.id;
4083 self.send_job(None, move |repo, _| async move {
4084 match repo {
4085 RepositoryState::Local { backend, .. } => backend.branches().await,
4086 RepositoryState::Remote { project_id, client } => {
4087 let response = client
4088 .request(proto::GitGetBranches {
4089 project_id: project_id.0,
4090 repository_id: id.to_proto(),
4091 })
4092 .await?;
4093
4094 let branches = response
4095 .branches
4096 .into_iter()
4097 .map(|branch| proto_to_branch(&branch))
4098 .collect();
4099
4100 Ok(branches)
4101 }
4102 }
4103 })
4104 }
4105
4106 pub fn default_branch(&mut self) -> oneshot::Receiver<Result<Option<SharedString>>> {
4107 let id = self.id;
4108 self.send_job(None, move |repo, _| async move {
4109 match repo {
4110 RepositoryState::Local { backend, .. } => backend.default_branch().await,
4111 RepositoryState::Remote { project_id, client } => {
4112 let response = client
4113 .request(proto::GetDefaultBranch {
4114 project_id: project_id.0,
4115 repository_id: id.to_proto(),
4116 })
4117 .await?;
4118
4119 anyhow::Ok(response.branch.map(SharedString::from))
4120 }
4121 }
4122 })
4123 }
4124
4125 pub fn diff(&mut self, diff_type: DiffType, _cx: &App) -> oneshot::Receiver<Result<String>> {
4126 let id = self.id;
4127 self.send_job(None, move |repo, _cx| async move {
4128 match repo {
4129 RepositoryState::Local { backend, .. } => backend.diff(diff_type).await,
4130 RepositoryState::Remote { project_id, client } => {
4131 let response = client
4132 .request(proto::GitDiff {
4133 project_id: project_id.0,
4134 repository_id: id.to_proto(),
4135 diff_type: match diff_type {
4136 DiffType::HeadToIndex => {
4137 proto::git_diff::DiffType::HeadToIndex.into()
4138 }
4139 DiffType::HeadToWorktree => {
4140 proto::git_diff::DiffType::HeadToWorktree.into()
4141 }
4142 },
4143 })
4144 .await?;
4145
4146 Ok(response.diff)
4147 }
4148 }
4149 })
4150 }
4151
4152 pub fn create_branch(&mut self, branch_name: String) -> oneshot::Receiver<Result<()>> {
4153 let id = self.id;
4154 self.send_job(
4155 Some(format!("git switch -c {branch_name}").into()),
4156 move |repo, _cx| async move {
4157 match repo {
4158 RepositoryState::Local { backend, .. } => {
4159 backend.create_branch(branch_name).await
4160 }
4161 RepositoryState::Remote { project_id, client } => {
4162 client
4163 .request(proto::GitCreateBranch {
4164 project_id: project_id.0,
4165 repository_id: id.to_proto(),
4166 branch_name,
4167 })
4168 .await?;
4169
4170 Ok(())
4171 }
4172 }
4173 },
4174 )
4175 }
4176
4177 pub fn change_branch(&mut self, branch_name: String) -> oneshot::Receiver<Result<()>> {
4178 let id = self.id;
4179 self.send_job(
4180 Some(format!("git switch {branch_name}").into()),
4181 move |repo, _cx| async move {
4182 match repo {
4183 RepositoryState::Local { backend, .. } => {
4184 backend.change_branch(branch_name).await
4185 }
4186 RepositoryState::Remote { project_id, client } => {
4187 client
4188 .request(proto::GitChangeBranch {
4189 project_id: project_id.0,
4190 repository_id: id.to_proto(),
4191 branch_name,
4192 })
4193 .await?;
4194
4195 Ok(())
4196 }
4197 }
4198 },
4199 )
4200 }
4201
4202 pub fn check_for_pushed_commits(&mut self) -> oneshot::Receiver<Result<Vec<SharedString>>> {
4203 let id = self.id;
4204 self.send_job(None, move |repo, _cx| async move {
4205 match repo {
4206 RepositoryState::Local { backend, .. } => backend.check_for_pushed_commit().await,
4207 RepositoryState::Remote { project_id, client } => {
4208 let response = client
4209 .request(proto::CheckForPushedCommits {
4210 project_id: project_id.0,
4211 repository_id: id.to_proto(),
4212 })
4213 .await?;
4214
4215 let branches = response.pushed_to.into_iter().map(Into::into).collect();
4216
4217 Ok(branches)
4218 }
4219 }
4220 })
4221 }
4222
4223 pub fn checkpoint(&mut self) -> oneshot::Receiver<Result<GitRepositoryCheckpoint>> {
4224 self.send_job(None, |repo, _cx| async move {
4225 match repo {
4226 RepositoryState::Local { backend, .. } => backend.checkpoint().await,
4227 RepositoryState::Remote { .. } => anyhow::bail!("not implemented yet"),
4228 }
4229 })
4230 }
4231
4232 pub fn restore_checkpoint(
4233 &mut self,
4234 checkpoint: GitRepositoryCheckpoint,
4235 ) -> oneshot::Receiver<Result<()>> {
4236 self.send_job(None, move |repo, _cx| async move {
4237 match repo {
4238 RepositoryState::Local { backend, .. } => {
4239 backend.restore_checkpoint(checkpoint).await
4240 }
4241 RepositoryState::Remote { .. } => anyhow::bail!("not implemented yet"),
4242 }
4243 })
4244 }
4245
4246 pub(crate) fn apply_remote_update(
4247 &mut self,
4248 update: proto::UpdateRepository,
4249 is_new: bool,
4250 cx: &mut Context<Self>,
4251 ) -> Result<()> {
4252 let conflicted_paths = TreeSet::from_ordered_entries(
4253 update
4254 .current_merge_conflicts
4255 .into_iter()
4256 .map(|path| RepoPath(Path::new(&path).into())),
4257 );
4258 self.snapshot.branch = update.branch_summary.as_ref().map(proto_to_branch);
4259 self.snapshot.head_commit = update
4260 .head_commit_details
4261 .as_ref()
4262 .map(proto_to_commit_details);
4263
4264 self.snapshot.merge.conflicted_paths = conflicted_paths;
4265
4266 let edits = update
4267 .removed_statuses
4268 .into_iter()
4269 .map(|path| sum_tree::Edit::Remove(PathKey(FromProto::from_proto(path))))
4270 .chain(
4271 update
4272 .updated_statuses
4273 .into_iter()
4274 .filter_map(|updated_status| {
4275 Some(sum_tree::Edit::Insert(updated_status.try_into().log_err()?))
4276 }),
4277 )
4278 .collect::<Vec<_>>();
4279 self.snapshot.statuses_by_path.edit(edits, &());
4280 if update.is_last_update {
4281 self.snapshot.scan_id = update.scan_id;
4282 }
4283 cx.emit(RepositoryEvent::Updated {
4284 full_scan: true,
4285 new_instance: is_new,
4286 });
4287 Ok(())
4288 }
4289
4290 pub fn compare_checkpoints(
4291 &mut self,
4292 left: GitRepositoryCheckpoint,
4293 right: GitRepositoryCheckpoint,
4294 ) -> oneshot::Receiver<Result<bool>> {
4295 self.send_job(None, move |repo, _cx| async move {
4296 match repo {
4297 RepositoryState::Local { backend, .. } => {
4298 backend.compare_checkpoints(left, right).await
4299 }
4300 RepositoryState::Remote { .. } => anyhow::bail!("not implemented yet"),
4301 }
4302 })
4303 }
4304
4305 pub fn diff_checkpoints(
4306 &mut self,
4307 base_checkpoint: GitRepositoryCheckpoint,
4308 target_checkpoint: GitRepositoryCheckpoint,
4309 ) -> oneshot::Receiver<Result<String>> {
4310 self.send_job(None, move |repo, _cx| async move {
4311 match repo {
4312 RepositoryState::Local { backend, .. } => {
4313 backend
4314 .diff_checkpoints(base_checkpoint, target_checkpoint)
4315 .await
4316 }
4317 RepositoryState::Remote { .. } => anyhow::bail!("not implemented yet"),
4318 }
4319 })
4320 }
4321
4322 fn schedule_scan(
4323 &mut self,
4324 updates_tx: Option<mpsc::UnboundedSender<DownstreamUpdate>>,
4325 cx: &mut Context<Self>,
4326 ) {
4327 let this = cx.weak_entity();
4328 let _ = self.send_keyed_job(
4329 Some(GitJobKey::ReloadGitState),
4330 None,
4331 |state, mut cx| async move {
4332 log::debug!("run scheduled git status scan");
4333
4334 let Some(this) = this.upgrade() else {
4335 return Ok(());
4336 };
4337 let RepositoryState::Local { backend, .. } = state else {
4338 bail!("not a local repository")
4339 };
4340 let (snapshot, events) = this
4341 .read_with(&mut cx, |this, _| {
4342 compute_snapshot(
4343 this.id,
4344 this.work_directory_abs_path.clone(),
4345 this.snapshot.clone(),
4346 backend.clone(),
4347 )
4348 })?
4349 .await?;
4350 this.update(&mut cx, |this, cx| {
4351 this.snapshot = snapshot.clone();
4352 for event in events {
4353 cx.emit(event);
4354 }
4355 })?;
4356 if let Some(updates_tx) = updates_tx {
4357 updates_tx
4358 .unbounded_send(DownstreamUpdate::UpdateRepository(snapshot))
4359 .ok();
4360 }
4361 Ok(())
4362 },
4363 );
4364 }
4365
4366 fn spawn_local_git_worker(
4367 work_directory_abs_path: Arc<Path>,
4368 dot_git_abs_path: Arc<Path>,
4369 _repository_dir_abs_path: Arc<Path>,
4370 _common_dir_abs_path: Arc<Path>,
4371 project_environment: WeakEntity<ProjectEnvironment>,
4372 fs: Arc<dyn Fs>,
4373 cx: &mut Context<Self>,
4374 ) -> mpsc::UnboundedSender<GitJob> {
4375 let (job_tx, mut job_rx) = mpsc::unbounded::<GitJob>();
4376
4377 cx.spawn(async move |_, cx| {
4378 let environment = project_environment
4379 .upgrade()
4380 .context("missing project environment")?
4381 .update(cx, |project_environment, cx| {
4382 project_environment.get_directory_environment(work_directory_abs_path.clone(), cx)
4383 })?
4384 .await
4385 .unwrap_or_else(|| {
4386 log::error!("failed to get working directory environment for repository {work_directory_abs_path:?}");
4387 HashMap::default()
4388 });
4389 let backend = cx
4390 .background_spawn(async move {
4391 fs.open_repo(&dot_git_abs_path)
4392 .with_context(|| format!("opening repository at {dot_git_abs_path:?}"))
4393 })
4394 .await?;
4395
4396 if let Some(git_hosting_provider_registry) =
4397 cx.update(|cx| GitHostingProviderRegistry::try_global(cx))?
4398 {
4399 git_hosting_providers::register_additional_providers(
4400 git_hosting_provider_registry,
4401 backend.clone(),
4402 );
4403 }
4404
4405 let state = RepositoryState::Local {
4406 backend,
4407 environment: Arc::new(environment),
4408 };
4409 let mut jobs = VecDeque::new();
4410 loop {
4411 while let Ok(Some(next_job)) = job_rx.try_next() {
4412 jobs.push_back(next_job);
4413 }
4414
4415 if let Some(job) = jobs.pop_front() {
4416 if let Some(current_key) = &job.key {
4417 if jobs
4418 .iter()
4419 .any(|other_job| other_job.key.as_ref() == Some(current_key))
4420 {
4421 continue;
4422 }
4423 }
4424 (job.job)(state.clone(), cx).await;
4425 } else if let Some(job) = job_rx.next().await {
4426 jobs.push_back(job);
4427 } else {
4428 break;
4429 }
4430 }
4431 anyhow::Ok(())
4432 })
4433 .detach_and_log_err(cx);
4434
4435 job_tx
4436 }
4437
4438 fn spawn_remote_git_worker(
4439 project_id: ProjectId,
4440 client: AnyProtoClient,
4441 cx: &mut Context<Self>,
4442 ) -> mpsc::UnboundedSender<GitJob> {
4443 let (job_tx, mut job_rx) = mpsc::unbounded::<GitJob>();
4444
4445 cx.spawn(async move |_, cx| {
4446 let state = RepositoryState::Remote { project_id, client };
4447 let mut jobs = VecDeque::new();
4448 loop {
4449 while let Ok(Some(next_job)) = job_rx.try_next() {
4450 jobs.push_back(next_job);
4451 }
4452
4453 if let Some(job) = jobs.pop_front() {
4454 if let Some(current_key) = &job.key {
4455 if jobs
4456 .iter()
4457 .any(|other_job| other_job.key.as_ref() == Some(current_key))
4458 {
4459 continue;
4460 }
4461 }
4462 (job.job)(state.clone(), cx).await;
4463 } else if let Some(job) = job_rx.next().await {
4464 jobs.push_back(job);
4465 } else {
4466 break;
4467 }
4468 }
4469 anyhow::Ok(())
4470 })
4471 .detach_and_log_err(cx);
4472
4473 job_tx
4474 }
4475
4476 fn load_staged_text(
4477 &mut self,
4478 buffer_id: BufferId,
4479 repo_path: RepoPath,
4480 cx: &App,
4481 ) -> Task<Result<Option<String>>> {
4482 let rx = self.send_job(None, move |state, _| async move {
4483 match state {
4484 RepositoryState::Local { backend, .. } => {
4485 anyhow::Ok(backend.load_index_text(repo_path).await)
4486 }
4487 RepositoryState::Remote { project_id, client } => {
4488 let response = client
4489 .request(proto::OpenUnstagedDiff {
4490 project_id: project_id.to_proto(),
4491 buffer_id: buffer_id.to_proto(),
4492 })
4493 .await?;
4494 Ok(response.staged_text)
4495 }
4496 }
4497 });
4498 cx.spawn(|_: &mut AsyncApp| async move { rx.await? })
4499 }
4500
4501 fn load_committed_text(
4502 &mut self,
4503 buffer_id: BufferId,
4504 repo_path: RepoPath,
4505 cx: &App,
4506 ) -> Task<Result<DiffBasesChange>> {
4507 let rx = self.send_job(None, move |state, _| async move {
4508 match state {
4509 RepositoryState::Local { backend, .. } => {
4510 let committed_text = backend.load_committed_text(repo_path.clone()).await;
4511 let staged_text = backend.load_index_text(repo_path).await;
4512 let diff_bases_change = if committed_text == staged_text {
4513 DiffBasesChange::SetBoth(committed_text)
4514 } else {
4515 DiffBasesChange::SetEach {
4516 index: staged_text,
4517 head: committed_text,
4518 }
4519 };
4520 anyhow::Ok(diff_bases_change)
4521 }
4522 RepositoryState::Remote { project_id, client } => {
4523 use proto::open_uncommitted_diff_response::Mode;
4524
4525 let response = client
4526 .request(proto::OpenUncommittedDiff {
4527 project_id: project_id.to_proto(),
4528 buffer_id: buffer_id.to_proto(),
4529 })
4530 .await?;
4531 let mode = Mode::from_i32(response.mode).context("Invalid mode")?;
4532 let bases = match mode {
4533 Mode::IndexMatchesHead => DiffBasesChange::SetBoth(response.committed_text),
4534 Mode::IndexAndHead => DiffBasesChange::SetEach {
4535 head: response.committed_text,
4536 index: response.staged_text,
4537 },
4538 };
4539 Ok(bases)
4540 }
4541 }
4542 });
4543
4544 cx.spawn(|_: &mut AsyncApp| async move { rx.await? })
4545 }
4546
4547 fn paths_changed(
4548 &mut self,
4549 paths: Vec<RepoPath>,
4550 updates_tx: Option<mpsc::UnboundedSender<DownstreamUpdate>>,
4551 cx: &mut Context<Self>,
4552 ) {
4553 self.paths_needing_status_update.extend(paths);
4554
4555 let this = cx.weak_entity();
4556 let _ = self.send_keyed_job(
4557 Some(GitJobKey::RefreshStatuses),
4558 None,
4559 |state, mut cx| async move {
4560 let (prev_snapshot, mut changed_paths) = this.update(&mut cx, |this, _| {
4561 (
4562 this.snapshot.clone(),
4563 mem::take(&mut this.paths_needing_status_update),
4564 )
4565 })?;
4566 let RepositoryState::Local { backend, .. } = state else {
4567 bail!("not a local repository")
4568 };
4569
4570 let paths = changed_paths.iter().cloned().collect::<Vec<_>>();
4571 let statuses = backend.status(&paths).await?;
4572
4573 let changed_path_statuses = cx
4574 .background_spawn(async move {
4575 let mut changed_path_statuses = Vec::new();
4576 let prev_statuses = prev_snapshot.statuses_by_path.clone();
4577 let mut cursor = prev_statuses.cursor::<PathProgress>(&());
4578
4579 for (repo_path, status) in &*statuses.entries {
4580 changed_paths.remove(repo_path);
4581 if cursor.seek_forward(&PathTarget::Path(repo_path), Bias::Left) {
4582 if cursor.item().is_some_and(|entry| entry.status == *status) {
4583 continue;
4584 }
4585 }
4586
4587 changed_path_statuses.push(Edit::Insert(StatusEntry {
4588 repo_path: repo_path.clone(),
4589 status: *status,
4590 }));
4591 }
4592 let mut cursor = prev_statuses.cursor::<PathProgress>(&());
4593 for path in changed_paths.into_iter() {
4594 if cursor.seek_forward(&PathTarget::Path(&path), Bias::Left) {
4595 changed_path_statuses.push(Edit::Remove(PathKey(path.0)));
4596 }
4597 }
4598 changed_path_statuses
4599 })
4600 .await;
4601
4602 this.update(&mut cx, |this, cx| {
4603 if !changed_path_statuses.is_empty() {
4604 this.snapshot
4605 .statuses_by_path
4606 .edit(changed_path_statuses, &());
4607 this.snapshot.scan_id += 1;
4608 if let Some(updates_tx) = updates_tx {
4609 updates_tx
4610 .unbounded_send(DownstreamUpdate::UpdateRepository(
4611 this.snapshot.clone(),
4612 ))
4613 .ok();
4614 }
4615 }
4616 cx.emit(RepositoryEvent::Updated {
4617 full_scan: false,
4618 new_instance: false,
4619 });
4620 })
4621 },
4622 );
4623 }
4624
4625 /// currently running git command and when it started
4626 pub fn current_job(&self) -> Option<JobInfo> {
4627 self.active_jobs.values().next().cloned()
4628 }
4629
4630 pub fn barrier(&mut self) -> oneshot::Receiver<()> {
4631 self.send_job(None, |_, _| async {})
4632 }
4633}
4634
4635fn get_permalink_in_rust_registry_src(
4636 provider_registry: Arc<GitHostingProviderRegistry>,
4637 path: PathBuf,
4638 selection: Range<u32>,
4639) -> Result<url::Url> {
4640 #[derive(Deserialize)]
4641 struct CargoVcsGit {
4642 sha1: String,
4643 }
4644
4645 #[derive(Deserialize)]
4646 struct CargoVcsInfo {
4647 git: CargoVcsGit,
4648 path_in_vcs: String,
4649 }
4650
4651 #[derive(Deserialize)]
4652 struct CargoPackage {
4653 repository: String,
4654 }
4655
4656 #[derive(Deserialize)]
4657 struct CargoToml {
4658 package: CargoPackage,
4659 }
4660
4661 let Some((dir, cargo_vcs_info_json)) = path.ancestors().skip(1).find_map(|dir| {
4662 let json = std::fs::read_to_string(dir.join(".cargo_vcs_info.json")).ok()?;
4663 Some((dir, json))
4664 }) else {
4665 bail!("No .cargo_vcs_info.json found in parent directories")
4666 };
4667 let cargo_vcs_info = serde_json::from_str::<CargoVcsInfo>(&cargo_vcs_info_json)?;
4668 let cargo_toml = std::fs::read_to_string(dir.join("Cargo.toml"))?;
4669 let manifest = toml::from_str::<CargoToml>(&cargo_toml)?;
4670 let (provider, remote) = parse_git_remote_url(provider_registry, &manifest.package.repository)
4671 .context("parsing package.repository field of manifest")?;
4672 let path = PathBuf::from(cargo_vcs_info.path_in_vcs).join(path.strip_prefix(dir).unwrap());
4673 let permalink = provider.build_permalink(
4674 remote,
4675 BuildPermalinkParams {
4676 sha: &cargo_vcs_info.git.sha1,
4677 path: &path.to_string_lossy(),
4678 selection: Some(selection),
4679 },
4680 );
4681 Ok(permalink)
4682}
4683
4684fn serialize_blame_buffer_response(blame: Option<git::blame::Blame>) -> proto::BlameBufferResponse {
4685 let Some(blame) = blame else {
4686 return proto::BlameBufferResponse {
4687 blame_response: None,
4688 };
4689 };
4690
4691 let entries = blame
4692 .entries
4693 .into_iter()
4694 .map(|entry| proto::BlameEntry {
4695 sha: entry.sha.as_bytes().into(),
4696 start_line: entry.range.start,
4697 end_line: entry.range.end,
4698 original_line_number: entry.original_line_number,
4699 author: entry.author,
4700 author_mail: entry.author_mail,
4701 author_time: entry.author_time,
4702 author_tz: entry.author_tz,
4703 committer: entry.committer_name,
4704 committer_mail: entry.committer_email,
4705 committer_time: entry.committer_time,
4706 committer_tz: entry.committer_tz,
4707 summary: entry.summary,
4708 previous: entry.previous,
4709 filename: entry.filename,
4710 })
4711 .collect::<Vec<_>>();
4712
4713 let messages = blame
4714 .messages
4715 .into_iter()
4716 .map(|(oid, message)| proto::CommitMessage {
4717 oid: oid.as_bytes().into(),
4718 message,
4719 })
4720 .collect::<Vec<_>>();
4721
4722 proto::BlameBufferResponse {
4723 blame_response: Some(proto::blame_buffer_response::BlameResponse {
4724 entries,
4725 messages,
4726 remote_url: blame.remote_url,
4727 }),
4728 }
4729}
4730
4731fn deserialize_blame_buffer_response(
4732 response: proto::BlameBufferResponse,
4733) -> Option<git::blame::Blame> {
4734 let response = response.blame_response?;
4735 let entries = response
4736 .entries
4737 .into_iter()
4738 .filter_map(|entry| {
4739 Some(git::blame::BlameEntry {
4740 sha: git::Oid::from_bytes(&entry.sha).ok()?,
4741 range: entry.start_line..entry.end_line,
4742 original_line_number: entry.original_line_number,
4743 committer_name: entry.committer,
4744 committer_time: entry.committer_time,
4745 committer_tz: entry.committer_tz,
4746 committer_email: entry.committer_mail,
4747 author: entry.author,
4748 author_mail: entry.author_mail,
4749 author_time: entry.author_time,
4750 author_tz: entry.author_tz,
4751 summary: entry.summary,
4752 previous: entry.previous,
4753 filename: entry.filename,
4754 })
4755 })
4756 .collect::<Vec<_>>();
4757
4758 let messages = response
4759 .messages
4760 .into_iter()
4761 .filter_map(|message| Some((git::Oid::from_bytes(&message.oid).ok()?, message.message)))
4762 .collect::<HashMap<_, _>>();
4763
4764 Some(Blame {
4765 entries,
4766 messages,
4767 remote_url: response.remote_url,
4768 })
4769}
4770
4771fn branch_to_proto(branch: &git::repository::Branch) -> proto::Branch {
4772 proto::Branch {
4773 is_head: branch.is_head,
4774 ref_name: branch.ref_name.to_string(),
4775 unix_timestamp: branch
4776 .most_recent_commit
4777 .as_ref()
4778 .map(|commit| commit.commit_timestamp as u64),
4779 upstream: branch.upstream.as_ref().map(|upstream| proto::GitUpstream {
4780 ref_name: upstream.ref_name.to_string(),
4781 tracking: upstream
4782 .tracking
4783 .status()
4784 .map(|upstream| proto::UpstreamTracking {
4785 ahead: upstream.ahead as u64,
4786 behind: upstream.behind as u64,
4787 }),
4788 }),
4789 most_recent_commit: branch
4790 .most_recent_commit
4791 .as_ref()
4792 .map(|commit| proto::CommitSummary {
4793 sha: commit.sha.to_string(),
4794 subject: commit.subject.to_string(),
4795 commit_timestamp: commit.commit_timestamp,
4796 }),
4797 }
4798}
4799
4800fn proto_to_branch(proto: &proto::Branch) -> git::repository::Branch {
4801 git::repository::Branch {
4802 is_head: proto.is_head,
4803 ref_name: proto.ref_name.clone().into(),
4804 upstream: proto
4805 .upstream
4806 .as_ref()
4807 .map(|upstream| git::repository::Upstream {
4808 ref_name: upstream.ref_name.to_string().into(),
4809 tracking: upstream
4810 .tracking
4811 .as_ref()
4812 .map(|tracking| {
4813 git::repository::UpstreamTracking::Tracked(UpstreamTrackingStatus {
4814 ahead: tracking.ahead as u32,
4815 behind: tracking.behind as u32,
4816 })
4817 })
4818 .unwrap_or(git::repository::UpstreamTracking::Gone),
4819 }),
4820 most_recent_commit: proto.most_recent_commit.as_ref().map(|commit| {
4821 git::repository::CommitSummary {
4822 sha: commit.sha.to_string().into(),
4823 subject: commit.subject.to_string().into(),
4824 commit_timestamp: commit.commit_timestamp,
4825 has_parent: true,
4826 }
4827 }),
4828 }
4829}
4830
4831fn commit_details_to_proto(commit: &CommitDetails) -> proto::GitCommitDetails {
4832 proto::GitCommitDetails {
4833 sha: commit.sha.to_string(),
4834 message: commit.message.to_string(),
4835 commit_timestamp: commit.commit_timestamp,
4836 author_email: commit.author_email.to_string(),
4837 author_name: commit.author_name.to_string(),
4838 }
4839}
4840
4841fn proto_to_commit_details(proto: &proto::GitCommitDetails) -> CommitDetails {
4842 CommitDetails {
4843 sha: proto.sha.clone().into(),
4844 message: proto.message.clone().into(),
4845 commit_timestamp: proto.commit_timestamp,
4846 author_email: proto.author_email.clone().into(),
4847 author_name: proto.author_name.clone().into(),
4848 }
4849}
4850
4851async fn compute_snapshot(
4852 id: RepositoryId,
4853 work_directory_abs_path: Arc<Path>,
4854 prev_snapshot: RepositorySnapshot,
4855 backend: Arc<dyn GitRepository>,
4856) -> Result<(RepositorySnapshot, Vec<RepositoryEvent>)> {
4857 let mut events = Vec::new();
4858 let branches = backend.branches().await?;
4859 let branch = branches.into_iter().find(|branch| branch.is_head);
4860 let statuses = backend
4861 .status(std::slice::from_ref(&WORK_DIRECTORY_REPO_PATH))
4862 .await?;
4863 let statuses_by_path = SumTree::from_iter(
4864 statuses
4865 .entries
4866 .iter()
4867 .map(|(repo_path, status)| StatusEntry {
4868 repo_path: repo_path.clone(),
4869 status: *status,
4870 }),
4871 &(),
4872 );
4873 let (merge_details, merge_heads_changed) =
4874 MergeDetails::load(&backend, &statuses_by_path, &prev_snapshot).await?;
4875 log::debug!("new merge details (changed={merge_heads_changed:?}): {merge_details:?}");
4876
4877 if merge_heads_changed
4878 || branch != prev_snapshot.branch
4879 || statuses_by_path != prev_snapshot.statuses_by_path
4880 {
4881 events.push(RepositoryEvent::Updated {
4882 full_scan: true,
4883 new_instance: false,
4884 });
4885 }
4886
4887 // Cache merge conflict paths so they don't change from staging/unstaging,
4888 // until the merge heads change (at commit time, etc.).
4889 if merge_heads_changed {
4890 events.push(RepositoryEvent::MergeHeadsChanged);
4891 }
4892
4893 // Useful when branch is None in detached head state
4894 let head_commit = match backend.head_sha().await {
4895 Some(head_sha) => backend.show(head_sha).await.log_err(),
4896 None => None,
4897 };
4898
4899 // Used by edit prediction data collection
4900 let remote_origin_url = backend.remote_url("origin");
4901 let remote_upstream_url = backend.remote_url("upstream");
4902
4903 let snapshot = RepositorySnapshot {
4904 id,
4905 statuses_by_path,
4906 work_directory_abs_path,
4907 scan_id: prev_snapshot.scan_id + 1,
4908 branch,
4909 head_commit,
4910 merge: merge_details,
4911 remote_origin_url,
4912 remote_upstream_url,
4913 };
4914
4915 Ok((snapshot, events))
4916}
4917
4918fn status_from_proto(
4919 simple_status: i32,
4920 status: Option<proto::GitFileStatus>,
4921) -> anyhow::Result<FileStatus> {
4922 use proto::git_file_status::Variant;
4923
4924 let Some(variant) = status.and_then(|status| status.variant) else {
4925 let code = proto::GitStatus::from_i32(simple_status)
4926 .with_context(|| format!("Invalid git status code: {simple_status}"))?;
4927 let result = match code {
4928 proto::GitStatus::Added => TrackedStatus {
4929 worktree_status: StatusCode::Added,
4930 index_status: StatusCode::Unmodified,
4931 }
4932 .into(),
4933 proto::GitStatus::Modified => TrackedStatus {
4934 worktree_status: StatusCode::Modified,
4935 index_status: StatusCode::Unmodified,
4936 }
4937 .into(),
4938 proto::GitStatus::Conflict => UnmergedStatus {
4939 first_head: UnmergedStatusCode::Updated,
4940 second_head: UnmergedStatusCode::Updated,
4941 }
4942 .into(),
4943 proto::GitStatus::Deleted => TrackedStatus {
4944 worktree_status: StatusCode::Deleted,
4945 index_status: StatusCode::Unmodified,
4946 }
4947 .into(),
4948 _ => anyhow::bail!("Invalid code for simple status: {simple_status}"),
4949 };
4950 return Ok(result);
4951 };
4952
4953 let result = match variant {
4954 Variant::Untracked(_) => FileStatus::Untracked,
4955 Variant::Ignored(_) => FileStatus::Ignored,
4956 Variant::Unmerged(unmerged) => {
4957 let [first_head, second_head] =
4958 [unmerged.first_head, unmerged.second_head].map(|head| {
4959 let code = proto::GitStatus::from_i32(head)
4960 .with_context(|| format!("Invalid git status code: {head}"))?;
4961 let result = match code {
4962 proto::GitStatus::Added => UnmergedStatusCode::Added,
4963 proto::GitStatus::Updated => UnmergedStatusCode::Updated,
4964 proto::GitStatus::Deleted => UnmergedStatusCode::Deleted,
4965 _ => anyhow::bail!("Invalid code for unmerged status: {code:?}"),
4966 };
4967 Ok(result)
4968 });
4969 let [first_head, second_head] = [first_head?, second_head?];
4970 UnmergedStatus {
4971 first_head,
4972 second_head,
4973 }
4974 .into()
4975 }
4976 Variant::Tracked(tracked) => {
4977 let [index_status, worktree_status] = [tracked.index_status, tracked.worktree_status]
4978 .map(|status| {
4979 let code = proto::GitStatus::from_i32(status)
4980 .with_context(|| format!("Invalid git status code: {status}"))?;
4981 let result = match code {
4982 proto::GitStatus::Modified => StatusCode::Modified,
4983 proto::GitStatus::TypeChanged => StatusCode::TypeChanged,
4984 proto::GitStatus::Added => StatusCode::Added,
4985 proto::GitStatus::Deleted => StatusCode::Deleted,
4986 proto::GitStatus::Renamed => StatusCode::Renamed,
4987 proto::GitStatus::Copied => StatusCode::Copied,
4988 proto::GitStatus::Unmodified => StatusCode::Unmodified,
4989 _ => anyhow::bail!("Invalid code for tracked status: {code:?}"),
4990 };
4991 Ok(result)
4992 });
4993 let [index_status, worktree_status] = [index_status?, worktree_status?];
4994 TrackedStatus {
4995 index_status,
4996 worktree_status,
4997 }
4998 .into()
4999 }
5000 };
5001 Ok(result)
5002}
5003
5004fn status_to_proto(status: FileStatus) -> proto::GitFileStatus {
5005 use proto::git_file_status::{Tracked, Unmerged, Variant};
5006
5007 let variant = match status {
5008 FileStatus::Untracked => Variant::Untracked(Default::default()),
5009 FileStatus::Ignored => Variant::Ignored(Default::default()),
5010 FileStatus::Unmerged(UnmergedStatus {
5011 first_head,
5012 second_head,
5013 }) => Variant::Unmerged(Unmerged {
5014 first_head: unmerged_status_to_proto(first_head),
5015 second_head: unmerged_status_to_proto(second_head),
5016 }),
5017 FileStatus::Tracked(TrackedStatus {
5018 index_status,
5019 worktree_status,
5020 }) => Variant::Tracked(Tracked {
5021 index_status: tracked_status_to_proto(index_status),
5022 worktree_status: tracked_status_to_proto(worktree_status),
5023 }),
5024 };
5025 proto::GitFileStatus {
5026 variant: Some(variant),
5027 }
5028}
5029
5030fn unmerged_status_to_proto(code: UnmergedStatusCode) -> i32 {
5031 match code {
5032 UnmergedStatusCode::Added => proto::GitStatus::Added as _,
5033 UnmergedStatusCode::Deleted => proto::GitStatus::Deleted as _,
5034 UnmergedStatusCode::Updated => proto::GitStatus::Updated as _,
5035 }
5036}
5037
5038fn tracked_status_to_proto(code: StatusCode) -> i32 {
5039 match code {
5040 StatusCode::Added => proto::GitStatus::Added as _,
5041 StatusCode::Deleted => proto::GitStatus::Deleted as _,
5042 StatusCode::Modified => proto::GitStatus::Modified as _,
5043 StatusCode::Renamed => proto::GitStatus::Renamed as _,
5044 StatusCode::TypeChanged => proto::GitStatus::TypeChanged as _,
5045 StatusCode::Copied => proto::GitStatus::Copied as _,
5046 StatusCode::Unmodified => proto::GitStatus::Unmodified as _,
5047 }
5048}