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, new_instance: 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, is_new, 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) {
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) {
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 {
3601 full_scan: false,
3602 new_instance: false,
3603 });
3604 snapshot
3605 })?;
3606 if let Some(updates_tx) = updates_tx {
3607 updates_tx
3608 .unbounded_send(DownstreamUpdate::UpdateRepository(snapshot))
3609 .ok();
3610 }
3611 }
3612 result
3613 }
3614 RepositoryState::Remote { project_id, client } => {
3615 askpass_delegates.lock().insert(askpass_id, askpass);
3616 let _defer = util::defer(|| {
3617 let askpass_delegate = askpass_delegates.lock().remove(&askpass_id);
3618 debug_assert!(askpass_delegate.is_some());
3619 });
3620 let response = client
3621 .request(proto::Push {
3622 project_id: project_id.0,
3623 repository_id: id.to_proto(),
3624 askpass_id,
3625 branch_name: branch.to_string(),
3626 remote_name: remote.to_string(),
3627 options: options.map(|options| match options {
3628 PushOptions::Force => proto::push::PushOptions::Force,
3629 PushOptions::SetUpstream => {
3630 proto::push::PushOptions::SetUpstream
3631 }
3632 }
3633 as i32),
3634 })
3635 .await
3636 .context("sending push request")?;
3637
3638 Ok(RemoteCommandOutput {
3639 stdout: response.stdout,
3640 stderr: response.stderr,
3641 })
3642 }
3643 }
3644 },
3645 )
3646 }
3647
3648 pub fn pull(
3649 &mut self,
3650 branch: SharedString,
3651 remote: SharedString,
3652 askpass: AskPassDelegate,
3653 _cx: &mut App,
3654 ) -> oneshot::Receiver<Result<RemoteCommandOutput>> {
3655 let askpass_delegates = self.askpass_delegates.clone();
3656 let askpass_id = util::post_inc(&mut self.latest_askpass_id);
3657 let id = self.id;
3658
3659 self.send_job(
3660 Some(format!("git pull {} {}", remote, branch).into()),
3661 move |git_repo, cx| async move {
3662 match git_repo {
3663 RepositoryState::Local {
3664 backend,
3665 environment,
3666 ..
3667 } => {
3668 backend
3669 .pull(
3670 branch.to_string(),
3671 remote.to_string(),
3672 askpass,
3673 environment.clone(),
3674 cx,
3675 )
3676 .await
3677 }
3678 RepositoryState::Remote { project_id, client } => {
3679 askpass_delegates.lock().insert(askpass_id, askpass);
3680 let _defer = util::defer(|| {
3681 let askpass_delegate = askpass_delegates.lock().remove(&askpass_id);
3682 debug_assert!(askpass_delegate.is_some());
3683 });
3684 let response = client
3685 .request(proto::Pull {
3686 project_id: project_id.0,
3687 repository_id: id.to_proto(),
3688 askpass_id,
3689 branch_name: branch.to_string(),
3690 remote_name: remote.to_string(),
3691 })
3692 .await
3693 .context("sending pull request")?;
3694
3695 Ok(RemoteCommandOutput {
3696 stdout: response.stdout,
3697 stderr: response.stderr,
3698 })
3699 }
3700 }
3701 },
3702 )
3703 }
3704
3705 fn spawn_set_index_text_job(
3706 &mut self,
3707 path: RepoPath,
3708 content: Option<String>,
3709 hunk_staging_operation_count: Option<usize>,
3710 cx: &mut Context<Self>,
3711 ) -> oneshot::Receiver<anyhow::Result<()>> {
3712 let id = self.id;
3713 let this = cx.weak_entity();
3714 let git_store = self.git_store.clone();
3715 self.send_keyed_job(
3716 Some(GitJobKey::WriteIndex(path.clone())),
3717 None,
3718 move |git_repo, mut cx| async move {
3719 log::debug!("start updating index text for buffer {}", path.display());
3720 match git_repo {
3721 RepositoryState::Local {
3722 backend,
3723 environment,
3724 ..
3725 } => {
3726 backend
3727 .set_index_text(path.clone(), content, environment.clone())
3728 .await?;
3729 }
3730 RepositoryState::Remote { project_id, client } => {
3731 client
3732 .request(proto::SetIndexText {
3733 project_id: project_id.0,
3734 repository_id: id.to_proto(),
3735 path: path.as_ref().to_proto(),
3736 text: content,
3737 })
3738 .await?;
3739 }
3740 }
3741 log::debug!("finish updating index text for buffer {}", path.display());
3742
3743 if let Some(hunk_staging_operation_count) = hunk_staging_operation_count {
3744 let project_path = this
3745 .read_with(&cx, |this, cx| this.repo_path_to_project_path(&path, cx))
3746 .ok()
3747 .flatten();
3748 git_store.update(&mut cx, |git_store, cx| {
3749 let buffer_id = git_store
3750 .buffer_store
3751 .read(cx)
3752 .get_by_path(&project_path?)?
3753 .read(cx)
3754 .remote_id();
3755 let diff_state = git_store.diffs.get(&buffer_id)?;
3756 diff_state.update(cx, |diff_state, _| {
3757 diff_state.hunk_staging_operation_count_as_of_write =
3758 hunk_staging_operation_count;
3759 });
3760 Some(())
3761 })?;
3762 }
3763 Ok(())
3764 },
3765 )
3766 }
3767
3768 pub fn get_remotes(
3769 &mut self,
3770 branch_name: Option<String>,
3771 ) -> oneshot::Receiver<Result<Vec<Remote>>> {
3772 let id = self.id;
3773 self.send_job(None, move |repo, _cx| async move {
3774 match repo {
3775 RepositoryState::Local { backend, .. } => backend.get_remotes(branch_name).await,
3776 RepositoryState::Remote { project_id, client } => {
3777 let response = client
3778 .request(proto::GetRemotes {
3779 project_id: project_id.0,
3780 repository_id: id.to_proto(),
3781 branch_name,
3782 })
3783 .await?;
3784
3785 let remotes = response
3786 .remotes
3787 .into_iter()
3788 .map(|remotes| git::repository::Remote {
3789 name: remotes.name.into(),
3790 })
3791 .collect();
3792
3793 Ok(remotes)
3794 }
3795 }
3796 })
3797 }
3798
3799 pub fn branches(&mut self) -> oneshot::Receiver<Result<Vec<Branch>>> {
3800 let id = self.id;
3801 self.send_job(None, move |repo, _| async move {
3802 match repo {
3803 RepositoryState::Local { backend, .. } => backend.branches().await,
3804 RepositoryState::Remote { project_id, client } => {
3805 let response = client
3806 .request(proto::GitGetBranches {
3807 project_id: project_id.0,
3808 repository_id: id.to_proto(),
3809 })
3810 .await?;
3811
3812 let branches = response
3813 .branches
3814 .into_iter()
3815 .map(|branch| proto_to_branch(&branch))
3816 .collect();
3817
3818 Ok(branches)
3819 }
3820 }
3821 })
3822 }
3823
3824 pub fn diff(&mut self, diff_type: DiffType, _cx: &App) -> oneshot::Receiver<Result<String>> {
3825 let id = self.id;
3826 self.send_job(None, move |repo, _cx| async move {
3827 match repo {
3828 RepositoryState::Local { backend, .. } => backend.diff(diff_type).await,
3829 RepositoryState::Remote { project_id, client } => {
3830 let response = client
3831 .request(proto::GitDiff {
3832 project_id: project_id.0,
3833 repository_id: id.to_proto(),
3834 diff_type: match diff_type {
3835 DiffType::HeadToIndex => {
3836 proto::git_diff::DiffType::HeadToIndex.into()
3837 }
3838 DiffType::HeadToWorktree => {
3839 proto::git_diff::DiffType::HeadToWorktree.into()
3840 }
3841 },
3842 })
3843 .await?;
3844
3845 Ok(response.diff)
3846 }
3847 }
3848 })
3849 }
3850
3851 pub fn create_branch(&mut self, branch_name: String) -> oneshot::Receiver<Result<()>> {
3852 let id = self.id;
3853 self.send_job(
3854 Some(format!("git switch -c {branch_name}").into()),
3855 move |repo, _cx| async move {
3856 match repo {
3857 RepositoryState::Local { backend, .. } => {
3858 backend.create_branch(branch_name).await
3859 }
3860 RepositoryState::Remote { project_id, client } => {
3861 client
3862 .request(proto::GitCreateBranch {
3863 project_id: project_id.0,
3864 repository_id: id.to_proto(),
3865 branch_name,
3866 })
3867 .await?;
3868
3869 Ok(())
3870 }
3871 }
3872 },
3873 )
3874 }
3875
3876 pub fn change_branch(&mut self, branch_name: String) -> oneshot::Receiver<Result<()>> {
3877 let id = self.id;
3878 self.send_job(
3879 Some(format!("git switch {branch_name}").into()),
3880 move |repo, _cx| async move {
3881 match repo {
3882 RepositoryState::Local { backend, .. } => {
3883 backend.change_branch(branch_name).await
3884 }
3885 RepositoryState::Remote { project_id, client } => {
3886 client
3887 .request(proto::GitChangeBranch {
3888 project_id: project_id.0,
3889 repository_id: id.to_proto(),
3890 branch_name,
3891 })
3892 .await?;
3893
3894 Ok(())
3895 }
3896 }
3897 },
3898 )
3899 }
3900
3901 pub fn check_for_pushed_commits(&mut self) -> oneshot::Receiver<Result<Vec<SharedString>>> {
3902 let id = self.id;
3903 self.send_job(None, move |repo, _cx| async move {
3904 match repo {
3905 RepositoryState::Local { backend, .. } => backend.check_for_pushed_commit().await,
3906 RepositoryState::Remote { project_id, client } => {
3907 let response = client
3908 .request(proto::CheckForPushedCommits {
3909 project_id: project_id.0,
3910 repository_id: id.to_proto(),
3911 })
3912 .await?;
3913
3914 let branches = response.pushed_to.into_iter().map(Into::into).collect();
3915
3916 Ok(branches)
3917 }
3918 }
3919 })
3920 }
3921
3922 pub fn checkpoint(&mut self) -> oneshot::Receiver<Result<GitRepositoryCheckpoint>> {
3923 self.send_job(None, |repo, _cx| async move {
3924 match repo {
3925 RepositoryState::Local { backend, .. } => backend.checkpoint().await,
3926 RepositoryState::Remote { .. } => anyhow::bail!("not implemented yet"),
3927 }
3928 })
3929 }
3930
3931 pub fn restore_checkpoint(
3932 &mut self,
3933 checkpoint: GitRepositoryCheckpoint,
3934 ) -> oneshot::Receiver<Result<()>> {
3935 self.send_job(None, move |repo, _cx| async move {
3936 match repo {
3937 RepositoryState::Local { backend, .. } => {
3938 backend.restore_checkpoint(checkpoint).await
3939 }
3940 RepositoryState::Remote { .. } => anyhow::bail!("not implemented yet"),
3941 }
3942 })
3943 }
3944
3945 pub(crate) fn apply_remote_update(
3946 &mut self,
3947 update: proto::UpdateRepository,
3948 is_new: bool,
3949 cx: &mut Context<Self>,
3950 ) -> Result<()> {
3951 let conflicted_paths = TreeSet::from_ordered_entries(
3952 update
3953 .current_merge_conflicts
3954 .into_iter()
3955 .map(|path| RepoPath(Path::new(&path).into())),
3956 );
3957 self.snapshot.branch = update.branch_summary.as_ref().map(proto_to_branch);
3958 self.snapshot.head_commit = update
3959 .head_commit_details
3960 .as_ref()
3961 .map(proto_to_commit_details);
3962
3963 self.snapshot.merge.conflicted_paths = conflicted_paths;
3964
3965 let edits = update
3966 .removed_statuses
3967 .into_iter()
3968 .map(|path| sum_tree::Edit::Remove(PathKey(FromProto::from_proto(path))))
3969 .chain(
3970 update
3971 .updated_statuses
3972 .into_iter()
3973 .filter_map(|updated_status| {
3974 Some(sum_tree::Edit::Insert(updated_status.try_into().log_err()?))
3975 }),
3976 )
3977 .collect::<Vec<_>>();
3978 self.snapshot.statuses_by_path.edit(edits, &());
3979 if update.is_last_update {
3980 self.snapshot.scan_id = update.scan_id;
3981 }
3982 cx.emit(RepositoryEvent::Updated {
3983 full_scan: true,
3984 new_instance: is_new,
3985 });
3986 Ok(())
3987 }
3988
3989 pub fn compare_checkpoints(
3990 &mut self,
3991 left: GitRepositoryCheckpoint,
3992 right: GitRepositoryCheckpoint,
3993 ) -> oneshot::Receiver<Result<bool>> {
3994 self.send_job(None, move |repo, _cx| async move {
3995 match repo {
3996 RepositoryState::Local { backend, .. } => {
3997 backend.compare_checkpoints(left, right).await
3998 }
3999 RepositoryState::Remote { .. } => anyhow::bail!("not implemented yet"),
4000 }
4001 })
4002 }
4003
4004 pub fn diff_checkpoints(
4005 &mut self,
4006 base_checkpoint: GitRepositoryCheckpoint,
4007 target_checkpoint: GitRepositoryCheckpoint,
4008 ) -> oneshot::Receiver<Result<String>> {
4009 self.send_job(None, move |repo, _cx| async move {
4010 match repo {
4011 RepositoryState::Local { backend, .. } => {
4012 backend
4013 .diff_checkpoints(base_checkpoint, target_checkpoint)
4014 .await
4015 }
4016 RepositoryState::Remote { .. } => anyhow::bail!("not implemented yet"),
4017 }
4018 })
4019 }
4020
4021 fn schedule_scan(
4022 &mut self,
4023 updates_tx: Option<mpsc::UnboundedSender<DownstreamUpdate>>,
4024 cx: &mut Context<Self>,
4025 ) {
4026 let this = cx.weak_entity();
4027 let _ = self.send_keyed_job(
4028 Some(GitJobKey::ReloadGitState),
4029 None,
4030 |state, mut cx| async move {
4031 log::debug!("run scheduled git status scan");
4032
4033 let Some(this) = this.upgrade() else {
4034 return Ok(());
4035 };
4036 let RepositoryState::Local { backend, .. } = state else {
4037 bail!("not a local repository")
4038 };
4039 let (snapshot, events) = this
4040 .read_with(&mut cx, |this, _| {
4041 compute_snapshot(
4042 this.id,
4043 this.work_directory_abs_path.clone(),
4044 this.snapshot.clone(),
4045 backend.clone(),
4046 )
4047 })?
4048 .await?;
4049 this.update(&mut cx, |this, cx| {
4050 this.snapshot = snapshot.clone();
4051 for event in events {
4052 cx.emit(event);
4053 }
4054 })?;
4055 if let Some(updates_tx) = updates_tx {
4056 updates_tx
4057 .unbounded_send(DownstreamUpdate::UpdateRepository(snapshot))
4058 .ok();
4059 }
4060 Ok(())
4061 },
4062 );
4063 }
4064
4065 fn spawn_local_git_worker(
4066 work_directory_abs_path: Arc<Path>,
4067 dot_git_abs_path: Arc<Path>,
4068 _repository_dir_abs_path: Arc<Path>,
4069 _common_dir_abs_path: Arc<Path>,
4070 project_environment: WeakEntity<ProjectEnvironment>,
4071 fs: Arc<dyn Fs>,
4072 cx: &mut Context<Self>,
4073 ) -> mpsc::UnboundedSender<GitJob> {
4074 let (job_tx, mut job_rx) = mpsc::unbounded::<GitJob>();
4075
4076 cx.spawn(async move |_, cx| {
4077 let environment = project_environment
4078 .upgrade()
4079 .context("missing project environment")?
4080 .update(cx, |project_environment, cx| {
4081 project_environment.get_directory_environment(work_directory_abs_path.clone(), cx)
4082 })?
4083 .await
4084 .unwrap_or_else(|| {
4085 log::error!("failed to get working directory environment for repository {work_directory_abs_path:?}");
4086 HashMap::default()
4087 });
4088 let backend = cx
4089 .background_spawn(async move {
4090 fs.open_repo(&dot_git_abs_path)
4091 .with_context(|| format!("opening repository at {dot_git_abs_path:?}"))
4092 })
4093 .await?;
4094
4095 if let Some(git_hosting_provider_registry) =
4096 cx.update(|cx| GitHostingProviderRegistry::try_global(cx))?
4097 {
4098 git_hosting_providers::register_additional_providers(
4099 git_hosting_provider_registry,
4100 backend.clone(),
4101 );
4102 }
4103
4104 let state = RepositoryState::Local {
4105 backend,
4106 environment: Arc::new(environment),
4107 };
4108 let mut jobs = VecDeque::new();
4109 loop {
4110 while let Ok(Some(next_job)) = job_rx.try_next() {
4111 jobs.push_back(next_job);
4112 }
4113
4114 if let Some(job) = jobs.pop_front() {
4115 if let Some(current_key) = &job.key {
4116 if jobs
4117 .iter()
4118 .any(|other_job| other_job.key.as_ref() == Some(current_key))
4119 {
4120 continue;
4121 }
4122 }
4123 (job.job)(state.clone(), cx).await;
4124 } else if let Some(job) = job_rx.next().await {
4125 jobs.push_back(job);
4126 } else {
4127 break;
4128 }
4129 }
4130 anyhow::Ok(())
4131 })
4132 .detach_and_log_err(cx);
4133
4134 job_tx
4135 }
4136
4137 fn spawn_remote_git_worker(
4138 project_id: ProjectId,
4139 client: AnyProtoClient,
4140 cx: &mut Context<Self>,
4141 ) -> mpsc::UnboundedSender<GitJob> {
4142 let (job_tx, mut job_rx) = mpsc::unbounded::<GitJob>();
4143
4144 cx.spawn(async move |_, cx| {
4145 let state = RepositoryState::Remote { project_id, client };
4146 let mut jobs = VecDeque::new();
4147 loop {
4148 while let Ok(Some(next_job)) = job_rx.try_next() {
4149 jobs.push_back(next_job);
4150 }
4151
4152 if let Some(job) = jobs.pop_front() {
4153 if let Some(current_key) = &job.key {
4154 if jobs
4155 .iter()
4156 .any(|other_job| other_job.key.as_ref() == Some(current_key))
4157 {
4158 continue;
4159 }
4160 }
4161 (job.job)(state.clone(), cx).await;
4162 } else if let Some(job) = job_rx.next().await {
4163 jobs.push_back(job);
4164 } else {
4165 break;
4166 }
4167 }
4168 anyhow::Ok(())
4169 })
4170 .detach_and_log_err(cx);
4171
4172 job_tx
4173 }
4174
4175 fn load_staged_text(
4176 &mut self,
4177 buffer_id: BufferId,
4178 repo_path: RepoPath,
4179 cx: &App,
4180 ) -> Task<Result<Option<String>>> {
4181 let rx = self.send_job(None, move |state, _| async move {
4182 match state {
4183 RepositoryState::Local { backend, .. } => {
4184 anyhow::Ok(backend.load_index_text(repo_path).await)
4185 }
4186 RepositoryState::Remote { project_id, client } => {
4187 let response = client
4188 .request(proto::OpenUnstagedDiff {
4189 project_id: project_id.to_proto(),
4190 buffer_id: buffer_id.to_proto(),
4191 })
4192 .await?;
4193 Ok(response.staged_text)
4194 }
4195 }
4196 });
4197 cx.spawn(|_: &mut AsyncApp| async move { rx.await? })
4198 }
4199
4200 fn load_committed_text(
4201 &mut self,
4202 buffer_id: BufferId,
4203 repo_path: RepoPath,
4204 cx: &App,
4205 ) -> Task<Result<DiffBasesChange>> {
4206 let rx = self.send_job(None, move |state, _| async move {
4207 match state {
4208 RepositoryState::Local { backend, .. } => {
4209 let committed_text = backend.load_committed_text(repo_path.clone()).await;
4210 let staged_text = backend.load_index_text(repo_path).await;
4211 let diff_bases_change = if committed_text == staged_text {
4212 DiffBasesChange::SetBoth(committed_text)
4213 } else {
4214 DiffBasesChange::SetEach {
4215 index: staged_text,
4216 head: committed_text,
4217 }
4218 };
4219 anyhow::Ok(diff_bases_change)
4220 }
4221 RepositoryState::Remote { project_id, client } => {
4222 use proto::open_uncommitted_diff_response::Mode;
4223
4224 let response = client
4225 .request(proto::OpenUncommittedDiff {
4226 project_id: project_id.to_proto(),
4227 buffer_id: buffer_id.to_proto(),
4228 })
4229 .await?;
4230 let mode = Mode::from_i32(response.mode).context("Invalid mode")?;
4231 let bases = match mode {
4232 Mode::IndexMatchesHead => DiffBasesChange::SetBoth(response.committed_text),
4233 Mode::IndexAndHead => DiffBasesChange::SetEach {
4234 head: response.committed_text,
4235 index: response.staged_text,
4236 },
4237 };
4238 Ok(bases)
4239 }
4240 }
4241 });
4242
4243 cx.spawn(|_: &mut AsyncApp| async move { rx.await? })
4244 }
4245
4246 fn paths_changed(
4247 &mut self,
4248 paths: Vec<RepoPath>,
4249 updates_tx: Option<mpsc::UnboundedSender<DownstreamUpdate>>,
4250 cx: &mut Context<Self>,
4251 ) {
4252 self.paths_needing_status_update.extend(paths);
4253
4254 let this = cx.weak_entity();
4255 let _ = self.send_keyed_job(
4256 Some(GitJobKey::RefreshStatuses),
4257 None,
4258 |state, mut cx| async move {
4259 let (prev_snapshot, mut changed_paths) = this.update(&mut cx, |this, _| {
4260 (
4261 this.snapshot.clone(),
4262 mem::take(&mut this.paths_needing_status_update),
4263 )
4264 })?;
4265 let RepositoryState::Local { backend, .. } = state else {
4266 bail!("not a local repository")
4267 };
4268
4269 let paths = changed_paths.iter().cloned().collect::<Vec<_>>();
4270 let statuses = backend.status(&paths).await?;
4271
4272 let changed_path_statuses = cx
4273 .background_spawn(async move {
4274 let mut changed_path_statuses = Vec::new();
4275 let prev_statuses = prev_snapshot.statuses_by_path.clone();
4276 let mut cursor = prev_statuses.cursor::<PathProgress>(&());
4277
4278 for (repo_path, status) in &*statuses.entries {
4279 changed_paths.remove(repo_path);
4280 if cursor.seek_forward(&PathTarget::Path(repo_path), Bias::Left, &()) {
4281 if cursor.item().is_some_and(|entry| entry.status == *status) {
4282 continue;
4283 }
4284 }
4285
4286 changed_path_statuses.push(Edit::Insert(StatusEntry {
4287 repo_path: repo_path.clone(),
4288 status: *status,
4289 }));
4290 }
4291 let mut cursor = prev_statuses.cursor::<PathProgress>(&());
4292 for path in changed_paths.into_iter() {
4293 if cursor.seek_forward(&PathTarget::Path(&path), Bias::Left, &()) {
4294 changed_path_statuses.push(Edit::Remove(PathKey(path.0)));
4295 }
4296 }
4297 changed_path_statuses
4298 })
4299 .await;
4300
4301 this.update(&mut cx, |this, cx| {
4302 if !changed_path_statuses.is_empty() {
4303 this.snapshot
4304 .statuses_by_path
4305 .edit(changed_path_statuses, &());
4306 this.snapshot.scan_id += 1;
4307 if let Some(updates_tx) = updates_tx {
4308 updates_tx
4309 .unbounded_send(DownstreamUpdate::UpdateRepository(
4310 this.snapshot.clone(),
4311 ))
4312 .ok();
4313 }
4314 }
4315 cx.emit(RepositoryEvent::Updated {
4316 full_scan: false,
4317 new_instance: false,
4318 });
4319 })
4320 },
4321 );
4322 }
4323
4324 /// currently running git command and when it started
4325 pub fn current_job(&self) -> Option<JobInfo> {
4326 self.active_jobs.values().next().cloned()
4327 }
4328
4329 pub fn barrier(&mut self) -> oneshot::Receiver<()> {
4330 self.send_job(None, |_, _| async {})
4331 }
4332}
4333
4334fn get_permalink_in_rust_registry_src(
4335 provider_registry: Arc<GitHostingProviderRegistry>,
4336 path: PathBuf,
4337 selection: Range<u32>,
4338) -> Result<url::Url> {
4339 #[derive(Deserialize)]
4340 struct CargoVcsGit {
4341 sha1: String,
4342 }
4343
4344 #[derive(Deserialize)]
4345 struct CargoVcsInfo {
4346 git: CargoVcsGit,
4347 path_in_vcs: String,
4348 }
4349
4350 #[derive(Deserialize)]
4351 struct CargoPackage {
4352 repository: String,
4353 }
4354
4355 #[derive(Deserialize)]
4356 struct CargoToml {
4357 package: CargoPackage,
4358 }
4359
4360 let Some((dir, cargo_vcs_info_json)) = path.ancestors().skip(1).find_map(|dir| {
4361 let json = std::fs::read_to_string(dir.join(".cargo_vcs_info.json")).ok()?;
4362 Some((dir, json))
4363 }) else {
4364 bail!("No .cargo_vcs_info.json found in parent directories")
4365 };
4366 let cargo_vcs_info = serde_json::from_str::<CargoVcsInfo>(&cargo_vcs_info_json)?;
4367 let cargo_toml = std::fs::read_to_string(dir.join("Cargo.toml"))?;
4368 let manifest = toml::from_str::<CargoToml>(&cargo_toml)?;
4369 let (provider, remote) = parse_git_remote_url(provider_registry, &manifest.package.repository)
4370 .context("parsing package.repository field of manifest")?;
4371 let path = PathBuf::from(cargo_vcs_info.path_in_vcs).join(path.strip_prefix(dir).unwrap());
4372 let permalink = provider.build_permalink(
4373 remote,
4374 BuildPermalinkParams {
4375 sha: &cargo_vcs_info.git.sha1,
4376 path: &path.to_string_lossy(),
4377 selection: Some(selection),
4378 },
4379 );
4380 Ok(permalink)
4381}
4382
4383fn serialize_blame_buffer_response(blame: Option<git::blame::Blame>) -> proto::BlameBufferResponse {
4384 let Some(blame) = blame else {
4385 return proto::BlameBufferResponse {
4386 blame_response: None,
4387 };
4388 };
4389
4390 let entries = blame
4391 .entries
4392 .into_iter()
4393 .map(|entry| proto::BlameEntry {
4394 sha: entry.sha.as_bytes().into(),
4395 start_line: entry.range.start,
4396 end_line: entry.range.end,
4397 original_line_number: entry.original_line_number,
4398 author: entry.author.clone(),
4399 author_mail: entry.author_mail.clone(),
4400 author_time: entry.author_time,
4401 author_tz: entry.author_tz.clone(),
4402 committer: entry.committer_name.clone(),
4403 committer_mail: entry.committer_email.clone(),
4404 committer_time: entry.committer_time,
4405 committer_tz: entry.committer_tz.clone(),
4406 summary: entry.summary.clone(),
4407 previous: entry.previous.clone(),
4408 filename: entry.filename.clone(),
4409 })
4410 .collect::<Vec<_>>();
4411
4412 let messages = blame
4413 .messages
4414 .into_iter()
4415 .map(|(oid, message)| proto::CommitMessage {
4416 oid: oid.as_bytes().into(),
4417 message,
4418 })
4419 .collect::<Vec<_>>();
4420
4421 proto::BlameBufferResponse {
4422 blame_response: Some(proto::blame_buffer_response::BlameResponse {
4423 entries,
4424 messages,
4425 remote_url: blame.remote_url,
4426 }),
4427 }
4428}
4429
4430fn deserialize_blame_buffer_response(
4431 response: proto::BlameBufferResponse,
4432) -> Option<git::blame::Blame> {
4433 let response = response.blame_response?;
4434 let entries = response
4435 .entries
4436 .into_iter()
4437 .filter_map(|entry| {
4438 Some(git::blame::BlameEntry {
4439 sha: git::Oid::from_bytes(&entry.sha).ok()?,
4440 range: entry.start_line..entry.end_line,
4441 original_line_number: entry.original_line_number,
4442 committer_name: entry.committer,
4443 committer_time: entry.committer_time,
4444 committer_tz: entry.committer_tz,
4445 committer_email: entry.committer_mail,
4446 author: entry.author,
4447 author_mail: entry.author_mail,
4448 author_time: entry.author_time,
4449 author_tz: entry.author_tz,
4450 summary: entry.summary,
4451 previous: entry.previous,
4452 filename: entry.filename,
4453 })
4454 })
4455 .collect::<Vec<_>>();
4456
4457 let messages = response
4458 .messages
4459 .into_iter()
4460 .filter_map(|message| Some((git::Oid::from_bytes(&message.oid).ok()?, message.message)))
4461 .collect::<HashMap<_, _>>();
4462
4463 Some(Blame {
4464 entries,
4465 messages,
4466 remote_url: response.remote_url,
4467 })
4468}
4469
4470fn branch_to_proto(branch: &git::repository::Branch) -> proto::Branch {
4471 proto::Branch {
4472 is_head: branch.is_head,
4473 ref_name: branch.ref_name.to_string(),
4474 unix_timestamp: branch
4475 .most_recent_commit
4476 .as_ref()
4477 .map(|commit| commit.commit_timestamp as u64),
4478 upstream: branch.upstream.as_ref().map(|upstream| proto::GitUpstream {
4479 ref_name: upstream.ref_name.to_string(),
4480 tracking: upstream
4481 .tracking
4482 .status()
4483 .map(|upstream| proto::UpstreamTracking {
4484 ahead: upstream.ahead as u64,
4485 behind: upstream.behind as u64,
4486 }),
4487 }),
4488 most_recent_commit: branch
4489 .most_recent_commit
4490 .as_ref()
4491 .map(|commit| proto::CommitSummary {
4492 sha: commit.sha.to_string(),
4493 subject: commit.subject.to_string(),
4494 commit_timestamp: commit.commit_timestamp,
4495 }),
4496 }
4497}
4498
4499fn proto_to_branch(proto: &proto::Branch) -> git::repository::Branch {
4500 git::repository::Branch {
4501 is_head: proto.is_head,
4502 ref_name: proto.ref_name.clone().into(),
4503 upstream: proto
4504 .upstream
4505 .as_ref()
4506 .map(|upstream| git::repository::Upstream {
4507 ref_name: upstream.ref_name.to_string().into(),
4508 tracking: upstream
4509 .tracking
4510 .as_ref()
4511 .map(|tracking| {
4512 git::repository::UpstreamTracking::Tracked(UpstreamTrackingStatus {
4513 ahead: tracking.ahead as u32,
4514 behind: tracking.behind as u32,
4515 })
4516 })
4517 .unwrap_or(git::repository::UpstreamTracking::Gone),
4518 }),
4519 most_recent_commit: proto.most_recent_commit.as_ref().map(|commit| {
4520 git::repository::CommitSummary {
4521 sha: commit.sha.to_string().into(),
4522 subject: commit.subject.to_string().into(),
4523 commit_timestamp: commit.commit_timestamp,
4524 has_parent: true,
4525 }
4526 }),
4527 }
4528}
4529
4530fn commit_details_to_proto(commit: &CommitDetails) -> proto::GitCommitDetails {
4531 proto::GitCommitDetails {
4532 sha: commit.sha.to_string(),
4533 message: commit.message.to_string(),
4534 commit_timestamp: commit.commit_timestamp,
4535 author_email: commit.author_email.to_string(),
4536 author_name: commit.author_name.to_string(),
4537 }
4538}
4539
4540fn proto_to_commit_details(proto: &proto::GitCommitDetails) -> CommitDetails {
4541 CommitDetails {
4542 sha: proto.sha.clone().into(),
4543 message: proto.message.clone().into(),
4544 commit_timestamp: proto.commit_timestamp,
4545 author_email: proto.author_email.clone().into(),
4546 author_name: proto.author_name.clone().into(),
4547 }
4548}
4549
4550async fn compute_snapshot(
4551 id: RepositoryId,
4552 work_directory_abs_path: Arc<Path>,
4553 prev_snapshot: RepositorySnapshot,
4554 backend: Arc<dyn GitRepository>,
4555) -> Result<(RepositorySnapshot, Vec<RepositoryEvent>)> {
4556 let mut events = Vec::new();
4557 let branches = backend.branches().await?;
4558 let branch = branches.into_iter().find(|branch| branch.is_head);
4559 let statuses = backend
4560 .status(std::slice::from_ref(&WORK_DIRECTORY_REPO_PATH))
4561 .await?;
4562 let statuses_by_path = SumTree::from_iter(
4563 statuses
4564 .entries
4565 .iter()
4566 .map(|(repo_path, status)| StatusEntry {
4567 repo_path: repo_path.clone(),
4568 status: *status,
4569 }),
4570 &(),
4571 );
4572 let (merge_details, merge_heads_changed) =
4573 MergeDetails::load(&backend, &statuses_by_path, &prev_snapshot).await?;
4574 log::debug!("new merge details (changed={merge_heads_changed:?}): {merge_details:?}");
4575
4576 if merge_heads_changed
4577 || branch != prev_snapshot.branch
4578 || statuses_by_path != prev_snapshot.statuses_by_path
4579 {
4580 events.push(RepositoryEvent::Updated {
4581 full_scan: true,
4582 new_instance: false,
4583 });
4584 }
4585
4586 // Cache merge conflict paths so they don't change from staging/unstaging,
4587 // until the merge heads change (at commit time, etc.).
4588 if merge_heads_changed {
4589 events.push(RepositoryEvent::MergeHeadsChanged);
4590 }
4591
4592 // Useful when branch is None in detached head state
4593 let head_commit = match backend.head_sha().await {
4594 Some(head_sha) => backend.show(head_sha).await.log_err(),
4595 None => None,
4596 };
4597
4598 let snapshot = RepositorySnapshot {
4599 id,
4600 statuses_by_path,
4601 work_directory_abs_path,
4602 scan_id: prev_snapshot.scan_id + 1,
4603 branch,
4604 head_commit,
4605 merge: merge_details,
4606 };
4607
4608 Ok((snapshot, events))
4609}
4610
4611fn status_from_proto(
4612 simple_status: i32,
4613 status: Option<proto::GitFileStatus>,
4614) -> anyhow::Result<FileStatus> {
4615 use proto::git_file_status::Variant;
4616
4617 let Some(variant) = status.and_then(|status| status.variant) else {
4618 let code = proto::GitStatus::from_i32(simple_status)
4619 .with_context(|| format!("Invalid git status code: {simple_status}"))?;
4620 let result = match code {
4621 proto::GitStatus::Added => TrackedStatus {
4622 worktree_status: StatusCode::Added,
4623 index_status: StatusCode::Unmodified,
4624 }
4625 .into(),
4626 proto::GitStatus::Modified => TrackedStatus {
4627 worktree_status: StatusCode::Modified,
4628 index_status: StatusCode::Unmodified,
4629 }
4630 .into(),
4631 proto::GitStatus::Conflict => UnmergedStatus {
4632 first_head: UnmergedStatusCode::Updated,
4633 second_head: UnmergedStatusCode::Updated,
4634 }
4635 .into(),
4636 proto::GitStatus::Deleted => TrackedStatus {
4637 worktree_status: StatusCode::Deleted,
4638 index_status: StatusCode::Unmodified,
4639 }
4640 .into(),
4641 _ => anyhow::bail!("Invalid code for simple status: {simple_status}"),
4642 };
4643 return Ok(result);
4644 };
4645
4646 let result = match variant {
4647 Variant::Untracked(_) => FileStatus::Untracked,
4648 Variant::Ignored(_) => FileStatus::Ignored,
4649 Variant::Unmerged(unmerged) => {
4650 let [first_head, second_head] =
4651 [unmerged.first_head, unmerged.second_head].map(|head| {
4652 let code = proto::GitStatus::from_i32(head)
4653 .with_context(|| format!("Invalid git status code: {head}"))?;
4654 let result = match code {
4655 proto::GitStatus::Added => UnmergedStatusCode::Added,
4656 proto::GitStatus::Updated => UnmergedStatusCode::Updated,
4657 proto::GitStatus::Deleted => UnmergedStatusCode::Deleted,
4658 _ => anyhow::bail!("Invalid code for unmerged status: {code:?}"),
4659 };
4660 Ok(result)
4661 });
4662 let [first_head, second_head] = [first_head?, second_head?];
4663 UnmergedStatus {
4664 first_head,
4665 second_head,
4666 }
4667 .into()
4668 }
4669 Variant::Tracked(tracked) => {
4670 let [index_status, worktree_status] = [tracked.index_status, tracked.worktree_status]
4671 .map(|status| {
4672 let code = proto::GitStatus::from_i32(status)
4673 .with_context(|| format!("Invalid git status code: {status}"))?;
4674 let result = match code {
4675 proto::GitStatus::Modified => StatusCode::Modified,
4676 proto::GitStatus::TypeChanged => StatusCode::TypeChanged,
4677 proto::GitStatus::Added => StatusCode::Added,
4678 proto::GitStatus::Deleted => StatusCode::Deleted,
4679 proto::GitStatus::Renamed => StatusCode::Renamed,
4680 proto::GitStatus::Copied => StatusCode::Copied,
4681 proto::GitStatus::Unmodified => StatusCode::Unmodified,
4682 _ => anyhow::bail!("Invalid code for tracked status: {code:?}"),
4683 };
4684 Ok(result)
4685 });
4686 let [index_status, worktree_status] = [index_status?, worktree_status?];
4687 TrackedStatus {
4688 index_status,
4689 worktree_status,
4690 }
4691 .into()
4692 }
4693 };
4694 Ok(result)
4695}
4696
4697fn status_to_proto(status: FileStatus) -> proto::GitFileStatus {
4698 use proto::git_file_status::{Tracked, Unmerged, Variant};
4699
4700 let variant = match status {
4701 FileStatus::Untracked => Variant::Untracked(Default::default()),
4702 FileStatus::Ignored => Variant::Ignored(Default::default()),
4703 FileStatus::Unmerged(UnmergedStatus {
4704 first_head,
4705 second_head,
4706 }) => Variant::Unmerged(Unmerged {
4707 first_head: unmerged_status_to_proto(first_head),
4708 second_head: unmerged_status_to_proto(second_head),
4709 }),
4710 FileStatus::Tracked(TrackedStatus {
4711 index_status,
4712 worktree_status,
4713 }) => Variant::Tracked(Tracked {
4714 index_status: tracked_status_to_proto(index_status),
4715 worktree_status: tracked_status_to_proto(worktree_status),
4716 }),
4717 };
4718 proto::GitFileStatus {
4719 variant: Some(variant),
4720 }
4721}
4722
4723fn unmerged_status_to_proto(code: UnmergedStatusCode) -> i32 {
4724 match code {
4725 UnmergedStatusCode::Added => proto::GitStatus::Added as _,
4726 UnmergedStatusCode::Deleted => proto::GitStatus::Deleted as _,
4727 UnmergedStatusCode::Updated => proto::GitStatus::Updated as _,
4728 }
4729}
4730
4731fn tracked_status_to_proto(code: StatusCode) -> i32 {
4732 match code {
4733 StatusCode::Added => proto::GitStatus::Added as _,
4734 StatusCode::Deleted => proto::GitStatus::Deleted as _,
4735 StatusCode::Modified => proto::GitStatus::Modified as _,
4736 StatusCode::Renamed => proto::GitStatus::Renamed as _,
4737 StatusCode::TypeChanged => proto::GitStatus::TypeChanged as _,
4738 StatusCode::Copied => proto::GitStatus::Copied as _,
4739 StatusCode::Unmodified => proto::GitStatus::Unmodified as _,
4740 }
4741}