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