git_store.rs

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