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