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