Skip to content

Visual Studio Code, rebuilt in Rust

Rust
13.2 KB
Raw Blame
use std::path::{Path, PathBuf};
use std::sync::mpsc::Receiver;
use std::sync::{Arc, Mutex};
use std::time::Duration;

use config::registry::Registry;
use config::service::Settings;
use exthost::extension_management::{Job, UserExtensions};
use files::watcher::{Change, ChangeType};
use exthost::gallery::test_support::{gallery_entry, serve_gallery};
use exthost::gallery::{Gallery, extension_key};
use gpui::{TestAppContext, VisualTestContext};
use serde_json::json;

use crate::host_sync::{HostMessage, HostSync};
use crate::languages::Languages;
use crate::workbench::Workbench;

struct Fixture {
    dir: PathBuf,
    messages: Receiver<HostMessage>,
}

impl Drop for Fixture {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.dir);
    }
}

/// A workbench on a fake gallery of `entries` (id, dependencies, pack) with signature checks off; the downloads of
/// `entries` are in the cache already, and the host is a channel the test reads its jobs from.
fn workbench_on_gallery<'a>(name: &str, entries: &[(&str, &[&str], &[&str])], cx: &'a mut TestAppContext) -> (Fixture, gpui::Entity<Workbench>, &'a mut VisualTestContext) {
    let dir = std::env::temp_dir().join(format!("code-gpui-{name}-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    let user = dir.join("data/User");
    std::fs::create_dir_all(&user).unwrap();
    std::fs::write(user.join("settings.json"), r#"{ "extensions.verifySignature": false }"#).unwrap();
    let served = entries.iter().map(|(id, dependencies, pack)| (id.to_string(), gallery_entry(id, dependencies, pack))).collect();
    let gallery = Gallery { service_url: serve_gallery(served), product_version: crate::VERSION.clone() };
    let downloads = dir.join("data/CachedExtensionVSIXs");
    std::fs::create_dir_all(&downloads).unwrap();
    for (id, _, _) in entries {
        let extension = gallery.installable_extension(id, None, false).unwrap();
        std::fs::write(downloads.join(extension_key(&extension).to_lowercase()), b"").unwrap();
    }
    let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
    let themes = exthost::scan::scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap();
    let theme = crate::theme::load_theme(&[themes], "Dark Modern").unwrap();
    let settings = Arc::new(Mutex::new(Settings::load(Registry::with_extensions(&[]), user, None)));
    let (sender, messages) = std::sync::mpsc::channel();
    let (workbench, cx) = cx.add_window_view(|_, cx| {
        let mut workbench = Workbench::new(theme, app_root, None, Languages::new(&[]), settings, HostSync::new(sender), cx);
        workbench.gallery_url = gallery.service_url;
        workbench.trust_publishers(&[("a".into(), "Red Hat".into())]);
        workbench
    });
    (Fixture { dir, messages }, workbench, cx)
}

/// extensionsActions.ts `InstallAction` on an unsigned extension: the prompt is refused in tests (skipDialogs), and the
/// signed install fails `NotSigned`; "Install Anyway" (`donotVerifySignature`) installs it.
#[gpui::test]
fn install_anyway_installs_an_unsigned_extension(cx: &mut TestAppContext) {
    let (fixture, workbench, cx) = workbench_on_gallery("install-unsigned", &[("a.yaml", &[], &[])], cx);
    workbench.update(cx, |workbench, _| workbench.settings.lock().unwrap().update_value("extensions.verifySignature", Some(&json!(true)), config::service::Target::User, None, &[]).unwrap());
    workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("workbench.extensions.action.installUnsigned", vec![json!("a.yaml")], window, cx)));
    cx.run_until_parked();
    workbench.update(cx, |workbench, cx| drop(workbench.install_from_gallery_verifying("a.yaml".into(), None, false, true, cx)));
    cx.run_until_parked();
    assert_eq!(sent_jobs(&fixture.messages), Vec::<String>::new(), "refused prompt and the signed install send nothing");
    workbench.update(cx, |workbench, cx| drop(workbench.install_from_gallery_verifying("a.yaml".into(), None, false, false, cx)));
    cx.run_until_parked();
    assert_eq!(sent_jobs(&fixture.messages), ["a.yaml"]);
}

/// The gallery's id and version are untrusted: one that would leave the picked folder names no file.
#[test]
fn a_vsix_name_rejects_a_path_from_the_gallery() {
    use super::vsix_file_name;
    assert_eq!(vsix_file_name("a.yaml", "2.0.0", exthost::gallery::UNDEFINED).unwrap(), "a.yaml-2.0.0.vsix");
    for (id, version) in [("..", "1.0.0"), ("a/../../b", "1.0.0"), ("a.b", "..\\x"), ("", "1.0.0"), ("a.b", "")] {
        assert!(vsix_file_name(id, version, exthost::gallery::UNDEFINED).is_err(), "{id} {version}");
    }
}

/// The jobs sent to the host: a gallery install by its id, a VSIX install as `vsix`.
fn sent_jobs(messages: &Receiver<HostMessage>) -> Vec<String> {
    let mut jobs = Vec::new();
    for message in messages.try_iter() {
        match message.extensions {
            Some((Job::InstallGallery(_, extension), _)) => jobs.push(extension.id),
            Some((Job::InstallVsix(_), _)) => jobs.push("vsix".into()),
            _ => {}
        }
    }
    jobs
}

fn write_vsix(dir: &Path, dependencies: &[&str], pack: &[&str]) -> PathBuf {
    let manifest = json!({ "name": "root", "publisher": "a", "version": "1.0.0", "engines": { "vscode": "^1.0.0" }, "extensionDependencies": dependencies, "extensionPack": pack }).to_string();
    let vsix = dir.join("root.vsix");
    std::fs::write(&vsix, exthost::zip::write_stored(&[("extension/package.json", manifest.as_bytes())])).unwrap();
    vsix
}

/// abstractExtensionManagementService.ts `installExtensions`: a VSIX's dependencies and pack members come from the
/// gallery and install before it.
#[gpui::test]
fn the_dependencies_and_pack_of_a_vsix_install_before_it(cx: &mut TestAppContext) {
    let entries: &[(&str, &[&str], &[&str])] = &[("a.dep", &[], &[]), ("a.member", &[], &[])];
    let (fixture, workbench, cx) = workbench_on_gallery("vsix-dependencies", entries, cx);
    let vsix = write_vsix(&fixture.dir, &["a.dep"], &["a.member"]);
    workbench.update(cx, |workbench, cx| drop(workbench.install_vsixs(vec![vsix], false, cx)));
    cx.run_until_parked();
    assert_eq!(sent_jobs(&fixture.messages), ["a.dep", "a.member", "vsix"]);
}

/// A VSIX ignores its dependencies and pack when the gallery cannot resolve them.
#[gpui::test]
fn a_vsix_installs_alone_when_the_gallery_fails(cx: &mut TestAppContext) {
    let (fixture, workbench, cx) = workbench_on_gallery("vsix-no-gallery", &[], cx);
    let vsix = write_vsix(&fixture.dir, &["a.dep"], &[]);
    workbench.update(cx, |workbench, cx| {
        workbench.gallery_url = "http://127.0.0.1:1".into();
        drop(workbench.install_vsixs(vec![vsix], false, cx));
    });
    cx.run_until_parked();
    assert_eq!(sent_jobs(&fixture.messages), ["vsix"]);
}

/// `installFromGallery` then `installExtensions`: dependencies and pack members install before the extension.
#[gpui::test]
fn a_gallery_install_brings_its_dependencies_and_pack_first(cx: &mut TestAppContext) {
    let entries: &[(&str, &[&str], &[&str])] = &[("a.root", &["a.dep"], &["a.member"]), ("a.dep", &["a.leaf"], &[]), ("a.member", &[], &[]), ("a.leaf", &[], &[])];
    let (fixture, workbench, cx) = workbench_on_gallery("gallery-dependencies", entries, cx);
    workbench.update(cx, |workbench, cx| drop(workbench.install_from_gallery("a.root".into(), None, false, cx)));
    cx.run_until_parked();
    assert_eq!(sent_jobs(&fixture.messages), ["a.dep", "a.leaf", "a.member", "a.root"]);
}

/// extensionsActions.ts `InstallAnotherVersionAction`: a pre-release install picks from every compatible version, the
/// installed one marked current, and the picked version installs.
#[gpui::test]
fn install_specific_version_installs_the_picked_version(cx: &mut TestAppContext) {
    let (fixture, workbench, cx) = workbench_on_gallery("another-version", &[("a.yaml", &[], &[])], cx);
    let description = json!({ "name": "yaml", "publisher": "a", "version": "2.1.2026112008", "preRelease": true, "uuid": "uuid-a.yaml" });
    let installed = exthost::scan::ScannedExtension { id: "a.yaml".into(), location: fixture.dir.clone(), description };
    workbench.update(cx, |workbench, _| {
        workbench.load_keybindings(crate::keybindings::default_keybindings(&[]), "/nonexistent/User/keybindings.json".into());
        workbench.extensions = vec![installed.clone()];
        workbench.extensions_viewlet.installed = vec![installed];
    });
    let enabled = workbench.update_in(cx, |workbench, window, _| {
        let extension = workbench.find_extension("a.yaml").unwrap();
        let actions = workbench.manage_extension_actions(&extension, false, window);
        actions.into_iter().find_map(|action| match action {
            crate::menus::MenuAction::Command { id, enabled, .. } if id == "workbench.extensions.action.install.anotherVersion" => Some(enabled),
            _ => None,
        })
    });
    assert_eq!(enabled, Some(true));
    workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("workbench.extensions.action.install.anotherVersion", vec![json!("a.yaml")], window, cx)));
    cx.run_until_parked();
    let picks = workbench.read_with(cx, |workbench, _| {
        let input = workbench.quick_inputs.current().expect("the version pick");
        let rows = input.order.iter().map(|row| (input.rows[*row].item.label.clone(), input.rows[*row].item.description.clone().unwrap_or_default()));
        (input.placeholder.clone().unwrap_or_default(), rows.collect::<Vec<_>>())
    });
    assert_eq!(picks.0, "Select Version to Install");
    let labels: Vec<&str> = picks.1.iter().map(|(label, _)| label.as_str()).collect();
    assert_eq!(labels, ["2.1.2026112008", "2.0.0"]);
    assert!(picks.1[0].1.ends_with(" (pre-release) (current)"), "{}", picks.1[0].1);
    assert!(!picks.1[1].1.contains('('), "{}", picks.1[1].1);
    cx.simulate_keystrokes("down enter");
    cx.run_until_parked();
    assert_eq!(sent_jobs(&fixture.messages), ["a.yaml"]);
}

