Mikayla MakiWIP: Implement pusha94b13d1 year agoHistory
2505 lines · 85.1 KB · Rust
RawDownload
use crate::git_panel_settings::StatusStyle;use crate::repository_selector::RepositorySelectorPopoverMenu;use crate::{    git_panel_settings::GitPanelSettings, git_status_icon, repository_selector::RepositorySelector,};use crate::{project_diff, ProjectDiff};use collections::HashMap;use db::kvp::KEY_VALUE_STORE;use editor::commit_tooltip::CommitTooltip;use editor::{    scroll::ScrollbarAutoHide, Editor, EditorElement, EditorMode, EditorSettings, MultiBuffer,    ShowScrollbar,};use git::repository::{Branch, CommitDetails, PushAction, ResetMode};use git::{repository::RepoPath, status::FileStatus, Commit, ToggleStaged};use git::{RestoreTrackedFiles, StageAll, TrashUntrackedFiles, UnstageAll};use gpui::*;use itertools::Itertools;use language::{Buffer, File};use menu::{Confirm, SecondaryConfirm, SelectFirst, SelectLast, SelectNext, SelectPrev};use multi_buffer::ExcerptInfo;use panel::{panel_editor_container, panel_editor_style, panel_filled_button, PanelHeader};use project::{    git::{GitEvent, Repository},    Fs, Project, ProjectPath,};use serde::{Deserialize, Serialize};use settings::Settings as _;use std::{collections::HashSet, path::PathBuf, sync::Arc, time::Duration, usize};use strum::{IntoEnumIterator, VariantNames};use time::OffsetDateTime;use ui::{    prelude::*, ButtonLike, Checkbox, ContextMenu, Divider, DividerColor, ElevationIndex, ListItem,    ListItemSpacing, Scrollbar, ScrollbarState, Tooltip,};use util::{maybe, ResultExt, TryFutureExt};use workspace::{    dock::{DockPosition, Panel, PanelEvent},    notifications::{DetachAndPromptErr, NotificationId},    Toast, Workspace,}; actions!(    git_panel,    [        Close,        ToggleFocus,        OpenMenu,        FocusEditor,        FocusChanges,        ToggleFillCoAuthors,    ]); fn prompt<T>(msg: &str, detail: Option<&str>, window: &mut Window, cx: &mut App) -> Task<Result<T>>where    T: IntoEnumIterator + VariantNames + 'static,{    let rx = window.prompt(PromptLevel::Info, msg, detail, &T::VARIANTS, cx);    cx.spawn(|_| async move { Ok(T::iter().nth(rx.await?).unwrap()) })} #[derive(strum::EnumIter, strum::VariantNames)]#[strum(serialize_all = "title_case")]enum TrashCancel {    Trash,    Cancel,} const GIT_PANEL_KEY: &str = "GitPanel"; const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50); pub fn init(cx: &mut App) {    cx.observe_new(        |workspace: &mut Workspace, _window, _cx: &mut Context<Workspace>| {            workspace.register_action(|workspace, _: &ToggleFocus, window, cx| {                workspace.toggle_panel_focus::<GitPanel>(window, cx);            });             workspace.register_action(|workspace, _: &Commit, window, cx| {                workspace.open_panel::<GitPanel>(window, cx);                if let Some(git_panel) = workspace.panel::<GitPanel>(cx) {                    git_panel                        .read(cx)                        .commit_editor                        .focus_handle(cx)                        .focus(window);                }            });        },    )    .detach();} #[derive(Debug, Clone)]pub enum Event {    Focus,} #[derive(Serialize, Deserialize)]struct SerializedGitPanel {    width: Option<Pixels>,} #[derive(Debug, PartialEq, Eq, Clone, Copy)]enum Section {    Conflict,    Tracked,    New,} #[derive(Debug, PartialEq, Eq, Clone)]struct GitHeaderEntry {    header: Section,} impl GitHeaderEntry {    pub fn contains(&self, status_entry: &GitStatusEntry, repo: &Repository) -> bool {        let this = &self.header;        let status = status_entry.status;        match this {            Section::Conflict => repo.has_conflict(&status_entry.repo_path),            Section::Tracked => !status.is_created(),            Section::New => status.is_created(),        }    }    pub fn title(&self) -> &'static str {        match self.header {            Section::Conflict => "Conflicts",            Section::Tracked => "Tracked",            Section::New => "Untracked",        }    }} #[derive(Debug, PartialEq, Eq, Clone)]enum GitListEntry {    GitStatusEntry(GitStatusEntry),    Header(GitHeaderEntry),} impl GitListEntry {    fn status_entry(&self) -> Option<&GitStatusEntry> {        match self {            GitListEntry::GitStatusEntry(entry) => Some(entry),            _ => None,        }    }} #[derive(Debug, PartialEq, Eq, Clone)]pub struct GitStatusEntry {    pub(crate) depth: usize,    pub(crate) display_name: String,    pub(crate) repo_path: RepoPath,    pub(crate) status: FileStatus,    pub(crate) is_staged: Option<bool>,} #[derive(Clone, Copy, Debug, PartialEq, Eq)]enum TargetStatus {    Staged,    Unstaged,    Reverted,    Unchanged,} struct PendingOperation {    finished: bool,    target_status: TargetStatus,    repo_paths: HashSet<RepoPath>,    op_id: usize,} pub struct GitPanel {    active_repository: Option<Entity<Repository>>,    commit_editor: Entity<Editor>,    conflicted_count: usize,    conflicted_staged_count: usize,    current_modifiers: Modifiers,    add_coauthors: bool,    entries: Vec<GitListEntry>,    entries_by_path: collections::HashMap<RepoPath, usize>,    focus_handle: FocusHandle,    fs: Arc<dyn Fs>,    hide_scrollbar_task: Option<Task<()>>,    new_count: usize,    new_staged_count: usize,    pending: Vec<PendingOperation>,    pending_commit: Option<Task<()>>,    pending_serialization: Task<Option<()>>,    project: Entity<Project>,    repository_selector: Entity<RepositorySelector>,    scroll_handle: UniformListScrollHandle,    scrollbar_state: ScrollbarState,    selected_entry: Option<usize>,    show_scrollbar: bool,    tracked_count: usize,    tracked_staged_count: usize,    update_visible_entries_task: Task<()>,    width: Option<Pixels>,    workspace: WeakEntity<Workspace>,    context_menu: Option<(Entity<ContextMenu>, Point<Pixels>, Subscription)>,} fn commit_message_editor(    commit_message_buffer: Entity<Buffer>,    project: Entity<Project>,    window: &mut Window,    cx: &mut Context<'_, Editor>,) -> Editor {    let buffer = cx.new(|cx| MultiBuffer::singleton(commit_message_buffer, cx));    let mut commit_editor = Editor::new(        EditorMode::AutoHeight { max_lines: 6 },        buffer,        None,        false,        window,        cx,    );    commit_editor.set_collaboration_hub(Box::new(project));    commit_editor.set_use_autoclose(false);    commit_editor.set_show_gutter(false, cx);    commit_editor.set_show_wrap_guides(false, cx);    commit_editor.set_show_indent_guides(false, cx);    commit_editor.set_placeholder_text("Enter commit message", cx);    commit_editor} impl GitPanel {    pub fn new(        workspace: &mut Workspace,        window: &mut Window,        cx: &mut Context<Workspace>,    ) -> Entity<Self> {        let fs = workspace.app_state().fs.clone();        let project = workspace.project().clone();        let git_store = project.read(cx).git_store().clone();        let active_repository = project.read(cx).active_repository(cx);        let workspace = cx.entity().downgrade();         cx.new(|cx| {            let focus_handle = cx.focus_handle();            cx.on_focus(&focus_handle, window, Self::focus_in).detach();            cx.on_focus_out(&focus_handle, window, |this, _, window, cx| {                this.hide_scrollbar(window, cx);            })            .detach();             // just to let us render a placeholder editor.            // Once the active git repo is set, this buffer will be replaced.            let temporary_buffer = cx.new(|cx| Buffer::local("", cx));            let commit_editor =                cx.new(|cx| commit_message_editor(temporary_buffer, project.clone(), window, cx));            commit_editor.update(cx, |editor, cx| {                editor.clear(window, cx);            });             let scroll_handle = UniformListScrollHandle::new();             cx.subscribe_in(                &git_store,                window,                move |this, git_store, event, window, cx| match event {                    GitEvent::FileSystemUpdated => {                        this.schedule_update(false, window, cx);                    }                    GitEvent::ActiveRepositoryChanged | GitEvent::GitStateUpdated => {                        this.active_repository = git_store.read(cx).active_repository();                        this.schedule_update(true, window, cx);                    }                },            )            .detach();             let scrollbar_state =                ScrollbarState::new(scroll_handle.clone()).parent_entity(&cx.entity());             let repository_selector =                cx.new(|cx| RepositorySelector::new(project.clone(), window, cx));             let mut git_panel = Self {                active_repository,                commit_editor,                conflicted_count: 0,                conflicted_staged_count: 0,                current_modifiers: window.modifiers(),                add_coauthors: true,                entries: Vec::new(),                entries_by_path: HashMap::default(),                focus_handle: cx.focus_handle(),                fs,                hide_scrollbar_task: None,                new_count: 0,                new_staged_count: 0,                pending: Vec::new(),                pending_commit: None,                pending_serialization: Task::ready(None),                project,                repository_selector,                scroll_handle,                scrollbar_state,                selected_entry: None,                show_scrollbar: false,                tracked_count: 0,                tracked_staged_count: 0,                update_visible_entries_task: Task::ready(()),                width: Some(px(360.)),                context_menu: None,                workspace,            };            git_panel.schedule_update(false, window, cx);            git_panel.show_scrollbar = git_panel.should_show_scrollbar(cx);            git_panel        })    }     pub fn select_entry_by_path(        &mut self,        path: ProjectPath,        _: &mut Window,        cx: &mut Context<Self>,    ) {        let Some(git_repo) = self.active_repository.as_ref() else {            return;        };        let Some(repo_path) = git_repo.read(cx).project_path_to_repo_path(&path) else {            return;        };        let Some(ix) = self.entries_by_path.get(&repo_path) else {            return;        };        self.selected_entry = Some(*ix);        cx.notify();    }     fn serialize(&mut self, cx: &mut Context<Self>) {        let width = self.width;        self.pending_serialization = cx.background_spawn(            async move {                KEY_VALUE_STORE                    .write_kvp(                        GIT_PANEL_KEY.into(),                        serde_json::to_string(&SerializedGitPanel { width })?,                    )                    .await?;                anyhow::Ok(())            }            .log_err(),        );    }     fn dispatch_context(&self, window: &mut Window, cx: &Context<Self>) -> KeyContext {        let mut dispatch_context = KeyContext::new_with_defaults();        dispatch_context.add("GitPanel");         if self.is_focused(window, cx) {            dispatch_context.add("menu");            dispatch_context.add("ChangesList");        }         if self.commit_editor.read(cx).is_focused(window) {            dispatch_context.add("CommitEditor");        }         dispatch_context    }     fn is_focused(&self, window: &Window, cx: &Context<Self>) -> bool {        window            .focused(cx)            .map_or(false, |focused| self.focus_handle == focused)    }     fn close_panel(&mut self, _: &Close, _window: &mut Window, cx: &mut Context<Self>) {        cx.emit(PanelEvent::Close);    }     fn focus_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {        if !self.focus_handle.contains_focused(window, cx) {            cx.emit(Event::Focus);        }    }     fn show_scrollbar(&self, cx: &mut Context<Self>) -> ShowScrollbar {        GitPanelSettings::get_global(cx)            .scrollbar            .show            .unwrap_or_else(|| EditorSettings::get_global(cx).scrollbar.show)    }     fn should_show_scrollbar(&self, cx: &mut Context<Self>) -> bool {        let show = self.show_scrollbar(cx);        match show {            ShowScrollbar::Auto => true,            ShowScrollbar::System => true,            ShowScrollbar::Always => true,            ShowScrollbar::Never => false,        }    }     fn should_autohide_scrollbar(&self, cx: &mut Context<Self>) -> bool {        let show = self.show_scrollbar(cx);        match show {            ShowScrollbar::Auto => true,            ShowScrollbar::System => cx                .try_global::<ScrollbarAutoHide>()                .map_or_else(|| cx.should_auto_hide_scrollbars(), |autohide| autohide.0),            ShowScrollbar::Always => false,            ShowScrollbar::Never => true,        }    }     fn hide_scrollbar(&mut self, window: &mut Window, cx: &mut Context<Self>) {        const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);        if !self.should_autohide_scrollbar(cx) {            return;        }        self.hide_scrollbar_task = Some(cx.spawn_in(window, |panel, mut cx| async move {            cx.background_executor()                .timer(SCROLLBAR_SHOW_INTERVAL)                .await;            panel                .update(&mut cx, |panel, cx| {                    panel.show_scrollbar = false;                    cx.notify();                })                .log_err();        }))    }     fn handle_modifiers_changed(        &mut self,        event: &ModifiersChangedEvent,        _: &mut Window,        cx: &mut Context<Self>,    ) {        self.current_modifiers = event.modifiers;        cx.notify();    }     fn calculate_depth_and_difference(        repo_path: &RepoPath,        visible_entries: &HashSet<RepoPath>,    ) -> (usize, usize) {        let ancestors = repo_path.ancestors().skip(1);        for ancestor in ancestors {            if let Some(parent_entry) = visible_entries.get(ancestor) {                let entry_component_count = repo_path.components().count();                let parent_component_count = parent_entry.components().count();                 let difference = entry_component_count - parent_component_count;                 let parent_depth = parent_entry                    .ancestors()                    .skip(1) // Skip the parent itself                    .filter(|ancestor| visible_entries.contains(*ancestor))                    .count();                 return (parent_depth + 1, difference);            }        }         (0, 0)    }     fn scroll_to_selected_entry(&mut self, cx: &mut Context<Self>) {        if let Some(selected_entry) = self.selected_entry {            self.scroll_handle                .scroll_to_item(selected_entry, ScrollStrategy::Center);        }         cx.notify();    }     fn select_first(&mut self, _: &SelectFirst, _window: &mut Window, cx: &mut Context<Self>) {        if self.entries.first().is_some() {            self.selected_entry = Some(1);            self.scroll_to_selected_entry(cx);        }    }     fn select_prev(&mut self, _: &SelectPrev, _window: &mut Window, cx: &mut Context<Self>) {        let item_count = self.entries.len();        if item_count == 0 {            return;        }         if let Some(selected_entry) = self.selected_entry {            let new_selected_entry = if selected_entry > 0 {                selected_entry - 1            } else {                selected_entry            };             if matches!(                self.entries.get(new_selected_entry),                Some(GitListEntry::Header(..))            ) {

Lines 1–500 of 2505.