Visual Studio Code, rebuilt in Rust
Rust
//! testingExplorerView.ts `getRunGroupDropdown`: the view title's run and debug dropdowns, with the profile pickers
//! of testingConfigurationUi.ts and testProfileService.ts's default profiles the user picks.
use gpui::{Bounds, Context, Pixels, Task, Window};
use serde_json::{Map, Value, json};
use super::Workbench;
use crate::commands::Outcome;
use crate::main_thread_quick_open::Owner;
use crate::menus::{MenuAction, MenuId, menu_actions};
use crate::quick_input::{Entry, Item, Kind, QuickInput};
use crate::testing::{GROUP_COVERAGE, GROUP_DEBUG, GROUP_RUN, Profile};
/// testProfileService.ts `userDefaults`: `{ [controllerId]: { [profileId]: isDefault } }` in the workspace.
const DEFAULTS_KEY: &str = "testingPreferredProfiles2";
/// testProfileService.ts `addProfile`: the user's stored choice wins over the extension's `isDefault`.
pub(super) fn stored_profile_default(storage: &storage::Storage, profile: &Profile) -> Option<bool> {
let defaults: Value = serde_json::from_str(storage.get(DEFAULTS_KEY)?).ok()?;
defaults[&profile.controller_id][profile.profile_id.to_string()].as_bool()
}
/// `updateProfile`: an `isDefault` update is stored as if the user had picked it.
pub(super) fn store_profile_default(storage: &mut storage::Storage, profile: &Profile) {
let mut defaults: Value = storage.get(DEFAULTS_KEY).and_then(|stored| serde_json::from_str(stored).ok()).unwrap_or_else(|| json!({}));
defaults[&profile.controller_id][profile.profile_id.to_string()] = json!(profile.is_default);
storage.set(DEFAULTS_KEY, defaults.to_string());
}
fn group_context(group: u64) -> Option<&'static str> {
match group {
GROUP_RUN => Some("run"),
GROUP_DEBUG => Some("debug"),
GROUP_COVERAGE => Some("coverage"),
_ => None,
}
}
impl super::testing_service::TestingService {
/// `all()`: the profiles of each controller in the order they were published, sorted as `sorter`: defaults
/// first, then by label.
fn profiles_by_controller(&self) -> Vec<Vec<Profile>> {
let mut controllers: Vec<Vec<Profile>> = Vec::new();
for profile in &self.profiles {
match controllers.iter_mut().find(|profiles| profiles[0].controller_id == profile.controller_id) {
Some(profiles) => profiles.push(profile.clone()),
None => controllers.push(vec![profile.clone()]),
}
}
for profiles in &mut controllers {
profiles.sort_by(|a, b| b.is_default.cmp(&a.is_default).then_with(|| crate::command_palette::locale_compare(&a.label, &b.label)));
}
controllers
}
/// `getGroupDefaultProfiles`: the group's default profiles, else its first one.
fn group_default_profiles(&self, group: u64) -> Vec<Profile> {
let all: Vec<Profile> = self.profiles_by_controller().into_iter().flatten().collect();
let defaults: Vec<Profile> = all.iter().filter(|profile| profile.group == group && profile.is_default).cloned().collect();
if !defaults.is_empty() {
return defaults;
}
all.into_iter().filter(|profile| profile.group == group).take(1).collect()
}
pub(super) fn group_profile_count(&self, group: u64) -> usize {
self.profiles.iter().filter(|profile| profile.group == group).count()
}
/// `setGroupDefaultProfiles`: the group's profiles in `chosen` become its defaults, and a controller's profile
/// of another group named as one of them follows it. Returns the defaults to store, replacing the stored ones.
fn set_group_default_profiles(&mut self, group: u64, chosen: &[i64]) -> Value {
for profile in self.profiles.iter_mut().filter(|profile| profile.group == group) {
profile.is_default = chosen.contains(&profile.profile_id);
}
let in_group: Vec<(String, String, bool)> = self.profiles.iter().filter(|profile| profile.group == group).map(|profile| (profile.controller_id.clone(), profile.label.clone(), profile.is_default)).collect();
let mut next = Map::new();
for profile in &mut self.profiles {
let entry = next.entry(profile.controller_id.clone()).or_insert_with(|| json!({}));
if profile.group != group {
let Some((.., is_default)) = in_group.iter().find(|(controller, label, _)| *controller == profile.controller_id && *label == profile.label) else { continue };
profile.is_default = *is_default;
}
entry[profile.profile_id.to_string()] = json!(profile.is_default);
}
Value::Object(next)
}
}
impl Workbench {
pub(super) fn register_testing_profile_commands(&mut self) {
// testExplorerActions.ts `SelectDefaultTestProfiles`.
self.commands.register("testing.selectDefaultTestProfiles", |workbench, args, window, cx| {
let group = args.first().and_then(Value::as_u64).unwrap_or(GROUP_RUN);
let selected = workbench.testing.group_default_profiles(group);
let picked = workbench.pick_test_profiles(Some(group), false, Some(&selected), None, window, cx);
cx.spawn_in(window, async move |this, cx| {
let Some(profiles) = picked.await.filter(|profiles| !profiles.is_empty()) else { return };
let chosen: Vec<i64> = profiles.iter().map(|profile| profile.profile_id).collect();
let _ = this.update_in(cx, |workbench, window, cx| workbench.set_group_default_profiles(group, &chosen, window, cx));
})
.detach();
Outcome::done()
});
// `ConfigureTestProfilesAction`: testProfileService.ts `configure` of the picked profile.
self.commands.register("testing.configureProfile", |workbench, args, window, cx| {
let group = args.first().and_then(Value::as_u64);
let picked = workbench.pick_test_profiles(group, true, None, Some("Select a profile to update"), window, cx);
cx.spawn_in(window, async move |this, cx| {
let Some(profile) = picked.await.and_then(|profiles| profiles.into_iter().next()) else { return };
let request = vec![json!(profile.controller_id), json!(profile.profile_id)];
let _ = this.update(cx, |workbench, _| workbench.host.send("ExtHostTesting", "$configureRunProfile", request));
})
.detach();
Outcome::done()
});
}
fn set_group_default_profiles(&mut self, group: u64, chosen: &[i64], window: &mut Window, cx: &mut Context<Self>) {
let defaults = self.testing.set_group_default_profiles(group, chosen);
self.workspace_storage.lock().unwrap().set(DEFAULTS_KEY, defaults.to_string());
self.send_default_profiles();
self.continuous_profiles_changed(window, cx);
cx.notify();
}
/// testingConfigurationUi.ts `buildPicker` for `vscode.pickTestProfile` (one profile) and, given `selected`,
/// `vscode.pickMultipleTestProfiles`: each controller's profiles by group under the group's name (none when
/// showing `only_group`), described by the controller's label.
fn pick_test_profiles(&mut self, only_group: Option<u64>, only_configurable: bool, selected: Option<&[Profile]>, placeholder: Option<&str>, window: &mut Window, cx: &mut Context<Self>) -> Task<Option<Vec<Profile>>> {
let mut entries = Vec::new();
let mut profiles = Vec::new();
for mut controller in self.testing.profiles_by_controller() {
let description = self.testing.controllers.get(&controller[0].controller_id).map(|controller| controller.label.clone());
controller.sort_by_key(|profile| profile.group);
let mut header = None;
for profile in &controller {
if only_group.is_some_and(|group| group != profile.group) || (only_configurable && !profile.has_configuration_handler) {
continue;
}
if only_group.is_none() && header != Some(profile.group) {
header = Some(profile.group);
entries.push(Entry::Separator(super::testing_continuous::group_name(profile.group).map(str::to_owned)));
}
let picked = selected.is_some_and(|selected| selected.iter().any(|chosen| chosen.controller_id == profile.controller_id && chosen.profile_id == profile.profile_id));
entries.push(Entry::Item(Item { handle: profiles.len() as i64, label: profile.label.clone(), description: description.clone(), picked, ..Item::default() }));
profiles.push(profile.clone());
}
}
let (sender, receiver) = futures::channel::oneshot::channel();
let mut input = QuickInput::new(0, Kind::QuickPick);
input.placeholder = Some(placeholder.unwrap_or("Pick a test profile to use").into());
input.can_select_many = selected.is_some();
input.set_items(entries);
input.select_picked_items();
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 handles = receiver.await.ok().flatten()?;
Some(handles.split(',').filter_map(|handle| profiles.get(handle.parse::<usize>().ok()?).cloned()).collect())
})
}
/// `getTestConfigGroupActions`: each controller's profiles of the group under its disabled label, then the
/// `testing/profiles/context` actions, then Select Default Profile and Configure Test Profiles.
pub(super) fn show_run_group_dropdown(&mut self, group: u64, anchor: Bounds<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
let defaults = self.testing.group_default_profiles(group);
let mut profile_actions = Vec::new();
let mut participating = 0;
let mut has_configurable = false;
for controller in self.testing.profiles_by_controller() {
let in_group: Vec<Profile> = controller.into_iter().filter(|profile| profile.group == group).collect();
let Some(first) = in_group.first() else { continue };
let label = self.testing.controllers.get(&first.controller_id).map(|controller| controller.label.clone()).unwrap_or_default();
profile_actions.push(MenuAction::Command { id: String::new(), title: label.into(), enabled: false, checked: false, alt: None });
for profile in in_group {
has_configurable |= profile.has_configuration_handler;
participating += 1;
let is_default = defaults.iter().any(|default| default.controller_id == profile.controller_id && default.profile_id == profile.profile_id);
let title = if is_default { format!("{} (Default)", profile.label) } else { profile.label.clone() };
// The menu runs commands: one per profile stands in for the dropdown's plain actions.
let id = format!("_testing.runUsingProfile.{}.{}", profile.controller_id, profile.profile_id);
self.commands.unregister(&id);
self.commands.register(id.clone(), move |workbench, _, window, cx| {
workbench.run_tests_with_profile(&profile, window, cx);
Outcome::done()
});
profile_actions.push(MenuAction::Command { id, title: title.into(), enabled: true, checked: false, alt: None });
}
}
let mut context = self.key_context(window);
if let Some(name) = group_context(group) {
context.insert("testing.profile.context.group".into(), json!(name));
}
let menu = menu_actions(&self.menus, MenuId::TestProfilesContext, &context);
let mut post_actions = Vec::new();
if participating > 1 {
post_actions.push(self.group_command_action("testing.selectDefaultTestProfiles", "Select Default Profile", group));
}
if has_configurable {
post_actions.push(self.group_command_action("testing.configureProfile", "Configure Test Profiles", group));
}
let mut actions = Vec::new();
for part in [profile_actions, menu, post_actions] {
if part.is_empty() {
continue;
}
if !actions.is_empty() {
actions.push(MenuAction::Separator);
}
actions.extend(part);
}
self.show_context_menu_actions(actions, &context, anchor, Vec::new(), window, cx);
}
/// An action running `command` with the group as its argument.
fn group_command_action(&mut self, command: &'static str, title: &str, group: u64) -> MenuAction {
let id = format!("_{command}.{group}");
self.commands.unregister(&id);
self.commands.register(id.clone(), move |workbench, _, window, cx| workbench.execute_command(command, vec![json!(group)], window, cx));
MenuAction::Command { id, title: title.into(), enabled: true, checked: false, alt: None }
}
/// A dropdown profile's run: `getTreeIncludeExclude(profile)` over the roots the profile can run.
fn run_tests_with_profile(&mut self, profile: &Profile, window: &mut Window, cx: &mut Context<Self>) {
let roots: Vec<String> = self.testing.collection.roots.iter().filter(|root| **root == profile.controller_id).cloned().collect();
let (include, exclude) = self.testing_include_exclude(profile.group, Some(&roots));
let request = json!({ "exclude": exclude, "group": profile.group, "targets": [{ "profileId": profile.profile_id, "controllerId": profile.controller_id, "testIds": include }] });
self.run_resolved_tests(request, window, cx);
}
}
#[cfg(test)]
mod tests;