Skip to content

Visual Studio Code, rebuilt in Rust

Rust
7.4 KB
Raw Blame
//! workbench/services/extensions/common/extensionsProposedApi.ts: which API proposals each extension may use, from
//! the environment, product.json `extensionEnabledApiProposals` and the proposals that exist.

use std::collections::{HashMap, HashSet};
use std::sync::LazyLock;

use serde_json::{Value, json};

use crate::scan::ScannedExtension;

/// extensionsApiProposals.ts `allApiProposals`: the keys of its `_allApiProposals` object.
static ALL_API_PROPOSALS: LazyLock<HashSet<&'static str>> = LazyLock::new(|| {
    let source = include_str!(concat!(env!("VSCODE_SRC"), "/src/vs/platform/extensions/common/extensionsApiProposals.ts"));
    source.lines().filter_map(|line| line.strip_prefix('\t')?.strip_suffix(": {")).collect()
});

/// extensionsProposedApiExceptions.ts `extensionsAllowedAnyApiProposal`.
const ALLOWED_ANY_API_PROPOSAL: [&str; 1] = ["ms-vscode.vscode-team-tools"];

/// What the environment service tells ExtensionsProposedApi.
pub struct Environment<'a> {
    pub is_built: bool,
    pub is_extension_development: bool,
    pub quality: Option<&'a str>,
    /// `--enable-proposed-api`: `None` without the flag, an empty list for the flag without extension ids.
    pub enabled_proposed_api: Option<Vec<String>>,
}

/// A window's ExtensionsProposedApi: its environment decides, as each renderer's does upstream.
#[derive(Clone)]
pub struct ProposedApi {
    env_enables_proposed_api_for_all: bool,
    env_enabled_extensions: HashSet<String>,
    product_enabled_extensions: HashMap<String, Vec<String>>,
    is_extension_development: bool,
}

/// environmentService.ts `extensionEnabledProposedApi`: the ids of `--enable-proposed-api=<id>` and
/// `--enable-proposed-api <id>`, an empty list for the bare flag, `None` without it.
pub fn enabled_proposed_api(args: &[String]) -> Option<Vec<String>> {
    let mut ids = Vec::new();
    let mut present = false;
    for (index, arg) in args.iter().enumerate() {
        if let Some(id) = arg.strip_prefix("--enable-proposed-api=") {
            present = true;
            ids.push(id.to_string());
        } else if arg == "--enable-proposed-api" {
            present = true;
            ids.extend(args.get(index + 1).filter(|next| !next.starts_with("--")).cloned());
        }
    }
    present.then_some(ids)
}

impl ProposedApi {
    /// `updateEnabledApiProposals`, its errors logged.
    pub fn update_enabled_api_proposals(&self, extensions: &mut [ScannedExtension]) {
        for extension in extensions {
            for error in self.update(&mut extension.description) {
                eprintln!("[extensions] {error}");
            }
        }
    }

    /// A run from the sources: every declared proposal that exists.
    pub fn unbuilt() -> ProposedApi {
        ProposedApi::new(&Environment { is_built: false, is_extension_development: false, quality: None, enabled_proposed_api: None }, &Value::Null)
    }

    pub fn new(environment: &Environment, product_enabled_api_proposals: &Value) -> ProposedApi {
        let env_enabled_extensions: HashSet<String> = environment.enabled_proposed_api.iter().flatten().map(|id| id.to_lowercase()).collect();
        let env_enables_proposed_api_for_all = !environment.is_built
            || (environment.is_extension_development && environment.quality != Some("stable"))
            || (env_enabled_extensions.is_empty() && environment.enabled_proposed_api.is_some());
        let mut product_enabled_extensions = HashMap::new();
        for (id, names) in product_enabled_api_proposals.as_object().into_iter().flatten() {
            let key = id.to_lowercase();
            let mut proposals = Vec::new();
            for name in names.as_array().into_iter().flatten().filter_map(Value::as_str) {
                match ALL_API_PROPOSALS.contains(name) {
                    true => proposals.push(name.to_string()),
                    false => eprintln!("[extensions] Via 'product.json#extensionEnabledApiProposals' extension '{key}' wants API proposal '{name}' but that proposal DOES NOT EXIST. Likely, the proposal has been finalized (check 'vscode.d.ts') or was abandoned."),
                }
            }
            product_enabled_extensions.insert(key, proposals);
        }
        ProposedApi { env_enables_proposed_api_for_all, env_enabled_extensions, product_enabled_extensions, is_extension_development: environment.is_extension_development }
    }

    /// `doUpdateEnabledApiProposals`: sets the description's `enabledApiProposals`, answers the errors it logs.
    pub fn update(&self, description: &mut Value) -> Vec<String> {
        let mut errors = Vec::new();
        let id = description["identifier"]["value"].as_str().unwrap_or_default().to_string();
        let key = id.to_lowercase();
        let declared: Vec<String> = description["enabledApiProposals"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect();
        let mut proposals = Vec::new();
        for name in declared {
            match ALL_API_PROPOSALS.contains(name.as_str()) {
                true => proposals.push(name),
                false => errors.push(format!("Extension '{key}' wants API proposal '{name}' but that proposal DOES NOT EXIST. Likely, the proposal has been finalized (check 'vscode.d.ts') or was abandoned.")),
            }
        }
        if description.get("enabledApiProposals").is_some() {
            description["enabledApiProposals"] = json!(proposals);
        }

        if ALLOWED_ANY_API_PROPOSAL.contains(&key.as_str()) {
            return errors;
        }

        // product.json's proposals replace the extension's, so the list tells what is used in the wild.
        if let Some(product_proposals) = self.product_enabled_extensions.get(&key) {
            let mut enabled = product_proposals.clone();
            let delta: Vec<&String> = proposals.iter().filter(|name| !product_proposals.contains(name)).collect();
            if !delta.is_empty() {
                let join = |names: &[&String]| names.iter().map(|name| name.as_str()).collect::<Vec<_>>().join("\n");
                let loses: Vec<&String> = proposals.iter().collect();
                let wins: Vec<&String> = product_proposals.iter().collect();
                errors.push(format!("Extension '{key}' appears in product.json but enables LESS API proposals than the extension wants.\npackage.json (LOSES): {}\nproduct.json (WINS): {}\nDELTA: {}", join(&loses), join(&wins), join(&delta)));
                if self.is_extension_development {
                    let extra = delta.iter().map(|name| name.as_str()).collect::<Vec<_>>().join(", ");
                    errors.push(format!("Proceeding with EXTRA proposals ({extra}) because extension is in development mode. Still, this EXTENSION WILL BE BROKEN unless product.json is updated."));
                    enabled.extend(delta.into_iter().cloned());
                }
            }
            description["enabledApiProposals"] = json!(enabled);
            return errors;
        }

        if self.env_enables_proposed_api_for_all || self.env_enabled_extensions.contains(&key) {
            return errors;
        }

        if description["isBuiltin"] != true && !proposals.is_empty() {
            errors.push(format!("Extension '{id} CANNOT USE these API proposals '{}'. You MUST start in extension development mode or use the --enable-proposed-api command line flag", proposals.join(", ")));
            description["enabledApiProposals"] = json!([]);
        }
        errors
    }
}

#[cfg(test)]
mod tests;