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