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