Skip to content

Visual Studio Code, rebuilt in Rust

Rust
10.5 KB
Raw Blame
//! testingDecorations.ts's gutter actions generator: the `getContextMenuActions` of the line's
//! `RunSingleTestDecoration` or `MultiRunTestDecoration`, which the editor gutter's menu shows first.

use gpui::{Context, Window};
use serde_json::{Value, json};

use super::Workbench;
use super::testing_item_menu::HAS_NON_DEFAULT_PROFILE;
use crate::commands::Outcome;
use crate::menus::{MenuAction, MenuId, menu_actions};
use crate::quick_input::{Entry as PickEntry, Item};
use crate::testing::{GROUP_COVERAGE, GROUP_DEBUG, GROUP_RUN, ResultState, parent_id};

const MAX_TESTS_IN_SUBMENU: usize = 30;

impl Workbench {
    pub(super) fn register_testing_gutter_commands(&mut self) {
        // testing.contribution.ts: reveals the test and opens the Test Explorer.
        self.commands.register("_revealTestInExplorer", |workbench, args, window, cx| {
            let Some(id) = args.first().and_then(|arg| arg.as_str().or(arg["extId"].as_str())) else { return Outcome::done() };
            workbench.expand_test_ancestors(id);
            workbench.testing_view.selected = Some(id.to_owned());
            workbench.testing_view.reveal_pending.set(true);
            workbench.open_testing_view(args.get(1) == Some(&json!(true)), window, cx);
            Outcome::done()
        });
        self.commands.register("_testing.gutterPickAndRun", |workbench, args, window, cx| {
            let tests: Vec<String> = args.iter().filter_map(|arg| arg.as_str().map(str::to_owned)).collect();
            workbench.pick_and_run_test(&tests, window, cx);
            Outcome::done()
        });
    }

    /// The actions of the tests whose range starts on the 1-based `line` of the active editor's file.
    pub(super) fn test_gutter_actions(&mut self, line: u32, window: &Window) -> Vec<MenuAction> {
        let Some(path) = self.editors.active().map(|editor| editor.document().path.to_string_lossy().into_owned()) else { return Vec::new() };
        match self.tests_at_line(&path, line).as_slice() {
            [] => Vec::new(),
            [test] => self.test_context_menu_actions(test, window),
            tests => self.multi_test_context_menu_actions(tests, window),
        }
    }

    /// `getTestContextMenuActions`.
    fn test_context_menu_actions(&mut self, id: &str, window: &Window) -> Vec<MenuAction> {
        let capabilities = self.test_capabilities(id);
        let mut actions = Vec::new();
        for (group, title) in [(GROUP_RUN, "Run Test"), (GROUP_DEBUG, "Debug Test"), (GROUP_COVERAGE, "Run with Coverage")] {
            if capabilities & group != 0 {
                actions.push(self.bound_action(title, "vscode.runTestsById", vec![json!(group), json!(id)]));
            }
        }
        if capabilities & HAS_NON_DEFAULT_PROFILE != 0 {
            actions.push(self.bound_action("Execute Using Profile...", "testing.runUsing", vec![json!(id)]));
        }
        let state = self.testing.state_of(id);
        if matches!(state, Some(ResultState::Failed | ResultState::Errored)) {
            actions.push(self.bound_action("Peek Error", "vscode.peekTestError", vec![json!(id)]));
        }
        if state == Some(ResultState::Running) {
            actions.push(self.bound_action("Cancel Test Run", "testing.cancelRun", Vec::new()));
        }
        actions.push(self.bound_action("Reveal in Test Explorer", "_revealTestInExplorer", vec![json!(id)]));
        // `getContributedTestActions`: `MenuId.TestItemGutter` with the test as its argument.
        let context = self.test_item_context(id, window);
        let contributed = menu_actions(&self.menus, MenuId::TestItemGutter, &context);
        let arg = self.test_item_arg(id);
        if !contributed.is_empty() {
            actions.push(MenuAction::Separator);
        }
        for action in contributed {
            let action = self.forward_with_args(action, std::slice::from_ref(&arg));
            actions.push(action);
        }
        actions
    }

    /// `MultiRunTestDecoration.getContextMenuActions`: the groups any of the tests can run in, then a submenu per test
    /// labeled by its parents until the labels differ, sorted by sortText or label.
    fn multi_test_context_menu_actions(&mut self, tests: &[String], window: &Window) -> Vec<MenuAction> {
        let mut actions = Vec::new();
        for (group, title) in [(GROUP_RUN, "Run All Tests"), (GROUP_COVERAGE, "Run All Tests with Coverage"), (GROUP_DEBUG, "Debug All Tests")] {
            if tests.iter().any(|id| self.test_capabilities(id) & group != 0) {
                let mut args = vec![json!(group)];
                args.extend(tests.iter().map(|id| json!(id)));
                actions.push(self.bound_action(title, "vscode.runTestsById", args));
            }
        }
        let labeled = self.multi_test_labels(tests);
        if !actions.is_empty() && !labeled.is_empty() {
            actions.push(MenuAction::Separator);
        }
        for (label, id) in labeled.iter().take(MAX_TESTS_IN_SUBMENU) {
            let stripped = crate::command_palette::strip_icons(label);
            let title = stripped.split('\n').next().unwrap_or_default().to_owned();
            let submenu = self.test_context_menu_actions(id, window);
            actions.push(MenuAction::Submenu { title, actions: submenu, checked: false });
        }
        let overflow = labeled.len().saturating_sub(MAX_TESTS_IN_SUBMENU);
        if overflow > 0 {
            actions.push(self.bound_action(&format!("{overflow} more tests..."), "_testing.gutterPickAndRun", tests.iter().map(|id| json!(id)).collect()));
        }
        actions
    }

