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        if !self.can_commit() {
1457            return;
1458        }
1459
1460        let model = match current_language_model(cx) {
1461            Some(value) => value,
1462            None => return,
1463        };
1464
1465        let Some(repo) = self.active_repository.as_ref() else {
1466            return;
1467        };
1468
1469        telemetry::event!("Git Commit Message Generated");
1470
1471        let diff = repo.update(cx, |repo, cx| {
1472            if self.has_staged_changes() {
1473                repo.diff(DiffType::HeadToIndex, cx)
1474            } else {
1475                repo.diff(DiffType::HeadToWorktree, cx)
1476            }
1477        });
1478
1479        self.generate_commit_message_task = Some(cx.spawn(|this, mut cx| {
1480            async move {
1481                let _defer = util::defer({
1482                    let mut cx = cx.clone();
1483                    let this = this.clone();
1484                    move || {
1485                        this.update(&mut cx, |this, _cx| {
1486                            this.generate_commit_message_task.take();
1487                        })
1488                        .ok();
1489                    }
1490                });
1491
1492                let mut diff_text = diff.await??;
1493
1494                const ONE_MB: usize = 1_000_000;
1495                if diff_text.len() > ONE_MB {
1496                    diff_text = diff_text.chars().take(ONE_MB).collect()
1497                }
1498
1499                let subject = this.update(&mut cx, |this, cx| {
1500                    this.commit_editor.read(cx).text(cx).lines().next().map(ToOwned::to_owned).unwrap_or_default()
1501                })?;
1502
1503                let text_empty = subject.trim().is_empty();
1504
1505                let content = if text_empty {
1506                    format!("{PROMPT}\nHere are the changes in this commit:\n{diff_text}")
1507                } else {
1508                    format!("{PROMPT}\nHere is the user's subject line:\n{subject}\nHere are the changes in this commit:\n{diff_text}\n")
1509                };
1510
1511                const PROMPT: &str = include_str!("commit_message_prompt.txt");
1512
1513                let request = LanguageModelRequest {
1514                    messages: vec![LanguageModelRequestMessage {
1515                        role: Role::User,
1516                        content: vec![content.into()],
1517                        cache: false,
1518                    }],
1519                    tools: Vec::new(),
1520                    stop: Vec::new(),
1521                    temperature: None,
1522                };
1523
1524                let stream = model.stream_completion_text(request, &cx);
1525                let mut messages = stream.await?;
1526
1527                if !text_empty {
1528                    this.update(&mut cx, |this, cx| {
1529                        this.commit_message_buffer(cx).update(cx, |buffer, cx| {
1530                            let insert_position = buffer.anchor_before(buffer.len());
1531                            buffer.edit([(insert_position..insert_position, "\n")], None, cx)
1532                        });
1533                    })?;
1534                }
1535
1536                while let Some(message) = messages.stream.next().await {
1537                    let text = message?;
1538
1539                    this.update(&mut cx, |this, cx| {
1540                        this.commit_message_buffer(cx).update(cx, |buffer, cx| {
1541                            let insert_position = buffer.anchor_before(buffer.len());
1542                            buffer.edit([(insert_position..insert_position, text)], None, cx);
1543                        });
1544                    })?;
1545                }
1546
1547                anyhow::Ok(())
1548            }
1549            .log_err()
1550        }));
1551    }
1552
1553    fn update_editor_placeholder(&mut self, cx: &mut Context<Self>) {
1554        let suggested_commit_message = self.suggest_commit_message();
1555        let placeholder_text = suggested_commit_message
1556            .as_deref()
1557            .unwrap_or("Enter commit message");
1558
1559        self.commit_editor.update(cx, |editor, cx| {
1560            editor.set_placeholder_text(Arc::from(placeholder_text), cx)
1561        });
1562
1563        cx.notify();
1564    }
1565
1566    pub(crate) fn fetch(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1567        if !self.can_push_and_pull(cx) {
1568            return;
1569        }
1570
1571        let Some(repo) = self.active_repository.clone() else {
1572            return;
1573        };
1574        telemetry::event!("Git Fetched");
1575        let guard = self.start_remote_operation();
1576        let askpass = self.askpass_delegate("git fetch", window, cx);
1577        cx.spawn(|this, mut cx| async move {
1578            let fetch = repo.update(&mut cx, |repo, cx| repo.fetch(askpass, cx))?;
1579
1580            let remote_message = fetch.await?;
1581            drop(guard);
1582            this.update(&mut cx, |this, cx| {
1583                match remote_message {
1584                    Ok(remote_message) => {
1585                        this.show_remote_output(RemoteAction::Fetch, remote_message, cx);
1586                    }
1587                    Err(e) => {
1588                        log::error!("Error while fetching {:?}", e);
1589                        this.show_err_toast(e, cx);
1590                    }
1591                }
1592
1593                anyhow::Ok(())
1594            })
1595            .ok();
1596            anyhow::Ok(())
1597        })
1598        .detach_and_log_err(cx);
1599    }
1600
1601    pub(crate) fn pull(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1602        if !self.can_push_and_pull(cx) {
1603            return;
1604        }
1605        let Some(repo) = self.active_repository.clone() else {
1606            return;
1607        };
1608        let Some(branch) = repo.read(cx).current_branch() else {
1609            return;
1610        };
1611        telemetry::event!("Git Pulled");
1612        let branch = branch.clone();
1613        let remote = self.get_current_remote(window, cx);
1614        cx.spawn_in(window, move |this, mut cx| async move {
1615            let remote = match remote.await {
1616                Ok(Some(remote)) => remote,
1617                Ok(None) => {
1618                    return Ok(());
1619                }
1620                Err(e) => {
1621                    log::error!("Failed to get current remote: {}", e);
1622                    this.update(&mut cx, |this, cx| this.show_err_toast(e, cx))
1623                        .ok();
1624                    return Ok(());
1625                }
1626            };
1627
1628            let askpass = this.update_in(&mut cx, |this, window, cx| {
1629                this.askpass_delegate(format!("git pull {}", remote.name), window, cx)
1630            })?;
1631
1632            let guard = this
1633                .update(&mut cx, |this, _| this.start_remote_operation())
1634                .ok();
1635
1636            let pull = repo.update(&mut cx, |repo, cx| {
1637                repo.pull(branch.name.clone(), remote.name.clone(), askpass, cx)
1638            })?;
1639
1640            let remote_message = pull.await?;
1641            drop(guard);
1642
1643            this.update(&mut cx, |this, cx| match remote_message {
1644                Ok(remote_message) => {
1645                    this.show_remote_output(RemoteAction::Pull, remote_message, cx)
1646                }
1647                Err(err) => {
1648                    log::error!("Error while pull {:?}", err);
1649                    this.show_err_toast(err, cx)
1650                }
1651            })
1652            .ok();
1653
1654            anyhow::Ok(())
1655        })
1656        .detach_and_log_err(cx);
1657    }
1658
1659    pub(crate) fn push(&mut self, force_push: bool, window: &mut Window, cx: &mut Context<Self>) {
1660        if !self.can_push_and_pull(cx) {
1661            return;
1662        }
1663        let Some(repo) = self.active_repository.clone() else {
1664            return;
1665        };
1666        let Some(branch) = repo.read(cx).current_branch() else {
1667            return;
1668        };
1669        telemetry::event!("Git Pushed");
1670        let branch = branch.clone();
1671        let options = if force_push {
1672            PushOptions::Force
1673        } else {
1674            PushOptions::SetUpstream
1675        };
1676        let remote = self.get_current_remote(window, cx);
1677
1678        cx.spawn_in(window, move |this, mut cx| async move {
1679            let remote = match remote.await {
1680                Ok(Some(remote)) => remote,
1681                Ok(None) => {
1682                    return Ok(());
1683                }
1684                Err(e) => {
1685                    log::error!("Failed to get current remote: {}", e);
1686                    this.update(&mut cx, |this, cx| this.show_err_toast(e, cx))
1687                        .ok();
1688                    return Ok(());
1689                }
1690            };
1691
1692            let askpass_delegate = this.update_in(&mut cx, |this, window, cx| {
1693                this.askpass_delegate(format!("git push {}", remote.name), window, cx)
1694            })?;
1695
1696            let guard = this
1697                .update(&mut cx, |this, _| this.start_remote_operation())
1698                .ok();
1699
1700            let push = repo.update(&mut cx, |repo, cx| {
1701                repo.push(
1702                    branch.name.clone(),
1703                    remote.name.clone(),
1704                    Some(options),
1705                    askpass_delegate,
1706                    cx,
1707                )
1708            })?;
1709
1710            let remote_output = push.await?;
1711            drop(guard);
1712
1713            this.update(&mut cx, |this, cx| match remote_output {
1714                Ok(remote_message) => {
1715                    this.show_remote_output(RemoteAction::Push(remote), remote_message, cx);
1716                }
1717                Err(e) => {
1718                    log::error!("Error while pushing {:?}", e);
1719                    this.show_err_toast(e, cx);
1720                }
1721            })?;
1722
1723            anyhow::Ok(())
1724        })
1725        .detach_and_log_err(cx);
1726    }
1727
1728    fn askpass_delegate(
1729        &self,
1730        operation: impl Into<SharedString>,
1731        window: &mut Window,
1732        cx: &mut Context<Self>,
1733    ) -> AskPassDelegate {
1734        let this = cx.weak_entity();
1735        let operation = operation.into();
1736        let window = window.window_handle();
1737        AskPassDelegate::new(&mut cx.to_async(), move |prompt, tx, cx| {
1738            window
1739                .update(cx, |_, window, cx| {
1740                    this.update(cx, |this, cx| {
1741                        this.workspace.update(cx, |workspace, cx| {
1742                            workspace.toggle_modal(window, cx, |window, cx| {
1743                                AskPassModal::new(operation.clone(), prompt.into(), tx, window, cx)
1744                            });
1745                        })
1746                    })
1747                })
1748                .ok();
1749        })
1750    }
1751
1752    fn can_push_and_pull(&self, cx: &App) -> bool {
1753        crate::can_push_and_pull(&self.project, cx)
1754    }
1755
1756    fn get_current_remote(
1757        &mut self,
1758        window: &mut Window,
1759        cx: &mut Context<Self>,
1760    ) -> impl Future<Output = anyhow::Result<Option<Remote>>> {
1761        let repo = self.active_repository.clone();
1762        let workspace = self.workspace.clone();
1763        let mut cx = window.to_async(cx);
1764
1765        async move {
1766            let Some(repo) = repo else {
1767                return Err(anyhow::anyhow!("No active repository"));
1768            };
1769
1770            let mut current_remotes: Vec<Remote> = repo
1771                .update(&mut cx, |repo, _| {
1772                    let Some(current_branch) = repo.current_branch() else {
1773                        return Err(anyhow::anyhow!("No active branch"));
1774                    };
1775
1776                    Ok(repo.get_remotes(Some(current_branch.name.to_string())))
1777                })??
1778                .await??;
1779
1780            if current_remotes.len() == 0 {
1781                return Err(anyhow::anyhow!("No active remote"));
1782            } else if current_remotes.len() == 1 {
1783                return Ok(Some(current_remotes.pop().unwrap()));
1784            } else {
1785                let current_remotes: Vec<_> = current_remotes
1786                    .into_iter()
1787                    .map(|remotes| remotes.name)
1788                    .collect();
1789                let selection = cx
1790                    .update(|window, cx| {
1791                        picker_prompt::prompt(
1792                            "Pick which remote to push to",
1793                            current_remotes.clone(),
1794                            workspace,
1795                            window,
1796                            cx,
1797                        )
1798                    })?
1799                    .await?;
1800
1801                Ok(selection.map(|selection| Remote {
1802                    name: current_remotes[selection].clone(),
1803                }))
1804            }
1805        }
1806    }
1807
1808    fn potential_co_authors(&self, cx: &App) -> Vec<(String, String)> {
1809        let mut new_co_authors = Vec::new();
1810        let project = self.project.read(cx);
1811
1812        let Some(room) = self
1813            .workspace
1814            .upgrade()
1815            .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned())
1816        else {
1817            return Vec::default();
1818        };
1819
1820        let room = room.read(cx);
1821
1822        for (peer_id, collaborator) in project.collaborators() {
1823            if collaborator.is_host {
1824                continue;
1825            }
1826
1827            let Some(participant) = room.remote_participant_for_peer_id(*peer_id) else {
1828                continue;
1829            };
1830            if participant.can_write() && participant.user.email.is_some() {
1831                let email = participant.user.email.clone().unwrap();
1832
1833                new_co_authors.push((
1834                    participant
1835                        .user
1836                        .name
1837                        .clone()
1838                        .unwrap_or_else(|| participant.user.github_login.clone()),
1839                    email,
1840                ))
1841            }
1842        }
1843        if !project.is_local() && !project.is_read_only(cx) {
1844            if let Some(user) = room.local_participant_user(cx) {
1845                if let Some(email) = user.email.clone() {
1846                    new_co_authors.push((
1847                        user.name
1848                            .clone()
1849                            .unwrap_or_else(|| user.github_login.clone()),
1850                        email.clone(),
1851                    ))
1852                }
1853            }
1854        }
1855        new_co_authors
1856    }
1857
1858    fn toggle_fill_co_authors(
1859        &mut self,
1860        _: &ToggleFillCoAuthors,
1861        _: &mut Window,
1862        cx: &mut Context<Self>,
1863    ) {
1864        self.add_coauthors = !self.add_coauthors;
1865        cx.notify();
1866    }
1867
1868    fn fill_co_authors(&mut self, message: &mut String, cx: &mut Context<Self>) {
1869        const CO_AUTHOR_PREFIX: &str = "Co-authored-by: ";
1870
1871        let existing_text = message.to_ascii_lowercase();
1872        let lowercase_co_author_prefix = CO_AUTHOR_PREFIX.to_lowercase();
1873        let mut ends_with_co_authors = false;
1874        let existing_co_authors = existing_text
1875            .lines()
1876            .filter_map(|line| {
1877                let line = line.trim();
1878                if line.starts_with(&lowercase_co_author_prefix) {
1879                    ends_with_co_authors = true;
1880                    Some(line)
1881                } else {
1882                    ends_with_co_authors = false;
1883                    None
1884                }
1885            })
1886            .collect::<HashSet<_>>();
1887
1888        let new_co_authors = self
1889            .potential_co_authors(cx)
1890            .into_iter()
1891            .filter(|(_, email)| {
1892                !existing_co_authors
1893                    .iter()
1894                    .any(|existing| existing.contains(email.as_str()))
1895            })
1896            .collect::<Vec<_>>();
1897
1898        if new_co_authors.is_empty() {
1899            return;
1900        }
1901
1902        if !ends_with_co_authors {
1903            message.push('\n');
1904        }
1905        for (name, email) in new_co_authors {
1906            message.push('\n');
1907            message.push_str(CO_AUTHOR_PREFIX);
1908            message.push_str(&name);
1909            message.push_str(" <");
1910            message.push_str(&email);
1911            message.push('>');
1912        }
1913        message.push('\n');
1914    }
1915
1916    fn schedule_update(
1917        &mut self,
1918        clear_pending: bool,
1919        window: &mut Window,
1920        cx: &mut Context<Self>,
1921    ) {
1922        let handle = cx.entity().downgrade();
1923        self.reopen_commit_buffer(window, cx);
1924        self.update_visible_entries_task = cx.spawn_in(window, |_, mut cx| async move {
1925            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
1926            if let Some(git_panel) = handle.upgrade() {
1927                git_panel
1928                    .update_in(&mut cx, |git_panel, _, cx| {
1929                        if clear_pending {
1930                            git_panel.clear_pending();
1931                        }
1932                        git_panel.update_visible_entries(cx);
1933                        git_panel.update_editor_placeholder(cx);
1934                    })
1935                    .ok();
1936            }
1937        });
1938    }
1939
1940    fn reopen_commit_buffer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1941        let Some(active_repo) = self.active_repository.as_ref() else {
1942            return;
1943        };
1944        let load_buffer = active_repo.update(cx, |active_repo, cx| {
1945            let project = self.project.read(cx);
1946            active_repo.open_commit_buffer(
1947                Some(project.languages().clone()),
1948                project.buffer_store().clone(),
1949                cx,
1950            )
1951        });
1952
1953        cx.spawn_in(window, |git_panel, mut cx| async move {
1954            let buffer = load_buffer.await?;
1955            git_panel.update_in(&mut cx, |git_panel, window, cx| {
1956                if git_panel
1957                    .commit_editor
1958                    .read(cx)
1959                    .buffer()
1960                    .read(cx)
1961                    .as_singleton()
1962                    .as_ref()
1963                    != Some(&buffer)
1964                {
1965                    git_panel.commit_editor = cx.new(|cx| {
1966                        commit_message_editor(
1967                            buffer,
1968                            git_panel.suggest_commit_message().as_deref(),
1969                            git_panel.project.clone(),
1970                            true,
1971                            window,
1972                            cx,
1973                        )
1974                    });
1975                }
1976            })
1977        })
1978        .detach_and_log_err(cx);
1979    }
1980
1981    fn clear_pending(&mut self) {
1982        self.pending.retain(|v| !v.finished)
1983    }
1984
1985    fn update_visible_entries(&mut self, cx: &mut Context<Self>) {
1986        self.entries.clear();
1987        self.single_staged_entry.take();
1988        self.single_staged_entry.take();
1989        let mut changed_entries = Vec::new();
1990        let mut new_entries = Vec::new();
1991        let mut conflict_entries = Vec::new();
1992        let mut last_staged = None;
1993        let mut staged_count = 0;
1994
1995        let Some(repo) = self.active_repository.as_ref() else {
1996            // Just clear entries if no repository is active.
1997            cx.notify();
1998            return;
1999        };
2000
2001        let repo = repo.read(cx);
2002
2003        for entry in repo.status() {
2004            let is_conflict = repo.has_conflict(&entry.repo_path);
2005            let is_new = entry.status.is_created();
2006            let staging = entry.status.staging();
2007
2008            if self.pending.iter().any(|pending| {
2009                pending.target_status == TargetStatus::Reverted
2010                    && !pending.finished
2011                    && pending
2012                        .entries
2013                        .iter()
2014                        .any(|pending| pending.repo_path == entry.repo_path)
2015            }) {
2016                continue;
2017            }
2018
2019            // dot_git_abs path always has at least one component, namely .git.
2020            let abs_path = repo
2021                .dot_git_abs_path
2022                .parent()
2023                .unwrap()
2024                .join(&entry.repo_path);
2025            let worktree_path = repo.repository_entry.unrelativize(&entry.repo_path);
2026            let entry = GitStatusEntry {
2027                repo_path: entry.repo_path.clone(),
2028                worktree_path,
2029                abs_path,
2030                status: entry.status,
2031                staging,
2032            };
2033
2034            if staging.has_staged() {
2035                staged_count += 1;
2036                last_staged = Some(entry.clone());
2037            }
2038
2039            if is_conflict {
2040                conflict_entries.push(entry);
2041            } else if is_new {
2042                new_entries.push(entry);
2043            } else {
2044                changed_entries.push(entry);
2045            }
2046        }
2047
2048        let mut pending_staged_count = 0;
2049        let mut last_pending_staged = None;
2050        let mut pending_status_for_last_staged = None;
2051        for pending in self.pending.iter() {
2052            if pending.target_status == TargetStatus::Staged {
2053                pending_staged_count += pending.entries.len();
2054                last_pending_staged = pending.entries.iter().next().cloned();
2055            }
2056            if let Some(last_staged) = &last_staged {
2057                if pending
2058                    .entries
2059                    .iter()
2060                    .any(|entry| entry.repo_path == last_staged.repo_path)
2061                {
2062                    pending_status_for_last_staged = Some(pending.target_status);
2063                }
2064            }
2065        }
2066
2067        if conflict_entries.len() == 0 && staged_count == 1 && pending_staged_count == 0 {
2068            match pending_status_for_last_staged {
2069                Some(TargetStatus::Staged) | None => {
2070                    self.single_staged_entry = last_staged;
2071                }
2072                _ => {}
2073            }
2074        } else if conflict_entries.len() == 0 && pending_staged_count == 1 {
2075            self.single_staged_entry = last_pending_staged;
2076        }
2077
2078        if conflict_entries.len() == 0 && changed_entries.len() == 1 {
2079            self.single_tracked_entry = changed_entries.first().cloned();
2080        }
2081
2082        if conflict_entries.len() > 0 {
2083            self.entries.push(GitListEntry::Header(GitHeaderEntry {
2084                header: Section::Conflict,
2085            }));
2086            self.entries.extend(
2087                conflict_entries
2088                    .into_iter()
2089                    .map(GitListEntry::GitStatusEntry),
2090            );
2091        }
2092
2093        if changed_entries.len() > 0 {
2094            self.entries.push(GitListEntry::Header(GitHeaderEntry {
2095                header: Section::Tracked,
2096            }));
2097            self.entries.extend(
2098                changed_entries
2099                    .into_iter()
2100                    .map(GitListEntry::GitStatusEntry),
2101            );
2102        }
2103        if new_entries.len() > 0 {
2104            self.entries.push(GitListEntry::Header(GitHeaderEntry {
2105                header: Section::New,
2106            }));
2107            self.entries
2108                .extend(new_entries.into_iter().map(GitListEntry::GitStatusEntry));
2109        }
2110
2111        self.update_counts(repo);
2112
2113        self.select_first_entry_if_none(cx);
2114
2115        cx.notify();
2116    }
2117
2118    fn header_state(&self, header_type: Section) -> ToggleState {
2119        let (staged_count, count) = match header_type {
2120            Section::New => (self.new_staged_count, self.new_count),
2121            Section::Tracked => (self.tracked_staged_count, self.tracked_count),
2122            Section::Conflict => (self.conflicted_staged_count, self.conflicted_count),
2123        };
2124        if staged_count == 0 {
2125            ToggleState::Unselected
2126        } else if count == staged_count {
2127            ToggleState::Selected
2128        } else {
2129            ToggleState::Indeterminate
2130        }
2131    }
2132
2133    fn update_counts(&mut self, repo: &Repository) {
2134        self.conflicted_count = 0;
2135        self.conflicted_staged_count = 0;
2136        self.new_count = 0;
2137        self.tracked_count = 0;
2138        self.new_staged_count = 0;
2139        self.tracked_staged_count = 0;
2140        for entry in &self.entries {
2141            let Some(status_entry) = entry.status_entry() else {
2142                continue;
2143            };
2144            if repo.has_conflict(&status_entry.repo_path) {
2145                self.conflicted_count += 1;
2146                if self.entry_staging(status_entry).has_staged() {
2147                    self.conflicted_staged_count += 1;
2148                }
2149            } else if status_entry.status.is_created() {
2150                self.new_count += 1;
2151                if self.entry_staging(status_entry).has_staged() {
2152                    self.new_staged_count += 1;
2153                }
2154            } else {
2155                self.tracked_count += 1;
2156                if self.entry_staging(status_entry).has_staged() {
2157                    self.tracked_staged_count += 1;
2158                }
2159            }
2160        }
2161    }
2162
2163    fn entry_staging(&self, entry: &GitStatusEntry) -> StageStatus {
2164        for pending in self.pending.iter().rev() {
2165            if pending
2166                .entries
2167                .iter()
2168                .any(|pending_entry| pending_entry.repo_path == entry.repo_path)
2169            {
2170                match pending.target_status {
2171                    TargetStatus::Staged => return StageStatus::Staged,
2172                    TargetStatus::Unstaged => return StageStatus::Unstaged,
2173                    TargetStatus::Reverted => continue,
2174                    TargetStatus::Unchanged => continue,
2175                }
2176            }
2177        }
2178        entry.staging
2179    }
2180
2181    pub(crate) fn has_staged_changes(&self) -> bool {
2182        self.tracked_staged_count > 0
2183            || self.new_staged_count > 0
2184            || self.conflicted_staged_count > 0
2185    }
2186
2187    pub(crate) fn has_unstaged_changes(&self) -> bool {
2188        self.tracked_count > self.tracked_staged_count
2189            || self.new_count > self.new_staged_count
2190            || self.conflicted_count > self.conflicted_staged_count
2191    }
2192
2193    fn has_conflicts(&self) -> bool {
2194        self.conflicted_count > 0
2195    }
2196
2197    fn has_tracked_changes(&self) -> bool {
2198        self.tracked_count > 0
2199    }
2200
2201    pub fn has_unstaged_conflicts(&self) -> bool {
2202        self.conflicted_count > 0 && self.conflicted_count != self.conflicted_staged_count
2203    }
2204
2205    fn show_err_toast(&self, e: anyhow::Error, cx: &mut App) {
2206        let Some(workspace) = self.workspace.upgrade() else {
2207            return;
2208        };
2209        let notif_id = NotificationId::Named("git-operation-error".into());
2210
2211        let message = e.to_string().trim().to_string();
2212        let toast;
2213        if message
2214            .matches(git::repository::REMOTE_CANCELLED_BY_USER)
2215            .next()
2216            .is_some()
2217        {
2218            return; // Hide the cancelled by user message
2219        } else {
2220            toast = Toast::new(notif_id, message).on_click("Open Zed Log", |window, cx| {
2221                window.dispatch_action(workspace::OpenLog.boxed_clone(), cx);
2222            });
2223        }
2224        workspace.update(cx, |workspace, cx| {
2225            workspace.show_toast(toast, cx);
2226        });
2227    }
2228
2229    fn show_remote_output(&self, action: RemoteAction, info: RemoteCommandOutput, cx: &mut App) {
2230        let Some(workspace) = self.workspace.upgrade() else {
2231            return;
2232        };
2233
2234        let notification_id = NotificationId::Named("git-remote-info".into());
2235
2236        workspace.update(cx, |workspace, cx| {
2237            workspace.show_notification(notification_id.clone(), cx, |cx| {
2238                let workspace = cx.weak_entity();
2239                cx.new(|cx| RemoteOutputToast::new(action, info, notification_id, workspace, cx))
2240            });
2241        });
2242    }
2243
2244    pub fn render_spinner(&self) -> Option<impl IntoElement> {
2245        (!self.pending_remote_operations.borrow().is_empty()).then(|| {
2246            Icon::new(IconName::ArrowCircle)
2247                .size(IconSize::XSmall)
2248                .color(Color::Info)
2249                .with_animation(
2250                    "arrow-circle",
2251                    Animation::new(Duration::from_secs(2)).repeat(),
2252                    |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
2253                )
2254                .into_any_element()
2255        })
2256    }
2257
2258    pub fn can_commit(&self) -> bool {
2259        (self.has_staged_changes() || self.has_tracked_changes()) && !self.has_unstaged_conflicts()
2260    }
2261
2262    pub fn can_stage_all(&self) -> bool {
2263        self.has_unstaged_changes()
2264    }
2265
2266    pub fn can_unstage_all(&self) -> bool {
2267        self.has_staged_changes()
2268    }
2269
2270    pub(crate) fn render_generate_commit_message_button(
2271        &self,
2272        cx: &Context<Self>,
2273    ) -> Option<AnyElement> {
2274        current_language_model(cx).is_some().then(|| {
2275            if self.generate_commit_message_task.is_some() {
2276                return h_flex()
2277                    .gap_1()
2278                    .child(
2279                        Icon::new(IconName::ArrowCircle)
2280                            .size(IconSize::XSmall)
2281                            .color(Color::Info)
2282                            .with_animation(
2283                                "arrow-circle",
2284                                Animation::new(Duration::from_secs(2)).repeat(),
2285                                |icon, delta| {
2286                                    icon.transform(Transformation::rotate(percentage(delta)))
2287                                },
2288                            ),
2289                    )
2290                    .child(
2291                        Label::new("Generating Commit...")
2292                            .size(LabelSize::Small)
2293                            .color(Color::Muted),
2294                    )
2295                    .into_any_element();
2296            }
2297
2298            let can_commit = self.can_commit();
2299            let editor_focus_handle = self.commit_editor.focus_handle(cx);
2300            IconButton::new("generate-commit-message", IconName::AiEdit)
2301                .shape(ui::IconButtonShape::Square)
2302                .icon_color(Color::Muted)
2303                .tooltip(move |window, cx| {
2304                    if can_commit {
2305                        Tooltip::for_action_in(
2306                            "Generate Commit Message",
2307                            &git::GenerateCommitMessage,
2308                            &editor_focus_handle,
2309                            window,
2310                            cx,
2311                        )
2312                    } else {
2313                        Tooltip::simple(
2314                            "You must have either staged changes or tracked files to generate a commit message",
2315                            cx,
2316                        )
2317                    }
2318                })
2319                .disabled(!can_commit)
2320                .on_click(cx.listener(move |this, _event, _window, cx| {
2321                    this.generate_commit_message(cx);
2322                }))
2323                .into_any_element()
2324        })
2325    }
2326
2327    pub(crate) fn render_co_authors(&self, cx: &Context<Self>) -> Option<AnyElement> {
2328        let potential_co_authors = self.potential_co_authors(cx);
2329        if potential_co_authors.is_empty() {
2330            None
2331        } else {
2332            Some(
2333                IconButton::new("co-authors", IconName::Person)
2334                    .shape(ui::IconButtonShape::Square)
2335                    .icon_color(Color::Disabled)
2336                    .selected_icon_color(Color::Selected)
2337                    .toggle_state(self.add_coauthors)
2338                    .tooltip(move |_, cx| {
2339                        let title = format!(
2340                            "Add co-authored-by:{}{}",
2341                            if potential_co_authors.len() == 1 {
2342                                ""
2343                            } else {
2344                                "\n"
2345                            },
2346                            potential_co_authors
2347                                .iter()
2348                                .map(|(name, email)| format!(" {} <{}>", name, email))
2349                                .join("\n")
2350                        );
2351                        Tooltip::simple(title, cx)
2352                    })
2353                    .on_click(cx.listener(|this, _, _, cx| {
2354                        this.add_coauthors = !this.add_coauthors;
2355                        cx.notify();
2356                    }))
2357                    .into_any_element(),
2358            )
2359        }
2360    }
2361
2362    pub fn configure_commit_button(&self, cx: &mut Context<Self>) -> (bool, &'static str) {
2363        if self.has_unstaged_conflicts() {
2364            (false, "You must resolve conflicts before committing")
2365        } else if !self.has_staged_changes() && !self.has_tracked_changes() {
2366            (
2367                false,
2368                "You must have either staged changes or tracked files to commit",
2369            )
2370        } else if self.pending_commit.is_some() {
2371            (false, "Commit in progress")
2372        } else if self.custom_or_suggested_commit_message(cx).is_none() {
2373            (false, "No commit message")
2374        } else if !self.has_write_access(cx) {
2375            (false, "You do not have write access to this project")
2376        } else {
2377            (true, self.commit_button_title())
2378        }
2379    }
2380
2381    pub fn commit_button_title(&self) -> &'static str {
2382        if self.has_staged_changes() {
2383            "Commit"
2384        } else {
2385            "Commit Tracked"
2386        }
2387    }
2388
2389    fn expand_commit_editor(
2390        &mut self,
2391        _: &git::ExpandCommitEditor,
2392        window: &mut Window,
2393        cx: &mut Context<Self>,
2394    ) {
2395        let workspace = self.workspace.clone();
2396        window.defer(cx, move |window, cx| {
2397            workspace
2398                .update(cx, |workspace, cx| {
2399                    CommitModal::toggle(workspace, window, cx)
2400                })
2401                .ok();
2402        })
2403    }
2404
2405    pub fn render_footer(
2406        &self,
2407        window: &mut Window,
2408        cx: &mut Context<Self>,
2409    ) -> Option<impl IntoElement> {
2410        let active_repository = self.active_repository.clone()?;
2411        let (can_commit, tooltip) = self.configure_commit_button(cx);
2412        let project = self.project.clone().read(cx);
2413        let panel_editor_style = panel_editor_style(true, window, cx);
2414
2415        let enable_coauthors = self.render_co_authors(cx);
2416        let title = self.commit_button_title();
2417
2418        let editor_focus_handle = self.commit_editor.focus_handle(cx);
2419        let commit_tooltip_focus_handle = editor_focus_handle.clone();
2420        let expand_tooltip_focus_handle = editor_focus_handle.clone();
2421
2422        let branch = active_repository.read(cx).current_branch().cloned();
2423
2424        let footer_size = px(32.);
2425        let gap = px(8.0);
2426        let max_height = window.line_height() * 5. + gap + footer_size;
2427
2428        let git_panel = cx.entity().clone();
2429        let display_name = SharedString::from(Arc::from(
2430            active_repository
2431                .read(cx)
2432                .display_name(project, cx)
2433                .trim_end_matches("/"),
2434        ));
2435
2436        let footer = v_flex()
2437            .child(PanelRepoFooter::new(
2438                "footer-button",
2439                display_name,
2440                branch,
2441                Some(git_panel),
2442            ))
2443            .child(
2444                panel_editor_container(window, cx)
2445                    .id("commit-editor-container")
2446                    .relative()
2447                    .h(max_height)
2448                    .w_full()
2449                    .border_t_1()
2450                    .border_color(cx.theme().colors().border_variant)
2451                    .bg(cx.theme().colors().editor_background)
2452                    .cursor_text()
2453                    .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
2454                        window.focus(&this.commit_editor.focus_handle(cx));
2455                    }))
2456                    .child(
2457                        h_flex()
2458                            .id("commit-footer")
2459                            .absolute()
2460                            .bottom_0()
2461                            .left_0()
2462                            .w_full()
2463                            .px_2()
2464                            .h(footer_size)
2465                            .flex_none()
2466                            .justify_between()
2467                            .child(
2468                                self.render_generate_commit_message_button(cx)
2469                                    .unwrap_or_else(|| div().into_any_element()),
2470                            )
2471                            .child(
2472                                h_flex().gap_0p5().children(enable_coauthors).child(
2473                                    panel_filled_button(title)
2474                                        .tooltip(move |window, cx| {
2475                                            if can_commit {
2476                                                Tooltip::for_action_in(
2477                                                    tooltip,
2478                                                    &Commit,
2479                                                    &commit_tooltip_focus_handle,
2480                                                    window,
2481                                                    cx,
2482                                                )
2483                                            } else {
2484                                                Tooltip::simple(tooltip, cx)
2485                                            }
2486                                        })
2487                                        .disabled(!can_commit || self.modal_open)
2488                                        .on_click({
2489                                            cx.listener(move |this, _: &ClickEvent, window, cx| {
2490                                                this.commit_changes(window, cx)
2491                                            })
2492                                        }),
2493                                ),
2494                            ),
2495                    )
2496                    .child(
2497                        div()
2498                            .pr_2p5()
2499                            .child(EditorElement::new(&self.commit_editor, panel_editor_style)),
2500                    )
2501                    .child(
2502                        h_flex()
2503                            .absolute()
2504                            .top_2()
2505                            .right_2()
2506                            .opacity(0.5)
2507                            .hover(|this| this.opacity(1.0))
2508                            .child(
2509                                panel_icon_button("expand-commit-editor", IconName::Maximize)
2510                                    .icon_size(IconSize::Small)
2511                                    .size(ui::ButtonSize::Default)
2512                                    .tooltip(move |window, cx| {
2513                                        Tooltip::for_action_in(
2514                                            "Open Commit Modal",
2515                                            &git::ExpandCommitEditor,
2516                                            &expand_tooltip_focus_handle,
2517                                            window,
2518                                            cx,
2519                                        )
2520                                    })
2521                                    .on_click(cx.listener({
2522                                        move |_, _, window, cx| {
2523                                            window.dispatch_action(
2524                                                git::ExpandCommitEditor.boxed_clone(),
2525                                                cx,
2526                                            )
2527                                        }
2528                                    })),
2529                            ),
2530                    ),
2531            );
2532
2533        Some(footer)
2534    }
2535
2536    fn render_previous_commit(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
2537        let active_repository = self.active_repository.as_ref()?;
2538        let branch = active_repository.read(cx).current_branch()?;
2539        let commit = branch.most_recent_commit.as_ref()?.clone();
2540
2541        let this = cx.entity();
2542        Some(
2543            h_flex()
2544                .items_center()
2545                .py_2()
2546                .px(px(8.))
2547                // .bg(cx.theme().colors().background)
2548                // .border_t_1()
2549                .border_color(cx.theme().colors().border)
2550                .gap_1p5()
2551                .child(
2552                    div()
2553                        .flex_grow()
2554                        .overflow_hidden()
2555                        .max_w(relative(0.6))
2556                        .h_full()
2557                        .child(
2558                            Label::new(commit.subject.clone())
2559                                .size(LabelSize::Small)
2560                                .truncate(),
2561                        )
2562                        .id("commit-msg-hover")
2563                        .hoverable_tooltip(move |window, cx| {
2564                            GitPanelMessageTooltip::new(
2565                                this.clone(),
2566                                commit.sha.clone(),
2567                                window,
2568                                cx,
2569                            )
2570                            .into()
2571                        }),
2572                )
2573                .child(div().flex_1())
2574                .child(
2575                    panel_icon_button("undo", IconName::Undo)
2576                        .icon_size(IconSize::Small)
2577                        .icon_color(Color::Muted)
2578                        .tooltip(Tooltip::for_action_title(
2579                            if self.has_staged_changes() {
2580                                "git reset HEAD^ --soft"
2581                            } else {
2582                                "git reset HEAD^"
2583                            },
2584                            &git::Uncommit,
2585                        ))
2586                        .on_click(cx.listener(|this, _, window, cx| this.uncommit(window, cx))),
2587                ),
2588        )
2589    }
2590
2591    fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
2592        h_flex()
2593            .h_full()
2594            .flex_grow()
2595            .justify_center()
2596            .items_center()
2597            .child(
2598                v_flex()
2599                    .gap_3()
2600                    .child(if self.active_repository.is_some() {
2601                        "No changes to commit"
2602                    } else {
2603                        "No Git repositories"
2604                    })
2605                    .text_ui_sm(cx)
2606                    .mx_auto()
2607                    .text_color(Color::Placeholder.color(cx)),
2608            )
2609    }
2610
2611    fn render_scrollbar(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
2612        let scroll_bar_style = self.show_scrollbar(cx);
2613        let show_container = matches!(scroll_bar_style, ShowScrollbar::Always);
2614
2615        if !self.should_show_scrollbar(cx)
2616            || !(self.show_scrollbar || self.scrollbar_state.is_dragging())
2617        {
2618            return None;
2619        }
2620
2621        Some(
2622            div()
2623                .id("git-panel-vertical-scroll")
2624                .occlude()
2625                .flex_none()
2626                .h_full()
2627                .cursor_default()
2628                .when(show_container, |this| this.pl_1().px_1p5())
2629                .when(!show_container, |this| {
2630                    this.absolute().right_1().top_1().bottom_1().w(px(12.))
2631                })
2632                .on_mouse_move(cx.listener(|_, _, _, cx| {
2633                    cx.notify();
2634                    cx.stop_propagation()
2635                }))
2636                .on_hover(|_, _, cx| {
2637                    cx.stop_propagation();
2638                })
2639                .on_any_mouse_down(|_, _, cx| {
2640                    cx.stop_propagation();
2641                })
2642                .on_mouse_up(
2643                    MouseButton::Left,
2644                    cx.listener(|this, _, window, cx| {
2645                        if !this.scrollbar_state.is_dragging()
2646                            && !this.focus_handle.contains_focused(window, cx)
2647                        {
2648                            this.hide_scrollbar(window, cx);
2649                            cx.notify();
2650                        }
2651
2652                        cx.stop_propagation();
2653                    }),
2654                )
2655                .on_scroll_wheel(cx.listener(|_, _, _, cx| {
2656                    cx.notify();
2657                }))
2658                .children(Scrollbar::vertical(
2659                    // percentage as f32..end_offset as f32,
2660                    self.scrollbar_state.clone(),
2661                )),
2662        )
2663    }
2664
2665    fn render_buffer_header_controls(
2666        &self,
2667        entity: &Entity<Self>,
2668        file: &Arc<dyn File>,
2669        _: &Window,
2670        cx: &App,
2671    ) -> Option<AnyElement> {
2672        let repo = self.active_repository.as_ref()?.read(cx);
2673        let repo_path = repo.worktree_id_path_to_repo_path(file.worktree_id(cx), file.path())?;
2674        let ix = self.entry_by_path(&repo_path)?;
2675        let entry = self.entries.get(ix)?;
2676
2677        let entry_staging = self.entry_staging(entry.status_entry()?);
2678
2679        let checkbox = Checkbox::new("stage-file", entry_staging.as_bool().into())
2680            .disabled(!self.has_write_access(cx))
2681            .fill()
2682            .elevation(ElevationIndex::Surface)
2683            .on_click({
2684                let entry = entry.clone();
2685                let git_panel = entity.downgrade();
2686                move |_, window, cx| {
2687                    git_panel
2688                        .update(cx, |this, cx| {
2689                            this.toggle_staged_for_entry(&entry, window, cx);
2690                            cx.stop_propagation();
2691                        })
2692                        .ok();
2693                }
2694            });
2695        Some(
2696            h_flex()
2697                .id("start-slot")
2698                .text_lg()
2699                .child(checkbox)
2700                .on_mouse_down(MouseButton::Left, |_, _, cx| {
2701                    // prevent the list item active state triggering when toggling checkbox
2702                    cx.stop_propagation();
2703                })
2704                .into_any_element(),
2705        )
2706    }
2707
2708    fn render_entries(
2709        &self,
2710        has_write_access: bool,
2711        _: &Window,
2712        cx: &mut Context<Self>,
2713    ) -> impl IntoElement {
2714        let entry_count = self.entries.len();
2715
2716        h_flex()
2717            .size_full()
2718            .flex_grow()
2719            .overflow_hidden()
2720            .child(
2721                uniform_list(cx.entity().clone(), "entries", entry_count, {
2722                    move |this, range, window, cx| {
2723                        let mut items = Vec::with_capacity(range.end - range.start);
2724
2725                        for ix in range {
2726                            match &this.entries.get(ix) {
2727                                Some(GitListEntry::GitStatusEntry(entry)) => {
2728                                    items.push(this.render_entry(
2729                                        ix,
2730                                        entry,
2731                                        has_write_access,
2732                                        window,
2733                                        cx,
2734                                    ));
2735                                }
2736                                Some(GitListEntry::Header(header)) => {
2737                                    items.push(this.render_list_header(
2738                                        ix,
2739                                        header,
2740                                        has_write_access,
2741                                        window,
2742                                        cx,
2743                                    ));
2744                                }
2745                                None => {}
2746                            }
2747                        }
2748
2749                        items
2750                    }
2751                })
2752                .size_full()
2753                .with_sizing_behavior(ListSizingBehavior::Auto)
2754                .with_horizontal_sizing_behavior(ListHorizontalSizingBehavior::Unconstrained)
2755                .track_scroll(self.scroll_handle.clone()),
2756            )
2757            .on_mouse_down(
2758                MouseButton::Right,
2759                cx.listener(move |this, event: &MouseDownEvent, window, cx| {
2760                    this.deploy_panel_context_menu(event.position, window, cx)
2761                }),
2762            )
2763            .children(self.render_scrollbar(cx))
2764    }
2765
2766    fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
2767        Label::new(label.into()).color(color).single_line()
2768    }
2769
2770    fn list_item_height(&self) -> Rems {
2771        rems(1.75)
2772    }
2773
2774    fn render_list_header(
2775        &self,
2776        ix: usize,
2777        header: &GitHeaderEntry,
2778        _: bool,
2779        _: &Window,
2780        _: &Context<Self>,
2781    ) -> AnyElement {
2782        let id: ElementId = ElementId::Name(format!("header_{}", ix).into());
2783
2784        h_flex()
2785            .id(id)
2786            .h(self.list_item_height())
2787            .w_full()
2788            .items_end()
2789            .px(rems(0.75)) // ~12px
2790            .pb(rems(0.3125)) // ~ 5px
2791            .child(
2792                Label::new(header.title())
2793                    .color(Color::Muted)
2794                    .size(LabelSize::Small)
2795                    .line_height_style(LineHeightStyle::UiLabel)
2796                    .single_line(),
2797            )
2798            .into_any_element()
2799    }
2800
2801    fn load_commit_details(
2802        &self,
2803        sha: &str,
2804        cx: &mut Context<Self>,
2805    ) -> Task<anyhow::Result<CommitDetails>> {
2806        let Some(repo) = self.active_repository.clone() else {
2807            return Task::ready(Err(anyhow::anyhow!("no active repo")));
2808        };
2809        repo.update(cx, |repo, cx| {
2810            let show = repo.show(sha);
2811            cx.spawn(|_, _| async move { show.await? })
2812        })
2813    }
2814
2815    fn deploy_entry_context_menu(
2816        &mut self,
2817        position: Point<Pixels>,
2818        ix: usize,
2819        window: &mut Window,
2820        cx: &mut Context<Self>,
2821    ) {
2822        let Some(entry) = self.entries.get(ix).and_then(|e| e.status_entry()) else {
2823            return;
2824        };
2825        let stage_title = if entry.status.staging().is_fully_staged() {
2826            "Unstage File"
2827        } else {
2828            "Stage File"
2829        };
2830        let restore_title = if entry.status.is_created() {
2831            "Trash File"
2832        } else {
2833            "Restore File"
2834        };
2835        let context_menu = ContextMenu::build(window, cx, |context_menu, _, _| {
2836            context_menu
2837                .action(stage_title, ToggleStaged.boxed_clone())
2838                .action(restore_title, git::RestoreFile.boxed_clone())
2839                .separator()
2840                .action("Open Diff", Confirm.boxed_clone())
2841                .action("Open File", SecondaryConfirm.boxed_clone())
2842        });
2843        self.selected_entry = Some(ix);
2844        self.set_context_menu(context_menu, position, window, cx);
2845    }
2846
2847    fn deploy_panel_context_menu(
2848        &mut self,
2849        position: Point<Pixels>,
2850        window: &mut Window,
2851        cx: &mut Context<Self>,
2852    ) {
2853        let context_menu = git_panel_context_menu(window, cx);
2854        self.set_context_menu(context_menu, position, window, cx);
2855    }
2856
2857    fn set_context_menu(
2858        &mut self,
2859        context_menu: Entity<ContextMenu>,
2860        position: Point<Pixels>,
2861        window: &Window,
2862        cx: &mut Context<Self>,
2863    ) {
2864        let subscription = cx.subscribe_in(
2865            &context_menu,
2866            window,
2867            |this, _, _: &DismissEvent, window, cx| {
2868                if this.context_menu.as_ref().is_some_and(|context_menu| {
2869                    context_menu.0.focus_handle(cx).contains_focused(window, cx)
2870                }) {
2871                    cx.focus_self(window);
2872                }
2873                this.context_menu.take();
2874                cx.notify();
2875            },
2876        );
2877        self.context_menu = Some((context_menu, position, subscription));
2878        cx.notify();
2879    }
2880
2881    fn render_entry(
2882        &self,
2883        ix: usize,
2884        entry: &GitStatusEntry,
2885        has_write_access: bool,
2886        window: &Window,
2887        cx: &Context<Self>,
2888    ) -> AnyElement {
2889        let display_name = entry
2890            .worktree_path
2891            .file_name()
2892            .map(|name| name.to_string_lossy().into_owned())
2893            .unwrap_or_else(|| entry.worktree_path.to_string_lossy().into_owned());
2894
2895        let worktree_path = entry.worktree_path.clone();
2896        let selected = self.selected_entry == Some(ix);
2897        let marked = self.marked_entries.contains(&ix);
2898        let status_style = GitPanelSettings::get_global(cx).status_style;
2899        let status = entry.status;
2900        let has_conflict = status.is_conflicted();
2901        let is_modified = status.is_modified();
2902        let is_deleted = status.is_deleted();
2903
2904        let label_color = if status_style == StatusStyle::LabelColor {
2905            if has_conflict {
2906                Color::Conflict
2907            } else if is_modified {
2908                Color::Modified
2909            } else if is_deleted {
2910                // We don't want a bunch of red labels in the list
2911                Color::Disabled
2912            } else {
2913                Color::Created
2914            }
2915        } else {
2916            Color::Default
2917        };
2918
2919        let path_color = if status.is_deleted() {
2920            Color::Disabled
2921        } else {
2922            Color::Muted
2923        };
2924
2925        let id: ElementId = ElementId::Name(format!("entry_{}_{}", display_name, ix).into());
2926        let checkbox_wrapper_id: ElementId =
2927            ElementId::Name(format!("entry_{}_{}_checkbox_wrapper", display_name, ix).into());
2928        let checkbox_id: ElementId =
2929            ElementId::Name(format!("entry_{}_{}_checkbox", display_name, ix).into());
2930
2931        let entry_staging = self.entry_staging(entry);
2932        let mut is_staged: ToggleState = self.entry_staging(entry).as_bool().into();
2933
2934        if !self.has_staged_changes() && !self.has_conflicts() && !entry.status.is_created() {
2935            is_staged = ToggleState::Selected;
2936        }
2937
2938        let handle = cx.weak_entity();
2939
2940        let selected_bg_alpha = 0.08;
2941        let marked_bg_alpha = 0.12;
2942        let state_opacity_step = 0.04;
2943
2944        let base_bg = match (selected, marked) {
2945            (true, true) => cx
2946                .theme()
2947                .status()
2948                .info
2949                .alpha(selected_bg_alpha + marked_bg_alpha),
2950            (true, false) => cx.theme().status().info.alpha(selected_bg_alpha),
2951            (false, true) => cx.theme().status().info.alpha(marked_bg_alpha),
2952            _ => cx.theme().colors().ghost_element_background,
2953        };
2954
2955        let hover_bg = if selected {
2956            cx.theme()
2957                .status()
2958                .info
2959                .alpha(selected_bg_alpha + state_opacity_step)
2960        } else {
2961            cx.theme().colors().ghost_element_hover
2962        };
2963
2964        let active_bg = if selected {
2965            cx.theme()
2966                .status()
2967                .info
2968                .alpha(selected_bg_alpha + state_opacity_step * 2.0)
2969        } else {
2970            cx.theme().colors().ghost_element_active
2971        };
2972
2973        h_flex()
2974            .id(id)
2975            .h(self.list_item_height())
2976            .w_full()
2977            .items_center()
2978            .border_1()
2979            .when(selected && self.focus_handle.is_focused(window), |el| {
2980                el.border_color(cx.theme().colors().border_focused)
2981            })
2982            .px(rems(0.75)) // ~12px
2983            .overflow_hidden()
2984            .flex_none()
2985            .gap(DynamicSpacing::Base04.rems(cx))
2986            .bg(base_bg)
2987            .hover(|this| this.bg(hover_bg))
2988            .active(|this| this.bg(active_bg))
2989            .on_click({
2990                cx.listener(move |this, event: &ClickEvent, window, cx| {
2991                    this.selected_entry = Some(ix);
2992                    cx.notify();
2993                    if event.modifiers().secondary() {
2994                        this.open_file(&Default::default(), window, cx)
2995                    } else {
2996                        this.open_diff(&Default::default(), window, cx);
2997                        this.focus_handle.focus(window);
2998                    }
2999                })
3000            })
3001            .on_mouse_down(
3002                MouseButton::Right,
3003                move |event: &MouseDownEvent, window, cx| {
3004                    // why isn't this happening automatically? we are passing MouseButton::Right to `on_mouse_down`?
3005                    if event.button != MouseButton::Right {
3006                        return;
3007                    }
3008
3009                    let Some(this) = handle.upgrade() else {
3010                        return;
3011                    };
3012                    this.update(cx, |this, cx| {
3013                        this.deploy_entry_context_menu(event.position, ix, window, cx);
3014                    });
3015                    cx.stop_propagation();
3016                },
3017            )
3018            // .on_secondary_mouse_down(cx.listener(
3019            //     move |this, event: &MouseDownEvent, window, cx| {
3020            //         this.deploy_entry_context_menu(event.position, ix, window, cx);
3021            //         cx.stop_propagation();
3022            //     },
3023            // ))
3024            .child(
3025                div()
3026                    .id(checkbox_wrapper_id)
3027                    .flex_none()
3028                    .occlude()
3029                    .cursor_pointer()
3030                    .child(
3031                        Checkbox::new(checkbox_id, is_staged)
3032                            .disabled(!has_write_access)
3033                            .fill()
3034                            .placeholder(!self.has_staged_changes() && !self.has_conflicts())
3035                            .elevation(ElevationIndex::Surface)
3036                            .on_click({
3037                                let entry = entry.clone();
3038                                cx.listener(move |this, _, window, cx| {
3039                                    if !has_write_access {
3040                                        return;
3041                                    }
3042                                    this.toggle_staged_for_entry(
3043                                        &GitListEntry::GitStatusEntry(entry.clone()),
3044                                        window,
3045                                        cx,
3046                                    );
3047                                    cx.stop_propagation();
3048                                })
3049                            })
3050                            .tooltip(move |window, cx| {
3051                                let tooltip_name = if entry_staging.is_fully_staged() {
3052                                    "Unstage"
3053                                } else {
3054                                    "Stage"
3055                                };
3056
3057                                Tooltip::for_action(tooltip_name, &ToggleStaged, window, cx)
3058                            }),
3059                    ),
3060            )
3061            .child(git_status_icon(status, cx))
3062            .child(
3063                h_flex()
3064                    .items_center()
3065                    .overflow_hidden()
3066                    .when_some(worktree_path.parent(), |this, parent| {
3067                        let parent_str = parent.to_string_lossy();
3068                        if !parent_str.is_empty() {
3069                            this.child(
3070                                self.entry_label(format!("{}/", parent_str), path_color)
3071                                    .when(status.is_deleted(), |this| this.strikethrough()),
3072                            )
3073                        } else {
3074                            this
3075                        }
3076                    })
3077                    .child(
3078                        self.entry_label(display_name.clone(), label_color)
3079                            .when(status.is_deleted(), |this| this.strikethrough()),
3080                    ),
3081            )
3082            .into_any_element()
3083    }
3084
3085    fn has_write_access(&self, cx: &App) -> bool {
3086        !self.project.read(cx).is_read_only(cx)
3087    }
3088}
3089
3090fn current_language_model(cx: &Context<'_, GitPanel>) -> Option<Arc<dyn LanguageModel>> {
3091    let provider = LanguageModelRegistry::read_global(cx).active_provider()?;
3092    let model = LanguageModelRegistry::read_global(cx).active_model()?;
3093    provider.is_authenticated(cx).then(|| model)
3094}
3095
3096impl Render for GitPanel {
3097    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3098        let project = self.project.read(cx);
3099        let has_entries = self.entries.len() > 0;
3100        let room = self
3101            .workspace
3102            .upgrade()
3103            .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned());
3104
3105        let has_write_access = self.has_write_access(cx);
3106
3107        let has_co_authors = room.map_or(false, |room| {
3108            room.read(cx)
3109                .remote_participants()
3110                .values()
3111                .any(|remote_participant| remote_participant.can_write())
3112        });
3113
3114        v_flex()
3115            .id("git_panel")
3116            .key_context(self.dispatch_context(window, cx))
3117            .track_focus(&self.focus_handle)
3118            .on_modifiers_changed(cx.listener(Self::handle_modifiers_changed))
3119            .when(has_write_access && !project.is_read_only(cx), |this| {
3120                this.on_action(cx.listener(|this, &ToggleStaged, window, cx| {
3121                    this.toggle_staged_for_selected(&ToggleStaged, window, cx)
3122                }))
3123                .on_action(cx.listener(GitPanel::commit))
3124            })
3125            .on_action(cx.listener(Self::select_first))
3126            .on_action(cx.listener(Self::select_next))
3127            .on_action(cx.listener(Self::select_previous))
3128            .on_action(cx.listener(Self::select_last))
3129            .on_action(cx.listener(Self::close_panel))
3130            .on_action(cx.listener(Self::open_diff))
3131            .on_action(cx.listener(Self::open_file))
3132            .on_action(cx.listener(Self::revert_selected))
3133            .on_action(cx.listener(Self::focus_changes_list))
3134            .on_action(cx.listener(Self::focus_editor))
3135            .on_action(cx.listener(Self::toggle_staged_for_selected))
3136            .on_action(cx.listener(Self::stage_all))
3137            .on_action(cx.listener(Self::unstage_all))
3138            .on_action(cx.listener(Self::restore_tracked_files))
3139            .on_action(cx.listener(Self::clean_all))
3140            .on_action(cx.listener(Self::expand_commit_editor))
3141            .on_action(cx.listener(Self::generate_commit_message_action))
3142            .when(has_write_access && has_co_authors, |git_panel| {
3143                git_panel.on_action(cx.listener(Self::toggle_fill_co_authors))
3144            })
3145            // .on_action(cx.listener(|this, &OpenSelected, cx| this.open_selected(&OpenSelected, cx)))
3146            .on_hover(cx.listener(|this, hovered, window, cx| {
3147                if *hovered {
3148                    this.show_scrollbar = true;
3149                    this.hide_scrollbar_task.take();
3150                    cx.notify();
3151                } else if !this.focus_handle.contains_focused(window, cx) {
3152                    this.hide_scrollbar(window, cx);
3153                }
3154            }))
3155            .size_full()
3156            .overflow_hidden()
3157            .bg(ElevationIndex::Surface.bg(cx))
3158            .child(
3159                v_flex()
3160                    .size_full()
3161                    .map(|this| {
3162                        if has_entries {
3163                            this.child(self.render_entries(has_write_access, window, cx))
3164                        } else {
3165                            this.child(self.render_empty_state(cx).into_any_element())
3166                        }
3167                    })
3168                    .children(self.render_footer(window, cx))
3169                    .children(self.render_previous_commit(cx))
3170                    .into_any_element(),
3171            )
3172            .children(self.context_menu.as_ref().map(|(menu, position, _)| {
3173                deferred(
3174                    anchored()
3175                        .position(*position)
3176                        .anchor(gpui::Corner::TopLeft)
3177                        .child(menu.clone()),
3178                )
3179                .with_priority(1)
3180            }))
3181    }
3182}
3183
3184impl Focusable for GitPanel {
3185    fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
3186        self.focus_handle.clone()
3187    }
3188}
3189
3190impl EventEmitter<Event> for GitPanel {}
3191
3192impl EventEmitter<PanelEvent> for GitPanel {}
3193
3194pub(crate) struct GitPanelAddon {
3195    pub(crate) workspace: WeakEntity<Workspace>,
3196}
3197
3198impl editor::Addon for GitPanelAddon {
3199    fn to_any(&self) -> &dyn std::any::Any {
3200        self
3201    }
3202
3203    fn render_buffer_header_controls(
3204        &self,
3205        excerpt_info: &ExcerptInfo,
3206        window: &Window,
3207        cx: &App,
3208    ) -> Option<AnyElement> {
3209        let file = excerpt_info.buffer.file()?;
3210        let git_panel = self.workspace.upgrade()?.read(cx).panel::<GitPanel>(cx)?;
3211
3212        git_panel
3213            .read(cx)
3214            .render_buffer_header_controls(&git_panel, &file, window, cx)
3215    }
3216}
3217
3218impl Panel for GitPanel {
3219    fn persistent_name() -> &'static str {
3220        "GitPanel"
3221    }
3222
3223    fn position(&self, _: &Window, cx: &App) -> DockPosition {
3224        GitPanelSettings::get_global(cx).dock
3225    }
3226
3227    fn position_is_valid(&self, position: DockPosition) -> bool {
3228        matches!(position, DockPosition::Left | DockPosition::Right)
3229    }
3230
3231    fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
3232        settings::update_settings_file::<GitPanelSettings>(
3233            self.fs.clone(),
3234            cx,
3235            move |settings, _| settings.dock = Some(position),
3236        );
3237    }
3238
3239    fn size(&self, _: &Window, cx: &App) -> Pixels {
3240        self.width
3241            .unwrap_or_else(|| GitPanelSettings::get_global(cx).default_width)
3242    }
3243
3244    fn set_size(&mut self, size: Option<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
3245        self.width = size;
3246        self.serialize(cx);
3247        cx.notify();
3248    }
3249
3250    fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
3251        Some(ui::IconName::GitBranchSmall).filter(|_| GitPanelSettings::get_global(cx).button)
3252    }
3253
3254    fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
3255        Some("Git Panel")
3256    }
3257
3258    fn toggle_action(&self) -> Box<dyn Action> {
3259        Box::new(ToggleFocus)
3260    }
3261
3262    fn activation_priority(&self) -> u32 {
3263        2
3264    }
3265}
3266
3267impl PanelHeader for GitPanel {}
3268
3269struct GitPanelMessageTooltip {
3270    commit_tooltip: Option<Entity<CommitTooltip>>,
3271}
3272
3273impl GitPanelMessageTooltip {
3274    fn new(
3275        git_panel: Entity<GitPanel>,
3276        sha: SharedString,
3277        window: &mut Window,
3278        cx: &mut App,
3279    ) -> Entity<Self> {
3280        cx.new(|cx| {
3281            cx.spawn_in(window, |this, mut cx| async move {
3282                let details = git_panel
3283                    .update(&mut cx, |git_panel, cx| {
3284                        git_panel.load_commit_details(&sha, cx)
3285                    })?
3286                    .await?;
3287
3288                let commit_details = editor::commit_tooltip::CommitDetails {
3289                    sha: details.sha.clone(),
3290                    committer_name: details.committer_name.clone(),
3291                    committer_email: details.committer_email.clone(),
3292                    commit_time: OffsetDateTime::from_unix_timestamp(details.commit_timestamp)?,
3293                    message: Some(editor::commit_tooltip::ParsedCommitMessage {
3294                        message: details.message.clone(),
3295                        ..Default::default()
3296                    }),
3297                };
3298
3299                this.update_in(&mut cx, |this: &mut GitPanelMessageTooltip, window, cx| {
3300                    this.commit_tooltip =
3301                        Some(cx.new(move |cx| CommitTooltip::new(commit_details, window, cx)));
3302                    cx.notify();
3303                })
3304            })
3305            .detach();
3306
3307            Self {
3308                commit_tooltip: None,
3309            }
3310        })
3311    }
3312}
3313
3314impl Render for GitPanelMessageTooltip {
3315    fn render(&mut self, _window: &mut Window, _cx: &mut Context<'_, Self>) -> impl IntoElement {
3316        if let Some(commit_tooltip) = &self.commit_tooltip {
3317            commit_tooltip.clone().into_any_element()
3318        } else {
3319            gpui::Empty.into_any_element()
3320        }
3321    }
3322}
3323
3324#[derive(IntoElement, IntoComponent)]
3325#[component(scope = "Version Control")]
3326pub struct PanelRepoFooter {
3327    id: SharedString,
3328    active_repository: SharedString,
3329    branch: Option<Branch>,
3330    // Getting a GitPanel in previews will be difficult.
3331    //
3332    // For now just take an option here, and we won't bind handlers to buttons in previews.
3333    git_panel: Option<Entity<GitPanel>>,
3334}
3335
3336impl PanelRepoFooter {
3337    pub fn new(
3338        id: impl Into<SharedString>,
3339        active_repository: SharedString,
3340        branch: Option<Branch>,
3341        git_panel: Option<Entity<GitPanel>>,
3342    ) -> Self {
3343        Self {
3344            id: id.into(),
3345            active_repository,
3346            branch,
3347            git_panel,
3348        }
3349    }
3350
3351    pub fn new_preview(
3352        id: impl Into<SharedString>,
3353        active_repository: SharedString,
3354        branch: Option<Branch>,
3355    ) -> Self {
3356        Self {
3357            id: id.into(),
3358            active_repository,
3359            branch,
3360            git_panel: None,
3361        }
3362    }
3363
3364    fn render_overflow_menu(&self, id: impl Into<ElementId>) -> impl IntoElement {
3365        PopoverMenu::new(id.into())
3366            .trigger(
3367                IconButton::new("overflow-menu-trigger", IconName::EllipsisVertical)
3368                    .icon_size(IconSize::Small)
3369                    .icon_color(Color::Muted),
3370            )
3371            .menu(move |window, cx| Some(git_panel_context_menu(window, cx)))
3372            .anchor(Corner::TopRight)
3373    }
3374}
3375
3376impl RenderOnce for PanelRepoFooter {
3377    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
3378        let active_repo = self.active_repository.clone();
3379        let overflow_menu_id: SharedString = format!("overflow-menu-{}", active_repo).into();
3380        let repo_selector_trigger = Button::new("repo-selector", active_repo)
3381            .style(ButtonStyle::Transparent)
3382            .size(ButtonSize::None)
3383            .label_size(LabelSize::Small)
3384            .color(Color::Muted);
3385
3386        let project = self
3387            .git_panel
3388            .as_ref()
3389            .map(|panel| panel.read(cx).project.clone());
3390
3391        let repo = self
3392            .git_panel
3393            .as_ref()
3394            .and_then(|panel| panel.read(cx).active_repository.clone());
3395
3396        let single_repo = project
3397            .as_ref()
3398            .map(|project| {
3399                filtered_repository_entries(project.read(cx).git_store().read(cx), cx).len() == 1
3400            })
3401            .unwrap_or(true);
3402
3403        let repo_selector = PopoverMenu::new("repository-switcher")
3404            .menu({
3405                let project = project.clone();
3406                move |window, cx| {
3407                    let project = project.clone()?;
3408                    Some(cx.new(|cx| RepositorySelector::new(project, window, cx)))
3409                }
3410            })
3411            .trigger_with_tooltip(
3412                repo_selector_trigger.disabled(single_repo).truncate(true),
3413                Tooltip::text("Switch active repository"),
3414            )
3415            .attach(gpui::Corner::BottomLeft)
3416            .into_any_element();
3417
3418        let branch = self.branch.clone();
3419        let branch_name = branch
3420            .as_ref()
3421            .map_or(" (no branch)".into(), |branch| branch.name.clone());
3422
3423        let branch_selector_button = Button::new("branch-selector", branch_name)
3424            .style(ButtonStyle::Transparent)
3425            .size(ButtonSize::None)
3426            .label_size(LabelSize::Small)
3427            .truncate(true)
3428            .tooltip(Tooltip::for_action_title(
3429                "Switch Branch",
3430                &zed_actions::git::Branch,
3431            ))
3432            .on_click(|_, window, cx| {
3433                window.dispatch_action(zed_actions::git::Branch.boxed_clone(), cx);
3434            });
3435
3436        let branch_selector = PopoverMenu::new("popover-button")
3437            .menu(move |window, cx| Some(branch_picker::popover(repo.clone(), window, cx)))
3438            .trigger_with_tooltip(
3439                branch_selector_button,
3440                Tooltip::for_action_title("Switch Branch", &zed_actions::git::Branch),
3441            )
3442            .anchor(Corner::TopLeft)
3443            .offset(gpui::Point {
3444                x: px(0.0),
3445                y: px(-2.0),
3446            });
3447
3448        let spinner = self
3449            .git_panel
3450            .as_ref()
3451            .and_then(|git_panel| git_panel.read(cx).render_spinner());
3452
3453        h_flex()
3454            .w_full()
3455            .px_2()
3456            .h(px(36.))
3457            .items_center()
3458            .justify_between()
3459            .child(
3460                h_flex()
3461                    .flex_1()
3462                    .overflow_hidden()
3463                    .items_center()
3464                    .child(
3465                        div().child(
3466                            Icon::new(IconName::GitBranchSmall)
3467                                .size(IconSize::Small)
3468                                .color(Color::Muted),
3469                        ),
3470                    )
3471                    .child(repo_selector)
3472                    .when_some(branch.clone(), |this, _| {
3473                        this.child(
3474                            div()
3475                                .text_color(cx.theme().colors().text_muted)
3476                                .text_sm()
3477                                .child("/"),
3478                        )
3479                    })
3480                    .child(branch_selector),
3481            )
3482            .child(
3483                h_flex()
3484                    .gap_1()
3485                    .flex_shrink_0()
3486                    .children(spinner)
3487                    .child(self.render_overflow_menu(overflow_menu_id))
3488                    .when_some(branch, |this, branch| {
3489                        let mut focus_handle = None;
3490                        if let Some(git_panel) = self.git_panel.as_ref() {
3491                            if !git_panel.read(cx).can_push_and_pull(cx) {
3492                                return this;
3493                            }
3494                            focus_handle = Some(git_panel.focus_handle(cx));
3495                        }
3496
3497                        this.children(render_remote_button(
3498                            self.id.clone(),
3499                            &branch,
3500                            focus_handle,
3501                            true,
3502                        ))
3503                    }),
3504            )
3505    }
3506}
3507
3508impl ComponentPreview for PanelRepoFooter {
3509    fn preview(_window: &mut Window, _cx: &mut App) -> AnyElement {
3510        let unknown_upstream = None;
3511        let no_remote_upstream = Some(UpstreamTracking::Gone);
3512        let ahead_of_upstream = Some(
3513            UpstreamTrackingStatus {
3514                ahead: 2,
3515                behind: 0,
3516            }
3517            .into(),
3518        );
3519        let behind_upstream = Some(
3520            UpstreamTrackingStatus {
3521                ahead: 0,
3522                behind: 2,
3523            }
3524            .into(),
3525        );
3526        let ahead_and_behind_upstream = Some(
3527            UpstreamTrackingStatus {
3528                ahead: 3,
3529                behind: 1,
3530            }
3531            .into(),
3532        );
3533
3534        let not_ahead_or_behind_upstream = Some(
3535            UpstreamTrackingStatus {
3536                ahead: 0,
3537                behind: 0,
3538            }
3539            .into(),
3540        );
3541
3542        fn branch(upstream: Option<UpstreamTracking>) -> Branch {
3543            Branch {
3544                is_head: true,
3545                name: "some-branch".into(),
3546                upstream: upstream.map(|tracking| Upstream {
3547                    ref_name: "origin/some-branch".into(),
3548                    tracking,
3549                }),
3550                most_recent_commit: Some(CommitSummary {
3551                    sha: "abc123".into(),
3552                    subject: "Modify stuff".into(),
3553                    commit_timestamp: 1710932954,
3554                }),
3555            }
3556        }
3557
3558        fn custom(branch_name: &str, upstream: Option<UpstreamTracking>) -> Branch {
3559            Branch {
3560                is_head: true,
3561                name: branch_name.to_string().into(),
3562                upstream: upstream.map(|tracking| Upstream {
3563                    ref_name: format!("zed/{}", branch_name).into(),
3564                    tracking,
3565                }),
3566                most_recent_commit: Some(CommitSummary {
3567                    sha: "abc123".into(),
3568                    subject: "Modify stuff".into(),
3569                    commit_timestamp: 1710932954,
3570                }),
3571            }
3572        }
3573
3574        fn active_repository(id: usize) -> SharedString {
3575            format!("repo-{}", id).into()
3576        }
3577
3578        let example_width = px(340.);
3579
3580        v_flex()
3581            .gap_6()
3582            .w_full()
3583            .flex_none()
3584            .children(vec![example_group_with_title(
3585                "Action Button States",
3586                vec![
3587                    single_example(
3588                        "No Branch",
3589                        div()
3590                            .w(example_width)
3591                            .overflow_hidden()
3592                            .child(PanelRepoFooter::new_preview(
3593                                "no-branch",
3594                                active_repository(1).clone(),
3595                                None,
3596                            ))
3597                            .into_any_element(),
3598                    )
3599                    .grow(),
3600                    single_example(
3601                        "Remote status unknown",
3602                        div()
3603                            .w(example_width)
3604                            .overflow_hidden()
3605                            .child(PanelRepoFooter::new_preview(
3606                                "unknown-upstream",
3607                                active_repository(2).clone(),
3608                                Some(branch(unknown_upstream)),
3609                            ))
3610                            .into_any_element(),
3611                    )
3612                    .grow(),
3613                    single_example(
3614                        "No Remote Upstream",
3615                        div()
3616                            .w(example_width)
3617                            .overflow_hidden()
3618                            .child(PanelRepoFooter::new_preview(
3619                                "no-remote-upstream",
3620                                active_repository(3).clone(),
3621                                Some(branch(no_remote_upstream)),
3622                            ))
3623                            .into_any_element(),
3624                    )
3625                    .grow(),
3626                    single_example(
3627                        "Not Ahead or Behind",
3628                        div()
3629                            .w(example_width)
3630                            .overflow_hidden()
3631                            .child(PanelRepoFooter::new_preview(
3632                                "not-ahead-or-behind",
3633                                active_repository(4).clone(),
3634                                Some(branch(not_ahead_or_behind_upstream)),
3635                            ))
3636                            .into_any_element(),
3637                    )
3638                    .grow(),
3639                    single_example(
3640                        "Behind remote",
3641                        div()
3642                            .w(example_width)
3643                            .overflow_hidden()
3644                            .child(PanelRepoFooter::new_preview(
3645                                "behind-remote",
3646                                active_repository(5).clone(),
3647                                Some(branch(behind_upstream)),
3648                            ))
3649                            .into_any_element(),
3650                    )
3651                    .grow(),
3652                    single_example(
3653                        "Ahead of remote",
3654                        div()
3655                            .w(example_width)
3656                            .overflow_hidden()
3657                            .child(PanelRepoFooter::new_preview(
3658                                "ahead-of-remote",
3659                                active_repository(6).clone(),
3660                                Some(branch(ahead_of_upstream)),
3661                            ))
3662                            .into_any_element(),
3663                    )
3664                    .grow(),
3665                    single_example(
3666                        "Ahead and behind remote",
3667                        div()
3668                            .w(example_width)
3669                            .overflow_hidden()
3670                            .child(PanelRepoFooter::new_preview(
3671                                "ahead-and-behind",
3672                                active_repository(7).clone(),
3673                                Some(branch(ahead_and_behind_upstream)),
3674                            ))
3675                            .into_any_element(),
3676                    )
3677                    .grow(),
3678                ],
3679            )
3680            .grow()
3681            .vertical()])
3682            .children(vec![example_group_with_title(
3683                "Labels",
3684                vec![
3685                    single_example(
3686                        "Short Branch & Repo",
3687                        div()
3688                            .w(example_width)
3689                            .overflow_hidden()
3690                            .child(PanelRepoFooter::new_preview(
3691                                "short-branch",
3692                                SharedString::from("zed"),
3693                                Some(custom("main", behind_upstream)),
3694                            ))
3695                            .into_any_element(),
3696                    )
3697                    .grow(),
3698                    single_example(
3699                        "Long Branch",
3700                        div()
3701                            .w(example_width)
3702                            .overflow_hidden()
3703                            .child(PanelRepoFooter::new_preview(
3704                                "long-branch",
3705                                SharedString::from("zed"),
3706                                Some(custom(
3707                                    "redesign-and-update-git-ui-list-entry-style",
3708                                    behind_upstream,
3709                                )),
3710                            ))
3711                            .into_any_element(),
3712                    )
3713                    .grow(),
3714                    single_example(
3715                        "Long Repo",
3716                        div()
3717                            .w(example_width)
3718                            .overflow_hidden()
3719                            .child(PanelRepoFooter::new_preview(
3720                                "long-repo",
3721                                SharedString::from("zed-industries-community-examples"),
3722                                Some(custom("gpui", ahead_of_upstream)),
3723                            ))
3724                            .into_any_element(),
3725                    )
3726                    .grow(),
3727                    single_example(
3728                        "Long Repo & Branch",
3729                        div()
3730                            .w(example_width)
3731                            .overflow_hidden()
3732                            .child(PanelRepoFooter::new_preview(
3733                                "long-repo-and-branch",
3734                                SharedString::from("zed-industries-community-examples"),
3735                                Some(custom(
3736                                    "redesign-and-update-git-ui-list-entry-style",
3737                                    behind_upstream,
3738                                )),
3739                            ))
3740                            .into_any_element(),
3741                    )
3742                    .grow(),
3743                    single_example(
3744                        "Uppercase Repo",
3745                        div()
3746                            .w(example_width)
3747                            .overflow_hidden()
3748                            .child(PanelRepoFooter::new_preview(
3749                                "uppercase-repo",
3750                                SharedString::from("LICENSES"),
3751                                Some(custom("main", ahead_of_upstream)),
3752                            ))
3753                            .into_any_element(),
3754                    )
3755                    .grow(),
3756                    single_example(
3757                        "Uppercase Branch",
3758                        div()
3759                            .w(example_width)
3760                            .overflow_hidden()
3761                            .child(PanelRepoFooter::new_preview(
3762                                "uppercase-branch",
3763                                SharedString::from("zed"),
3764                                Some(custom("update-README", behind_upstream)),
3765                            ))
3766                            .into_any_element(),
3767                    )
3768                    .grow(),
3769                ],
3770            )
3771            .grow()
3772            .vertical()])
3773            .into_any_element()
3774    }
3775}
3776
3777#[cfg(test)]
3778mod tests {
3779    use git::status::StatusCode;
3780    use gpui::TestAppContext;
3781    use project::{FakeFs, WorktreeSettings};
3782    use serde_json::json;
3783    use settings::SettingsStore;
3784    use theme::LoadThemes;
3785    use util::path;
3786
3787    use super::*;
3788
3789    fn init_test(cx: &mut gpui::TestAppContext) {
3790        if std::env::var("RUST_LOG").is_ok() {
3791            env_logger::try_init().ok();
3792        }
3793
3794        cx.update(|cx| {
3795            let settings_store = SettingsStore::test(cx);
3796            cx.set_global(settings_store);
3797            WorktreeSettings::register(cx);
3798            workspace::init_settings(cx);
3799            theme::init(LoadThemes::JustBase, cx);
3800            language::init(cx);
3801            editor::init(cx);
3802            Project::init_settings(cx);
3803            crate::init(cx);
3804        });
3805    }
3806
3807    #[gpui::test]
3808    async fn test_entry_worktree_paths(cx: &mut TestAppContext) {
3809        init_test(cx);
3810        let fs = FakeFs::new(cx.background_executor.clone());
3811        fs.insert_tree(
3812            "/root",
3813            json!({
3814                "zed": {
3815                    ".git": {},
3816                    "crates": {
3817                        "gpui": {
3818                            "gpui.rs": "fn main() {}"
3819                        },
3820                        "util": {
3821                            "util.rs": "fn do_it() {}"
3822                        }
3823                    }
3824                },
3825            }),
3826        )
3827        .await;
3828
3829        fs.set_status_for_repo_via_git_operation(
3830            Path::new(path!("/root/zed/.git")),
3831            &[
3832                (
3833                    Path::new("crates/gpui/gpui.rs"),
3834                    StatusCode::Modified.worktree(),
3835                ),
3836                (
3837                    Path::new("crates/util/util.rs"),
3838                    StatusCode::Modified.worktree(),
3839                ),
3840            ],
3841        );
3842
3843        let project =
3844            Project::test(fs.clone(), [path!("/root/zed/crates/gpui").as_ref()], cx).await;
3845        let (workspace, cx) =
3846            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
3847
3848        cx.read(|cx| {
3849            project
3850                .read(cx)
3851                .worktrees(cx)
3852                .nth(0)
3853                .unwrap()
3854                .read(cx)
3855                .as_local()
3856                .unwrap()
3857                .scan_complete()
3858        })
3859        .await;
3860
3861        cx.executor().run_until_parked();
3862
3863        let app_state = workspace.update(cx, |workspace, _| workspace.app_state().clone());
3864        let panel = cx.new_window_entity(|window, cx| {
3865            GitPanel::new(workspace.clone(), project.clone(), app_state, window, cx)
3866        });
3867
3868        let handle = cx.update_window_entity(&panel, |panel, _, _| {
3869            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
3870        });
3871        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
3872        handle.await;
3873
3874        let entries = panel.update(cx, |panel, _| panel.entries.clone());
3875        pretty_assertions::assert_eq!(
3876            entries,
3877            [
3878                GitListEntry::Header(GitHeaderEntry {
3879                    header: Section::Tracked
3880                }),
3881                GitListEntry::GitStatusEntry(GitStatusEntry {
3882                    abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
3883                    repo_path: "crates/gpui/gpui.rs".into(),
3884                    worktree_path: Path::new("gpui.rs").into(),
3885                    status: StatusCode::Modified.worktree(),
3886                    staging: StageStatus::Unstaged,
3887                }),
3888                GitListEntry::GitStatusEntry(GitStatusEntry {
3889                    abs_path: path!("/root/zed/crates/util/util.rs").into(),
3890                    repo_path: "crates/util/util.rs".into(),
3891                    worktree_path: Path::new("../util/util.rs").into(),
3892                    status: StatusCode::Modified.worktree(),
3893                    staging: StageStatus::Unstaged,
3894                },),
3895            ],
3896        );
3897
3898        cx.update_window_entity(&panel, |panel, window, cx| {
3899            panel.select_last(&Default::default(), window, cx);
3900            assert_eq!(panel.selected_entry, Some(2));
3901            panel.open_diff(&Default::default(), window, cx);
3902        });
3903        cx.run_until_parked();
3904
3905        let worktree_roots = workspace.update(cx, |workspace, cx| {
3906            workspace
3907                .worktrees(cx)
3908                .map(|worktree| worktree.read(cx).abs_path())
3909                .collect::<Vec<_>>()
3910        });
3911        pretty_assertions::assert_eq!(
3912            worktree_roots,
3913            vec![
3914                Path::new(path!("/root/zed/crates/gpui")).into(),
3915                Path::new(path!("/root/zed/crates/util/util.rs")).into(),
3916            ]
3917        );
3918
3919        let repo_from_single_file_worktree = project.update(cx, |project, cx| {
3920            let git_store = project.git_store().read(cx);
3921            // The repo that comes from the single-file worktree can't be selected through the UI.
3922            let filtered_entries = filtered_repository_entries(git_store, cx)
3923                .iter()
3924                .map(|repo| repo.read(cx).worktree_abs_path.clone())
3925                .collect::<Vec<_>>();
3926            assert_eq!(
3927                filtered_entries,
3928                [Path::new(path!("/root/zed/crates/gpui")).into()]
3929            );
3930            // But we can select it artificially here.
3931            git_store
3932                .all_repositories()
3933                .into_iter()
3934                .find(|repo| {
3935                    &*repo.read(cx).worktree_abs_path
3936                        == Path::new(path!("/root/zed/crates/util/util.rs"))
3937                })
3938                .unwrap()
3939        });
3940
3941        // Paths still make sense when we somehow activate a repo that comes from a single-file worktree.
3942        repo_from_single_file_worktree.update(cx, |repo, cx| repo.activate(cx));
3943        let handle = cx.update_window_entity(&panel, |panel, _, _| {
3944            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
3945        });
3946        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
3947        handle.await;
3948        let entries = panel.update(cx, |panel, _| panel.entries.clone());
3949        pretty_assertions::assert_eq!(
3950            entries,
3951            [
3952                GitListEntry::Header(GitHeaderEntry {
3953                    header: Section::Tracked
3954                }),
3955                GitListEntry::GitStatusEntry(GitStatusEntry {
3956                    abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
3957                    repo_path: "crates/gpui/gpui.rs".into(),
3958                    worktree_path: Path::new("../../gpui/gpui.rs").into(),
3959                    status: StatusCode::Modified.worktree(),
3960                    staging: StageStatus::Unstaged,
3961                }),
3962                GitListEntry::GitStatusEntry(GitStatusEntry {
3963                    abs_path: path!("/root/zed/crates/util/util.rs").into(),
3964                    repo_path: "crates/util/util.rs".into(),
3965                    worktree_path: Path::new("util.rs").into(),
3966                    status: StatusCode::Modified.worktree(),
3967                    staging: StageStatus::Unstaged,
3968                },),
3969            ],
3970        );
3971    }
3972}