5734 lines · 205.4 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::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 agent_settings::AgentSettings;use anyhow::Context as _;use askpass::AskPassDelegate;use db::kvp::KEY_VALUE_STORE;use editor::{    Direction, Editor, EditorElement, EditorMode, MultiBuffer, actions::ExpandAllDiffHunks,};use futures::StreamExt as _;use git::blame::ParsedCommitMessage;use git::repository::{    Branch, CommitDetails, CommitOptions, CommitSummary, DiffType, FetchOptions, GitCommitter,    PushOptions, Remote, RemoteCommandOutput, ResetMode, Upstream, UpstreamTracking,    UpstreamTrackingStatus, get_git_committer,};use git::stash::GitStash;use git::status::StageStatus;use git::{Amend, Signoff, ToggleStaged, repository::RepoPath, status::FileStatus};use git::{    ExpandCommitEditor, RestoreTrackedFiles, StageAll, StashAll, StashApply, StashPop,    TrashUntrackedFiles, UnstageAll,};use gpui::{    Action, AppContext, AsyncApp, AsyncWindowContext, ClickEvent, Corner, DismissEvent, Entity,    EventEmitter, FocusHandle, Focusable, KeyContext, ListHorizontalSizingBehavior,    ListSizingBehavior, MouseButton, MouseDownEvent, Point, PromptLevel, ScrollStrategy,    Subscription, Task, UniformListScrollHandle, WeakEntity, actions, anchored, deferred,    uniform_list,};use itertools::Itertools;use language::{Buffer, File};use language_model::{    ConfiguredModel, LanguageModelRegistry, LanguageModelRequest, LanguageModelRequestMessage, Role,};use menu::{Confirm, SecondaryConfirm, SelectFirst, SelectLast, SelectNext, SelectPrevious};use multi_buffer::ExcerptInfo;use notifications::status_toast::{StatusToast, ToastIcon};use panel::{    PanelHeader, panel_button, panel_editor_container, panel_editor_style, panel_filled_button,    panel_icon_button,};use project::{    Fs, Project, ProjectPath,    git_store::{GitStoreEvent, Repository, RepositoryEvent, RepositoryId, pending_op},};use serde::{Deserialize, Serialize};use settings::{Settings, SettingsStore, StatusStyle};use std::future::Future;use std::ops::Range;use std::path::Path;use std::{collections::HashSet, sync::Arc, time::Duration, usize};use strum::{IntoEnumIterator, VariantNames};use time::OffsetDateTime;use ui::{    ButtonLike, Checkbox, CommonAnimationExt, ContextMenu, ElevationIndex, PopoverMenu, ScrollAxes,    Scrollbars, SplitButton, Tooltip, WithScrollbar, prelude::*,};use util::paths::PathStyle;use util::{ResultExt, TryFutureExt, maybe};use workspace::SERIALIZATION_THROTTLE_TIME; use cloud_llm_client::CompletionIntent;use workspace::{    Workspace,    dock::{DockPosition, Panel, PanelEvent},    notifications::{DetachAndPromptErr, ErrorMessagePrompt, NotificationId, NotifyResultExt},}; actions!(    git_panel,    [        /// Closes the git panel.        Close,        /// Toggles focus on the git panel.        ToggleFocus,        /// Opens the git panel menu.        OpenMenu,        /// Focuses on the commit message editor.        FocusEditor,        /// Focuses on the changes list.        FocusChanges,        /// Toggles automatic co-author suggestions.        ToggleFillCoAuthors,        /// Toggles sorting entries by path vs status.        ToggleSortByPath,    ]); 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,    sort_by_path: bool,    has_stash_items: 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)            .action_disabled_when(                !state.has_unstaged_changes,                "Stage All",                StageAll.boxed_clone(),            )            .action_disabled_when(                !state.has_staged_changes,                "Unstage All",                UnstageAll.boxed_clone(),            )            .separator()            .action_disabled_when(                !(state.has_new_changes || state.has_tracked_changes),                "Stash All",                StashAll.boxed_clone(),            )            .action_disabled_when(!state.has_stash_items, "Stash Pop", StashPop.boxed_clone())            .action("View Stash", zed_actions::git::ViewStash.boxed_clone())            .separator()            .action("Open Diff", project_diff::Diff.boxed_clone())            .separator()            .action_disabled_when(                !state.has_tracked_changes,                "Discard Tracked Changes",                RestoreTrackedFiles.boxed_clone(),            )            .action_disabled_when(                !state.has_new_changes,                "Trash Untracked Files",                TrashUntrackedFiles.boxed_clone(),            )            .separator()            .entry(                if state.sort_by_path {                    "Sort by Status"                } else {                    "Sort by Path"                },                Some(Box::new(ToggleSortByPath)),                move |window, cx| window.dispatch_action(Box::new(ToggleSortByPath), cx),            )    })} 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>,    #[serde(default)]    amend_pending: bool,    #[serde(default)]    signoff_enabled: bool,} #[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.had_conflict_on_last_merge_head_change(&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 {    Status(GitStatusEntry),    Header(GitHeaderEntry),} impl GitListEntry {    fn status_entry(&self) -> Option<&GitStatusEntry> {        match self {            GitListEntry::Status(entry) => Some(entry),            _ => None,        }    }} #[derive(Debug, PartialEq, Eq, Clone)]pub struct GitStatusEntry {    pub(crate) repo_path: RepoPath,    pub(crate) status: FileStatus,    pub(crate) staging: StageStatus,} impl GitStatusEntry {    fn display_name(&self, path_style: PathStyle) -> String {        self.repo_path            .file_name()            .map(|name| name.to_owned())            .unwrap_or_else(|| self.repo_path.display(path_style).to_string())    }     fn parent_dir(&self, path_style: PathStyle) -> Option<String> {        self.repo_path            .parent()            .map(|parent| parent.display(path_style).to_string())    }} pub struct GitPanel {    pub(crate) active_repository: Option<Entity<Repository>>,    pub(crate) commit_editor: Entity<Editor>,    conflicted_count: usize,    conflicted_staged_count: usize,    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>,    new_count: usize,    entry_count: usize,    new_staged_count: usize,    pending_commit: Option<Task<()>>,    amend_pending: bool,    original_commit_message: Option<String>,    signoff_enabled: bool,    pending_serialization: Task<()>,    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,    show_placeholders: bool,    local_committer: Option<GitCommitter>,    local_committer_task: Option<Task<()>>,    bulk_staging: Option<BulkStaging>,    stash_entries: GitStash,    _settings_subscription: Subscription,    /// On clicking an entry in a the git_panel this will    /// trigger loading it    open_diff_task: Option<Task<()>>,} #[derive(Clone, Debug, PartialEq, Eq)]struct BulkStaging {    repo_id: RepositoryId,    anchor: RepoPath,} 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 {            min_lines: max_lines,            max_lines: Some(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_use_modal_editing(true);    commit_editor.set_show_wrap_guides(false, cx);    commit_editor.set_show_indent_guides(false, cx);    let placeholder = placeholder.unwrap_or("Enter commit message".into());    commit_editor.set_placeholder_text(&placeholder, window, cx);    commit_editor} impl GitPanel {    fn new(        workspace: &mut Workspace,        window: &mut Window,        cx: &mut Context<Workspace>,    ) -> Entity<Self> {        let project = workspace.project().clone();        let app_state = workspace.app_state().clone();        let fs = app_state.fs.clone();        let git_store = project.read(cx).git_store().clone();        let active_repository = project.read(cx).active_repository(cx);         cx.new(|cx| {            let focus_handle = cx.focus_handle();            cx.on_focus(&focus_handle, window, Self::focus_in).detach();             let mut was_sort_by_path = GitPanelSettings::get_global(cx).sort_by_path;            cx.observe_global_in::<SettingsStore>(window, move |this, window, cx| {                let is_sort_by_path = GitPanelSettings::get_global(cx).sort_by_path;                if is_sort_by_path != was_sort_by_path {                    this.entries.clear();                    this.update_visible_entries(window, cx);                }                was_sort_by_path = is_sort_by_path            })            .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();             let mut was_ai_enabled = AgentSettings::get_global(cx).enabled(cx);            let _settings_subscription = cx.observe_global::<SettingsStore>(move |_, cx| {                let is_ai_enabled = AgentSettings::get_global(cx).enabled(cx);                if was_ai_enabled != is_ai_enabled {                    was_ai_enabled = is_ai_enabled;                    cx.notify();                }            });             cx.subscribe_in(                &git_store,                window,                move |this, _git_store, event, window, cx| match event {                    GitStoreEvent::ActiveRepositoryChanged(_) => {                        this.active_repository = this.project.read(cx).active_repository(cx);                        this.schedule_update(window, cx);                    }                    GitStoreEvent::RepositoryUpdated(                        _,                        RepositoryEvent::StatusesChanged                        | RepositoryEvent::BranchChanged                        | RepositoryEvent::MergeHeadsChanged,                        true,                    )                    | GitStoreEvent::RepositoryAdded                    | GitStoreEvent::RepositoryRemoved(_) => {                        this.schedule_update(window, cx);                    }                    GitStoreEvent::IndexWriteError(error) => {                        this.workspace                            .update(cx, |workspace, cx| {                                workspace.show_error(error, cx);                            })                            .ok();                    }                    GitStoreEvent::RepositoryUpdated(_, _, _) => {}                    GitStoreEvent::JobsUpdated | GitStoreEvent::ConflictsUpdated => {}                },            )            .detach();             let mut this = Self {                active_repository,                commit_editor,                conflicted_count: 0,                conflicted_staged_count: 0,                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_commit: None,                amend_pending: false,                original_commit_message: None,                signoff_enabled: false,                pending_serialization: Task::ready(()),                single_staged_entry: None,                single_tracked_entry: None,                project,                scroll_handle,                max_width_item_index: None,                selected_entry: None,                marked_entries: Vec::new(),                tracked_count: 0,                tracked_staged_count: 0,                update_visible_entries_task: Task::ready(()),                width: None,                show_placeholders: false,                local_committer: None,                local_committer_task: None,                context_menu: None,                workspace: workspace.weak_handle(),                modal_open: false,                entry_count: 0,                bulk_staging: None,                stash_entries: Default::default(),                _settings_subscription,                open_diff_task: None,            };             this.schedule_update(window, cx);            this        })    }     pub fn entry_by_path(&self, path: &RepoPath, cx: &App) -> Option<usize> {        if GitPanelSettings::get_global(cx).sort_by_path {            return self                .entries                .binary_search_by(|entry| entry.status_entry().unwrap().repo_path.cmp(path))                .ok();        }         if self.conflicted_count > 0 {            let conflicted_start = 1;            if let Ok(ix) = self.entries[conflicted_start..conflicted_start + self.conflicted_count]                .binary_search_by(|entry| entry.status_entry().unwrap().repo_path.cmp(path))            {                return Some(conflicted_start + ix);            }

Lines 1–500 of 5734.