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