Skip to content

Visual Studio Code, rebuilt in Rust

Rust
20.1 KB
Raw Blame
//! `workbench.action.importSettings` and its first-run offer (port feature, Artur): pick an installed VS Code,
//! Cursor or VSCodium, see what will be imported, and write it into the current profile; the extensions are
//! installed again from Open VSX, and the ones Open VSX cannot give are copied from that editor's extensions folder.

use exthost::extension_management::Job;
use gpui::{Context, Window};
use serde_json::Value;

use super::Workbench;
use crate::commands::Outcome;
use crate::extension_enablement::{Enablement, EnablementState, Identifier};
use crate::notifications::Severity;
use crate::quick_input::{Entry, Item, Kind, QuickInput};
use crate::settings_import::{self, Import, Source, Target};

/// Profile storage: the first-run offer was shown.
const OFFERED_KEY: &str = "settingsImport.offered";

impl Workbench {
    pub(super) fn register_settings_import_commands(&mut self) {
        self.commands.register("workbench.action.importSettings", |workbench, _, window, cx| {
            workbench.pick_settings_import_source(window, cx);
            Outcome::done()
        });
    }

    /// The first start with the default user data and no settings of its own offers the import once.
    pub(crate) fn offer_settings_import(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        let default_user_data = !std::env::args().any(|arg| arg == "--user-data-dir");
        let settings_file = self.settings.lock().unwrap().user_files().settings.clone();
        let offered = self.application_storage.lock().unwrap().get(OFFERED_KEY).is_some();
        if !default_user_data || offered || settings_file.exists() || self.skip_dialogs || import_sources().is_empty() {
            return;
        }
        self.application_storage.lock().unwrap().set(OFFERED_KEY, "true".into());
        let reply = self.prompt_notification(Severity::Info, "Import settings, keyboard shortcuts, snippets and extensions from VS Code, Cursor or VSCodium?", &["Import", "Not Now"]);
        cx.spawn_in(window, async move |workbench, cx| {
            let Ok(Ok(Value::Number(choice))) = reply.await else { return };
            if choice.as_u64() == Some(0) {
                let _ = workbench.update_in(cx, |workbench, window, cx| workbench.pick_settings_import_source(window, cx));
            }
        })
        .detach();
    }

    fn pick_settings_import_source(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        let sources = import_sources();
        if sources.is_empty() {
            self.notify_error("No VS Code, Cursor or VSCodium user data was found.");
            return;
        }
        let mut input = QuickInput::new(0, Kind::QuickPick);
        input.placeholder = Some("Select the editor to import from".into());
        let items = sources.iter().enumerate().map(|(handle, source)| {
            Entry::Item(Item { handle: handle as i64, label: source.name.into(), description: Some(source.user_dir.display().to_string()), pickable: true, ..Item::default() })
        });
        input.set_items(items.collect());
        let picked = self.choose(input, window, cx);
        cx.spawn_in(window, async move |workbench, cx| {
            let Ok(Ok(Value::Number(handle))) = picked.await else { return };
            let source = sources[handle.as_u64().expect("a handle") as usize].clone();
            let _ = workbench.update_in(cx, |workbench, window, cx| workbench.pick_settings_import_contents(source, window, cx));
        })
        .detach();
    }

    /// What will be imported, all checked; the unchecked parts are left out.
    fn pick_settings_import_contents(&mut self, source: Source, window: &mut Window, cx: &mut Context<Self>) {
        let import = settings_import::read(&source);
        let parts = [
            ("Settings", import.settings.len()),
            ("Keyboard Shortcuts", import.keybindings.len()),
            ("Snippets", import.snippets.len()),
            ("Extensions", import.extensions.len()),
            ("UI State", import.ui_state.len()),
        ];
        let mut input = QuickInput::new(0, Kind::QuickPick);
        input.title = Some(format!("Import from {}", source.name));
        input.placeholder = Some("Select what to import into the current profile".into());
        input.can_select_many = true;
        let items: Vec<Entry> = parts
            .iter()
            .enumerate()
            .filter(|(_, (_, count))| *count > 0)
            .map(|(handle, (label, count))| Entry::Item(Item { handle: handle as i64, label: (*label).into(), description: Some(count.to_string()), picked: true, pickable: true, ..Item::default() }))
            .collect();
        if items.is_empty() {
            self.notify_error(format!("{} has nothing to import.", source.name));
            return;
        }
        input.set_items(items);
        let picked = self.choose(input, window, cx);
        cx.spawn_in(window, async move |workbench, cx| {
            let Ok(Ok(Value::Array(handles))) = picked.await else { return };
            let chosen: Vec<u64> = handles.iter().filter_map(Value::as_u64).collect();
            let import = Import {
                settings: if chosen.contains(&0) { import.settings } else { Default::default() },
                keybindings: if chosen.contains(&1) { import.keybindings } else { Vec::new() },
                snippets: if chosen.contains(&2) { import.snippets } else { Vec::new() },
                keybindings_text: import.keybindings_text,
                extensions: if chosen.contains(&3) { import.extensions } else { Vec::new() },
                disabled_extensions: if chosen.contains(&3) { import.disabled_extensions } else { Vec::new() },
                ui_state: if chosen.contains(&4) { import.ui_state } else { Default::default() },
            };
            let _ = workbench.update_in(cx, |workbench, window, cx| workbench.write_settings_import(&source, import, window, cx));
        })
        .detach();
    }

