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