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