Skip to content

Visual Studio Code, rebuilt in Rust

Rust
7.5 KB
Raw Blame
//! extensionBisect.ts: the binary search over the stored state and the commands across simulated reloads.

use std::cell::Cell;
use std::path::Path;
use std::rc::Rc;
use std::sync::{Arc, Mutex};

use config::registry::Registry;
use config::service::Settings;
use exthost::scan::{ScannedExtension, scan_extension};
use gpui::{TestAppContext, VisualTestContext};
use serde_json::json;

use super::*;
use crate::host_sync::HostSync;
use crate::languages::Languages;
use crate::theme::load_theme;

fn ids(names: &[&str]) -> Vec<String> {
    names.iter().map(|name| name.to_string()).collect()
}

#[test]
fn bisect_halves_the_disabled_extensions_until_one_is_left() {
    let mut storage = Storage::in_memory();
    start(&mut storage, ids(&["a", "b", "c", "d"]));
    let state = BisectState::read(&storage).unwrap();
    assert_eq!((state.low, state.high, state.mid, state.disabled_count()), (0, 4, 0, 4));
    assert!(["a", "b", "c", "d"].iter().all(|id| state.is_disabled(id)));
    assert_eq!(next(&mut storage, &state, true), Some((String::new(), true)), "bad with everything disabled");

    assert_eq!(next(&mut storage, &state, false), None);
    let state = BisectState::read(&storage).unwrap();
    assert_eq!((state.low, state.high, state.mid), (0, 4, 2));
    assert_eq!(["a", "b", "c", "d"].map(|id| state.is_disabled(id)), [false, false, true, true]);
    assert_eq!(next(&mut storage, &state, true), None);
    let state = BisectState::read(&storage).unwrap();
    assert_eq!((state.low, state.high, state.mid), (0, 2, 1));
    assert_eq!(next(&mut storage, &state, false), None);
    let state = BisectState::read(&storage).unwrap();
    assert_eq!((state.low, state.high, state.mid), (1, 2, 1));
    assert_eq!(next(&mut storage, &state, false), Some(("b".into(), false)));
    assert!(BisectState::read(&storage).is_none(), "the last step resets");

    assert_eq!((reload_estimate(0), reload_estimate(1), reload_estimate(4), reload_estimate(10)), (0, 2, 4, 5));
}

fn open(cx: &mut TestAppContext) -> (gpui::Entity<Workbench>, &mut VisualTestContext) {
    let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
    let themes = scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap();
    let theme = load_theme(&[themes], "Dark Modern").unwrap();
    let dir = std::env::temp_dir().join(format!("code-gpui-bisect-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(dir.join("User")).unwrap();
    std::fs::write(dir.join("User/settings.json"), r#"{ "window.dialogStyle": "custom" }"#).unwrap();
    let settings = Arc::new(Mutex::new(Settings::load(Registry::with_extensions(&[]), dir.join("User"), None)));
    let (sender, _receiver) = std::sync::mpsc::channel();
    cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), settings, HostSync::new(sender), cx))
}

/// What a reload changes here: the window reads the bisect state again and shows its prompt.
fn reload(workbench: &gpui::Entity<Workbench>, cx: &mut VisualTestContext) {
    workbench.update(cx, |workbench, _| {
        workbench.extensions_viewlet.bisect = BisectState::read(&workbench.application_storage.lock().unwrap());
        workbench.notifications.model.items.clear();
        workbench.show_extension_bisect_prompt();
    });
}

/// Presses a button of the custom dialog the command shows.
fn press(workbench: &gpui::Entity<Workbench>, cx: &mut VisualTestContext, button: usize) -> (String, Option<String>, bool) {
    cx.run_until_parked();
    let shown = workbench.update(cx, |workbench, cx| {
        let shown = workbench.dialogs.first().map(|shown| (shown.dialog.detail.clone().unwrap(), shown.dialog.checkbox.clone(), shown.dialog.checkbox_checked)).unwrap();
        workbench.close_custom_dialog(button, cx);
        shown
    });
    cx.run_until_parked();
    shown
}

