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