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