git_panel.rs

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