git_store.rs

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