git_panel.rs

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