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