    /// The line's tests with their labels, prefixed by their parents' until the labels differ, sorted by sortText or label.
    fn multi_test_labels(&self, tests: &[String]) -> Vec<(String, String)> {
        let items = &self.testing.collection.items;
        let label_of = |id: &str| items.get(id).map_or(String::new(), |test| test.label().to_owned());
        let mut labeled: Vec<(String, Option<&str>, &String)> = tests.iter().map(|id| (label_of(id), parent_id(id), id)).collect();
        let mut has_parent = true;
        while has_parent {
            let conflicts: Vec<usize> = (0..labeled.len()).filter(|&index| labeled.iter().filter(|(label, ..)| *label == labeled[index].0).count() > 1).collect();
            if conflicts.is_empty() {
                break;
            }
            for index in conflicts {
                let (label, parent, _) = &mut labeled[index];
                match parent {
                    Some(id) => {
                        *label = format!("{} > {label}", label_of(id));
                        *parent = parent_id(id);
                    }
                    None => has_parent = false,
                }
            }
        }
        let sort_key = |id: &str| items.get(id).map_or(String::new(), |test| test.item["sortText"].as_str().unwrap_or(test.label()).to_owned());
        labeled.sort_by(|a, b| crate::command_palette::locale_compare(&sort_key(a.2), &sort_key(b.2)));
        labeled.into_iter().map(|(label, _, id)| (label, id.clone())).collect()
    }

    /// `MultiRunTestDecoration.pickAndRun`: a test of the line, then one of its gutter actions.
    fn pick_and_run_test(&mut self, tests: &[String], window: &mut Window, cx: &mut Context<Self>) {
        let labeled = self.multi_test_labels(tests);
        let entries = labeled.iter().enumerate().map(|(index, (label, _))| PickEntry::Item(Item { handle: index as i64, label: label.clone(), ..Item::default() })).collect();
        let picked_test = self.debug_pick("Select a test to run", entries, window, cx);
        cx.spawn_in(window, async move |this, cx| {
            let Some(index) = picked_test.await.ok().flatten().and_then(|handle| handle.parse::<usize>().ok()) else { return };
            let (label, id) = &labeled[index];
            let Ok((picked_action, commands)) = this.update_in(cx, |workbench, window, cx| {
                let mut commands = Vec::new();
                let mut entries = Vec::new();
                for action in workbench.test_context_menu_actions(id, window) {
                    match action {
                        MenuAction::Command { id, title, .. } => {
                            entries.push(PickEntry::Item(Item { handle: commands.len() as i64, label: title, ..Item::default() }));
                            commands.push(id);
                        }
                        MenuAction::Separator => entries.push(PickEntry::Separator(None)),
                        MenuAction::Submenu { .. } => {}
                    }
                }
                (workbench.debug_pick(label, entries, window, cx), commands)
            }) else { return };
            let Some(index) = picked_action.await.ok().flatten().and_then(|handle| handle.parse::<usize>().ok()) else { return };
            let _ = this.update_in(cx, |workbench, window, cx| drop(workbench.execute_command(&commands[index], Vec::new(), window, cx)));
        })
        .detach();
    }

    /// An item running `command` with `args`, registered under an id of its own since a menu passes every item the
    /// same arguments: the gutter's the line's `{ lineNumber, uri }`, the Test Results tree's the row's context.
    pub(super) fn bound_action(&mut self, title: &str, command: &str, args: Vec<Value>) -> MenuAction {
        MenuAction::Command { id: self.bound_command(command, args), title: title.into(), enabled: true, checked: false, alt: None }
    }

    pub(super) fn bound_command(&mut self, command: &str, args: Vec<Value>) -> String {
        let id = format!("_testing.bound:{command}:{}", Value::from(args.clone()));
        if self.commands.get(&id).is_none() {
            let command = command.to_owned();
            self.commands.register(id.clone(), move |workbench, _, window, cx| workbench.execute_command(&command, args.clone(), window, cx));
        }
        id
    }

    /// `shouldForwardArgs` with `args`: a contributed item and its alternative run with them.
    pub(super) fn forward_with_args(&mut self, action: MenuAction, args: &[Value]) -> MenuAction {
        match action {
            MenuAction::Command { id, title, enabled, checked, alt } => {
                let alt = alt.map(|(alt_id, alt_title)| (self.bound_command(&alt_id, args.to_vec()), alt_title));
                MenuAction::Command { id: self.bound_command(&id, args.to_vec()), title, enabled, checked, alt }
            }
            MenuAction::Submenu { title, actions, checked } => MenuAction::Submenu { title, actions: actions.into_iter().map(|action| self.forward_with_args(action, args)).collect(), checked },
            MenuAction::Separator => MenuAction::Separator,
        }
    }
}

#[cfg(test)]
pub(super) mod tests;