    fn write_settings_import(&mut self, source: &Source, import: Import, window: &mut Window, cx: &mut Context<Self>) {
        let name = source.name;
        let Some(profile) = self.user_data_profiles.state.as_ref().map(|state| state.current.clone()) else { return };
        let settings_file = self.settings.lock().unwrap().user_files().settings.clone();
        let target = Target { settings: &settings_file, keybindings: &profile.keybindings_resource, snippets_home: &profile.snippets_home };
        let written = settings_import::write(&import, &target, &self.settings.lock().unwrap().configuration);
        let written = match written {
            Ok(written) => written,
            Err(error) => return self.notify_error(error),
        };
        self.reload_changed_settings_files(cx);
        crate::profile_template::store_user_state(&mut self.profile_storage.lock().unwrap(), &import.ui_state);
        let installed: Vec<String> = self.extensions.iter().map(|extension| extension.id.to_lowercase()).collect();
        let missing: Vec<String> = import.extensions.into_iter().filter(|id| !installed.contains(id)).collect();
        // extensionsResource.ts: an extension disabled there is disabled here before it is installed and started.
        let disabled: Vec<&String> = import.disabled_extensions.iter().filter(|id| missing.contains(id)).collect();
        if !disabled.is_empty() {
            let mut profile = self.profile_storage.lock().unwrap();
            let mut enablement = Enablement { profile: &mut profile, workspace: None };
            for id in disabled {
                enablement.set_user_state(&Identifier { id: id.clone(), uuid: None }, EnablementState::DisabledGlobally);
            }
        }
        let message = format!(
            "Imported from {name}: {} settings, {} keyboard shortcuts, {} snippet files, {} UI state entries; installing {} extensions from Open VSX, else from {name}'s extensions folder.",
            written.settings,
            written.keybindings,
            written.snippets,
            import.ui_state.len(),
            missing.len()
        );
        drop(self.prompt_notification(Severity::Info, message, &[]));
        cx.notify();
        if missing.is_empty() {
            return;
        }
        let from_gallery = self.install_gallery_extensions(missing, window, cx);
        let extensions_dir = source.extensions_dir.clone();
        cx.spawn(async move |workbench, cx| {
            let mut failed = Vec::new();
            for (id, reason) in from_gallery.await {
                // A publisher the user did not trust stays out.
                let folder = settings_import::extension_folder(&extensions_dir, &id).filter(|_| reason != super::trusted_publishers::CANCELED);
                let Some(folder) = folder else {
                    failed.push((id, reason));
                    continue;
                };
                let Ok(reply) = workbench.update(cx, |workbench, _| workbench.host.run_extensions(Job::InstallFolder(folder))) else { return };
                match reply.await.unwrap_or_else(|_| Err("The extension host is not running.".into())) {
                    Ok(running) => drop(workbench.update(cx, |workbench, cx| workbench.set_running_extensions(running, cx))),
                    Err(error) => failed.push((id, format!("{reason} Copying it from {name} failed: {error}"))),
                }
            }
            if failed.is_empty() {
                return;
            }
            let lines: Vec<String> = failed.iter().map(|(id, reason)| format!("{id}: {reason}")).collect();
            let message = format!("Extensions from {name} that were not installed:\n{}", lines.join("\n"));
            let _ = workbench.update(cx, |workbench, _| workbench.notify_error(message));
        })
        .detach();
    }
}

fn import_sources() -> Vec<Source> {
    let home = std::path::PathBuf::from(std::env::var_os("HOME").unwrap_or_default());
    settings_import::sources(&home)
}

#[cfg(test)]
pub(super) mod tests {
    use std::path::Path;

    use gpui::TestAppContext;

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

