Skip to content

Visual Studio Code, rebuilt in Rust

Rust
7.7 KB
Raw Blame
//! `--extensionDevelopmentPath` / `--extensionTestsPath`: the extension under development joins the
//! scanned set and init data names it and its test runner, as upstream's extension development host does.

use std::path::PathBuf;

use serde_json::{Value, json};

use crate::scan::{ScannedExtension, file_uri, scan_extension};

#[derive(Clone, Debug, PartialEq)]
pub struct ExtensionDevelopment {
    pub extension_path: PathBuf,
    pub tests_path: Option<PathBuf>,
}

/// environmentService.ts `debugExtensionHost` (`parseExtensionHostDebugPort`): `--inspect-extensions=<port>` or
/// `--inspect-brk-extensions=<port>`, `--debugId=<debug session>` and `--extensionEnvironment=<JSON object>`.
/// shortcut: no 5870 default port of a build from source, the checkout would always run Node.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ExtensionHostDebug {
    pub port: Option<u16>,
    pub break_on_start: bool,
    pub debug_id: Option<String>,
    pub env: Vec<(String, String)>,
}

impl ExtensionHostDebug {
    pub fn from_args(args: &[String]) -> Self {
        let value = |flag: &str| args.iter().find_map(|arg| arg.strip_prefix(flag)?.strip_prefix('='));
        let brk_port = value("--inspect-brk-extensions").and_then(|port| port.parse::<u16>().ok()).filter(|port| *port != 0);
        let port = brk_port.or_else(|| value("--inspect-extensions").and_then(|port| port.parse::<u16>().ok()).filter(|port| *port != 0));
        // parseDebugParams ignores an environment that is not JSON; values that are not strings are left out.
        let env = value("--extensionEnvironment").and_then(|json| serde_json::from_str::<serde_json::Map<String, Value>>(json).ok()).unwrap_or_default();
        let env = env.into_iter().filter_map(|(key, value)| Some((key, value.as_str()?.to_owned()))).collect();
        ExtensionHostDebug { port, break_on_start: brk_port.is_some(), debug_id: value("--debugId").map(str::to_owned), env }
    }

    /// localProcessExtensionHost.ts `_start` execArgv: the inspector on the port, paused before the first line with
    /// `--inspect-brk-extensions`. Bun has no V8 inspector, so a debugged host runs on Node.
    pub fn node_args(&self, port: u16) -> Vec<String> {
        let inspect = if self.break_on_start { "--inspect-brk" } else { "--inspect" };
        vec!["--dns-result-order=ipv4first".into(), "--experimental-network-inspection".into(), "--nolazy".into(), format!("{inspect}=127.0.0.1:{port}")]
    }
}

impl ExtensionDevelopment {
    /// Reads `--extensionDevelopmentPath=<dir>` and `--extensionTestsPath=<path>` (the `=` form upstream's scripts pass).
    /// Paths are made absolute without resolving symlinks, as environmentService's `path.resolve` does.
    pub fn from_args(args: &[String]) -> anyhow::Result<Option<Self>> {
        let value = |flag: &str| args.iter().find_map(|arg| arg.strip_prefix(flag)?.strip_prefix('=')).map(std::path::absolute).transpose();
        let extension_path = value("--extensionDevelopmentPath")?;
        let tests_path = value("--extensionTestsPath")?;
        match (extension_path, tests_path) {
            (Some(extension_path), tests_path) => Ok(Some(ExtensionDevelopment { extension_path, tests_path })),
            (None, Some(_)) => anyhow::bail!("--extensionTestsPath needs --extensionDevelopmentPath"),
            (None, None) => Ok(None),
        }
    }

    /// Adds the extension under development; it replaces a built-in with the same id and keeps its type
    /// (`scanExtensionsUnderDevelopment`), so a built-in's copy stays built-in.
    pub fn add_extension(&self, extensions: &mut Vec<ScannedExtension>) -> anyhow::Result<()> {
        let mut extension = scan_extension(&self.extension_path, false)?;
        extension.description["isUnderDevelopment"] = json!(true);
        if let Some(existing) = extensions.iter().find(|other| other.id.eq_ignore_ascii_case(&extension.id)) {
            extension.description["isBuiltin"] = existing.description["isBuiltin"].clone();
        }
        extensions.retain(|other| !other.id.eq_ignore_ascii_case(&extension.id));
        extensions.push(extension);
        Ok(())
    }

