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