    /// Enter on the contents pick imports every part, as they all start checked. The UI state is what a VS Code profile
    /// export carries (globalStateResource.ts: the `StorageTarget.USER` keys), so Source Control moved to the secondary
    /// side bar comes along, and neither the side bar's size, a machine key, nor the trusted publishers do.
    #[gpui::test]
    fn accepting_the_contents_pick_imports_every_part(cx: &mut TestAppContext) {
        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 dir = std::env::temp_dir().join(format!("code-gpui-settings-import-pick-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let source = Source { name: "Cursor", user_dir: dir.join("Cursor/User"), extensions_dir: dir.join(".cursor/extensions") };
        std::fs::create_dir_all(&source.user_dir).unwrap();
        std::fs::write(source.user_dir.join("settings.json"), r#"{ "editor.fontSize": 17 }"#).unwrap();
        std::fs::write(source.user_dir.join("keybindings.json"), r#"[{ "key": "cmd+alt+7", "command": "workbench.action.files.save" }]"#).unwrap();
        std::fs::create_dir_all(source.user_dir.join("globalStorage")).unwrap();
        let mut state = storage::Storage::open(&source.user_dir.join("globalStorage/state.vscdb"));
        state.set("views.customizations", r#"{"viewContainerLocations":{"workbench.view.scm":2},"viewLocations":{},"viewContainerBadgeEnablementStates":{}}"#.into());
        state.set("workbench.sideBar.size", "300".into());
        state.set("extensions.trustedPublishers", r#"{"ms-azuretools":{}}"#.into());
        state.set("__$__targetStorageMarker", r#"{"views.customizations":0,"workbench.sideBar.size":1,"extensions.trustedPublishers":0}"#.into());
        drop(state);
        let user = dir.join("data/User");
        std::fs::create_dir_all(&user).unwrap();
        let settings = std::sync::Arc::new(std::sync::Mutex::new(config::service::Settings::load(config::registry::Registry::with_extensions(&[]), user.clone(), None)));
        let (workbench, cx) = cx.add_window_view(|_, cx| {
            let mut profiles = crate::user_data_profile::UserDataProfilesService::load(&dir.join("data"), &dir.join("extensions"));
            let profile = profiles.resolve(None, None, false, false);
            cx.set_global(profiles);
            let mut workbench = Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), settings, HostSync::new(std::sync::mpsc::channel().0), cx);
            workbench.set_user_data_profiles(profile, cx);
            workbench.load_keybindings(crate::keybindings::default_keybindings(&[]), user.join("keybindings.json"));
            workbench
        });
        workbench.update_in(cx, |workbench, window, cx| workbench.pick_settings_import_contents(source, window, cx));
        cx.simulate_keystrokes("enter");
        cx.run_until_parked();
        let keybindings = workbench.read_with(cx, |workbench, _| workbench.user_data_profiles.state.as_ref().unwrap().current.keybindings_resource.clone());
        assert!(std::fs::read_to_string(user.join("settings.json")).unwrap().contains(r#""editor.fontSize": 17"#));
        assert!(std::fs::read_to_string(keybindings).unwrap().contains("cmd+alt+7"));
        workbench.read_with(cx, |workbench, _| {
            assert_eq!(workbench.container_location("workbench.view.scm"), super::super::layout::Part::AuxiliaryBar);
            let storage = workbench.profile_storage.lock().unwrap();
            assert_eq!((storage.get("workbench.sideBar.size"), storage.get("extensions.trustedPublishers")), (None, None));
        });
        std::fs::remove_dir_all(dir).unwrap();
    }

    /// A gallery on localhost that answers every query with `redhat.vscode-yaml` and `beta.vscode-yaml`, of the
    /// untrusted publishers "Red Hat" and "Beta".
    pub(in crate::workbench) fn two_publisher_gallery() -> String {
        let yaml: Value = serde_json::from_str(include_str!("../../../exthost/src/gallery/vscode-yaml-latest.json")).unwrap();
        let mut other = yaml.clone();
        other["publisher"]["publisherName"] = "beta".into();
        other["publisher"]["displayName"] = "Beta".into();
        other["extensionId"] = "00000000-0000-0000-0000-000000000002".into();
        let body = serde_json::json!({ "results": [{ "extensions": [yaml, other], "resultMetadata": [{ "metadataType": "ResultCount", "metadataItems": [{ "name": "TotalCount", "count": 2 }] }] }] });
        serve_gallery(body.to_string())
    }

    /// A gallery on localhost that answers every request with `body`.
    fn serve_gallery(body: String) -> String {
        use std::io::{Read, Write};
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let url = format!("http://{}", listener.local_addr().unwrap());
        std::thread::spawn(move || {
            for mut stream in listener.incoming().flatten() {
                let _ = stream.read(&mut [0; 65536]);
                let reply = format!("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len());
                let _ = stream.write_all(reply.as_bytes());
            }
        });
        url
    }

    /// A window whose profile lives in a fresh temporary `dir`, installing from `gallery_url`.
    fn import_window<'a>(name: &str, gallery_url: String, cx: &'a mut TestAppContext) -> (gpui::Entity<Workbench>, &'a mut gpui::VisualTestContext, std::path::PathBuf) {
        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 dir = std::env::temp_dir().join(format!("code-gpui-settings-import-{name}-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let user = dir.join("data/User");
        std::fs::create_dir_all(&user).unwrap();
        let settings = std::sync::Arc::new(std::sync::Mutex::new(config::service::Settings::load(config::registry::Registry::with_extensions(&[]), user.clone(), None)));
        let (workbench, cx) = cx.add_window_view(|_, cx| {
            let mut profiles = crate::user_data_profile::UserDataProfilesService::load(&dir.join("data"), &dir.join("extensions"));
            let profile = profiles.resolve(None, None, false, false);
            cx.set_global(profiles);
            let mut workbench = Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), settings, HostSync::new(std::sync::mpsc::channel().0), cx);
            workbench.set_user_data_profiles(profile, cx);
            workbench.gallery_url = gallery_url;
            workbench
        });
        (workbench, cx, dir)
    }

    /// extensionManagementService.ts `installGalleryExtensions`: the extensions of two untrusted publishers ask for
    /// trust once, in one dialog that names both.
    #[gpui::test]
    fn imported_extensions_ask_for_publisher_trust_once(cx: &mut TestAppContext) {
        let (workbench, cx, dir) = import_window("trust", two_publisher_gallery(), cx);
        let ids = vec!["redhat.vscode-yaml".to_owned(), "beta.vscode-yaml".to_owned()];
        let source = Source { name: "VS Code", user_dir: dir.join("Code/User"), extensions_dir: dir.join(".vscode/extensions") };
        let import = Import { extensions: ids, disabled_extensions: vec!["beta.vscode-yaml".into()], ..Import::default() };
        workbench.update_in(cx, |workbench, window, cx| workbench.write_settings_import(&source, import, window, cx));
        cx.run_until_parked();
        let messages: Vec<String> = workbench.read_with(cx, |workbench, _| workbench.dialogs.iter().map(|shown| shown.dialog.message.clone()).collect());
        assert_eq!(messages, ["Do you trust publishers \"Red Hat\" and \"Beta\"?"]);
        let disabled = workbench.read_with(cx, |workbench, _| crate::extension_enablement::identifiers(&workbench.profile_storage.lock().unwrap(), crate::extension_enablement::DISABLED_EXTENSIONS_STORAGE_PATH));
        assert_eq!(disabled.iter().map(|identifier| identifier.id.as_str()).collect::<Vec<_>>(), ["beta.vscode-yaml"]);
        std::fs::remove_dir_all(dir).unwrap();
    }

    /// An extension Open VSX does not have is copied from the source's extensions folder; one missing there too is
    /// reported with the gallery's reason alone. The test host does not run, so the copy fails with that error.
    #[gpui::test]
    fn extensions_open_vsx_lacks_are_copied_from_the_source(cx: &mut TestAppContext) {
        let empty = serde_json::json!({ "results": [{ "extensions": [], "resultMetadata": [{ "metadataType": "ResultCount", "metadataItems": [{ "name": "TotalCount", "count": 0 }] }] }] });
        let (workbench, cx, dir) = import_window("copy", serve_gallery(empty.to_string()), cx);
        let source = Source { name: "VS Code", user_dir: dir.join("Code/User"), extensions_dir: dir.join(".vscode/extensions") };
        std::fs::create_dir_all(source.extensions_dir.join("alpha.one-1.0.0")).unwrap();
        std::fs::write(source.extensions_dir.join("alpha.one-1.0.0/package.json"), r#"{ "name": "one", "publisher": "alpha", "version": "1.0.0" }"#).unwrap();
        let import = Import { extensions: vec!["alpha.one".into(), "beta.two".into()], ..Import::default() };
        workbench.update_in(cx, |workbench, window, cx| workbench.write_settings_import(&source, import, window, cx));
        cx.run_until_parked();
        let messages: Vec<String> = workbench.read_with(cx, |workbench, _| workbench.notifications.model.items.iter().map(|item| item.message.raw.clone()).collect());
        let expected = "Extensions from VS Code that were not installed:\nalpha.one: The extension 'alpha.one' cannot be installed because it was not found. Copying it from VS Code failed: The extension host is not running.\nbeta.two: The extension 'beta.two' cannot be installed because it was not found.";
        assert!(messages.iter().any(|message| message == expected), "{messages:?}");
        std::fs::remove_dir_all(dir).unwrap();
    }
}