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