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)
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(&mut self, branch_name: String) -> oneshot::Receiver<Result<()>> {
4751        let id = self.id;
4752        self.send_job(
4753            Some(format!("git switch -c {branch_name}").into()),
4754            move |repo, _cx| async move {
4755                match repo {
4756                    RepositoryState::Local { backend, .. } => {
4757                        backend.create_branch(branch_name).await
4758                    }
4759                    RepositoryState::Remote { project_id, client } => {
4760                        client
4761                            .request(proto::GitCreateBranch {
4762                                project_id: project_id.0,
4763                                repository_id: id.to_proto(),
4764                                branch_name,
4765                            })
4766                            .await?;
4767
4768                        Ok(())
4769                    }
4770                }
4771            },
4772        )
4773    }
4774
4775    pub fn change_branch(&mut self, branch_name: String) -> oneshot::Receiver<Result<()>> {
4776        let id = self.id;
4777        self.send_job(
4778            Some(format!("git switch {branch_name}").into()),
4779            move |repo, _cx| async move {
4780                match repo {
4781                    RepositoryState::Local { backend, .. } => {
4782                        backend.change_branch(branch_name).await
4783                    }
4784                    RepositoryState::Remote { project_id, client } => {
4785                        client
4786                            .request(proto::GitChangeBranch {
4787                                project_id: project_id.0,
4788                                repository_id: id.to_proto(),
4789                                branch_name,
4790                            })
4791                            .await?;
4792
4793                        Ok(())
4794                    }
4795                }
4796            },
4797        )
4798    }
4799
4800    pub fn rename_branch(
4801        &mut self,
4802        branch: String,
4803        new_name: String,
4804    ) -> oneshot::Receiver<Result<()>> {
4805        let id = self.id;
4806        self.send_job(
4807            Some(format!("git branch -m {branch} {new_name}").into()),
4808            move |repo, _cx| async move {
4809                match repo {
4810                    RepositoryState::Local { backend, .. } => {
4811                        backend.rename_branch(branch, new_name).await
4812                    }
4813                    RepositoryState::Remote { project_id, client } => {
4814                        client
4815                            .request(proto::GitRenameBranch {
4816                                project_id: project_id.0,
4817                                repository_id: id.to_proto(),
4818                                branch,
4819                                new_name,
4820                            })
4821                            .await?;
4822
4823                        Ok(())
4824                    }
4825                }
4826            },
4827        )
4828    }
4829
4830    pub fn check_for_pushed_commits(&mut self) -> oneshot::Receiver<Result<Vec<SharedString>>> {
4831        let id = self.id;
4832        self.send_job(None, move |repo, _cx| async move {
4833            match repo {
4834                RepositoryState::Local { backend, .. } => backend.check_for_pushed_commit().await,
4835                RepositoryState::Remote { project_id, client } => {
4836                    let response = client
4837                        .request(proto::CheckForPushedCommits {
4838                            project_id: project_id.0,
4839                            repository_id: id.to_proto(),
4840                        })
4841                        .await?;
4842
4843                    let branches = response.pushed_to.into_iter().map(Into::into).collect();
4844
4845                    Ok(branches)
4846                }
4847            }
4848        })
4849    }
4850
4851    pub fn checkpoint(&mut self) -> oneshot::Receiver<Result<GitRepositoryCheckpoint>> {
4852        self.send_job(None, |repo, _cx| async move {
4853            match repo {
4854                RepositoryState::Local { backend, .. } => backend.checkpoint().await,
4855                RepositoryState::Remote { .. } => anyhow::bail!("not implemented yet"),
4856            }
4857        })
4858    }
4859
4860    pub fn restore_checkpoint(
4861        &mut self,
4862        checkpoint: GitRepositoryCheckpoint,
4863    ) -> oneshot::Receiver<Result<()>> {
4864        self.send_job(None, move |repo, _cx| async move {
4865            match repo {
4866                RepositoryState::Local { backend, .. } => {
4867                    backend.restore_checkpoint(checkpoint).await
4868                }
4869                RepositoryState::Remote { .. } => anyhow::bail!("not implemented yet"),
4870            }
4871        })
4872    }
4873
4874    pub(crate) fn apply_remote_update(
4875        &mut self,
4876        update: proto::UpdateRepository,
4877        cx: &mut Context<Self>,
4878    ) -> Result<()> {
4879        let conflicted_paths = TreeSet::from_ordered_entries(
4880            update
4881                .current_merge_conflicts
4882                .into_iter()
4883                .filter_map(|path| RepoPath::from_proto(&path).log_err()),
4884        );
4885        let new_branch = update.branch_summary.as_ref().map(proto_to_branch);
4886        let new_head_commit = update
4887            .head_commit_details
4888            .as_ref()
4889            .map(proto_to_commit_details);
4890        if self.snapshot.branch != new_branch || self.snapshot.head_commit != new_head_commit {
4891            cx.emit(RepositoryEvent::BranchChanged)
4892        }
4893        self.snapshot.branch = new_branch;
4894        self.snapshot.head_commit = new_head_commit;
4895
4896        self.snapshot.merge.conflicted_paths = conflicted_paths;
4897        self.snapshot.merge.message = update.merge_message.map(SharedString::from);
4898        let new_stash_entries = GitStash {
4899            entries: update
4900                .stash_entries
4901                .iter()
4902                .filter_map(|entry| proto_to_stash(entry).ok())
4903                .collect(),
4904        };
4905        if self.snapshot.stash_entries != new_stash_entries {
4906            cx.emit(RepositoryEvent::StashEntriesChanged)
4907        }
4908        self.snapshot.stash_entries = new_stash_entries;
4909
4910        let edits = update
4911            .removed_statuses
4912            .into_iter()
4913            .filter_map(|path| {
4914                Some(sum_tree::Edit::Remove(PathKey(
4915                    RelPath::from_proto(&path).log_err()?,
4916                )))
4917            })
4918            .chain(
4919                update
4920                    .updated_statuses
4921                    .into_iter()
4922                    .filter_map(|updated_status| {
4923                        Some(sum_tree::Edit::Insert(updated_status.try_into().log_err()?))
4924                    }),
4925            )
4926            .collect::<Vec<_>>();
4927        if !edits.is_empty() {
4928            cx.emit(RepositoryEvent::StatusesChanged { full_scan: true });
4929        }
4930        self.snapshot.statuses_by_path.edit(edits, ());
4931        if update.is_last_update {
4932            self.snapshot.scan_id = update.scan_id;
4933        }
4934        Ok(())
4935    }
4936
4937    pub fn compare_checkpoints(
4938        &mut self,
4939        left: GitRepositoryCheckpoint,
4940        right: GitRepositoryCheckpoint,
4941    ) -> oneshot::Receiver<Result<bool>> {
4942        self.send_job(None, move |repo, _cx| async move {
4943            match repo {
4944                RepositoryState::Local { backend, .. } => {
4945                    backend.compare_checkpoints(left, right).await
4946                }
4947                RepositoryState::Remote { .. } => anyhow::bail!("not implemented yet"),
4948            }
4949        })
4950    }
4951
4952    pub fn diff_checkpoints(
4953        &mut self,
4954        base_checkpoint: GitRepositoryCheckpoint,
4955        target_checkpoint: GitRepositoryCheckpoint,
4956    ) -> oneshot::Receiver<Result<String>> {
4957        self.send_job(None, move |repo, _cx| async move {
4958            match repo {
4959                RepositoryState::Local { backend, .. } => {
4960                    backend
4961                        .diff_checkpoints(base_checkpoint, target_checkpoint)
4962                        .await
4963                }
4964                RepositoryState::Remote { .. } => anyhow::bail!("not implemented yet"),
4965            }
4966        })
4967    }
4968
4969    fn schedule_scan(
4970        &mut self,
4971        updates_tx: Option<mpsc::UnboundedSender<DownstreamUpdate>>,
4972        cx: &mut Context<Self>,
4973    ) {
4974        let this = cx.weak_entity();
4975        let _ = self.send_keyed_job(
4976            Some(GitJobKey::ReloadGitState),
4977            None,
4978            |state, mut cx| async move {
4979                log::debug!("run scheduled git status scan");
4980
4981                let Some(this) = this.upgrade() else {
4982                    return Ok(());
4983                };
4984                let RepositoryState::Local { backend, .. } = state else {
4985                    bail!("not a local repository")
4986                };
4987                let (snapshot, events) = this
4988                    .update(&mut cx, |this, _| {
4989                        this.paths_needing_status_update.clear();
4990                        compute_snapshot(
4991                            this.id,
4992                            this.work_directory_abs_path.clone(),
4993                            this.snapshot.clone(),
4994                            backend.clone(),
4995                        )
4996                    })?
4997                    .await?;
4998                this.update(&mut cx, |this, cx| {
4999                    this.snapshot = snapshot.clone();
5000                    for event in events {
5001                        cx.emit(event);
5002                    }
5003                })?;
5004                if let Some(updates_tx) = updates_tx {
5005                    updates_tx
5006                        .unbounded_send(DownstreamUpdate::UpdateRepository(snapshot))
5007                        .ok();
5008                }
5009                Ok(())
5010            },
5011        );
5012    }
5013
5014    fn spawn_local_git_worker(
5015        work_directory_abs_path: Arc<Path>,
5016        dot_git_abs_path: Arc<Path>,
5017        _repository_dir_abs_path: Arc<Path>,
5018        _common_dir_abs_path: Arc<Path>,
5019        project_environment: WeakEntity<ProjectEnvironment>,
5020        fs: Arc<dyn Fs>,
5021        cx: &mut Context<Self>,
5022    ) -> mpsc::UnboundedSender<GitJob> {
5023        let (job_tx, mut job_rx) = mpsc::unbounded::<GitJob>();
5024
5025        cx.spawn(async move |_, cx| {
5026            let environment = project_environment
5027                .upgrade()
5028                .context("missing project environment")?
5029                .update(cx, |project_environment, cx| {
5030                    project_environment.local_directory_environment(&Shell::System, work_directory_abs_path.clone(), cx)
5031                })?
5032                .await
5033                .unwrap_or_else(|| {
5034                    log::error!("failed to get working directory environment for repository {work_directory_abs_path:?}");
5035                    HashMap::default()
5036                });
5037            let search_paths = environment.get("PATH").map(|val| val.to_owned());
5038            let backend = cx
5039                .background_spawn(async move {
5040                    let system_git_binary_path = search_paths.and_then(|search_paths| which::which_in("git", Some(search_paths), &work_directory_abs_path).ok())
5041                        .or_else(|| which::which("git").ok());
5042                    fs.open_repo(&dot_git_abs_path, system_git_binary_path.as_deref())
5043                        .with_context(|| format!("opening repository at {dot_git_abs_path:?}"))
5044                })
5045                .await?;
5046
5047            if let Some(git_hosting_provider_registry) =
5048                cx.update(|cx| GitHostingProviderRegistry::try_global(cx))?
5049            {
5050                git_hosting_providers::register_additional_providers(
5051                    git_hosting_provider_registry,
5052                    backend.clone(),
5053                );
5054            }
5055
5056            let state = RepositoryState::Local {
5057                backend,
5058                environment: Arc::new(environment),
5059            };
5060            let mut jobs = VecDeque::new();
5061            loop {
5062                while let Ok(Some(next_job)) = job_rx.try_next() {
5063                    jobs.push_back(next_job);
5064                }
5065
5066                if let Some(job) = jobs.pop_front() {
5067                    if let Some(current_key) = &job.key
5068                        && jobs
5069                            .iter()
5070                            .any(|other_job| other_job.key.as_ref() == Some(current_key))
5071                        {
5072                            continue;
5073                        }
5074                    (job.job)(state.clone(), cx).await;
5075                } else if let Some(job) = job_rx.next().await {
5076                    jobs.push_back(job);
5077                } else {
5078                    break;
5079                }
5080            }
5081            anyhow::Ok(())
5082        })
5083        .detach_and_log_err(cx);
5084
5085        job_tx
5086    }
5087
5088    fn spawn_remote_git_worker(
5089        project_id: ProjectId,
5090        client: AnyProtoClient,
5091        cx: &mut Context<Self>,
5092    ) -> mpsc::UnboundedSender<GitJob> {
5093        let (job_tx, mut job_rx) = mpsc::unbounded::<GitJob>();
5094
5095        cx.spawn(async move |_, cx| {
5096            let state = RepositoryState::Remote { project_id, client };
5097            let mut jobs = VecDeque::new();
5098            loop {
5099                while let Ok(Some(next_job)) = job_rx.try_next() {
5100                    jobs.push_back(next_job);
5101                }
5102
5103                if let Some(job) = jobs.pop_front() {
5104                    if let Some(current_key) = &job.key
5105                        && jobs
5106                            .iter()
5107                            .any(|other_job| other_job.key.as_ref() == Some(current_key))
5108                    {
5109                        continue;
5110                    }
5111                    (job.job)(state.clone(), cx).await;
5112                } else if let Some(job) = job_rx.next().await {
5113                    jobs.push_back(job);
5114                } else {
5115                    break;
5116                }
5117            }
5118            anyhow::Ok(())
5119        })
5120        .detach_and_log_err(cx);
5121
5122        job_tx
5123    }
5124
5125    fn load_staged_text(
5126        &mut self,
5127        buffer_id: BufferId,
5128        repo_path: RepoPath,
5129        cx: &App,
5130    ) -> Task<Result<Option<String>>> {
5131        let rx = self.send_job(None, move |state, _| async move {
5132            match state {
5133                RepositoryState::Local { backend, .. } => {
5134                    anyhow::Ok(backend.load_index_text(repo_path).await)
5135                }
5136                RepositoryState::Remote { project_id, client } => {
5137                    let response = client
5138                        .request(proto::OpenUnstagedDiff {
5139                            project_id: project_id.to_proto(),
5140                            buffer_id: buffer_id.to_proto(),
5141                        })
5142                        .await?;
5143                    Ok(response.staged_text)
5144                }
5145            }
5146        });
5147        cx.spawn(|_: &mut AsyncApp| async move { rx.await? })
5148    }
5149
5150    fn load_committed_text(
5151        &mut self,
5152        buffer_id: BufferId,
5153        repo_path: RepoPath,
5154        cx: &App,
5155    ) -> Task<Result<DiffBasesChange>> {
5156        let rx = self.send_job(None, move |state, _| async move {
5157            match state {
5158                RepositoryState::Local { backend, .. } => {
5159                    let committed_text = backend.load_committed_text(repo_path.clone()).await;
5160                    let staged_text = backend.load_index_text(repo_path).await;
5161                    let diff_bases_change = if committed_text == staged_text {
5162                        DiffBasesChange::SetBoth(committed_text)
5163                    } else {
5164                        DiffBasesChange::SetEach {
5165                            index: staged_text,
5166                            head: committed_text,
5167                        }
5168                    };
5169                    anyhow::Ok(diff_bases_change)
5170                }
5171                RepositoryState::Remote { project_id, client } => {
5172                    use proto::open_uncommitted_diff_response::Mode;
5173
5174                    let response = client
5175                        .request(proto::OpenUncommittedDiff {
5176                            project_id: project_id.to_proto(),
5177                            buffer_id: buffer_id.to_proto(),
5178                        })
5179                        .await?;
5180                    let mode = Mode::from_i32(response.mode).context("Invalid mode")?;
5181                    let bases = match mode {
5182                        Mode::IndexMatchesHead => DiffBasesChange::SetBoth(response.committed_text),
5183                        Mode::IndexAndHead => DiffBasesChange::SetEach {
5184                            head: response.committed_text,
5185                            index: response.staged_text,
5186                        },
5187                    };
5188                    Ok(bases)
5189                }
5190            }
5191        });
5192
5193        cx.spawn(|_: &mut AsyncApp| async move { rx.await? })
5194    }
5195    fn load_blob_content(&mut self, oid: Oid, cx: &App) -> Task<Result<String>> {
5196        let repository_id = self.snapshot.id;
5197        let rx = self.send_job(None, move |state, _| async move {
5198            match state {
5199                RepositoryState::Local { backend, .. } => backend.load_blob_content(oid).await,
5200                RepositoryState::Remote { client, project_id } => {
5201                    let response = client
5202                        .request(proto::GetBlobContent {
5203                            project_id: project_id.to_proto(),
5204                            repository_id: repository_id.0,
5205                            oid: oid.to_string(),
5206                        })
5207                        .await?;
5208                    Ok(response.content)
5209                }
5210            }
5211        });
5212        cx.spawn(|_: &mut AsyncApp| async move { rx.await? })
5213    }
5214
5215    fn paths_changed(
5216        &mut self,
5217        paths: Vec<RepoPath>,
5218        updates_tx: Option<mpsc::UnboundedSender<DownstreamUpdate>>,
5219        cx: &mut Context<Self>,
5220    ) {
5221        self.paths_needing_status_update.extend(paths);
5222
5223        let this = cx.weak_entity();
5224        let _ = self.send_keyed_job(
5225            Some(GitJobKey::RefreshStatuses),
5226            None,
5227            |state, mut cx| async move {
5228                let (prev_snapshot, mut changed_paths) = this.update(&mut cx, |this, _| {
5229                    (
5230                        this.snapshot.clone(),
5231                        mem::take(&mut this.paths_needing_status_update),
5232                    )
5233                })?;
5234                let RepositoryState::Local { backend, .. } = state else {
5235                    bail!("not a local repository")
5236                };
5237
5238                let paths = changed_paths.iter().cloned().collect::<Vec<_>>();
5239                if paths.is_empty() {
5240                    return Ok(());
5241                }
5242                let statuses = backend.status(&paths).await?;
5243                let stash_entries = backend.stash_entries().await?;
5244
5245                let changed_path_statuses = cx
5246                    .background_spawn(async move {
5247                        let mut changed_path_statuses = Vec::new();
5248                        let prev_statuses = prev_snapshot.statuses_by_path.clone();
5249                        let mut cursor = prev_statuses.cursor::<PathProgress>(());
5250
5251                        for (repo_path, status) in &*statuses.entries {
5252                            changed_paths.remove(repo_path);
5253                            if cursor.seek_forward(&PathTarget::Path(repo_path), Bias::Left)
5254                                && cursor.item().is_some_and(|entry| entry.status == *status)
5255                            {
5256                                continue;
5257                            }
5258
5259                            changed_path_statuses.push(Edit::Insert(StatusEntry {
5260                                repo_path: repo_path.clone(),
5261                                status: *status,
5262                            }));
5263                        }
5264                        let mut cursor = prev_statuses.cursor::<PathProgress>(());
5265                        for path in changed_paths.into_iter() {
5266                            if cursor.seek_forward(&PathTarget::Path(&path), Bias::Left) {
5267                                changed_path_statuses.push(Edit::Remove(PathKey(path.0)));
5268                            }
5269                        }
5270                        changed_path_statuses
5271                    })
5272                    .await;
5273
5274                this.update(&mut cx, |this, cx| {
5275                    if this.snapshot.stash_entries != stash_entries {
5276                        cx.emit(RepositoryEvent::StashEntriesChanged);
5277                        this.snapshot.stash_entries = stash_entries;
5278                    }
5279
5280                    if !changed_path_statuses.is_empty() {
5281                        cx.emit(RepositoryEvent::StatusesChanged { full_scan: false });
5282                        this.snapshot
5283                            .statuses_by_path
5284                            .edit(changed_path_statuses, ());
5285                        this.snapshot.scan_id += 1;
5286                    }
5287
5288                    if let Some(updates_tx) = updates_tx {
5289                        updates_tx
5290                            .unbounded_send(DownstreamUpdate::UpdateRepository(
5291                                this.snapshot.clone(),
5292                            ))
5293                            .ok();
5294                    }
5295                })
5296            },
5297        );
5298    }
5299
5300    /// currently running git command and when it started
5301    pub fn current_job(&self) -> Option<JobInfo> {
5302        self.active_jobs.values().next().cloned()
5303    }
5304
5305    pub fn barrier(&mut self) -> oneshot::Receiver<()> {
5306        self.send_job(None, |_, _| async {})
5307    }
5308
5309    fn spawn_job_with_tracking<AsyncFn>(
5310        &mut self,
5311        paths: Vec<RepoPath>,
5312        git_status: pending_op::GitStatus,
5313        cx: &mut Context<Self>,
5314        f: AsyncFn,
5315    ) -> Task<Result<()>>
5316    where
5317        AsyncFn: AsyncFnOnce(WeakEntity<Repository>, &mut AsyncApp) -> Result<()> + 'static,
5318    {
5319        let ids = self.new_pending_ops_for_paths(paths, git_status);
5320
5321        cx.spawn(async move |this, cx| {
5322            let (job_status, result) = match f(this.clone(), cx).await {
5323                Ok(()) => (pending_op::JobStatus::Finished, Ok(())),
5324                Err(err) if err.is::<Canceled>() => (pending_op::JobStatus::Skipped, Ok(())),
5325                Err(err) => (pending_op::JobStatus::Error, Err(err)),
5326            };
5327
5328            this.update(cx, |this, _| {
5329                let mut edits = Vec::with_capacity(ids.len());
5330                for (id, entry) in ids {
5331                    if let Some(mut ops) = this.snapshot.pending_ops_for_path(&entry) {
5332                        if let Some(op) = ops.op_by_id_mut(id) {
5333                            op.job_status = job_status;
5334                        }
5335                        edits.push(sum_tree::Edit::Insert(ops));
5336                    }
5337                }
5338                this.snapshot.pending_ops_by_path.edit(edits, ());
5339            })?;
5340
5341            result
5342        })
5343    }
5344
5345    fn new_pending_ops_for_paths(
5346        &mut self,
5347        paths: Vec<RepoPath>,
5348        git_status: pending_op::GitStatus,
5349    ) -> Vec<(PendingOpId, RepoPath)> {
5350        let mut edits = Vec::with_capacity(paths.len());
5351        let mut ids = Vec::with_capacity(paths.len());
5352        for path in paths {
5353            let mut ops = self
5354                .snapshot
5355                .pending_ops_for_path(&path)
5356                .unwrap_or_else(|| PendingOps::new(&path));
5357            let id = ops.max_id() + 1;
5358            ops.ops.push(PendingOp {
5359                id,
5360                git_status,
5361                job_status: pending_op::JobStatus::Running,
5362            });
5363            edits.push(sum_tree::Edit::Insert(ops));
5364            ids.push((id, path));
5365        }
5366        self.snapshot.pending_ops_by_path.edit(edits, ());
5367        ids
5368    }
5369}
5370
5371fn get_permalink_in_rust_registry_src(
5372    provider_registry: Arc<GitHostingProviderRegistry>,
5373    path: PathBuf,
5374    selection: Range<u32>,
5375) -> Result<url::Url> {
5376    #[derive(Deserialize)]
5377    struct CargoVcsGit {
5378        sha1: String,
5379    }
5380
5381    #[derive(Deserialize)]
5382    struct CargoVcsInfo {
5383        git: CargoVcsGit,
5384        path_in_vcs: String,
5385    }
5386
5387    #[derive(Deserialize)]
5388    struct CargoPackage {
5389        repository: String,
5390    }
5391
5392    #[derive(Deserialize)]
5393    struct CargoToml {
5394        package: CargoPackage,
5395    }
5396
5397    let Some((dir, cargo_vcs_info_json)) = path.ancestors().skip(1).find_map(|dir| {
5398        let json = std::fs::read_to_string(dir.join(".cargo_vcs_info.json")).ok()?;
5399        Some((dir, json))
5400    }) else {
5401        bail!("No .cargo_vcs_info.json found in parent directories")
5402    };
5403    let cargo_vcs_info = serde_json::from_str::<CargoVcsInfo>(&cargo_vcs_info_json)?;
5404    let cargo_toml = std::fs::read_to_string(dir.join("Cargo.toml"))?;
5405    let manifest = toml::from_str::<CargoToml>(&cargo_toml)?;
5406    let (provider, remote) = parse_git_remote_url(provider_registry, &manifest.package.repository)
5407        .context("parsing package.repository field of manifest")?;
5408    let path = PathBuf::from(cargo_vcs_info.path_in_vcs).join(path.strip_prefix(dir).unwrap());
5409    let permalink = provider.build_permalink(
5410        remote,
5411        BuildPermalinkParams::new(
5412            &cargo_vcs_info.git.sha1,
5413            &RepoPath(
5414                RelPath::new(&path, PathStyle::local())
5415                    .context("invalid path")?
5416                    .into_arc(),
5417            ),
5418            Some(selection),
5419        ),
5420    );
5421    Ok(permalink)
5422}
5423
5424fn serialize_blame_buffer_response(blame: Option<git::blame::Blame>) -> proto::BlameBufferResponse {
5425    let Some(blame) = blame else {
5426        return proto::BlameBufferResponse {
5427            blame_response: None,
5428        };
5429    };
5430
5431    let entries = blame
5432        .entries
5433        .into_iter()
5434        .map(|entry| proto::BlameEntry {
5435            sha: entry.sha.as_bytes().into(),
5436            start_line: entry.range.start,
5437            end_line: entry.range.end,
5438            original_line_number: entry.original_line_number,
5439            author: entry.author,
5440            author_mail: entry.author_mail,
5441            author_time: entry.author_time,
5442            author_tz: entry.author_tz,
5443            committer: entry.committer_name,
5444            committer_mail: entry.committer_email,
5445            committer_time: entry.committer_time,
5446            committer_tz: entry.committer_tz,
5447            summary: entry.summary,
5448            previous: entry.previous,
5449            filename: entry.filename,
5450        })
5451        .collect::<Vec<_>>();
5452
5453    let messages = blame
5454        .messages
5455        .into_iter()
5456        .map(|(oid, message)| proto::CommitMessage {
5457            oid: oid.as_bytes().into(),
5458            message,
5459        })
5460        .collect::<Vec<_>>();
5461
5462    proto::BlameBufferResponse {
5463        blame_response: Some(proto::blame_buffer_response::BlameResponse {
5464            entries,
5465            messages,
5466            remote_url: blame.remote_url,
5467        }),
5468    }
5469}
5470
5471fn deserialize_blame_buffer_response(
5472    response: proto::BlameBufferResponse,
5473) -> Option<git::blame::Blame> {
5474    let response = response.blame_response?;
5475    let entries = response
5476        .entries
5477        .into_iter()
5478        .filter_map(|entry| {
5479            Some(git::blame::BlameEntry {
5480                sha: git::Oid::from_bytes(&entry.sha).ok()?,
5481                range: entry.start_line..entry.end_line,
5482                original_line_number: entry.original_line_number,
5483                committer_name: entry.committer,
5484                committer_time: entry.committer_time,
5485                committer_tz: entry.committer_tz,
5486                committer_email: entry.committer_mail,
5487                author: entry.author,
5488                author_mail: entry.author_mail,
5489                author_time: entry.author_time,
5490                author_tz: entry.author_tz,
5491                summary: entry.summary,
5492                previous: entry.previous,
5493                filename: entry.filename,
5494            })
5495        })
5496        .collect::<Vec<_>>();
5497
5498    let messages = response
5499        .messages
5500        .into_iter()
5501        .filter_map(|message| Some((git::Oid::from_bytes(&message.oid).ok()?, message.message)))
5502        .collect::<HashMap<_, _>>();
5503
5504    Some(Blame {
5505        entries,
5506        messages,
5507        remote_url: response.remote_url,
5508    })
5509}
5510
5511fn branch_to_proto(branch: &git::repository::Branch) -> proto::Branch {
5512    proto::Branch {
5513        is_head: branch.is_head,
5514        ref_name: branch.ref_name.to_string(),
5515        unix_timestamp: branch
5516            .most_recent_commit
5517            .as_ref()
5518            .map(|commit| commit.commit_timestamp as u64),
5519        upstream: branch.upstream.as_ref().map(|upstream| proto::GitUpstream {
5520            ref_name: upstream.ref_name.to_string(),
5521            tracking: upstream
5522                .tracking
5523                .status()
5524                .map(|upstream| proto::UpstreamTracking {
5525                    ahead: upstream.ahead as u64,
5526                    behind: upstream.behind as u64,
5527                }),
5528        }),
5529        most_recent_commit: branch
5530            .most_recent_commit
5531            .as_ref()
5532            .map(|commit| proto::CommitSummary {
5533                sha: commit.sha.to_string(),
5534                subject: commit.subject.to_string(),
5535                commit_timestamp: commit.commit_timestamp,
5536                author_name: commit.author_name.to_string(),
5537            }),
5538    }
5539}
5540
5541fn worktree_to_proto(worktree: &git::repository::Worktree) -> proto::Worktree {
5542    proto::Worktree {
5543        path: worktree.path.to_string_lossy().to_string(),
5544        ref_name: worktree.ref_name.to_string(),
5545        sha: worktree.sha.to_string(),
5546    }
5547}
5548
5549fn proto_to_worktree(proto: &proto::Worktree) -> git::repository::Worktree {
5550    git::repository::Worktree {
5551        path: PathBuf::from(proto.path.clone()),
5552        ref_name: proto.ref_name.clone().into(),
5553        sha: proto.sha.clone().into(),
5554    }
5555}
5556
5557fn proto_to_branch(proto: &proto::Branch) -> git::repository::Branch {
5558    git::repository::Branch {
5559        is_head: proto.is_head,
5560        ref_name: proto.ref_name.clone().into(),
5561        upstream: proto
5562            .upstream
5563            .as_ref()
5564            .map(|upstream| git::repository::Upstream {
5565                ref_name: upstream.ref_name.to_string().into(),
5566                tracking: upstream
5567                    .tracking
5568                    .as_ref()
5569                    .map(|tracking| {
5570                        git::repository::UpstreamTracking::Tracked(UpstreamTrackingStatus {
5571                            ahead: tracking.ahead as u32,
5572                            behind: tracking.behind as u32,
5573                        })
5574                    })
5575                    .unwrap_or(git::repository::UpstreamTracking::Gone),
5576            }),
5577        most_recent_commit: proto.most_recent_commit.as_ref().map(|commit| {
5578            git::repository::CommitSummary {
5579                sha: commit.sha.to_string().into(),
5580                subject: commit.subject.to_string().into(),
5581                commit_timestamp: commit.commit_timestamp,
5582                author_name: commit.author_name.to_string().into(),
5583                has_parent: true,
5584            }
5585        }),
5586    }
5587}
5588
5589fn commit_details_to_proto(commit: &CommitDetails) -> proto::GitCommitDetails {
5590    proto::GitCommitDetails {
5591        sha: commit.sha.to_string(),
5592        message: commit.message.to_string(),
5593        commit_timestamp: commit.commit_timestamp,
5594        author_email: commit.author_email.to_string(),
5595        author_name: commit.author_name.to_string(),
5596    }
5597}
5598
5599fn proto_to_commit_details(proto: &proto::GitCommitDetails) -> CommitDetails {
5600    CommitDetails {
5601        sha: proto.sha.clone().into(),
5602        message: proto.message.clone().into(),
5603        commit_timestamp: proto.commit_timestamp,
5604        author_email: proto.author_email.clone().into(),
5605        author_name: proto.author_name.clone().into(),
5606    }
5607}
5608
5609async fn compute_snapshot(
5610    id: RepositoryId,
5611    work_directory_abs_path: Arc<Path>,
5612    prev_snapshot: RepositorySnapshot,
5613    backend: Arc<dyn GitRepository>,
5614) -> Result<(RepositorySnapshot, Vec<RepositoryEvent>)> {
5615    let mut events = Vec::new();
5616    let branches = backend.branches().await?;
5617    let branch = branches.into_iter().find(|branch| branch.is_head);
5618    let statuses = backend.status(&[RelPath::empty().into()]).await?;
5619    let stash_entries = backend.stash_entries().await?;
5620    let statuses_by_path = SumTree::from_iter(
5621        statuses
5622            .entries
5623            .iter()
5624            .map(|(repo_path, status)| StatusEntry {
5625                repo_path: repo_path.clone(),
5626                status: *status,
5627            }),
5628        (),
5629    );
5630    let (merge_details, merge_heads_changed) =
5631        MergeDetails::load(&backend, &statuses_by_path, &prev_snapshot).await?;
5632    log::debug!("new merge details (changed={merge_heads_changed:?}): {merge_details:?}");
5633
5634    let pending_ops_by_path = SumTree::from_iter(
5635        prev_snapshot.pending_ops_by_path.iter().filter_map(|ops| {
5636            let inner_ops: Vec<PendingOp> =
5637                ops.ops.iter().filter(|op| op.running()).cloned().collect();
5638            if inner_ops.is_empty() {
5639                None
5640            } else {
5641                Some(PendingOps {
5642                    repo_path: ops.repo_path.clone(),
5643                    ops: inner_ops,
5644                })
5645            }
5646        }),
5647        (),
5648    );
5649
5650    if pending_ops_by_path != prev_snapshot.pending_ops_by_path {
5651        events.push(RepositoryEvent::PendingOpsChanged {
5652            pending_ops: prev_snapshot.pending_ops_by_path.clone(),
5653        })
5654    }
5655
5656    if merge_heads_changed {
5657        events.push(RepositoryEvent::MergeHeadsChanged);
5658    }
5659
5660    if statuses_by_path != prev_snapshot.statuses_by_path {
5661        events.push(RepositoryEvent::StatusesChanged { full_scan: true })
5662    }
5663
5664    // Useful when branch is None in detached head state
5665    let head_commit = match backend.head_sha().await {
5666        Some(head_sha) => backend.show(head_sha).await.log_err(),
5667        None => None,
5668    };
5669
5670    if branch != prev_snapshot.branch || head_commit != prev_snapshot.head_commit {
5671        events.push(RepositoryEvent::BranchChanged);
5672    }
5673
5674    // Used by edit prediction data collection
5675    let remote_origin_url = backend.remote_url("origin");
5676    let remote_upstream_url = backend.remote_url("upstream");
5677
5678    let snapshot = RepositorySnapshot {
5679        id,
5680        statuses_by_path,
5681        pending_ops_by_path,
5682        work_directory_abs_path,
5683        path_style: prev_snapshot.path_style,
5684        scan_id: prev_snapshot.scan_id + 1,
5685        branch,
5686        head_commit,
5687        merge: merge_details,
5688        remote_origin_url,
5689        remote_upstream_url,
5690        stash_entries,
5691    };
5692
5693    Ok((snapshot, events))
5694}
5695
5696fn status_from_proto(
5697    simple_status: i32,
5698    status: Option<proto::GitFileStatus>,
5699) -> anyhow::Result<FileStatus> {
5700    use proto::git_file_status::Variant;
5701
5702    let Some(variant) = status.and_then(|status| status.variant) else {
5703        let code = proto::GitStatus::from_i32(simple_status)
5704            .with_context(|| format!("Invalid git status code: {simple_status}"))?;
5705        let result = match code {
5706            proto::GitStatus::Added => TrackedStatus {
5707                worktree_status: StatusCode::Added,
5708                index_status: StatusCode::Unmodified,
5709            }
5710            .into(),
5711            proto::GitStatus::Modified => TrackedStatus {
5712                worktree_status: StatusCode::Modified,
5713                index_status: StatusCode::Unmodified,
5714            }
5715            .into(),
5716            proto::GitStatus::Conflict => UnmergedStatus {
5717                first_head: UnmergedStatusCode::Updated,
5718                second_head: UnmergedStatusCode::Updated,
5719            }
5720            .into(),
5721            proto::GitStatus::Deleted => TrackedStatus {
5722                worktree_status: StatusCode::Deleted,
5723                index_status: StatusCode::Unmodified,
5724            }
5725            .into(),
5726            _ => anyhow::bail!("Invalid code for simple status: {simple_status}"),
5727        };
5728        return Ok(result);
5729    };
5730
5731    let result = match variant {
5732        Variant::Untracked(_) => FileStatus::Untracked,
5733        Variant::Ignored(_) => FileStatus::Ignored,
5734        Variant::Unmerged(unmerged) => {
5735            let [first_head, second_head] =
5736                [unmerged.first_head, unmerged.second_head].map(|head| {
5737                    let code = proto::GitStatus::from_i32(head)
5738                        .with_context(|| format!("Invalid git status code: {head}"))?;
5739                    let result = match code {
5740                        proto::GitStatus::Added => UnmergedStatusCode::Added,
5741                        proto::GitStatus::Updated => UnmergedStatusCode::Updated,
5742                        proto::GitStatus::Deleted => UnmergedStatusCode::Deleted,
5743                        _ => anyhow::bail!("Invalid code for unmerged status: {code:?}"),
5744                    };
5745                    Ok(result)
5746                });
5747            let [first_head, second_head] = [first_head?, second_head?];
5748            UnmergedStatus {
5749                first_head,
5750                second_head,
5751            }
5752            .into()
5753        }
5754        Variant::Tracked(tracked) => {
5755            let [index_status, worktree_status] = [tracked.index_status, tracked.worktree_status]
5756                .map(|status| {
5757                    let code = proto::GitStatus::from_i32(status)
5758                        .with_context(|| format!("Invalid git status code: {status}"))?;
5759                    let result = match code {
5760                        proto::GitStatus::Modified => StatusCode::Modified,
5761                        proto::GitStatus::TypeChanged => StatusCode::TypeChanged,
5762                        proto::GitStatus::Added => StatusCode::Added,
5763                        proto::GitStatus::Deleted => StatusCode::Deleted,
5764                        proto::GitStatus::Renamed => StatusCode::Renamed,
5765                        proto::GitStatus::Copied => StatusCode::Copied,
5766                        proto::GitStatus::Unmodified => StatusCode::Unmodified,
5767                        _ => anyhow::bail!("Invalid code for tracked status: {code:?}"),
5768                    };
5769                    Ok(result)
5770                });
5771            let [index_status, worktree_status] = [index_status?, worktree_status?];
5772            TrackedStatus {
5773                index_status,
5774                worktree_status,
5775            }
5776            .into()
5777        }
5778    };
5779    Ok(result)
5780}
5781
5782fn status_to_proto(status: FileStatus) -> proto::GitFileStatus {
5783    use proto::git_file_status::{Tracked, Unmerged, Variant};
5784
5785    let variant = match status {
5786        FileStatus::Untracked => Variant::Untracked(Default::default()),
5787        FileStatus::Ignored => Variant::Ignored(Default::default()),
5788        FileStatus::Unmerged(UnmergedStatus {
5789            first_head,
5790            second_head,
5791        }) => Variant::Unmerged(Unmerged {
5792            first_head: unmerged_status_to_proto(first_head),
5793            second_head: unmerged_status_to_proto(second_head),
5794        }),
5795        FileStatus::Tracked(TrackedStatus {
5796            index_status,
5797            worktree_status,
5798        }) => Variant::Tracked(Tracked {
5799            index_status: tracked_status_to_proto(index_status),
5800            worktree_status: tracked_status_to_proto(worktree_status),
5801        }),
5802    };
5803    proto::GitFileStatus {
5804        variant: Some(variant),
5805    }
5806}
5807
5808fn unmerged_status_to_proto(code: UnmergedStatusCode) -> i32 {
5809    match code {
5810        UnmergedStatusCode::Added => proto::GitStatus::Added as _,
5811        UnmergedStatusCode::Deleted => proto::GitStatus::Deleted as _,
5812        UnmergedStatusCode::Updated => proto::GitStatus::Updated as _,
5813    }
5814}
5815
5816fn tracked_status_to_proto(code: StatusCode) -> i32 {
5817    match code {
5818        StatusCode::Added => proto::GitStatus::Added as _,
5819        StatusCode::Deleted => proto::GitStatus::Deleted as _,
5820        StatusCode::Modified => proto::GitStatus::Modified as _,
5821        StatusCode::Renamed => proto::GitStatus::Renamed as _,
5822        StatusCode::TypeChanged => proto::GitStatus::TypeChanged as _,
5823        StatusCode::Copied => proto::GitStatus::Copied as _,
5824        StatusCode::Unmodified => proto::GitStatus::Unmodified as _,
5825    }
5826}