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