git_panel.rs

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