fn disabled(workbench: &gpui::Entity<Workbench>, cx: &mut VisualTestContext) -> Vec<String> {
    workbench.read_with(cx, |workbench, _| {
        let viewlet = &workbench.extensions_viewlet;
        let disabled = workbench.local_extensions().into_iter().filter(|extension| extension.enablement == EnablementState::DisabledByEnvironment);
        let startup = crate::workbench::extensions_view::disabled_at_startup(&viewlet.installed, &mut Storage::in_memory(), None, &[], viewlet.bisect.as_ref());
        let disabled: Vec<String> = disabled.map(|extension| extension.local.unwrap().id).collect();
        assert_eq!(disabled, startup, "the window and the host leave out the same extensions");
        disabled
    })
}

#[gpui::test]
fn bisect_finds_the_extension_and_keeps_it_disabled(cx: &mut TestAppContext) {
    let (workbench, cx) = open(cx);
    let reloads = Rc::new(Cell::new(0));
    workbench.update(cx, |workbench, _| {
        let counted = reloads.clone();
        workbench.commands.register(RELOAD_WINDOW, move |_, _, _, _| {
            counted.set(counted.get() + 1);
            Outcome::done()
        });
        let extension = |id: &str, builtin: bool| ScannedExtension { id: id.into(), location: format!("/{id}").into(), description: json!({ "name": id, "isBuiltin": builtin }) };
        workbench.extensions_viewlet.installed = vec![extension("pub.a", false), extension("pub.b", false), extension("pub.c", false), extension("vscode.builtin", true)];
    });
    let run = |workbench: &gpui::Entity<Workbench>, cx: &mut VisualTestContext, id: &str, args: Vec<serde_json::Value>| {
        drop(workbench.update_in(cx, |workbench, window, cx| workbench.execute_command(id, args, window, cx)));
    };

    run(&workbench, cx, "extension.bisect.start", Vec::new());
    let (detail, _, _) = press(&workbench, cx, 0);
    assert!(detail.contains("(~3 times)"), "{detail}");
    assert_eq!(reloads.get(), 1);
    reload(&workbench, cx);
    assert_eq!(disabled(&workbench, cx), ["pub.a", "pub.b", "pub.c"], "built-in extensions stay out of the bisect");
    workbench.read_with(cx, |workbench, _| {
        let item = workbench.notifications.model.items.first().unwrap();
        assert_eq!(item.message.raw, disabled_message(3));
        let labels: Vec<&str> = item.primary.iter().map(|action| action.label.as_str()).collect();
        assert_eq!(labels, ["I can't reproduce", "I can reproduce", "Stop Bisect"]);
        assert_eq!(workbench.context_keys.get("isExtensionBisectActive"), Some(&json!(true)));
    });

    run(&workbench, cx, "extension.bisect.next", vec![json!(false)]);
    reload(&workbench, cx);
    assert_eq!(disabled(&workbench, cx), ["pub.b", "pub.c"]);
    run(&workbench, cx, "extension.bisect.next", vec![json!(true)]);
    reload(&workbench, cx);
    assert_eq!(disabled(&workbench, cx), ["pub.a"]);
    assert_eq!(reloads.get(), 3);

    run(&workbench, cx, "extension.bisect.next", vec![json!(false)]);
    let (detail, checkbox, checked) = press(&workbench, cx, 0);
    assert_eq!(detail, "Extension Bisect is done and has identified pub.a as the extension causing the problem.");
    assert_eq!((checkbox.as_deref(), checked), (Some("Keep this extension disabled"), true));
    assert_eq!(reloads.get(), 4);
    reload(&workbench, cx);
    assert!(workbench.read_with(cx, |workbench, _| workbench.extensions_viewlet.bisect.is_none() && workbench.notifications.model.items.is_empty()));
    let user_state = workbench.read_with(cx, |workbench, _| {
        let mut profile = workbench.profile_storage.lock().unwrap();
        Enablement { profile: &mut profile, workspace: None }.user_state(&Identifier { id: "pub.a".into(), uuid: None })
    });
    assert_eq!(user_state, EnablementState::DisabledGlobally);
}