    /// Sets `environment.extensionDevelopmentLocationURI` and `extensionTestsLocationURI` of `IExtensionHostInitData`.
    pub fn add_to_init_data(&self, init: &mut Value) {
        let environment = &mut init["environment"];
        environment["extensionDevelopmentLocationURI"] = json!([file_uri(&self.extension_path)]);
        if let Some(tests_path) = &self.tests_path {
            environment["extensionTestsLocationURI"] = file_uri(tests_path);
        }
        // localProcessExtensionHost.ts: an extension development host forwards native console output, tests from the CLI forward nothing.
        let tests_from_cli = self.tests_path.is_some();
        init["consoleForward"] = json!({ "includeStack": !tests_from_cli, "logNative": !tests_from_cli });
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn reads_equals_form_flags() {
        let dir = std::env::temp_dir();
        let args = |list: &[&str]| list.iter().map(|arg| arg.to_string()).collect::<Vec<_>>();
        let development = ExtensionDevelopment::from_args(&args(&["code-gpui", &format!("--extensionDevelopmentPath={}", dir.display()), &format!("--extensionTestsPath={}", dir.display())]))
            .unwrap()
            .unwrap();
        assert_eq!((development.extension_path, development.tests_path), (dir.clone(), Some(dir.clone())));
        assert!(ExtensionDevelopment::from_args(&args(&["code-gpui", "folder"])).unwrap().is_none());
        assert!(ExtensionDevelopment::from_args(&args(&["code-gpui", &format!("--extensionTestsPath={}", dir.display())])).is_err());
    }

    #[test]
    fn reads_the_extension_host_debug_flags() {
        let args = |list: &[&str]| list.iter().map(|arg| arg.to_string()).collect::<Vec<_>>();
        let debug = ExtensionHostDebug::from_args(&args(&["code", "--debugId=abc", "--inspect-brk-extensions=9333", r#"--extensionEnvironment={"A":"1","B":null}"#]));
        assert_eq!(debug, ExtensionHostDebug { port: Some(9333), break_on_start: true, debug_id: Some("abc".into()), env: vec![("A".into(), "1".into())] });
        assert_eq!(debug.node_args(9333), ["--dns-result-order=ipv4first", "--experimental-network-inspection", "--nolazy", "--inspect-brk=127.0.0.1:9333"]);
        let debug = ExtensionHostDebug::from_args(&args(&["code", "--inspect-extensions=9334", "--extensionEnvironment=nope"]));
        assert_eq!((debug.port, debug.break_on_start, debug.env.len()), (Some(9334), false, 0));
        assert_eq!(ExtensionHostDebug::from_args(&args(&["code", "--inspect-extensions"])), ExtensionHostDebug::default());
    }

    #[test]
    fn replaces_the_builtin_with_the_development_copy() {
        let dir = std::env::temp_dir().join(format!("extension-development-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("package.json"), r#"{"name":"vscode-api-tests","publisher":"vscode"}"#).unwrap();
        let mut extensions = vec![scan_extension(&dir, true).unwrap()];
        let development = ExtensionDevelopment { extension_path: dir.clone(), tests_path: Some(dir.join("out")) };
        development.add_extension(&mut extensions).unwrap();
        let mut user = vec![];
        development.add_extension(&mut user).unwrap();
        let mut init = json!({ "environment": {} });
        development.add_to_init_data(&mut init);
        std::fs::remove_dir_all(&dir).unwrap();
        assert_eq!(extensions.len(), 1);
        assert_eq!((&extensions[0].description["isBuiltin"], &extensions[0].description["isUnderDevelopment"]), (&json!(true), &json!(true)));
        assert_eq!(user[0].description["isBuiltin"], json!(false));
        assert_eq!(init["environment"]["extensionTestsLocationURI"]["path"], json!(dir.join("out").to_string_lossy()));
    }
}