git_panel.rs

   1use crate::askpass_modal::AskPassModal;
   2use crate::branch_picker;
   3use crate::commit_modal::CommitModal;
   4use crate::git_panel_settings::StatusStyle;
   5use crate::remote_output_toast::{RemoteAction, RemoteOutputToast};
   6use crate::{
   7    git_panel_settings::GitPanelSettings, git_status_icon, repository_selector::RepositorySelector,
   8};
   9use crate::{picker_prompt, project_diff, ProjectDiff};
  10use anyhow::Result;
  11use askpass::AskPassDelegate;
  12use db::kvp::KEY_VALUE_STORE;
  13use editor::commit_tooltip::CommitTooltip;
  14
  15use editor::{
  16    scroll::ScrollbarAutoHide, Editor, EditorElement, EditorMode, EditorSettings, MultiBuffer,
  17    ShowScrollbar,
  18};
  19use futures::StreamExt as _;
  20use git::repository::{
  21    Branch, CommitDetails, CommitSummary, PushOptions, Remote, RemoteCommandOutput, ResetMode,
  22    Upstream, UpstreamTracking, UpstreamTrackingStatus,
  23};
  24use git::{repository::RepoPath, status::FileStatus, Commit, ToggleStaged};
  25use git::{RestoreTrackedFiles, StageAll, TrashUntrackedFiles, UnstageAll};
  26use gpui::*;
  27use itertools::Itertools;
  28use language::{Buffer, File};
  29use language_model::{
  30    LanguageModelRegistry, LanguageModelRequest, LanguageModelRequestMessage, Role,
  31};
  32use menu::{Confirm, SecondaryConfirm, SelectFirst, SelectLast, SelectNext, SelectPrevious};
  33use multi_buffer::ExcerptInfo;
  34use panel::{
  35    panel_editor_container, panel_editor_style, panel_filled_button, panel_icon_button, PanelHeader,
  36};
  37use project::{
  38    git::{GitEvent, Repository},
  39    Fs, Project, ProjectPath,
  40};
  41use serde::{Deserialize, Serialize};
  42use settings::Settings as _;
  43use smallvec::smallvec;
  44use std::cell::RefCell;
  45use std::future::Future;
  46use std::rc::Rc;
  47use std::{collections::HashSet, sync::Arc, time::Duration, usize};
  48use strum::{IntoEnumIterator, VariantNames};
  49use time::OffsetDateTime;
  50use ui::{
  51    prelude::*, ButtonLike, Checkbox, ContextMenu, ElevationIndex, PopoverMenu, Scrollbar,
  52    ScrollbarState, Tooltip,
  53};
  54use util::{maybe, post_inc, ResultExt, TryFutureExt};
  55
  56use workspace::{
  57    dock::{DockPosition, Panel, PanelEvent},
  58    notifications::{DetachAndPromptErr, NotificationId},
  59    Toast, Workspace,
  60};
  61
  62actions!(
  63    git_panel,
  64    [
  65        Close,
  66        ToggleFocus,
  67        OpenMenu,
  68        FocusEditor,
  69        FocusChanges,
  70        ToggleFillCoAuthors,
  71    ]
  72);
  73
  74fn prompt<T>(msg: &str, detail: Option<&str>, window: &mut Window, cx: &mut App) -> Task<Result<T>>
  75where
  76    T: IntoEnumIterator + VariantNames + 'static,
  77{
  78    let rx = window.prompt(PromptLevel::Info, msg, detail, &T::VARIANTS, cx);
  79    cx.spawn(|_| async move { Ok(T::iter().nth(rx.await?).unwrap()) })
  80}
  81
  82#[derive(strum::EnumIter, strum::VariantNames)]
  83#[strum(serialize_all = "title_case")]
  84enum TrashCancel {
  85    Trash,
  86    Cancel,
  87}
  88
  89fn git_panel_context_menu(window: &mut Window, cx: &mut App) -> Entity<ContextMenu> {
  90    ContextMenu::build(window, cx, |context_menu, _, _| {
  91        context_menu
  92            .action("Stage All", StageAll.boxed_clone())
  93            .action("Unstage All", UnstageAll.boxed_clone())
  94            .separator()
  95            .action("Open Diff", project_diff::Diff.boxed_clone())
  96            .separator()
  97            .action("Discard Tracked Changes", RestoreTrackedFiles.boxed_clone())
  98            .action("Trash Untracked Files", TrashUntrackedFiles.boxed_clone())
  99    })
 100}
 101
 102const GIT_PANEL_KEY: &str = "GitPanel";
 103
 104const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
 105
 106pub fn init(cx: &mut App) {
 107    cx.observe_new(
 108        |workspace: &mut Workspace, _window, _: &mut Context<Workspace>| {
 109            workspace.register_action(|workspace, _: &ToggleFocus, window, cx| {
 110                workspace.toggle_panel_focus::<GitPanel>(window, cx);
 111            });
 112        },
 113    )
 114    .detach();
 115}
 116
 117#[derive(Debug, Clone)]
 118pub enum Event {
 119    Focus,
 120}
 121
 122#[derive(Serialize, Deserialize)]
 123struct SerializedGitPanel {
 124    width: Option<Pixels>,
 125}
 126
 127#[derive(Debug, PartialEq, Eq, Clone, Copy)]
 128enum Section {
 129    Conflict,
 130    Tracked,
 131    New,
 132}
 133
 134#[derive(Debug, PartialEq, Eq, Clone)]
 135struct GitHeaderEntry {
 136    header: Section,
 137}
 138
 139impl GitHeaderEntry {
 140    pub fn contains(&self, status_entry: &GitStatusEntry, repo: &Repository) -> bool {
 141        let this = &self.header;
 142        let status = status_entry.status;
 143        match this {
 144            Section::Conflict => repo.has_conflict(&status_entry.repo_path),
 145            Section::Tracked => !status.is_created(),
 146            Section::New => status.is_created(),
 147        }
 148    }
 149    pub fn title(&self) -> &'static str {
 150        match self.header {
 151            Section::Conflict => "Conflicts",
 152            Section::Tracked => "Tracked",
 153            Section::New => "Untracked",
 154        }
 155    }
 156}
 157
 158#[derive(Debug, PartialEq, Eq, Clone)]
 159enum GitListEntry {
 160    GitStatusEntry(GitStatusEntry),
 161    Header(GitHeaderEntry),
 162}
 163
 164impl GitListEntry {
 165    fn status_entry(&self) -> Option<&GitStatusEntry> {
 166        match self {
 167            GitListEntry::GitStatusEntry(entry) => Some(entry),
 168            _ => None,
 169        }
 170    }
 171}
 172
 173#[derive(Debug, PartialEq, Eq, Clone)]
 174pub struct GitStatusEntry {
 175    pub(crate) repo_path: RepoPath,
 176    pub(crate) status: FileStatus,
 177    pub(crate) is_staged: Option<bool>,
 178}
 179
 180#[derive(Clone, Copy, Debug, PartialEq, Eq)]
 181enum TargetStatus {
 182    Staged,
 183    Unstaged,
 184    Reverted,
 185    Unchanged,
 186}
 187
 188struct PendingOperation {
 189    finished: bool,
 190    target_status: TargetStatus,
 191    repo_paths: HashSet<RepoPath>,
 192    op_id: usize,
 193}
 194
 195type RemoteOperations = Rc<RefCell<HashSet<u32>>>;
 196
 197pub struct GitPanel {
 198    remote_operation_id: u32,
 199    pending_remote_operations: RemoteOperations,
 200    pub(crate) active_repository: Option<Entity<Repository>>,
 201    pub(crate) commit_editor: Entity<Editor>,
 202    conflicted_count: usize,
 203    conflicted_staged_count: usize,
 204    current_modifiers: Modifiers,
 205    add_coauthors: bool,
 206    generate_commit_message_task: Option<Task<Option<()>>>,
 207    entries: Vec<GitListEntry>,
 208    focus_handle: FocusHandle,
 209    fs: Arc<dyn Fs>,
 210    hide_scrollbar_task: Option<Task<()>>,
 211    new_count: usize,
 212    new_staged_count: usize,
 213    pending: Vec<PendingOperation>,
 214    pending_commit: Option<Task<()>>,
 215    pending_serialization: Task<Option<()>>,
 216    pub(crate) project: Entity<Project>,
 217    scroll_handle: UniformListScrollHandle,
 218    scrollbar_state: ScrollbarState,
 219    selected_entry: Option<usize>,
 220    marked_entries: Vec<usize>,
 221    show_scrollbar: bool,
 222    tracked_count: usize,
 223    tracked_staged_count: usize,
 224    update_visible_entries_task: Task<()>,
 225    width: Option<Pixels>,
 226    workspace: WeakEntity<Workspace>,
 227    context_menu: Option<(Entity<ContextMenu>, Point<Pixels>, Subscription)>,
 228    modal_open: bool,
 229}
 230
 231struct RemoteOperationGuard {
 232    id: u32,
 233    pending_remote_operations: RemoteOperations,
 234}
 235
 236impl Drop for RemoteOperationGuard {
 237    fn drop(&mut self) {
 238        self.pending_remote_operations.borrow_mut().remove(&self.id);
 239    }
 240}
 241
 242pub(crate) fn commit_message_editor(
 243    commit_message_buffer: Entity<Buffer>,
 244    placeholder: Option<&str>,
 245    project: Entity<Project>,
 246    in_panel: bool,
 247    window: &mut Window,
 248    cx: &mut Context<'_, Editor>,
 249) -> Editor {
 250    let buffer = cx.new(|cx| MultiBuffer::singleton(commit_message_buffer, cx));
 251    let max_lines = if in_panel { 6 } else { 18 };
 252    let mut commit_editor = Editor::new(
 253        EditorMode::AutoHeight { max_lines },
 254        buffer,
 255        None,
 256        false,
 257        window,
 258        cx,
 259    );
 260    commit_editor.set_collaboration_hub(Box::new(project));
 261    commit_editor.set_use_autoclose(false);
 262    commit_editor.set_show_gutter(false, cx);
 263    commit_editor.set_show_wrap_guides(false, cx);
 264    commit_editor.set_show_indent_guides(false, cx);
 265    let placeholder = placeholder.unwrap_or("Enter commit message");
 266    commit_editor.set_placeholder_text(placeholder, cx);
 267    commit_editor
 268}
 269
 270impl GitPanel {
 271    pub fn new(
 272        workspace: &mut Workspace,
 273        window: &mut Window,
 274        cx: &mut Context<Workspace>,
 275    ) -> Entity<Self> {
 276        let fs = workspace.app_state().fs.clone();
 277        let project = workspace.project().clone();
 278        let git_store = project.read(cx).git_store().clone();
 279        let active_repository = project.read(cx).active_repository(cx);
 280        let workspace = cx.entity().downgrade();
 281
 282        cx.new(|cx| {
 283            let focus_handle = cx.focus_handle();
 284            cx.on_focus(&focus_handle, window, Self::focus_in).detach();
 285            cx.on_focus_out(&focus_handle, window, |this, _, window, cx| {
 286                this.hide_scrollbar(window, cx);
 287            })
 288            .detach();
 289
 290            // just to let us render a placeholder editor.
 291            // Once the active git repo is set, this buffer will be replaced.
 292            let temporary_buffer = cx.new(|cx| Buffer::local("", cx));
 293            let commit_editor = cx.new(|cx| {
 294                commit_message_editor(temporary_buffer, None, project.clone(), true, window, cx)
 295            });
 296
 297            commit_editor.update(cx, |editor, cx| {
 298                editor.clear(window, cx);
 299            });
 300
 301            let scroll_handle = UniformListScrollHandle::new();
 302
 303            cx.subscribe_in(
 304                &git_store,
 305                window,
 306                move |this, git_store, event, window, cx| match event {
 307                    GitEvent::FileSystemUpdated => {
 308                        this.schedule_update(false, window, cx);
 309                    }
 310                    GitEvent::ActiveRepositoryChanged | GitEvent::GitStateUpdated => {
 311                        this.active_repository = git_store.read(cx).active_repository();
 312                        this.schedule_update(true, window, cx);
 313                    }
 314                    GitEvent::IndexWriteError(error) => {
 315                        this.workspace
 316                            .update(cx, |workspace, cx| {
 317                                workspace.show_error(error, cx);
 318                            })
 319                            .ok();
 320                    }
 321                },
 322            )
 323            .detach();
 324
 325            let scrollbar_state =
 326                ScrollbarState::new(scroll_handle.clone()).parent_entity(&cx.entity());
 327
 328            let mut git_panel = Self {
 329                pending_remote_operations: Default::default(),
 330                remote_operation_id: 0,
 331                active_repository,
 332                commit_editor,
 333                conflicted_count: 0,
 334                conflicted_staged_count: 0,
 335                current_modifiers: window.modifiers(),
 336                add_coauthors: true,
 337                generate_commit_message_task: None,
 338                entries: Vec::new(),
 339                focus_handle: cx.focus_handle(),
 340                fs,
 341                hide_scrollbar_task: None,
 342                new_count: 0,
 343                new_staged_count: 0,
 344                pending: Vec::new(),
 345                pending_commit: None,
 346                pending_serialization: Task::ready(None),
 347                project,
 348                scroll_handle,
 349                scrollbar_state,
 350                selected_entry: None,
 351                marked_entries: Vec::new(),
 352                show_scrollbar: false,
 353                tracked_count: 0,
 354                tracked_staged_count: 0,
 355                update_visible_entries_task: Task::ready(()),
 356                width: Some(px(360.)),
 357                context_menu: None,
 358                workspace,
 359                modal_open: false,
 360            };
 361            git_panel.schedule_update(false, window, cx);
 362            git_panel.show_scrollbar = git_panel.should_show_scrollbar(cx);
 363            git_panel
 364        })
 365    }
 366
 367    pub fn entry_by_path(&self, path: &RepoPath) -> Option<usize> {
 368        fn binary_search<F>(mut low: usize, mut high: usize, is_target: F) -> Option<usize>
 369        where
 370            F: Fn(usize) -> std::cmp::Ordering,
 371        {
 372            while low < high {
 373                let mid = low + (high - low) / 2;
 374                match is_target(mid) {
 375                    std::cmp::Ordering::Equal => return Some(mid),
 376                    std::cmp::Ordering::Less => low = mid + 1,
 377                    std::cmp::Ordering::Greater => high = mid,
 378                }
 379            }
 380            None
 381        }
 382        if self.conflicted_count > 0 {
 383            let conflicted_start = 1;
 384            if let Some(ix) = binary_search(
 385                conflicted_start,
 386                conflicted_start + self.conflicted_count,
 387                |ix| {
 388                    self.entries[ix]
 389                        .status_entry()
 390                        .unwrap()
 391                        .repo_path
 392                        .cmp(&path)
 393                },
 394            ) {
 395                return Some(ix);
 396            }
 397        }
 398        if self.tracked_count > 0 {
 399            let tracked_start = if self.conflicted_count > 0 {
 400                1 + self.conflicted_count
 401            } else {
 402                0
 403            } + 1;
 404            if let Some(ix) =
 405                binary_search(tracked_start, tracked_start + self.tracked_count, |ix| {
 406                    self.entries[ix]
 407                        .status_entry()
 408                        .unwrap()
 409                        .repo_path
 410                        .cmp(&path)
 411                })
 412            {
 413                return Some(ix);
 414            }
 415        }
 416        if self.new_count > 0 {
 417            let untracked_start = if self.conflicted_count > 0 {
 418                1 + self.conflicted_count
 419            } else {
 420                0
 421            } + if self.tracked_count > 0 {
 422                1 + self.tracked_count
 423            } else {
 424                0
 425            } + 1;
 426            if let Some(ix) =
 427                binary_search(untracked_start, untracked_start + self.new_count, |ix| {
 428                    self.entries[ix]
 429                        .status_entry()
 430                        .unwrap()
 431                        .repo_path
 432                        .cmp(&path)
 433                })
 434            {
 435                return Some(ix);
 436            }
 437        }
 438        None
 439    }
 440
 441    pub fn select_entry_by_path(
 442        &mut self,
 443        path: ProjectPath,
 444        _: &mut Window,
 445        cx: &mut Context<Self>,
 446    ) {
 447        let Some(git_repo) = self.active_repository.as_ref() else {
 448            return;
 449        };
 450        let Some(repo_path) = git_repo.read(cx).project_path_to_repo_path(&path) else {
 451            return;
 452        };
 453        let Some(ix) = self.entry_by_path(&repo_path) else {
 454            return;
 455        };
 456        self.selected_entry = Some(ix);
 457        cx.notify();
 458    }
 459
 460    fn start_remote_operation(&mut self) -> RemoteOperationGuard {
 461        let id = post_inc(&mut self.remote_operation_id);
 462        self.pending_remote_operations.borrow_mut().insert(id);
 463
 464        RemoteOperationGuard {
 465            id,
 466            pending_remote_operations: self.pending_remote_operations.clone(),
 467        }
 468    }
 469
 470    fn serialize(&mut self, cx: &mut Context<Self>) {
 471        let width = self.width;
 472        self.pending_serialization = cx.background_spawn(
 473            async move {
 474                KEY_VALUE_STORE
 475                    .write_kvp(
 476                        GIT_PANEL_KEY.into(),
 477                        serde_json::to_string(&SerializedGitPanel { width })?,
 478                    )
 479                    .await?;
 480                anyhow::Ok(())
 481            }
 482            .log_err(),
 483        );
 484    }
 485
 486    pub(crate) fn set_modal_open(&mut self, open: bool, cx: &mut Context<Self>) {
 487        self.modal_open = open;
 488        cx.notify();
 489    }
 490
 491    fn dispatch_context(&self, window: &mut Window, cx: &Context<Self>) -> KeyContext {
 492        let mut dispatch_context = KeyContext::new_with_defaults();
 493        dispatch_context.add("GitPanel");
 494
 495        if self.is_focused(window, cx) {
 496            dispatch_context.add("menu");
 497            dispatch_context.add("ChangesList");
 498        }
 499
 500        if self.commit_editor.read(cx).is_focused(window) {
 501            dispatch_context.add("CommitEditor");
 502        }
 503
 504        dispatch_context
 505    }
 506
 507    fn is_focused(&self, window: &Window, cx: &Context<Self>) -> bool {
 508        window
 509            .focused(cx)
 510            .map_or(false, |focused| self.focus_handle == focused)
 511    }
 512
 513    fn close_panel(&mut self, _: &Close, _window: &mut Window, cx: &mut Context<Self>) {
 514        cx.emit(PanelEvent::Close);
 515    }
 516
 517    fn focus_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 518        if !self.focus_handle.contains_focused(window, cx) {
 519            cx.emit(Event::Focus);
 520        }
 521    }
 522
 523    fn show_scrollbar(&self, cx: &mut Context<Self>) -> ShowScrollbar {
 524        GitPanelSettings::get_global(cx)
 525            .scrollbar
 526            .show
 527            .unwrap_or_else(|| EditorSettings::get_global(cx).scrollbar.show)
 528    }
 529
 530    fn should_show_scrollbar(&self, cx: &mut Context<Self>) -> bool {
 531        let show = self.show_scrollbar(cx);
 532        match show {
 533            ShowScrollbar::Auto => true,
 534            ShowScrollbar::System => true,
 535            ShowScrollbar::Always => true,
 536            ShowScrollbar::Never => false,
 537        }
 538    }
 539
 540    fn should_autohide_scrollbar(&self, cx: &mut Context<Self>) -> bool {
 541        let show = self.show_scrollbar(cx);
 542        match show {
 543            ShowScrollbar::Auto => true,
 544            ShowScrollbar::System => cx
 545                .try_global::<ScrollbarAutoHide>()
 546                .map_or_else(|| cx.should_auto_hide_scrollbars(), |autohide| autohide.0),
 547            ShowScrollbar::Always => false,
 548            ShowScrollbar::Never => true,
 549        }
 550    }
 551
 552    fn hide_scrollbar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 553        const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);
 554        if !self.should_autohide_scrollbar(cx) {
 555            return;
 556        }
 557        self.hide_scrollbar_task = Some(cx.spawn_in(window, |panel, mut cx| async move {
 558            cx.background_executor()
 559                .timer(SCROLLBAR_SHOW_INTERVAL)
 560                .await;
 561            panel
 562                .update(&mut cx, |panel, cx| {
 563                    panel.show_scrollbar = false;
 564                    cx.notify();
 565                })
 566                .log_err();
 567        }))
 568    }
 569
 570    fn handle_modifiers_changed(
 571        &mut self,
 572        event: &ModifiersChangedEvent,
 573        _: &mut Window,
 574        cx: &mut Context<Self>,
 575    ) {
 576        self.current_modifiers = event.modifiers;
 577        cx.notify();
 578    }
 579
 580    fn scroll_to_selected_entry(&mut self, cx: &mut Context<Self>) {
 581        if let Some(selected_entry) = self.selected_entry {
 582            self.scroll_handle
 583                .scroll_to_item(selected_entry, ScrollStrategy::Center);
 584        }
 585
 586        cx.notify();
 587    }
 588
 589    fn select_first(&mut self, _: &SelectFirst, _window: &mut Window, cx: &mut Context<Self>) {
 590        if !self.entries.is_empty() {
 591            self.selected_entry = Some(1);
 592            self.scroll_to_selected_entry(cx);
 593        }
 594    }
 595
 596    fn select_previous(
 597        &mut self,
 598        _: &SelectPrevious,
 599        _window: &mut Window,
 600        cx: &mut Context<Self>,
 601    ) {
 602        let item_count = self.entries.len();
 603        if item_count == 0 {
 604            return;
 605        }
 606
 607        if let Some(selected_entry) = self.selected_entry {
 608            let new_selected_entry = if selected_entry > 0 {
 609                selected_entry - 1
 610            } else {
 611                selected_entry
 612            };
 613
 614            if matches!(
 615                self.entries.get(new_selected_entry),
 616                Some(GitListEntry::Header(..))
 617            ) {
 618                if new_selected_entry > 0 {
 619                    self.selected_entry = Some(new_selected_entry - 1)
 620                }
 621            } else {
 622                self.selected_entry = Some(new_selected_entry);
 623            }
 624
 625            self.scroll_to_selected_entry(cx);
 626        }
 627
 628        cx.notify();
 629    }
 630
 631    fn select_next(&mut self, _: &SelectNext, _window: &mut Window, cx: &mut Context<Self>) {
 632        let item_count = self.entries.len();
 633        if item_count == 0 {
 634            return;
 635        }
 636
 637        if let Some(selected_entry) = self.selected_entry {
 638            let new_selected_entry = if selected_entry < item_count - 1 {
 639                selected_entry + 1
 640            } else {
 641                selected_entry
 642            };
 643            if matches!(
 644                self.entries.get(new_selected_entry),
 645                Some(GitListEntry::Header(..))
 646            ) {
 647                self.selected_entry = Some(new_selected_entry + 1);
 648            } else {
 649                self.selected_entry = Some(new_selected_entry);
 650            }
 651
 652            self.scroll_to_selected_entry(cx);
 653        }
 654
 655        cx.notify();
 656    }
 657
 658    fn select_last(&mut self, _: &SelectLast, _window: &mut Window, cx: &mut Context<Self>) {
 659        if self.entries.last().is_some() {
 660            self.selected_entry = Some(self.entries.len() - 1);
 661            self.scroll_to_selected_entry(cx);
 662        }
 663    }
 664
 665    pub(crate) fn editor_focus_handle(&self, cx: &mut Context<Self>) -> FocusHandle {
 666        self.commit_editor.focus_handle(cx).clone()
 667    }
 668
 669    fn focus_editor(&mut self, _: &FocusEditor, window: &mut Window, cx: &mut Context<Self>) {
 670        self.commit_editor.update(cx, |editor, cx| {
 671            window.focus(&editor.focus_handle(cx));
 672        });
 673        cx.notify();
 674    }
 675
 676    fn select_first_entry_if_none(&mut self, cx: &mut Context<Self>) {
 677        let have_entries = self
 678            .active_repository
 679            .as_ref()
 680            .map_or(false, |active_repository| {
 681                active_repository.read(cx).entry_count() > 0
 682            });
 683        if have_entries && self.selected_entry.is_none() {
 684            self.selected_entry = Some(1);
 685            self.scroll_to_selected_entry(cx);
 686            cx.notify();
 687        }
 688    }
 689
 690    fn focus_changes_list(
 691        &mut self,
 692        _: &FocusChanges,
 693        window: &mut Window,
 694        cx: &mut Context<Self>,
 695    ) {
 696        self.select_first_entry_if_none(cx);
 697
 698        cx.focus_self(window);
 699        cx.notify();
 700    }
 701
 702    fn get_selected_entry(&self) -> Option<&GitListEntry> {
 703        self.selected_entry.and_then(|i| self.entries.get(i))
 704    }
 705
 706    fn open_diff(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
 707        maybe!({
 708            let entry = self.entries.get(self.selected_entry?)?.status_entry()?;
 709            let workspace = self.workspace.upgrade()?;
 710            let git_repo = self.active_repository.as_ref()?;
 711
 712            if let Some(project_diff) = workspace.read(cx).active_item_as::<ProjectDiff>(cx) {
 713                if let Some(project_path) = project_diff.read(cx).active_path(cx) {
 714                    if Some(&entry.repo_path)
 715                        == git_repo
 716                            .read(cx)
 717                            .project_path_to_repo_path(&project_path)
 718                            .as_ref()
 719                    {
 720                        project_diff.focus_handle(cx).focus(window);
 721                        return None;
 722                    }
 723                }
 724            };
 725
 726            self.workspace
 727                .update(cx, |workspace, cx| {
 728                    ProjectDiff::deploy_at(workspace, Some(entry.clone()), window, cx);
 729                })
 730                .ok();
 731            self.focus_handle.focus(window);
 732
 733            Some(())
 734        });
 735    }
 736
 737    fn open_file(
 738        &mut self,
 739        _: &menu::SecondaryConfirm,
 740        window: &mut Window,
 741        cx: &mut Context<Self>,
 742    ) {
 743        maybe!({
 744            let entry = self.entries.get(self.selected_entry?)?.status_entry()?;
 745            let active_repo = self.active_repository.as_ref()?;
 746            let path = active_repo
 747                .read(cx)
 748                .repo_path_to_project_path(&entry.repo_path)?;
 749            if entry.status.is_deleted() {
 750                return None;
 751            }
 752
 753            self.workspace
 754                .update(cx, |workspace, cx| {
 755                    workspace
 756                        .open_path_preview(path, None, false, false, true, window, cx)
 757                        .detach_and_prompt_err("Failed to open file", window, cx, |e, _, _| {
 758                            Some(format!("{e}"))
 759                        });
 760                })
 761                .ok()
 762        });
 763    }
 764
 765    fn revert_selected(
 766        &mut self,
 767        _: &git::RestoreFile,
 768        window: &mut Window,
 769        cx: &mut Context<Self>,
 770    ) {
 771        maybe!({
 772            let list_entry = self.entries.get(self.selected_entry?)?.clone();
 773            let entry = list_entry.status_entry()?;
 774            self.revert_entry(&entry, window, cx);
 775            Some(())
 776        });
 777    }
 778
 779    fn revert_entry(
 780        &mut self,
 781        entry: &GitStatusEntry,
 782        window: &mut Window,
 783        cx: &mut Context<Self>,
 784    ) {
 785        maybe!({
 786            let active_repo = self.active_repository.clone()?;
 787            let path = active_repo
 788                .read(cx)
 789                .repo_path_to_project_path(&entry.repo_path)?;
 790            let workspace = self.workspace.clone();
 791
 792            if entry.status.is_staged() != Some(false) {
 793                self.perform_stage(false, vec![entry.repo_path.clone()], cx);
 794            }
 795            let filename = path.path.file_name()?.to_string_lossy();
 796
 797            if !entry.status.is_created() {
 798                self.perform_checkout(vec![entry.repo_path.clone()], cx);
 799            } else {
 800                let prompt = prompt(&format!("Trash {}?", filename), None, window, cx);
 801                cx.spawn_in(window, |_, mut cx| async move {
 802                    match prompt.await? {
 803                        TrashCancel::Trash => {}
 804                        TrashCancel::Cancel => return Ok(()),
 805                    }
 806                    let task = workspace.update(&mut cx, |workspace, cx| {
 807                        workspace
 808                            .project()
 809                            .update(cx, |project, cx| project.delete_file(path, true, cx))
 810                    })?;
 811                    if let Some(task) = task {
 812                        task.await?;
 813                    }
 814                    Ok(())
 815                })
 816                .detach_and_prompt_err(
 817                    "Failed to trash file",
 818                    window,
 819                    cx,
 820                    |e, _, _| Some(format!("{e}")),
 821                );
 822            }
 823            Some(())
 824        });
 825    }
 826
 827    fn perform_checkout(&mut self, repo_paths: Vec<RepoPath>, cx: &mut Context<Self>) {
 828        let workspace = self.workspace.clone();
 829        let Some(active_repository) = self.active_repository.clone() else {
 830            return;
 831        };
 832
 833        let op_id = self.pending.iter().map(|p| p.op_id).max().unwrap_or(0) + 1;
 834        self.pending.push(PendingOperation {
 835            op_id,
 836            target_status: TargetStatus::Reverted,
 837            repo_paths: repo_paths.iter().cloned().collect(),
 838            finished: false,
 839        });
 840        self.update_visible_entries(cx);
 841        let task = cx.spawn(|_, mut cx| async move {
 842            let tasks: Vec<_> = workspace.update(&mut cx, |workspace, cx| {
 843                workspace.project().update(cx, |project, cx| {
 844                    repo_paths
 845                        .iter()
 846                        .filter_map(|repo_path| {
 847                            let path = active_repository
 848                                .read(cx)
 849                                .repo_path_to_project_path(&repo_path)?;
 850                            Some(project.open_buffer(path, cx))
 851                        })
 852                        .collect()
 853                })
 854            })?;
 855
 856            let buffers = futures::future::join_all(tasks).await;
 857
 858            active_repository
 859                .update(&mut cx, |repo, _| repo.checkout_files("HEAD", repo_paths))?
 860                .await??;
 861
 862            let tasks: Vec<_> = cx.update(|cx| {
 863                buffers
 864                    .iter()
 865                    .filter_map(|buffer| {
 866                        buffer.as_ref().ok()?.update(cx, |buffer, cx| {
 867                            buffer.is_dirty().then(|| buffer.reload(cx))
 868                        })
 869                    })
 870                    .collect()
 871            })?;
 872
 873            futures::future::join_all(tasks).await;
 874
 875            Ok(())
 876        });
 877
 878        cx.spawn(|this, mut cx| async move {
 879            let result = task.await;
 880
 881            this.update(&mut cx, |this, cx| {
 882                for pending in this.pending.iter_mut() {
 883                    if pending.op_id == op_id {
 884                        pending.finished = true;
 885                        if result.is_err() {
 886                            pending.target_status = TargetStatus::Unchanged;
 887                            this.update_visible_entries(cx);
 888                        }
 889                        break;
 890                    }
 891                }
 892                result
 893                    .map_err(|e| {
 894                        this.show_err_toast(e, cx);
 895                    })
 896                    .ok();
 897            })
 898            .ok();
 899        })
 900        .detach();
 901    }
 902
 903    fn restore_tracked_files(
 904        &mut self,
 905        _: &RestoreTrackedFiles,
 906        window: &mut Window,
 907        cx: &mut Context<Self>,
 908    ) {
 909        let entries = self
 910            .entries
 911            .iter()
 912            .filter_map(|entry| entry.status_entry().cloned())
 913            .filter(|status_entry| !status_entry.status.is_created())
 914            .collect::<Vec<_>>();
 915
 916        match entries.len() {
 917            0 => return,
 918            1 => return self.revert_entry(&entries[0], window, cx),
 919            _ => {}
 920        }
 921        let mut details = entries
 922            .iter()
 923            .filter_map(|entry| entry.repo_path.0.file_name())
 924            .map(|filename| filename.to_string_lossy())
 925            .take(5)
 926            .join("\n");
 927        if entries.len() > 5 {
 928            details.push_str(&format!("\nand {} more…", entries.len() - 5))
 929        }
 930
 931        #[derive(strum::EnumIter, strum::VariantNames)]
 932        #[strum(serialize_all = "title_case")]
 933        enum RestoreCancel {
 934            RestoreTrackedFiles,
 935            Cancel,
 936        }
 937        let prompt = prompt(
 938            "Discard changes to these files?",
 939            Some(&details),
 940            window,
 941            cx,
 942        );
 943        cx.spawn(|this, mut cx| async move {
 944            match prompt.await {
 945                Ok(RestoreCancel::RestoreTrackedFiles) => {
 946                    this.update(&mut cx, |this, cx| {
 947                        let repo_paths = entries.into_iter().map(|entry| entry.repo_path).collect();
 948                        this.perform_checkout(repo_paths, cx);
 949                    })
 950                    .ok();
 951                }
 952                _ => {
 953                    return;
 954                }
 955            }
 956        })
 957        .detach();
 958    }
 959
 960    fn clean_all(&mut self, _: &TrashUntrackedFiles, window: &mut Window, cx: &mut Context<Self>) {
 961        let workspace = self.workspace.clone();
 962        let Some(active_repo) = self.active_repository.clone() else {
 963            return;
 964        };
 965        let to_delete = self
 966            .entries
 967            .iter()
 968            .filter_map(|entry| entry.status_entry())
 969            .filter(|status_entry| status_entry.status.is_created())
 970            .cloned()
 971            .collect::<Vec<_>>();
 972
 973        match to_delete.len() {
 974            0 => return,
 975            1 => return self.revert_entry(&to_delete[0], window, cx),
 976            _ => {}
 977        };
 978
 979        let mut details = to_delete
 980            .iter()
 981            .map(|entry| {
 982                entry
 983                    .repo_path
 984                    .0
 985                    .file_name()
 986                    .map(|f| f.to_string_lossy())
 987                    .unwrap_or_default()
 988            })
 989            .take(5)
 990            .join("\n");
 991
 992        if to_delete.len() > 5 {
 993            details.push_str(&format!("\nand {} more…", to_delete.len() - 5))
 994        }
 995
 996        let prompt = prompt("Trash these files?", Some(&details), window, cx);
 997        cx.spawn_in(window, |this, mut cx| async move {
 998            match prompt.await? {
 999                TrashCancel::Trash => {}
1000                TrashCancel::Cancel => return Ok(()),
1001            }
1002            let tasks = workspace.update(&mut cx, |workspace, cx| {
1003                to_delete
1004                    .iter()
1005                    .filter_map(|entry| {
1006                        workspace.project().update(cx, |project, cx| {
1007                            let project_path = active_repo
1008                                .read(cx)
1009                                .repo_path_to_project_path(&entry.repo_path)?;
1010                            project.delete_file(project_path, true, cx)
1011                        })
1012                    })
1013                    .collect::<Vec<_>>()
1014            })?;
1015            let to_unstage = to_delete
1016                .into_iter()
1017                .filter_map(|entry| {
1018                    if entry.status.is_staged() != Some(false) {
1019                        Some(entry.repo_path.clone())
1020                    } else {
1021                        None
1022                    }
1023                })
1024                .collect();
1025            this.update(&mut cx, |this, cx| {
1026                this.perform_stage(false, to_unstage, cx)
1027            })?;
1028            for task in tasks {
1029                task.await?;
1030            }
1031            Ok(())
1032        })
1033        .detach_and_prompt_err("Failed to trash files", window, cx, |e, _, _| {
1034            Some(format!("{e}"))
1035        });
1036    }
1037
1038    fn stage_all(&mut self, _: &StageAll, _window: &mut Window, cx: &mut Context<Self>) {
1039        let repo_paths = self
1040            .entries
1041            .iter()
1042            .filter_map(|entry| entry.status_entry())
1043            .filter(|status_entry| status_entry.is_staged != Some(true))
1044            .map(|status_entry| status_entry.repo_path.clone())
1045            .collect::<Vec<_>>();
1046        self.perform_stage(true, repo_paths, cx);
1047    }
1048
1049    fn unstage_all(&mut self, _: &UnstageAll, _window: &mut Window, cx: &mut Context<Self>) {
1050        let repo_paths = self
1051            .entries
1052            .iter()
1053            .filter_map(|entry| entry.status_entry())
1054            .filter(|status_entry| status_entry.is_staged != Some(false))
1055            .map(|status_entry| status_entry.repo_path.clone())
1056            .collect::<Vec<_>>();
1057        self.perform_stage(false, repo_paths, cx);
1058    }
1059
1060    fn toggle_staged_for_entry(
1061        &mut self,
1062        entry: &GitListEntry,
1063        _window: &mut Window,
1064        cx: &mut Context<Self>,
1065    ) {
1066        let Some(active_repository) = self.active_repository.as_ref() else {
1067            return;
1068        };
1069        let (stage, repo_paths) = match entry {
1070            GitListEntry::GitStatusEntry(status_entry) => {
1071                if status_entry.status.is_staged().unwrap_or(false) {
1072                    (false, vec![status_entry.repo_path.clone()])
1073                } else {
1074                    (true, vec![status_entry.repo_path.clone()])
1075                }
1076            }
1077            GitListEntry::Header(section) => {
1078                let goal_staged_state = !self.header_state(section.header).selected();
1079                let repository = active_repository.read(cx);
1080                let entries = self
1081                    .entries
1082                    .iter()
1083                    .filter_map(|entry| entry.status_entry())
1084                    .filter(|status_entry| {
1085                        section.contains(&status_entry, repository)
1086                            && status_entry.is_staged != Some(goal_staged_state)
1087                    })
1088                    .map(|status_entry| status_entry.repo_path.clone())
1089                    .collect::<Vec<_>>();
1090
1091                (goal_staged_state, entries)
1092            }
1093        };
1094        self.perform_stage(stage, repo_paths, cx);
1095    }
1096
1097    fn perform_stage(&mut self, stage: bool, repo_paths: Vec<RepoPath>, cx: &mut Context<Self>) {
1098        let Some(active_repository) = self.active_repository.clone() else {
1099            return;
1100        };
1101        let op_id = self.pending.iter().map(|p| p.op_id).max().unwrap_or(0) + 1;
1102        self.pending.push(PendingOperation {
1103            op_id,
1104            target_status: if stage {
1105                TargetStatus::Staged
1106            } else {
1107                TargetStatus::Unstaged
1108            },
1109            repo_paths: repo_paths.iter().cloned().collect(),
1110            finished: false,
1111        });
1112        let repo_paths = repo_paths.clone();
1113        let repository = active_repository.read(cx);
1114        self.update_counts(repository);
1115        cx.notify();
1116
1117        cx.spawn({
1118            |this, mut cx| async move {
1119                let result = cx
1120                    .update(|cx| {
1121                        if stage {
1122                            active_repository
1123                                .update(cx, |repo, cx| repo.stage_entries(repo_paths.clone(), cx))
1124                        } else {
1125                            active_repository
1126                                .update(cx, |repo, cx| repo.unstage_entries(repo_paths.clone(), cx))
1127                        }
1128                    })?
1129                    .await;
1130
1131                this.update(&mut cx, |this, cx| {
1132                    for pending in this.pending.iter_mut() {
1133                        if pending.op_id == op_id {
1134                            pending.finished = true
1135                        }
1136                    }
1137                    result
1138                        .map_err(|e| {
1139                            this.show_err_toast(e, cx);
1140                        })
1141                        .ok();
1142                    cx.notify();
1143                })
1144            }
1145        })
1146        .detach();
1147    }
1148
1149    pub fn total_staged_count(&self) -> usize {
1150        self.tracked_staged_count + self.new_staged_count + self.conflicted_staged_count
1151    }
1152
1153    pub fn commit_message_buffer(&self, cx: &App) -> Entity<Buffer> {
1154        self.commit_editor
1155            .read(cx)
1156            .buffer()
1157            .read(cx)
1158            .as_singleton()
1159            .unwrap()
1160            .clone()
1161    }
1162
1163    fn toggle_staged_for_selected(
1164        &mut self,
1165        _: &git::ToggleStaged,
1166        window: &mut Window,
1167        cx: &mut Context<Self>,
1168    ) {
1169        if let Some(selected_entry) = self.get_selected_entry().cloned() {
1170            self.toggle_staged_for_entry(&selected_entry, window, cx);
1171        }
1172    }
1173
1174    fn commit(&mut self, _: &git::Commit, window: &mut Window, cx: &mut Context<Self>) {
1175        if self
1176            .commit_editor
1177            .focus_handle(cx)
1178            .contains_focused(window, cx)
1179        {
1180            telemetry::event!("Git Committed", source = "Git Panel");
1181            self.commit_changes(window, cx)
1182        } else {
1183            cx.propagate();
1184        }
1185    }
1186
1187    fn custom_or_suggested_commit_message(&self, cx: &mut Context<Self>) -> Option<String> {
1188        let message = self.commit_editor.read(cx).text(cx);
1189
1190        if !message.trim().is_empty() {
1191            return Some(message.to_string());
1192        }
1193
1194        self.suggest_commit_message()
1195            .filter(|message| !message.trim().is_empty())
1196    }
1197
1198    pub(crate) fn commit_changes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1199        let Some(active_repository) = self.active_repository.clone() else {
1200            return;
1201        };
1202        let error_spawn = |message, window: &mut Window, cx: &mut App| {
1203            let prompt = window.prompt(PromptLevel::Warning, message, None, &["Ok"], cx);
1204            cx.spawn(|_| async move {
1205                prompt.await.ok();
1206            })
1207            .detach();
1208        };
1209
1210        if self.has_unstaged_conflicts() {
1211            error_spawn(
1212                "There are still conflicts. You must stage these before committing",
1213                window,
1214                cx,
1215            );
1216            return;
1217        }
1218
1219        let commit_message = self.custom_or_suggested_commit_message(cx);
1220
1221        let Some(mut message) = commit_message else {
1222            self.commit_editor.read(cx).focus_handle(cx).focus(window);
1223            return;
1224        };
1225
1226        if self.add_coauthors {
1227            self.fill_co_authors(&mut message, cx);
1228        }
1229
1230        let task = if self.has_staged_changes() {
1231            // Repository serializes all git operations, so we can just send a commit immediately
1232            let commit_task = active_repository.read(cx).commit(message.into(), None);
1233            cx.background_spawn(async move { commit_task.await? })
1234        } else {
1235            let changed_files = self
1236                .entries
1237                .iter()
1238                .filter_map(|entry| entry.status_entry())
1239                .filter(|status_entry| !status_entry.status.is_created())
1240                .map(|status_entry| status_entry.repo_path.clone())
1241                .collect::<Vec<_>>();
1242
1243            if changed_files.is_empty() {
1244                error_spawn("No changes to commit", window, cx);
1245                return;
1246            }
1247
1248            let stage_task =
1249                active_repository.update(cx, |repo, cx| repo.stage_entries(changed_files, cx));
1250            cx.spawn(|_, mut cx| async move {
1251                stage_task.await?;
1252                let commit_task = active_repository
1253                    .update(&mut cx, |repo, _| repo.commit(message.into(), None))?;
1254                commit_task.await?
1255            })
1256        };
1257        let task = cx.spawn_in(window, |this, mut cx| async move {
1258            let result = task.await;
1259            this.update_in(&mut cx, |this, window, cx| {
1260                this.pending_commit.take();
1261                match result {
1262                    Ok(()) => {
1263                        this.commit_editor
1264                            .update(cx, |editor, cx| editor.clear(window, cx));
1265                    }
1266                    Err(e) => this.show_err_toast(e, cx),
1267                }
1268            })
1269            .ok();
1270        });
1271
1272        self.pending_commit = Some(task);
1273    }
1274
1275    fn uncommit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1276        let Some(repo) = self.active_repository.clone() else {
1277            return;
1278        };
1279        telemetry::event!("Git Uncommitted");
1280
1281        let confirmation = self.check_for_pushed_commits(window, cx);
1282        let prior_head = self.load_commit_details("HEAD", cx);
1283
1284        let task = cx.spawn_in(window, |this, mut cx| async move {
1285            let result = maybe!(async {
1286                if let Ok(true) = confirmation.await {
1287                    let prior_head = prior_head.await?;
1288
1289                    repo.update(&mut cx, |repo, _| repo.reset("HEAD^", ResetMode::Soft))?
1290                        .await??;
1291
1292                    Ok(Some(prior_head))
1293                } else {
1294                    Ok(None)
1295                }
1296            })
1297            .await;
1298
1299            this.update_in(&mut cx, |this, window, cx| {
1300                this.pending_commit.take();
1301                match result {
1302                    Ok(None) => {}
1303                    Ok(Some(prior_commit)) => {
1304                        this.commit_editor.update(cx, |editor, cx| {
1305                            editor.set_text(prior_commit.message, window, cx)
1306                        });
1307                    }
1308                    Err(e) => this.show_err_toast(e, cx),
1309                }
1310            })
1311            .ok();
1312        });
1313
1314        self.pending_commit = Some(task);
1315    }
1316
1317    fn check_for_pushed_commits(
1318        &mut self,
1319        window: &mut Window,
1320        cx: &mut Context<Self>,
1321    ) -> impl Future<Output = Result<bool, anyhow::Error>> {
1322        let repo = self.active_repository.clone();
1323        let mut cx = window.to_async(cx);
1324
1325        async move {
1326            let Some(repo) = repo else {
1327                return Err(anyhow::anyhow!("No active repository"));
1328            };
1329
1330            let pushed_to: Vec<SharedString> = repo
1331                .update(&mut cx, |repo, _| repo.check_for_pushed_commits())?
1332                .await??;
1333
1334            if pushed_to.is_empty() {
1335                Ok(true)
1336            } else {
1337                #[derive(strum::EnumIter, strum::VariantNames)]
1338                #[strum(serialize_all = "title_case")]
1339                enum CancelUncommit {
1340                    Uncommit,
1341                    Cancel,
1342                }
1343                let detail = format!(
1344                    "This commit was already pushed to {}.",
1345                    pushed_to.into_iter().join(", ")
1346                );
1347                let result = cx
1348                    .update(|window, cx| prompt("Are you sure?", Some(&detail), window, cx))?
1349                    .await?;
1350
1351                match result {
1352                    CancelUncommit::Cancel => Ok(false),
1353                    CancelUncommit::Uncommit => Ok(true),
1354                }
1355            }
1356        }
1357    }
1358
1359    /// Suggests a commit message based on the changed files and their statuses
1360    pub fn suggest_commit_message(&self) -> Option<String> {
1361        if self.total_staged_count() != 1 {
1362            return None;
1363        }
1364
1365        let entry = self
1366            .entries
1367            .iter()
1368            .find(|entry| match entry.status_entry() {
1369                Some(entry) => entry.is_staged.unwrap_or(false),
1370                _ => false,
1371            })?;
1372
1373        let GitListEntry::GitStatusEntry(git_status_entry) = entry.clone() else {
1374            return None;
1375        };
1376
1377        let action_text = if git_status_entry.status.is_deleted() {
1378            Some("Delete")
1379        } else if git_status_entry.status.is_created() {
1380            Some("Create")
1381        } else if git_status_entry.status.is_modified() {
1382            Some("Update")
1383        } else {
1384            None
1385        }?;
1386
1387        let file_name = git_status_entry
1388            .repo_path
1389            .file_name()
1390            .unwrap_or_default()
1391            .to_string_lossy();
1392
1393        Some(format!("{} {}", action_text, file_name))
1394    }
1395
1396    /// Generates a commit message using an LLM.
1397    fn generate_commit_message(&mut self, cx: &mut Context<Self>) {
1398        let Some(provider) = LanguageModelRegistry::read_global(cx).active_provider() else {
1399            return;
1400        };
1401        let Some(model) = LanguageModelRegistry::read_global(cx).active_model() else {
1402            return;
1403        };
1404
1405        if !provider.is_authenticated(cx) {
1406            return;
1407        }
1408
1409        const PROMPT: &str = include_str!("commit_message_prompt.txt");
1410
1411        // TODO: We need to generate a diff from the actual Git state.
1412        //
1413        // It need not look exactly like the structure below, this is just an example generated by Claude.
1414        let diff_text = "diff --git a/src/main.rs b/src/main.rs
1415index 1234567..abcdef0 100644
1416--- a/src/main.rs
1417+++ b/src/main.rs
1418@@ -10,7 +10,7 @@ fn main() {
1419     println!(\"Hello, world!\");
1420-    let unused_var = 42;
1421+    let important_value = 42;
1422
1423     // Do something with the value
1424-    // TODO: Implement this later
1425+    println!(\"The answer is {}\", important_value);
1426 }";
1427
1428        let request = LanguageModelRequest {
1429            messages: vec![LanguageModelRequestMessage {
1430                role: Role::User,
1431                content: vec![format!("{PROMPT}\n{diff_text}").into()],
1432                cache: false,
1433            }],
1434            tools: Vec::new(),
1435            stop: Vec::new(),
1436            temperature: None,
1437        };
1438
1439        self.generate_commit_message_task = Some(cx.spawn(|this, mut cx| {
1440            async move {
1441                let stream = model.stream_completion_text(request, &cx);
1442                let mut messages = stream.await?;
1443
1444                while let Some(message) = messages.stream.next().await {
1445                    let text = message?;
1446
1447                    this.update(&mut cx, |this, cx| {
1448                        this.commit_message_buffer(cx).update(cx, |buffer, cx| {
1449                            let insert_position = buffer.anchor_before(buffer.len());
1450                            buffer.edit([(insert_position..insert_position, text)], None, cx);
1451                        });
1452                    })?;
1453                }
1454
1455                anyhow::Ok(())
1456            }
1457            .log_err()
1458        }));
1459    }
1460
1461    fn update_editor_placeholder(&mut self, cx: &mut Context<Self>) {
1462        let suggested_commit_message = self.suggest_commit_message();
1463        let placeholder_text = suggested_commit_message
1464            .as_deref()
1465            .unwrap_or("Enter commit message");
1466
1467        self.commit_editor.update(cx, |editor, cx| {
1468            editor.set_placeholder_text(Arc::from(placeholder_text), cx)
1469        });
1470
1471        cx.notify();
1472    }
1473
1474    pub(crate) fn fetch(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1475        if !self.can_push_and_pull(cx) {
1476            return;
1477        }
1478
1479        let Some(repo) = self.active_repository.clone() else {
1480            return;
1481        };
1482        telemetry::event!("Git Fetched");
1483        let guard = self.start_remote_operation();
1484        let askpass = self.askpass_delegate("git fetch", window, cx);
1485        cx.spawn(|this, mut cx| async move {
1486            let fetch = repo.update(&mut cx, |repo, cx| repo.fetch(askpass, cx))?;
1487
1488            let remote_message = fetch.await?;
1489            drop(guard);
1490            this.update(&mut cx, |this, cx| {
1491                match remote_message {
1492                    Ok(remote_message) => {
1493                        this.show_remote_output(RemoteAction::Fetch, remote_message, cx);
1494                    }
1495                    Err(e) => {
1496                        this.show_err_toast(e, cx);
1497                    }
1498                }
1499
1500                anyhow::Ok(())
1501            })
1502            .ok();
1503            anyhow::Ok(())
1504        })
1505        .detach_and_log_err(cx);
1506    }
1507
1508    pub(crate) fn pull(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1509        if !self.can_push_and_pull(cx) {
1510            return;
1511        }
1512        let Some(repo) = self.active_repository.clone() else {
1513            return;
1514        };
1515        let Some(branch) = repo.read(cx).current_branch() else {
1516            return;
1517        };
1518        telemetry::event!("Git Pulled");
1519        let branch = branch.clone();
1520        let remote = self.get_current_remote(window, cx);
1521        cx.spawn_in(window, move |this, mut cx| async move {
1522            let remote = match remote.await {
1523                Ok(Some(remote)) => remote,
1524                Ok(None) => {
1525                    return Ok(());
1526                }
1527                Err(e) => {
1528                    log::error!("Failed to get current remote: {}", e);
1529                    this.update(&mut cx, |this, cx| this.show_err_toast(e, cx))
1530                        .ok();
1531                    return Ok(());
1532                }
1533            };
1534
1535            let askpass = this.update_in(&mut cx, |this, window, cx| {
1536                this.askpass_delegate(format!("git pull {}", remote.name), window, cx)
1537            })?;
1538
1539            let guard = this
1540                .update(&mut cx, |this, _| this.start_remote_operation())
1541                .ok();
1542
1543            let pull = repo.update(&mut cx, |repo, cx| {
1544                repo.pull(branch.name.clone(), remote.name.clone(), askpass, cx)
1545            })?;
1546
1547            let remote_message = pull.await?;
1548            drop(guard);
1549
1550            this.update(&mut cx, |this, cx| match remote_message {
1551                Ok(remote_message) => {
1552                    this.show_remote_output(RemoteAction::Pull, remote_message, cx)
1553                }
1554                Err(err) => this.show_err_toast(err, cx),
1555            })
1556            .ok();
1557
1558            anyhow::Ok(())
1559        })
1560        .detach_and_log_err(cx);
1561    }
1562
1563    pub(crate) fn push(&mut self, force_push: bool, window: &mut Window, cx: &mut Context<Self>) {
1564        if !self.can_push_and_pull(cx) {
1565            return;
1566        }
1567        let Some(repo) = self.active_repository.clone() else {
1568            return;
1569        };
1570        let Some(branch) = repo.read(cx).current_branch() else {
1571            return;
1572        };
1573        telemetry::event!("Git Pushed");
1574        let branch = branch.clone();
1575        let options = if force_push {
1576            PushOptions::Force
1577        } else {
1578            PushOptions::SetUpstream
1579        };
1580        let remote = self.get_current_remote(window, cx);
1581
1582        cx.spawn_in(window, move |this, mut cx| async move {
1583            let remote = match remote.await {
1584                Ok(Some(remote)) => remote,
1585                Ok(None) => {
1586                    return Ok(());
1587                }
1588                Err(e) => {
1589                    log::error!("Failed to get current remote: {}", e);
1590                    this.update(&mut cx, |this, cx| this.show_err_toast(e, cx))
1591                        .ok();
1592                    return Ok(());
1593                }
1594            };
1595
1596            let askpass_delegate = this.update_in(&mut cx, |this, window, cx| {
1597                this.askpass_delegate(format!("git push {}", remote.name), window, cx)
1598            })?;
1599
1600            let guard = this
1601                .update(&mut cx, |this, _| this.start_remote_operation())
1602                .ok();
1603
1604            let push = repo.update(&mut cx, |repo, cx| {
1605                repo.push(
1606                    branch.name.clone(),
1607                    remote.name.clone(),
1608                    Some(options),
1609                    askpass_delegate,
1610                    cx,
1611                )
1612            })?;
1613
1614            let remote_output = push.await?;
1615            drop(guard);
1616
1617            this.update(&mut cx, |this, cx| match remote_output {
1618                Ok(remote_message) => {
1619                    this.show_remote_output(RemoteAction::Push(remote), remote_message, cx);
1620                }
1621                Err(e) => {
1622                    this.show_err_toast(e, cx);
1623                }
1624            })?;
1625
1626            anyhow::Ok(())
1627        })
1628        .detach_and_log_err(cx);
1629    }
1630
1631    fn askpass_delegate(
1632        &self,
1633        operation: impl Into<SharedString>,
1634        window: &mut Window,
1635        cx: &mut Context<Self>,
1636    ) -> AskPassDelegate {
1637        let this = cx.weak_entity();
1638        let operation = operation.into();
1639        let window = window.window_handle();
1640        AskPassDelegate::new(&mut cx.to_async(), move |prompt, tx, cx| {
1641            window
1642                .update(cx, |_, window, cx| {
1643                    this.update(cx, |this, cx| {
1644                        this.workspace.update(cx, |workspace, cx| {
1645                            workspace.toggle_modal(window, cx, |window, cx| {
1646                                AskPassModal::new(operation.clone(), prompt.into(), tx, window, cx)
1647                            });
1648                        })
1649                    })
1650                })
1651                .ok();
1652        })
1653    }
1654
1655    fn can_push_and_pull(&self, cx: &App) -> bool {
1656        !self.project.read(cx).is_via_collab()
1657    }
1658
1659    fn get_current_remote(
1660        &mut self,
1661        window: &mut Window,
1662        cx: &mut Context<Self>,
1663    ) -> impl Future<Output = Result<Option<Remote>>> {
1664        let repo = self.active_repository.clone();
1665        let workspace = self.workspace.clone();
1666        let mut cx = window.to_async(cx);
1667
1668        async move {
1669            let Some(repo) = repo else {
1670                return Err(anyhow::anyhow!("No active repository"));
1671            };
1672
1673            let mut current_remotes: Vec<Remote> = repo
1674                .update(&mut cx, |repo, _| {
1675                    let Some(current_branch) = repo.current_branch() else {
1676                        return Err(anyhow::anyhow!("No active branch"));
1677                    };
1678
1679                    Ok(repo.get_remotes(Some(current_branch.name.to_string())))
1680                })??
1681                .await??;
1682
1683            if current_remotes.len() == 0 {
1684                return Err(anyhow::anyhow!("No active remote"));
1685            } else if current_remotes.len() == 1 {
1686                return Ok(Some(current_remotes.pop().unwrap()));
1687            } else {
1688                let current_remotes: Vec<_> = current_remotes
1689                    .into_iter()
1690                    .map(|remotes| remotes.name)
1691                    .collect();
1692                let selection = cx
1693                    .update(|window, cx| {
1694                        picker_prompt::prompt(
1695                            "Pick which remote to push to",
1696                            current_remotes.clone(),
1697                            workspace,
1698                            window,
1699                            cx,
1700                        )
1701                    })?
1702                    .await?;
1703
1704                Ok(selection.map(|selection| Remote {
1705                    name: current_remotes[selection].clone(),
1706                }))
1707            }
1708        }
1709    }
1710
1711    fn potential_co_authors(&self, cx: &App) -> Vec<(String, String)> {
1712        let mut new_co_authors = Vec::new();
1713        let project = self.project.read(cx);
1714
1715        let Some(room) = self
1716            .workspace
1717            .upgrade()
1718            .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned())
1719        else {
1720            return Vec::default();
1721        };
1722
1723        let room = room.read(cx);
1724
1725        for (peer_id, collaborator) in project.collaborators() {
1726            if collaborator.is_host {
1727                continue;
1728            }
1729
1730            let Some(participant) = room.remote_participant_for_peer_id(*peer_id) else {
1731                continue;
1732            };
1733            if participant.can_write() && participant.user.email.is_some() {
1734                let email = participant.user.email.clone().unwrap();
1735
1736                new_co_authors.push((
1737                    participant
1738                        .user
1739                        .name
1740                        .clone()
1741                        .unwrap_or_else(|| participant.user.github_login.clone()),
1742                    email,
1743                ))
1744            }
1745        }
1746        if !project.is_local() && !project.is_read_only(cx) {
1747            if let Some(user) = room.local_participant_user(cx) {
1748                if let Some(email) = user.email.clone() {
1749                    new_co_authors.push((
1750                        user.name
1751                            .clone()
1752                            .unwrap_or_else(|| user.github_login.clone()),
1753                        email.clone(),
1754                    ))
1755                }
1756            }
1757        }
1758        new_co_authors
1759    }
1760
1761    fn toggle_fill_co_authors(
1762        &mut self,
1763        _: &ToggleFillCoAuthors,
1764        _: &mut Window,
1765        cx: &mut Context<Self>,
1766    ) {
1767        self.add_coauthors = !self.add_coauthors;
1768        cx.notify();
1769    }
1770
1771    fn fill_co_authors(&mut self, message: &mut String, cx: &mut Context<Self>) {
1772        const CO_AUTHOR_PREFIX: &str = "Co-authored-by: ";
1773
1774        let existing_text = message.to_ascii_lowercase();
1775        let lowercase_co_author_prefix = CO_AUTHOR_PREFIX.to_lowercase();
1776        let mut ends_with_co_authors = false;
1777        let existing_co_authors = existing_text
1778            .lines()
1779            .filter_map(|line| {
1780                let line = line.trim();
1781                if line.starts_with(&lowercase_co_author_prefix) {
1782                    ends_with_co_authors = true;
1783                    Some(line)
1784                } else {
1785                    ends_with_co_authors = false;
1786                    None
1787                }
1788            })
1789            .collect::<HashSet<_>>();
1790
1791        let new_co_authors = self
1792            .potential_co_authors(cx)
1793            .into_iter()
1794            .filter(|(_, email)| {
1795                !existing_co_authors
1796                    .iter()
1797                    .any(|existing| existing.contains(email.as_str()))
1798            })
1799            .collect::<Vec<_>>();
1800
1801        if new_co_authors.is_empty() {
1802            return;
1803        }
1804
1805        if !ends_with_co_authors {
1806            message.push('\n');
1807        }
1808        for (name, email) in new_co_authors {
1809            message.push('\n');
1810            message.push_str(CO_AUTHOR_PREFIX);
1811            message.push_str(&name);
1812            message.push_str(" <");
1813            message.push_str(&email);
1814            message.push('>');
1815        }
1816        message.push('\n');
1817    }
1818
1819    fn schedule_update(
1820        &mut self,
1821        clear_pending: bool,
1822        window: &mut Window,
1823        cx: &mut Context<Self>,
1824    ) {
1825        let handle = cx.entity().downgrade();
1826        self.reopen_commit_buffer(window, cx);
1827        self.update_visible_entries_task = cx.spawn_in(window, |_, mut cx| async move {
1828            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
1829            if let Some(git_panel) = handle.upgrade() {
1830                git_panel
1831                    .update_in(&mut cx, |git_panel, _, cx| {
1832                        if clear_pending {
1833                            git_panel.clear_pending();
1834                        }
1835                        git_panel.update_visible_entries(cx);
1836                        git_panel.update_editor_placeholder(cx);
1837                    })
1838                    .ok();
1839            }
1840        });
1841    }
1842
1843    fn reopen_commit_buffer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1844        let Some(active_repo) = self.active_repository.as_ref() else {
1845            return;
1846        };
1847        let load_buffer = active_repo.update(cx, |active_repo, cx| {
1848            let project = self.project.read(cx);
1849            active_repo.open_commit_buffer(
1850                Some(project.languages().clone()),
1851                project.buffer_store().clone(),
1852                cx,
1853            )
1854        });
1855
1856        cx.spawn_in(window, |git_panel, mut cx| async move {
1857            let buffer = load_buffer.await?;
1858            git_panel.update_in(&mut cx, |git_panel, window, cx| {
1859                if git_panel
1860                    .commit_editor
1861                    .read(cx)
1862                    .buffer()
1863                    .read(cx)
1864                    .as_singleton()
1865                    .as_ref()
1866                    != Some(&buffer)
1867                {
1868                    git_panel.commit_editor = cx.new(|cx| {
1869                        commit_message_editor(
1870                            buffer,
1871                            git_panel.suggest_commit_message().as_deref(),
1872                            git_panel.project.clone(),
1873                            true,
1874                            window,
1875                            cx,
1876                        )
1877                    });
1878                }
1879            })
1880        })
1881        .detach_and_log_err(cx);
1882    }
1883
1884    fn clear_pending(&mut self) {
1885        self.pending.retain(|v| !v.finished)
1886    }
1887
1888    fn update_visible_entries(&mut self, cx: &mut Context<Self>) {
1889        self.entries.clear();
1890        let mut changed_entries = Vec::new();
1891        let mut new_entries = Vec::new();
1892        let mut conflict_entries = Vec::new();
1893
1894        let Some(repo) = self.active_repository.as_ref() else {
1895            // Just clear entries if no repository is active.
1896            cx.notify();
1897            return;
1898        };
1899
1900        // First pass - collect all paths
1901        let repo = repo.read(cx);
1902
1903        // Second pass - create entries with proper depth calculation
1904        for entry in repo.status() {
1905            let is_conflict = repo.has_conflict(&entry.repo_path);
1906            let is_new = entry.status.is_created();
1907            let is_staged = entry.status.is_staged();
1908
1909            if self.pending.iter().any(|pending| {
1910                pending.target_status == TargetStatus::Reverted
1911                    && !pending.finished
1912                    && pending.repo_paths.contains(&entry.repo_path)
1913            }) {
1914                continue;
1915            }
1916
1917            let entry = GitStatusEntry {
1918                repo_path: entry.repo_path.clone(),
1919                status: entry.status,
1920                is_staged,
1921            };
1922
1923            if is_conflict {
1924                conflict_entries.push(entry);
1925            } else if is_new {
1926                new_entries.push(entry);
1927            } else {
1928                changed_entries.push(entry);
1929            }
1930        }
1931
1932        if conflict_entries.len() > 0 {
1933            self.entries.push(GitListEntry::Header(GitHeaderEntry {
1934                header: Section::Conflict,
1935            }));
1936            self.entries.extend(
1937                conflict_entries
1938                    .into_iter()
1939                    .map(GitListEntry::GitStatusEntry),
1940            );
1941        }
1942
1943        if changed_entries.len() > 0 {
1944            self.entries.push(GitListEntry::Header(GitHeaderEntry {
1945                header: Section::Tracked,
1946            }));
1947            self.entries.extend(
1948                changed_entries
1949                    .into_iter()
1950                    .map(GitListEntry::GitStatusEntry),
1951            );
1952        }
1953        if new_entries.len() > 0 {
1954            self.entries.push(GitListEntry::Header(GitHeaderEntry {
1955                header: Section::New,
1956            }));
1957            self.entries
1958                .extend(new_entries.into_iter().map(GitListEntry::GitStatusEntry));
1959        }
1960
1961        self.update_counts(repo);
1962
1963        self.select_first_entry_if_none(cx);
1964
1965        cx.notify();
1966    }
1967
1968    fn header_state(&self, header_type: Section) -> ToggleState {
1969        let (staged_count, count) = match header_type {
1970            Section::New => (self.new_staged_count, self.new_count),
1971            Section::Tracked => (self.tracked_staged_count, self.tracked_count),
1972            Section::Conflict => (self.conflicted_staged_count, self.conflicted_count),
1973        };
1974        if staged_count == 0 {
1975            ToggleState::Unselected
1976        } else if count == staged_count {
1977            ToggleState::Selected
1978        } else {
1979            ToggleState::Indeterminate
1980        }
1981    }
1982
1983    fn update_counts(&mut self, repo: &Repository) {
1984        self.conflicted_count = 0;
1985        self.conflicted_staged_count = 0;
1986        self.new_count = 0;
1987        self.tracked_count = 0;
1988        self.new_staged_count = 0;
1989        self.tracked_staged_count = 0;
1990        for entry in &self.entries {
1991            let Some(status_entry) = entry.status_entry() else {
1992                continue;
1993            };
1994            if repo.has_conflict(&status_entry.repo_path) {
1995                self.conflicted_count += 1;
1996                if self.entry_is_staged(status_entry) != Some(false) {
1997                    self.conflicted_staged_count += 1;
1998                }
1999            } else if status_entry.status.is_created() {
2000                self.new_count += 1;
2001                if self.entry_is_staged(status_entry) != Some(false) {
2002                    self.new_staged_count += 1;
2003                }
2004            } else {
2005                self.tracked_count += 1;
2006                if self.entry_is_staged(status_entry) != Some(false) {
2007                    self.tracked_staged_count += 1;
2008                }
2009            }
2010        }
2011    }
2012
2013    fn entry_is_staged(&self, entry: &GitStatusEntry) -> Option<bool> {
2014        for pending in self.pending.iter().rev() {
2015            if pending.repo_paths.contains(&entry.repo_path) {
2016                match pending.target_status {
2017                    TargetStatus::Staged => return Some(true),
2018                    TargetStatus::Unstaged => return Some(false),
2019                    TargetStatus::Reverted => continue,
2020                    TargetStatus::Unchanged => continue,
2021                }
2022            }
2023        }
2024        entry.is_staged
2025    }
2026
2027    pub(crate) fn has_staged_changes(&self) -> bool {
2028        self.tracked_staged_count > 0
2029            || self.new_staged_count > 0
2030            || self.conflicted_staged_count > 0
2031    }
2032
2033    pub(crate) fn has_unstaged_changes(&self) -> bool {
2034        self.tracked_count > self.tracked_staged_count
2035            || self.new_count > self.new_staged_count
2036            || self.conflicted_count > self.conflicted_staged_count
2037    }
2038
2039    fn has_conflicts(&self) -> bool {
2040        self.conflicted_count > 0
2041    }
2042
2043    fn has_tracked_changes(&self) -> bool {
2044        self.tracked_count > 0
2045    }
2046
2047    pub fn has_unstaged_conflicts(&self) -> bool {
2048        self.conflicted_count > 0 && self.conflicted_count != self.conflicted_staged_count
2049    }
2050
2051    fn show_err_toast(&self, e: anyhow::Error, cx: &mut App) {
2052        let Some(workspace) = self.workspace.upgrade() else {
2053            return;
2054        };
2055        let notif_id = NotificationId::Named("git-operation-error".into());
2056
2057        let message = e.to_string().trim().to_string();
2058        let toast;
2059        if message
2060            .matches(git::repository::REMOTE_CANCELLED_BY_USER)
2061            .next()
2062            .is_some()
2063        {
2064            return; // Hide the cancelled by user message
2065        } else {
2066            toast = Toast::new(notif_id, message).on_click("Open Zed Log", |window, cx| {
2067                window.dispatch_action(workspace::OpenLog.boxed_clone(), cx);
2068            });
2069        }
2070        workspace.update(cx, |workspace, cx| {
2071            workspace.show_toast(toast, cx);
2072        });
2073    }
2074
2075    fn show_remote_output(&self, action: RemoteAction, info: RemoteCommandOutput, cx: &mut App) {
2076        let Some(workspace) = self.workspace.upgrade() else {
2077            return;
2078        };
2079
2080        let notification_id = NotificationId::Named("git-remote-info".into());
2081
2082        workspace.update(cx, |workspace, cx| {
2083            workspace.show_notification(notification_id.clone(), cx, |cx| {
2084                let workspace = cx.weak_entity();
2085                cx.new(|cx| RemoteOutputToast::new(action, info, notification_id, workspace, cx))
2086            });
2087        });
2088    }
2089
2090    pub fn render_spinner(&self) -> Option<impl IntoElement> {
2091        (!self.pending_remote_operations.borrow().is_empty()).then(|| {
2092            Icon::new(IconName::ArrowCircle)
2093                .size(IconSize::XSmall)
2094                .color(Color::Info)
2095                .with_animation(
2096                    "arrow-circle",
2097                    Animation::new(Duration::from_secs(2)).repeat(),
2098                    |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
2099                )
2100                .into_any_element()
2101        })
2102    }
2103
2104    pub fn can_commit(&self) -> bool {
2105        (self.has_staged_changes() || self.has_tracked_changes()) && !self.has_unstaged_conflicts()
2106    }
2107
2108    pub fn can_stage_all(&self) -> bool {
2109        self.has_unstaged_changes()
2110    }
2111
2112    pub fn can_unstage_all(&self) -> bool {
2113        self.has_staged_changes()
2114    }
2115
2116    pub(crate) fn render_co_authors(&self, cx: &Context<Self>) -> Option<AnyElement> {
2117        let potential_co_authors = self.potential_co_authors(cx);
2118        if potential_co_authors.is_empty() {
2119            None
2120        } else {
2121            Some(
2122                IconButton::new("co-authors", IconName::Person)
2123                    .icon_color(Color::Disabled)
2124                    .selected_icon_color(Color::Selected)
2125                    .toggle_state(self.add_coauthors)
2126                    .tooltip(move |_, cx| {
2127                        let title = format!(
2128                            "Add co-authored-by:{}{}",
2129                            if potential_co_authors.len() == 1 {
2130                                ""
2131                            } else {
2132                                "\n"
2133                            },
2134                            potential_co_authors
2135                                .iter()
2136                                .map(|(name, email)| format!(" {} <{}>", name, email))
2137                                .join("\n")
2138                        );
2139                        Tooltip::simple(title, cx)
2140                    })
2141                    .on_click(cx.listener(|this, _, _, cx| {
2142                        this.add_coauthors = !this.add_coauthors;
2143                        cx.notify();
2144                    }))
2145                    .into_any_element(),
2146            )
2147        }
2148    }
2149
2150    pub fn configure_commit_button(&self, cx: &mut Context<Self>) -> (bool, &'static str) {
2151        if self.has_unstaged_conflicts() {
2152            (false, "You must resolve conflicts before committing")
2153        } else if !self.has_staged_changes() && !self.has_tracked_changes() {
2154            (
2155                false,
2156                "You must have either staged changes or tracked files to commit",
2157            )
2158        } else if self.pending_commit.is_some() {
2159            (false, "Commit in progress")
2160        } else if self.custom_or_suggested_commit_message(cx).is_none() {
2161            (false, "No commit message")
2162        } else if !self.has_write_access(cx) {
2163            (false, "You do not have write access to this project")
2164        } else {
2165            (true, self.commit_button_title())
2166        }
2167    }
2168
2169    pub fn commit_button_title(&self) -> &'static str {
2170        if self.has_staged_changes() {
2171            "Commit"
2172        } else {
2173            "Commit Tracked"
2174        }
2175    }
2176
2177    fn expand_commit_editor(
2178        &mut self,
2179        _: &git::ExpandCommitEditor,
2180        window: &mut Window,
2181        cx: &mut Context<Self>,
2182    ) {
2183        let workspace = self.workspace.clone();
2184        window.defer(cx, move |window, cx| {
2185            workspace
2186                .update(cx, |workspace, cx| {
2187                    CommitModal::toggle(workspace, window, cx)
2188                })
2189                .ok();
2190        })
2191    }
2192
2193    pub fn render_footer(
2194        &self,
2195        window: &mut Window,
2196        cx: &mut Context<Self>,
2197    ) -> Option<impl IntoElement> {
2198        let active_repository = self.active_repository.clone()?;
2199        let (can_commit, tooltip) = self.configure_commit_button(cx);
2200        let project = self.project.clone().read(cx);
2201        let panel_editor_style = panel_editor_style(true, window, cx);
2202
2203        let enable_coauthors = self.render_co_authors(cx);
2204        // Note: This is hard-coded to `false` as it is not fully implemented.
2205        let show_generate_commit_message_button = false;
2206
2207        let title = self.commit_button_title();
2208        let editor_focus_handle = self.commit_editor.focus_handle(cx);
2209
2210        let branch = active_repository.read(cx).current_branch().cloned();
2211
2212        let footer_size = px(32.);
2213        let gap = px(8.0);
2214
2215        let max_height = window.line_height() * 5. + gap + footer_size;
2216
2217        let expand_button_size = px(16.);
2218
2219        let git_panel = cx.entity().clone();
2220        let display_name = SharedString::from(Arc::from(
2221            active_repository
2222                .read(cx)
2223                .display_name(project, cx)
2224                .trim_end_matches("/"),
2225        ));
2226
2227        let footer = v_flex()
2228            .child(PanelRepoFooter::new(
2229                "footer-button",
2230                display_name,
2231                branch,
2232                Some(git_panel),
2233            ))
2234            .child(
2235                panel_editor_container(window, cx)
2236                    .id("commit-editor-container")
2237                    .relative()
2238                    .h(max_height)
2239                    // .w_full()
2240                    // .border_t_1()
2241                    // .border_color(cx.theme().colors().border)
2242                    .bg(cx.theme().colors().editor_background)
2243                    .cursor_text()
2244                    .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
2245                        window.focus(&this.commit_editor.focus_handle(cx));
2246                    }))
2247                    .child(
2248                        h_flex()
2249                            .id("commit-footer")
2250                            .absolute()
2251                            .bottom_0()
2252                            .right_2()
2253                            .gap_0p5()
2254                            .h(footer_size)
2255                            .flex_none()
2256                            .when(show_generate_commit_message_button, |parent| {
2257                                parent.child(
2258                                    panel_filled_button("Generate Commit Message").on_click(
2259                                        cx.listener(move |this, _event, _window, cx| {
2260                                            this.generate_commit_message(cx);
2261                                        }),
2262                                    ),
2263                                )
2264                            })
2265                            .children(enable_coauthors)
2266                            .child(
2267                                panel_filled_button(title)
2268                                    .tooltip(move |window, cx| {
2269                                        if can_commit {
2270                                            Tooltip::for_action_in(
2271                                                tooltip,
2272                                                &Commit,
2273                                                &editor_focus_handle,
2274                                                window,
2275                                                cx,
2276                                            )
2277                                        } else {
2278                                            Tooltip::simple(tooltip, cx)
2279                                        }
2280                                    })
2281                                    .disabled(!can_commit || self.modal_open)
2282                                    .on_click({
2283                                        cx.listener(move |this, _: &ClickEvent, window, cx| {
2284                                            telemetry::event!(
2285                                                "Git Committed",
2286                                                source = "Git Panel"
2287                                            );
2288                                            this.commit_changes(window, cx)
2289                                        })
2290                                    }),
2291                            ),
2292                    )
2293                    // .when(!self.modal_open, |el| {
2294                    .child(EditorElement::new(&self.commit_editor, panel_editor_style))
2295                    .child(
2296                        div()
2297                            .absolute()
2298                            .top_1()
2299                            .right_2()
2300                            .opacity(0.5)
2301                            .hover(|this| this.opacity(1.0))
2302                            .w(expand_button_size)
2303                            .child(
2304                                panel_icon_button("expand-commit-editor", IconName::Maximize)
2305                                    .icon_size(IconSize::Small)
2306                                    .style(ButtonStyle::Transparent)
2307                                    .width(expand_button_size.into())
2308                                    .on_click(cx.listener({
2309                                        move |_, _, window, cx| {
2310                                            window.dispatch_action(
2311                                                git::ExpandCommitEditor.boxed_clone(),
2312                                                cx,
2313                                            )
2314                                        }
2315                                    })),
2316                            ),
2317                    ),
2318            );
2319
2320        Some(footer)
2321    }
2322
2323    fn render_previous_commit(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
2324        let active_repository = self.active_repository.as_ref()?;
2325        let branch = active_repository.read(cx).current_branch()?;
2326        let commit = branch.most_recent_commit.as_ref()?.clone();
2327
2328        let this = cx.entity();
2329        Some(
2330            h_flex()
2331                .items_center()
2332                .py_2()
2333                .px(px(8.))
2334                // .bg(cx.theme().colors().background)
2335                // .border_t_1()
2336                .border_color(cx.theme().colors().border)
2337                .gap_1p5()
2338                .child(
2339                    div()
2340                        .flex_grow()
2341                        .overflow_hidden()
2342                        .max_w(relative(0.6))
2343                        .h_full()
2344                        .child(
2345                            Label::new(commit.subject.clone())
2346                                .size(LabelSize::Small)
2347                                .truncate(),
2348                        )
2349                        .id("commit-msg-hover")
2350                        .hoverable_tooltip(move |window, cx| {
2351                            GitPanelMessageTooltip::new(
2352                                this.clone(),
2353                                commit.sha.clone(),
2354                                window,
2355                                cx,
2356                            )
2357                            .into()
2358                        }),
2359                )
2360                .child(div().flex_1())
2361                .when(commit.has_parent, |this| {
2362                    let has_unstaged = self.has_unstaged_changes();
2363                    this.child(
2364                        panel_icon_button("undo", IconName::Undo)
2365                            .icon_size(IconSize::Small)
2366                            .icon_color(Color::Muted)
2367                            .tooltip(move |window, cx| {
2368                                Tooltip::with_meta(
2369                                    "Uncommit",
2370                                    Some(&git::Uncommit),
2371                                    if has_unstaged {
2372                                        "git reset HEAD^ --soft"
2373                                    } else {
2374                                        "git reset HEAD^"
2375                                    },
2376                                    window,
2377                                    cx,
2378                                )
2379                            })
2380                            .on_click(cx.listener(|this, _, window, cx| this.uncommit(window, cx))),
2381                    )
2382                }),
2383        )
2384    }
2385
2386    fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
2387        h_flex()
2388            .h_full()
2389            .flex_grow()
2390            .justify_center()
2391            .items_center()
2392            .child(
2393                v_flex()
2394                    .gap_3()
2395                    .child(if self.active_repository.is_some() {
2396                        "No changes to commit"
2397                    } else {
2398                        "No Git repositories"
2399                    })
2400                    .text_ui_sm(cx)
2401                    .mx_auto()
2402                    .text_color(Color::Placeholder.color(cx)),
2403            )
2404    }
2405
2406    fn render_scrollbar(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
2407        let scroll_bar_style = self.show_scrollbar(cx);
2408        let show_container = matches!(scroll_bar_style, ShowScrollbar::Always);
2409
2410        if !self.should_show_scrollbar(cx)
2411            || !(self.show_scrollbar || self.scrollbar_state.is_dragging())
2412        {
2413            return None;
2414        }
2415
2416        Some(
2417            div()
2418                .id("git-panel-vertical-scroll")
2419                .occlude()
2420                .flex_none()
2421                .h_full()
2422                .cursor_default()
2423                .when(show_container, |this| this.pl_1().px_1p5())
2424                .when(!show_container, |this| {
2425                    this.absolute().right_1().top_1().bottom_1().w(px(12.))
2426                })
2427                .on_mouse_move(cx.listener(|_, _, _, cx| {
2428                    cx.notify();
2429                    cx.stop_propagation()
2430                }))
2431                .on_hover(|_, _, cx| {
2432                    cx.stop_propagation();
2433                })
2434                .on_any_mouse_down(|_, _, cx| {
2435                    cx.stop_propagation();
2436                })
2437                .on_mouse_up(
2438                    MouseButton::Left,
2439                    cx.listener(|this, _, window, cx| {
2440                        if !this.scrollbar_state.is_dragging()
2441                            && !this.focus_handle.contains_focused(window, cx)
2442                        {
2443                            this.hide_scrollbar(window, cx);
2444                            cx.notify();
2445                        }
2446
2447                        cx.stop_propagation();
2448                    }),
2449                )
2450                .on_scroll_wheel(cx.listener(|_, _, _, cx| {
2451                    cx.notify();
2452                }))
2453                .children(Scrollbar::vertical(
2454                    // percentage as f32..end_offset as f32,
2455                    self.scrollbar_state.clone(),
2456                )),
2457        )
2458    }
2459
2460    fn render_buffer_header_controls(
2461        &self,
2462        entity: &Entity<Self>,
2463        file: &Arc<dyn File>,
2464        _: &Window,
2465        cx: &App,
2466    ) -> Option<AnyElement> {
2467        let repo = self.active_repository.as_ref()?.read(cx);
2468        let repo_path = repo.worktree_id_path_to_repo_path(file.worktree_id(cx), file.path())?;
2469        let ix = self.entry_by_path(&repo_path)?;
2470        let entry = self.entries.get(ix)?;
2471
2472        let is_staged = self.entry_is_staged(entry.status_entry()?);
2473
2474        let checkbox = Checkbox::new("stage-file", is_staged.into())
2475            .disabled(!self.has_write_access(cx))
2476            .fill()
2477            .elevation(ElevationIndex::Surface)
2478            .on_click({
2479                let entry = entry.clone();
2480                let git_panel = entity.downgrade();
2481                move |_, window, cx| {
2482                    git_panel
2483                        .update(cx, |this, cx| {
2484                            this.toggle_staged_for_entry(&entry, window, cx);
2485                            cx.stop_propagation();
2486                        })
2487                        .ok();
2488                }
2489            });
2490        Some(
2491            h_flex()
2492                .id("start-slot")
2493                .text_lg()
2494                .child(checkbox)
2495                .on_mouse_down(MouseButton::Left, |_, _, cx| {
2496                    // prevent the list item active state triggering when toggling checkbox
2497                    cx.stop_propagation();
2498                })
2499                .into_any_element(),
2500        )
2501    }
2502
2503    fn render_entries(
2504        &self,
2505        has_write_access: bool,
2506        _: &Window,
2507        cx: &mut Context<Self>,
2508    ) -> impl IntoElement {
2509        let entry_count = self.entries.len();
2510
2511        h_flex()
2512            .size_full()
2513            .flex_grow()
2514            .overflow_hidden()
2515            .child(
2516                uniform_list(cx.entity().clone(), "entries", entry_count, {
2517                    move |this, range, window, cx| {
2518                        let mut items = Vec::with_capacity(range.end - range.start);
2519
2520                        for ix in range {
2521                            match &this.entries.get(ix) {
2522                                Some(GitListEntry::GitStatusEntry(entry)) => {
2523                                    items.push(this.render_entry(
2524                                        ix,
2525                                        entry,
2526                                        has_write_access,
2527                                        window,
2528                                        cx,
2529                                    ));
2530                                }
2531                                Some(GitListEntry::Header(header)) => {
2532                                    items.push(this.render_list_header(
2533                                        ix,
2534                                        header,
2535                                        has_write_access,
2536                                        window,
2537                                        cx,
2538                                    ));
2539                                }
2540                                None => {}
2541                            }
2542                        }
2543
2544                        items
2545                    }
2546                })
2547                .size_full()
2548                .with_sizing_behavior(ListSizingBehavior::Auto)
2549                .with_horizontal_sizing_behavior(ListHorizontalSizingBehavior::Unconstrained)
2550                .track_scroll(self.scroll_handle.clone()),
2551            )
2552            .on_mouse_down(
2553                MouseButton::Right,
2554                cx.listener(move |this, event: &MouseDownEvent, window, cx| {
2555                    this.deploy_panel_context_menu(event.position, window, cx)
2556                }),
2557            )
2558            .children(self.render_scrollbar(cx))
2559    }
2560
2561    fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
2562        Label::new(label.into()).color(color).single_line()
2563    }
2564
2565    fn list_item_height(&self) -> Rems {
2566        rems(1.75)
2567    }
2568
2569    fn render_list_header(
2570        &self,
2571        ix: usize,
2572        header: &GitHeaderEntry,
2573        _: bool,
2574        _: &Window,
2575        _: &Context<Self>,
2576    ) -> AnyElement {
2577        let id: ElementId = ElementId::Name(format!("header_{}", ix).into());
2578
2579        h_flex()
2580            .id(id)
2581            .h(self.list_item_height())
2582            .w_full()
2583            .items_end()
2584            .px(rems(0.75)) // ~12px
2585            .pb(rems(0.3125)) // ~ 5px
2586            .child(
2587                Label::new(header.title())
2588                    .color(Color::Muted)
2589                    .size(LabelSize::Small)
2590                    .line_height_style(LineHeightStyle::UiLabel)
2591                    .single_line(),
2592            )
2593            .into_any_element()
2594    }
2595
2596    fn load_commit_details(
2597        &self,
2598        sha: &str,
2599        cx: &mut Context<Self>,
2600    ) -> Task<Result<CommitDetails>> {
2601        let Some(repo) = self.active_repository.clone() else {
2602            return Task::ready(Err(anyhow::anyhow!("no active repo")));
2603        };
2604        repo.update(cx, |repo, cx| {
2605            let show = repo.show(sha);
2606            cx.spawn(|_, _| async move { show.await? })
2607        })
2608    }
2609
2610    fn deploy_entry_context_menu(
2611        &mut self,
2612        position: Point<Pixels>,
2613        ix: usize,
2614        window: &mut Window,
2615        cx: &mut Context<Self>,
2616    ) {
2617        let Some(entry) = self.entries.get(ix).and_then(|e| e.status_entry()) else {
2618            return;
2619        };
2620        let stage_title = if entry.status.is_staged() == Some(true) {
2621            "Unstage File"
2622        } else {
2623            "Stage File"
2624        };
2625        let restore_title = if entry.status.is_created() {
2626            "Trash File"
2627        } else {
2628            "Restore File"
2629        };
2630        let context_menu = ContextMenu::build(window, cx, |context_menu, _, _| {
2631            context_menu
2632                .action(stage_title, ToggleStaged.boxed_clone())
2633                .action(restore_title, git::RestoreFile.boxed_clone())
2634                .separator()
2635                .action("Open Diff", Confirm.boxed_clone())
2636                .action("Open File", SecondaryConfirm.boxed_clone())
2637        });
2638        self.selected_entry = Some(ix);
2639        self.set_context_menu(context_menu, position, window, cx);
2640    }
2641
2642    fn deploy_panel_context_menu(
2643        &mut self,
2644        position: Point<Pixels>,
2645        window: &mut Window,
2646        cx: &mut Context<Self>,
2647    ) {
2648        let context_menu = git_panel_context_menu(window, cx);
2649        self.set_context_menu(context_menu, position, window, cx);
2650    }
2651
2652    fn set_context_menu(
2653        &mut self,
2654        context_menu: Entity<ContextMenu>,
2655        position: Point<Pixels>,
2656        window: &Window,
2657        cx: &mut Context<Self>,
2658    ) {
2659        let subscription = cx.subscribe_in(
2660            &context_menu,
2661            window,
2662            |this, _, _: &DismissEvent, window, cx| {
2663                if this.context_menu.as_ref().is_some_and(|context_menu| {
2664                    context_menu.0.focus_handle(cx).contains_focused(window, cx)
2665                }) {
2666                    cx.focus_self(window);
2667                }
2668                this.context_menu.take();
2669                cx.notify();
2670            },
2671        );
2672        self.context_menu = Some((context_menu, position, subscription));
2673        cx.notify();
2674    }
2675
2676    fn render_entry(
2677        &self,
2678        ix: usize,
2679        entry: &GitStatusEntry,
2680        has_write_access: bool,
2681        window: &Window,
2682        cx: &Context<Self>,
2683    ) -> AnyElement {
2684        let display_name = entry
2685            .repo_path
2686            .file_name()
2687            .map(|name| name.to_string_lossy().into_owned())
2688            .unwrap_or_else(|| entry.repo_path.to_string_lossy().into_owned());
2689
2690        let repo_path = entry.repo_path.clone();
2691        let selected = self.selected_entry == Some(ix);
2692        let marked = self.marked_entries.contains(&ix);
2693        let status_style = GitPanelSettings::get_global(cx).status_style;
2694        let status = entry.status;
2695        let has_conflict = status.is_conflicted();
2696        let is_modified = status.is_modified();
2697        let is_deleted = status.is_deleted();
2698
2699        let label_color = if status_style == StatusStyle::LabelColor {
2700            if has_conflict {
2701                Color::Conflict
2702            } else if is_modified {
2703                Color::Modified
2704            } else if is_deleted {
2705                // We don't want a bunch of red labels in the list
2706                Color::Disabled
2707            } else {
2708                Color::Created
2709            }
2710        } else {
2711            Color::Default
2712        };
2713
2714        let path_color = if status.is_deleted() {
2715            Color::Disabled
2716        } else {
2717            Color::Muted
2718        };
2719
2720        let id: ElementId = ElementId::Name(format!("entry_{}_{}", display_name, ix).into());
2721        let checkbox_wrapper_id: ElementId =
2722            ElementId::Name(format!("entry_{}_{}_checkbox_wrapper", display_name, ix).into());
2723        let checkbox_id: ElementId =
2724            ElementId::Name(format!("entry_{}_{}_checkbox", display_name, ix).into());
2725
2726        let is_entry_staged = self.entry_is_staged(entry);
2727        let mut is_staged: ToggleState = self.entry_is_staged(entry).into();
2728
2729        if !self.has_staged_changes() && !self.has_conflicts() && !entry.status.is_created() {
2730            is_staged = ToggleState::Selected;
2731        }
2732
2733        let handle = cx.weak_entity();
2734
2735        let selected_bg_alpha = 0.08;
2736        let marked_bg_alpha = 0.12;
2737        let state_opacity_step = 0.04;
2738
2739        let base_bg = match (selected, marked) {
2740            (true, true) => cx
2741                .theme()
2742                .status()
2743                .info
2744                .alpha(selected_bg_alpha + marked_bg_alpha),
2745            (true, false) => cx.theme().status().info.alpha(selected_bg_alpha),
2746            (false, true) => cx.theme().status().info.alpha(marked_bg_alpha),
2747            _ => cx.theme().colors().ghost_element_background,
2748        };
2749
2750        let hover_bg = if selected {
2751            cx.theme()
2752                .status()
2753                .info
2754                .alpha(selected_bg_alpha + state_opacity_step)
2755        } else {
2756            cx.theme().colors().ghost_element_hover
2757        };
2758
2759        let active_bg = if selected {
2760            cx.theme()
2761                .status()
2762                .info
2763                .alpha(selected_bg_alpha + state_opacity_step * 2.0)
2764        } else {
2765            cx.theme().colors().ghost_element_active
2766        };
2767
2768        h_flex()
2769            .id(id)
2770            .h(self.list_item_height())
2771            .w_full()
2772            .items_center()
2773            .border_1()
2774            .when(selected && self.focus_handle.is_focused(window), |el| {
2775                el.border_color(cx.theme().colors().border_focused)
2776            })
2777            .px(rems(0.75)) // ~12px
2778            .overflow_hidden()
2779            .flex_none()
2780            .gap(DynamicSpacing::Base04.rems(cx))
2781            .bg(base_bg)
2782            .hover(|this| this.bg(hover_bg))
2783            .active(|this| this.bg(active_bg))
2784            .on_click({
2785                cx.listener(move |this, event: &ClickEvent, window, cx| {
2786                    this.selected_entry = Some(ix);
2787                    cx.notify();
2788                    if event.modifiers().secondary() {
2789                        this.open_file(&Default::default(), window, cx)
2790                    } else {
2791                        this.open_diff(&Default::default(), window, cx);
2792                        this.focus_handle.focus(window);
2793                    }
2794                })
2795            })
2796            .on_mouse_down(
2797                MouseButton::Right,
2798                move |event: &MouseDownEvent, window, cx| {
2799                    // why isn't this happening automatically? we are passing MouseButton::Right to `on_mouse_down`?
2800                    if event.button != MouseButton::Right {
2801                        return;
2802                    }
2803
2804                    let Some(this) = handle.upgrade() else {
2805                        return;
2806                    };
2807                    this.update(cx, |this, cx| {
2808                        this.deploy_entry_context_menu(event.position, ix, window, cx);
2809                    });
2810                    cx.stop_propagation();
2811                },
2812            )
2813            // .on_secondary_mouse_down(cx.listener(
2814            //     move |this, event: &MouseDownEvent, window, cx| {
2815            //         this.deploy_entry_context_menu(event.position, ix, window, cx);
2816            //         cx.stop_propagation();
2817            //     },
2818            // ))
2819            .child(
2820                div()
2821                    .id(checkbox_wrapper_id)
2822                    .flex_none()
2823                    .occlude()
2824                    .cursor_pointer()
2825                    .child(
2826                        Checkbox::new(checkbox_id, is_staged)
2827                            .disabled(!has_write_access)
2828                            .fill()
2829                            .placeholder(!self.has_staged_changes() && !self.has_conflicts())
2830                            .elevation(ElevationIndex::Surface)
2831                            .on_click({
2832                                let entry = entry.clone();
2833                                cx.listener(move |this, _, window, cx| {
2834                                    if !has_write_access {
2835                                        return;
2836                                    }
2837                                    this.toggle_staged_for_entry(
2838                                        &GitListEntry::GitStatusEntry(entry.clone()),
2839                                        window,
2840                                        cx,
2841                                    );
2842                                    cx.stop_propagation();
2843                                })
2844                            })
2845                            .tooltip(move |window, cx| {
2846                                let tooltip_name = if is_entry_staged.unwrap_or(false) {
2847                                    "Unstage"
2848                                } else {
2849                                    "Stage"
2850                                };
2851
2852                                Tooltip::for_action(tooltip_name, &ToggleStaged, window, cx)
2853                            }),
2854                    ),
2855            )
2856            .child(git_status_icon(status, cx))
2857            .child(
2858                h_flex()
2859                    .items_center()
2860                    .overflow_hidden()
2861                    .when_some(repo_path.parent(), |this, parent| {
2862                        let parent_str = parent.to_string_lossy();
2863                        if !parent_str.is_empty() {
2864                            this.child(
2865                                self.entry_label(format!("{}/", parent_str), path_color)
2866                                    .when(status.is_deleted(), |this| this.strikethrough()),
2867                            )
2868                        } else {
2869                            this
2870                        }
2871                    })
2872                    .child(
2873                        self.entry_label(display_name.clone(), label_color)
2874                            .when(status.is_deleted(), |this| this.strikethrough()),
2875                    ),
2876            )
2877            .into_any_element()
2878    }
2879
2880    fn has_write_access(&self, cx: &App) -> bool {
2881        !self.project.read(cx).is_read_only(cx)
2882    }
2883}
2884
2885impl Render for GitPanel {
2886    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2887        let project = self.project.read(cx);
2888        let has_entries = self.entries.len() > 0;
2889        let room = self
2890            .workspace
2891            .upgrade()
2892            .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned());
2893
2894        let has_write_access = self.has_write_access(cx);
2895
2896        let has_co_authors = room.map_or(false, |room| {
2897            room.read(cx)
2898                .remote_participants()
2899                .values()
2900                .any(|remote_participant| remote_participant.can_write())
2901        });
2902
2903        v_flex()
2904            .id("git_panel")
2905            .key_context(self.dispatch_context(window, cx))
2906            .track_focus(&self.focus_handle)
2907            .on_modifiers_changed(cx.listener(Self::handle_modifiers_changed))
2908            .when(has_write_access && !project.is_read_only(cx), |this| {
2909                this.on_action(cx.listener(|this, &ToggleStaged, window, cx| {
2910                    this.toggle_staged_for_selected(&ToggleStaged, window, cx)
2911                }))
2912                .on_action(cx.listener(GitPanel::commit))
2913            })
2914            .on_action(cx.listener(Self::select_first))
2915            .on_action(cx.listener(Self::select_next))
2916            .on_action(cx.listener(Self::select_previous))
2917            .on_action(cx.listener(Self::select_last))
2918            .on_action(cx.listener(Self::close_panel))
2919            .on_action(cx.listener(Self::open_diff))
2920            .on_action(cx.listener(Self::open_file))
2921            .on_action(cx.listener(Self::revert_selected))
2922            .on_action(cx.listener(Self::focus_changes_list))
2923            .on_action(cx.listener(Self::focus_editor))
2924            .on_action(cx.listener(Self::toggle_staged_for_selected))
2925            .on_action(cx.listener(Self::stage_all))
2926            .on_action(cx.listener(Self::unstage_all))
2927            .on_action(cx.listener(Self::restore_tracked_files))
2928            .on_action(cx.listener(Self::clean_all))
2929            .on_action(cx.listener(Self::expand_commit_editor))
2930            .when(has_write_access && has_co_authors, |git_panel| {
2931                git_panel.on_action(cx.listener(Self::toggle_fill_co_authors))
2932            })
2933            // .on_action(cx.listener(|this, &OpenSelected, cx| this.open_selected(&OpenSelected, cx)))
2934            .on_hover(cx.listener(|this, hovered, window, cx| {
2935                if *hovered {
2936                    this.show_scrollbar = true;
2937                    this.hide_scrollbar_task.take();
2938                    cx.notify();
2939                } else if !this.focus_handle.contains_focused(window, cx) {
2940                    this.hide_scrollbar(window, cx);
2941                }
2942            }))
2943            .size_full()
2944            .overflow_hidden()
2945            .bg(ElevationIndex::Surface.bg(cx))
2946            .child(
2947                v_flex()
2948                    .size_full()
2949                    .map(|this| {
2950                        if has_entries {
2951                            this.child(self.render_entries(has_write_access, window, cx))
2952                        } else {
2953                            this.child(self.render_empty_state(cx).into_any_element())
2954                        }
2955                    })
2956                    .children(self.render_footer(window, cx))
2957                    .children(self.render_previous_commit(cx))
2958                    .into_any_element(),
2959            )
2960            .children(self.context_menu.as_ref().map(|(menu, position, _)| {
2961                deferred(
2962                    anchored()
2963                        .position(*position)
2964                        .anchor(gpui::Corner::TopLeft)
2965                        .child(menu.clone()),
2966                )
2967                .with_priority(1)
2968            }))
2969    }
2970}
2971
2972impl Focusable for GitPanel {
2973    fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
2974        self.focus_handle.clone()
2975    }
2976}
2977
2978impl EventEmitter<Event> for GitPanel {}
2979
2980impl EventEmitter<PanelEvent> for GitPanel {}
2981
2982pub(crate) struct GitPanelAddon {
2983    pub(crate) workspace: WeakEntity<Workspace>,
2984}
2985
2986impl editor::Addon for GitPanelAddon {
2987    fn to_any(&self) -> &dyn std::any::Any {
2988        self
2989    }
2990
2991    fn render_buffer_header_controls(
2992        &self,
2993        excerpt_info: &ExcerptInfo,
2994        window: &Window,
2995        cx: &App,
2996    ) -> Option<AnyElement> {
2997        let file = excerpt_info.buffer.file()?;
2998        let git_panel = self.workspace.upgrade()?.read(cx).panel::<GitPanel>(cx)?;
2999
3000        git_panel
3001            .read(cx)
3002            .render_buffer_header_controls(&git_panel, &file, window, cx)
3003    }
3004}
3005
3006impl Panel for GitPanel {
3007    fn persistent_name() -> &'static str {
3008        "GitPanel"
3009    }
3010
3011    fn position(&self, _: &Window, cx: &App) -> DockPosition {
3012        GitPanelSettings::get_global(cx).dock
3013    }
3014
3015    fn position_is_valid(&self, position: DockPosition) -> bool {
3016        matches!(position, DockPosition::Left | DockPosition::Right)
3017    }
3018
3019    fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
3020        settings::update_settings_file::<GitPanelSettings>(
3021            self.fs.clone(),
3022            cx,
3023            move |settings, _| settings.dock = Some(position),
3024        );
3025    }
3026
3027    fn size(&self, _: &Window, cx: &App) -> Pixels {
3028        self.width
3029            .unwrap_or_else(|| GitPanelSettings::get_global(cx).default_width)
3030    }
3031
3032    fn set_size(&mut self, size: Option<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
3033        self.width = size;
3034        self.serialize(cx);
3035        cx.notify();
3036    }
3037
3038    fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
3039        Some(ui::IconName::GitBranchSmall).filter(|_| GitPanelSettings::get_global(cx).button)
3040    }
3041
3042    fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
3043        Some("Git Panel")
3044    }
3045
3046    fn toggle_action(&self) -> Box<dyn Action> {
3047        Box::new(ToggleFocus)
3048    }
3049
3050    fn activation_priority(&self) -> u32 {
3051        2
3052    }
3053}
3054
3055impl PanelHeader for GitPanel {}
3056
3057struct GitPanelMessageTooltip {
3058    commit_tooltip: Option<Entity<CommitTooltip>>,
3059}
3060
3061impl GitPanelMessageTooltip {
3062    fn new(
3063        git_panel: Entity<GitPanel>,
3064        sha: SharedString,
3065        window: &mut Window,
3066        cx: &mut App,
3067    ) -> Entity<Self> {
3068        cx.new(|cx| {
3069            cx.spawn_in(window, |this, mut cx| async move {
3070                let details = git_panel
3071                    .update(&mut cx, |git_panel, cx| {
3072                        git_panel.load_commit_details(&sha, cx)
3073                    })?
3074                    .await?;
3075
3076                let commit_details = editor::commit_tooltip::CommitDetails {
3077                    sha: details.sha.clone(),
3078                    committer_name: details.committer_name.clone(),
3079                    committer_email: details.committer_email.clone(),
3080                    commit_time: OffsetDateTime::from_unix_timestamp(details.commit_timestamp)?,
3081                    message: Some(editor::commit_tooltip::ParsedCommitMessage {
3082                        message: details.message.clone(),
3083                        ..Default::default()
3084                    }),
3085                };
3086
3087                this.update_in(&mut cx, |this: &mut GitPanelMessageTooltip, window, cx| {
3088                    this.commit_tooltip =
3089                        Some(cx.new(move |cx| CommitTooltip::new(commit_details, window, cx)));
3090                    cx.notify();
3091                })
3092            })
3093            .detach();
3094
3095            Self {
3096                commit_tooltip: None,
3097            }
3098        })
3099    }
3100}
3101
3102impl Render for GitPanelMessageTooltip {
3103    fn render(&mut self, _window: &mut Window, _cx: &mut Context<'_, Self>) -> impl IntoElement {
3104        if let Some(commit_tooltip) = &self.commit_tooltip {
3105            commit_tooltip.clone().into_any_element()
3106        } else {
3107            gpui::Empty.into_any_element()
3108        }
3109    }
3110}
3111
3112fn git_action_tooltip(
3113    label: impl Into<SharedString>,
3114    action: &dyn Action,
3115    command: impl Into<SharedString>,
3116    focus_handle: Option<FocusHandle>,
3117    window: &mut Window,
3118    cx: &mut App,
3119) -> AnyView {
3120    let label = label.into();
3121    let command = command.into();
3122
3123    if let Some(handle) = focus_handle {
3124        Tooltip::with_meta_in(
3125            label.clone(),
3126            Some(action),
3127            command.clone(),
3128            &handle,
3129            window,
3130            cx,
3131        )
3132    } else {
3133        Tooltip::with_meta(label.clone(), Some(action), command.clone(), window, cx)
3134    }
3135}
3136
3137#[derive(IntoElement)]
3138struct SplitButton {
3139    pub left: ButtonLike,
3140    pub right: AnyElement,
3141}
3142
3143impl SplitButton {
3144    fn new(
3145        id: impl Into<SharedString>,
3146        left_label: impl Into<SharedString>,
3147        ahead_count: usize,
3148        behind_count: usize,
3149        left_icon: Option<IconName>,
3150        left_on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
3151        tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
3152    ) -> Self {
3153        let id = id.into();
3154
3155        fn count(count: usize) -> impl IntoElement {
3156            h_flex()
3157                .ml_neg_px()
3158                .h(rems(0.875))
3159                .items_center()
3160                .overflow_hidden()
3161                .px_0p5()
3162                .child(
3163                    Label::new(count.to_string())
3164                        .size(LabelSize::XSmall)
3165                        .line_height_style(LineHeightStyle::UiLabel),
3166                )
3167        }
3168
3169        let should_render_counts = left_icon.is_none() && (ahead_count > 0 || behind_count > 0);
3170
3171        let left = ui::ButtonLike::new_rounded_left(ElementId::Name(
3172            format!("split-button-left-{}", id).into(),
3173        ))
3174        .layer(ui::ElevationIndex::ModalSurface)
3175        .size(ui::ButtonSize::Compact)
3176        .when(should_render_counts, |this| {
3177            this.child(
3178                h_flex()
3179                    .ml_neg_0p5()
3180                    .mr_1()
3181                    .when(behind_count > 0, |this| {
3182                        this.child(Icon::new(IconName::ArrowDown).size(IconSize::XSmall))
3183                            .child(count(behind_count))
3184                    })
3185                    .when(ahead_count > 0, |this| {
3186                        this.child(Icon::new(IconName::ArrowUp).size(IconSize::XSmall))
3187                            .child(count(ahead_count))
3188                    }),
3189            )
3190        })
3191        .when_some(left_icon, |this, left_icon| {
3192            this.child(
3193                h_flex()
3194                    .ml_neg_0p5()
3195                    .mr_1()
3196                    .child(Icon::new(left_icon).size(IconSize::XSmall)),
3197            )
3198        })
3199        .child(
3200            div()
3201                .child(Label::new(left_label).size(LabelSize::Small))
3202                .mr_0p5(),
3203        )
3204        .on_click(left_on_click)
3205        .tooltip(tooltip);
3206
3207        let right =
3208            render_git_action_menu(ElementId::Name(format!("split-button-right-{}", id).into()))
3209                .into_any_element();
3210        // .on_click(right_on_click);
3211
3212        Self { left, right }
3213    }
3214}
3215
3216impl RenderOnce for SplitButton {
3217    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
3218        h_flex()
3219            .rounded_sm()
3220            .border_1()
3221            .border_color(cx.theme().colors().text_muted.alpha(0.12))
3222            .child(self.left)
3223            .child(
3224                div()
3225                    .h_full()
3226                    .w_px()
3227                    .bg(cx.theme().colors().text_muted.alpha(0.16)),
3228            )
3229            .child(self.right)
3230            .bg(ElevationIndex::Surface.on_elevation_bg(cx))
3231            .shadow(smallvec![BoxShadow {
3232                color: hsla(0.0, 0.0, 0.0, 0.16),
3233                offset: point(px(0.), px(1.)),
3234                blur_radius: px(0.),
3235                spread_radius: px(0.),
3236            }])
3237    }
3238}
3239
3240fn render_git_action_menu(id: impl Into<ElementId>) -> impl IntoElement {
3241    PopoverMenu::new(id.into())
3242        .trigger(
3243            ui::ButtonLike::new_rounded_right("split-button-right")
3244                .layer(ui::ElevationIndex::ModalSurface)
3245                .size(ui::ButtonSize::None)
3246                .child(
3247                    div()
3248                        .px_1()
3249                        .child(Icon::new(IconName::ChevronDownSmall).size(IconSize::XSmall)),
3250                ),
3251        )
3252        .menu(move |window, cx| {
3253            Some(ContextMenu::build(window, cx, |context_menu, _, _| {
3254                context_menu
3255                    .action("Fetch", git::Fetch.boxed_clone())
3256                    .action("Pull", git::Pull.boxed_clone())
3257                    .separator()
3258                    .action("Push", git::Push.boxed_clone())
3259                    .action("Force Push", git::ForcePush.boxed_clone())
3260            }))
3261        })
3262        .anchor(Corner::TopRight)
3263}
3264
3265#[derive(IntoElement, IntoComponent)]
3266#[component(scope = "git_panel")]
3267pub struct PanelRepoFooter {
3268    id: SharedString,
3269    active_repository: SharedString,
3270    branch: Option<Branch>,
3271    // Getting a GitPanel in previews will be difficult.
3272    //
3273    // For now just take an option here, and we won't bind handlers to buttons in previews.
3274    git_panel: Option<Entity<GitPanel>>,
3275}
3276
3277impl PanelRepoFooter {
3278    pub fn new(
3279        id: impl Into<SharedString>,
3280        active_repository: SharedString,
3281        branch: Option<Branch>,
3282        git_panel: Option<Entity<GitPanel>>,
3283    ) -> Self {
3284        Self {
3285            id: id.into(),
3286            active_repository,
3287            branch,
3288            git_panel,
3289        }
3290    }
3291
3292    pub fn new_preview(
3293        id: impl Into<SharedString>,
3294        active_repository: SharedString,
3295        branch: Option<Branch>,
3296    ) -> Self {
3297        Self {
3298            id: id.into(),
3299            active_repository,
3300            branch,
3301            git_panel: None,
3302        }
3303    }
3304
3305    fn render_overflow_menu(&self, id: impl Into<ElementId>) -> impl IntoElement {
3306        PopoverMenu::new(id.into())
3307            .trigger(
3308                IconButton::new("overflow-menu-trigger", IconName::EllipsisVertical)
3309                    .icon_size(IconSize::Small)
3310                    .icon_color(Color::Muted),
3311            )
3312            .menu(move |window, cx| Some(git_panel_context_menu(window, cx)))
3313            .anchor(Corner::TopRight)
3314    }
3315
3316    fn panel_focus_handle(&self, cx: &App) -> Option<FocusHandle> {
3317        if let Some(git_panel) = self.git_panel.clone() {
3318            Some(git_panel.focus_handle(cx))
3319        } else {
3320            None
3321        }
3322    }
3323
3324    fn render_push_button(&self, id: SharedString, ahead: u32, cx: &mut App) -> SplitButton {
3325        let panel = self.git_panel.clone();
3326        let panel_focus_handle = self.panel_focus_handle(cx);
3327
3328        SplitButton::new(
3329            id,
3330            "Push",
3331            ahead as usize,
3332            0,
3333            None,
3334            move |_, window, cx| {
3335                if let Some(panel) = panel.as_ref() {
3336                    panel.update(cx, |panel, cx| {
3337                        panel.push(false, window, cx);
3338                    });
3339                }
3340            },
3341            move |window, cx| {
3342                git_action_tooltip(
3343                    "Push committed changes to remote",
3344                    &git::Push,
3345                    "git push",
3346                    panel_focus_handle.clone(),
3347                    window,
3348                    cx,
3349                )
3350            },
3351        )
3352    }
3353
3354    fn render_pull_button(
3355        &self,
3356        id: SharedString,
3357        ahead: u32,
3358        behind: u32,
3359        cx: &mut App,
3360    ) -> SplitButton {
3361        let panel = self.git_panel.clone();
3362        let panel_focus_handle = self.panel_focus_handle(cx);
3363
3364        SplitButton::new(
3365            id,
3366            "Pull",
3367            ahead as usize,
3368            behind as usize,
3369            None,
3370            move |_, window, cx| {
3371                if let Some(panel) = panel.as_ref() {
3372                    panel.update(cx, |panel, cx| {
3373                        panel.pull(window, cx);
3374                    });
3375                }
3376            },
3377            move |window, cx| {
3378                git_action_tooltip(
3379                    "Pull",
3380                    &git::Pull,
3381                    "git pull",
3382                    panel_focus_handle.clone(),
3383                    window,
3384                    cx,
3385                )
3386            },
3387        )
3388    }
3389
3390    fn render_fetch_button(&self, id: SharedString, cx: &mut App) -> SplitButton {
3391        let panel = self.git_panel.clone();
3392        let panel_focus_handle = self.panel_focus_handle(cx);
3393
3394        SplitButton::new(
3395            id,
3396            "Fetch",
3397            0,
3398            0,
3399            Some(IconName::ArrowCircle),
3400            move |_, window, cx| {
3401                if let Some(panel) = panel.as_ref() {
3402                    panel.update(cx, |panel, cx| {
3403                        panel.fetch(window, cx);
3404                    });
3405                }
3406            },
3407            move |window, cx| {
3408                git_action_tooltip(
3409                    "Fetch updates from remote",
3410                    &git::Fetch,
3411                    "git fetch",
3412                    panel_focus_handle.clone(),
3413                    window,
3414                    cx,
3415                )
3416            },
3417        )
3418    }
3419
3420    fn render_publish_button(&self, id: SharedString, cx: &mut App) -> SplitButton {
3421        let panel = self.git_panel.clone();
3422        let panel_focus_handle = self.panel_focus_handle(cx);
3423
3424        SplitButton::new(
3425            id,
3426            "Publish",
3427            0,
3428            0,
3429            Some(IconName::ArrowUpFromLine),
3430            move |_, window, cx| {
3431                if let Some(panel) = panel.as_ref() {
3432                    panel.update(cx, |panel, cx| {
3433                        panel.push(false, window, cx);
3434                    });
3435                }
3436            },
3437            move |window, cx| {
3438                git_action_tooltip(
3439                    "Publish branch to remote",
3440                    &git::Push,
3441                    "git push --set-upstream",
3442                    panel_focus_handle.clone(),
3443                    window,
3444                    cx,
3445                )
3446            },
3447        )
3448    }
3449
3450    fn render_republish_button(&self, id: SharedString, cx: &mut App) -> SplitButton {
3451        let panel = self.git_panel.clone();
3452        let panel_focus_handle = self.panel_focus_handle(cx);
3453
3454        SplitButton::new(
3455            id,
3456            "Republish",
3457            0,
3458            0,
3459            Some(IconName::ArrowUpFromLine),
3460            move |_, window, cx| {
3461                if let Some(panel) = panel.as_ref() {
3462                    panel.update(cx, |panel, cx| {
3463                        panel.push(false, window, cx);
3464                    });
3465                }
3466            },
3467            move |window, cx| {
3468                git_action_tooltip(
3469                    "Re-publish branch to remote",
3470                    &git::Push,
3471                    "git push --set-upstream",
3472                    panel_focus_handle.clone(),
3473                    window,
3474                    cx,
3475                )
3476            },
3477        )
3478    }
3479
3480    fn render_relevant_button(
3481        &self,
3482        id: impl Into<SharedString>,
3483        branch: &Branch,
3484        cx: &mut App,
3485    ) -> Option<impl IntoElement> {
3486        if let Some(git_panel) = self.git_panel.as_ref() {
3487            if !git_panel.read(cx).can_push_and_pull(cx) {
3488                return None;
3489            }
3490        }
3491        let id = id.into();
3492        let upstream = branch.upstream.as_ref();
3493        Some(match upstream {
3494            Some(Upstream {
3495                tracking: UpstreamTracking::Tracked(UpstreamTrackingStatus { ahead, behind }),
3496                ..
3497            }) => match (*ahead, *behind) {
3498                (0, 0) => self.render_fetch_button(id, cx),
3499                (ahead, 0) => self.render_push_button(id, ahead, cx),
3500                (ahead, behind) => self.render_pull_button(id, ahead, behind, cx),
3501            },
3502            Some(Upstream {
3503                tracking: UpstreamTracking::Gone,
3504                ..
3505            }) => self.render_republish_button(id, cx),
3506            None => self.render_publish_button(id, cx),
3507        })
3508    }
3509}
3510
3511impl RenderOnce for PanelRepoFooter {
3512    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
3513        let active_repo = self.active_repository.clone();
3514        let overflow_menu_id: SharedString = format!("overflow-menu-{}", active_repo).into();
3515        let repo_selector_trigger = Button::new("repo-selector", active_repo)
3516            .style(ButtonStyle::Transparent)
3517            .size(ButtonSize::None)
3518            .label_size(LabelSize::Small)
3519            .color(Color::Muted);
3520
3521        let project = self
3522            .git_panel
3523            .as_ref()
3524            .map(|panel| panel.read(cx).project.clone());
3525
3526        let repo = self
3527            .git_panel
3528            .as_ref()
3529            .and_then(|panel| panel.read(cx).active_repository.clone());
3530
3531        let single_repo = project
3532            .as_ref()
3533            .map(|project| project.read(cx).all_repositories(cx).len() == 1)
3534            .unwrap_or(true);
3535
3536        let repo_selector = PopoverMenu::new("repository-switcher")
3537            .menu({
3538                let project = project.clone();
3539                move |window, cx| {
3540                    let project = project.clone()?;
3541                    Some(cx.new(|cx| RepositorySelector::new(project, window, cx)))
3542                }
3543            })
3544            .trigger_with_tooltip(
3545                repo_selector_trigger.disabled(single_repo).truncate(true),
3546                Tooltip::text("Switch active repository"),
3547            )
3548            .attach(gpui::Corner::BottomLeft)
3549            .into_any_element();
3550
3551        let branch = self.branch.clone();
3552        let branch_name = branch
3553            .as_ref()
3554            .map_or(" (no branch)".into(), |branch| branch.name.clone());
3555
3556        let branch_selector_button = Button::new("branch-selector", branch_name)
3557            .style(ButtonStyle::Transparent)
3558            .size(ButtonSize::None)
3559            .label_size(LabelSize::Small)
3560            .truncate(true)
3561            .tooltip(Tooltip::for_action_title(
3562                "Switch Branch",
3563                &zed_actions::git::Branch,
3564            ))
3565            .on_click(|_, window, cx| {
3566                window.dispatch_action(zed_actions::git::Branch.boxed_clone(), cx);
3567            });
3568
3569        let branch_selector = PopoverMenu::new("popover-button")
3570            .menu(move |window, cx| Some(branch_picker::popover(repo.clone(), window, cx)))
3571            .trigger_with_tooltip(
3572                branch_selector_button,
3573                Tooltip::for_action_title("Switch Branch", &zed_actions::git::Branch),
3574            )
3575            .anchor(Corner::TopLeft)
3576            .offset(gpui::Point {
3577                x: px(0.0),
3578                y: px(-2.0),
3579            });
3580
3581        let spinner = self
3582            .git_panel
3583            .as_ref()
3584            .and_then(|git_panel| git_panel.read(cx).render_spinner());
3585
3586        h_flex()
3587            .w_full()
3588            .px_2()
3589            .h(px(36.))
3590            .items_center()
3591            .justify_between()
3592            .child(
3593                h_flex()
3594                    .flex_1()
3595                    .overflow_hidden()
3596                    .items_center()
3597                    .child(
3598                        div().child(
3599                            Icon::new(IconName::GitBranchSmall)
3600                                .size(IconSize::Small)
3601                                .color(Color::Muted),
3602                        ),
3603                    )
3604                    .child(repo_selector)
3605                    .when_some(branch.clone(), |this, _| {
3606                        this.child(
3607                            div()
3608                                .text_color(cx.theme().colors().text_muted)
3609                                .text_sm()
3610                                .child("/"),
3611                        )
3612                    })
3613                    .child(branch_selector),
3614            )
3615            .child(
3616                h_flex()
3617                    .gap_1()
3618                    .flex_shrink_0()
3619                    .children(spinner)
3620                    .child(self.render_overflow_menu(overflow_menu_id))
3621                    .when_some(branch, |this, branch| {
3622                        let button = self.render_relevant_button(self.id.clone(), &branch, cx);
3623                        this.children(button)
3624                    }),
3625            )
3626    }
3627}
3628
3629impl ComponentPreview for PanelRepoFooter {
3630    fn preview(_window: &mut Window, _cx: &mut App) -> AnyElement {
3631        let unknown_upstream = None;
3632        let no_remote_upstream = Some(UpstreamTracking::Gone);
3633        let ahead_of_upstream = Some(
3634            UpstreamTrackingStatus {
3635                ahead: 2,
3636                behind: 0,
3637            }
3638            .into(),
3639        );
3640        let behind_upstream = Some(
3641            UpstreamTrackingStatus {
3642                ahead: 0,
3643                behind: 2,
3644            }
3645            .into(),
3646        );
3647        let ahead_and_behind_upstream = Some(
3648            UpstreamTrackingStatus {
3649                ahead: 3,
3650                behind: 1,
3651            }
3652            .into(),
3653        );
3654
3655        let not_ahead_or_behind_upstream = Some(
3656            UpstreamTrackingStatus {
3657                ahead: 0,
3658                behind: 0,
3659            }
3660            .into(),
3661        );
3662
3663        fn branch(upstream: Option<UpstreamTracking>) -> Branch {
3664            Branch {
3665                is_head: true,
3666                name: "some-branch".into(),
3667                upstream: upstream.map(|tracking| Upstream {
3668                    ref_name: "origin/some-branch".into(),
3669                    tracking,
3670                }),
3671                most_recent_commit: Some(CommitSummary {
3672                    sha: "abc123".into(),
3673                    subject: "Modify stuff".into(),
3674                    commit_timestamp: 1710932954,
3675                    has_parent: true,
3676                }),
3677            }
3678        }
3679
3680        fn custom(branch_name: &str, upstream: Option<UpstreamTracking>) -> Branch {
3681            Branch {
3682                is_head: true,
3683                name: branch_name.to_string().into(),
3684                upstream: upstream.map(|tracking| Upstream {
3685                    ref_name: format!("zed/{}", branch_name).into(),
3686                    tracking,
3687                }),
3688                most_recent_commit: Some(CommitSummary {
3689                    sha: "abc123".into(),
3690                    subject: "Modify stuff".into(),
3691                    commit_timestamp: 1710932954,
3692                    has_parent: true,
3693                }),
3694            }
3695        }
3696
3697        fn active_repository(id: usize) -> SharedString {
3698            format!("repo-{}", id).into()
3699        }
3700
3701        let example_width = px(340.);
3702
3703        v_flex()
3704            .gap_6()
3705            .w_full()
3706            .flex_none()
3707            .children(vec![example_group_with_title(
3708                "Action Button States",
3709                vec![
3710                    single_example(
3711                        "No Branch",
3712                        div()
3713                            .w(example_width)
3714                            .overflow_hidden()
3715                            .child(PanelRepoFooter::new_preview(
3716                                "no-branch",
3717                                active_repository(1).clone(),
3718                                None,
3719                            ))
3720                            .into_any_element(),
3721                    )
3722                    .grow(),
3723                    single_example(
3724                        "Remote status unknown",
3725                        div()
3726                            .w(example_width)
3727                            .overflow_hidden()
3728                            .child(PanelRepoFooter::new_preview(
3729                                "unknown-upstream",
3730                                active_repository(2).clone(),
3731                                Some(branch(unknown_upstream)),
3732                            ))
3733                            .into_any_element(),
3734                    )
3735                    .grow(),
3736                    single_example(
3737                        "No Remote Upstream",
3738                        div()
3739                            .w(example_width)
3740                            .overflow_hidden()
3741                            .child(PanelRepoFooter::new_preview(
3742                                "no-remote-upstream",
3743                                active_repository(3).clone(),
3744                                Some(branch(no_remote_upstream)),
3745                            ))
3746                            .into_any_element(),
3747                    )
3748                    .grow(),
3749                    single_example(
3750                        "Not Ahead or Behind",
3751                        div()
3752                            .w(example_width)
3753                            .overflow_hidden()
3754                            .child(PanelRepoFooter::new_preview(
3755                                "not-ahead-or-behind",
3756                                active_repository(4).clone(),
3757                                Some(branch(not_ahead_or_behind_upstream)),
3758                            ))
3759                            .into_any_element(),
3760                    )
3761                    .grow(),
3762                    single_example(
3763                        "Behind remote",
3764                        div()
3765                            .w(example_width)
3766                            .overflow_hidden()
3767                            .child(PanelRepoFooter::new_preview(
3768                                "behind-remote",
3769                                active_repository(5).clone(),
3770                                Some(branch(behind_upstream)),
3771                            ))
3772                            .into_any_element(),
3773                    )
3774                    .grow(),
3775                    single_example(
3776                        "Ahead of remote",
3777                        div()
3778                            .w(example_width)
3779                            .overflow_hidden()
3780                            .child(PanelRepoFooter::new_preview(
3781                                "ahead-of-remote",
3782                                active_repository(6).clone(),
3783                                Some(branch(ahead_of_upstream)),
3784                            ))
3785                            .into_any_element(),
3786                    )
3787                    .grow(),
3788                    single_example(
3789                        "Ahead and behind remote",
3790                        div()
3791                            .w(example_width)
3792                            .overflow_hidden()
3793                            .child(PanelRepoFooter::new_preview(
3794                                "ahead-and-behind",
3795                                active_repository(7).clone(),
3796                                Some(branch(ahead_and_behind_upstream)),
3797                            ))
3798                            .into_any_element(),
3799                    )
3800                    .grow(),
3801                ],
3802            )
3803            .grow()
3804            .vertical()])
3805            .children(vec![example_group_with_title(
3806                "Labels",
3807                vec![
3808                    single_example(
3809                        "Short Branch & Repo",
3810                        div()
3811                            .w(example_width)
3812                            .overflow_hidden()
3813                            .child(PanelRepoFooter::new_preview(
3814                                "short-branch",
3815                                SharedString::from("zed"),
3816                                Some(custom("main", behind_upstream)),
3817                            ))
3818                            .into_any_element(),
3819                    )
3820                    .grow(),
3821                    single_example(
3822                        "Long Branch",
3823                        div()
3824                            .w(example_width)
3825                            .overflow_hidden()
3826                            .child(PanelRepoFooter::new_preview(
3827                                "long-branch",
3828                                SharedString::from("zed"),
3829                                Some(custom(
3830                                    "redesign-and-update-git-ui-list-entry-style",
3831                                    behind_upstream,
3832                                )),
3833                            ))
3834                            .into_any_element(),
3835                    )
3836                    .grow(),
3837                    single_example(
3838                        "Long Repo",
3839                        div()
3840                            .w(example_width)
3841                            .overflow_hidden()
3842                            .child(PanelRepoFooter::new_preview(
3843                                "long-repo",
3844                                SharedString::from("zed-industries-community-examples"),
3845                                Some(custom("gpui", ahead_of_upstream)),
3846                            ))
3847                            .into_any_element(),
3848                    )
3849                    .grow(),
3850                    single_example(
3851                        "Long Repo & Branch",
3852                        div()
3853                            .w(example_width)
3854                            .overflow_hidden()
3855                            .child(PanelRepoFooter::new_preview(
3856                                "long-repo-and-branch",
3857                                SharedString::from("zed-industries-community-examples"),
3858                                Some(custom(
3859                                    "redesign-and-update-git-ui-list-entry-style",
3860                                    behind_upstream,
3861                                )),
3862                            ))
3863                            .into_any_element(),
3864                    )
3865                    .grow(),
3866                    single_example(
3867                        "Uppercase Repo",
3868                        div()
3869                            .w(example_width)
3870                            .overflow_hidden()
3871                            .child(PanelRepoFooter::new_preview(
3872                                "uppercase-repo",
3873                                SharedString::from("LICENSES"),
3874                                Some(custom("main", ahead_of_upstream)),
3875                            ))
3876                            .into_any_element(),
3877                    )
3878                    .grow(),
3879                    single_example(
3880                        "Uppercase Branch",
3881                        div()
3882                            .w(example_width)
3883                            .overflow_hidden()
3884                            .child(PanelRepoFooter::new_preview(
3885                                "uppercase-branch",
3886                                SharedString::from("zed"),
3887                                Some(custom("update-README", behind_upstream)),
3888                            ))
3889                            .into_any_element(),
3890                    )
3891                    .grow(),
3892                ],
3893            )
3894            .grow()
3895            .vertical()])
3896            .into_any_element()
3897    }
3898}