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