Skip to content

Visual Studio Code, rebuilt in Rust

Rust
13.4 KB
Raw Blame
//! testExplorerActions.ts's `MenuId.TestItem` actions and testingExplorerView.ts `onContextMenu` with
//! `getActionableElementActions`: a test row's context menu.

use std::collections::HashMap;

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

use super::Workbench;
use crate::commands::Outcome;
use crate::contextkey::Expr;
use crate::main_thread_quick_open::Owner;
use crate::menus::{Entry, MenuId, MenuItem, Toggled, menu_group_actions};
use crate::quick_input::{Entry as PickEntry, Item, Kind, QuickInput};
use crate::testing::{GROUP_COVERAGE, GROUP_DEBUG, GROUP_RUN, Profile, ResultState, parent_id};

/// marshallingIds.ts `MarshalledId.TestItemContext`.
const TEST_ITEM_CONTEXT_MID: u64 = 16;
/// testTypes.ts `TestRunProfileBitset.HasNonDefaultProfile`.
pub(super) const HAS_NON_DEFAULT_PROFILE: u64 = 1 << 4;
const EXCLUDED_KEY: &str = "excludedTestItems";

/// The tests a test command runs on: test ids, or a row's `TestItemTreeElement.toJSON` (its chain of serialized
/// tests below the controller, or `{ controllerId }` for a controller's root).
pub(super) fn test_ids(args: &[Value]) -> Vec<String> {
    let mut ids = Vec::new();
    for arg in args {
        let id = match arg["tests"].as_array().and_then(|tests| tests.last()) {
            Some(test) => test["item"]["extId"].as_str(),
            None => arg.as_str().or(arg["controllerId"].as_str()).or(arg["id"].as_str()),
        };
        ids.extend(id.map(str::to_owned));
    }
    ids
}

/// testingContextKeys.ts `testResultStateToContextValues`.
pub(super) fn result_state_context(state: ResultState) -> &'static str {
    match state {
        ResultState::Unset => "unset",
        ResultState::Queued => "queued",
        ResultState::Running => "running",
        ResultState::Passed => "passed",
        ResultState::Failed => "failed",
        ResultState::Skipped => "skipped",
        ResultState::Errored => "errored",
    }
}

impl Workbench {
    pub(super) fn register_test_item_commands(&mut self) {
        // `RunVisibleAction`: the shown tests within the row's.
        for (id, group) in [("testing.run", GROUP_RUN), ("testing.debug", GROUP_DEBUG), ("testing.coverage", GROUP_COVERAGE)] {
            self.commands.register(id, move |workbench, args, window, cx| {
                let (include, exclude) = workbench.testing_include_exclude(group, Some(&test_ids(&args)));
                workbench.run_tests(&include, Some(&exclude), group, window, cx);
                cx.notify();
                Outcome::done()
            });
        }
        self.commands.register("testing.editFocusedTest", |workbench, args, window, cx| {
            if let Some(id) = test_ids(&args).first() {
                workbench.reveal_test(id, window, cx);
            }
            Outcome::done()
        });
        // `HideTestAction`, `UnhideTestAction` and `UnhideAllTestsAction`.
        for (id, exclude) in [("testing.hideTest", true), ("testing.unhideTest", false)] {
            self.commands.register(id, move |workbench, args, _, cx| {
                for test in test_ids(&args) {
                    workbench.set_test_excluded(&test, exclude, cx);
                }
                Outcome::done()
            });
        }
        self.commands.register("testing.unhideAllTests", |workbench, _, _, cx| {
            workbench.testing.excluded.clear();
            workbench.store_test_exclusions(cx);
            Outcome::done()
        });
        // `RunUsingProfileAction`: a profile of the first test's, then the tests that profile can run.
        self.commands.register("testing.runUsing", |workbench, args, window, cx| {
            let ids = test_ids(&args);
            let Some(first) = ids.first() else { return Outcome::done() };
            let picked = workbench.pick_test_profile(first, window, cx);
            cx.spawn_in(window, async move |this, cx| {
                let Some(profile) = picked.await else { return };
                let _ = this.update_in(cx, |workbench, window, cx| {
                    let items = &workbench.testing.collection.items;
                    let test_ids: Vec<&String> = ids.iter().filter(|id| items.get(*id).is_some_and(|test| profile.can_run(test))).collect();
                    let request = json!({ "group": profile.group, "targets": [{ "profileId": profile.profile_id, "controllerId": profile.controller_id, "testIds": test_ids }] });
                    workbench.run_resolved_tests(request, window, cx);
                    cx.notify();
                });
            })
            .detach();
            Outcome::done()
        });
    }