/// extensionsWorkbenchService.ts `downloadVSIX` with `any`: every version of the gallery extension is offered, then the
/// folder to save the VSIX in is asked for.
#[gpui::test]
fn download_specific_version_picks_a_version_then_a_folder(cx: &mut TestAppContext) {
    let (_fixture, workbench, cx) = workbench_on_gallery("download-version", &[("a.yaml", &[], &[])], cx);
    workbench.update(cx, |workbench, _| workbench.load_keybindings(crate::keybindings::default_keybindings(&[]), "/nonexistent/User/keybindings.json".into()));
    workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("workbench.extensions.action.downloadSpecificVersion", vec![json!("a.yaml")], window, cx)));
    cx.run_until_parked();
    let picks = workbench.read_with(cx, |workbench, _| {
        let input = workbench.quick_inputs.current().expect("the version pick");
        let labels = input.order.iter().map(|row| input.rows[*row].item.label.clone());
        (input.placeholder.clone().unwrap_or_default(), labels.collect::<Vec<_>>())
    });
    assert_eq!(picks, ("Select Version to Download".to_string(), vec!["2.1.2026112008".to_string(), "2.0.0".to_string()]));
    cx.simulate_keystrokes("down enter");
    cx.run_until_parked();
    assert!(cx.did_prompt_for_paths(), "the folder dialog opens");
    cx.simulate_path_prompt_response(|options| {
        assert!(options.directories && !options.files);
        None
    });
}

