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