    /// testExplorerActions.ts's `MenuId.TestItem` registrations, then the `testing/item/context` contributions.
    pub(super) fn test_item_menus(&self) -> Vec<MenuItem> {
        let mut items = Vec::new();
        let mut add = |id: &str, title: &str, group: &str, order: f64, when: &str, precondition: Option<&str>, toggled: Option<Toggled>| {
            let entry = Entry::Command { id: id.to_owned(), precondition: precondition.and_then(Expr::deserialize), toggled, alt: None };
            items.push(MenuItem { menu: MenuId::TestItem, entry, title: title.to_owned(), group: group.to_owned(), order, when: Expr::deserialize(when) });
        };
        // `ActionOrder`: Run 11, Debug 12, Coverage 13, RunContinuous 14, RunUsing 15, GoToTest 20.
        for group in ["inline", "builtin@1"] {
            add("testing.run", "Run Test", group, 11., "testing.hasRunnableTests", None, None);
            add("testing.debug", "Debug Test", group, 12., "testing.hasDebuggableTests", None, None);
            add("testing.coverage", "Run Test with Coverage", group, 13., "testing.hasCoverableTests", None, None);
            let off = Toggled { condition: Expr::deserialize("testing.isContinuousModeOn").expect("a valid expression"), title: Some("Turn off Continuous Run".to_owned()), icon: None };
            add("testing.toggleContinuousRunForTest", "Turn on Continuous Run", group, f64::from(i32::MAX), "testing.supportsContinuousRun", Some("testing.isContinuousModeOn || !testing.isParentRunningContinuously"), Some(off));
        }
        add("testing.continuousRunUsingForTest", "Start Continous Run Using...", "builtin@2", 14., "testing.supportsContinuousRun && !testing.isContinuousModeOn", None, None);
        add("testing.runUsing", "Execute Using Profile...", "builtin@2", 15., "testing.hasNonDefaultProfile", None, None);
        add("testing.editFocusedTest", "Go to Test", "builtin@1", 20., "testing.testItemHasUri", None, None);
        add("testing.hideTest", "Hide Test", "builtin@2", 0., "testing.testItemIsHidden == false", None, None);
        add("testing.unhideTest", "Unhide Test", "", 21., "testing.testItemIsHidden == true", None, None);
        items.extend(self.menus.iter().filter(|item| item.menu == MenuId::TestItem).cloned());
        items
    }

    /// `getActionableElementActions`'s overlay over the workbench's keys, with testProfileService.ts's global
    /// `testing.hasNonDefaultProfile`.
    pub(super) fn test_item_context(&self, id: &str, window: &Window) -> HashMap<String, Value> {
        let mut context = self.key_context(window);
        let testing = &self.testing;
        let Some(test) = testing.collection.items.get(id) else { return context };
        let controller = test.controller_id();
        let mut all = 0;
        for profile in &testing.profiles {
            all |= if all & profile.group != 0 { HAS_NON_DEFAULT_PROFILE } else { profile.group };
        }
        let capabilities = self.test_capabilities(id);
        let supports_continuous = testing.profiles.iter().any(|profile| profile.controller_id == controller && profile.supports_continuous_run && profile.can_run(test));
        let refreshable = testing.controllers.get(controller).is_some_and(|controller| controller.capabilities & 2 != 0);
        let state = result_state_context(testing.state_of(id).unwrap_or_default());
        for (key, value) in [
            ("testing.hasNonDefaultProfile", json!(all & HAS_NON_DEFAULT_PROFILE != 0)),
            ("testId", json!(id.rsplit('\0').next())),
            ("controllerId", json!(controller)),
            ("testing.testItemHasUri", json!(!test.item["uri"].is_null())),
            ("testing.hasRunnableTests", json!(capabilities & GROUP_RUN != 0)),
            ("testing.hasDebuggableTests", json!(capabilities & GROUP_DEBUG != 0)),
            ("testing.hasCoverableTests", json!(capabilities & GROUP_COVERAGE != 0)),
            ("view", json!("workbench.view.testing")),
            ("testing.canRefresh", json!(refreshable && id == controller)),
            ("testing.testItemIsHidden", json!(testing.excluded.iter().any(|excluded| excluded == id))),
            ("testing.isContinuousModeOn", json!(supports_continuous && testing.is_continuous_for(id))),
            ("testing.isParentRunningContinuously", json!(supports_continuous && testing.is_continuous_for_a_parent_of(id))),
            ("testing.supportsContinuousRun", json!(supports_continuous)),
            ("testResultOutdated", json!(testing.is_retired(id))),
            ("testResultState", json!(state)),
        ] {
            context.insert(key.to_owned(), value);
        }
        context
    }

