commit_view.rs

   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        self.multibuffer.read(cx).snapshot(cx).total_changed_lines()
 418    }
 419
 420    fn render_header(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 421        let commit = &self.commit;
 422        let author_name = commit.author_name.clone();
 423        let author_email = commit.author_email.clone();
 424        let commit_sha = commit.sha.clone();
 425        let commit_date = time::OffsetDateTime::from_unix_timestamp(commit.commit_timestamp)
 426            .unwrap_or_else(|_| time::OffsetDateTime::now_utc());
 427        let local_offset = time::UtcOffset::current_local_offset().unwrap_or(time::UtcOffset::UTC);
 428        let date_string = time_format::format_localized_timestamp(
 429            commit_date,
 430            time::OffsetDateTime::now_utc(),
 431            local_offset,
 432            time_format::TimestampFormat::MediumAbsolute,
 433        );
 434
 435        let gutter_width = self.editor.update(cx, |editor, cx| {
 436            let snapshot = editor.snapshot(window, cx);
 437            let style = editor.style(cx);
 438            let font_id = window.text_system().resolve_font(&style.text.font());
 439            let font_size = style.text.font_size.to_pixels(window.rem_size());
 440            snapshot
 441                .gutter_dimensions(font_id, font_size, style, window, cx)
 442                .full_width()
 443        });
 444
 445        let clipboard_has_sha = cx
 446            .read_from_clipboard()
 447            .and_then(|entry| entry.text())
 448            .map_or(false, |clipboard_text| {
 449                clipboard_text.trim() == commit_sha.as_ref()
 450            });
 451
 452        let (copy_icon, copy_icon_color) = if clipboard_has_sha {
 453            (IconName::Check, Color::Success)
 454        } else {
 455            (IconName::Copy, Color::Muted)
 456        };
 457
 458        h_flex()
 459            .py_2()
 460            .pr_2p5()
 461            .w_full()
 462            .justify_between()
 463            .border_b_1()
 464            .border_color(cx.theme().colors().border_variant)
 465            .child(
 466                h_flex()
 467                    .child(h_flex().w(gutter_width).justify_center().child(
 468                        self.render_commit_avatar(&commit.sha, rems_from_px(40.), window, cx),
 469                    ))
 470                    .child(
 471                        v_flex().child(Label::new(author_name)).child(
 472                            h_flex()
 473                                .gap_1p5()
 474                                .child(
 475                                    Label::new(date_string)
 476                                        .color(Color::Muted)
 477                                        .size(LabelSize::Small),
 478                                )
 479                                .child(
 480                                    Label::new("")
 481                                        .size(LabelSize::Small)
 482                                        .color(Color::Muted)
 483                                        .alpha(0.5),
 484                                )
 485                                .child(
 486                                    Label::new(author_email)
 487                                        .color(Color::Muted)
 488                                        .size(LabelSize::Small),
 489                                ),
 490                        ),
 491                    ),
 492            )
 493            .when(self.stash.is_none(), |this| {
 494                this.child(
 495                    Button::new("sha", "Commit SHA")
 496                        .start_icon(
 497                            Icon::new(copy_icon)
 498                                .size(IconSize::Small)
 499                                .color(copy_icon_color),
 500                        )
 501                        .tooltip({
 502                            let commit_sha = commit_sha.clone();
 503                            move |_, cx| {
 504                                Tooltip::with_meta("Copy Commit SHA", None, commit_sha.clone(), cx)
 505                            }
 506                        })
 507                        .on_click(move |_, _, cx| {
 508                            cx.stop_propagation();
 509                            cx.write_to_clipboard(ClipboardItem::new_string(
 510                                commit_sha.to_string(),
 511                            ));
 512                        }),
 513                )
 514            })
 515    }
 516
 517    fn apply_stash(workspace: &mut Workspace, window: &mut Window, cx: &mut App) {
 518        Self::stash_action(
 519            workspace,
 520            "Apply",
 521            window,
 522            cx,
 523            async move |repository, sha, stash, commit_view, workspace, cx| {
 524                let result = repository.update(cx, |repo, cx| {
 525                    if !stash_matches_index(&sha, stash, repo) {
 526                        return Err(anyhow::anyhow!("Stash has changed, not applying"));
 527                    }
 528                    Ok(repo.stash_apply(Some(stash), cx))
 529                });
 530
 531                match result {
 532                    Ok(task) => task.await?,
 533                    Err(err) => {
 534                        Self::close_commit_view(commit_view, workspace, cx).await?;
 535                        return Err(err);
 536                    }
 537                };
 538                Self::close_commit_view(commit_view, workspace, cx).await?;
 539                anyhow::Ok(())
 540            },
 541        );
 542    }
 543
 544    fn pop_stash(workspace: &mut Workspace, window: &mut Window, cx: &mut App) {
 545        Self::stash_action(
 546            workspace,
 547            "Pop",
 548            window,
 549            cx,
 550            async move |repository, sha, stash, commit_view, workspace, cx| {
 551                let result = repository.update(cx, |repo, cx| {
 552                    if !stash_matches_index(&sha, stash, repo) {
 553                        return Err(anyhow::anyhow!("Stash has changed, pop aborted"));
 554                    }
 555                    Ok(repo.stash_pop(Some(stash), cx))
 556                });
 557
 558                match result {
 559                    Ok(task) => task.await?,
 560                    Err(err) => {
 561                        Self::close_commit_view(commit_view, workspace, cx).await?;
 562                        return Err(err);
 563                    }
 564                };
 565                Self::close_commit_view(commit_view, workspace, cx).await?;
 566                anyhow::Ok(())
 567            },
 568        );
 569    }
 570
 571    fn remove_stash(workspace: &mut Workspace, window: &mut Window, cx: &mut App) {
 572        Self::stash_action(
 573            workspace,
 574            "Drop",
 575            window,
 576            cx,
 577            async move |repository, sha, stash, commit_view, workspace, cx| {
 578                let result = repository.update(cx, |repo, cx| {
 579                    if !stash_matches_index(&sha, stash, repo) {
 580                        return Err(anyhow::anyhow!("Stash has changed, drop aborted"));
 581                    }
 582                    Ok(repo.stash_drop(Some(stash), cx))
 583                });
 584
 585                match result {
 586                    Ok(task) => task.await??,
 587                    Err(err) => {
 588                        Self::close_commit_view(commit_view, workspace, cx).await?;
 589                        return Err(err);
 590                    }
 591                };
 592                Self::close_commit_view(commit_view, workspace, cx).await?;
 593                anyhow::Ok(())
 594            },
 595        );
 596    }
 597
 598    fn stash_action<AsyncFn>(
 599        workspace: &mut Workspace,
 600        str_action: &str,
 601        window: &mut Window,
 602        cx: &mut App,
 603        callback: AsyncFn,
 604    ) where
 605        AsyncFn: AsyncFnOnce(
 606                Entity<Repository>,
 607                &SharedString,
 608                usize,
 609                Entity<CommitView>,
 610                WeakEntity<Workspace>,
 611                &mut AsyncWindowContext,
 612            ) -> anyhow::Result<()>
 613            + 'static,
 614    {
 615        let Some(commit_view) = workspace.active_item_as::<CommitView>(cx) else {
 616            return;
 617        };
 618        let Some(stash) = commit_view.read(cx).stash else {
 619            return;
 620        };
 621        let sha = commit_view.read(cx).commit.sha.clone();
 622        let answer = window.prompt(
 623            PromptLevel::Info,
 624            &format!("{} stash@{{{}}}?", str_action, stash),
 625            None,
 626            &[str_action, "Cancel"],
 627            cx,
 628        );
 629
 630        let workspace_weak = workspace.weak_handle();
 631        let commit_view_entity = commit_view;
 632
 633        window
 634            .spawn(cx, async move |cx| {
 635                if answer.await != Ok(0) {
 636                    return anyhow::Ok(());
 637                }
 638
 639                let Some(workspace) = workspace_weak.upgrade() else {
 640                    return Ok(());
 641                };
 642
 643                let repo = workspace.update(cx, |workspace, cx| {
 644                    workspace
 645                        .panel::<GitPanel>(cx)
 646                        .and_then(|p| p.read(cx).active_repository.clone())
 647                });
 648
 649                let Some(repo) = repo else {
 650                    return Ok(());
 651                };
 652
 653                callback(repo, &sha, stash, commit_view_entity, workspace_weak, cx).await?;
 654                anyhow::Ok(())
 655            })
 656            .detach_and_notify_err(workspace.weak_handle(), window, cx);
 657    }
 658
 659    async fn close_commit_view(
 660        commit_view: Entity<CommitView>,
 661        workspace: WeakEntity<Workspace>,
 662        cx: &mut AsyncWindowContext,
 663    ) -> anyhow::Result<()> {
 664        workspace
 665            .update_in(cx, |workspace, window, cx| {
 666                let active_pane = workspace.active_pane();
 667                let commit_view_id = commit_view.entity_id();
 668                active_pane.update(cx, |pane, cx| {
 669                    pane.close_item_by_id(commit_view_id, SaveIntent::Skip, window, cx)
 670                })
 671            })?
 672            .await?;
 673        anyhow::Ok(())
 674    }
 675}
 676
 677impl language::File for GitBlob {
 678    fn as_local(&self) -> Option<&dyn language::LocalFile> {
 679        None
 680    }
 681
 682    fn disk_state(&self) -> DiskState {
 683        DiskState::Historic {
 684            was_deleted: self.is_deleted,
 685        }
 686    }
 687
 688    fn path_style(&self, _: &App) -> PathStyle {
 689        PathStyle::local()
 690    }
 691
 692    fn path(&self) -> &Arc<RelPath> {
 693        self.path.as_ref()
 694    }
 695
 696    fn full_path(&self, _: &App) -> PathBuf {
 697        self.path.as_std_path().to_path_buf()
 698    }
 699
 700    fn file_name<'a>(&'a self, _: &'a App) -> &'a str {
 701        self.display_name.as_ref()
 702    }
 703
 704    fn worktree_id(&self, _: &App) -> WorktreeId {
 705        self.worktree_id
 706    }
 707
 708    fn to_proto(&self, _cx: &App) -> language::proto::File {
 709        unimplemented!()
 710    }
 711
 712    fn is_private(&self) -> bool {
 713        false
 714    }
 715
 716    fn can_open(&self) -> bool {
 717        !self.is_binary
 718    }
 719}
 720
 721async fn build_buffer(
 722    mut text: String,
 723    blob: Arc<dyn File>,
 724    language_registry: &Arc<language::LanguageRegistry>,
 725    cx: &mut AsyncApp,
 726) -> Result<Entity<Buffer>> {
 727    let line_ending = LineEnding::detect(&text);
 728    LineEnding::normalize(&mut text);
 729    let text = Rope::from(text);
 730    let language = cx.update(|cx| language_registry.language_for_file(&blob, Some(&text), cx));
 731    let language = if let Some(language) = language {
 732        language_registry
 733            .load_language(&language)
 734            .await
 735            .ok()
 736            .and_then(|e| e.log_err())
 737    } else {
 738        None
 739    };
 740    let buffer = cx.new(|cx| {
 741        let buffer = TextBuffer::new_normalized(
 742            ReplicaId::LOCAL,
 743            cx.entity_id().as_non_zero_u64().into(),
 744            line_ending,
 745            text,
 746        );
 747        let mut buffer = Buffer::build(buffer, Some(blob), Capability::ReadWrite);
 748        buffer.set_language_async(language, cx);
 749        buffer
 750    });
 751    Ok(buffer)
 752}
 753
 754async fn build_buffer_diff(
 755    mut old_text: Option<String>,
 756    buffer: &Entity<Buffer>,
 757    language_registry: &Arc<LanguageRegistry>,
 758    cx: &mut AsyncApp,
 759) -> Result<Entity<BufferDiff>> {
 760    if let Some(old_text) = &mut old_text {
 761        LineEnding::normalize(old_text);
 762    }
 763
 764    let language = cx.update(|cx| buffer.read(cx).language().cloned());
 765    let buffer = cx.update(|cx| buffer.read(cx).snapshot());
 766
 767    let diff = cx.new(|cx| BufferDiff::new(&buffer.text, cx));
 768
 769    let update = diff
 770        .update(cx, |diff, cx| {
 771            diff.update_diff(
 772                buffer.text.clone(),
 773                old_text.map(|old_text| Arc::from(old_text.as_str())),
 774                Some(true),
 775                language.clone(),
 776                cx,
 777            )
 778        })
 779        .await;
 780
 781    diff.update(cx, |diff, cx| {
 782        diff.language_changed(language, Some(language_registry.clone()), cx);
 783        diff.set_snapshot(update, &buffer.text, cx)
 784    })
 785    .await;
 786
 787    Ok(diff)
 788}
 789
 790impl EventEmitter<EditorEvent> for CommitView {}
 791
 792impl Focusable for CommitView {
 793    fn focus_handle(&self, cx: &App) -> FocusHandle {
 794        self.editor.focus_handle(cx)
 795    }
 796}
 797
 798impl Item for CommitView {
 799    type Event = EditorEvent;
 800
 801    fn tab_icon(&self, _window: &Window, _cx: &App) -> Option<Icon> {
 802        Some(Icon::new(IconName::GitCommit).color(Color::Muted))
 803    }
 804
 805    fn tab_content(&self, params: TabContentParams, _window: &Window, cx: &App) -> AnyElement {
 806        Label::new(self.tab_content_text(params.detail.unwrap_or_default(), cx))
 807            .color(if params.selected {
 808                Color::Default
 809            } else {
 810                Color::Muted
 811            })
 812            .into_any_element()
 813    }
 814
 815    fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
 816        let short_sha = self.commit.sha.get(0..7).unwrap_or(&*self.commit.sha);
 817        let subject = truncate_and_trailoff(self.commit.message.split('\n').next().unwrap(), 20);
 818        format!("{short_sha}{subject}").into()
 819    }
 820
 821    fn tab_tooltip_content(&self, _: &App) -> Option<TabTooltipContent> {
 822        let short_sha = self.commit.sha.get(0..16).unwrap_or(&*self.commit.sha);
 823        let subject = self.commit.message.split('\n').next().unwrap();
 824
 825        Some(TabTooltipContent::Custom(Box::new(Tooltip::element({
 826            let subject = subject.to_string();
 827            let short_sha = short_sha.to_string();
 828
 829            move |_, _| {
 830                v_flex()
 831                    .child(Label::new(subject.clone()))
 832                    .child(
 833                        Label::new(short_sha.clone())
 834                            .color(Color::Muted)
 835                            .size(LabelSize::Small),
 836                    )
 837                    .into_any_element()
 838            }
 839        }))))
 840    }
 841
 842    fn to_item_events(event: &EditorEvent, f: &mut dyn FnMut(ItemEvent)) {
 843        Editor::to_item_events(event, f)
 844    }
 845
 846    fn telemetry_event_text(&self) -> Option<&'static str> {
 847        Some("Commit View Opened")
 848    }
 849
 850    fn deactivated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 851        self.editor
 852            .update(cx, |editor, cx| editor.deactivated(window, cx));
 853    }
 854
 855    fn act_as_type<'a>(
 856        &'a self,
 857        type_id: TypeId,
 858        self_handle: &'a Entity<Self>,
 859        _: &'a App,
 860    ) -> Option<gpui::AnyEntity> {
 861        if type_id == TypeId::of::<Self>() {
 862            Some(self_handle.clone().into())
 863        } else if type_id == TypeId::of::<Editor>() {
 864            Some(self.editor.clone().into())
 865        } else {
 866            None
 867        }
 868    }
 869
 870    fn as_searchable(&self, _: &Entity<Self>, _: &App) -> Option<Box<dyn SearchableItemHandle>> {
 871        Some(Box::new(self.editor.clone()))
 872    }
 873
 874    fn for_each_project_item(
 875        &self,
 876        cx: &App,
 877        f: &mut dyn FnMut(gpui::EntityId, &dyn project::ProjectItem),
 878    ) {
 879        self.editor.for_each_project_item(cx, f)
 880    }
 881
 882    fn set_nav_history(
 883        &mut self,
 884        nav_history: ItemNavHistory,
 885        _: &mut Window,
 886        cx: &mut Context<Self>,
 887    ) {
 888        self.editor.update(cx, |editor, _| {
 889            editor.set_nav_history(Some(nav_history));
 890        });
 891    }
 892
 893    fn navigate(
 894        &mut self,
 895        data: Arc<dyn Any + Send>,
 896        window: &mut Window,
 897        cx: &mut Context<Self>,
 898    ) -> bool {
 899        self.editor
 900            .update(cx, |editor, cx| editor.navigate(data, window, cx))
 901    }
 902
 903    fn added_to_workspace(
 904        &mut self,
 905        workspace: &mut Workspace,
 906        window: &mut Window,
 907        cx: &mut Context<Self>,
 908    ) {
 909        self.editor.update(cx, |editor, cx| {
 910            editor.added_to_workspace(workspace, window, cx)
 911        });
 912    }
 913
 914    fn can_split(&self) -> bool {
 915        true
 916    }
 917
 918    fn clone_on_split(
 919        &self,
 920        _workspace_id: Option<workspace::WorkspaceId>,
 921        window: &mut Window,
 922        cx: &mut Context<Self>,
 923    ) -> Task<Option<Entity<Self>>>
 924    where
 925        Self: Sized,
 926    {
 927        let file_statuses = self
 928            .editor
 929            .read(cx)
 930            .addon::<CommitDiffAddon>()
 931            .map(|addon| addon.file_statuses.clone())
 932            .unwrap_or_default();
 933        Task::ready(Some(cx.new(|cx| {
 934            let editor = cx.new({
 935                let file_statuses = file_statuses.clone();
 936                |cx| {
 937                    let mut editor = self
 938                        .editor
 939                        .update(cx, |editor, cx| editor.clone(window, cx));
 940                    editor.register_addon(CommitDiffAddon { file_statuses });
 941                    editor
 942                }
 943            });
 944            let multibuffer = editor.read(cx).buffer().clone();
 945            Self {
 946                editor,
 947                multibuffer,
 948                commit: self.commit.clone(),
 949                stash: self.stash,
 950                repository: self.repository.clone(),
 951                remote: self.remote.clone(),
 952            }
 953        })))
 954    }
 955}
 956
 957impl Render for CommitView {
 958    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 959        let is_stash = self.stash.is_some();
 960
 961        v_flex()
 962            .key_context(if is_stash { "StashDiff" } else { "CommitDiff" })
 963            .size_full()
 964            .bg(cx.theme().colors().editor_background)
 965            .child(self.render_header(window, cx))
 966            .when(!self.editor.read(cx).is_empty(cx), |this| {
 967                this.child(div().flex_grow().child(self.editor.clone()))
 968            })
 969    }
 970}
 971
 972pub struct CommitViewToolbar {
 973    commit_view: Option<WeakEntity<CommitView>>,
 974}
 975
 976impl CommitViewToolbar {
 977    pub fn new() -> Self {
 978        Self { commit_view: None }
 979    }
 980}
 981
 982impl EventEmitter<ToolbarItemEvent> for CommitViewToolbar {}
 983
 984impl Render for CommitViewToolbar {
 985    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 986        let Some(commit_view) = self.commit_view.as_ref().and_then(|w| w.upgrade()) else {
 987            return div();
 988        };
 989
 990        let commit_view_ref = commit_view.read(cx);
 991        let is_stash = commit_view_ref.stash.is_some();
 992
 993        let (additions, deletions) = commit_view_ref.calculate_changed_lines(cx);
 994
 995        let commit_sha = commit_view_ref.commit.sha.clone();
 996
 997        let remote_info = commit_view_ref.remote.as_ref().map(|remote| {
 998            let provider = remote.host.name();
 999            let parsed_remote = ParsedGitRemote {
1000                owner: remote.owner.as_ref().into(),
1001                repo: remote.repo.as_ref().into(),
1002            };
1003            let params = BuildCommitPermalinkParams { sha: &commit_sha };
1004            let url = remote
1005                .host
1006                .build_commit_permalink(&parsed_remote, params)
1007                .to_string();
1008            (provider, url)
1009        });
1010
1011        let sha_for_graph = commit_sha.to_string();
1012
1013        h_flex()
1014            .gap_1()
1015            .when(additions > 0 || deletions > 0, |this| {
1016                this.child(
1017                    h_flex()
1018                        .gap_2()
1019                        .child(DiffStat::new(
1020                            "toolbar-diff-stat",
1021                            additions as usize,
1022                            deletions as usize,
1023                        ))
1024                        .child(Divider::vertical()),
1025                )
1026            })
1027            .child(
1028                IconButton::new("buffer-search", IconName::MagnifyingGlass)
1029                    .icon_size(IconSize::Small)
1030                    .tooltip(move |_, cx| {
1031                        Tooltip::for_action(
1032                            "Buffer Search",
1033                            &zed_actions::buffer_search::Deploy::find(),
1034                            cx,
1035                        )
1036                    })
1037                    .on_click(|_, window, cx| {
1038                        window.dispatch_action(
1039                            Box::new(zed_actions::buffer_search::Deploy::find()),
1040                            cx,
1041                        );
1042                    }),
1043            )
1044            .when(!is_stash, |this| {
1045                this.when(cx.has_flag::<GitGraphFeatureFlag>(), |this| {
1046                    this.child(
1047                        IconButton::new("show-in-git-graph", IconName::GitGraph)
1048                            .icon_size(IconSize::Small)
1049                            .tooltip(Tooltip::text("Show in Git Graph"))
1050                            .on_click(move |_, window, cx| {
1051                                window.dispatch_action(
1052                                    Box::new(crate::git_panel::OpenAtCommit {
1053                                        sha: sha_for_graph.clone(),
1054                                    }),
1055                                    cx,
1056                                );
1057                            }),
1058                    )
1059                })
1060                .children(remote_info.map(|(provider_name, url)| {
1061                    let icon = match provider_name.as_str() {
1062                        "GitHub" => IconName::Github,
1063                        _ => IconName::Link,
1064                    };
1065
1066                    IconButton::new("view_on_provider", icon)
1067                        .icon_size(IconSize::Small)
1068                        .tooltip(Tooltip::text(format!("View on {}", provider_name)))
1069                        .on_click(move |_, _, cx| cx.open_url(&url))
1070                }))
1071            })
1072    }
1073}
1074
1075impl ToolbarItemView for CommitViewToolbar {
1076    fn set_active_pane_item(
1077        &mut self,
1078        active_pane_item: Option<&dyn ItemHandle>,
1079        _: &mut Window,
1080        cx: &mut Context<Self>,
1081    ) -> ToolbarItemLocation {
1082        if let Some(entity) = active_pane_item.and_then(|i| i.act_as::<CommitView>(cx)) {
1083            self.commit_view = Some(entity.downgrade());
1084            return ToolbarItemLocation::PrimaryRight;
1085        }
1086        self.commit_view = None;
1087        ToolbarItemLocation::Hidden
1088    }
1089
1090    fn pane_focus_update(
1091        &mut self,
1092        _pane_focused: bool,
1093        _window: &mut Window,
1094        _cx: &mut Context<Self>,
1095    ) {
1096    }
1097}
1098
1099fn stash_matches_index(sha: &str, stash_index: usize, repo: &Repository) -> bool {
1100    repo.stash_entries
1101        .entries
1102        .get(stash_index)
1103        .map(|entry| entry.oid.to_string() == sha)
1104        .unwrap_or(false)
1105}