4944 lines · 180.8 KB · Rust
RawDownload
use crate::askpass_modal::AskPassModal;use crate::commit_modal::CommitModal;use crate::commit_tooltip::CommitTooltip;use crate::commit_view::CommitView;use crate::git_panel_settings::StatusStyle;use crate::project_diff::{self, Diff, ProjectDiff};use crate::remote_output::{self, RemoteAction, SuccessMessage};use crate::{branch_picker, picker_prompt, render_remote_button};use crate::{    git_panel_settings::GitPanelSettings, git_status_icon, repository_selector::RepositorySelector,};use anyhow::Result;use askpass::AskPassDelegate;use assistant_settings::AssistantSettings;use db::kvp::KEY_VALUE_STORE; use editor::{    Editor, EditorElement, EditorMode, EditorSettings, MultiBuffer, ShowScrollbar,    scroll::ScrollbarAutoHide,};use futures::StreamExt as _;use git::blame::ParsedCommitMessage;use git::repository::{    Branch, CommitDetails, CommitOptions, CommitSummary, DiffType, PushOptions, Remote,    RemoteCommandOutput, ResetMode, Upstream, UpstreamTracking, UpstreamTrackingStatus,};use git::status::StageStatus;use git::{Amend, ToggleStaged, repository::RepoPath, status::FileStatus};use git::{ExpandCommitEditor, RestoreTrackedFiles, StageAll, TrashUntrackedFiles, UnstageAll};use gpui::{    Action, Animation, AnimationExt as _, Axis, ClickEvent, Corner, DismissEvent, Entity,    EventEmitter, FocusHandle, Focusable, KeyContext, ListHorizontalSizingBehavior,    ListSizingBehavior, Modifiers, ModifiersChangedEvent, MouseButton, MouseDownEvent, Point,    PromptLevel, ScrollStrategy, Subscription, Task, Transformation, UniformListScrollHandle,    WeakEntity, actions, anchored, deferred, percentage, uniform_list,};use itertools::Itertools;use language::{Buffer, File};use language_model::{    ConfiguredModel, LanguageModel, LanguageModelRegistry, LanguageModelRequest,    LanguageModelRequestMessage, Role,};use menu::{Confirm, SecondaryConfirm, SelectFirst, SelectLast, SelectNext, SelectPrevious};use multi_buffer::ExcerptInfo;use panel::{    PanelHeader, panel_button, panel_editor_container, panel_editor_style, panel_filled_button,    panel_icon_button,};use project::git_store::RepositoryEvent;use project::{    Fs, Project, ProjectPath,    git_store::{GitStoreEvent, Repository},};use serde::{Deserialize, Serialize};use settings::{Settings as _, SettingsStore};use std::future::Future;use std::path::{Path, PathBuf};use std::{collections::HashSet, sync::Arc, time::Duration, usize};use strum::{IntoEnumIterator, VariantNames};use time::OffsetDateTime;use ui::{    Checkbox, ContextMenu, ElevationIndex, PopoverMenu, Scrollbar, ScrollbarState, SplitButton,    Tooltip, prelude::*,};use util::{ResultExt, TryFutureExt, maybe};use workspace::AppState; use notifications::status_toast::{StatusToast, ToastIcon};use workspace::{    Workspace,    dock::{DockPosition, Panel, PanelEvent},    notifications::DetachAndPromptErr,}; actions!(    git_panel,    [        Close,        ToggleFocus,        OpenMenu,        FocusEditor,        FocusChanges,        ToggleFillCoAuthors,        GenerateCommitMessage    ]); fn prompt<T>(    msg: &str,    detail: Option<&str>,    window: &mut Window,    cx: &mut App,) -> Task<anyhow::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,} struct GitMenuState {    has_tracked_changes: bool,    has_staged_changes: bool,    has_unstaged_changes: bool,    has_new_changes: bool,} fn git_panel_context_menu(    focus_handle: FocusHandle,    state: GitMenuState,    window: &mut Window,    cx: &mut App,) -> Entity<ContextMenu> {    ContextMenu::build(window, cx, move |context_menu, _, _| {        context_menu            .context(focus_handle)            .map(|menu| {                if state.has_unstaged_changes {                    menu.action("Stage All", StageAll.boxed_clone())                } else {                    menu.disabled_action("Stage All", StageAll.boxed_clone())                }            })            .map(|menu| {                if state.has_staged_changes {                    menu.action("Unstage All", UnstageAll.boxed_clone())                } else {                    menu.disabled_action("Unstage All", UnstageAll.boxed_clone())                }            })            .separator()            .action("Open Diff", project_diff::Diff.boxed_clone())            .separator()            .map(|menu| {                if state.has_tracked_changes {                    menu.action("Discard Tracked Changes", RestoreTrackedFiles.boxed_clone())                } else {                    menu.disabled_action(                        "Discard Tracked Changes",                        RestoreTrackedFiles.boxed_clone(),                    )                }            })            .map(|menu| {                if state.has_new_changes {                    menu.action("Trash Untracked Files", TrashUntrackedFiles.boxed_clone())                } else {                    menu.disabled_action("Trash Untracked Files", TrashUntrackedFiles.boxed_clone())                }            })    })} const GIT_PANEL_KEY: &str = "GitPanel"; const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50); pub fn register(workspace: &mut Workspace) {    workspace.register_action(|workspace, _: &ToggleFocus, window, cx| {        workspace.toggle_panel_focus::<GitPanel>(window, cx);    });    workspace.register_action(|workspace, _: &ExpandCommitEditor, window, cx| {        CommitModal::toggle(workspace, None, window, cx)    });} #[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) repo_path: RepoPath,    pub(crate) abs_path: PathBuf,    pub(crate) status: FileStatus,    pub(crate) staging: StageStatus,} impl GitStatusEntry {    fn display_name(&self) -> String {        self.repo_path            .file_name()            .map(|name| name.to_string_lossy().into_owned())            .unwrap_or_else(|| self.repo_path.to_string_lossy().into_owned())    }     fn parent_dir(&self) -> Option<String> {        self.repo_path            .parent()            .map(|parent| parent.to_string_lossy().into_owned())    }} #[derive(Clone, Copy, Debug, PartialEq, Eq)]enum TargetStatus {    Staged,    Unstaged,    Reverted,    Unchanged,} struct PendingOperation {    finished: bool,    target_status: TargetStatus,    entries: Vec<GitStatusEntry>,    op_id: usize,} // computed state related to how to render scrollbars// one per axis// on render we just read this off the panel// we update it when// - settings change// - on focus in, on focus out, on hover, etc.#[derive(Debug)]struct ScrollbarProperties {    axis: Axis,    show_scrollbar: bool,    show_track: bool,    auto_hide: bool,    hide_task: Option<Task<()>>,    state: ScrollbarState,} impl ScrollbarProperties {    // Shows the scrollbar and cancels any pending hide task    fn show(&mut self, cx: &mut Context<GitPanel>) {        if !self.auto_hide {            return;        }        self.show_scrollbar = true;        self.hide_task.take();        cx.notify();    }     fn hide(&mut self, window: &mut Window, cx: &mut Context<GitPanel>) {        const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);         if !self.auto_hide {            return;        }         let axis = self.axis;        self.hide_task = Some(cx.spawn_in(window, async move |panel, cx| {            cx.background_executor()                .timer(SCROLLBAR_SHOW_INTERVAL)                .await;             if let Some(panel) = panel.upgrade() {                panel                    .update(cx, |panel, cx| {                        match axis {                            Axis::Vertical => panel.vertical_scrollbar.show_scrollbar = false,                            Axis::Horizontal => panel.horizontal_scrollbar.show_scrollbar = false,                        }                        cx.notify();                    })                    .log_err();            }        }));    }} pub struct GitPanel {    pub(crate) active_repository: Option<Entity<Repository>>,    pub(crate) commit_editor: Entity<Editor>,    conflicted_count: usize,    conflicted_staged_count: usize,    current_modifiers: Modifiers,    add_coauthors: bool,    generate_commit_message_task: Option<Task<Option<()>>>,    entries: Vec<GitListEntry>,    single_staged_entry: Option<GitStatusEntry>,    single_tracked_entry: Option<GitStatusEntry>,    focus_handle: FocusHandle,    fs: Arc<dyn Fs>,    horizontal_scrollbar: ScrollbarProperties,    vertical_scrollbar: ScrollbarProperties,    new_count: usize,    entry_count: usize,    new_staged_count: usize,    pending: Vec<PendingOperation>,    pending_commit: Option<Task<()>>,    amend_pending: bool,    pending_serialization: Task<Option<()>>,    pub(crate) project: Entity<Project>,    scroll_handle: UniformListScrollHandle,    max_width_item_index: Option<usize>,    selected_entry: Option<usize>,    marked_entries: Vec<usize>,    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)>,    modal_open: bool,    _settings_subscription: Subscription,} const MAX_PANEL_EDITOR_LINES: usize = 6; pub(crate) fn commit_message_editor(    commit_message_buffer: Entity<Buffer>,    placeholder: Option<SharedString>,    project: Entity<Project>,    in_panel: bool,    window: &mut Window,    cx: &mut Context<Editor>,) -> Editor {    let buffer = cx.new(|cx| MultiBuffer::singleton(commit_message_buffer, cx));    let max_lines = if in_panel { MAX_PANEL_EDITOR_LINES } else { 18 };    let mut commit_editor = Editor::new(        EditorMode::AutoHeight { max_lines },        buffer,        None,        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_hard_wrap(Some(72), cx);    let placeholder = placeholder.unwrap_or("Enter commit message".into());    commit_editor.set_placeholder_text(placeholder, cx);    commit_editor} impl GitPanel {    pub fn new(        workspace: Entity<Workspace>,        project: Entity<Project>,        app_state: Arc<AppState>,        window: &mut Window,        cx: &mut Context<Self>,    ) -> Self {        let fs = app_state.fs.clone();        let git_store = project.read(cx).git_store().clone();        let active_repository = project.read(cx).active_repository(cx);        let workspace = workspace.downgrade();         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_scrollbars(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, None, project.clone(), true, 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 {                GitStoreEvent::ActiveRepositoryChanged(_) => {                    this.active_repository = git_store.read(cx).active_repository();                    this.schedule_update(true, window, cx);                }                GitStoreEvent::RepositoryUpdated(                    _,                    RepositoryEvent::Updated { full_scan },                    true,                ) => {                    this.schedule_update(*full_scan, window, cx);                }                 GitStoreEvent::RepositoryAdded(_) | GitStoreEvent::RepositoryRemoved(_) => {                    this.schedule_update(false, window, cx);                }                GitStoreEvent::IndexWriteError(error) => {                    this.workspace                        .update(cx, |workspace, cx| {                            workspace.show_error(error, cx);                        })                        .ok();                }                GitStoreEvent::RepositoryUpdated(_, _, _) => {}                GitStoreEvent::JobsUpdated => {}            },        )        .detach();         let vertical_scrollbar = ScrollbarProperties {            axis: Axis::Vertical,            state: ScrollbarState::new(scroll_handle.clone()).parent_entity(&cx.entity()),            show_scrollbar: false,            show_track: false,            auto_hide: false,            hide_task: None,        };         let horizontal_scrollbar = ScrollbarProperties {            axis: Axis::Horizontal,            state: ScrollbarState::new(scroll_handle.clone()).parent_entity(&cx.entity()),            show_scrollbar: false,            show_track: false,            auto_hide: false,            hide_task: None,        };         let mut assistant_enabled = AssistantSettings::get_global(cx).enabled;        let _settings_subscription = cx.observe_global::<SettingsStore>(move |_, cx| {            if assistant_enabled != AssistantSettings::get_global(cx).enabled {                assistant_enabled = AssistantSettings::get_global(cx).enabled;                cx.notify();            }        });         let mut git_panel = Self {            active_repository,            commit_editor,            conflicted_count: 0,            conflicted_staged_count: 0,            current_modifiers: window.modifiers(),            add_coauthors: true,            generate_commit_message_task: None,            entries: Vec::new(),            focus_handle: cx.focus_handle(),            fs,            new_count: 0,            new_staged_count: 0,            pending: Vec::new(),            pending_commit: None,            amend_pending: false,            pending_serialization: Task::ready(None),            single_staged_entry: None,            single_tracked_entry: None,            project,

Lines 1–500 of 4944.