    /// testExclusions.ts `toggle` with `exclude` given.
    fn set_test_excluded(&mut self, id: &str, exclude: bool, cx: &mut Context<Self>) {
        let excluded = &mut self.testing.excluded;
        match excluded.iter().position(|test| test == id) {
            Some(index) if !exclude => _ = excluded.remove(index),
            None if exclude => excluded.push(id.to_owned()),
            _ => return,
        }
        self.store_test_exclusions(cx);
    }

    /// testProfileService.ts `capabilitiesForTest` without its continuous run bit.
    pub(super) fn test_capabilities(&self, id: &str) -> u64 {
        let Some(test) = self.testing.collection.items.get(id) else { return 0 };
        let mut capabilities = 0;
        for profile in &self.testing.profiles {
            if profile.controller_id == test.controller_id() && profile.can_run(test) {
                capabilities |= if capabilities & profile.group != 0 { HAS_NON_DEFAULT_PROFILE } else { profile.group };
            }
        }
        capabilities
    }

    /// The `excludedTestItems` workspace value.
    fn store_test_exclusions(&mut self, cx: &mut Context<Self>) {
        self.workspace_storage.lock().unwrap().set(EXCLUDED_KEY, json!(self.testing.excluded).to_string());
        cx.notify();
    }

    pub(super) fn restore_test_exclusions(&mut self) {
        let stored = self.workspace_storage.lock().unwrap().get(EXCLUDED_KEY).and_then(|raw| serde_json::from_str(raw).ok());
        self.testing.excluded = stored.unwrap_or_default();
    }

    /// `TestItemTreeElement.toJSON`, which the host revives as the `TestItem`.
    pub(super) fn test_item_arg(&self, id: &str) -> Value {
        let Some(mut ancestor) = parent_id(id) else { return json!({ "controllerId": id }) };
        let mut chain = vec![id];
        while let Some(next) = parent_id(ancestor) {
            chain.push(ancestor);
            ancestor = next;
        }
        let items = &self.testing.collection.items;
        let tests: Vec<Value> = chain.into_iter().rev().filter_map(|id| items.get(id)).map(|test| json!({ "expand": test.expand as u8, "item": test.item })).collect();
        json!({ "$mid": TEST_ITEM_CONTEXT_MID, "tests": tests })
    }

    /// testingExplorerView.ts `onContextMenu`: `MenuId.TestItem` but its `inline` group.
    pub(super) fn show_test_item_menu(&mut self, id: &str, anchor: Bounds<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
        let context = self.test_item_context(id, window);
        let actions = menu_group_actions(&self.test_item_menus(), MenuId::TestItem, &context, |group| group != "inline");
        let args = vec![self.test_item_arg(id)];
        self.show_context_menu_actions(actions, &context, anchor, args, window, cx);
    }

    /// testingConfigurationUi.ts `vscode.pickTestProfile` with `onlyForTest`: the profiles of the test's
    /// controller that can run it, under their group's name.
    fn pick_test_profile(&mut self, test_id: &str, window: &mut Window, cx: &mut Context<Self>) -> Task<Option<Profile>> {
        let Some(test) = self.testing.collection.items.get(test_id) else { return Task::ready(None) };
        let mut profiles: Vec<Profile> = self.testing.profiles.iter().filter(|profile| profile.controller_id == test.controller_id() && profile.can_run(test)).cloned().collect();
        profiles.sort_by_key(|profile| profile.group);
        let mut entries = Vec::new();
        for (index, profile) in profiles.iter().enumerate() {
            if index == 0 || profiles[index - 1].group != profile.group {
                entries.push(PickEntry::Separator(super::testing_continuous::group_name(profile.group).map(str::to_owned)));
            }
            entries.push(PickEntry::Item(Item { handle: index as i64, label: profile.label.clone(), ..Item::default() }));
        }
        let (sender, receiver) = futures::channel::oneshot::channel();
        let mut input = QuickInput::new(0, Kind::QuickPick);
        input.placeholder = Some("Pick a test profile to use".into());
        input.set_items(entries);
        let id = self.quick_inputs.add(input, Owner::Debug(Some(sender)));
        self.show_quick_input(id, window, cx);
        self.flush_quick_input_events(window, cx);
        cx.spawn(async move |_, _| {
            let handle = receiver.await.ok().flatten()?;
            profiles.get(handle.parse::<usize>().ok()?).cloned()
        })
    }
}

#[cfg(test)]
mod tests;