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, RunHook,
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, PendingOpsSummary};
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 work_directory_abs_path: Arc<Path>,
259 pub path_style: PathStyle,
260 pub branch: Option<Branch>,
261 pub head_commit: Option<CommitDetails>,
262 pub scan_id: u64,
263 pub merge: MergeDetails,
264 pub remote_origin_url: Option<String>,
265 pub remote_upstream_url: Option<String>,
266 pub stash_entries: GitStash,
267}
268
269type JobId = u64;
270
271#[derive(Clone, Debug, PartialEq, Eq)]
272pub struct JobInfo {
273 pub start: Instant,
274 pub message: SharedString,
275}
276
277pub struct Repository {
278 this: WeakEntity<Self>,
279 snapshot: RepositorySnapshot,
280 commit_message_buffer: Option<Entity<Buffer>>,
281 git_store: WeakEntity<GitStore>,
282 // For a local repository, holds paths that have had worktree events since the last status scan completed,
283 // and that should be examined during the next status scan.
284 paths_needing_status_update: BTreeSet<RepoPath>,
285 job_sender: mpsc::UnboundedSender<GitJob>,
286 active_jobs: HashMap<JobId, JobInfo>,
287 pending_ops: SumTree<PendingOps>,
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 fs: Arc<dyn Fs>,
305 backend: Arc<dyn GitRepository>,
306 environment: Arc<HashMap<String, String>>,
307 },
308 Remote {
309 project_id: ProjectId,
310 client: AnyProtoClient,
311 },
312}
313
314#[derive(Clone, Debug, PartialEq, Eq)]
315pub enum RepositoryEvent {
316 StatusesChanged,
317 MergeHeadsChanged,
318 BranchChanged,
319 StashEntriesChanged,
320 PendingOpsChanged { pending_ops: SumTree<PendingOps> },
321}
322
323#[derive(Clone, Debug)]
324pub struct JobsUpdated;
325
326#[derive(Debug)]
327pub enum GitStoreEvent {
328 ActiveRepositoryChanged(Option<RepositoryId>),
329 RepositoryUpdated(RepositoryId, RepositoryEvent, bool),
330 RepositoryAdded,
331 RepositoryRemoved(RepositoryId),
332 IndexWriteError(anyhow::Error),
333 JobsUpdated,
334 ConflictsUpdated,
335}
336
337impl EventEmitter<RepositoryEvent> for Repository {}
338impl EventEmitter<JobsUpdated> for Repository {}
339impl EventEmitter<GitStoreEvent> for GitStore {}
340
341pub struct GitJob {
342 job: Box<dyn FnOnce(RepositoryState, &mut AsyncApp) -> Task<()>>,
343 key: Option<GitJobKey>,
344}
345
346#[derive(PartialEq, Eq)]
347enum GitJobKey {
348 WriteIndex(Vec<RepoPath>),
349 ReloadBufferDiffBases,
350 RefreshStatuses,
351 ReloadGitState,
352}
353
354impl GitStore {
355 pub fn local(
356 worktree_store: &Entity<WorktreeStore>,
357 buffer_store: Entity<BufferStore>,
358 environment: Entity<ProjectEnvironment>,
359 fs: Arc<dyn Fs>,
360 cx: &mut Context<Self>,
361 ) -> Self {
362 Self::new(
363 worktree_store.clone(),
364 buffer_store,
365 GitStoreState::Local {
366 next_repository_id: Arc::new(AtomicU64::new(1)),
367 downstream: None,
368 project_environment: environment,
369 fs,
370 },
371 cx,
372 )
373 }
374
375 pub fn remote(
376 worktree_store: &Entity<WorktreeStore>,
377 buffer_store: Entity<BufferStore>,
378 upstream_client: AnyProtoClient,
379 project_id: u64,
380 cx: &mut Context<Self>,
381 ) -> Self {
382 Self::new(
383 worktree_store.clone(),
384 buffer_store,
385 GitStoreState::Remote {
386 upstream_client,
387 upstream_project_id: project_id,
388 downstream: None,
389 },
390 cx,
391 )
392 }
393
394 fn new(
395 worktree_store: Entity<WorktreeStore>,
396 buffer_store: Entity<BufferStore>,
397 state: GitStoreState,
398 cx: &mut Context<Self>,
399 ) -> Self {
400 let _subscriptions = vec![
401 cx.subscribe(&worktree_store, Self::on_worktree_store_event),
402 cx.subscribe(&buffer_store, Self::on_buffer_store_event),
403 ];
404
405 GitStore {
406 state,
407 buffer_store,
408 worktree_store,
409 repositories: HashMap::default(),
410 worktree_ids: HashMap::default(),
411 active_repo_id: None,
412 _subscriptions,
413 loading_diffs: HashMap::default(),
414 shared_diffs: HashMap::default(),
415 diffs: HashMap::default(),
416 }
417 }
418
419 pub fn init(client: &AnyProtoClient) {
420 client.add_entity_request_handler(Self::handle_get_remotes);
421 client.add_entity_request_handler(Self::handle_get_branches);
422 client.add_entity_request_handler(Self::handle_get_default_branch);
423 client.add_entity_request_handler(Self::handle_change_branch);
424 client.add_entity_request_handler(Self::handle_create_branch);
425 client.add_entity_request_handler(Self::handle_rename_branch);
426 client.add_entity_request_handler(Self::handle_git_init);
427 client.add_entity_request_handler(Self::handle_push);
428 client.add_entity_request_handler(Self::handle_pull);
429 client.add_entity_request_handler(Self::handle_fetch);
430 client.add_entity_request_handler(Self::handle_stage);
431 client.add_entity_request_handler(Self::handle_unstage);
432 client.add_entity_request_handler(Self::handle_stash);
433 client.add_entity_request_handler(Self::handle_stash_pop);
434 client.add_entity_request_handler(Self::handle_stash_apply);
435 client.add_entity_request_handler(Self::handle_stash_drop);
436 client.add_entity_request_handler(Self::handle_commit);
437 client.add_entity_request_handler(Self::handle_run_hook);
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_run_hook(
1988 this: Entity<Self>,
1989 envelope: TypedEnvelope<proto::RunGitHook>,
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 hook = RunHook::from_proto(envelope.payload.hook).context("invalid hook")?;
1995 repository_handle
1996 .update(&mut cx, |repository_handle, cx| {
1997 repository_handle.run_hook(hook, cx)
1998 })?
1999 .await??;
2000 Ok(proto::Ack {})
2001 }
2002
2003 async fn handle_commit(
2004 this: Entity<Self>,
2005 envelope: TypedEnvelope<proto::Commit>,
2006 mut cx: AsyncApp,
2007 ) -> Result<proto::Ack> {
2008 let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
2009 let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;
2010 let askpass_id = envelope.payload.askpass_id;
2011
2012 let askpass = make_remote_delegate(
2013 this,
2014 envelope.payload.project_id,
2015 repository_id,
2016 askpass_id,
2017 &mut cx,
2018 );
2019
2020 let message = SharedString::from(envelope.payload.message);
2021 let name = envelope.payload.name.map(SharedString::from);
2022 let email = envelope.payload.email.map(SharedString::from);
2023 let options = envelope.payload.options.unwrap_or_default();
2024
2025 repository_handle
2026 .update(&mut cx, |repository_handle, cx| {
2027 repository_handle.commit(
2028 message,
2029 name.zip(email),
2030 CommitOptions {
2031 amend: options.amend,
2032 signoff: options.signoff,
2033 },
2034 askpass,
2035 cx,
2036 )
2037 })?
2038 .await??;
2039 Ok(proto::Ack {})
2040 }
2041
2042 async fn handle_get_remotes(
2043 this: Entity<Self>,
2044 envelope: TypedEnvelope<proto::GetRemotes>,
2045 mut cx: AsyncApp,
2046 ) -> Result<proto::GetRemotesResponse> {
2047 let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
2048 let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;
2049
2050 let branch_name = envelope.payload.branch_name;
2051
2052 let remotes = repository_handle
2053 .update(&mut cx, |repository_handle, _| {
2054 repository_handle.get_remotes(branch_name)
2055 })?
2056 .await??;
2057
2058 Ok(proto::GetRemotesResponse {
2059 remotes: remotes
2060 .into_iter()
2061 .map(|remotes| proto::get_remotes_response::Remote {
2062 name: remotes.name.to_string(),
2063 })
2064 .collect::<Vec<_>>(),
2065 })
2066 }
2067
2068 async fn handle_get_worktrees(
2069 this: Entity<Self>,
2070 envelope: TypedEnvelope<proto::GitGetWorktrees>,
2071 mut cx: AsyncApp,
2072 ) -> Result<proto::GitWorktreesResponse> {
2073 let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
2074 let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;
2075
2076 let worktrees = repository_handle
2077 .update(&mut cx, |repository_handle, _| {
2078 repository_handle.worktrees()
2079 })?
2080 .await??;
2081
2082 Ok(proto::GitWorktreesResponse {
2083 worktrees: worktrees
2084 .into_iter()
2085 .map(|worktree| worktree_to_proto(&worktree))
2086 .collect::<Vec<_>>(),
2087 })
2088 }
2089
2090 async fn handle_create_worktree(
2091 this: Entity<Self>,
2092 envelope: TypedEnvelope<proto::GitCreateWorktree>,
2093 mut cx: AsyncApp,
2094 ) -> Result<proto::Ack> {
2095 let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
2096 let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;
2097 let directory = PathBuf::from(envelope.payload.directory);
2098 let name = envelope.payload.name;
2099 let commit = envelope.payload.commit;
2100
2101 repository_handle
2102 .update(&mut cx, |repository_handle, _| {
2103 repository_handle.create_worktree(name, directory, commit)
2104 })?
2105 .await??;
2106
2107 Ok(proto::Ack {})
2108 }
2109
2110 async fn handle_get_branches(
2111 this: Entity<Self>,
2112 envelope: TypedEnvelope<proto::GitGetBranches>,
2113 mut cx: AsyncApp,
2114 ) -> Result<proto::GitBranchesResponse> {
2115 let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
2116 let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;
2117
2118 let branches = repository_handle
2119 .update(&mut cx, |repository_handle, _| repository_handle.branches())?
2120 .await??;
2121
2122 Ok(proto::GitBranchesResponse {
2123 branches: branches
2124 .into_iter()
2125 .map(|branch| branch_to_proto(&branch))
2126 .collect::<Vec<_>>(),
2127 })
2128 }
2129 async fn handle_get_default_branch(
2130 this: Entity<Self>,
2131 envelope: TypedEnvelope<proto::GetDefaultBranch>,
2132 mut cx: AsyncApp,
2133 ) -> Result<proto::GetDefaultBranchResponse> {
2134 let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
2135 let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;
2136
2137 let branch = repository_handle
2138 .update(&mut cx, |repository_handle, _| {
2139 repository_handle.default_branch()
2140 })?
2141 .await??
2142 .map(Into::into);
2143
2144 Ok(proto::GetDefaultBranchResponse { branch })
2145 }
2146 async fn handle_create_branch(
2147 this: Entity<Self>,
2148 envelope: TypedEnvelope<proto::GitCreateBranch>,
2149 mut cx: AsyncApp,
2150 ) -> Result<proto::Ack> {
2151 let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
2152 let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;
2153 let branch_name = envelope.payload.branch_name;
2154
2155 repository_handle
2156 .update(&mut cx, |repository_handle, _| {
2157 repository_handle.create_branch(branch_name, None)
2158 })?
2159 .await??;
2160
2161 Ok(proto::Ack {})
2162 }
2163
2164 async fn handle_change_branch(
2165 this: Entity<Self>,
2166 envelope: TypedEnvelope<proto::GitChangeBranch>,
2167 mut cx: AsyncApp,
2168 ) -> Result<proto::Ack> {
2169 let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
2170 let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;
2171 let branch_name = envelope.payload.branch_name;
2172
2173 repository_handle
2174 .update(&mut cx, |repository_handle, _| {
2175 repository_handle.change_branch(branch_name)
2176 })?
2177 .await??;
2178
2179 Ok(proto::Ack {})
2180 }
2181
2182 async fn handle_rename_branch(
2183 this: Entity<Self>,
2184 envelope: TypedEnvelope<proto::GitRenameBranch>,
2185 mut cx: AsyncApp,
2186 ) -> Result<proto::Ack> {
2187 let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
2188 let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;
2189 let branch = envelope.payload.branch;
2190 let new_name = envelope.payload.new_name;
2191
2192 repository_handle
2193 .update(&mut cx, |repository_handle, _| {
2194 repository_handle.rename_branch(branch, new_name)
2195 })?
2196 .await??;
2197
2198 Ok(proto::Ack {})
2199 }
2200
2201 async fn handle_show(
2202 this: Entity<Self>,
2203 envelope: TypedEnvelope<proto::GitShow>,
2204 mut cx: AsyncApp,
2205 ) -> Result<proto::GitCommitDetails> {
2206 let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
2207 let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;
2208
2209 let commit = repository_handle
2210 .update(&mut cx, |repository_handle, _| {
2211 repository_handle.show(envelope.payload.commit)
2212 })?
2213 .await??;
2214 Ok(proto::GitCommitDetails {
2215 sha: commit.sha.into(),
2216 message: commit.message.into(),
2217 commit_timestamp: commit.commit_timestamp,
2218 author_email: commit.author_email.into(),
2219 author_name: commit.author_name.into(),
2220 })
2221 }
2222
2223 async fn handle_load_commit_diff(
2224 this: Entity<Self>,
2225 envelope: TypedEnvelope<proto::LoadCommitDiff>,
2226 mut cx: AsyncApp,
2227 ) -> Result<proto::LoadCommitDiffResponse> {
2228 let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
2229 let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;
2230
2231 let commit_diff = repository_handle
2232 .update(&mut cx, |repository_handle, _| {
2233 repository_handle.load_commit_diff(envelope.payload.commit)
2234 })?
2235 .await??;
2236 Ok(proto::LoadCommitDiffResponse {
2237 files: commit_diff
2238 .files
2239 .into_iter()
2240 .map(|file| proto::CommitFile {
2241 path: file.path.to_proto(),
2242 old_text: file.old_text,
2243 new_text: file.new_text,
2244 })
2245 .collect(),
2246 })
2247 }
2248
2249 async fn handle_reset(
2250 this: Entity<Self>,
2251 envelope: TypedEnvelope<proto::GitReset>,
2252 mut cx: AsyncApp,
2253 ) -> Result<proto::Ack> {
2254 let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
2255 let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;
2256
2257 let mode = match envelope.payload.mode() {
2258 git_reset::ResetMode::Soft => ResetMode::Soft,
2259 git_reset::ResetMode::Mixed => ResetMode::Mixed,
2260 };
2261
2262 repository_handle
2263 .update(&mut cx, |repository_handle, cx| {
2264 repository_handle.reset(envelope.payload.commit, mode, cx)
2265 })?
2266 .await??;
2267 Ok(proto::Ack {})
2268 }
2269
2270 async fn handle_checkout_files(
2271 this: Entity<Self>,
2272 envelope: TypedEnvelope<proto::GitCheckoutFiles>,
2273 mut cx: AsyncApp,
2274 ) -> Result<proto::Ack> {
2275 let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
2276 let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;
2277 let paths = envelope
2278 .payload
2279 .paths
2280 .iter()
2281 .map(|s| RepoPath::from_proto(s))
2282 .collect::<Result<Vec<_>>>()?;
2283
2284 repository_handle
2285 .update(&mut cx, |repository_handle, cx| {
2286 repository_handle.checkout_files(&envelope.payload.commit, paths, cx)
2287 })?
2288 .await?;
2289 Ok(proto::Ack {})
2290 }
2291
2292 async fn handle_open_commit_message_buffer(
2293 this: Entity<Self>,
2294 envelope: TypedEnvelope<proto::OpenCommitMessageBuffer>,
2295 mut cx: AsyncApp,
2296 ) -> Result<proto::OpenBufferResponse> {
2297 let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
2298 let repository = Self::repository_for_request(&this, repository_id, &mut cx)?;
2299 let buffer = repository
2300 .update(&mut cx, |repository, cx| {
2301 repository.open_commit_buffer(None, this.read(cx).buffer_store.clone(), cx)
2302 })?
2303 .await?;
2304
2305 let buffer_id = buffer.read_with(&cx, |buffer, _| buffer.remote_id())?;
2306 this.update(&mut cx, |this, cx| {
2307 this.buffer_store.update(cx, |buffer_store, cx| {
2308 buffer_store
2309 .create_buffer_for_peer(
2310 &buffer,
2311 envelope.original_sender_id.unwrap_or(envelope.sender_id),
2312 cx,
2313 )
2314 .detach_and_log_err(cx);
2315 })
2316 })?;
2317
2318 Ok(proto::OpenBufferResponse {
2319 buffer_id: buffer_id.to_proto(),
2320 })
2321 }
2322
2323 async fn handle_askpass(
2324 this: Entity<Self>,
2325 envelope: TypedEnvelope<proto::AskPassRequest>,
2326 mut cx: AsyncApp,
2327 ) -> Result<proto::AskPassResponse> {
2328 let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
2329 let repository = Self::repository_for_request(&this, repository_id, &mut cx)?;
2330
2331 let delegates = cx.update(|cx| repository.read(cx).askpass_delegates.clone())?;
2332 let Some(mut askpass) = delegates.lock().remove(&envelope.payload.askpass_id) else {
2333 debug_panic!("no askpass found");
2334 anyhow::bail!("no askpass found");
2335 };
2336
2337 let response = askpass
2338 .ask_password(envelope.payload.prompt)
2339 .await
2340 .ok_or_else(|| anyhow::anyhow!("askpass cancelled"))?;
2341
2342 delegates
2343 .lock()
2344 .insert(envelope.payload.askpass_id, askpass);
2345
2346 // In fact, we don't quite know what we're doing here, as we're sending askpass password unencrypted, but..
2347 Ok(proto::AskPassResponse {
2348 response: response.decrypt(IKnowWhatIAmDoingAndIHaveReadTheDocs)?,
2349 })
2350 }
2351
2352 async fn handle_check_for_pushed_commits(
2353 this: Entity<Self>,
2354 envelope: TypedEnvelope<proto::CheckForPushedCommits>,
2355 mut cx: AsyncApp,
2356 ) -> Result<proto::CheckForPushedCommitsResponse> {
2357 let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
2358 let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;
2359
2360 let branches = repository_handle
2361 .update(&mut cx, |repository_handle, _| {
2362 repository_handle.check_for_pushed_commits()
2363 })?
2364 .await??;
2365 Ok(proto::CheckForPushedCommitsResponse {
2366 pushed_to: branches
2367 .into_iter()
2368 .map(|commit| commit.to_string())
2369 .collect(),
2370 })
2371 }
2372
2373 async fn handle_git_diff(
2374 this: Entity<Self>,
2375 envelope: TypedEnvelope<proto::GitDiff>,
2376 mut cx: AsyncApp,
2377 ) -> Result<proto::GitDiffResponse> {
2378 let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
2379 let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;
2380 let diff_type = match envelope.payload.diff_type() {
2381 proto::git_diff::DiffType::HeadToIndex => DiffType::HeadToIndex,
2382 proto::git_diff::DiffType::HeadToWorktree => DiffType::HeadToWorktree,
2383 };
2384
2385 let mut diff = repository_handle
2386 .update(&mut cx, |repository_handle, cx| {
2387 repository_handle.diff(diff_type, cx)
2388 })?
2389 .await??;
2390 const ONE_MB: usize = 1_000_000;
2391 if diff.len() > ONE_MB {
2392 diff = diff.chars().take(ONE_MB).collect()
2393 }
2394
2395 Ok(proto::GitDiffResponse { diff })
2396 }
2397
2398 async fn handle_tree_diff(
2399 this: Entity<Self>,
2400 request: TypedEnvelope<proto::GetTreeDiff>,
2401 mut cx: AsyncApp,
2402 ) -> Result<proto::GetTreeDiffResponse> {
2403 let repository_id = RepositoryId(request.payload.repository_id);
2404 let diff_type = if request.payload.is_merge {
2405 DiffTreeType::MergeBase {
2406 base: request.payload.base.into(),
2407 head: request.payload.head.into(),
2408 }
2409 } else {
2410 DiffTreeType::Since {
2411 base: request.payload.base.into(),
2412 head: request.payload.head.into(),
2413 }
2414 };
2415
2416 let diff = this
2417 .update(&mut cx, |this, cx| {
2418 let repository = this.repositories().get(&repository_id)?;
2419 Some(repository.update(cx, |repo, cx| repo.diff_tree(diff_type, cx)))
2420 })?
2421 .context("missing repository")?
2422 .await??;
2423
2424 Ok(proto::GetTreeDiffResponse {
2425 entries: diff
2426 .entries
2427 .into_iter()
2428 .map(|(path, status)| proto::TreeDiffStatus {
2429 path: path.as_ref().to_proto(),
2430 status: match status {
2431 TreeDiffStatus::Added {} => proto::tree_diff_status::Status::Added.into(),
2432 TreeDiffStatus::Modified { .. } => {
2433 proto::tree_diff_status::Status::Modified.into()
2434 }
2435 TreeDiffStatus::Deleted { .. } => {
2436 proto::tree_diff_status::Status::Deleted.into()
2437 }
2438 },
2439 oid: match status {
2440 TreeDiffStatus::Deleted { old } | TreeDiffStatus::Modified { old } => {
2441 Some(old.to_string())
2442 }
2443 TreeDiffStatus::Added => None,
2444 },
2445 })
2446 .collect(),
2447 })
2448 }
2449
2450 async fn handle_get_blob_content(
2451 this: Entity<Self>,
2452 request: TypedEnvelope<proto::GetBlobContent>,
2453 mut cx: AsyncApp,
2454 ) -> Result<proto::GetBlobContentResponse> {
2455 let oid = git::Oid::from_str(&request.payload.oid)?;
2456 let repository_id = RepositoryId(request.payload.repository_id);
2457 let content = this
2458 .update(&mut cx, |this, cx| {
2459 let repository = this.repositories().get(&repository_id)?;
2460 Some(repository.update(cx, |repo, cx| repo.load_blob_content(oid, cx)))
2461 })?
2462 .context("missing repository")?
2463 .await?;
2464 Ok(proto::GetBlobContentResponse { content })
2465 }
2466
2467 async fn handle_open_unstaged_diff(
2468 this: Entity<Self>,
2469 request: TypedEnvelope<proto::OpenUnstagedDiff>,
2470 mut cx: AsyncApp,
2471 ) -> Result<proto::OpenUnstagedDiffResponse> {
2472 let buffer_id = BufferId::new(request.payload.buffer_id)?;
2473 let diff = this
2474 .update(&mut cx, |this, cx| {
2475 let buffer = this.buffer_store.read(cx).get(buffer_id)?;
2476 Some(this.open_unstaged_diff(buffer, cx))
2477 })?
2478 .context("missing buffer")?
2479 .await?;
2480 this.update(&mut cx, |this, _| {
2481 let shared_diffs = this
2482 .shared_diffs
2483 .entry(request.original_sender_id.unwrap_or(request.sender_id))
2484 .or_default();
2485 shared_diffs.entry(buffer_id).or_default().unstaged = Some(diff.clone());
2486 })?;
2487 let staged_text = diff.read_with(&cx, |diff, _| diff.base_text_string())?;
2488 Ok(proto::OpenUnstagedDiffResponse { staged_text })
2489 }
2490
2491 async fn handle_open_uncommitted_diff(
2492 this: Entity<Self>,
2493 request: TypedEnvelope<proto::OpenUncommittedDiff>,
2494 mut cx: AsyncApp,
2495 ) -> Result<proto::OpenUncommittedDiffResponse> {
2496 let buffer_id = BufferId::new(request.payload.buffer_id)?;
2497 let diff = this
2498 .update(&mut cx, |this, cx| {
2499 let buffer = this.buffer_store.read(cx).get(buffer_id)?;
2500 Some(this.open_uncommitted_diff(buffer, cx))
2501 })?
2502 .context("missing buffer")?
2503 .await?;
2504 this.update(&mut cx, |this, _| {
2505 let shared_diffs = this
2506 .shared_diffs
2507 .entry(request.original_sender_id.unwrap_or(request.sender_id))
2508 .or_default();
2509 shared_diffs.entry(buffer_id).or_default().uncommitted = Some(diff.clone());
2510 })?;
2511 diff.read_with(&cx, |diff, cx| {
2512 use proto::open_uncommitted_diff_response::Mode;
2513
2514 let unstaged_diff = diff.secondary_diff();
2515 let index_snapshot = unstaged_diff.and_then(|diff| {
2516 let diff = diff.read(cx);
2517 diff.base_text_exists().then(|| diff.base_text())
2518 });
2519
2520 let mode;
2521 let staged_text;
2522 let committed_text;
2523 if diff.base_text_exists() {
2524 let committed_snapshot = diff.base_text();
2525 committed_text = Some(committed_snapshot.text());
2526 if let Some(index_text) = index_snapshot {
2527 if index_text.remote_id() == committed_snapshot.remote_id() {
2528 mode = Mode::IndexMatchesHead;
2529 staged_text = None;
2530 } else {
2531 mode = Mode::IndexAndHead;
2532 staged_text = Some(index_text.text());
2533 }
2534 } else {
2535 mode = Mode::IndexAndHead;
2536 staged_text = None;
2537 }
2538 } else {
2539 mode = Mode::IndexAndHead;
2540 committed_text = None;
2541 staged_text = index_snapshot.as_ref().map(|buffer| buffer.text());
2542 }
2543
2544 proto::OpenUncommittedDiffResponse {
2545 committed_text,
2546 staged_text,
2547 mode: mode.into(),
2548 }
2549 })
2550 }
2551
2552 async fn handle_update_diff_bases(
2553 this: Entity<Self>,
2554 request: TypedEnvelope<proto::UpdateDiffBases>,
2555 mut cx: AsyncApp,
2556 ) -> Result<()> {
2557 let buffer_id = BufferId::new(request.payload.buffer_id)?;
2558 this.update(&mut cx, |this, cx| {
2559 if let Some(diff_state) = this.diffs.get_mut(&buffer_id)
2560 && let Some(buffer) = this.buffer_store.read(cx).get(buffer_id)
2561 {
2562 let buffer = buffer.read(cx).text_snapshot();
2563 diff_state.update(cx, |diff_state, cx| {
2564 diff_state.handle_base_texts_updated(buffer, request.payload, cx);
2565 })
2566 }
2567 })
2568 }
2569
2570 async fn handle_blame_buffer(
2571 this: Entity<Self>,
2572 envelope: TypedEnvelope<proto::BlameBuffer>,
2573 mut cx: AsyncApp,
2574 ) -> Result<proto::BlameBufferResponse> {
2575 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
2576 let version = deserialize_version(&envelope.payload.version);
2577 let buffer = this.read_with(&cx, |this, cx| {
2578 this.buffer_store.read(cx).get_existing(buffer_id)
2579 })??;
2580 buffer
2581 .update(&mut cx, |buffer, _| {
2582 buffer.wait_for_version(version.clone())
2583 })?
2584 .await?;
2585 let blame = this
2586 .update(&mut cx, |this, cx| {
2587 this.blame_buffer(&buffer, Some(version), cx)
2588 })?
2589 .await?;
2590 Ok(serialize_blame_buffer_response(blame))
2591 }
2592
2593 async fn handle_get_permalink_to_line(
2594 this: Entity<Self>,
2595 envelope: TypedEnvelope<proto::GetPermalinkToLine>,
2596 mut cx: AsyncApp,
2597 ) -> Result<proto::GetPermalinkToLineResponse> {
2598 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
2599 // let version = deserialize_version(&envelope.payload.version);
2600 let selection = {
2601 let proto_selection = envelope
2602 .payload
2603 .selection
2604 .context("no selection to get permalink for defined")?;
2605 proto_selection.start as u32..proto_selection.end as u32
2606 };
2607 let buffer = this.read_with(&cx, |this, cx| {
2608 this.buffer_store.read(cx).get_existing(buffer_id)
2609 })??;
2610 let permalink = this
2611 .update(&mut cx, |this, cx| {
2612 this.get_permalink_to_line(&buffer, selection, cx)
2613 })?
2614 .await?;
2615 Ok(proto::GetPermalinkToLineResponse {
2616 permalink: permalink.to_string(),
2617 })
2618 }
2619
2620 fn repository_for_request(
2621 this: &Entity<Self>,
2622 id: RepositoryId,
2623 cx: &mut AsyncApp,
2624 ) -> Result<Entity<Repository>> {
2625 this.read_with(cx, |this, _| {
2626 this.repositories
2627 .get(&id)
2628 .context("missing repository handle")
2629 .cloned()
2630 })?
2631 }
2632
2633 pub fn repo_snapshots(&self, cx: &App) -> HashMap<RepositoryId, RepositorySnapshot> {
2634 self.repositories
2635 .iter()
2636 .map(|(id, repo)| (*id, repo.read(cx).snapshot.clone()))
2637 .collect()
2638 }
2639
2640 fn process_updated_entries(
2641 &self,
2642 worktree: &Entity<Worktree>,
2643 updated_entries: &[(Arc<RelPath>, ProjectEntryId, PathChange)],
2644 cx: &mut App,
2645 ) -> Task<HashMap<Entity<Repository>, Vec<RepoPath>>> {
2646 let path_style = worktree.read(cx).path_style();
2647 let mut repo_paths = self
2648 .repositories
2649 .values()
2650 .map(|repo| (repo.read(cx).work_directory_abs_path.clone(), repo.clone()))
2651 .collect::<Vec<_>>();
2652 let mut entries: Vec<_> = updated_entries
2653 .iter()
2654 .map(|(path, _, _)| path.clone())
2655 .collect();
2656 entries.sort();
2657 let worktree = worktree.read(cx);
2658
2659 let entries = entries
2660 .into_iter()
2661 .map(|path| worktree.absolutize(&path))
2662 .collect::<Arc<[_]>>();
2663
2664 let executor = cx.background_executor().clone();
2665 cx.background_executor().spawn(async move {
2666 repo_paths.sort_by(|lhs, rhs| lhs.0.cmp(&rhs.0));
2667 let mut paths_by_git_repo = HashMap::<_, Vec<_>>::default();
2668 let mut tasks = FuturesOrdered::new();
2669 for (repo_path, repo) in repo_paths.into_iter().rev() {
2670 let entries = entries.clone();
2671 let task = executor.spawn(async move {
2672 // Find all repository paths that belong to this repo
2673 let mut ix = entries.partition_point(|path| path < &*repo_path);
2674 if ix == entries.len() {
2675 return None;
2676 };
2677
2678 let mut paths = Vec::new();
2679 // All paths prefixed by a given repo will constitute a continuous range.
2680 while let Some(path) = entries.get(ix)
2681 && let Some(repo_path) = RepositorySnapshot::abs_path_to_repo_path_inner(
2682 &repo_path, path, path_style,
2683 )
2684 {
2685 paths.push((repo_path, ix));
2686 ix += 1;
2687 }
2688 if paths.is_empty() {
2689 None
2690 } else {
2691 Some((repo, paths))
2692 }
2693 });
2694 tasks.push_back(task);
2695 }
2696
2697 // Now, let's filter out the "duplicate" entries that were processed by multiple distinct repos.
2698 let mut path_was_used = vec![false; entries.len()];
2699 let tasks = tasks.collect::<Vec<_>>().await;
2700 // Process tasks from the back: iterating backwards allows us to see more-specific paths first.
2701 // We always want to assign a path to it's innermost repository.
2702 for t in tasks {
2703 let Some((repo, paths)) = t else {
2704 continue;
2705 };
2706 let entry = paths_by_git_repo.entry(repo).or_default();
2707 for (repo_path, ix) in paths {
2708 if path_was_used[ix] {
2709 continue;
2710 }
2711 path_was_used[ix] = true;
2712 entry.push(repo_path);
2713 }
2714 }
2715
2716 paths_by_git_repo
2717 })
2718 }
2719}
2720
2721impl BufferGitState {
2722 fn new(_git_store: WeakEntity<GitStore>) -> Self {
2723 Self {
2724 unstaged_diff: Default::default(),
2725 uncommitted_diff: Default::default(),
2726 recalculate_diff_task: Default::default(),
2727 language: Default::default(),
2728 language_registry: Default::default(),
2729 recalculating_tx: postage::watch::channel_with(false).0,
2730 hunk_staging_operation_count: 0,
2731 hunk_staging_operation_count_as_of_write: 0,
2732 head_text: Default::default(),
2733 index_text: Default::default(),
2734 head_changed: Default::default(),
2735 index_changed: Default::default(),
2736 language_changed: Default::default(),
2737 conflict_updated_futures: Default::default(),
2738 conflict_set: Default::default(),
2739 reparse_conflict_markers_task: Default::default(),
2740 }
2741 }
2742
2743 fn buffer_language_changed(&mut self, buffer: Entity<Buffer>, cx: &mut Context<Self>) {
2744 self.language = buffer.read(cx).language().cloned();
2745 self.language_changed = true;
2746 let _ = self.recalculate_diffs(buffer.read(cx).text_snapshot(), cx);
2747 }
2748
2749 fn reparse_conflict_markers(
2750 &mut self,
2751 buffer: text::BufferSnapshot,
2752 cx: &mut Context<Self>,
2753 ) -> oneshot::Receiver<()> {
2754 let (tx, rx) = oneshot::channel();
2755
2756 let Some(conflict_set) = self
2757 .conflict_set
2758 .as_ref()
2759 .and_then(|conflict_set| conflict_set.upgrade())
2760 else {
2761 return rx;
2762 };
2763
2764 let old_snapshot = conflict_set.read_with(cx, |conflict_set, _| {
2765 if conflict_set.has_conflict {
2766 Some(conflict_set.snapshot())
2767 } else {
2768 None
2769 }
2770 });
2771
2772 if let Some(old_snapshot) = old_snapshot {
2773 self.conflict_updated_futures.push(tx);
2774 self.reparse_conflict_markers_task = Some(cx.spawn(async move |this, cx| {
2775 let (snapshot, changed_range) = cx
2776 .background_spawn(async move {
2777 let new_snapshot = ConflictSet::parse(&buffer);
2778 let changed_range = old_snapshot.compare(&new_snapshot, &buffer);
2779 (new_snapshot, changed_range)
2780 })
2781 .await;
2782 this.update(cx, |this, cx| {
2783 if let Some(conflict_set) = &this.conflict_set {
2784 conflict_set
2785 .update(cx, |conflict_set, cx| {
2786 conflict_set.set_snapshot(snapshot, changed_range, cx);
2787 })
2788 .ok();
2789 }
2790 let futures = std::mem::take(&mut this.conflict_updated_futures);
2791 for tx in futures {
2792 tx.send(()).ok();
2793 }
2794 })
2795 }))
2796 }
2797
2798 rx
2799 }
2800
2801 fn unstaged_diff(&self) -> Option<Entity<BufferDiff>> {
2802 self.unstaged_diff.as_ref().and_then(|set| set.upgrade())
2803 }
2804
2805 fn uncommitted_diff(&self) -> Option<Entity<BufferDiff>> {
2806 self.uncommitted_diff.as_ref().and_then(|set| set.upgrade())
2807 }
2808
2809 fn handle_base_texts_updated(
2810 &mut self,
2811 buffer: text::BufferSnapshot,
2812 message: proto::UpdateDiffBases,
2813 cx: &mut Context<Self>,
2814 ) {
2815 use proto::update_diff_bases::Mode;
2816
2817 let Some(mode) = Mode::from_i32(message.mode) else {
2818 return;
2819 };
2820
2821 let diff_bases_change = match mode {
2822 Mode::HeadOnly => DiffBasesChange::SetHead(message.committed_text),
2823 Mode::IndexOnly => DiffBasesChange::SetIndex(message.staged_text),
2824 Mode::IndexMatchesHead => DiffBasesChange::SetBoth(message.committed_text),
2825 Mode::IndexAndHead => DiffBasesChange::SetEach {
2826 index: message.staged_text,
2827 head: message.committed_text,
2828 },
2829 };
2830
2831 self.diff_bases_changed(buffer, Some(diff_bases_change), cx);
2832 }
2833
2834 pub fn wait_for_recalculation(&mut self) -> Option<impl Future<Output = ()> + use<>> {
2835 if *self.recalculating_tx.borrow() {
2836 let mut rx = self.recalculating_tx.subscribe();
2837 Some(async move {
2838 loop {
2839 let is_recalculating = rx.recv().await;
2840 if is_recalculating != Some(true) {
2841 break;
2842 }
2843 }
2844 })
2845 } else {
2846 None
2847 }
2848 }
2849
2850 fn diff_bases_changed(
2851 &mut self,
2852 buffer: text::BufferSnapshot,
2853 diff_bases_change: Option<DiffBasesChange>,
2854 cx: &mut Context<Self>,
2855 ) {
2856 match diff_bases_change {
2857 Some(DiffBasesChange::SetIndex(index)) => {
2858 self.index_text = index.map(|mut index| {
2859 text::LineEnding::normalize(&mut index);
2860 Arc::new(index)
2861 });
2862 self.index_changed = true;
2863 }
2864 Some(DiffBasesChange::SetHead(head)) => {
2865 self.head_text = head.map(|mut head| {
2866 text::LineEnding::normalize(&mut head);
2867 Arc::new(head)
2868 });
2869 self.head_changed = true;
2870 }
2871 Some(DiffBasesChange::SetBoth(text)) => {
2872 let text = text.map(|mut text| {
2873 text::LineEnding::normalize(&mut text);
2874 Arc::new(text)
2875 });
2876 self.head_text = text.clone();
2877 self.index_text = text;
2878 self.head_changed = true;
2879 self.index_changed = true;
2880 }
2881 Some(DiffBasesChange::SetEach { index, head }) => {
2882 self.index_text = index.map(|mut index| {
2883 text::LineEnding::normalize(&mut index);
2884 Arc::new(index)
2885 });
2886 self.index_changed = true;
2887 self.head_text = head.map(|mut head| {
2888 text::LineEnding::normalize(&mut head);
2889 Arc::new(head)
2890 });
2891 self.head_changed = true;
2892 }
2893 None => {}
2894 }
2895
2896 self.recalculate_diffs(buffer, cx)
2897 }
2898
2899 fn recalculate_diffs(&mut self, buffer: text::BufferSnapshot, cx: &mut Context<Self>) {
2900 *self.recalculating_tx.borrow_mut() = true;
2901
2902 let language = self.language.clone();
2903 let language_registry = self.language_registry.clone();
2904 let unstaged_diff = self.unstaged_diff();
2905 let uncommitted_diff = self.uncommitted_diff();
2906 let head = self.head_text.clone();
2907 let index = self.index_text.clone();
2908 let index_changed = self.index_changed;
2909 let head_changed = self.head_changed;
2910 let language_changed = self.language_changed;
2911 let prev_hunk_staging_operation_count = self.hunk_staging_operation_count_as_of_write;
2912 let index_matches_head = match (self.index_text.as_ref(), self.head_text.as_ref()) {
2913 (Some(index), Some(head)) => Arc::ptr_eq(index, head),
2914 (None, None) => true,
2915 _ => false,
2916 };
2917 self.recalculate_diff_task = Some(cx.spawn(async move |this, cx| {
2918 log::debug!(
2919 "start recalculating diffs for buffer {}",
2920 buffer.remote_id()
2921 );
2922
2923 let mut new_unstaged_diff = None;
2924 if let Some(unstaged_diff) = &unstaged_diff {
2925 new_unstaged_diff = Some(
2926 BufferDiff::update_diff(
2927 unstaged_diff.clone(),
2928 buffer.clone(),
2929 index,
2930 index_changed,
2931 language_changed,
2932 language.clone(),
2933 language_registry.clone(),
2934 cx,
2935 )
2936 .await?,
2937 );
2938 }
2939
2940 let mut new_uncommitted_diff = None;
2941 if let Some(uncommitted_diff) = &uncommitted_diff {
2942 new_uncommitted_diff = if index_matches_head {
2943 new_unstaged_diff.clone()
2944 } else {
2945 Some(
2946 BufferDiff::update_diff(
2947 uncommitted_diff.clone(),
2948 buffer.clone(),
2949 head,
2950 head_changed,
2951 language_changed,
2952 language.clone(),
2953 language_registry.clone(),
2954 cx,
2955 )
2956 .await?,
2957 )
2958 }
2959 }
2960
2961 let cancel = this.update(cx, |this, _| {
2962 // This checks whether all pending stage/unstage operations
2963 // have quiesced (i.e. both the corresponding write and the
2964 // read of that write have completed). If not, then we cancel
2965 // this recalculation attempt to avoid invalidating pending
2966 // state too quickly; another recalculation will come along
2967 // later and clear the pending state once the state of the index has settled.
2968 if this.hunk_staging_operation_count > prev_hunk_staging_operation_count {
2969 *this.recalculating_tx.borrow_mut() = false;
2970 true
2971 } else {
2972 false
2973 }
2974 })?;
2975 if cancel {
2976 log::debug!(
2977 concat!(
2978 "aborting recalculating diffs for buffer {}",
2979 "due to subsequent hunk operations",
2980 ),
2981 buffer.remote_id()
2982 );
2983 return Ok(());
2984 }
2985
2986 let unstaged_changed_range = if let Some((unstaged_diff, new_unstaged_diff)) =
2987 unstaged_diff.as_ref().zip(new_unstaged_diff.clone())
2988 {
2989 unstaged_diff.update(cx, |diff, cx| {
2990 if language_changed {
2991 diff.language_changed(cx);
2992 }
2993 diff.set_snapshot(new_unstaged_diff, &buffer, cx)
2994 })?
2995 } else {
2996 None
2997 };
2998
2999 if let Some((uncommitted_diff, new_uncommitted_diff)) =
3000 uncommitted_diff.as_ref().zip(new_uncommitted_diff.clone())
3001 {
3002 uncommitted_diff.update(cx, |diff, cx| {
3003 if language_changed {
3004 diff.language_changed(cx);
3005 }
3006 diff.set_snapshot_with_secondary(
3007 new_uncommitted_diff,
3008 &buffer,
3009 unstaged_changed_range,
3010 true,
3011 cx,
3012 );
3013 })?;
3014 }
3015
3016 log::debug!(
3017 "finished recalculating diffs for buffer {}",
3018 buffer.remote_id()
3019 );
3020
3021 if let Some(this) = this.upgrade() {
3022 this.update(cx, |this, _| {
3023 this.index_changed = false;
3024 this.head_changed = false;
3025 this.language_changed = false;
3026 *this.recalculating_tx.borrow_mut() = false;
3027 })?;
3028 }
3029
3030 Ok(())
3031 }));
3032 }
3033}
3034
3035fn make_remote_delegate(
3036 this: Entity<GitStore>,
3037 project_id: u64,
3038 repository_id: RepositoryId,
3039 askpass_id: u64,
3040 cx: &mut AsyncApp,
3041) -> AskPassDelegate {
3042 AskPassDelegate::new(cx, move |prompt, tx, cx| {
3043 this.update(cx, |this, cx| {
3044 let Some((client, _)) = this.downstream_client() else {
3045 return;
3046 };
3047 let response = client.request(proto::AskPassRequest {
3048 project_id,
3049 repository_id: repository_id.to_proto(),
3050 askpass_id,
3051 prompt,
3052 });
3053 cx.spawn(async move |_, _| {
3054 let mut response = response.await?.response;
3055 tx.send(EncryptedPassword::try_from(response.as_ref())?)
3056 .ok();
3057 response.zeroize();
3058 anyhow::Ok(())
3059 })
3060 .detach_and_log_err(cx);
3061 })
3062 .log_err();
3063 })
3064}
3065
3066impl RepositoryId {
3067 pub fn to_proto(self) -> u64 {
3068 self.0
3069 }
3070
3071 pub fn from_proto(id: u64) -> Self {
3072 RepositoryId(id)
3073 }
3074}
3075
3076impl RepositorySnapshot {
3077 fn empty(id: RepositoryId, work_directory_abs_path: Arc<Path>, path_style: PathStyle) -> Self {
3078 Self {
3079 id,
3080 statuses_by_path: Default::default(),
3081 work_directory_abs_path,
3082 branch: None,
3083 head_commit: None,
3084 scan_id: 0,
3085 merge: Default::default(),
3086 remote_origin_url: None,
3087 remote_upstream_url: None,
3088 stash_entries: Default::default(),
3089 path_style,
3090 }
3091 }
3092
3093 fn initial_update(&self, project_id: u64) -> proto::UpdateRepository {
3094 proto::UpdateRepository {
3095 branch_summary: self.branch.as_ref().map(branch_to_proto),
3096 head_commit_details: self.head_commit.as_ref().map(commit_details_to_proto),
3097 updated_statuses: self
3098 .statuses_by_path
3099 .iter()
3100 .map(|entry| entry.to_proto())
3101 .collect(),
3102 removed_statuses: Default::default(),
3103 current_merge_conflicts: self
3104 .merge
3105 .conflicted_paths
3106 .iter()
3107 .map(|repo_path| repo_path.to_proto())
3108 .collect(),
3109 merge_message: self.merge.message.as_ref().map(|msg| msg.to_string()),
3110 project_id,
3111 id: self.id.to_proto(),
3112 abs_path: self.work_directory_abs_path.to_string_lossy().into_owned(),
3113 entry_ids: vec![self.id.to_proto()],
3114 scan_id: self.scan_id,
3115 is_last_update: true,
3116 stash_entries: self
3117 .stash_entries
3118 .entries
3119 .iter()
3120 .map(stash_to_proto)
3121 .collect(),
3122 }
3123 }
3124
3125 fn build_update(&self, old: &Self, project_id: u64) -> proto::UpdateRepository {
3126 let mut updated_statuses: Vec<proto::StatusEntry> = Vec::new();
3127 let mut removed_statuses: Vec<String> = Vec::new();
3128
3129 let mut new_statuses = self.statuses_by_path.iter().peekable();
3130 let mut old_statuses = old.statuses_by_path.iter().peekable();
3131
3132 let mut current_new_entry = new_statuses.next();
3133 let mut current_old_entry = old_statuses.next();
3134 loop {
3135 match (current_new_entry, current_old_entry) {
3136 (Some(new_entry), Some(old_entry)) => {
3137 match new_entry.repo_path.cmp(&old_entry.repo_path) {
3138 Ordering::Less => {
3139 updated_statuses.push(new_entry.to_proto());
3140 current_new_entry = new_statuses.next();
3141 }
3142 Ordering::Equal => {
3143 if new_entry.status != old_entry.status {
3144 updated_statuses.push(new_entry.to_proto());
3145 }
3146 current_old_entry = old_statuses.next();
3147 current_new_entry = new_statuses.next();
3148 }
3149 Ordering::Greater => {
3150 removed_statuses.push(old_entry.repo_path.to_proto());
3151 current_old_entry = old_statuses.next();
3152 }
3153 }
3154 }
3155 (None, Some(old_entry)) => {
3156 removed_statuses.push(old_entry.repo_path.to_proto());
3157 current_old_entry = old_statuses.next();
3158 }
3159 (Some(new_entry), None) => {
3160 updated_statuses.push(new_entry.to_proto());
3161 current_new_entry = new_statuses.next();
3162 }
3163 (None, None) => break,
3164 }
3165 }
3166
3167 proto::UpdateRepository {
3168 branch_summary: self.branch.as_ref().map(branch_to_proto),
3169 head_commit_details: self.head_commit.as_ref().map(commit_details_to_proto),
3170 updated_statuses,
3171 removed_statuses,
3172 current_merge_conflicts: self
3173 .merge
3174 .conflicted_paths
3175 .iter()
3176 .map(|path| path.to_proto())
3177 .collect(),
3178 merge_message: self.merge.message.as_ref().map(|msg| msg.to_string()),
3179 project_id,
3180 id: self.id.to_proto(),
3181 abs_path: self.work_directory_abs_path.to_string_lossy().into_owned(),
3182 entry_ids: vec![],
3183 scan_id: self.scan_id,
3184 is_last_update: true,
3185 stash_entries: self
3186 .stash_entries
3187 .entries
3188 .iter()
3189 .map(stash_to_proto)
3190 .collect(),
3191 }
3192 }
3193
3194 pub fn status(&self) -> impl Iterator<Item = StatusEntry> + '_ {
3195 self.statuses_by_path.iter().cloned()
3196 }
3197
3198 pub fn status_summary(&self) -> GitSummary {
3199 self.statuses_by_path.summary().item_summary
3200 }
3201
3202 pub fn status_for_path(&self, path: &RepoPath) -> Option<StatusEntry> {
3203 self.statuses_by_path
3204 .get(&PathKey(path.as_ref().clone()), ())
3205 .cloned()
3206 }
3207
3208 pub fn abs_path_to_repo_path(&self, abs_path: &Path) -> Option<RepoPath> {
3209 Self::abs_path_to_repo_path_inner(&self.work_directory_abs_path, abs_path, self.path_style)
3210 }
3211
3212 fn repo_path_to_abs_path(&self, repo_path: &RepoPath) -> PathBuf {
3213 self.path_style
3214 .join(&self.work_directory_abs_path, repo_path.as_std_path())
3215 .unwrap()
3216 .into()
3217 }
3218
3219 #[inline]
3220 fn abs_path_to_repo_path_inner(
3221 work_directory_abs_path: &Path,
3222 abs_path: &Path,
3223 path_style: PathStyle,
3224 ) -> Option<RepoPath> {
3225 let rel_path = path_style.strip_prefix(abs_path, work_directory_abs_path)?;
3226 Some(RepoPath::from_rel_path(&rel_path))
3227 }
3228
3229 pub fn had_conflict_on_last_merge_head_change(&self, repo_path: &RepoPath) -> bool {
3230 self.merge.conflicted_paths.contains(repo_path)
3231 }
3232
3233 pub fn has_conflict(&self, repo_path: &RepoPath) -> bool {
3234 let had_conflict_on_last_merge_head_change =
3235 self.merge.conflicted_paths.contains(repo_path);
3236 let has_conflict_currently = self
3237 .status_for_path(repo_path)
3238 .is_some_and(|entry| entry.status.is_conflicted());
3239 had_conflict_on_last_merge_head_change || has_conflict_currently
3240 }
3241
3242 /// This is the name that will be displayed in the repository selector for this repository.
3243 pub fn display_name(&self) -> SharedString {
3244 self.work_directory_abs_path
3245 .file_name()
3246 .unwrap_or_default()
3247 .to_string_lossy()
3248 .to_string()
3249 .into()
3250 }
3251}
3252
3253pub fn stash_to_proto(entry: &StashEntry) -> proto::StashEntry {
3254 proto::StashEntry {
3255 oid: entry.oid.as_bytes().to_vec(),
3256 message: entry.message.clone(),
3257 branch: entry.branch.clone(),
3258 index: entry.index as u64,
3259 timestamp: entry.timestamp,
3260 }
3261}
3262
3263pub fn proto_to_stash(entry: &proto::StashEntry) -> Result<StashEntry> {
3264 Ok(StashEntry {
3265 oid: Oid::from_bytes(&entry.oid)?,
3266 message: entry.message.clone(),
3267 index: entry.index as usize,
3268 branch: entry.branch.clone(),
3269 timestamp: entry.timestamp,
3270 })
3271}
3272
3273impl MergeDetails {
3274 async fn load(
3275 backend: &Arc<dyn GitRepository>,
3276 status: &SumTree<StatusEntry>,
3277 prev_snapshot: &RepositorySnapshot,
3278 ) -> Result<(MergeDetails, bool)> {
3279 log::debug!("load merge details");
3280 let message = backend.merge_message().await;
3281 let heads = backend
3282 .revparse_batch(vec![
3283 "MERGE_HEAD".into(),
3284 "CHERRY_PICK_HEAD".into(),
3285 "REBASE_HEAD".into(),
3286 "REVERT_HEAD".into(),
3287 "APPLY_HEAD".into(),
3288 ])
3289 .await
3290 .log_err()
3291 .unwrap_or_default()
3292 .into_iter()
3293 .map(|opt| opt.map(SharedString::from))
3294 .collect::<Vec<_>>();
3295 let merge_heads_changed = heads != prev_snapshot.merge.heads;
3296 let conflicted_paths = if merge_heads_changed {
3297 let current_conflicted_paths = TreeSet::from_ordered_entries(
3298 status
3299 .iter()
3300 .filter(|entry| entry.status.is_conflicted())
3301 .map(|entry| entry.repo_path.clone()),
3302 );
3303
3304 // It can happen that we run a scan while a lengthy merge is in progress
3305 // that will eventually result in conflicts, but before those conflicts
3306 // are reported by `git status`. Since for the moment we only care about
3307 // the merge heads state for the purposes of tracking conflicts, don't update
3308 // this state until we see some conflicts.
3309 if heads.iter().any(Option::is_some)
3310 && !prev_snapshot.merge.heads.iter().any(Option::is_some)
3311 && current_conflicted_paths.is_empty()
3312 {
3313 log::debug!("not updating merge heads because no conflicts found");
3314 return Ok((
3315 MergeDetails {
3316 message: message.map(SharedString::from),
3317 ..prev_snapshot.merge.clone()
3318 },
3319 false,
3320 ));
3321 }
3322
3323 current_conflicted_paths
3324 } else {
3325 prev_snapshot.merge.conflicted_paths.clone()
3326 };
3327 let details = MergeDetails {
3328 conflicted_paths,
3329 message: message.map(SharedString::from),
3330 heads,
3331 };
3332 Ok((details, merge_heads_changed))
3333 }
3334}
3335
3336impl Repository {
3337 pub fn snapshot(&self) -> RepositorySnapshot {
3338 self.snapshot.clone()
3339 }
3340
3341 pub fn pending_ops(&self) -> impl Iterator<Item = PendingOps> + '_ {
3342 self.pending_ops.iter().cloned()
3343 }
3344
3345 pub fn pending_ops_summary(&self) -> PathSummary<PendingOpsSummary> {
3346 self.pending_ops.summary().clone()
3347 }
3348
3349 pub fn pending_ops_for_path(&self, path: &RepoPath) -> Option<PendingOps> {
3350 self.pending_ops
3351 .get(&PathKey(path.as_ref().clone()), ())
3352 .cloned()
3353 }
3354
3355 fn local(
3356 id: RepositoryId,
3357 work_directory_abs_path: Arc<Path>,
3358 dot_git_abs_path: Arc<Path>,
3359 repository_dir_abs_path: Arc<Path>,
3360 common_dir_abs_path: Arc<Path>,
3361 project_environment: WeakEntity<ProjectEnvironment>,
3362 fs: Arc<dyn Fs>,
3363 git_store: WeakEntity<GitStore>,
3364 cx: &mut Context<Self>,
3365 ) -> Self {
3366 let snapshot =
3367 RepositorySnapshot::empty(id, work_directory_abs_path.clone(), PathStyle::local());
3368 Repository {
3369 this: cx.weak_entity(),
3370 git_store,
3371 snapshot,
3372 pending_ops: Default::default(),
3373 commit_message_buffer: None,
3374 askpass_delegates: Default::default(),
3375 paths_needing_status_update: Default::default(),
3376 latest_askpass_id: 0,
3377 job_sender: Repository::spawn_local_git_worker(
3378 work_directory_abs_path,
3379 dot_git_abs_path,
3380 repository_dir_abs_path,
3381 common_dir_abs_path,
3382 project_environment,
3383 fs,
3384 cx,
3385 ),
3386 job_id: 0,
3387 active_jobs: Default::default(),
3388 }
3389 }
3390
3391 fn remote(
3392 id: RepositoryId,
3393 work_directory_abs_path: Arc<Path>,
3394 path_style: PathStyle,
3395 project_id: ProjectId,
3396 client: AnyProtoClient,
3397 git_store: WeakEntity<GitStore>,
3398 cx: &mut Context<Self>,
3399 ) -> Self {
3400 let snapshot = RepositorySnapshot::empty(id, work_directory_abs_path, path_style);
3401 Self {
3402 this: cx.weak_entity(),
3403 snapshot,
3404 commit_message_buffer: None,
3405 git_store,
3406 pending_ops: Default::default(),
3407 paths_needing_status_update: Default::default(),
3408 job_sender: Self::spawn_remote_git_worker(project_id, client, cx),
3409 askpass_delegates: Default::default(),
3410 latest_askpass_id: 0,
3411 active_jobs: Default::default(),
3412 job_id: 0,
3413 }
3414 }
3415
3416 pub fn git_store(&self) -> Option<Entity<GitStore>> {
3417 self.git_store.upgrade()
3418 }
3419
3420 fn reload_buffer_diff_bases(&mut self, cx: &mut Context<Self>) {
3421 let this = cx.weak_entity();
3422 let git_store = self.git_store.clone();
3423 let _ = self.send_keyed_job(
3424 Some(GitJobKey::ReloadBufferDiffBases),
3425 None,
3426 |state, mut cx| async move {
3427 let RepositoryState::Local { backend, .. } = state else {
3428 log::error!("tried to recompute diffs for a non-local repository");
3429 return Ok(());
3430 };
3431
3432 let Some(this) = this.upgrade() else {
3433 return Ok(());
3434 };
3435
3436 let repo_diff_state_updates = this.update(&mut cx, |this, cx| {
3437 git_store.update(cx, |git_store, cx| {
3438 git_store
3439 .diffs
3440 .iter()
3441 .filter_map(|(buffer_id, diff_state)| {
3442 let buffer_store = git_store.buffer_store.read(cx);
3443 let buffer = buffer_store.get(*buffer_id)?;
3444 let file = File::from_dyn(buffer.read(cx).file())?;
3445 let abs_path = file.worktree.read(cx).absolutize(&file.path);
3446 let repo_path = this.abs_path_to_repo_path(&abs_path)?;
3447 log::debug!(
3448 "start reload diff bases for repo path {}",
3449 repo_path.as_unix_str()
3450 );
3451 diff_state.update(cx, |diff_state, _| {
3452 let has_unstaged_diff = diff_state
3453 .unstaged_diff
3454 .as_ref()
3455 .is_some_and(|diff| diff.is_upgradable());
3456 let has_uncommitted_diff = diff_state
3457 .uncommitted_diff
3458 .as_ref()
3459 .is_some_and(|set| set.is_upgradable());
3460
3461 Some((
3462 buffer,
3463 repo_path,
3464 has_unstaged_diff.then(|| diff_state.index_text.clone()),
3465 has_uncommitted_diff.then(|| diff_state.head_text.clone()),
3466 ))
3467 })
3468 })
3469 .collect::<Vec<_>>()
3470 })
3471 })??;
3472
3473 let buffer_diff_base_changes = cx
3474 .background_spawn(async move {
3475 let mut changes = Vec::new();
3476 for (buffer, repo_path, current_index_text, current_head_text) in
3477 &repo_diff_state_updates
3478 {
3479 let index_text = if current_index_text.is_some() {
3480 backend.load_index_text(repo_path.clone()).await
3481 } else {
3482 None
3483 };
3484 let head_text = if current_head_text.is_some() {
3485 backend.load_committed_text(repo_path.clone()).await
3486 } else {
3487 None
3488 };
3489
3490 let change =
3491 match (current_index_text.as_ref(), current_head_text.as_ref()) {
3492 (Some(current_index), Some(current_head)) => {
3493 let index_changed =
3494 index_text.as_ref() != current_index.as_deref();
3495 let head_changed =
3496 head_text.as_ref() != current_head.as_deref();
3497 if index_changed && head_changed {
3498 if index_text == head_text {
3499 Some(DiffBasesChange::SetBoth(head_text))
3500 } else {
3501 Some(DiffBasesChange::SetEach {
3502 index: index_text,
3503 head: head_text,
3504 })
3505 }
3506 } else if index_changed {
3507 Some(DiffBasesChange::SetIndex(index_text))
3508 } else if head_changed {
3509 Some(DiffBasesChange::SetHead(head_text))
3510 } else {
3511 None
3512 }
3513 }
3514 (Some(current_index), None) => {
3515 let index_changed =
3516 index_text.as_ref() != current_index.as_deref();
3517 index_changed
3518 .then_some(DiffBasesChange::SetIndex(index_text))
3519 }
3520 (None, Some(current_head)) => {
3521 let head_changed =
3522 head_text.as_ref() != current_head.as_deref();
3523 head_changed.then_some(DiffBasesChange::SetHead(head_text))
3524 }
3525 (None, None) => None,
3526 };
3527
3528 changes.push((buffer.clone(), change))
3529 }
3530 changes
3531 })
3532 .await;
3533
3534 git_store.update(&mut cx, |git_store, cx| {
3535 for (buffer, diff_bases_change) in buffer_diff_base_changes {
3536 let buffer_snapshot = buffer.read(cx).text_snapshot();
3537 let buffer_id = buffer_snapshot.remote_id();
3538 let Some(diff_state) = git_store.diffs.get(&buffer_id) else {
3539 continue;
3540 };
3541
3542 let downstream_client = git_store.downstream_client();
3543 diff_state.update(cx, |diff_state, cx| {
3544 use proto::update_diff_bases::Mode;
3545
3546 if let Some((diff_bases_change, (client, project_id))) =
3547 diff_bases_change.clone().zip(downstream_client)
3548 {
3549 let (staged_text, committed_text, mode) = match diff_bases_change {
3550 DiffBasesChange::SetIndex(index) => {
3551 (index, None, Mode::IndexOnly)
3552 }
3553 DiffBasesChange::SetHead(head) => (None, head, Mode::HeadOnly),
3554 DiffBasesChange::SetEach { index, head } => {
3555 (index, head, Mode::IndexAndHead)
3556 }
3557 DiffBasesChange::SetBoth(text) => {
3558 (None, text, Mode::IndexMatchesHead)
3559 }
3560 };
3561 client
3562 .send(proto::UpdateDiffBases {
3563 project_id: project_id.to_proto(),
3564 buffer_id: buffer_id.to_proto(),
3565 staged_text,
3566 committed_text,
3567 mode: mode as i32,
3568 })
3569 .log_err();
3570 }
3571
3572 diff_state.diff_bases_changed(buffer_snapshot, diff_bases_change, cx);
3573 });
3574 }
3575 })
3576 },
3577 );
3578 }
3579
3580 pub fn send_job<F, Fut, R>(
3581 &mut self,
3582 status: Option<SharedString>,
3583 job: F,
3584 ) -> oneshot::Receiver<R>
3585 where
3586 F: FnOnce(RepositoryState, AsyncApp) -> Fut + 'static,
3587 Fut: Future<Output = R> + 'static,
3588 R: Send + 'static,
3589 {
3590 self.send_keyed_job(None, status, job)
3591 }
3592
3593 fn send_keyed_job<F, Fut, R>(
3594 &mut self,
3595 key: Option<GitJobKey>,
3596 status: Option<SharedString>,
3597 job: F,
3598 ) -> oneshot::Receiver<R>
3599 where
3600 F: FnOnce(RepositoryState, AsyncApp) -> Fut + 'static,
3601 Fut: Future<Output = R> + 'static,
3602 R: Send + 'static,
3603 {
3604 let (result_tx, result_rx) = futures::channel::oneshot::channel();
3605 let job_id = post_inc(&mut self.job_id);
3606 let this = self.this.clone();
3607 self.job_sender
3608 .unbounded_send(GitJob {
3609 key,
3610 job: Box::new(move |state, cx: &mut AsyncApp| {
3611 let job = job(state, cx.clone());
3612 cx.spawn(async move |cx| {
3613 if let Some(s) = status.clone() {
3614 this.update(cx, |this, cx| {
3615 this.active_jobs.insert(
3616 job_id,
3617 JobInfo {
3618 start: Instant::now(),
3619 message: s.clone(),
3620 },
3621 );
3622
3623 cx.notify();
3624 })
3625 .ok();
3626 }
3627 let result = job.await;
3628
3629 this.update(cx, |this, cx| {
3630 this.active_jobs.remove(&job_id);
3631 cx.notify();
3632 })
3633 .ok();
3634
3635 result_tx.send(result).ok();
3636 })
3637 }),
3638 })
3639 .ok();
3640 result_rx
3641 }
3642
3643 pub fn set_as_active_repository(&self, cx: &mut Context<Self>) {
3644 let Some(git_store) = self.git_store.upgrade() else {
3645 return;
3646 };
3647 let entity = cx.entity();
3648 git_store.update(cx, |git_store, cx| {
3649 let Some((&id, _)) = git_store
3650 .repositories
3651 .iter()
3652 .find(|(_, handle)| *handle == &entity)
3653 else {
3654 return;
3655 };
3656 git_store.active_repo_id = Some(id);
3657 cx.emit(GitStoreEvent::ActiveRepositoryChanged(Some(id)));
3658 });
3659 }
3660
3661 pub fn cached_status(&self) -> impl '_ + Iterator<Item = StatusEntry> {
3662 self.snapshot.status()
3663 }
3664
3665 pub fn cached_stash(&self) -> GitStash {
3666 self.snapshot.stash_entries.clone()
3667 }
3668
3669 pub fn repo_path_to_project_path(&self, path: &RepoPath, cx: &App) -> Option<ProjectPath> {
3670 let git_store = self.git_store.upgrade()?;
3671 let worktree_store = git_store.read(cx).worktree_store.read(cx);
3672 let abs_path = self.snapshot.repo_path_to_abs_path(path);
3673 let abs_path = SanitizedPath::new(&abs_path);
3674 let (worktree, relative_path) = worktree_store.find_worktree(abs_path, cx)?;
3675 Some(ProjectPath {
3676 worktree_id: worktree.read(cx).id(),
3677 path: relative_path,
3678 })
3679 }
3680
3681 pub fn project_path_to_repo_path(&self, path: &ProjectPath, cx: &App) -> Option<RepoPath> {
3682 let git_store = self.git_store.upgrade()?;
3683 let worktree_store = git_store.read(cx).worktree_store.read(cx);
3684 let abs_path = worktree_store.absolutize(path, cx)?;
3685 self.snapshot.abs_path_to_repo_path(&abs_path)
3686 }
3687
3688 pub fn contains_sub_repo(&self, other: &Entity<Self>, cx: &App) -> bool {
3689 other
3690 .read(cx)
3691 .snapshot
3692 .work_directory_abs_path
3693 .starts_with(&self.snapshot.work_directory_abs_path)
3694 }
3695
3696 pub fn open_commit_buffer(
3697 &mut self,
3698 languages: Option<Arc<LanguageRegistry>>,
3699 buffer_store: Entity<BufferStore>,
3700 cx: &mut Context<Self>,
3701 ) -> Task<Result<Entity<Buffer>>> {
3702 let id = self.id;
3703 if let Some(buffer) = self.commit_message_buffer.clone() {
3704 return Task::ready(Ok(buffer));
3705 }
3706 let this = cx.weak_entity();
3707
3708 let rx = self.send_job(None, move |state, mut cx| async move {
3709 let Some(this) = this.upgrade() else {
3710 bail!("git store was dropped");
3711 };
3712 match state {
3713 RepositoryState::Local { .. } => {
3714 this.update(&mut cx, |_, cx| {
3715 Self::open_local_commit_buffer(languages, buffer_store, cx)
3716 })?
3717 .await
3718 }
3719 RepositoryState::Remote { project_id, client } => {
3720 let request = client.request(proto::OpenCommitMessageBuffer {
3721 project_id: project_id.0,
3722 repository_id: id.to_proto(),
3723 });
3724 let response = request.await.context("requesting to open commit buffer")?;
3725 let buffer_id = BufferId::new(response.buffer_id)?;
3726 let buffer = buffer_store
3727 .update(&mut cx, |buffer_store, cx| {
3728 buffer_store.wait_for_remote_buffer(buffer_id, cx)
3729 })?
3730 .await?;
3731 if let Some(language_registry) = languages {
3732 let git_commit_language =
3733 language_registry.language_for_name("Git Commit").await?;
3734 buffer.update(&mut cx, |buffer, cx| {
3735 buffer.set_language(Some(git_commit_language), cx);
3736 })?;
3737 }
3738 this.update(&mut cx, |this, _| {
3739 this.commit_message_buffer = Some(buffer.clone());
3740 })?;
3741 Ok(buffer)
3742 }
3743 }
3744 });
3745
3746 cx.spawn(|_, _: &mut AsyncApp| async move { rx.await? })
3747 }
3748
3749 fn open_local_commit_buffer(
3750 language_registry: Option<Arc<LanguageRegistry>>,
3751 buffer_store: Entity<BufferStore>,
3752 cx: &mut Context<Self>,
3753 ) -> Task<Result<Entity<Buffer>>> {
3754 cx.spawn(async move |repository, cx| {
3755 let buffer = buffer_store
3756 .update(cx, |buffer_store, cx| buffer_store.create_buffer(false, cx))?
3757 .await?;
3758
3759 if let Some(language_registry) = language_registry {
3760 let git_commit_language = language_registry.language_for_name("Git Commit").await?;
3761 buffer.update(cx, |buffer, cx| {
3762 buffer.set_language(Some(git_commit_language), cx);
3763 })?;
3764 }
3765
3766 repository.update(cx, |repository, _| {
3767 repository.commit_message_buffer = Some(buffer.clone());
3768 })?;
3769 Ok(buffer)
3770 })
3771 }
3772
3773 pub fn checkout_files(
3774 &mut self,
3775 commit: &str,
3776 paths: Vec<RepoPath>,
3777 cx: &mut Context<Self>,
3778 ) -> Task<Result<()>> {
3779 let commit = commit.to_string();
3780 let id = self.id;
3781
3782 self.spawn_job_with_tracking(
3783 paths.clone(),
3784 pending_op::GitStatus::Reverted,
3785 cx,
3786 async move |this, cx| {
3787 this.update(cx, |this, _cx| {
3788 this.send_job(
3789 Some(format!("git checkout {}", commit).into()),
3790 move |git_repo, _| async move {
3791 match git_repo {
3792 RepositoryState::Local {
3793 backend,
3794 environment,
3795 ..
3796 } => {
3797 backend
3798 .checkout_files(commit, paths, environment.clone())
3799 .await
3800 }
3801 RepositoryState::Remote { project_id, client } => {
3802 client
3803 .request(proto::GitCheckoutFiles {
3804 project_id: project_id.0,
3805 repository_id: id.to_proto(),
3806 commit,
3807 paths: paths
3808 .into_iter()
3809 .map(|p| p.to_proto())
3810 .collect(),
3811 })
3812 .await?;
3813
3814 Ok(())
3815 }
3816 }
3817 },
3818 )
3819 })?
3820 .await?
3821 },
3822 )
3823 }
3824
3825 pub fn reset(
3826 &mut self,
3827 commit: String,
3828 reset_mode: ResetMode,
3829 _cx: &mut App,
3830 ) -> oneshot::Receiver<Result<()>> {
3831 let id = self.id;
3832
3833 self.send_job(None, move |git_repo, _| async move {
3834 match git_repo {
3835 RepositoryState::Local {
3836 backend,
3837 environment,
3838 ..
3839 } => backend.reset(commit, reset_mode, environment).await,
3840 RepositoryState::Remote { project_id, client } => {
3841 client
3842 .request(proto::GitReset {
3843 project_id: project_id.0,
3844 repository_id: id.to_proto(),
3845 commit,
3846 mode: match reset_mode {
3847 ResetMode::Soft => git_reset::ResetMode::Soft.into(),
3848 ResetMode::Mixed => git_reset::ResetMode::Mixed.into(),
3849 },
3850 })
3851 .await?;
3852
3853 Ok(())
3854 }
3855 }
3856 })
3857 }
3858
3859 pub fn show(&mut self, commit: String) -> oneshot::Receiver<Result<CommitDetails>> {
3860 let id = self.id;
3861 self.send_job(None, move |git_repo, _cx| async move {
3862 match git_repo {
3863 RepositoryState::Local { backend, .. } => backend.show(commit).await,
3864 RepositoryState::Remote { project_id, client } => {
3865 let resp = client
3866 .request(proto::GitShow {
3867 project_id: project_id.0,
3868 repository_id: id.to_proto(),
3869 commit,
3870 })
3871 .await?;
3872
3873 Ok(CommitDetails {
3874 sha: resp.sha.into(),
3875 message: resp.message.into(),
3876 commit_timestamp: resp.commit_timestamp,
3877 author_email: resp.author_email.into(),
3878 author_name: resp.author_name.into(),
3879 })
3880 }
3881 }
3882 })
3883 }
3884
3885 pub fn load_commit_diff(&mut self, commit: String) -> oneshot::Receiver<Result<CommitDiff>> {
3886 let id = self.id;
3887 self.send_job(None, move |git_repo, cx| async move {
3888 match git_repo {
3889 RepositoryState::Local { backend, .. } => backend.load_commit(commit, cx).await,
3890 RepositoryState::Remote {
3891 client, project_id, ..
3892 } => {
3893 let response = client
3894 .request(proto::LoadCommitDiff {
3895 project_id: project_id.0,
3896 repository_id: id.to_proto(),
3897 commit,
3898 })
3899 .await?;
3900 Ok(CommitDiff {
3901 files: response
3902 .files
3903 .into_iter()
3904 .map(|file| {
3905 Ok(CommitFile {
3906 path: RepoPath::from_proto(&file.path)?,
3907 old_text: file.old_text,
3908 new_text: file.new_text,
3909 })
3910 })
3911 .collect::<Result<Vec<_>>>()?,
3912 })
3913 }
3914 }
3915 })
3916 }
3917
3918 fn buffer_store(&self, cx: &App) -> Option<Entity<BufferStore>> {
3919 Some(self.git_store.upgrade()?.read(cx).buffer_store.clone())
3920 }
3921
3922 fn save_buffers<'a>(
3923 &self,
3924 entries: impl IntoIterator<Item = &'a RepoPath>,
3925 cx: &mut Context<Self>,
3926 ) -> Vec<Task<anyhow::Result<()>>> {
3927 let mut save_futures = Vec::new();
3928 if let Some(buffer_store) = self.buffer_store(cx) {
3929 buffer_store.update(cx, |buffer_store, cx| {
3930 for path in entries {
3931 let Some(project_path) = self.repo_path_to_project_path(path, cx) else {
3932 continue;
3933 };
3934 if let Some(buffer) = buffer_store.get_by_path(&project_path)
3935 && buffer
3936 .read(cx)
3937 .file()
3938 .is_some_and(|file| file.disk_state().exists())
3939 && buffer.read(cx).has_unsaved_edits()
3940 {
3941 save_futures.push(buffer_store.save_buffer(buffer, cx));
3942 }
3943 }
3944 })
3945 }
3946 save_futures
3947 }
3948
3949 pub fn stage_entries(
3950 &mut self,
3951 entries: Vec<RepoPath>,
3952 cx: &mut Context<Self>,
3953 ) -> Task<anyhow::Result<()>> {
3954 if entries.is_empty() {
3955 return Task::ready(Ok(()));
3956 }
3957 let id = self.id;
3958 let save_tasks = self.save_buffers(&entries, cx);
3959 let paths = entries
3960 .iter()
3961 .map(|p| p.as_unix_str())
3962 .collect::<Vec<_>>()
3963 .join(" ");
3964 let status = format!("git add {paths}");
3965 let job_key = GitJobKey::WriteIndex(entries.clone());
3966
3967 self.spawn_job_with_tracking(
3968 entries.clone(),
3969 pending_op::GitStatus::Staged,
3970 cx,
3971 async move |this, cx| {
3972 for save_task in save_tasks {
3973 save_task.await?;
3974 }
3975
3976 this.update(cx, |this, _| {
3977 this.send_keyed_job(
3978 Some(job_key),
3979 Some(status.into()),
3980 move |git_repo, _cx| async move {
3981 match git_repo {
3982 RepositoryState::Local {
3983 backend,
3984 environment,
3985 ..
3986 } => backend.stage_paths(entries, environment.clone()).await,
3987 RepositoryState::Remote { project_id, client } => {
3988 client
3989 .request(proto::Stage {
3990 project_id: project_id.0,
3991 repository_id: id.to_proto(),
3992 paths: entries
3993 .into_iter()
3994 .map(|repo_path| repo_path.to_proto())
3995 .collect(),
3996 })
3997 .await
3998 .context("sending stage request")?;
3999
4000 Ok(())
4001 }
4002 }
4003 },
4004 )
4005 })?
4006 .await?
4007 },
4008 )
4009 }
4010
4011 pub fn unstage_entries(
4012 &mut self,
4013 entries: Vec<RepoPath>,
4014 cx: &mut Context<Self>,
4015 ) -> Task<anyhow::Result<()>> {
4016 if entries.is_empty() {
4017 return Task::ready(Ok(()));
4018 }
4019 let id = self.id;
4020 let save_tasks = self.save_buffers(&entries, cx);
4021 let paths = entries
4022 .iter()
4023 .map(|p| p.as_unix_str())
4024 .collect::<Vec<_>>()
4025 .join(" ");
4026 let status = format!("git reset {paths}");
4027 let job_key = GitJobKey::WriteIndex(entries.clone());
4028
4029 self.spawn_job_with_tracking(
4030 entries.clone(),
4031 pending_op::GitStatus::Unstaged,
4032 cx,
4033 async move |this, cx| {
4034 for save_task in save_tasks {
4035 save_task.await?;
4036 }
4037
4038 this.update(cx, |this, _| {
4039 this.send_keyed_job(
4040 Some(job_key),
4041 Some(status.into()),
4042 move |git_repo, _cx| async move {
4043 match git_repo {
4044 RepositoryState::Local {
4045 backend,
4046 environment,
4047 ..
4048 } => backend.unstage_paths(entries, environment).await,
4049 RepositoryState::Remote { project_id, client } => {
4050 client
4051 .request(proto::Unstage {
4052 project_id: project_id.0,
4053 repository_id: id.to_proto(),
4054 paths: entries
4055 .into_iter()
4056 .map(|repo_path| repo_path.to_proto())
4057 .collect(),
4058 })
4059 .await
4060 .context("sending unstage request")?;
4061
4062 Ok(())
4063 }
4064 }
4065 },
4066 )
4067 })?
4068 .await?
4069 },
4070 )
4071 }
4072
4073 pub fn stage_all(&mut self, cx: &mut Context<Self>) -> Task<anyhow::Result<()>> {
4074 let to_stage = self
4075 .cached_status()
4076 .filter_map(|entry| {
4077 if let Some(ops) = self.pending_ops_for_path(&entry.repo_path) {
4078 if ops.staging() || ops.staged() {
4079 None
4080 } else {
4081 Some(entry.repo_path)
4082 }
4083 } else if entry.status.staging().is_fully_staged() {
4084 None
4085 } else {
4086 Some(entry.repo_path)
4087 }
4088 })
4089 .collect();
4090 self.stage_entries(to_stage, cx)
4091 }
4092
4093 pub fn unstage_all(&mut self, cx: &mut Context<Self>) -> Task<anyhow::Result<()>> {
4094 let to_unstage = self
4095 .cached_status()
4096 .filter_map(|entry| {
4097 if let Some(ops) = self.pending_ops_for_path(&entry.repo_path) {
4098 if !ops.staging() && !ops.staged() {
4099 None
4100 } else {
4101 Some(entry.repo_path)
4102 }
4103 } else if entry.status.staging().is_fully_unstaged() {
4104 None
4105 } else {
4106 Some(entry.repo_path)
4107 }
4108 })
4109 .collect();
4110 self.unstage_entries(to_unstage, cx)
4111 }
4112
4113 pub fn stash_all(&mut self, cx: &mut Context<Self>) -> Task<anyhow::Result<()>> {
4114 let to_stash = self.cached_status().map(|entry| entry.repo_path).collect();
4115
4116 self.stash_entries(to_stash, cx)
4117 }
4118
4119 pub fn stash_entries(
4120 &mut self,
4121 entries: Vec<RepoPath>,
4122 cx: &mut Context<Self>,
4123 ) -> Task<anyhow::Result<()>> {
4124 let id = self.id;
4125
4126 cx.spawn(async move |this, cx| {
4127 this.update(cx, |this, _| {
4128 this.send_job(None, move |git_repo, _cx| async move {
4129 match git_repo {
4130 RepositoryState::Local {
4131 backend,
4132 environment,
4133 ..
4134 } => backend.stash_paths(entries, environment).await,
4135 RepositoryState::Remote { project_id, client } => {
4136 client
4137 .request(proto::Stash {
4138 project_id: project_id.0,
4139 repository_id: id.to_proto(),
4140 paths: entries
4141 .into_iter()
4142 .map(|repo_path| repo_path.to_proto())
4143 .collect(),
4144 })
4145 .await
4146 .context("sending stash request")?;
4147 Ok(())
4148 }
4149 }
4150 })
4151 })?
4152 .await??;
4153 Ok(())
4154 })
4155 }
4156
4157 pub fn stash_pop(
4158 &mut self,
4159 index: Option<usize>,
4160 cx: &mut Context<Self>,
4161 ) -> Task<anyhow::Result<()>> {
4162 let id = self.id;
4163 cx.spawn(async move |this, cx| {
4164 this.update(cx, |this, _| {
4165 this.send_job(None, move |git_repo, _cx| async move {
4166 match git_repo {
4167 RepositoryState::Local {
4168 backend,
4169 environment,
4170 ..
4171 } => backend.stash_pop(index, environment).await,
4172 RepositoryState::Remote { project_id, client } => {
4173 client
4174 .request(proto::StashPop {
4175 project_id: project_id.0,
4176 repository_id: id.to_proto(),
4177 stash_index: index.map(|i| i as u64),
4178 })
4179 .await
4180 .context("sending stash pop request")?;
4181 Ok(())
4182 }
4183 }
4184 })
4185 })?
4186 .await??;
4187 Ok(())
4188 })
4189 }
4190
4191 pub fn stash_apply(
4192 &mut self,
4193 index: Option<usize>,
4194 cx: &mut Context<Self>,
4195 ) -> Task<anyhow::Result<()>> {
4196 let id = self.id;
4197 cx.spawn(async move |this, cx| {
4198 this.update(cx, |this, _| {
4199 this.send_job(None, move |git_repo, _cx| async move {
4200 match git_repo {
4201 RepositoryState::Local {
4202 backend,
4203 environment,
4204 ..
4205 } => backend.stash_apply(index, environment).await,
4206 RepositoryState::Remote { project_id, client } => {
4207 client
4208 .request(proto::StashApply {
4209 project_id: project_id.0,
4210 repository_id: id.to_proto(),
4211 stash_index: index.map(|i| i as u64),
4212 })
4213 .await
4214 .context("sending stash apply request")?;
4215 Ok(())
4216 }
4217 }
4218 })
4219 })?
4220 .await??;
4221 Ok(())
4222 })
4223 }
4224
4225 pub fn stash_drop(
4226 &mut self,
4227 index: Option<usize>,
4228 cx: &mut Context<Self>,
4229 ) -> oneshot::Receiver<anyhow::Result<()>> {
4230 let id = self.id;
4231 let updates_tx = self
4232 .git_store()
4233 .and_then(|git_store| match &git_store.read(cx).state {
4234 GitStoreState::Local { downstream, .. } => downstream
4235 .as_ref()
4236 .map(|downstream| downstream.updates_tx.clone()),
4237 _ => None,
4238 });
4239 let this = cx.weak_entity();
4240 self.send_job(None, move |git_repo, mut cx| async move {
4241 match git_repo {
4242 RepositoryState::Local {
4243 backend,
4244 environment,
4245 ..
4246 } => {
4247 // TODO would be nice to not have to do this manually
4248 let result = backend.stash_drop(index, environment).await;
4249 if result.is_ok()
4250 && let Ok(stash_entries) = backend.stash_entries().await
4251 {
4252 let snapshot = this.update(&mut cx, |this, cx| {
4253 this.snapshot.stash_entries = stash_entries;
4254 cx.emit(RepositoryEvent::StashEntriesChanged);
4255 this.snapshot.clone()
4256 })?;
4257 if let Some(updates_tx) = updates_tx {
4258 updates_tx
4259 .unbounded_send(DownstreamUpdate::UpdateRepository(snapshot))
4260 .ok();
4261 }
4262 }
4263
4264 result
4265 }
4266 RepositoryState::Remote { project_id, client } => {
4267 client
4268 .request(proto::StashDrop {
4269 project_id: project_id.0,
4270 repository_id: id.to_proto(),
4271 stash_index: index.map(|i| i as u64),
4272 })
4273 .await
4274 .context("sending stash pop request")?;
4275 Ok(())
4276 }
4277 }
4278 })
4279 }
4280
4281 pub fn run_hook(&mut self, hook: RunHook, _cx: &mut App) -> oneshot::Receiver<Result<()>> {
4282 let id = self.id;
4283 self.send_job(
4284 Some(format!("git hook {}", hook.as_str()).into()),
4285 move |git_repo, _cx| async move {
4286 match git_repo {
4287 RepositoryState::Local {
4288 backend,
4289 environment,
4290 ..
4291 } => backend.run_hook(hook, environment.clone()).await,
4292 RepositoryState::Remote { project_id, client } => {
4293 client
4294 .request(proto::RunGitHook {
4295 project_id: project_id.0,
4296 repository_id: id.to_proto(),
4297 hook: hook.to_proto(),
4298 })
4299 .await?;
4300
4301 Ok(())
4302 }
4303 }
4304 },
4305 )
4306 }
4307
4308 pub fn commit(
4309 &mut self,
4310 message: SharedString,
4311 name_and_email: Option<(SharedString, SharedString)>,
4312 options: CommitOptions,
4313 askpass: AskPassDelegate,
4314 cx: &mut App,
4315 ) -> oneshot::Receiver<Result<()>> {
4316 let id = self.id;
4317 let askpass_delegates = self.askpass_delegates.clone();
4318 let askpass_id = util::post_inc(&mut self.latest_askpass_id);
4319
4320 let rx = self.run_hook(RunHook::PreCommit, cx);
4321
4322 self.send_job(Some("git commit".into()), move |git_repo, _cx| async move {
4323 rx.await??;
4324
4325 match git_repo {
4326 RepositoryState::Local {
4327 backend,
4328 environment,
4329 ..
4330 } => {
4331 backend
4332 .commit(message, name_and_email, options, askpass, environment)
4333 .await
4334 }
4335 RepositoryState::Remote { project_id, client } => {
4336 askpass_delegates.lock().insert(askpass_id, askpass);
4337 let _defer = util::defer(|| {
4338 let askpass_delegate = askpass_delegates.lock().remove(&askpass_id);
4339 debug_assert!(askpass_delegate.is_some());
4340 });
4341 let (name, email) = name_and_email.unzip();
4342 client
4343 .request(proto::Commit {
4344 project_id: project_id.0,
4345 repository_id: id.to_proto(),
4346 message: String::from(message),
4347 name: name.map(String::from),
4348 email: email.map(String::from),
4349 options: Some(proto::commit::CommitOptions {
4350 amend: options.amend,
4351 signoff: options.signoff,
4352 }),
4353 askpass_id,
4354 })
4355 .await
4356 .context("sending commit request")?;
4357
4358 Ok(())
4359 }
4360 }
4361 })
4362 }
4363
4364 pub fn fetch(
4365 &mut self,
4366 fetch_options: FetchOptions,
4367 askpass: AskPassDelegate,
4368 _cx: &mut App,
4369 ) -> oneshot::Receiver<Result<RemoteCommandOutput>> {
4370 let askpass_delegates = self.askpass_delegates.clone();
4371 let askpass_id = util::post_inc(&mut self.latest_askpass_id);
4372 let id = self.id;
4373
4374 self.send_job(Some("git fetch".into()), move |git_repo, cx| async move {
4375 match git_repo {
4376 RepositoryState::Local {
4377 backend,
4378 environment,
4379 ..
4380 } => backend.fetch(fetch_options, askpass, environment, cx).await,
4381 RepositoryState::Remote { project_id, client } => {
4382 askpass_delegates.lock().insert(askpass_id, askpass);
4383 let _defer = util::defer(|| {
4384 let askpass_delegate = askpass_delegates.lock().remove(&askpass_id);
4385 debug_assert!(askpass_delegate.is_some());
4386 });
4387
4388 let response = client
4389 .request(proto::Fetch {
4390 project_id: project_id.0,
4391 repository_id: id.to_proto(),
4392 askpass_id,
4393 remote: fetch_options.to_proto(),
4394 })
4395 .await
4396 .context("sending fetch request")?;
4397
4398 Ok(RemoteCommandOutput {
4399 stdout: response.stdout,
4400 stderr: response.stderr,
4401 })
4402 }
4403 }
4404 })
4405 }
4406
4407 pub fn push(
4408 &mut self,
4409 branch: SharedString,
4410 remote: SharedString,
4411 options: Option<PushOptions>,
4412 askpass: AskPassDelegate,
4413 cx: &mut Context<Self>,
4414 ) -> oneshot::Receiver<Result<RemoteCommandOutput>> {
4415 let askpass_delegates = self.askpass_delegates.clone();
4416 let askpass_id = util::post_inc(&mut self.latest_askpass_id);
4417 let id = self.id;
4418
4419 let args = options
4420 .map(|option| match option {
4421 PushOptions::SetUpstream => " --set-upstream",
4422 PushOptions::Force => " --force-with-lease",
4423 })
4424 .unwrap_or("");
4425
4426 let updates_tx = self
4427 .git_store()
4428 .and_then(|git_store| match &git_store.read(cx).state {
4429 GitStoreState::Local { downstream, .. } => downstream
4430 .as_ref()
4431 .map(|downstream| downstream.updates_tx.clone()),
4432 _ => None,
4433 });
4434
4435 let this = cx.weak_entity();
4436 self.send_job(
4437 Some(format!("git push {} {} {}", args, remote, branch).into()),
4438 move |git_repo, mut cx| async move {
4439 match git_repo {
4440 RepositoryState::Local {
4441 backend,
4442 environment,
4443 ..
4444 } => {
4445 let result = backend
4446 .push(
4447 branch.to_string(),
4448 remote.to_string(),
4449 options,
4450 askpass,
4451 environment.clone(),
4452 cx.clone(),
4453 )
4454 .await;
4455 // TODO would be nice to not have to do this manually
4456 if result.is_ok() {
4457 let branches = backend.branches().await?;
4458 let branch = branches.into_iter().find(|branch| branch.is_head);
4459 log::info!("head branch after scan is {branch:?}");
4460 let snapshot = this.update(&mut cx, |this, cx| {
4461 this.snapshot.branch = branch;
4462 cx.emit(RepositoryEvent::BranchChanged);
4463 this.snapshot.clone()
4464 })?;
4465 if let Some(updates_tx) = updates_tx {
4466 updates_tx
4467 .unbounded_send(DownstreamUpdate::UpdateRepository(snapshot))
4468 .ok();
4469 }
4470 }
4471 result
4472 }
4473 RepositoryState::Remote { project_id, client } => {
4474 askpass_delegates.lock().insert(askpass_id, askpass);
4475 let _defer = util::defer(|| {
4476 let askpass_delegate = askpass_delegates.lock().remove(&askpass_id);
4477 debug_assert!(askpass_delegate.is_some());
4478 });
4479 let response = client
4480 .request(proto::Push {
4481 project_id: project_id.0,
4482 repository_id: id.to_proto(),
4483 askpass_id,
4484 branch_name: branch.to_string(),
4485 remote_name: remote.to_string(),
4486 options: options.map(|options| match options {
4487 PushOptions::Force => proto::push::PushOptions::Force,
4488 PushOptions::SetUpstream => {
4489 proto::push::PushOptions::SetUpstream
4490 }
4491 }
4492 as i32),
4493 })
4494 .await
4495 .context("sending push request")?;
4496
4497 Ok(RemoteCommandOutput {
4498 stdout: response.stdout,
4499 stderr: response.stderr,
4500 })
4501 }
4502 }
4503 },
4504 )
4505 }
4506
4507 pub fn pull(
4508 &mut self,
4509 branch: Option<SharedString>,
4510 remote: SharedString,
4511 rebase: bool,
4512 askpass: AskPassDelegate,
4513 _cx: &mut App,
4514 ) -> oneshot::Receiver<Result<RemoteCommandOutput>> {
4515 let askpass_delegates = self.askpass_delegates.clone();
4516 let askpass_id = util::post_inc(&mut self.latest_askpass_id);
4517 let id = self.id;
4518
4519 let mut status = "git pull".to_string();
4520 if rebase {
4521 status.push_str(" --rebase");
4522 }
4523 status.push_str(&format!(" {}", remote));
4524 if let Some(b) = &branch {
4525 status.push_str(&format!(" {}", b));
4526 }
4527
4528 self.send_job(Some(status.into()), move |git_repo, cx| async move {
4529 match git_repo {
4530 RepositoryState::Local {
4531 backend,
4532 environment,
4533 ..
4534 } => {
4535 backend
4536 .pull(
4537 branch.as_ref().map(|b| b.to_string()),
4538 remote.to_string(),
4539 rebase,
4540 askpass,
4541 environment.clone(),
4542 cx,
4543 )
4544 .await
4545 }
4546 RepositoryState::Remote { project_id, client } => {
4547 askpass_delegates.lock().insert(askpass_id, askpass);
4548 let _defer = util::defer(|| {
4549 let askpass_delegate = askpass_delegates.lock().remove(&askpass_id);
4550 debug_assert!(askpass_delegate.is_some());
4551 });
4552 let response = client
4553 .request(proto::Pull {
4554 project_id: project_id.0,
4555 repository_id: id.to_proto(),
4556 askpass_id,
4557 rebase,
4558 branch_name: branch.as_ref().map(|b| b.to_string()),
4559 remote_name: remote.to_string(),
4560 })
4561 .await
4562 .context("sending pull request")?;
4563
4564 Ok(RemoteCommandOutput {
4565 stdout: response.stdout,
4566 stderr: response.stderr,
4567 })
4568 }
4569 }
4570 })
4571 }
4572
4573 fn spawn_set_index_text_job(
4574 &mut self,
4575 path: RepoPath,
4576 content: Option<String>,
4577 hunk_staging_operation_count: Option<usize>,
4578 cx: &mut Context<Self>,
4579 ) -> oneshot::Receiver<anyhow::Result<()>> {
4580 let id = self.id;
4581 let this = cx.weak_entity();
4582 let git_store = self.git_store.clone();
4583 let abs_path = self.snapshot.repo_path_to_abs_path(&path);
4584 self.send_keyed_job(
4585 Some(GitJobKey::WriteIndex(vec![path.clone()])),
4586 None,
4587 move |git_repo, mut cx| async move {
4588 log::debug!(
4589 "start updating index text for buffer {}",
4590 path.as_unix_str()
4591 );
4592
4593 match git_repo {
4594 RepositoryState::Local {
4595 fs,
4596 backend,
4597 environment,
4598 ..
4599 } => {
4600 let executable = match fs.metadata(&abs_path).await {
4601 Ok(Some(meta)) => meta.is_executable,
4602 Ok(None) => false,
4603 Err(_err) => false,
4604 };
4605 backend
4606 .set_index_text(path.clone(), content, environment.clone(), executable)
4607 .await?;
4608 }
4609 RepositoryState::Remote { project_id, client } => {
4610 client
4611 .request(proto::SetIndexText {
4612 project_id: project_id.0,
4613 repository_id: id.to_proto(),
4614 path: path.to_proto(),
4615 text: content,
4616 })
4617 .await?;
4618 }
4619 }
4620 log::debug!(
4621 "finish updating index text for buffer {}",
4622 path.as_unix_str()
4623 );
4624
4625 if let Some(hunk_staging_operation_count) = hunk_staging_operation_count {
4626 let project_path = this
4627 .read_with(&cx, |this, cx| this.repo_path_to_project_path(&path, cx))
4628 .ok()
4629 .flatten();
4630 git_store.update(&mut cx, |git_store, cx| {
4631 let buffer_id = git_store
4632 .buffer_store
4633 .read(cx)
4634 .get_by_path(&project_path?)?
4635 .read(cx)
4636 .remote_id();
4637 let diff_state = git_store.diffs.get(&buffer_id)?;
4638 diff_state.update(cx, |diff_state, _| {
4639 diff_state.hunk_staging_operation_count_as_of_write =
4640 hunk_staging_operation_count;
4641 });
4642 Some(())
4643 })?;
4644 }
4645 Ok(())
4646 },
4647 )
4648 }
4649
4650 pub fn get_remotes(
4651 &mut self,
4652 branch_name: Option<String>,
4653 ) -> oneshot::Receiver<Result<Vec<Remote>>> {
4654 let id = self.id;
4655 self.send_job(None, move |repo, _cx| async move {
4656 match repo {
4657 RepositoryState::Local { backend, .. } => backend.get_remotes(branch_name).await,
4658 RepositoryState::Remote { project_id, client } => {
4659 let response = client
4660 .request(proto::GetRemotes {
4661 project_id: project_id.0,
4662 repository_id: id.to_proto(),
4663 branch_name,
4664 })
4665 .await?;
4666
4667 let remotes = response
4668 .remotes
4669 .into_iter()
4670 .map(|remotes| git::repository::Remote {
4671 name: remotes.name.into(),
4672 })
4673 .collect();
4674
4675 Ok(remotes)
4676 }
4677 }
4678 })
4679 }
4680
4681 pub fn branches(&mut self) -> oneshot::Receiver<Result<Vec<Branch>>> {
4682 let id = self.id;
4683 self.send_job(None, move |repo, _| async move {
4684 match repo {
4685 RepositoryState::Local { backend, .. } => backend.branches().await,
4686 RepositoryState::Remote { project_id, client } => {
4687 let response = client
4688 .request(proto::GitGetBranches {
4689 project_id: project_id.0,
4690 repository_id: id.to_proto(),
4691 })
4692 .await?;
4693
4694 let branches = response
4695 .branches
4696 .into_iter()
4697 .map(|branch| proto_to_branch(&branch))
4698 .collect();
4699
4700 Ok(branches)
4701 }
4702 }
4703 })
4704 }
4705
4706 pub fn worktrees(&mut self) -> oneshot::Receiver<Result<Vec<GitWorktree>>> {
4707 let id = self.id;
4708 self.send_job(None, move |repo, _| async move {
4709 match repo {
4710 RepositoryState::Local { backend, .. } => backend.worktrees().await,
4711 RepositoryState::Remote { project_id, client } => {
4712 let response = client
4713 .request(proto::GitGetWorktrees {
4714 project_id: project_id.0,
4715 repository_id: id.to_proto(),
4716 })
4717 .await?;
4718
4719 let worktrees = response
4720 .worktrees
4721 .into_iter()
4722 .map(|worktree| proto_to_worktree(&worktree))
4723 .collect();
4724
4725 Ok(worktrees)
4726 }
4727 }
4728 })
4729 }
4730
4731 pub fn create_worktree(
4732 &mut self,
4733 name: String,
4734 path: PathBuf,
4735 commit: Option<String>,
4736 ) -> oneshot::Receiver<Result<()>> {
4737 let id = self.id;
4738 self.send_job(
4739 Some("git worktree add".into()),
4740 move |repo, _cx| async move {
4741 match repo {
4742 RepositoryState::Local { backend, .. } => {
4743 backend.create_worktree(name, path, commit).await
4744 }
4745 RepositoryState::Remote { project_id, client } => {
4746 client
4747 .request(proto::GitCreateWorktree {
4748 project_id: project_id.0,
4749 repository_id: id.to_proto(),
4750 name,
4751 directory: path.to_string_lossy().to_string(),
4752 commit,
4753 })
4754 .await?;
4755
4756 Ok(())
4757 }
4758 }
4759 },
4760 )
4761 }
4762
4763 pub fn default_branch(&mut self) -> oneshot::Receiver<Result<Option<SharedString>>> {
4764 let id = self.id;
4765 self.send_job(None, move |repo, _| async move {
4766 match repo {
4767 RepositoryState::Local { backend, .. } => backend.default_branch().await,
4768 RepositoryState::Remote { project_id, client } => {
4769 let response = client
4770 .request(proto::GetDefaultBranch {
4771 project_id: project_id.0,
4772 repository_id: id.to_proto(),
4773 })
4774 .await?;
4775
4776 anyhow::Ok(response.branch.map(SharedString::from))
4777 }
4778 }
4779 })
4780 }
4781
4782 pub fn diff_tree(
4783 &mut self,
4784 diff_type: DiffTreeType,
4785 _cx: &App,
4786 ) -> oneshot::Receiver<Result<TreeDiff>> {
4787 let repository_id = self.snapshot.id;
4788 self.send_job(None, move |repo, _cx| async move {
4789 match repo {
4790 RepositoryState::Local { backend, .. } => backend.diff_tree(diff_type).await,
4791 RepositoryState::Remote { client, project_id } => {
4792 let response = client
4793 .request(proto::GetTreeDiff {
4794 project_id: project_id.0,
4795 repository_id: repository_id.0,
4796 is_merge: matches!(diff_type, DiffTreeType::MergeBase { .. }),
4797 base: diff_type.base().to_string(),
4798 head: diff_type.head().to_string(),
4799 })
4800 .await?;
4801
4802 let entries = response
4803 .entries
4804 .into_iter()
4805 .filter_map(|entry| {
4806 let status = match entry.status() {
4807 proto::tree_diff_status::Status::Added => TreeDiffStatus::Added,
4808 proto::tree_diff_status::Status::Modified => {
4809 TreeDiffStatus::Modified {
4810 old: git::Oid::from_str(
4811 &entry.oid.context("missing oid").log_err()?,
4812 )
4813 .log_err()?,
4814 }
4815 }
4816 proto::tree_diff_status::Status::Deleted => {
4817 TreeDiffStatus::Deleted {
4818 old: git::Oid::from_str(
4819 &entry.oid.context("missing oid").log_err()?,
4820 )
4821 .log_err()?,
4822 }
4823 }
4824 };
4825 Some((
4826 RepoPath::from_rel_path(
4827 &RelPath::from_proto(&entry.path).log_err()?,
4828 ),
4829 status,
4830 ))
4831 })
4832 .collect();
4833
4834 Ok(TreeDiff { entries })
4835 }
4836 }
4837 })
4838 }
4839
4840 pub fn diff(&mut self, diff_type: DiffType, _cx: &App) -> oneshot::Receiver<Result<String>> {
4841 let id = self.id;
4842 self.send_job(None, move |repo, _cx| async move {
4843 match repo {
4844 RepositoryState::Local { backend, .. } => backend.diff(diff_type).await,
4845 RepositoryState::Remote { project_id, client } => {
4846 let response = client
4847 .request(proto::GitDiff {
4848 project_id: project_id.0,
4849 repository_id: id.to_proto(),
4850 diff_type: match diff_type {
4851 DiffType::HeadToIndex => {
4852 proto::git_diff::DiffType::HeadToIndex.into()
4853 }
4854 DiffType::HeadToWorktree => {
4855 proto::git_diff::DiffType::HeadToWorktree.into()
4856 }
4857 },
4858 })
4859 .await?;
4860
4861 Ok(response.diff)
4862 }
4863 }
4864 })
4865 }
4866
4867 pub fn create_branch(
4868 &mut self,
4869 branch_name: String,
4870 base_branch: Option<String>,
4871 ) -> oneshot::Receiver<Result<()>> {
4872 let id = self.id;
4873 let status_msg = if let Some(ref base) = base_branch {
4874 format!("git switch -c {branch_name} {base}").into()
4875 } else {
4876 format!("git switch -c {branch_name}").into()
4877 };
4878 self.send_job(Some(status_msg), move |repo, _cx| async move {
4879 match repo {
4880 RepositoryState::Local { backend, .. } => {
4881 backend.create_branch(branch_name, base_branch).await
4882 }
4883 RepositoryState::Remote { project_id, client } => {
4884 client
4885 .request(proto::GitCreateBranch {
4886 project_id: project_id.0,
4887 repository_id: id.to_proto(),
4888 branch_name,
4889 })
4890 .await?;
4891
4892 Ok(())
4893 }
4894 }
4895 })
4896 }
4897
4898 pub fn change_branch(&mut self, branch_name: String) -> oneshot::Receiver<Result<()>> {
4899 let id = self.id;
4900 self.send_job(
4901 Some(format!("git switch {branch_name}").into()),
4902 move |repo, _cx| async move {
4903 match repo {
4904 RepositoryState::Local { backend, .. } => {
4905 backend.change_branch(branch_name).await
4906 }
4907 RepositoryState::Remote { project_id, client } => {
4908 client
4909 .request(proto::GitChangeBranch {
4910 project_id: project_id.0,
4911 repository_id: id.to_proto(),
4912 branch_name,
4913 })
4914 .await?;
4915
4916 Ok(())
4917 }
4918 }
4919 },
4920 )
4921 }
4922
4923 pub fn rename_branch(
4924 &mut self,
4925 branch: String,
4926 new_name: String,
4927 ) -> oneshot::Receiver<Result<()>> {
4928 let id = self.id;
4929 self.send_job(
4930 Some(format!("git branch -m {branch} {new_name}").into()),
4931 move |repo, _cx| async move {
4932 match repo {
4933 RepositoryState::Local { backend, .. } => {
4934 backend.rename_branch(branch, new_name).await
4935 }
4936 RepositoryState::Remote { project_id, client } => {
4937 client
4938 .request(proto::GitRenameBranch {
4939 project_id: project_id.0,
4940 repository_id: id.to_proto(),
4941 branch,
4942 new_name,
4943 })
4944 .await?;
4945
4946 Ok(())
4947 }
4948 }
4949 },
4950 )
4951 }
4952
4953 pub fn check_for_pushed_commits(&mut self) -> oneshot::Receiver<Result<Vec<SharedString>>> {
4954 let id = self.id;
4955 self.send_job(None, move |repo, _cx| async move {
4956 match repo {
4957 RepositoryState::Local { backend, .. } => backend.check_for_pushed_commit().await,
4958 RepositoryState::Remote { project_id, client } => {
4959 let response = client
4960 .request(proto::CheckForPushedCommits {
4961 project_id: project_id.0,
4962 repository_id: id.to_proto(),
4963 })
4964 .await?;
4965
4966 let branches = response.pushed_to.into_iter().map(Into::into).collect();
4967
4968 Ok(branches)
4969 }
4970 }
4971 })
4972 }
4973
4974 pub fn checkpoint(&mut self) -> oneshot::Receiver<Result<GitRepositoryCheckpoint>> {
4975 self.send_job(None, |repo, _cx| async move {
4976 match repo {
4977 RepositoryState::Local { backend, .. } => backend.checkpoint().await,
4978 RepositoryState::Remote { .. } => anyhow::bail!("not implemented yet"),
4979 }
4980 })
4981 }
4982
4983 pub fn restore_checkpoint(
4984 &mut self,
4985 checkpoint: GitRepositoryCheckpoint,
4986 ) -> oneshot::Receiver<Result<()>> {
4987 self.send_job(None, move |repo, _cx| async move {
4988 match repo {
4989 RepositoryState::Local { backend, .. } => {
4990 backend.restore_checkpoint(checkpoint).await
4991 }
4992 RepositoryState::Remote { .. } => anyhow::bail!("not implemented yet"),
4993 }
4994 })
4995 }
4996
4997 pub(crate) fn apply_remote_update(
4998 &mut self,
4999 update: proto::UpdateRepository,
5000 cx: &mut Context<Self>,
5001 ) -> Result<()> {
5002 let conflicted_paths = TreeSet::from_ordered_entries(
5003 update
5004 .current_merge_conflicts
5005 .into_iter()
5006 .filter_map(|path| RepoPath::from_proto(&path).log_err()),
5007 );
5008 let new_branch = update.branch_summary.as_ref().map(proto_to_branch);
5009 let new_head_commit = update
5010 .head_commit_details
5011 .as_ref()
5012 .map(proto_to_commit_details);
5013 if self.snapshot.branch != new_branch || self.snapshot.head_commit != new_head_commit {
5014 cx.emit(RepositoryEvent::BranchChanged)
5015 }
5016 self.snapshot.branch = new_branch;
5017 self.snapshot.head_commit = new_head_commit;
5018
5019 self.snapshot.merge.conflicted_paths = conflicted_paths;
5020 self.snapshot.merge.message = update.merge_message.map(SharedString::from);
5021 let new_stash_entries = GitStash {
5022 entries: update
5023 .stash_entries
5024 .iter()
5025 .filter_map(|entry| proto_to_stash(entry).ok())
5026 .collect(),
5027 };
5028 if self.snapshot.stash_entries != new_stash_entries {
5029 cx.emit(RepositoryEvent::StashEntriesChanged)
5030 }
5031 self.snapshot.stash_entries = new_stash_entries;
5032
5033 let edits = update
5034 .removed_statuses
5035 .into_iter()
5036 .filter_map(|path| {
5037 Some(sum_tree::Edit::Remove(PathKey(
5038 RelPath::from_proto(&path).log_err()?,
5039 )))
5040 })
5041 .chain(
5042 update
5043 .updated_statuses
5044 .into_iter()
5045 .filter_map(|updated_status| {
5046 Some(sum_tree::Edit::Insert(updated_status.try_into().log_err()?))
5047 }),
5048 )
5049 .collect::<Vec<_>>();
5050 if !edits.is_empty() {
5051 cx.emit(RepositoryEvent::StatusesChanged);
5052 }
5053 self.snapshot.statuses_by_path.edit(edits, ());
5054 if update.is_last_update {
5055 self.snapshot.scan_id = update.scan_id;
5056 }
5057 self.clear_pending_ops(cx);
5058 Ok(())
5059 }
5060
5061 pub fn compare_checkpoints(
5062 &mut self,
5063 left: GitRepositoryCheckpoint,
5064 right: GitRepositoryCheckpoint,
5065 ) -> oneshot::Receiver<Result<bool>> {
5066 self.send_job(None, move |repo, _cx| async move {
5067 match repo {
5068 RepositoryState::Local { backend, .. } => {
5069 backend.compare_checkpoints(left, right).await
5070 }
5071 RepositoryState::Remote { .. } => anyhow::bail!("not implemented yet"),
5072 }
5073 })
5074 }
5075
5076 pub fn diff_checkpoints(
5077 &mut self,
5078 base_checkpoint: GitRepositoryCheckpoint,
5079 target_checkpoint: GitRepositoryCheckpoint,
5080 ) -> oneshot::Receiver<Result<String>> {
5081 self.send_job(None, move |repo, _cx| async move {
5082 match repo {
5083 RepositoryState::Local { backend, .. } => {
5084 backend
5085 .diff_checkpoints(base_checkpoint, target_checkpoint)
5086 .await
5087 }
5088 RepositoryState::Remote { .. } => anyhow::bail!("not implemented yet"),
5089 }
5090 })
5091 }
5092
5093 fn clear_pending_ops(&mut self, cx: &mut Context<Self>) {
5094 let updated = SumTree::from_iter(
5095 self.pending_ops.iter().filter_map(|ops| {
5096 let inner_ops: Vec<PendingOp> =
5097 ops.ops.iter().filter(|op| op.running()).cloned().collect();
5098 if inner_ops.is_empty() {
5099 None
5100 } else {
5101 Some(PendingOps {
5102 repo_path: ops.repo_path.clone(),
5103 ops: inner_ops,
5104 })
5105 }
5106 }),
5107 (),
5108 );
5109
5110 if updated != self.pending_ops {
5111 cx.emit(RepositoryEvent::PendingOpsChanged {
5112 pending_ops: self.pending_ops.clone(),
5113 })
5114 }
5115
5116 self.pending_ops = updated;
5117 }
5118
5119 fn schedule_scan(
5120 &mut self,
5121 updates_tx: Option<mpsc::UnboundedSender<DownstreamUpdate>>,
5122 cx: &mut Context<Self>,
5123 ) {
5124 let this = cx.weak_entity();
5125 let _ = self.send_keyed_job(
5126 Some(GitJobKey::ReloadGitState),
5127 None,
5128 |state, mut cx| async move {
5129 log::debug!("run scheduled git status scan");
5130
5131 let Some(this) = this.upgrade() else {
5132 return Ok(());
5133 };
5134 let RepositoryState::Local { backend, .. } = state else {
5135 bail!("not a local repository")
5136 };
5137 let (snapshot, events) = this
5138 .update(&mut cx, |this, _| {
5139 this.paths_needing_status_update.clear();
5140 compute_snapshot(
5141 this.id,
5142 this.work_directory_abs_path.clone(),
5143 this.snapshot.clone(),
5144 backend.clone(),
5145 )
5146 })?
5147 .await?;
5148 this.update(&mut cx, |this, cx| {
5149 this.snapshot = snapshot.clone();
5150 this.clear_pending_ops(cx);
5151 for event in events {
5152 cx.emit(event);
5153 }
5154 })?;
5155 if let Some(updates_tx) = updates_tx {
5156 updates_tx
5157 .unbounded_send(DownstreamUpdate::UpdateRepository(snapshot))
5158 .ok();
5159 }
5160 Ok(())
5161 },
5162 );
5163 }
5164
5165 fn spawn_local_git_worker(
5166 work_directory_abs_path: Arc<Path>,
5167 dot_git_abs_path: Arc<Path>,
5168 _repository_dir_abs_path: Arc<Path>,
5169 _common_dir_abs_path: Arc<Path>,
5170 project_environment: WeakEntity<ProjectEnvironment>,
5171 fs: Arc<dyn Fs>,
5172 cx: &mut Context<Self>,
5173 ) -> mpsc::UnboundedSender<GitJob> {
5174 let (job_tx, mut job_rx) = mpsc::unbounded::<GitJob>();
5175 let fs_cloned = fs.clone();
5176
5177 cx.spawn(async move |_, cx| {
5178 let environment = project_environment
5179 .upgrade()
5180 .context("missing project environment")?
5181 .update(cx, |project_environment, cx| {
5182 project_environment.local_directory_environment(&Shell::System, work_directory_abs_path.clone(), cx)
5183 })?
5184 .await
5185 .unwrap_or_else(|| {
5186 log::error!("failed to get working directory environment for repository {work_directory_abs_path:?}");
5187 HashMap::default()
5188 });
5189 let search_paths = environment.get("PATH").map(|val| val.to_owned());
5190 let backend = cx
5191 .background_spawn(async move {
5192 let system_git_binary_path = search_paths.and_then(|search_paths| which::which_in("git", Some(search_paths), &work_directory_abs_path).ok())
5193 .or_else(|| which::which("git").ok());
5194 fs.open_repo(&dot_git_abs_path, system_git_binary_path.as_deref())
5195 .with_context(|| format!("opening repository at {dot_git_abs_path:?}"))
5196 })
5197 .await?;
5198
5199 if let Some(git_hosting_provider_registry) =
5200 cx.update(|cx| GitHostingProviderRegistry::try_global(cx))?
5201 {
5202 git_hosting_providers::register_additional_providers(
5203 git_hosting_provider_registry,
5204 backend.clone(),
5205 );
5206 }
5207 let state = RepositoryState::Local {
5208 fs: fs_cloned,
5209 backend,
5210 environment: Arc::new(environment),
5211 };
5212 let mut jobs = VecDeque::new();
5213 loop {
5214 while let Ok(Some(next_job)) = job_rx.try_next() {
5215 jobs.push_back(next_job);
5216 }
5217
5218 if let Some(job) = jobs.pop_front() {
5219 if let Some(current_key) = &job.key
5220 && jobs
5221 .iter()
5222 .any(|other_job| other_job.key.as_ref() == Some(current_key))
5223 {
5224 continue;
5225 }
5226 (job.job)(state.clone(), cx).await;
5227 } else if let Some(job) = job_rx.next().await {
5228 jobs.push_back(job);
5229 } else {
5230 break;
5231 }
5232 }
5233 anyhow::Ok(())
5234 })
5235 .detach_and_log_err(cx);
5236
5237 job_tx
5238 }
5239
5240 fn spawn_remote_git_worker(
5241 project_id: ProjectId,
5242 client: AnyProtoClient,
5243 cx: &mut Context<Self>,
5244 ) -> mpsc::UnboundedSender<GitJob> {
5245 let (job_tx, mut job_rx) = mpsc::unbounded::<GitJob>();
5246
5247 cx.spawn(async move |_, cx| {
5248 let state = RepositoryState::Remote { project_id, client };
5249 let mut jobs = VecDeque::new();
5250 loop {
5251 while let Ok(Some(next_job)) = job_rx.try_next() {
5252 jobs.push_back(next_job);
5253 }
5254
5255 if let Some(job) = jobs.pop_front() {
5256 if let Some(current_key) = &job.key
5257 && jobs
5258 .iter()
5259 .any(|other_job| other_job.key.as_ref() == Some(current_key))
5260 {
5261 continue;
5262 }
5263 (job.job)(state.clone(), cx).await;
5264 } else if let Some(job) = job_rx.next().await {
5265 jobs.push_back(job);
5266 } else {
5267 break;
5268 }
5269 }
5270 anyhow::Ok(())
5271 })
5272 .detach_and_log_err(cx);
5273
5274 job_tx
5275 }
5276
5277 fn load_staged_text(
5278 &mut self,
5279 buffer_id: BufferId,
5280 repo_path: RepoPath,
5281 cx: &App,
5282 ) -> Task<Result<Option<String>>> {
5283 let rx = self.send_job(None, move |state, _| async move {
5284 match state {
5285 RepositoryState::Local { backend, .. } => {
5286 anyhow::Ok(backend.load_index_text(repo_path).await)
5287 }
5288 RepositoryState::Remote { project_id, client } => {
5289 let response = client
5290 .request(proto::OpenUnstagedDiff {
5291 project_id: project_id.to_proto(),
5292 buffer_id: buffer_id.to_proto(),
5293 })
5294 .await?;
5295 Ok(response.staged_text)
5296 }
5297 }
5298 });
5299 cx.spawn(|_: &mut AsyncApp| async move { rx.await? })
5300 }
5301
5302 fn load_committed_text(
5303 &mut self,
5304 buffer_id: BufferId,
5305 repo_path: RepoPath,
5306 cx: &App,
5307 ) -> Task<Result<DiffBasesChange>> {
5308 let rx = self.send_job(None, move |state, _| async move {
5309 match state {
5310 RepositoryState::Local { backend, .. } => {
5311 let committed_text = backend.load_committed_text(repo_path.clone()).await;
5312 let staged_text = backend.load_index_text(repo_path).await;
5313 let diff_bases_change = if committed_text == staged_text {
5314 DiffBasesChange::SetBoth(committed_text)
5315 } else {
5316 DiffBasesChange::SetEach {
5317 index: staged_text,
5318 head: committed_text,
5319 }
5320 };
5321 anyhow::Ok(diff_bases_change)
5322 }
5323 RepositoryState::Remote { project_id, client } => {
5324 use proto::open_uncommitted_diff_response::Mode;
5325
5326 let response = client
5327 .request(proto::OpenUncommittedDiff {
5328 project_id: project_id.to_proto(),
5329 buffer_id: buffer_id.to_proto(),
5330 })
5331 .await?;
5332 let mode = Mode::from_i32(response.mode).context("Invalid mode")?;
5333 let bases = match mode {
5334 Mode::IndexMatchesHead => DiffBasesChange::SetBoth(response.committed_text),
5335 Mode::IndexAndHead => DiffBasesChange::SetEach {
5336 head: response.committed_text,
5337 index: response.staged_text,
5338 },
5339 };
5340 Ok(bases)
5341 }
5342 }
5343 });
5344
5345 cx.spawn(|_: &mut AsyncApp| async move { rx.await? })
5346 }
5347 fn load_blob_content(&mut self, oid: Oid, cx: &App) -> Task<Result<String>> {
5348 let repository_id = self.snapshot.id;
5349 let rx = self.send_job(None, move |state, _| async move {
5350 match state {
5351 RepositoryState::Local { backend, .. } => backend.load_blob_content(oid).await,
5352 RepositoryState::Remote { client, project_id } => {
5353 let response = client
5354 .request(proto::GetBlobContent {
5355 project_id: project_id.to_proto(),
5356 repository_id: repository_id.0,
5357 oid: oid.to_string(),
5358 })
5359 .await?;
5360 Ok(response.content)
5361 }
5362 }
5363 });
5364 cx.spawn(|_: &mut AsyncApp| async move { rx.await? })
5365 }
5366
5367 fn paths_changed(
5368 &mut self,
5369 paths: Vec<RepoPath>,
5370 updates_tx: Option<mpsc::UnboundedSender<DownstreamUpdate>>,
5371 cx: &mut Context<Self>,
5372 ) {
5373 self.paths_needing_status_update.extend(paths);
5374
5375 let this = cx.weak_entity();
5376 let _ = self.send_keyed_job(
5377 Some(GitJobKey::RefreshStatuses),
5378 None,
5379 |state, mut cx| async move {
5380 let (prev_snapshot, mut changed_paths) = this.update(&mut cx, |this, _| {
5381 (
5382 this.snapshot.clone(),
5383 mem::take(&mut this.paths_needing_status_update),
5384 )
5385 })?;
5386 let RepositoryState::Local { backend, .. } = state else {
5387 bail!("not a local repository")
5388 };
5389
5390 let paths = changed_paths.iter().cloned().collect::<Vec<_>>();
5391 if paths.is_empty() {
5392 return Ok(());
5393 }
5394 let statuses = backend.status(&paths).await?;
5395 let stash_entries = backend.stash_entries().await?;
5396
5397 let changed_path_statuses = cx
5398 .background_spawn(async move {
5399 let mut changed_path_statuses = Vec::new();
5400 let prev_statuses = prev_snapshot.statuses_by_path.clone();
5401 let mut cursor = prev_statuses.cursor::<PathProgress>(());
5402
5403 for (repo_path, status) in &*statuses.entries {
5404 changed_paths.remove(repo_path);
5405 if cursor.seek_forward(&PathTarget::Path(repo_path), Bias::Left)
5406 && cursor.item().is_some_and(|entry| entry.status == *status)
5407 {
5408 continue;
5409 }
5410
5411 changed_path_statuses.push(Edit::Insert(StatusEntry {
5412 repo_path: repo_path.clone(),
5413 status: *status,
5414 }));
5415 }
5416 let mut cursor = prev_statuses.cursor::<PathProgress>(());
5417 for path in changed_paths.into_iter() {
5418 if cursor.seek_forward(&PathTarget::Path(&path), Bias::Left) {
5419 changed_path_statuses
5420 .push(Edit::Remove(PathKey(path.as_ref().clone())));
5421 }
5422 }
5423 changed_path_statuses
5424 })
5425 .await;
5426
5427 this.update(&mut cx, |this, cx| {
5428 if this.snapshot.stash_entries != stash_entries {
5429 cx.emit(RepositoryEvent::StashEntriesChanged);
5430 this.snapshot.stash_entries = stash_entries;
5431 }
5432
5433 if !changed_path_statuses.is_empty() {
5434 cx.emit(RepositoryEvent::StatusesChanged);
5435 this.snapshot
5436 .statuses_by_path
5437 .edit(changed_path_statuses, ());
5438 this.snapshot.scan_id += 1;
5439 }
5440
5441 if let Some(updates_tx) = updates_tx {
5442 updates_tx
5443 .unbounded_send(DownstreamUpdate::UpdateRepository(
5444 this.snapshot.clone(),
5445 ))
5446 .ok();
5447 }
5448 })
5449 },
5450 );
5451 }
5452
5453 /// currently running git command and when it started
5454 pub fn current_job(&self) -> Option<JobInfo> {
5455 self.active_jobs.values().next().cloned()
5456 }
5457
5458 pub fn barrier(&mut self) -> oneshot::Receiver<()> {
5459 self.send_job(None, |_, _| async {})
5460 }
5461
5462 fn spawn_job_with_tracking<AsyncFn>(
5463 &mut self,
5464 paths: Vec<RepoPath>,
5465 git_status: pending_op::GitStatus,
5466 cx: &mut Context<Self>,
5467 f: AsyncFn,
5468 ) -> Task<Result<()>>
5469 where
5470 AsyncFn: AsyncFnOnce(WeakEntity<Repository>, &mut AsyncApp) -> Result<()> + 'static,
5471 {
5472 let ids = self.new_pending_ops_for_paths(paths, git_status);
5473
5474 cx.spawn(async move |this, cx| {
5475 let (job_status, result) = match f(this.clone(), cx).await {
5476 Ok(()) => (pending_op::JobStatus::Finished, Ok(())),
5477 Err(err) if err.is::<Canceled>() => (pending_op::JobStatus::Skipped, Ok(())),
5478 Err(err) => (pending_op::JobStatus::Error, Err(err)),
5479 };
5480
5481 this.update(cx, |this, _| {
5482 let mut edits = Vec::with_capacity(ids.len());
5483 for (id, entry) in ids {
5484 if let Some(mut ops) = this
5485 .pending_ops
5486 .get(&PathKey(entry.as_ref().clone()), ())
5487 .cloned()
5488 {
5489 if let Some(op) = ops.op_by_id_mut(id) {
5490 op.job_status = job_status;
5491 }
5492 edits.push(sum_tree::Edit::Insert(ops));
5493 }
5494 }
5495 this.pending_ops.edit(edits, ());
5496 })?;
5497
5498 result
5499 })
5500 }
5501
5502 fn new_pending_ops_for_paths(
5503 &mut self,
5504 paths: Vec<RepoPath>,
5505 git_status: pending_op::GitStatus,
5506 ) -> Vec<(PendingOpId, RepoPath)> {
5507 let mut edits = Vec::with_capacity(paths.len());
5508 let mut ids = Vec::with_capacity(paths.len());
5509 for path in paths {
5510 let mut ops = self
5511 .pending_ops
5512 .get(&PathKey(path.as_ref().clone()), ())
5513 .cloned()
5514 .unwrap_or_else(|| PendingOps::new(&path));
5515 let id = ops.max_id() + 1;
5516 ops.ops.push(PendingOp {
5517 id,
5518 git_status,
5519 job_status: pending_op::JobStatus::Running,
5520 });
5521 edits.push(sum_tree::Edit::Insert(ops));
5522 ids.push((id, path));
5523 }
5524 self.pending_ops.edit(edits, ());
5525 ids
5526 }
5527}
5528
5529fn get_permalink_in_rust_registry_src(
5530 provider_registry: Arc<GitHostingProviderRegistry>,
5531 path: PathBuf,
5532 selection: Range<u32>,
5533) -> Result<url::Url> {
5534 #[derive(Deserialize)]
5535 struct CargoVcsGit {
5536 sha1: String,
5537 }
5538
5539 #[derive(Deserialize)]
5540 struct CargoVcsInfo {
5541 git: CargoVcsGit,
5542 path_in_vcs: String,
5543 }
5544
5545 #[derive(Deserialize)]
5546 struct CargoPackage {
5547 repository: String,
5548 }
5549
5550 #[derive(Deserialize)]
5551 struct CargoToml {
5552 package: CargoPackage,
5553 }
5554
5555 let Some((dir, cargo_vcs_info_json)) = path.ancestors().skip(1).find_map(|dir| {
5556 let json = std::fs::read_to_string(dir.join(".cargo_vcs_info.json")).ok()?;
5557 Some((dir, json))
5558 }) else {
5559 bail!("No .cargo_vcs_info.json found in parent directories")
5560 };
5561 let cargo_vcs_info = serde_json::from_str::<CargoVcsInfo>(&cargo_vcs_info_json)?;
5562 let cargo_toml = std::fs::read_to_string(dir.join("Cargo.toml"))?;
5563 let manifest = toml::from_str::<CargoToml>(&cargo_toml)?;
5564 let (provider, remote) = parse_git_remote_url(provider_registry, &manifest.package.repository)
5565 .context("parsing package.repository field of manifest")?;
5566 let path = PathBuf::from(cargo_vcs_info.path_in_vcs).join(path.strip_prefix(dir).unwrap());
5567 let permalink = provider.build_permalink(
5568 remote,
5569 BuildPermalinkParams::new(
5570 &cargo_vcs_info.git.sha1,
5571 &RepoPath::from_rel_path(
5572 &RelPath::new(&path, PathStyle::local()).context("invalid path")?,
5573 ),
5574 Some(selection),
5575 ),
5576 );
5577 Ok(permalink)
5578}
5579
5580fn serialize_blame_buffer_response(blame: Option<git::blame::Blame>) -> proto::BlameBufferResponse {
5581 let Some(blame) = blame else {
5582 return proto::BlameBufferResponse {
5583 blame_response: None,
5584 };
5585 };
5586
5587 let entries = blame
5588 .entries
5589 .into_iter()
5590 .map(|entry| proto::BlameEntry {
5591 sha: entry.sha.as_bytes().into(),
5592 start_line: entry.range.start,
5593 end_line: entry.range.end,
5594 original_line_number: entry.original_line_number,
5595 author: entry.author,
5596 author_mail: entry.author_mail,
5597 author_time: entry.author_time,
5598 author_tz: entry.author_tz,
5599 committer: entry.committer_name,
5600 committer_mail: entry.committer_email,
5601 committer_time: entry.committer_time,
5602 committer_tz: entry.committer_tz,
5603 summary: entry.summary,
5604 previous: entry.previous,
5605 filename: entry.filename,
5606 })
5607 .collect::<Vec<_>>();
5608
5609 let messages = blame
5610 .messages
5611 .into_iter()
5612 .map(|(oid, message)| proto::CommitMessage {
5613 oid: oid.as_bytes().into(),
5614 message,
5615 })
5616 .collect::<Vec<_>>();
5617
5618 proto::BlameBufferResponse {
5619 blame_response: Some(proto::blame_buffer_response::BlameResponse {
5620 entries,
5621 messages,
5622 remote_url: blame.remote_url,
5623 }),
5624 }
5625}
5626
5627fn deserialize_blame_buffer_response(
5628 response: proto::BlameBufferResponse,
5629) -> Option<git::blame::Blame> {
5630 let response = response.blame_response?;
5631 let entries = response
5632 .entries
5633 .into_iter()
5634 .filter_map(|entry| {
5635 Some(git::blame::BlameEntry {
5636 sha: git::Oid::from_bytes(&entry.sha).ok()?,
5637 range: entry.start_line..entry.end_line,
5638 original_line_number: entry.original_line_number,
5639 committer_name: entry.committer,
5640 committer_time: entry.committer_time,
5641 committer_tz: entry.committer_tz,
5642 committer_email: entry.committer_mail,
5643 author: entry.author,
5644 author_mail: entry.author_mail,
5645 author_time: entry.author_time,
5646 author_tz: entry.author_tz,
5647 summary: entry.summary,
5648 previous: entry.previous,
5649 filename: entry.filename,
5650 })
5651 })
5652 .collect::<Vec<_>>();
5653
5654 let messages = response
5655 .messages
5656 .into_iter()
5657 .filter_map(|message| Some((git::Oid::from_bytes(&message.oid).ok()?, message.message)))
5658 .collect::<HashMap<_, _>>();
5659
5660 Some(Blame {
5661 entries,
5662 messages,
5663 remote_url: response.remote_url,
5664 })
5665}
5666
5667fn branch_to_proto(branch: &git::repository::Branch) -> proto::Branch {
5668 proto::Branch {
5669 is_head: branch.is_head,
5670 ref_name: branch.ref_name.to_string(),
5671 unix_timestamp: branch
5672 .most_recent_commit
5673 .as_ref()
5674 .map(|commit| commit.commit_timestamp as u64),
5675 upstream: branch.upstream.as_ref().map(|upstream| proto::GitUpstream {
5676 ref_name: upstream.ref_name.to_string(),
5677 tracking: upstream
5678 .tracking
5679 .status()
5680 .map(|upstream| proto::UpstreamTracking {
5681 ahead: upstream.ahead as u64,
5682 behind: upstream.behind as u64,
5683 }),
5684 }),
5685 most_recent_commit: branch
5686 .most_recent_commit
5687 .as_ref()
5688 .map(|commit| proto::CommitSummary {
5689 sha: commit.sha.to_string(),
5690 subject: commit.subject.to_string(),
5691 commit_timestamp: commit.commit_timestamp,
5692 author_name: commit.author_name.to_string(),
5693 }),
5694 }
5695}
5696
5697fn worktree_to_proto(worktree: &git::repository::Worktree) -> proto::Worktree {
5698 proto::Worktree {
5699 path: worktree.path.to_string_lossy().to_string(),
5700 ref_name: worktree.ref_name.to_string(),
5701 sha: worktree.sha.to_string(),
5702 }
5703}
5704
5705fn proto_to_worktree(proto: &proto::Worktree) -> git::repository::Worktree {
5706 git::repository::Worktree {
5707 path: PathBuf::from(proto.path.clone()),
5708 ref_name: proto.ref_name.clone().into(),
5709 sha: proto.sha.clone().into(),
5710 }
5711}
5712
5713fn proto_to_branch(proto: &proto::Branch) -> git::repository::Branch {
5714 git::repository::Branch {
5715 is_head: proto.is_head,
5716 ref_name: proto.ref_name.clone().into(),
5717 upstream: proto
5718 .upstream
5719 .as_ref()
5720 .map(|upstream| git::repository::Upstream {
5721 ref_name: upstream.ref_name.to_string().into(),
5722 tracking: upstream
5723 .tracking
5724 .as_ref()
5725 .map(|tracking| {
5726 git::repository::UpstreamTracking::Tracked(UpstreamTrackingStatus {
5727 ahead: tracking.ahead as u32,
5728 behind: tracking.behind as u32,
5729 })
5730 })
5731 .unwrap_or(git::repository::UpstreamTracking::Gone),
5732 }),
5733 most_recent_commit: proto.most_recent_commit.as_ref().map(|commit| {
5734 git::repository::CommitSummary {
5735 sha: commit.sha.to_string().into(),
5736 subject: commit.subject.to_string().into(),
5737 commit_timestamp: commit.commit_timestamp,
5738 author_name: commit.author_name.to_string().into(),
5739 has_parent: true,
5740 }
5741 }),
5742 }
5743}
5744
5745fn commit_details_to_proto(commit: &CommitDetails) -> proto::GitCommitDetails {
5746 proto::GitCommitDetails {
5747 sha: commit.sha.to_string(),
5748 message: commit.message.to_string(),
5749 commit_timestamp: commit.commit_timestamp,
5750 author_email: commit.author_email.to_string(),
5751 author_name: commit.author_name.to_string(),
5752 }
5753}
5754
5755fn proto_to_commit_details(proto: &proto::GitCommitDetails) -> CommitDetails {
5756 CommitDetails {
5757 sha: proto.sha.clone().into(),
5758 message: proto.message.clone().into(),
5759 commit_timestamp: proto.commit_timestamp,
5760 author_email: proto.author_email.clone().into(),
5761 author_name: proto.author_name.clone().into(),
5762 }
5763}
5764
5765async fn compute_snapshot(
5766 id: RepositoryId,
5767 work_directory_abs_path: Arc<Path>,
5768 prev_snapshot: RepositorySnapshot,
5769 backend: Arc<dyn GitRepository>,
5770) -> Result<(RepositorySnapshot, Vec<RepositoryEvent>)> {
5771 let mut events = Vec::new();
5772 let branches = backend.branches().await?;
5773 let branch = branches.into_iter().find(|branch| branch.is_head);
5774 let statuses = backend
5775 .status(&[RepoPath::from_rel_path(
5776 &RelPath::new(".".as_ref(), PathStyle::local()).unwrap(),
5777 )])
5778 .await?;
5779 let stash_entries = backend.stash_entries().await?;
5780 let statuses_by_path = SumTree::from_iter(
5781 statuses
5782 .entries
5783 .iter()
5784 .map(|(repo_path, status)| StatusEntry {
5785 repo_path: repo_path.clone(),
5786 status: *status,
5787 }),
5788 (),
5789 );
5790 let (merge_details, merge_heads_changed) =
5791 MergeDetails::load(&backend, &statuses_by_path, &prev_snapshot).await?;
5792 log::debug!("new merge details (changed={merge_heads_changed:?}): {merge_details:?}");
5793
5794 if merge_heads_changed {
5795 events.push(RepositoryEvent::MergeHeadsChanged);
5796 }
5797
5798 if statuses_by_path != prev_snapshot.statuses_by_path {
5799 events.push(RepositoryEvent::StatusesChanged)
5800 }
5801
5802 // Useful when branch is None in detached head state
5803 let head_commit = match backend.head_sha().await {
5804 Some(head_sha) => backend.show(head_sha).await.log_err(),
5805 None => None,
5806 };
5807
5808 if branch != prev_snapshot.branch || head_commit != prev_snapshot.head_commit {
5809 events.push(RepositoryEvent::BranchChanged);
5810 }
5811
5812 // Used by edit prediction data collection
5813 let remote_origin_url = backend.remote_url("origin");
5814 let remote_upstream_url = backend.remote_url("upstream");
5815
5816 let snapshot = RepositorySnapshot {
5817 id,
5818 statuses_by_path,
5819 work_directory_abs_path,
5820 path_style: prev_snapshot.path_style,
5821 scan_id: prev_snapshot.scan_id + 1,
5822 branch,
5823 head_commit,
5824 merge: merge_details,
5825 remote_origin_url,
5826 remote_upstream_url,
5827 stash_entries,
5828 };
5829
5830 Ok((snapshot, events))
5831}
5832
5833fn status_from_proto(
5834 simple_status: i32,
5835 status: Option<proto::GitFileStatus>,
5836) -> anyhow::Result<FileStatus> {
5837 use proto::git_file_status::Variant;
5838
5839 let Some(variant) = status.and_then(|status| status.variant) else {
5840 let code = proto::GitStatus::from_i32(simple_status)
5841 .with_context(|| format!("Invalid git status code: {simple_status}"))?;
5842 let result = match code {
5843 proto::GitStatus::Added => TrackedStatus {
5844 worktree_status: StatusCode::Added,
5845 index_status: StatusCode::Unmodified,
5846 }
5847 .into(),
5848 proto::GitStatus::Modified => TrackedStatus {
5849 worktree_status: StatusCode::Modified,
5850 index_status: StatusCode::Unmodified,
5851 }
5852 .into(),
5853 proto::GitStatus::Conflict => UnmergedStatus {
5854 first_head: UnmergedStatusCode::Updated,
5855 second_head: UnmergedStatusCode::Updated,
5856 }
5857 .into(),
5858 proto::GitStatus::Deleted => TrackedStatus {
5859 worktree_status: StatusCode::Deleted,
5860 index_status: StatusCode::Unmodified,
5861 }
5862 .into(),
5863 _ => anyhow::bail!("Invalid code for simple status: {simple_status}"),
5864 };
5865 return Ok(result);
5866 };
5867
5868 let result = match variant {
5869 Variant::Untracked(_) => FileStatus::Untracked,
5870 Variant::Ignored(_) => FileStatus::Ignored,
5871 Variant::Unmerged(unmerged) => {
5872 let [first_head, second_head] =
5873 [unmerged.first_head, unmerged.second_head].map(|head| {
5874 let code = proto::GitStatus::from_i32(head)
5875 .with_context(|| format!("Invalid git status code: {head}"))?;
5876 let result = match code {
5877 proto::GitStatus::Added => UnmergedStatusCode::Added,
5878 proto::GitStatus::Updated => UnmergedStatusCode::Updated,
5879 proto::GitStatus::Deleted => UnmergedStatusCode::Deleted,
5880 _ => anyhow::bail!("Invalid code for unmerged status: {code:?}"),
5881 };
5882 Ok(result)
5883 });
5884 let [first_head, second_head] = [first_head?, second_head?];
5885 UnmergedStatus {
5886 first_head,
5887 second_head,
5888 }
5889 .into()
5890 }
5891 Variant::Tracked(tracked) => {
5892 let [index_status, worktree_status] = [tracked.index_status, tracked.worktree_status]
5893 .map(|status| {
5894 let code = proto::GitStatus::from_i32(status)
5895 .with_context(|| format!("Invalid git status code: {status}"))?;
5896 let result = match code {
5897 proto::GitStatus::Modified => StatusCode::Modified,
5898 proto::GitStatus::TypeChanged => StatusCode::TypeChanged,
5899 proto::GitStatus::Added => StatusCode::Added,
5900 proto::GitStatus::Deleted => StatusCode::Deleted,
5901 proto::GitStatus::Renamed => StatusCode::Renamed,
5902 proto::GitStatus::Copied => StatusCode::Copied,
5903 proto::GitStatus::Unmodified => StatusCode::Unmodified,
5904 _ => anyhow::bail!("Invalid code for tracked status: {code:?}"),
5905 };
5906 Ok(result)
5907 });
5908 let [index_status, worktree_status] = [index_status?, worktree_status?];
5909 TrackedStatus {
5910 index_status,
5911 worktree_status,
5912 }
5913 .into()
5914 }
5915 };
5916 Ok(result)
5917}
5918
5919fn status_to_proto(status: FileStatus) -> proto::GitFileStatus {
5920 use proto::git_file_status::{Tracked, Unmerged, Variant};
5921
5922 let variant = match status {
5923 FileStatus::Untracked => Variant::Untracked(Default::default()),
5924 FileStatus::Ignored => Variant::Ignored(Default::default()),
5925 FileStatus::Unmerged(UnmergedStatus {
5926 first_head,
5927 second_head,
5928 }) => Variant::Unmerged(Unmerged {
5929 first_head: unmerged_status_to_proto(first_head),
5930 second_head: unmerged_status_to_proto(second_head),
5931 }),
5932 FileStatus::Tracked(TrackedStatus {
5933 index_status,
5934 worktree_status,
5935 }) => Variant::Tracked(Tracked {
5936 index_status: tracked_status_to_proto(index_status),
5937 worktree_status: tracked_status_to_proto(worktree_status),
5938 }),
5939 };
5940 proto::GitFileStatus {
5941 variant: Some(variant),
5942 }
5943}
5944
5945fn unmerged_status_to_proto(code: UnmergedStatusCode) -> i32 {
5946 match code {
5947 UnmergedStatusCode::Added => proto::GitStatus::Added as _,
5948 UnmergedStatusCode::Deleted => proto::GitStatus::Deleted as _,
5949 UnmergedStatusCode::Updated => proto::GitStatus::Updated as _,
5950 }
5951}
5952
5953fn tracked_status_to_proto(code: StatusCode) -> i32 {
5954 match code {
5955 StatusCode::Added => proto::GitStatus::Added as _,
5956 StatusCode::Deleted => proto::GitStatus::Deleted as _,
5957 StatusCode::Modified => proto::GitStatus::Modified as _,
5958 StatusCode::Renamed => proto::GitStatus::Renamed as _,
5959 StatusCode::TypeChanged => proto::GitStatus::TypeChanged as _,
5960 StatusCode::Copied => proto::GitStatus::Copied as _,
5961 StatusCode::Unmodified => proto::GitStatus::Unmodified as _,
5962 }
5963}