git_panel.rs

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