Visual Studio Code, rebuilt in Rust
Rust
//! platform/configuration/common/configurationRegistry.ts and the `configuration` and `configurationDefaults`
//! extension points of workbench/api/common/configurationExtensionPoint.ts: every registered setting with its
//! schema, scope and default, and the defaults model built from them.
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use serde_json::{Map, Value, json};
use crate::model::{ConfigurationModel, is_override_key};
/// `ConfigurationScope`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Scope {
Application = 1,
Machine = 2,
ApplicationMachine = 3,
Window = 4,
Resource = 5,
LanguageOverridable = 6,
MachineOverridable = 7,
}
impl Scope {
fn from_number(value: &Value) -> Option<Scope> {
Some(match value.as_u64()? {
1 => Scope::Application,
2 => Scope::Machine,
3 => Scope::ApplicationMachine,
4 => Scope::Window,
5 => Scope::Resource,
6 => Scope::LanguageOverridable,
7 => Scope::MachineOverridable,
_ => return None,
})
}
/// `parseScope`: what an extension's package.json may say; anything else, `application-machine` included, is WINDOW.
fn parse(scope: &str) -> Scope {
match scope {
"application" => Scope::Application,
"machine" => Scope::Machine,
"resource" => Scope::Resource,
"machine-overridable" => Scope::MachineOverridable,
"language-overridable" => Scope::LanguageOverridable,
_ => Scope::Window,
}
}
}
/// `APPLICATION_SCOPES`, `WORKSPACE_SCOPES` and `FOLDER_SCOPES` of workbench/services/configuration/common/configuration.ts.
pub const APPLICATION_SCOPES: [Scope; 2] = [Scope::Application, Scope::ApplicationMachine];
pub const PROFILE_SCOPES: [Scope; 5] = [Scope::Machine, Scope::Window, Scope::Resource, Scope::LanguageOverridable, Scope::MachineOverridable];
pub const WORKSPACE_SCOPES: [Scope; 4] = [Scope::Window, Scope::Resource, Scope::LanguageOverridable, Scope::MachineOverridable];
pub const FOLDER_SCOPES: [Scope; 3] = [Scope::Resource, Scope::LanguageOverridable, Scope::MachineOverridable];
/// An extension point's `collector.warn` or `collector.error` message.
#[derive(Clone, Debug, PartialEq)]
pub enum CollectorMessage {
Warning(String),
Error(String),
}
/// `IRegisteredConfigurationPropertySchema`: the schema as registered, plus what the registry derives from it.
#[derive(Clone, Debug)]
pub struct Property {
pub schema: Value,
/// WINDOW for `[lang]` properties, whose scope upstream leaves unset.
pub scope: Scope,
pub restricted: bool,
pub default: Value,
/// `defaultDefaultValue`: the default before any `configurationDefaults` contribution.
default_default: Option<Value>,
/// The contributing extension id; `None` for core settings.
pub source: Option<String>,
}
#[derive(Default)]
pub struct Registry {
keys: Vec<String>,
properties: HashMap<String, Property>,
/// `configurationDefaultsOverrides`: the merged value each key's `configurationDefaults` contributions give it.
default_overrides: Vec<(String, Value, Option<String>)>,
/// `registerOverrideIdentifiers`: the language ids languagesRegistry.ts registers.
pub override_identifiers: Vec<String>,
/// `getExcludedConfigurationProperties`: the schemas of `included: false` properties, which only policies read.
pub excluded: HashMap<String, Value>,
/// The extensions' `contributes.commands`, id and title, which keybindings.json may name.
pub extension_commands: Vec<(String, String)>,
/// codeActionsContribution.ts `_allProvidedCodeActionKinds`, for the keybindings schema's `kind` suggestions.
pub code_action_kinds: Vec<String>,
/// inlineCompletions.contribution.ts: `inlineCompletionProviderGetMatcher` of every inline completion provider.
pub inline_completion_providers: Vec<String>,
/// The extensions' `contributes.colors`, `semanticTokenTypes` and `semanticTokenModifiers` entries and their
/// debuggers, which the workbench-colors, token-styling and launch schemas list.
pub colors: Vec<Value>,
pub semantic_token_types: Vec<Value>,
pub semantic_token_modifiers: Vec<Value>,
pub debuggers: Vec<crate::debuggers::Debugger>,
/// The `configuration` and `configurationDefaults` points' collector messages, by extension id.
pub messages: Vec<(String, CollectorMessage)>,
}
/// The core settings of VS Code 1.147.0 as its registry holds them, dumped with port/tools/dump-settings.
const CORE_SETTINGS: &str = include_str!("../core-settings.json");
/// The core settings a `stable` build registers differently (`product.quality` gates their default or `included`),
/// dumped with port/tools/dump-settings; null for one it does not register.
const STABLE_SETTINGS: &str = include_str!("../core-settings-stable.json");
/// VSRustium's own settings, in the same shape.
const PORT_SETTINGS: &str = include_str!("../port-settings.json");
static STABLE_QUALITY: AtomicBool = AtomicBool::new(false);
/// The product is a `stable` build: every `Registry::core` after this registers the stable settings.
pub fn use_stable_quality() {
STABLE_QUALITY.store(true, Ordering::Relaxed);
}
impl Registry {
/// The core settings and the language defaults of editor/common/languages/modesRegistry.ts.
pub fn core() -> Registry {
Registry::core_of_quality(STABLE_QUALITY.load(Ordering::Relaxed))
}
fn core_of_quality(stable: bool) -> Registry {
let mut registry = Registry::default();
let Value::Object(mut settings) = serde_json::from_str(CORE_SETTINGS).expect("core-settings.json is JSON") else {
unreachable!("core-settings.json holds an object")
};
if stable {
let Value::Object(stable_settings) = serde_json::from_str(STABLE_SETTINGS).expect("core-settings-stable.json is JSON") else {
unreachable!("core-settings-stable.json holds an object")
};
for (key, schema) in stable_settings {
match schema {
Value::Null => settings.remove(&key),
schema => settings.insert(key, schema),
};
}
}
let Value::Object(port) = serde_json::from_str(PORT_SETTINGS).expect("port-settings.json is JSON") else {
unreachable!("port-settings.json holds an object")
};
settings.extend(port);
if cfg!(windows) {
settings.extend(windows_settings());
}
for (key, schema) in settings {
let scope = Scope::from_number(&schema["scope"]).unwrap_or(Scope::Window);
let restricted = schema["restricted"].as_bool().unwrap_or(false);
let default = schema.get("default").cloned();
registry.insert(key, Property { scope, restricted, default: Value::Null, default_default: default, source: None, schema });
}
// Port addition (port/notes.md "Update feed"): upstream's channel is the build's quality, so it is the default.
let channel = if stable { "latest" } else { "pre-release" };
let schema = json!({
"type": "string",
"enum": ["latest", "pre-release"],
"default": channel,
"scope": 1,
"description": "Configure which releases you receive updates from. The updates are fetched from the GitHub releases of VSRustium.",
"enumDescriptions": ["Receive only releases that are not marked as pre-release.", "Receive pre-releases too, and any newer release."],
"tags": ["usesOnlineServices"],
"section": { "id": "update", "title": "Update", "order": 15 },
"restricted": false,
});
registry.insert("update.releaseChannel".into(), Property { scope: Scope::Application, restricted: false, default: Value::Null, default_default: Some(json!(channel)), source: None, schema });
registry.register_defaults(
&json!({
"[plaintext]": { "editor.unicodeHighlight.ambiguousCharacters": false, "editor.unicodeHighlight.invisibleCharacters": false },
"[go]": { "editor.insertSpaces": false },
"[makefile]": { "editor.insertSpaces": false },
"[shellscript]": { "files.eol": "\n" },
"[yaml]": { "editor.insertSpaces": true, "editor.tabSize": 2 },
}),
None,
);
registry
}
/// The core settings plus what each extension (id, package.json) contributes, defaults resolved.
pub fn with_extensions(extensions: &[(&str, &Value)]) -> Registry {
let mut registry = Registry::core();
for (id, description) in extensions {
registry.register_configuration(id, description);
}
for (id, description) in extensions {
registry.register_configuration_defaults(id, description);
}
// The core plaintext language (modesRegistry.ts), then each `contributes.languages` id.
registry.override_identifiers.push("plaintext".into());
for (_, description) in extensions {
for language in description["contributes"]["languages"].as_array().into_iter().flatten() {
if let Some(id) = language["id"].as_str().filter(|id| !registry.override_identifiers.iter().any(|known| known == id)) {
registry.override_identifiers.push(id.into());
}
}
}
for (_, description) in extensions {
for command in description["contributes"]["commands"].as_array().into_iter().flatten() {
let title = command["title"].as_str().or(command["title"]["value"].as_str()).unwrap_or_default();
if let Some(id) = command["command"].as_str() {
registry.extension_commands.push((id.into(), title.into()));
}
}
}
for (_, description) in extensions {
let contributes = &description["contributes"];
registry.colors.extend(contributes["colors"].as_array().into_iter().flatten().cloned());
registry.semantic_token_types.extend(contributes["semanticTokenTypes"].as_array().into_iter().flatten().cloned());
registry.semantic_token_modifiers.extend(contributes["semanticTokenModifiers"].as_array().into_iter().flatten().cloned());
}
registry.debuggers = crate::debuggers::debuggers(extensions);
registry.list_folding_range_providers(extensions);
registry.list_default_formatters(extensions, &[]);
registry.finish();
registry
}
/// formatActionsMultiple.ts `_updateConfigValues`: `editor.defaultFormatter` offers None, then the extensions with
/// code: the ones with a registered formatter first, then Formatters or Programming Languages, each group by name.
pub fn list_default_formatters(&mut self, extensions: &[(&str, &Value)], formatter_ids: &[String]) {
let Some(property) = self.properties.get_mut("editor.defaultFormatter") else { return };
let mut with_code: Vec<_> = extensions.iter().filter(|(_, description)| description.get("main").is_some() || description.get("browser").is_some()).collect();
let is_boosted = |description: &Value| description["categories"].as_array().is_some_and(|categories| categories.iter().any(|category| category == "Formatters" || category == "Programming Languages"));
let has_formatter = |id: &str| formatter_ids.iter().any(|formatter| formatter.eq_ignore_ascii_case(id));
with_code.sort_by_key(|(id, description)| (!has_formatter(id), !is_boosted(description), description["name"].as_str().unwrap_or_default().to_lowercase()));
let mut ids = vec![Value::Null];
let mut labels = vec![json!("None")];
let mut descriptions = vec![json!("None")];
for (id, description) in with_code {
ids.push(json!(id));
labels.push(json!(description["displayName"].as_str().unwrap_or_default()));
descriptions.push(json!(description["description"].as_str().unwrap_or_default()));
}
property.schema["enum"] = Value::Array(ids);
property.schema["enumItemLabels"] = Value::Array(labels);
property.schema["markdownEnumDescriptions"] = Value::Array(descriptions);
}
/// codeActionsContribution.ts `updateConfigurationSchema`: each provided `source` kind gets its own property in
/// `editor.codeActionsOnSave` and `notebook.codeActionsOnSave`; properties once added stay.
pub fn list_code_actions_on_save(&mut self, source_kinds: &[&str]) {
for kind in source_kinds {
let description = format!("Controls whether '{kind}' actions should be run on file save.");
if let Some(property) = self.properties.get_mut("editor.codeActionsOnSave")
&& property.schema["properties"].get(*kind).is_none()
{
property.schema["properties"][*kind] = json!({
"type": "string",
"enum": ["always", "explicit", "never", true, false],
"enumDescriptions": [
"Triggers Code Actions on explicit saves and auto saves triggered by window or focus changes.",
"Triggers Code Actions only when explicitly saved",
"Never triggers Code Actions on save",
"Triggers Code Actions only when explicitly saved. This value will be deprecated in favor of \"explicit\".",
"Never triggers Code Actions on save. This value will be deprecated in favor of \"never\".",
],
"default": "explicit",
"description": description,
});
}
if let Some(property) = self.properties.get_mut("notebook.codeActionsOnSave")
&& property.schema["properties"].get(*kind).is_none()
{
property.schema["properties"][*kind] = json!({
"type": ["string", "boolean"],
"enum": ["explicit", "never", true, false],
"enumDescriptions": [
"Triggers Code Actions only when explicitly saved.",
"Never triggers Code Actions on save.",
"Triggers Code Actions only when explicitly saved. This value will be deprecated in favor of \"explicit\".",
"Triggers Code Actions only when explicitly saved. This value will be deprecated in favor of \"never\".",
],
"default": "explicit",
"description": description,
});
}
}
}
/// folding.contribution.ts `_updateConfigValues`: `editor.defaultFoldingRangeProvider` offers All, then the
/// extensions with code, Programming Languages first, each group by name.
fn list_folding_range_providers(&mut self, extensions: &[(&str, &Value)]) {
let Some(property) = self.properties.get_mut("editor.defaultFoldingRangeProvider") else { return };
let mut with_code: Vec<_> = extensions.iter().filter(|(_, description)| description.get("main").is_some() || description.get("browser").is_some()).collect();
let is_language = |description: &Value| description["categories"].as_array().is_some_and(|categories| categories.iter().any(|category| category == "Programming Languages"));
with_code.sort_by_key(|(_, description)| (!is_language(description), description["name"].as_str().unwrap_or_default().to_lowercase()));
let mut ids = vec![Value::Null];
let mut labels = vec![json!("All")];
let mut descriptions = vec![json!("All active folding range providers")];
for (id, description) in with_code {
ids.push(json!(id));
labels.push(json!(description["displayName"].as_str().unwrap_or_default()));
descriptions.push(json!(description["description"].as_str().unwrap_or_default()));
}
property.schema["enum"] = Value::Array(ids);
property.schema["enumItemLabels"] = Value::Array(labels);
property.schema["markdownEnumDescriptions"] = Value::Array(descriptions);
}
/// The `configuration` contribution of one extension's package.json (`configurationExtPoint` handler).
pub fn register_configuration(&mut self, extension_id: &str, description: &Value) {
let display_name = description["displayName"].as_str();
let restricted: Vec<&str> = match &description["capabilities"]["untrustedWorkspaces"] {
limited if limited["supported"] == "limited" => limited["restrictedConfigurations"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(),
_ => Vec::new(),
};
let nodes = match &description["contributes"]["configuration"] {
Value::Array(nodes) => nodes.iter().collect(),
node @ Value::Object(_) => vec![node],
_ => Vec::new(),
};
for node in nodes {
if js_truthy(&node["title"]) && !node["title"].is_string() {
self.messages.push((extension_id.to_owned(), CollectorMessage::Error("'configuration.title' must be a string".into())));
}
let section = json!({
"id": node["id"].as_str().unwrap_or(extension_id),
"title": node["title"].as_str().or(display_name).unwrap_or(extension_id),
"order": node["order"],
"extensionInfo": { "id": extension_id, "displayName": display_name },
});
self.register_properties(extension_id, description, node, §ion, &restricted);
}
}
/// configurationExtensionPoint.ts `validateProperties` of a node and its `allOf` nodes, then the registration of
/// the properties that pass.
fn register_properties(&mut self, extension_id: &str, description: &Value, node: &Value, section: &Value, restricted: &[&str]) {
let mut report = |message| self.messages.push((extension_id.to_owned(), message));
let properties = &node["properties"];
if js_truthy(properties) && !properties.is_object() && !properties.is_array() {
report(CollectorMessage::Error("'configuration.properties' must be an object".into()));
}
let proposed = description["enabledApiProposals"].as_array().is_some_and(|proposals| proposals.iter().any(|proposal| proposal == "agentsWindowConfiguration"));
let mut accepted = Vec::new();
for (key, schema) in properties.as_object().into_iter().flatten() {
// configurationRegistry.ts `validateProperty`; a key seen earlier in this delta is registered already.
let invalid = if key.trim().is_empty() {
Some("Cannot register an empty property".to_owned())
} else if is_override_key(key) {
Some(format!("Cannot register '{key}'. This matches property pattern '\\[.*\\]$' for describing language specific editor settings. Use 'configurationDefaults' contribution."))
} else if self.properties.contains_key(key) || accepted.iter().any(|(accepted, _)| accepted == key) {
Some(format!("Cannot register '{key}'. This property is already registered."))
} else if js_truthy(&schema["policy"]) && js_truthy(&schema["policyReference"]) {
Some(format!("Cannot register '{key}'. A setting must not declare both 'policy' and 'policyReference'."))
} else {
None
};
if let Some(message) = invalid {
report(CollectorMessage::Warning(message));
continue;
}
if !schema.is_object() {
report(CollectorMessage::Error(format!("configuration.properties property '{key}' must be an object")));
continue;
}
if js_truthy(&schema["agentsWindow"]) && !proposed {
report(CollectorMessage::Error(format!("Extension '{extension_id}' CANNOT use 'agentsWindow' property on configuration '{key}' without enabling the 'agentsWindowConfiguration' API proposal.")));
}
if js_truthy(&schema["agentHost"]) {
report(CollectorMessage::Error(format!("Extension '{extension_id}' CANNOT use the 'agentHost' property on configuration '{key}'.")));
}
accepted.push((key.clone(), schema));
}
let sub_nodes = &node["allOf"];
if js_truthy(sub_nodes) {
report(CollectorMessage::Error("'configuration.allOf' is deprecated and should no longer be used. Instead, pass multiple configuration sections as an array to the 'configuration' contribution point.".into()));
}
for (key, schema) in accepted {
// `included: false` goes to the excluded properties, which only policies and experiments read.
if schema["included"] == false {
self.excluded.insert(key, schema.clone());
continue;
}
let mut schema = schema.clone();
schema["section"] = section.clone();
let scope = schema["scope"].as_str().map_or(Scope::Window, Scope::parse);
let restricted = schema["restricted"].as_bool().unwrap_or_else(|| restricted.contains(&key.as_str()));
let default = schema.get("default").cloned();
self.insert(key, Property { scope, restricted, default: Value::Null, default_default: default, source: Some(extension_id.to_owned()), schema });
}
for sub_node in sub_nodes.as_array().into_iter().flatten() {
self.register_properties(extension_id, description, sub_node, section, restricted);
}
}
/// The `configurationDefaults` contribution of one extension (`defaultConfigurationExtPoint` handler).
pub fn register_configuration_defaults(&mut self, extension_id: &str, description: &Value) {
let Some(overrides) = description["contributes"]["configurationDefaults"].as_object() else { return };
const ALLOWED: [Scope; 4] = [Scope::MachineOverridable, Scope::Window, Scope::Resource, Scope::LanguageOverridable];
let mut allowed = Map::new();
for (key, value) in overrides {
let property = self.properties.get(key);
if property.is_some_and(|p| p.schema["disallowConfigurationDefault"] == true) {
self.messages.push((extension_id.to_owned(), CollectorMessage::Warning(format!("Cannot register configuration defaults for '{key}'. This setting does not allow contributing configuration defaults."))));
continue;
}
if !is_override_key(key) && property.is_some_and(|p| !ALLOWED.contains(&p.scope)) {
self.messages.push((extension_id.to_owned(), CollectorMessage::Warning(format!("Cannot register configuration defaults for '{key}'. Only defaults for machine-overridable, window, resource and language overridable scoped settings are supported."))));
continue;
}
allowed.insert(key.clone(), value.clone());
}
self.register_defaults(&Value::Object(allowed), Some(extension_id));
}
/// `doRegisterDefaultConfigurations`: `[lang]` blocks merge key by key, object settings merge their keys, the rest replace.
fn register_defaults(&mut self, overrides: &Value, source: Option<&str>) {
for (key, value) in overrides.as_object().into_iter().flatten() {
let existing = self.default_overrides.iter().position(|(k, _, _)| k == key);
let previous = existing.map(|index| self.default_overrides[index].1.clone());
let merged = if is_override_key(key) {
let mut merged = previous.and_then(|p| p.as_object().cloned()).unwrap_or_default();
for (property, property_value) in value.as_object().into_iter().flatten() {
if let (Some(Value::Object(base)), Value::Object(add)) = (merged.get_mut(property), property_value) {
base.extend(add.clone());
continue;
}
merged.insert(property.clone(), property_value.clone());
}
Value::Object(merged)
} else {
let property = self.properties.get(key);
let existing_default = previous.or_else(|| property.and_then(|p| p.default_default.clone()));
let is_object_setting = value.is_object()
&& match property {
Some(property) => property.schema["type"] == "object",
None => existing_default.as_ref().is_none_or(Value::is_object),
};
match (is_object_setting, existing_default) {
(true, Some(Value::Object(mut base))) => {
base.extend(value.as_object().cloned().unwrap_or_default());
Value::Object(base)
}
_ => value.clone(),
}
};
let entry = (key.clone(), merged, source.map(str::to_owned));
match existing {
Some(index) => self.default_overrides[index] = entry,
None => self.default_overrides.push(entry),
}
}
}
fn insert(&mut self, key: String, property: Property) {
if !self.properties.contains_key(&key) {
self.keys.push(key.clone());
}
self.properties.insert(key, property);
}
/// Resolves every default (`updatePropertyDefaultValue`) and adds a `[lang]` property per language default
/// (`updateDefaultOverrideProperty`). Call once all contributions are in.
pub fn finish(&mut self) {
for (key, value, source) in self.default_overrides.clone() {
if is_override_key(&key) {
// `getLanguageTagSettingPlainKey`: `[a][b]` reads `a, b`.
let plain_key = key.strip_prefix('[').and_then(|key| key.strip_suffix(']')).expect("an override key").replace("][", ", ");
let schema = json!({
"type": "object",
"default": value,
"description": format!("Configure settings to be overridden for {plain_key}."),
"$ref": "vscode://schemas/settings/resourceLanguage",
"section": { "id": "defaultOverrides", "title": "Default Language Configuration Overrides" },
});
self.insert(key, Property { schema, scope: Scope::Window, restricted: false, default: Value::Null, default_default: Some(value), source });
}
}
for property in self.properties.values_mut() {
property.default = property.default_default.clone().unwrap_or_else(|| default_for_type(&property.schema["type"]));
}
for (key, value, source) in &self.default_overrides {
let Some(property) = self.properties.get_mut(key) else { continue };
if is_override_key(key) || property.schema["disallowConfigurationDefault"] != true || source.is_none() {
property.default = value.clone();
}
}
}
pub fn property(&self, key: &str) -> Option<&Property> {
self.properties.get(key)
}
/// Registered keys in registration order.
pub fn keys(&self) -> &[String] {
&self.keys
}
/// `DefaultConfiguration.configurationModel`: every property's default, `[lang]` defaults as overrides.
pub fn default_model(&self) -> ConfigurationModel {
let mut model = ConfigurationModel::default();
for key in &self.keys {
model.set_value(key, self.properties[key].default.clone());
}
model
}
/// `getScopes()`: what `$initializeConfiguration` sends as `configurationScopes` in a development build.
pub fn scopes(&self) -> Value {
let mut scopes: Vec<Value> = self
.keys
.iter()
.map(|key| match is_override_key(key) {
true => json!([key, null]),
false => json!([key, self.properties[key].scope as u8]),
})
.collect();
scopes.push(json!(["launch", Scope::Resource as u8]));
scopes.push(json!(["task", Scope::Resource as u8]));
Value::Array(scopes)
}
}
/// workbench/common/configuration.ts `DynamicWorkbenchSecurityConfiguration`: the UNC settings it registers on
/// Windows only, so the macOS dump in core-settings.json has none.
fn windows_settings() -> Map<String, Value> {
let section = json!({ "id": "security", "title": "Security", "order": 7 });
let Value::Object(settings) = json!({
"security.allowedUNCHosts": {
"type": "array",
"items": { "type": "string", "pattern": "^[^\\\\]+$", "patternErrorMessage": "UNC host names must not contain backslashes." },
"default": [],
"markdownDescription": "A set of UNC host names (without leading or trailing backslash, for example `192.168.0.1` or `my-server`) to allow without user confirmation. If a UNC host is being accessed that is not allowed via this setting or has not been acknowledged via user confirmation, an error will occur and the operation stopped. A restart is required when changing this setting. Find out more about this setting at https://aka.ms/vscode-windows-unc.",
"scope": 3,
"section": section,
"restricted": false,
},
"security.restrictUNCAccess": {
"type": "boolean",
"default": true,
"markdownDescription": "If enabled, only allows access to UNC host names that are allowed by the `#security.allowedUNCHosts#` setting or after user confirmation. Find out more about this setting at https://aka.ms/vscode-windows-unc.",
"scope": 3,
"section": section,
"restricted": false,
},
}) else {
unreachable!("an object literal")
};
settings
}
/// `getDefaultValue(type)`.
fn js_truthy(value: &Value) -> bool {
match value {
Value::Null | Value::Bool(false) => false,
Value::Number(number) => number.as_f64() != Some(0.),
Value::String(text) => !text.is_empty(),
_ => true,
}
}
fn default_for_type(type_: &Value) -> Value {
let first = match type_ {
Value::Array(types) => types.first().and_then(Value::as_str),
other => other.as_str(),
};
match first {
Some("boolean") => json!(false),
Some("integer" | "number") => json!(0),
Some("string") => json!(""),
Some("array") => json!([]),
Some("object") => json!({}),
_ => Value::Null,
}
}
/// The default-override cases of platform/configuration/test/common/configurationRegistry.test.ts, fed through
/// package.json contributions. The policy and hidden-experiment cases are left out: the port has no policies.
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_unc_settings_are_registered_only_on_windows_and_restrict_by_default() {
let registry = Registry::with_extensions(&[]);
assert_eq!(registry.properties.contains_key("security.allowedUNCHosts"), cfg!(windows));
assert_eq!(windows_settings()["security.restrictUNCAccess"]["default"], json!(true));
assert_eq!(windows_settings()["security.allowedUNCHosts"]["default"], json!([]));
}
#[test]
fn the_folding_range_provider_setting_lists_the_extensions_with_code() {
let css = json!({ "name": "css-language-features", "displayName": "CSS", "description": "css", "main": "a", "categories": ["Programming Languages"] });
let git = json!({ "name": "git", "displayName": "Git", "description": "git", "main": "b" });
let theme = json!({ "name": "theme-abyss", "displayName": "Abyss" });
let html = json!({ "name": "html-language-features", "displayName": "HTML", "browser": "c", "categories": ["Programming Languages"] });
let registry = Registry::with_extensions(&[("vscode.git", &git), ("vscode.theme-abyss", &theme), ("vscode.html-language-features", &html), ("vscode.css-language-features", &css)]);
let schema = ®istry.properties["editor.defaultFoldingRangeProvider"].schema;
assert_eq!(schema["enum"], json!([null, "vscode.css-language-features", "vscode.html-language-features", "vscode.git"]));
assert_eq!(schema["enumItemLabels"], json!(["All", "CSS", "HTML", "Git"]));
assert_eq!(schema["markdownEnumDescriptions"], json!(["All active folding range providers", "css", "", "git"]));
}
#[test]
fn the_default_formatter_setting_lists_registered_formatters_first() {
let css = json!({ "name": "css-language-features", "displayName": "CSS", "description": "css", "main": "a", "categories": ["Programming Languages"] });
let git = json!({ "name": "git", "displayName": "Git", "description": "git", "main": "b" });
let prettier = json!({ "name": "prettier", "displayName": "Prettier", "main": "c", "categories": ["Formatters"] });
let ts = json!({ "name": "typescript-language-features", "displayName": "TS", "main": "d" });
let extensions: [(&str, &Value); 4] = [("vscode.git", &git), ("vscode.css-language-features", &css), ("esbenp.prettier", &prettier), ("vscode.typescript-language-features", &ts)];
let mut registry = Registry::with_extensions(&extensions);
registry.list_default_formatters(&extensions, &["VSCODE.typescript-language-features".into()]);
let schema = ®istry.properties["editor.defaultFormatter"].schema;
assert_eq!(schema["enum"], json!([null, "vscode.typescript-language-features", "vscode.css-language-features", "esbenp.prettier", "vscode.git"]));
assert_eq!(schema["enumItemLabels"], json!(["None", "TS", "CSS", "Prettier", "Git"]));
}
#[test]
fn code_actions_on_save_gets_a_property_per_provided_source_kind() {
let mut registry = Registry::core();
registry.list_code_actions_on_save(&["source.organizeImports"]);
let editor = ®istry.properties["editor.codeActionsOnSave"].schema["properties"]["source.organizeImports"];
assert_eq!((editor["default"].as_str(), editor["enum"][0].as_str()), (Some("explicit"), Some("always")));
assert_eq!(editor["description"], "Controls whether 'source.organizeImports' actions should be run on file save.");
assert_eq!(registry.properties["notebook.codeActionsOnSave"].schema["properties"]["source.organizeImports"]["enum"], json!(["explicit", "never", true, false]));
}
#[test]
fn a_stable_build_registers_the_stable_settings() {
let (stable, oss) = (Registry::core_of_quality(true), Registry::core_of_quality(false));
let default = |registry: &Registry, key: &str| registry.properties[key].default_default.clone();
assert_eq!(default(&stable, "workbench.settings.alwaysShowAdvancedSettings"), Some(json!(false)));
assert_eq!(default(&oss, "workbench.settings.alwaysShowAdvancedSettings"), Some(json!(true)));
assert_eq!(default(&stable, "window.menuStyle"), Some(json!("native")));
assert!(oss.properties.contains_key("extensions.autoRestart"));
assert!(!stable.properties.contains_key("extensions.autoRestart"));
assert_eq!(default(&stable, "update.releaseChannel"), Some(json!("latest")));
assert_eq!(default(&oss, "update.releaseChannel"), Some(json!("pre-release")));
assert_eq!(oss.properties["update.releaseChannel"].schema["default"], "pre-release");
}
fn registry(properties: Value, defaults: &[Value]) -> Registry {
let mut registry = Registry::default();
registry.register_configuration("test", &json!({ "contributes": { "configuration": { "id": "_test_default", "type": "object", "properties": properties } } }));
for (index, overrides) in defaults.iter().enumerate() {
registry.register_configuration_defaults(&format!("defaults{index}"), &json!({ "contributes": { "configurationDefaults": overrides } }));
}
registry.finish();
registry
}
#[test]
fn configuration_override() {
let registry = registry(json!({ "config": { "type": "object" } }), &[json!({ "config": { "a": 1, "b": 2 } }), json!({ "[lang]": { "a": 2, "c": 3 } })]);
assert_eq!(registry.property("config").unwrap().default, json!({ "a": 1, "b": 2 }));
assert_eq!(registry.property("[lang]").unwrap().default, json!({ "a": 2, "c": 3 }));
}
#[test]
fn override_defaults_cannot_override_a_disallowed_default() {
let properties = json!({ "config.preventDefaultValueOverride": { "type": "object", "default": { "a": 0 }, "disallowConfigurationDefault": true } });
let registry = registry(properties, &[json!({ "config.preventDefaultValueOverride": { "a": 1, "b": 2 } })]);
assert_eq!(registry.property("config.preventDefaultValueOverride").unwrap().default, json!({ "a": 0 }));
}
#[test]
fn override_defaults_merge() {
let languages = registry(json!({}), &[json!({ "[lang]": { "a": 1, "b": 2 } }), json!({ "[lang]": { "a": 2, "c": 3 } })]);
assert_eq!(languages.property("[lang]").unwrap().default, json!({ "a": 2, "b": 2, "c": 3 }));
let registry = registry(json!({ "config": { "type": "object" } }), &[json!({ "config": { "a": 1, "b": 2 } }), json!({ "config": { "a": 2, "c": 3 } })]);
assert_eq!(registry.property("config").unwrap().default, json!({ "a": 2, "b": 2, "c": 3 }));
}
#[test]
fn contributed_defaults_respect_scope() {
let properties = json!({ "app": { "type": "string", "default": "a", "scope": "application" }, "win": { "type": "string", "default": "a" } });
let registry = registry(properties, &[json!({ "app": "b", "win": "b" })]);
assert_eq!((®istry.property("app").unwrap().default, ®istry.property("win").unwrap().default), (&json!("a"), &json!("b")));
}
#[test]
fn core_registry_has_upstream_defaults() {
let registry = Registry::with_extensions(&[]);
assert_eq!(registry.property("editor.tabSize").unwrap().default, json!(4));
assert_eq!(registry.property("workbench.colorTheme").unwrap().default, json!("Dark 2026"));
assert_eq!(registry.property("[yaml]").unwrap().default, json!({ "editor.insertSpaces": true, "editor.tabSize": 2 }));
assert_eq!(registry.property("window.appIcon").unwrap().default, json!("default"), "a port setting");
}
/// configurations.test.ts `DefaultConfiguration` cases without events: the port builds the registry once per
/// extension set (`with_extensions`), so the initialize, update and deregister cases have no counterpart.
#[test]
fn default_configuration_cases() {
let model = registry(json!({ "a": { "type": "boolean", "default": false } }), &[]).default_model();
assert_eq!(model.get_value(Some("a")), Some(json!(false)), "registering a property");
let model = registry(json!({ "a.b": { "type": "object", "default": {} }, "a.b.c": { "type": "object", "default": "2" } }), &[]).default_model();
assert_eq!(model.get_value(Some("a")), Some(json!({ "b": { "c": "2" } })), "nested properties");
assert_eq!(model.keys, ["a.b", "a.b.c"]);
let mut same = Registry::default();
for (id, default) in [("first", true), ("second", false)] {
same.register_configuration(id, &json!({ "contributes": { "configuration": { "id": "a", "properties": { "a": { "type": "boolean", "default": default } } } } }));
}
same.finish();
assert_eq!(same.default_model().get_value(Some("a")), Some(json!(true)), "the first registration wins");
let model = registry(json!({}), &[json!({ "[a]": { "b": true } })]).default_model();
assert_eq!(model.get_value(Some("[a]")), Some(json!({ "b": true })), "an override identifier");
assert_eq!(model.keys, ["[a]"]);
assert_eq!(model.get_override_value(Some("b"), "a"), Some(json!(true)));
let model = registry(json!({ "b": { "type": "boolean", "default": false } }), &[json!({ "[a]": { "b": true } })]).default_model();
assert_eq!((model.get_value(Some("b")), model.get_value(Some("[a]"))), (Some(json!(false)), Some(json!({ "b": true }))), "a property and an override identifier");
assert_eq!(model.keys, ["b", "[a]"]);
assert_eq!(model.get_override_value(Some("b"), "a"), Some(json!(true)));
}
}