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