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