Skip to content

Visual Studio Code, rebuilt in Rust

Rust
6.0 KB
Raw Blame
//! platform/product: product.json of the VS Code tree with the port's overlay (port/product.json) over it, or the app
//! bundle's product.json (package-app merged the overlay into it), read once at startup, with package.json's version
//! when product.json has none (product.ts). Before `load` (tests, early startup) the overlay alone answers.

use std::path::Path;
use std::sync::{LazyLock, OnceLock};

use serde_json::Value;

/// Where a packaged app keeps its files: VSRustium.app/Contents/Resources/app (package-app), or
/// resources/app beside the binary in the Linux and Windows folders (package-linux, package-windows), as VS Code's builds.
#[cfg(target_os = "macos")]
pub const BUNDLED_APP: &str = "Contents/Resources/app";
#[cfg(any(target_os = "linux", target_os = "windows"))]
pub const BUNDLED_APP: &str = "resources/app";

/// Whether `app_root` is a packaged app's, not the VS Code tree a checkout run reads.
pub fn is_bundled(app_root: &Path) -> bool {
    app_root.ends_with(BUNDLED_APP)
}

static PRODUCT: OnceLock<Value> = OnceLock::new();
static OVERLAY: LazyLock<Value> = LazyLock::new(|| serde_json::from_str(include_str!("../../../../port/product.json")).expect("port/product.json is JSON"));

/// Reads `<root>/product.json`, port/product.json over it unless `bundled`, and `<root>/package.json`; a missing or
/// broken file leaves the built-in defaults.
pub fn load(root: &Path, bundled: bool) {
    let read = |name: &str| std::fs::read(root.join(name)).ok().and_then(|bytes| serde_json::from_slice::<Value>(&bytes).ok());
    let mut product = read("product.json").unwrap_or_else(|| Value::Object(Default::default()));
    for (key, value) in OVERLAY.as_object().expect("port/product.json is a JSON object").iter().filter(|_| !bundled) {
        product[key] = value.clone();
    }
    // bootstrap-meta.ts: run with VSCODE_DEV, `<root>/product.overrides.json` overrides product.json's keys.
    if std::env::var_os("VSCODE_DEV").is_some() {
        for (key, value) in read("product.overrides.json").as_ref().and_then(Value::as_object).into_iter().flatten() {
            product[key] = value.clone();
        }
    }
    if product["version"].is_null() {
        if let Some(version) = read("package.json").map(|package| package["version"].clone()) {
            product["version"] = version;
        }
    }
    let _ = PRODUCT.set(product);
}

pub fn get(key: &str) -> &'static Value {
    &PRODUCT.get().unwrap_or(&OVERLAY)[key]
}

/// The windows' X11 WM_CLASS and Wayland app id, which the .desktop file's `StartupWMClass` names (package-linux).
pub fn linux_desktop_name() -> Option<String> {
    get("linuxDesktopName").as_str().map(Into::into)
}

/// `productService.quality`: `stable` on a latest build, `insider` on a pre-release, none on a dev build.
pub fn quality() -> Option<&'static str> {
    #[cfg(test)]
    if let Some(quality) = test_quality::QUALITY.get() {
        return quality;
    }
    get("quality").as_str()
}

pub fn is_stable() -> bool {
    quality() == Some("stable")
}

#[cfg(test)]
pub mod test_quality {
    use std::cell::Cell;

    thread_local! {
        pub(super) static QUALITY: Cell<Option<Option<&'static str>>> = const { Cell::new(None) };
    }

    /// Answers `quality()` with `quality` on this thread (gpui tests run on one) until the guard drops.
    pub fn set(quality: Option<&'static str>) -> impl Drop {
        QUALITY.set(Some(quality));
        Reset
    }

    struct Reset;

    impl Drop for Reset {
        fn drop(&mut self) {
            QUALITY.set(None);
        }
    }
}

/// The port's version users see: VS Code's `version` with product.json `release` (port/product.json, the port's build
/// of that VS Code version) as a fourth number, `1.148.0.1` or `1.148.0.1-insider`. Extensions see `crate::VERSION`.
pub fn display_version() -> String {
    with_release(get("version").as_str().unwrap_or_default(), get("release").as_u64().unwrap_or(0))
}

/// `version` with `release` after its patch number; release 0 (a build or feed entry from before releases) adds none.
pub fn with_release(version: &str, release: u64) -> String {
    if release == 0 || version.is_empty() {
        return version.to_owned();
    }
    match version.split_once('-') {
        Some((numbers, quality)) => format!("{numbers}.{release}-{quality}"),
        None => format!("{version}.{release}"),
    }
}

pub fn name_long() -> &'static str {
    get("nameLong").as_str().expect("port/product.json has nameLong")
}

pub fn name_short() -> &'static str {
    get("nameShort").as_str().expect("port/product.json has nameShort")
}

#[cfg(test)]
mod tests {
    #[test]
    fn reads_the_checkout_product() {
        super::load(std::path::Path::new(env!("VSCODE_SRC")), false);
        assert_eq!(super::name_long(), "VSRustium");
        assert_eq!(super::name_short(), "VSRustium");
        assert_eq!(super::get("urlProtocol"), "vsrustium");
        assert_eq!(super::get("darwinBundleIdentifier"), "com.rokartur.vsrustium");
        assert!(super::get("version").as_str().is_some_and(|version| version.starts_with("1.148")));
    }

    #[test]
    fn display_version_adds_the_release() {
        assert_eq!(super::with_release("1.148.0", 1), "1.148.0.1");
        assert_eq!(super::with_release("1.148.0-insider", 12), "1.148.0.12-insider");
        assert_eq!(super::with_release("1.148.0", 0), "1.148.0");
        super::load(std::path::Path::new(env!("VSCODE_SRC")), false);
        let release = super::get("release").as_u64().expect("port/product.json has release");
        assert!(release > 0);
        assert_eq!(super::display_version(), format!("1.148.0.{release}"));
    }

    /// The release is the port's: extensions (init data, gallery and engines checks) keep VS Code's version.
    #[test]
    fn extensions_see_the_vscode_version_without_the_release() {
        super::load(std::path::Path::new(env!("VSCODE_SRC")), false);
        assert!(super::get("release").as_u64().is_some_and(|release| release > 0));
        assert_eq!(crate::version_for_quality(Some("stable")), "1.148.0");
        assert_eq!(crate::version_for_quality(Some("insider")), "1.148.0-insider");
    }
}