git_store.rs

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