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 can_split(&self) -> bool {
560        true
561    }
562
563    fn clone_on_split(
564        &self,
565        _workspace_id: Option<workspace::WorkspaceId>,
566        window: &mut Window,
567        cx: &mut Context<Self>,
568    ) -> Task<Option<Entity<Self>>>
569    where
570        Self: Sized,
571    {
572        Task::ready(Some(cx.new(|cx| {
573            let editor = cx.new(|cx| {
574                self.editor
575                    .update(cx, |editor, cx| editor.clone(window, cx))
576            });
577            let multibuffer = editor.read(cx).buffer().clone();
578            Self {
579                editor,
580                multibuffer,
581                commit: self.commit.clone(),
582                stash: self.stash,
583            }
584        })))
585    }
586}
587
588impl Render for CommitView {
589    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
590        let is_stash = self.stash.is_some();
591        div()
592            .key_context(if is_stash { "StashDiff" } else { "CommitDiff" })
593            .bg(cx.theme().colors().editor_background)
594            .flex()
595            .items_center()
596            .justify_center()
597            .size_full()
598            .child(self.editor.clone())
599    }
600}
601
602pub struct CommitViewToolbar {
603    commit_view: Option<WeakEntity<CommitView>>,
604    workspace: WeakEntity<Workspace>,
605}
606
607impl CommitViewToolbar {
608    pub fn new(workspace: &Workspace, _: &mut Context<Self>) -> Self {
609        Self {
610            commit_view: None,
611            workspace: workspace.weak_handle(),
612        }
613    }
614
615    fn commit_view(&self, _: &App) -> Option<Entity<CommitView>> {
616        self.commit_view.as_ref()?.upgrade()
617    }
618
619    async fn close_commit_view(
620        commit_view: Entity<CommitView>,
621        workspace: WeakEntity<Workspace>,
622        cx: &mut AsyncWindowContext,
623    ) -> anyhow::Result<()> {
624        workspace
625            .update_in(cx, |workspace, window, cx| {
626                let active_pane = workspace.active_pane();
627                let commit_view_id = commit_view.entity_id();
628                active_pane.update(cx, |pane, cx| {
629                    pane.close_item_by_id(commit_view_id, SaveIntent::Skip, window, cx)
630                })
631            })?
632            .await?;
633        anyhow::Ok(())
634    }
635
636    fn apply_stash(&mut self, window: &mut Window, cx: &mut Context<Self>) {
637        self.stash_action(
638            "Apply",
639            window,
640            cx,
641            async move |repository, sha, stash, commit_view, workspace, cx| {
642                let result = repository.update(cx, |repo, cx| {
643                    if !stash_matches_index(&sha, stash, repo) {
644                        return Err(anyhow::anyhow!("Stash has changed, not applying"));
645                    }
646                    Ok(repo.stash_apply(Some(stash), cx))
647                })?;
648
649                match result {
650                    Ok(task) => task.await?,
651                    Err(err) => {
652                        Self::close_commit_view(commit_view, workspace, cx).await?;
653                        return Err(err);
654                    }
655                };
656                Self::close_commit_view(commit_view, workspace, cx).await?;
657                anyhow::Ok(())
658            },
659        );
660    }
661
662    fn pop_stash(&mut self, window: &mut Window, cx: &mut Context<Self>) {
663        self.stash_action(
664            "Pop",
665            window,
666            cx,
667            async move |repository, sha, stash, commit_view, workspace, cx| {
668                let result = repository.update(cx, |repo, cx| {
669                    if !stash_matches_index(&sha, stash, repo) {
670                        return Err(anyhow::anyhow!("Stash has changed, pop aborted"));
671                    }
672                    Ok(repo.stash_pop(Some(stash), cx))
673                })?;
674
675                match result {
676                    Ok(task) => task.await?,
677                    Err(err) => {
678                        Self::close_commit_view(commit_view, workspace, cx).await?;
679                        return Err(err);
680                    }
681                };
682                Self::close_commit_view(commit_view, workspace, cx).await?;
683                anyhow::Ok(())
684            },
685        );
686    }
687
688    fn remove_stash(&mut self, window: &mut Window, cx: &mut Context<Self>) {
689        self.stash_action(
690            "Drop",
691            window,
692            cx,
693            async move |repository, sha, stash, commit_view, workspace, cx| {
694                let result = repository.update(cx, |repo, cx| {
695                    if !stash_matches_index(&sha, stash, repo) {
696                        return Err(anyhow::anyhow!("Stash has changed, drop aborted"));
697                    }
698                    Ok(repo.stash_drop(Some(stash), cx))
699                })?;
700
701                match result {
702                    Ok(task) => task.await??,
703                    Err(err) => {
704                        Self::close_commit_view(commit_view, workspace, cx).await?;
705                        return Err(err);
706                    }
707                };
708                Self::close_commit_view(commit_view, workspace, cx).await?;
709                anyhow::Ok(())
710            },
711        );
712    }
713
714    fn stash_action<AsyncFn>(
715        &mut self,
716        str_action: &str,
717        window: &mut Window,
718        cx: &mut Context<Self>,
719        callback: AsyncFn,
720    ) where
721        AsyncFn: AsyncFnOnce(
722                Entity<Repository>,
723                &SharedString,
724                usize,
725                Entity<CommitView>,
726                WeakEntity<Workspace>,
727                &mut AsyncWindowContext,
728            ) -> anyhow::Result<()>
729            + 'static,
730    {
731        let Some(commit_view) = self.commit_view(cx) else {
732            return;
733        };
734        let Some(stash) = commit_view.read(cx).stash else {
735            return;
736        };
737        let sha = commit_view.read(cx).commit.sha.clone();
738        let answer = window.prompt(
739            PromptLevel::Info,
740            &format!("{} stash@{{{}}}?", str_action, stash),
741            None,
742            &[str_action, "Cancel"],
743            cx,
744        );
745
746        let workspace = self.workspace.clone();
747        cx.spawn_in(window, async move |_, cx| {
748            if answer.await != Ok(0) {
749                return anyhow::Ok(());
750            }
751            let repo = workspace.update(cx, |workspace, cx| {
752                workspace
753                    .panel::<GitPanel>(cx)
754                    .and_then(|p| p.read(cx).active_repository.clone())
755            })?;
756
757            let Some(repo) = repo else {
758                return Ok(());
759            };
760            callback(repo, &sha, stash, commit_view, workspace, cx).await?;
761            anyhow::Ok(())
762        })
763        .detach_and_notify_err(window, cx);
764    }
765}
766
767impl EventEmitter<ToolbarItemEvent> for CommitViewToolbar {}
768
769impl ToolbarItemView for CommitViewToolbar {
770    fn set_active_pane_item(
771        &mut self,
772        active_pane_item: Option<&dyn ItemHandle>,
773        _: &mut Window,
774        cx: &mut Context<Self>,
775    ) -> ToolbarItemLocation {
776        if let Some(entity) = active_pane_item.and_then(|i| i.act_as::<CommitView>(cx))
777            && entity.read(cx).stash.is_some()
778        {
779            self.commit_view = Some(entity.downgrade());
780            return ToolbarItemLocation::PrimaryRight;
781        }
782        ToolbarItemLocation::Hidden
783    }
784
785    fn pane_focus_update(
786        &mut self,
787        _pane_focused: bool,
788        _window: &mut Window,
789        _cx: &mut Context<Self>,
790    ) {
791    }
792}
793
794impl Render for CommitViewToolbar {
795    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
796        let Some(commit_view) = self.commit_view(cx) else {
797            return div();
798        };
799
800        let is_stash = commit_view.read(cx).stash.is_some();
801        if !is_stash {
802            return div();
803        }
804
805        let focus_handle = commit_view.focus_handle(cx);
806
807        h_group_xl().my_neg_1().py_1().items_center().child(
808            h_group_sm()
809                .child(
810                    Button::new("apply-stash", "Apply")
811                        .tooltip(Tooltip::for_action_title_in(
812                            "Apply current stash",
813                            &ApplyCurrentStash,
814                            &focus_handle,
815                        ))
816                        .on_click(cx.listener(|this, _, window, cx| this.apply_stash(window, cx))),
817                )
818                .child(
819                    Button::new("pop-stash", "Pop")
820                        .tooltip(Tooltip::for_action_title_in(
821                            "Pop current stash",
822                            &PopCurrentStash,
823                            &focus_handle,
824                        ))
825                        .on_click(cx.listener(|this, _, window, cx| this.pop_stash(window, cx))),
826                )
827                .child(
828                    Button::new("remove-stash", "Remove")
829                        .icon(IconName::Trash)
830                        .tooltip(Tooltip::for_action_title_in(
831                            "Remove current stash",
832                            &DropCurrentStash,
833                            &focus_handle,
834                        ))
835                        .on_click(cx.listener(|this, _, window, cx| this.remove_stash(window, cx))),
836                ),
837        )
838    }
839}
840
841fn register_workspace_action<A: Action>(
842    workspace: &mut Workspace,
843    callback: fn(&mut CommitViewToolbar, &A, &mut Window, &mut Context<CommitViewToolbar>),
844) {
845    workspace.register_action(move |workspace, action: &A, window, cx| {
846        if workspace.has_active_modal(window, cx) {
847            cx.propagate();
848            return;
849        }
850
851        workspace.active_pane().update(cx, |pane, cx| {
852            pane.toolbar().update(cx, move |workspace, cx| {
853                if let Some(toolbar) = workspace.item_of_type::<CommitViewToolbar>() {
854                    toolbar.update(cx, move |toolbar, cx| {
855                        callback(toolbar, action, window, cx);
856                        cx.notify();
857                    });
858                }
859            });
860        })
861    });
862}
863
864fn stash_matches_index(sha: &str, index: usize, repo: &mut Repository) -> bool {
865    match repo
866        .cached_stash()
867        .entries
868        .iter()
869        .find(|entry| entry.index == index)
870    {
871        Some(entry) => entry.oid.to_string() == sha,
872        None => false,
873    }
874}