git_panel.rs

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