commit_view.rs

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