1use anyhow::{Context as _, Result};
2use buffer_diff::BufferDiff;
3use collections::HashMap;
4use editor::display_map::{BlockPlacement, BlockProperties, BlockStyle};
5use editor::{Addon, Editor, EditorEvent, ExcerptRange, MultiBuffer, multibuffer_context_lines};
6use git::repository::{CommitDetails, CommitDiff, RepoPath, is_binary_content};
7use git::status::{FileStatus, StatusCode, TrackedStatus};
8use git::{
9 BuildCommitPermalinkParams, GitHostingProviderRegistry, GitRemote, ParsedGitRemote,
10 parse_git_remote_url,
11};
12use gpui::{
13 AnyElement, App, AppContext as _, AsyncApp, AsyncWindowContext, ClipboardItem, Context,
14 Element, Entity, EventEmitter, FocusHandle, Focusable, InteractiveElement, IntoElement,
15 ParentElement, PromptLevel, Render, Styled, Task, WeakEntity, Window, actions,
16};
17use language::{
18 Anchor, Buffer, Capability, DiskState, File, LanguageRegistry, LineEnding, OffsetRangeExt as _,
19 Point, ReplicaId, Rope, TextBuffer,
20};
21use multi_buffer::PathKey;
22use project::{Project, WorktreeId, git_store::Repository};
23use std::{
24 any::{Any, TypeId},
25 collections::HashSet,
26 path::PathBuf,
27 sync::Arc,
28};
29use theme::ActiveTheme;
30use ui::{ButtonLike, DiffStat, Tooltip, prelude::*};
31use util::{ResultExt, paths::PathStyle, rel_path::RelPath, truncate_and_trailoff};
32use workspace::item::TabTooltipContent;
33use workspace::{
34 Item, ItemHandle, ItemNavHistory, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
35 Workspace,
36 item::{ItemEvent, TabContentParams},
37 notifications::NotifyTaskExt,
38 pane::SaveIntent,
39 searchable::SearchableItemHandle,
40};
41
42use crate::commit_tooltip::CommitAvatar;
43use crate::git_panel::GitPanel;
44
45actions!(git, [ApplyCurrentStash, PopCurrentStash, DropCurrentStash,]);
46
47pub fn init(cx: &mut App) {
48 cx.observe_new(|workspace: &mut Workspace, _window, _cx| {
49 workspace.register_action(|workspace, _: &ApplyCurrentStash, window, cx| {
50 CommitView::apply_stash(workspace, window, cx);
51 });
52 workspace.register_action(|workspace, _: &DropCurrentStash, window, cx| {
53 CommitView::remove_stash(workspace, window, cx);
54 });
55 workspace.register_action(|workspace, _: &PopCurrentStash, window, cx| {
56 CommitView::pop_stash(workspace, window, cx);
57 });
58 })
59 .detach();
60}
61
62pub struct CommitView {
63 commit: CommitDetails,
64 editor: Entity<Editor>,
65 stash: Option<usize>,
66 multibuffer: Entity<MultiBuffer>,
67 repository: Entity<Repository>,
68 remote: Option<GitRemote>,
69}
70
71struct GitBlob {
72 path: RepoPath,
73 worktree_id: WorktreeId,
74 is_deleted: bool,
75 is_binary: bool,
76 display_name: String,
77}
78
79struct CommitDiffAddon {
80 file_statuses: HashMap<language::BufferId, FileStatus>,
81}
82
83impl Addon for CommitDiffAddon {
84 fn to_any(&self) -> &dyn std::any::Any {
85 self
86 }
87
88 fn override_status_for_buffer_id(
89 &self,
90 buffer_id: language::BufferId,
91 _cx: &App,
92 ) -> Option<FileStatus> {
93 self.file_statuses.get(&buffer_id).copied()
94 }
95}
96
97const COMMIT_MESSAGE_SORT_PREFIX: u64 = 0;
98const FILE_NAMESPACE_SORT_PREFIX: u64 = 1;
99
100impl CommitView {
101 pub fn open(
102 commit_sha: String,
103 repo: WeakEntity<Repository>,
104 workspace: WeakEntity<Workspace>,
105 stash: Option<usize>,
106 file_filter: Option<RepoPath>,
107 window: &mut Window,
108 cx: &mut App,
109 ) {
110 let commit_diff = repo
111 .update(cx, |repo, _| repo.load_commit_diff(commit_sha.clone()))
112 .ok();
113 let commit_details = repo
114 .update(cx, |repo, _| repo.show(commit_sha.clone()))
115 .ok();
116
117 window
118 .spawn(cx, async move |cx| {
119 let (commit_diff, commit_details) = futures::join!(commit_diff?, commit_details?);
120 let mut commit_diff = commit_diff.log_err()?.log_err()?;
121 let commit_details = commit_details.log_err()?.log_err()?;
122
123 // Filter to specific file if requested
124 if let Some(ref filter_path) = file_filter {
125 commit_diff.files.retain(|f| &f.path == filter_path);
126 }
127
128 let repo = repo.upgrade()?;
129
130 workspace
131 .update_in(cx, |workspace, window, cx| {
132 let project = workspace.project();
133 let commit_view = cx.new(|cx| {
134 CommitView::new(
135 commit_details,
136 commit_diff,
137 repo,
138 project.clone(),
139 stash,
140 window,
141 cx,
142 )
143 });
144
145 let pane = workspace.active_pane();
146 pane.update(cx, |pane, cx| {
147 let ix = pane.items().position(|item| {
148 let commit_view = item.downcast::<CommitView>();
149 commit_view
150 .is_some_and(|view| view.read(cx).commit.sha == commit_sha)
151 });
152 if let Some(ix) = ix {
153 pane.activate_item(ix, true, true, window, cx);
154 } else {
155 pane.add_item(Box::new(commit_view), true, true, None, window, cx);
156 }
157 })
158 })
159 .log_err()
160 })
161 .detach();
162 }
163
164 fn new(
165 commit: CommitDetails,
166 commit_diff: CommitDiff,
167 repository: Entity<Repository>,
168 project: Entity<Project>,
169 stash: Option<usize>,
170 window: &mut Window,
171 cx: &mut Context<Self>,
172 ) -> Self {
173 let language_registry = project.read(cx).languages().clone();
174 let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadOnly));
175
176 let message_buffer = cx.new(|cx| {
177 let mut buffer = Buffer::local(commit.message.clone(), cx);
178 buffer.set_capability(Capability::ReadOnly, cx);
179 buffer
180 });
181
182 multibuffer.update(cx, |multibuffer, cx| {
183 let snapshot = message_buffer.read(cx).snapshot();
184 let full_range = Point::zero()..snapshot.max_point();
185 let range = ExcerptRange {
186 context: full_range.clone(),
187 primary: full_range,
188 };
189 multibuffer.set_excerpt_ranges_for_path(
190 PathKey::with_sort_prefix(
191 COMMIT_MESSAGE_SORT_PREFIX,
192 RelPath::unix("commit message").unwrap().into(),
193 ),
194 message_buffer.clone(),
195 &snapshot,
196 vec![range],
197 cx,
198 )
199 });
200
201 let editor = cx.new(|cx| {
202 let mut editor =
203 Editor::for_multibuffer(multibuffer.clone(), Some(project.clone()), window, cx);
204
205 editor.disable_inline_diagnostics();
206 editor.set_show_breakpoints(false, cx);
207 editor.set_show_diff_review_button(true, cx);
208 editor.set_expand_all_diff_hunks(cx);
209 editor.disable_header_for_buffer(message_buffer.read(cx).remote_id(), cx);
210 editor.disable_indent_guides_for_buffer(message_buffer.read(cx).remote_id(), cx);
211
212 editor.insert_blocks(
213 [BlockProperties {
214 placement: BlockPlacement::Above(editor::Anchor::min()),
215 height: Some(1),
216 style: BlockStyle::Sticky,
217 render: Arc::new(|_| gpui::Empty.into_any_element()),
218 priority: 0,
219 }]
220 .into_iter()
221 .chain(
222 editor
223 .buffer()
224 .read(cx)
225 .buffer_anchor_to_anchor(&message_buffer, Anchor::MAX, cx)
226 .map(|anchor| BlockProperties {
227 placement: BlockPlacement::Below(anchor),
228 height: Some(1),
229 style: BlockStyle::Sticky,
230 render: Arc::new(|_| gpui::Empty.into_any_element()),
231 priority: 0,
232 }),
233 ),
234 None,
235 cx,
236 );
237
238 editor
239 });
240
241 let commit_sha = Arc::<str>::from(commit.sha.as_ref());
242
243 let first_worktree_id = project
244 .read(cx)
245 .worktrees(cx)
246 .next()
247 .map(|worktree| worktree.read(cx).id());
248
249 let repository_clone = repository.clone();
250
251 cx.spawn(async move |this, cx| {
252 let mut binary_buffer_ids: HashSet<language::BufferId> = HashSet::default();
253 let mut file_statuses: HashMap<language::BufferId, FileStatus> = HashMap::default();
254
255 for file in commit_diff.files {
256 let is_created = file.old_text.is_none();
257 let is_deleted = file.new_text.is_none();
258 let raw_new_text = file.new_text.unwrap_or_default();
259 let raw_old_text = file.old_text;
260
261 let is_binary = file.is_binary
262 || is_binary_content(raw_new_text.as_bytes())
263 || raw_old_text
264 .as_ref()
265 .is_some_and(|text| is_binary_content(text.as_bytes()));
266
267 let new_text = if is_binary {
268 "(binary file not shown)".to_string()
269 } else {
270 raw_new_text
271 };
272 let old_text = if is_binary { None } else { raw_old_text };
273 let worktree_id = repository_clone
274 .update(cx, |repository, cx| {
275 repository
276 .repo_path_to_project_path(&file.path, cx)
277 .map(|path| path.worktree_id)
278 .or(first_worktree_id)
279 })
280 .context("project has no worktrees")?;
281 let short_sha = commit_sha.get(0..7).unwrap_or(&commit_sha);
282 let file_name = file
283 .path
284 .file_name()
285 .map(|name| name.to_string())
286 .unwrap_or_else(|| file.path.display(PathStyle::local()).to_string());
287 let display_name = format!("{short_sha} - {file_name}");
288
289 let file = Arc::new(GitBlob {
290 path: file.path.clone(),
291 is_deleted,
292 is_binary,
293 worktree_id,
294 display_name,
295 }) as Arc<dyn language::File>;
296
297 let buffer = build_buffer(new_text, file, &language_registry, cx).await?;
298 let buffer_id = cx.update(|cx| buffer.read(cx).remote_id());
299
300 let status_code = if is_created {
301 StatusCode::Added
302 } else if is_deleted {
303 StatusCode::Deleted
304 } else {
305 StatusCode::Modified
306 };
307 file_statuses.insert(
308 buffer_id,
309 FileStatus::Tracked(TrackedStatus {
310 index_status: status_code,
311 worktree_status: StatusCode::Unmodified,
312 }),
313 );
314
315 if is_binary {
316 binary_buffer_ids.insert(buffer_id);
317 }
318
319 let buffer_diff = if is_binary {
320 None
321 } else {
322 Some(build_buffer_diff(old_text, &buffer, &language_registry, cx).await?)
323 };
324
325 this.update(cx, |this, cx| {
326 this.multibuffer.update(cx, |multibuffer, cx| {
327 let snapshot = buffer.read(cx).snapshot();
328 let path = snapshot.file().unwrap().path().clone();
329 let excerpt_ranges = if is_binary {
330 vec![language::Point::zero()..snapshot.max_point()]
331 } else if let Some(buffer_diff) = &buffer_diff {
332 let diff_snapshot = buffer_diff.read(cx).snapshot(cx);
333 let mut hunks = diff_snapshot.hunks(&snapshot).peekable();
334 if hunks.peek().is_none() {
335 vec![language::Point::zero()..snapshot.max_point()]
336 } else {
337 hunks
338 .map(|hunk| hunk.buffer_range.to_point(&snapshot))
339 .collect::<Vec<_>>()
340 }
341 } else {
342 vec![language::Point::zero()..snapshot.max_point()]
343 };
344
345 let _is_newly_added = multibuffer.set_excerpts_for_path(
346 PathKey::with_sort_prefix(FILE_NAMESPACE_SORT_PREFIX, path),
347 buffer,
348 excerpt_ranges,
349 multibuffer_context_lines(cx),
350 cx,
351 );
352 if let Some(buffer_diff) = buffer_diff {
353 multibuffer.add_diff(buffer_diff, cx);
354 }
355 });
356 })?;
357 }
358
359 this.update(cx, |this, cx| {
360 this.editor.update(cx, |editor, _cx| {
361 editor.register_addon(CommitDiffAddon { file_statuses });
362 });
363 if !binary_buffer_ids.is_empty() {
364 this.editor.update(cx, |editor, cx| {
365 for buffer_id in binary_buffer_ids {
366 editor.fold_buffer(buffer_id, cx);
367 }
368 });
369 }
370 })?;
371
372 anyhow::Ok(())
373 })
374 .detach();
375
376 let snapshot = repository.read(cx).snapshot();
377 let remote_url = snapshot
378 .remote_upstream_url
379 .as_ref()
380 .or(snapshot.remote_origin_url.as_ref());
381
382 let remote = remote_url.and_then(|url| {
383 let provider_registry = GitHostingProviderRegistry::default_global(cx);
384 parse_git_remote_url(provider_registry, url).map(|(host, parsed)| GitRemote {
385 host,
386 owner: parsed.owner.into(),
387 repo: parsed.repo.into(),
388 })
389 });
390
391 Self {
392 commit,
393 editor,
394 multibuffer,
395 stash,
396 repository,
397 remote,
398 }
399 }
400
401 fn render_commit_avatar(
402 &self,
403 sha: &SharedString,
404 size: impl Into<gpui::AbsoluteLength>,
405 window: &mut Window,
406 cx: &mut App,
407 ) -> AnyElement {
408 let size = size.into();
409 let avatar = CommitAvatar::new(
410 sha,
411 Some(self.commit.author_email.clone()),
412 self.remote.as_ref(),
413 );
414
415 v_flex()
416 .w(size)
417 .h(size)
418 .border_1()
419 .border_color(cx.theme().colors().border)
420 .rounded_full()
421 .justify_center()
422 .items_center()
423 .child(
424 avatar
425 .avatar(window, cx)
426 .map(|a| a.size(size).into_any_element())
427 .unwrap_or_else(|| {
428 Icon::new(IconName::Person)
429 .color(Color::Muted)
430 .size(IconSize::Medium)
431 .into_any_element()
432 }),
433 )
434 .into_any()
435 }
436
437 fn calculate_changed_lines(&self, cx: &App) -> (u32, u32) {
438 let snapshot = self.multibuffer.read(cx).snapshot(cx);
439 let mut total_additions = 0u32;
440 let mut total_deletions = 0u32;
441
442 let mut seen_buffers = std::collections::HashSet::new();
443 for (_, buffer, _) in snapshot.excerpts() {
444 let buffer_id = buffer.remote_id();
445 if !seen_buffers.insert(buffer_id) {
446 continue;
447 }
448
449 let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
450 continue;
451 };
452
453 let base_text = diff.base_text();
454
455 for hunk in diff.hunks_intersecting_range(Anchor::MIN..Anchor::MAX, buffer) {
456 let added_rows = hunk.range.end.row.saturating_sub(hunk.range.start.row);
457 total_additions += added_rows;
458
459 let base_start = base_text
460 .offset_to_point(hunk.diff_base_byte_range.start)
461 .row;
462 let base_end = base_text.offset_to_point(hunk.diff_base_byte_range.end).row;
463 let deleted_rows = base_end.saturating_sub(base_start);
464
465 total_deletions += deleted_rows;
466 }
467 }
468
469 (total_additions, total_deletions)
470 }
471
472 fn render_header(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
473 let commit = &self.commit;
474 let author_name = commit.author_name.clone();
475 let commit_sha = commit.sha.clone();
476 let commit_date = time::OffsetDateTime::from_unix_timestamp(commit.commit_timestamp)
477 .unwrap_or_else(|_| time::OffsetDateTime::now_utc());
478 let local_offset = time::UtcOffset::current_local_offset().unwrap_or(time::UtcOffset::UTC);
479 let date_string = time_format::format_localized_timestamp(
480 commit_date,
481 time::OffsetDateTime::now_utc(),
482 local_offset,
483 time_format::TimestampFormat::MediumAbsolute,
484 );
485
486 let remote_info = self.remote.as_ref().map(|remote| {
487 let provider = remote.host.name();
488 let parsed_remote = ParsedGitRemote {
489 owner: remote.owner.as_ref().into(),
490 repo: remote.repo.as_ref().into(),
491 };
492 let params = BuildCommitPermalinkParams { sha: &commit.sha };
493 let url = remote
494 .host
495 .build_commit_permalink(&parsed_remote, params)
496 .to_string();
497 (provider, url)
498 });
499
500 let (additions, deletions) = self.calculate_changed_lines(cx);
501
502 let commit_diff_stat = if additions > 0 || deletions > 0 {
503 Some(DiffStat::new(
504 "commit-diff-stat",
505 additions as usize,
506 deletions as usize,
507 ))
508 } else {
509 None
510 };
511
512 let gutter_width = self.editor.update(cx, |editor, cx| {
513 let snapshot = editor.snapshot(window, cx);
514 let style = editor.style(cx);
515 let font_id = window.text_system().resolve_font(&style.text.font());
516 let font_size = style.text.font_size.to_pixels(window.rem_size());
517 snapshot
518 .gutter_dimensions(font_id, font_size, style, window, cx)
519 .full_width()
520 });
521
522 let clipboard_has_link = cx
523 .read_from_clipboard()
524 .and_then(|entry| entry.text())
525 .map_or(false, |clipboard_text| {
526 clipboard_text.trim() == commit_sha.as_ref()
527 });
528
529 let (copy_icon, copy_icon_color) = if clipboard_has_link {
530 (IconName::Check, Color::Success)
531 } else {
532 (IconName::Copy, Color::Muted)
533 };
534
535 h_flex()
536 .border_b_1()
537 .border_color(cx.theme().colors().border_variant)
538 .w_full()
539 .child(
540 h_flex()
541 .w(gutter_width)
542 .justify_center()
543 .child(self.render_commit_avatar(&commit.sha, rems_from_px(48.), window, cx)),
544 )
545 .child(
546 h_flex()
547 .py_4()
548 .pl_1()
549 .pr_4()
550 .w_full()
551 .items_start()
552 .justify_between()
553 .flex_wrap()
554 .child(
555 v_flex()
556 .child(
557 h_flex()
558 .gap_1()
559 .child(Label::new(author_name).color(Color::Default))
560 .child({
561 ButtonLike::new("sha")
562 .child(
563 h_flex()
564 .group("sha_btn")
565 .size_full()
566 .max_w_32()
567 .gap_0p5()
568 .child(
569 Label::new(commit_sha.clone())
570 .color(Color::Muted)
571 .size(LabelSize::Small)
572 .truncate()
573 .buffer_font(cx),
574 )
575 .child(
576 div().visible_on_hover("sha_btn").child(
577 Icon::new(copy_icon)
578 .color(copy_icon_color)
579 .size(IconSize::Small),
580 ),
581 ),
582 )
583 .tooltip({
584 let commit_sha = commit_sha.clone();
585 move |_, cx| {
586 Tooltip::with_meta(
587 "Copy Commit SHA",
588 None,
589 commit_sha.clone(),
590 cx,
591 )
592 }
593 })
594 .on_click(move |_, _, cx| {
595 cx.stop_propagation();
596 cx.write_to_clipboard(ClipboardItem::new_string(
597 commit_sha.to_string(),
598 ));
599 })
600 }),
601 )
602 .child(
603 h_flex()
604 .gap_1p5()
605 .child(
606 Label::new(date_string)
607 .color(Color::Muted)
608 .size(LabelSize::Small),
609 )
610 .child(
611 Label::new("•")
612 .color(Color::Ignored)
613 .size(LabelSize::Small),
614 )
615 .children(commit_diff_stat),
616 ),
617 )
618 .children(remote_info.map(|(provider_name, url)| {
619 let icon = match provider_name.as_str() {
620 "GitHub" => IconName::Github,
621 _ => IconName::Link,
622 };
623
624 Button::new("view_on_provider", format!("View on {}", provider_name))
625 .icon(icon)
626 .icon_color(Color::Muted)
627 .icon_size(IconSize::Small)
628 .icon_position(IconPosition::Start)
629 .on_click(move |_, _, cx| cx.open_url(&url))
630 })),
631 )
632 }
633
634 fn apply_stash(workspace: &mut Workspace, window: &mut Window, cx: &mut App) {
635 Self::stash_action(
636 workspace,
637 "Apply",
638 window,
639 cx,
640 async move |repository, sha, stash, commit_view, workspace, cx| {
641 let result = repository.update(cx, |repo, cx| {
642 if !stash_matches_index(&sha, stash, repo) {
643 return Err(anyhow::anyhow!("Stash has changed, not applying"));
644 }
645 Ok(repo.stash_apply(Some(stash), cx))
646 });
647
648 match result {
649 Ok(task) => task.await?,
650 Err(err) => {
651 Self::close_commit_view(commit_view, workspace, cx).await?;
652 return Err(err);
653 }
654 };
655 Self::close_commit_view(commit_view, workspace, cx).await?;
656 anyhow::Ok(())
657 },
658 );
659 }
660
661 fn pop_stash(workspace: &mut Workspace, window: &mut Window, cx: &mut App) {
662 Self::stash_action(
663 workspace,
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(workspace: &mut Workspace, window: &mut Window, cx: &mut App) {
689 Self::stash_action(
690 workspace,
691 "Drop",
692 window,
693 cx,
694 async move |repository, sha, stash, commit_view, workspace, cx| {
695 let result = repository.update(cx, |repo, cx| {
696 if !stash_matches_index(&sha, stash, repo) {
697 return Err(anyhow::anyhow!("Stash has changed, drop aborted"));
698 }
699 Ok(repo.stash_drop(Some(stash), cx))
700 });
701
702 match result {
703 Ok(task) => task.await??,
704 Err(err) => {
705 Self::close_commit_view(commit_view, workspace, cx).await?;
706 return Err(err);
707 }
708 };
709 Self::close_commit_view(commit_view, workspace, cx).await?;
710 anyhow::Ok(())
711 },
712 );
713 }
714
715 fn stash_action<AsyncFn>(
716 workspace: &mut Workspace,
717 str_action: &str,
718 window: &mut Window,
719 cx: &mut App,
720 callback: AsyncFn,
721 ) where
722 AsyncFn: AsyncFnOnce(
723 Entity<Repository>,
724 &SharedString,
725 usize,
726 Entity<CommitView>,
727 WeakEntity<Workspace>,
728 &mut AsyncWindowContext,
729 ) -> anyhow::Result<()>
730 + 'static,
731 {
732 let Some(commit_view) = workspace.active_item_as::<CommitView>(cx) else {
733 return;
734 };
735 let Some(stash) = commit_view.read(cx).stash else {
736 return;
737 };
738 let sha = commit_view.read(cx).commit.sha.clone();
739 let answer = window.prompt(
740 PromptLevel::Info,
741 &format!("{} stash@{{{}}}?", str_action, stash),
742 None,
743 &[str_action, "Cancel"],
744 cx,
745 );
746
747 let workspace_weak = workspace.weak_handle();
748 let commit_view_entity = commit_view;
749
750 window
751 .spawn(cx, async move |cx| {
752 if answer.await != Ok(0) {
753 return anyhow::Ok(());
754 }
755
756 let Some(workspace) = workspace_weak.upgrade() else {
757 return Ok(());
758 };
759
760 let repo = workspace.update(cx, |workspace, cx| {
761 workspace
762 .panel::<GitPanel>(cx)
763 .and_then(|p| p.read(cx).active_repository.clone())
764 });
765
766 let Some(repo) = repo else {
767 return Ok(());
768 };
769
770 callback(repo, &sha, stash, commit_view_entity, workspace_weak, cx).await?;
771 anyhow::Ok(())
772 })
773 .detach_and_notify_err(window, cx);
774 }
775
776 async fn close_commit_view(
777 commit_view: Entity<CommitView>,
778 workspace: WeakEntity<Workspace>,
779 cx: &mut AsyncWindowContext,
780 ) -> anyhow::Result<()> {
781 workspace
782 .update_in(cx, |workspace, window, cx| {
783 let active_pane = workspace.active_pane();
784 let commit_view_id = commit_view.entity_id();
785 active_pane.update(cx, |pane, cx| {
786 pane.close_item_by_id(commit_view_id, SaveIntent::Skip, window, cx)
787 })
788 })?
789 .await?;
790 anyhow::Ok(())
791 }
792}
793
794impl language::File for GitBlob {
795 fn as_local(&self) -> Option<&dyn language::LocalFile> {
796 None
797 }
798
799 fn disk_state(&self) -> DiskState {
800 DiskState::Historic {
801 was_deleted: self.is_deleted,
802 }
803 }
804
805 fn path_style(&self, _: &App) -> PathStyle {
806 PathStyle::local()
807 }
808
809 fn path(&self) -> &Arc<RelPath> {
810 self.path.as_ref()
811 }
812
813 fn full_path(&self, _: &App) -> PathBuf {
814 self.path.as_std_path().to_path_buf()
815 }
816
817 fn file_name<'a>(&'a self, _: &'a App) -> &'a str {
818 self.display_name.as_ref()
819 }
820
821 fn worktree_id(&self, _: &App) -> WorktreeId {
822 self.worktree_id
823 }
824
825 fn to_proto(&self, _cx: &App) -> language::proto::File {
826 unimplemented!()
827 }
828
829 fn is_private(&self) -> bool {
830 false
831 }
832
833 fn can_open(&self) -> bool {
834 !self.is_binary
835 }
836}
837
838async fn build_buffer(
839 mut text: String,
840 blob: Arc<dyn File>,
841 language_registry: &Arc<language::LanguageRegistry>,
842 cx: &mut AsyncApp,
843) -> Result<Entity<Buffer>> {
844 let line_ending = LineEnding::detect(&text);
845 LineEnding::normalize(&mut text);
846 let text = Rope::from(text);
847 let language = cx.update(|cx| language_registry.language_for_file(&blob, Some(&text), cx));
848 let language = if let Some(language) = language {
849 language_registry
850 .load_language(&language)
851 .await
852 .ok()
853 .and_then(|e| e.log_err())
854 } else {
855 None
856 };
857 let buffer = cx.new(|cx| {
858 let buffer = TextBuffer::new_normalized(
859 ReplicaId::LOCAL,
860 cx.entity_id().as_non_zero_u64().into(),
861 line_ending,
862 text,
863 );
864 let mut buffer = Buffer::build(buffer, Some(blob), Capability::ReadWrite);
865 buffer.set_language_async(language, cx);
866 buffer
867 });
868 Ok(buffer)
869}
870
871async fn build_buffer_diff(
872 mut old_text: Option<String>,
873 buffer: &Entity<Buffer>,
874 language_registry: &Arc<LanguageRegistry>,
875 cx: &mut AsyncApp,
876) -> Result<Entity<BufferDiff>> {
877 if let Some(old_text) = &mut old_text {
878 LineEnding::normalize(old_text);
879 }
880
881 let language = cx.update(|cx| buffer.read(cx).language().cloned());
882 let buffer = cx.update(|cx| buffer.read(cx).snapshot());
883
884 let diff = cx.new(|cx| BufferDiff::new(&buffer.text, cx));
885
886 let update = diff
887 .update(cx, |diff, cx| {
888 diff.update_diff(
889 buffer.text.clone(),
890 old_text.map(|old_text| Arc::from(old_text.as_str())),
891 Some(true),
892 language.clone(),
893 cx,
894 )
895 })
896 .await;
897
898 diff.update(cx, |diff, cx| {
899 diff.language_changed(language, Some(language_registry.clone()), cx);
900 diff.set_snapshot(update, &buffer.text, cx)
901 })
902 .await;
903
904 Ok(diff)
905}
906
907impl EventEmitter<EditorEvent> for CommitView {}
908
909impl Focusable for CommitView {
910 fn focus_handle(&self, cx: &App) -> FocusHandle {
911 self.editor.focus_handle(cx)
912 }
913}
914
915impl Item for CommitView {
916 type Event = EditorEvent;
917
918 fn tab_icon(&self, _window: &Window, _cx: &App) -> Option<Icon> {
919 Some(Icon::new(IconName::GitBranch).color(Color::Muted))
920 }
921
922 fn tab_content(&self, params: TabContentParams, _window: &Window, cx: &App) -> AnyElement {
923 Label::new(self.tab_content_text(params.detail.unwrap_or_default(), cx))
924 .color(if params.selected {
925 Color::Default
926 } else {
927 Color::Muted
928 })
929 .into_any_element()
930 }
931
932 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
933 let short_sha = self.commit.sha.get(0..7).unwrap_or(&*self.commit.sha);
934 let subject = truncate_and_trailoff(self.commit.message.split('\n').next().unwrap(), 20);
935 format!("{short_sha} — {subject}").into()
936 }
937
938 fn tab_tooltip_content(&self, _: &App) -> Option<TabTooltipContent> {
939 let short_sha = self.commit.sha.get(0..16).unwrap_or(&*self.commit.sha);
940 let subject = self.commit.message.split('\n').next().unwrap();
941
942 Some(TabTooltipContent::Custom(Box::new(Tooltip::element({
943 let subject = subject.to_string();
944 let short_sha = short_sha.to_string();
945
946 move |_, _| {
947 v_flex()
948 .child(Label::new(subject.clone()))
949 .child(
950 Label::new(short_sha.clone())
951 .color(Color::Muted)
952 .size(LabelSize::Small),
953 )
954 .into_any_element()
955 }
956 }))))
957 }
958
959 fn to_item_events(event: &EditorEvent, f: impl FnMut(ItemEvent)) {
960 Editor::to_item_events(event, f)
961 }
962
963 fn telemetry_event_text(&self) -> Option<&'static str> {
964 Some("Commit View Opened")
965 }
966
967 fn deactivated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
968 self.editor
969 .update(cx, |editor, cx| editor.deactivated(window, cx));
970 }
971
972 fn act_as_type<'a>(
973 &'a self,
974 type_id: TypeId,
975 self_handle: &'a Entity<Self>,
976 _: &'a App,
977 ) -> Option<gpui::AnyEntity> {
978 if type_id == TypeId::of::<Self>() {
979 Some(self_handle.clone().into())
980 } else if type_id == TypeId::of::<Editor>() {
981 Some(self.editor.clone().into())
982 } else {
983 None
984 }
985 }
986
987 fn as_searchable(&self, _: &Entity<Self>, _: &App) -> Option<Box<dyn SearchableItemHandle>> {
988 Some(Box::new(self.editor.clone()))
989 }
990
991 fn for_each_project_item(
992 &self,
993 cx: &App,
994 f: &mut dyn FnMut(gpui::EntityId, &dyn project::ProjectItem),
995 ) {
996 self.editor.for_each_project_item(cx, f)
997 }
998
999 fn set_nav_history(
1000 &mut self,
1001 nav_history: ItemNavHistory,
1002 _: &mut Window,
1003 cx: &mut Context<Self>,
1004 ) {
1005 self.editor.update(cx, |editor, _| {
1006 editor.set_nav_history(Some(nav_history));
1007 });
1008 }
1009
1010 fn navigate(
1011 &mut self,
1012 data: Arc<dyn Any + Send>,
1013 window: &mut Window,
1014 cx: &mut Context<Self>,
1015 ) -> bool {
1016 self.editor
1017 .update(cx, |editor, cx| editor.navigate(data, window, cx))
1018 }
1019
1020 fn added_to_workspace(
1021 &mut self,
1022 workspace: &mut Workspace,
1023 window: &mut Window,
1024 cx: &mut Context<Self>,
1025 ) {
1026 self.editor.update(cx, |editor, cx| {
1027 editor.added_to_workspace(workspace, window, cx)
1028 });
1029 }
1030
1031 fn can_split(&self) -> bool {
1032 true
1033 }
1034
1035 fn clone_on_split(
1036 &self,
1037 _workspace_id: Option<workspace::WorkspaceId>,
1038 window: &mut Window,
1039 cx: &mut Context<Self>,
1040 ) -> Task<Option<Entity<Self>>>
1041 where
1042 Self: Sized,
1043 {
1044 let file_statuses = self
1045 .editor
1046 .read(cx)
1047 .addon::<CommitDiffAddon>()
1048 .map(|addon| addon.file_statuses.clone())
1049 .unwrap_or_default();
1050 Task::ready(Some(cx.new(|cx| {
1051 let editor = cx.new({
1052 let file_statuses = file_statuses.clone();
1053 |cx| {
1054 let mut editor = self
1055 .editor
1056 .update(cx, |editor, cx| editor.clone(window, cx));
1057 editor.register_addon(CommitDiffAddon { file_statuses });
1058 editor
1059 }
1060 });
1061 let multibuffer = editor.read(cx).buffer().clone();
1062 Self {
1063 editor,
1064 multibuffer,
1065 commit: self.commit.clone(),
1066 stash: self.stash,
1067 repository: self.repository.clone(),
1068 remote: self.remote.clone(),
1069 }
1070 })))
1071 }
1072}
1073
1074impl Render for CommitView {
1075 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1076 let is_stash = self.stash.is_some();
1077
1078 v_flex()
1079 .key_context(if is_stash { "StashDiff" } else { "CommitDiff" })
1080 .size_full()
1081 .bg(cx.theme().colors().editor_background)
1082 .child(self.render_header(window, cx))
1083 .when(!self.editor.read(cx).is_empty(cx), |this| {
1084 this.child(div().flex_grow().child(self.editor.clone()))
1085 })
1086 }
1087}
1088
1089pub struct CommitViewToolbar {
1090 commit_view: Option<WeakEntity<CommitView>>,
1091}
1092
1093impl CommitViewToolbar {
1094 pub fn new() -> Self {
1095 Self { commit_view: None }
1096 }
1097}
1098
1099impl EventEmitter<ToolbarItemEvent> for CommitViewToolbar {}
1100
1101impl Render for CommitViewToolbar {
1102 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
1103 div().hidden()
1104 }
1105}
1106
1107impl ToolbarItemView for CommitViewToolbar {
1108 fn set_active_pane_item(
1109 &mut self,
1110 active_pane_item: Option<&dyn ItemHandle>,
1111 _: &mut Window,
1112 cx: &mut Context<Self>,
1113 ) -> ToolbarItemLocation {
1114 if let Some(entity) = active_pane_item.and_then(|i| i.act_as::<CommitView>(cx))
1115 && entity.read(cx).stash.is_some()
1116 {
1117 self.commit_view = Some(entity.downgrade());
1118 return ToolbarItemLocation::PrimaryRight;
1119 }
1120 ToolbarItemLocation::Hidden
1121 }
1122
1123 fn pane_focus_update(
1124 &mut self,
1125 _pane_focused: bool,
1126 _window: &mut Window,
1127 _cx: &mut Context<Self>,
1128 ) {
1129 }
1130}
1131
1132fn stash_matches_index(sha: &str, stash_index: usize, repo: &Repository) -> bool {
1133 repo.stash_entries
1134 .entries
1135 .get(stash_index)
1136 .map(|entry| entry.oid.to_string() == sha)
1137 .unwrap_or(false)
1138}