/// The deltas sent to the host: the ids started and the ids stopped.
fn sent_deltas(messages: &Receiver<HostMessage>) -> Vec<(Vec<String>, Vec<String>)> {
    let mut deltas = Vec::new();
    for message in messages.try_iter() {
        if let Some((Job::Delta(to_add, to_remove), _)) = message.extensions {
            deltas.push((to_add.into_iter().map(|extension| extension.id).collect(), to_remove));
        }
    }
    deltas
}

/// extensionsWatcher.ts: an extension the CLI adds to the profile's extensions.json starts in the running window, one
/// it removes stops, and one that already runs makes no delta.
#[gpui::test]
fn extensions_installed_by_another_source_start_and_stop(cx: &mut TestAppContext) {
    let (fixture, workbench, cx) = workbench_on_gallery("extensions-watcher", &[], cx);
    let cli = UserExtensions::new(fixture.dir.join("extensions"), &crate::VERSION);
    workbench.update(cx, |workbench, _| workbench.extensions_viewlet.user = Some(cli.clone_for_profile()));
    let vsix = write_vsix(&fixture.dir, &[], &[]);
    let changed = vec![Change { path: cli.extensions_file.clone(), kind: ChangeType::Updated }];

    let installed = cli.install_vsix(&vsix).unwrap();
    workbench.update(cx, |workbench, cx| workbench.profile_extensions_changed(&changed, cx));
    cx.executor().advance_clock(Duration::from_millis(200));
    cx.run_until_parked();
    assert_eq!(sent_deltas(&fixture.messages), [(vec!["a.root".to_owned()], Vec::new())]);

    workbench.update(cx, |workbench, cx| {
        workbench.extensions = vec![installed];
        drop(workbench.apply_profile_extensions(cx));
    });
    cx.run_until_parked();
    assert_eq!(sent_deltas(&fixture.messages), []);

    cli.uninstall("a.root").unwrap();
    workbench.update(cx, |workbench, cx| workbench.profile_extensions_changed(&changed, cx));
    cx.executor().advance_clock(Duration::from_millis(200));
    cx.run_until_parked();
    assert_eq!(sent_deltas(&fixture.messages), [(Vec::new(), vec!["a.root".to_owned()])]);
}