1use anyhow::{Context as _, Result};
  2use buffer_diff::{BufferDiff, BufferDiffSnapshot};
  3use editor::{Editor, EditorEvent, MultiBuffer, SelectionEffects, multibuffer_context_lines};
  4use git::repository::{CommitDetails, CommitDiff, RepoPath};
  5use gpui::{
  6    Action, AnyElement, AnyView, App, AppContext as _, AsyncApp, AsyncWindowContext, Context,
  7    Entity, EventEmitter, FocusHandle, Focusable, IntoElement, PromptLevel, Render, Task,
  8    WeakEntity, Window, actions,
  9};
 10use language::{
 11    Anchor, Buffer, Capability, DiskState, File, LanguageRegistry, LineEnding, OffsetRangeExt as _,
 12    Point, ReplicaId, Rope, TextBuffer,
 13};
 14use multi_buffer::PathKey;
 15use project::{Project, WorktreeId, git_store::Repository};
 16use std::{
 17    any::{Any, TypeId},
 18    fmt::Write as _,
 19    path::PathBuf,
 20    sync::Arc,
 21};
 22use ui::{
 23    Button, Color, Icon, IconName, Label, LabelCommon as _, SharedString, Tooltip, prelude::*,
 24};
 25use util::{ResultExt, paths::PathStyle, rel_path::RelPath, truncate_and_trailoff};
 26use workspace::{
 27    Item, ItemHandle, ItemNavHistory, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
 28    Workspace,
 29    item::{BreadcrumbText, ItemEvent, TabContentParams},
 30    notifications::NotifyTaskExt,
 31    pane::SaveIntent,
 32    searchable::SearchableItemHandle,
 33};
 34
 35use crate::git_panel::GitPanel;
 36
 37actions!(git, [ApplyCurrentStash, PopCurrentStash, DropCurrentStash,]);
 38
 39pub fn init(cx: &mut App) {
 40    cx.observe_new(|workspace: &mut Workspace, _window, _cx| {
 41        register_workspace_action(workspace, |toolbar, _: &ApplyCurrentStash, window, cx| {
 42            toolbar.apply_stash(window, cx);
 43        });
 44        register_workspace_action(workspace, |toolbar, _: &DropCurrentStash, window, cx| {
 45            toolbar.remove_stash(window, cx);
 46        });
 47        register_workspace_action(workspace, |toolbar, _: &PopCurrentStash, window, cx| {
 48            toolbar.pop_stash(window, cx);
 49        });
 50    })
 51    .detach();
 52}
 53
 54pub struct CommitView {
 55    commit: CommitDetails,
 56    editor: Entity<Editor>,
 57    stash: Option<usize>,
 58    multibuffer: Entity<MultiBuffer>,
 59}
 60
 61struct GitBlob {
 62    path: RepoPath,
 63    worktree_id: WorktreeId,
 64    is_deleted: bool,
 65}
 66
 67struct CommitMetadataFile {
 68    title: Arc<RelPath>,
 69    worktree_id: WorktreeId,
 70}
 71
 72const COMMIT_METADATA_SORT_PREFIX: u64 = 0;
 73const FILE_NAMESPACE_SORT_PREFIX: u64 = 1;
 74
 75impl CommitView {
 76    pub fn open(
 77        commit_sha: String,
 78        repo: WeakEntity<Repository>,
 79        workspace: WeakEntity<Workspace>,
 80        stash: Option<usize>,
 81        window: &mut Window,
 82        cx: &mut App,
 83    ) {
 84        let commit_diff = repo
 85            .update(cx, |repo, _| repo.load_commit_diff(commit_sha.clone()))
 86            .ok();
 87        let commit_details = repo
 88            .update(cx, |repo, _| repo.show(commit_sha.clone()))
 89            .ok();
 90
 91        window
 92            .spawn(cx, async move |cx| {
 93                let (commit_diff, commit_details) = futures::join!(commit_diff?, commit_details?);
 94                let commit_diff = commit_diff.log_err()?.log_err()?;
 95                let commit_details = commit_details.log_err()?.log_err()?;
 96                let repo = repo.upgrade()?;
 97
 98                workspace
 99                    .update_in(cx, |workspace, window, cx| {
100                        let project = workspace.project();
101                        let commit_view = cx.new(|cx| {
102                            CommitView::new(
103                                commit_details,
104                                commit_diff,
105                                repo,
106                                project.clone(),
107                                stash,
108                                window,
109                                cx,
110                            )
111                        });
112
113                        let pane = workspace.active_pane();
114                        pane.update(cx, |pane, cx| {
115                            let ix = pane.items().position(|item| {
116                                let commit_view = item.downcast::<CommitView>();
117                                commit_view
118                                    .is_some_and(|view| view.read(cx).commit.sha == commit_sha)
119                            });
120                            if let Some(ix) = ix {
121                                pane.activate_item(ix, true, true, window, cx);
122                            } else {
123                                pane.add_item(Box::new(commit_view), true, true, None, window, cx);
124                            }
125                        })
126                    })
127                    .log_err()
128            })
129            .detach();
130    }
131
132    fn new(
133        commit: CommitDetails,
134        commit_diff: CommitDiff,
135        repository: Entity<Repository>,
136        project: Entity<Project>,
137        stash: Option<usize>,
138        window: &mut Window,
139        cx: &mut Context<Self>,
140    ) -> Self {
141        let language_registry = project.read(cx).languages().clone();
142        let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadOnly));
143        let editor = cx.new(|cx| {
144            let mut editor =
145                Editor::for_multibuffer(multibuffer.clone(), Some(project.clone()), window, cx);
146            editor.disable_inline_diagnostics();
147            editor.set_expand_all_diff_hunks(cx);
148            editor
149        });
150
151        let first_worktree_id = project
152            .read(cx)
153            .worktrees(cx)
154            .next()
155            .map(|worktree| worktree.read(cx).id());
156
157        let mut metadata_buffer_id = None;
158        if let Some(worktree_id) = first_worktree_id {
159            let title = if let Some(stash) = stash {
160                format!("stash@{{{}}}", stash)
161            } else {
162                format!("commit {}", commit.sha)
163            };
164            let file = Arc::new(CommitMetadataFile {
165                title: RelPath::unix(&title).unwrap().into(),
166                worktree_id,
167            });
168            let buffer = cx.new(|cx| {
169                let buffer = TextBuffer::new_normalized(
170                    ReplicaId::LOCAL,
171                    cx.entity_id().as_non_zero_u64().into(),
172                    LineEnding::default(),
173                    format_commit(&commit, stash.is_some()).into(),
174                );
175                metadata_buffer_id = Some(buffer.remote_id());
176                Buffer::build(buffer, Some(file.clone()), Capability::ReadWrite)
177            });
178            multibuffer.update(cx, |multibuffer, cx| {
179                multibuffer.set_excerpts_for_path(
180                    PathKey::with_sort_prefix(COMMIT_METADATA_SORT_PREFIX, file.title.clone()),
181                    buffer.clone(),
182                    vec![Point::zero()..buffer.read(cx).max_point()],
183                    0,
184                    cx,
185                );
186            });
187            editor.update(cx, |editor, cx| {
188                editor.disable_header_for_buffer(metadata_buffer_id.unwrap(), cx);
189                editor.change_selections(SelectionEffects::no_scroll(), window, cx, |selections| {
190                    selections.select_ranges(vec![0..0]);
191                });
192            });
193        }
194
195        cx.spawn(async move |this, cx| {
196            for file in commit_diff.files {
197                let is_deleted = file.new_text.is_none();
198                let new_text = file.new_text.unwrap_or_default();
199                let old_text = file.old_text;
200                let worktree_id = repository
201                    .update(cx, |repository, cx| {
202                        repository
203                            .repo_path_to_project_path(&file.path, cx)
204                            .map(|path| path.worktree_id)
205                            .or(first_worktree_id)
206                    })?
207                    .context("project has no worktrees")?;
208                let file = Arc::new(GitBlob {
209                    path: file.path.clone(),
210                    is_deleted,
211                    worktree_id,
212                }) as Arc<dyn language::File>;
213
214                let buffer = build_buffer(new_text, file, &language_registry, cx).await?;
215                let buffer_diff =
216                    build_buffer_diff(old_text, &buffer, &language_registry, cx).await?;
217
218                this.update(cx, |this, cx| {
219                    this.multibuffer.update(cx, |multibuffer, cx| {
220                        let snapshot = buffer.read(cx).snapshot();
221                        let diff = buffer_diff.read(cx);
222                        let diff_hunk_ranges = diff
223                            .hunks_intersecting_range(Anchor::MIN..Anchor::MAX, &snapshot, cx)
224                            .map(|diff_hunk| diff_hunk.buffer_range.to_point(&snapshot))
225                            .collect::<Vec<_>>();
226                        let path = snapshot.file().unwrap().path().clone();
227                        let _is_newly_added = multibuffer.set_excerpts_for_path(
228                            PathKey::with_sort_prefix(FILE_NAMESPACE_SORT_PREFIX, path),
229                            buffer,
230                            diff_hunk_ranges,
231                            multibuffer_context_lines(cx),
232                            cx,
233                        );
234                        multibuffer.add_diff(buffer_diff, cx);
235                    });
236                })?;
237            }
238            anyhow::Ok(())
239        })
240        .detach();
241
242        Self {
243            commit,
244            editor,
245            multibuffer,
246            stash,
247        }
248    }
249}
250
251impl language::File for GitBlob {
252    fn as_local(&self) -> Option<&dyn language::LocalFile> {
253        None
254    }
255
256    fn disk_state(&self) -> DiskState {
257        if self.is_deleted {
258            DiskState::Deleted
259        } else {
260            DiskState::New
261        }
262    }
263
264    fn path_style(&self, _: &App) -> PathStyle {
265        PathStyle::Posix
266    }
267
268    fn path(&self) -> &Arc<RelPath> {
269        &self.path.0
270    }
271
272    fn full_path(&self, _: &App) -> PathBuf {
273        self.path.as_std_path().to_path_buf()
274    }
275
276    fn file_name<'a>(&'a self, _: &'a App) -> &'a str {
277        self.path.file_name().unwrap()
278    }
279
280    fn worktree_id(&self, _: &App) -> WorktreeId {
281        self.worktree_id
282    }
283
284    fn to_proto(&self, _cx: &App) -> language::proto::File {
285        unimplemented!()
286    }
287
288    fn is_private(&self) -> bool {
289        false
290    }
291}
292
293impl language::File for CommitMetadataFile {
294    fn as_local(&self) -> Option<&dyn language::LocalFile> {
295        None
296    }
297
298    fn disk_state(&self) -> DiskState {
299        DiskState::New
300    }
301
302    fn path_style(&self, _: &App) -> PathStyle {
303        PathStyle::Posix
304    }
305
306    fn path(&self) -> &Arc<RelPath> {
307        &self.title
308    }
309
310    fn full_path(&self, _: &App) -> PathBuf {
311        PathBuf::from(self.title.as_unix_str().to_owned())
312    }
313
314    fn file_name<'a>(&'a self, _: &'a App) -> &'a str {
315        self.title.file_name().unwrap()
316    }
317
318    fn worktree_id(&self, _: &App) -> WorktreeId {
319        self.worktree_id
320    }
321
322    fn to_proto(&self, _: &App) -> language::proto::File {
323        unimplemented!()
324    }
325
326    fn is_private(&self) -> bool {
327        false
328    }
329}
330
331async fn build_buffer(
332    mut text: String,
333    blob: Arc<dyn File>,
334    language_registry: &Arc<language::LanguageRegistry>,
335    cx: &mut AsyncApp,
336) -> Result<Entity<Buffer>> {
337    let line_ending = LineEnding::detect(&text);
338    LineEnding::normalize(&mut text);
339    let text = Rope::from(text);
340    let language = cx.update(|cx| language_registry.language_for_file(&blob, Some(&text), cx))?;
341    let language = if let Some(language) = language {
342        language_registry
343            .load_language(&language)
344            .await
345            .ok()
346            .and_then(|e| e.log_err())
347    } else {
348        None
349    };
350    let buffer = cx.new(|cx| {
351        let buffer = TextBuffer::new_normalized(
352            ReplicaId::LOCAL,
353            cx.entity_id().as_non_zero_u64().into(),
354            line_ending,
355            text,
356        );
357        let mut buffer = Buffer::build(buffer, Some(blob), Capability::ReadWrite);
358        buffer.set_language(language, cx);
359        buffer
360    })?;
361    Ok(buffer)
362}
363
364async fn build_buffer_diff(
365    mut old_text: Option<String>,
366    buffer: &Entity<Buffer>,
367    language_registry: &Arc<LanguageRegistry>,
368    cx: &mut AsyncApp,
369) -> Result<Entity<BufferDiff>> {
370    if let Some(old_text) = &mut old_text {
371        LineEnding::normalize(old_text);
372    }
373
374    let buffer = cx.update(|cx| buffer.read(cx).snapshot())?;
375
376    let base_buffer = cx
377        .update(|cx| {
378            Buffer::build_snapshot(
379                old_text.as_deref().unwrap_or("").into(),
380                buffer.language().cloned(),
381                Some(language_registry.clone()),
382                cx,
383            )
384        })?
385        .await;
386
387    let diff_snapshot = cx
388        .update(|cx| {
389            BufferDiffSnapshot::new_with_base_buffer(
390                buffer.text.clone(),
391                old_text.map(Arc::new),
392                base_buffer,
393                cx,
394            )
395        })?
396        .await;
397
398    cx.new(|cx| {
399        let mut diff = BufferDiff::new(&buffer.text, cx);
400        diff.set_snapshot(diff_snapshot, &buffer.text, cx);
401        diff
402    })
403}
404
405fn format_commit(commit: &CommitDetails, is_stash: bool) -> String {
406    let mut result = String::new();
407    if is_stash {
408        writeln!(&mut result, "stash commit {}", commit.sha).unwrap();
409    } else {
410        writeln!(&mut result, "commit {}", commit.sha).unwrap();
411    }
412    writeln!(
413        &mut result,
414        "Author: {} <{}>",
415        commit.author_name, commit.author_email
416    )
417    .unwrap();
418    writeln!(
419        &mut result,
420        "Date:   {}",
421        time_format::format_local_timestamp(
422            time::OffsetDateTime::from_unix_timestamp(commit.commit_timestamp).unwrap(),
423            time::OffsetDateTime::now_utc(),
424            time_format::TimestampFormat::MediumAbsolute,
425        ),
426    )
427    .unwrap();
428    result.push('\n');
429    for line in commit.message.split('\n') {
430        if line.is_empty() {
431            result.push('\n');
432        } else {
433            writeln!(&mut result, "    {}", line).unwrap();
434        }
435    }
436    if result.ends_with("\n\n") {
437        result.pop();
438    }
439    result
440}
441
442impl EventEmitter<EditorEvent> for CommitView {}
443
444impl Focusable for CommitView {
445    fn focus_handle(&self, cx: &App) -> FocusHandle {
446        self.editor.focus_handle(cx)
447    }
448}
449
450impl Item for CommitView {
451    type Event = EditorEvent;
452
453    fn tab_icon(&self, _window: &Window, _cx: &App) -> Option<Icon> {
454        Some(Icon::new(IconName::GitBranch).color(Color::Muted))
455    }
456
457    fn tab_content(&self, params: TabContentParams, _window: &Window, cx: &App) -> AnyElement {
458        Label::new(self.tab_content_text(params.detail.unwrap_or_default(), cx))
459            .color(if params.selected {
460                Color::Default
461            } else {
462                Color::Muted
463            })
464            .into_any_element()
465    }
466
467    fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
468        let short_sha = self.commit.sha.get(0..7).unwrap_or(&*self.commit.sha);
469        let subject = truncate_and_trailoff(self.commit.message.split('\n').next().unwrap(), 20);
470        format!("{short_sha} - {subject}").into()
471    }
472
473    fn tab_tooltip_text(&self, _: &App) -> Option<ui::SharedString> {
474        let short_sha = self.commit.sha.get(0..16).unwrap_or(&*self.commit.sha);
475        let subject = self.commit.message.split('\n').next().unwrap();
476        Some(format!("{short_sha} - {subject}").into())
477    }
478
479    fn to_item_events(event: &EditorEvent, f: impl FnMut(ItemEvent)) {
480        Editor::to_item_events(event, f)
481    }
482
483    fn telemetry_event_text(&self) -> Option<&'static str> {
484        Some("Commit View Opened")
485    }
486
487    fn deactivated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
488        self.editor
489            .update(cx, |editor, cx| editor.deactivated(window, cx));
490    }
491
492    fn act_as_type<'a>(
493        &'a self,
494        type_id: TypeId,
495        self_handle: &'a Entity<Self>,
496        _: &'a App,
497    ) -> Option<AnyView> {
498        if type_id == TypeId::of::<Self>() {
499            Some(self_handle.to_any())
500        } else if type_id == TypeId::of::<Editor>() {
501            Some(self.editor.to_any())
502        } else {
503            None
504        }
505    }
506
507    fn as_searchable(&self, _: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
508        Some(Box::new(self.editor.clone()))
509    }
510
511    fn for_each_project_item(
512        &self,
513        cx: &App,
514        f: &mut dyn FnMut(gpui::EntityId, &dyn project::ProjectItem),
515    ) {
516        self.editor.for_each_project_item(cx, f)
517    }
518
519    fn set_nav_history(
520        &mut self,
521        nav_history: ItemNavHistory,
522        _: &mut Window,
523        cx: &mut Context<Self>,
524    ) {
525        self.editor.update(cx, |editor, _| {
526            editor.set_nav_history(Some(nav_history));
527        });
528    }
529
530    fn navigate(
531        &mut self,
532        data: Box<dyn Any>,
533        window: &mut Window,
534        cx: &mut Context<Self>,
535    ) -> bool {
536        self.editor
537            .update(cx, |editor, cx| editor.navigate(data, window, cx))
538    }
539
540    fn breadcrumb_location(&self, _: &App) -> ToolbarItemLocation {
541        ToolbarItemLocation::PrimaryLeft
542    }
543
544    fn breadcrumbs(&self, theme: &theme::Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
545        self.editor.breadcrumbs(theme, cx)
546    }
547
548    fn added_to_workspace(
549        &mut self,
550        workspace: &mut Workspace,
551        window: &mut Window,
552        cx: &mut Context<Self>,
553    ) {
554        self.editor.update(cx, |editor, cx| {
555            editor.added_to_workspace(workspace, window, cx)
556        });
557    }
558
559    fn clone_on_split(
560        &self,
561        _workspace_id: Option<workspace::WorkspaceId>,
562        window: &mut Window,
563        cx: &mut Context<Self>,
564    ) -> Task<Option<Entity<Self>>>
565    where
566        Self: Sized,
567    {
568        Task::ready(Some(cx.new(|cx| {
569            let editor = cx.new(|cx| {
570                self.editor
571                    .update(cx, |editor, cx| editor.clone(window, cx))
572            });
573            let multibuffer = editor.read(cx).buffer().clone();
574            Self {
575                editor,
576                multibuffer,
577                commit: self.commit.clone(),
578                stash: self.stash,
579            }
580        })))
581    }
582}
583
584impl Render for CommitView {
585    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
586        let is_stash = self.stash.is_some();
587        div()
588            .key_context(if is_stash { "StashDiff" } else { "CommitDiff" })
589            .bg(cx.theme().colors().editor_background)
590            .flex()
591            .items_center()
592            .justify_center()
593            .size_full()
594            .child(self.editor.clone())
595    }
596}
597
598pub struct CommitViewToolbar {
599    commit_view: Option<WeakEntity<CommitView>>,
600    workspace: WeakEntity<Workspace>,
601}
602
603impl CommitViewToolbar {
604    pub fn new(workspace: &Workspace, _: &mut Context<Self>) -> Self {
605        Self {
606            commit_view: None,
607            workspace: workspace.weak_handle(),
608        }
609    }
610
611    fn commit_view(&self, _: &App) -> Option<Entity<CommitView>> {
612        self.commit_view.as_ref()?.upgrade()
613    }
614
615    async fn close_commit_view(
616        commit_view: Entity<CommitView>,
617        workspace: WeakEntity<Workspace>,
618        cx: &mut AsyncWindowContext,
619    ) -> anyhow::Result<()> {
620        workspace
621            .update_in(cx, |workspace, window, cx| {
622                let active_pane = workspace.active_pane();
623                let commit_view_id = commit_view.entity_id();
624                active_pane.update(cx, |pane, cx| {
625                    pane.close_item_by_id(commit_view_id, SaveIntent::Skip, window, cx)
626                })
627            })?
628            .await?;
629        anyhow::Ok(())
630    }
631
632    fn apply_stash(&mut self, window: &mut Window, cx: &mut Context<Self>) {
633        self.stash_action(
634            "Apply",
635            window,
636            cx,
637            async move |repository, sha, stash, commit_view, workspace, cx| {
638                let result = repository.update(cx, |repo, cx| {
639                    if !stash_matches_index(&sha, stash, repo) {
640                        return Err(anyhow::anyhow!("Stash has changed, not applying"));
641                    }
642                    Ok(repo.stash_apply(Some(stash), cx))
643                })?;
644
645                match result {
646                    Ok(task) => task.await?,
647                    Err(err) => {
648                        Self::close_commit_view(commit_view, workspace, cx).await?;
649                        return Err(err);
650                    }
651                };
652                Self::close_commit_view(commit_view, workspace, cx).await?;
653                anyhow::Ok(())
654            },
655        );
656    }
657
658    fn pop_stash(&mut self, window: &mut Window, cx: &mut Context<Self>) {
659        self.stash_action(
660            "Pop",
661            window,
662            cx,
663            async move |repository, sha, stash, commit_view, workspace, cx| {
664                let result = repository.update(cx, |repo, cx| {
665                    if !stash_matches_index(&sha, stash, repo) {
666                        return Err(anyhow::anyhow!("Stash has changed, pop aborted"));
667                    }
668                    Ok(repo.stash_pop(Some(stash), cx))
669                })?;
670
671                match result {
672                    Ok(task) => task.await?,
673                    Err(err) => {
674                        Self::close_commit_view(commit_view, workspace, cx).await?;
675                        return Err(err);
676                    }
677                };
678                Self::close_commit_view(commit_view, workspace, cx).await?;
679                anyhow::Ok(())
680            },
681        );
682    }
683
684    fn remove_stash(&mut self, window: &mut Window, cx: &mut Context<Self>) {
685        self.stash_action(
686            "Drop",
687            window,
688            cx,
689            async move |repository, sha, stash, commit_view, workspace, cx| {
690                let result = repository.update(cx, |repo, cx| {
691                    if !stash_matches_index(&sha, stash, repo) {
692                        return Err(anyhow::anyhow!("Stash has changed, drop aborted"));
693                    }
694                    Ok(repo.stash_drop(Some(stash), cx))
695                })?;
696
697                match result {
698                    Ok(task) => task.await??,
699                    Err(err) => {
700                        Self::close_commit_view(commit_view, workspace, cx).await?;
701                        return Err(err);
702                    }
703                };
704                Self::close_commit_view(commit_view, workspace, cx).await?;
705                anyhow::Ok(())
706            },
707        );
708    }
709
710    fn stash_action<AsyncFn>(
711        &mut self,
712        str_action: &str,
713        window: &mut Window,
714        cx: &mut Context<Self>,
715        callback: AsyncFn,
716    ) where
717        AsyncFn: AsyncFnOnce(
718                Entity<Repository>,
719                &SharedString,
720                usize,
721                Entity<CommitView>,
722                WeakEntity<Workspace>,
723                &mut AsyncWindowContext,
724            ) -> anyhow::Result<()>
725            + 'static,
726    {
727        let Some(commit_view) = self.commit_view(cx) else {
728            return;
729        };
730        let Some(stash) = commit_view.read(cx).stash else {
731            return;
732        };
733        let sha = commit_view.read(cx).commit.sha.clone();
734        let answer = window.prompt(
735            PromptLevel::Info,
736            &format!("{} stash@{{{}}}?", str_action, stash),
737            None,
738            &[str_action, "Cancel"],
739            cx,
740        );
741
742        let workspace = self.workspace.clone();
743        cx.spawn_in(window, async move |_, cx| {
744            if answer.await != Ok(0) {
745                return anyhow::Ok(());
746            }
747            let repo = workspace.update(cx, |workspace, cx| {
748                workspace
749                    .panel::<GitPanel>(cx)
750                    .and_then(|p| p.read(cx).active_repository.clone())
751            })?;
752
753            let Some(repo) = repo else {
754                return Ok(());
755            };
756            callback(repo, &sha, stash, commit_view, workspace, cx).await?;
757            anyhow::Ok(())
758        })
759        .detach_and_notify_err(window, cx);
760    }
761}
762
763impl EventEmitter<ToolbarItemEvent> for CommitViewToolbar {}
764
765impl ToolbarItemView for CommitViewToolbar {
766    fn set_active_pane_item(
767        &mut self,
768        active_pane_item: Option<&dyn ItemHandle>,
769        _: &mut Window,
770        cx: &mut Context<Self>,
771    ) -> ToolbarItemLocation {
772        if let Some(entity) = active_pane_item.and_then(|i| i.act_as::<CommitView>(cx))
773            && entity.read(cx).stash.is_some()
774        {
775            self.commit_view = Some(entity.downgrade());
776            return ToolbarItemLocation::PrimaryRight;
777        }
778        ToolbarItemLocation::Hidden
779    }
780
781    fn pane_focus_update(
782        &mut self,
783        _pane_focused: bool,
784        _window: &mut Window,
785        _cx: &mut Context<Self>,
786    ) {
787    }
788}
789
790impl Render for CommitViewToolbar {
791    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
792        let Some(commit_view) = self.commit_view(cx) else {
793            return div();
794        };
795
796        let is_stash = commit_view.read(cx).stash.is_some();
797        if !is_stash {
798            return div();
799        }
800
801        let focus_handle = commit_view.focus_handle(cx);
802
803        h_group_xl().my_neg_1().py_1().items_center().child(
804            h_group_sm()
805                .child(
806                    Button::new("apply-stash", "Apply")
807                        .tooltip(Tooltip::for_action_title_in(
808                            "Apply current stash",
809                            &ApplyCurrentStash,
810                            &focus_handle,
811                        ))
812                        .on_click(cx.listener(|this, _, window, cx| this.apply_stash(window, cx))),
813                )
814                .child(
815                    Button::new("pop-stash", "Pop")
816                        .tooltip(Tooltip::for_action_title_in(
817                            "Pop current stash",
818                            &PopCurrentStash,
819                            &focus_handle,
820                        ))
821                        .on_click(cx.listener(|this, _, window, cx| this.pop_stash(window, cx))),
822                )
823                .child(
824                    Button::new("remove-stash", "Remove")
825                        .icon(IconName::Trash)
826                        .tooltip(Tooltip::for_action_title_in(
827                            "Remove current stash",
828                            &DropCurrentStash,
829                            &focus_handle,
830                        ))
831                        .on_click(cx.listener(|this, _, window, cx| this.remove_stash(window, cx))),
832                ),
833        )
834    }
835}
836
837fn register_workspace_action<A: Action>(
838    workspace: &mut Workspace,
839    callback: fn(&mut CommitViewToolbar, &A, &mut Window, &mut Context<CommitViewToolbar>),
840) {
841    workspace.register_action(move |workspace, action: &A, window, cx| {
842        if workspace.has_active_modal(window, cx) {
843            cx.propagate();
844            return;
845        }
846
847        workspace.active_pane().update(cx, |pane, cx| {
848            pane.toolbar().update(cx, move |workspace, cx| {
849                if let Some(toolbar) = workspace.item_of_type::<CommitViewToolbar>() {
850                    toolbar.update(cx, move |toolbar, cx| {
851                        callback(toolbar, action, window, cx);
852                        cx.notify();
853                    });
854                }
855            });
856        })
857    });
858}
859
860fn stash_matches_index(sha: &str, index: usize, repo: &mut Repository) -> bool {
861    match repo
862        .cached_stash()
863        .entries
864        .iter()
865        .find(|entry| entry.index == index)
866    {
867        Some(entry) => entry.oid.to_string() == sha,
868        None => false,
869    }
870}