Visual Studio Code, rebuilt in Rust
Rust
//! `SettingsFileSystemProvider` (workbench/contrib/preferences/common/settingsFilesystemProvider.ts): the read-only
//! `vscode` scheme serving the JSON schemas of the contribution registry, their file associations, and the
//! `vscode://defaultsettings` documents, whose content the workbench builds (`getDefaultSettingsContent`).
use std::time::{SystemTime, UNIX_EPOCH};
use config::json_schema::{INLINE_COMPLETION_PROVIDERS_SCHEMA_ID, KEYBINDINGS_SCHEMA_ID, REFERENCED_SCHEMAS, compressed_content, keybindings_schema, referenced_schema, settings_schemas};
use config::service::Settings;
use files::{FILE, FILE_NOT_FOUND, PROVIDER_READONLY, READONLY, Resource, Stat};
/// `FileSystemProviderCapabilities.Readonly + FileReadWrite`.
pub const CAPABILITIES: u32 = PROVIDER_READONLY + 2;
const SCHEMA_ASSOCIATIONS: &str = "vscode://schemas-associations/schemas-associations.json";
pub fn read_file(settings: &Settings, resource: &Resource, default_settings_content: Option<String>) -> files::Result<Vec<u8>> {
let content = match resource.authority.as_str() {
// `getSchemaContent`: an unregistered schema is the empty schema.
"schemas" => schema_content(settings, &uri_string(resource)),
// Only chat registers schema associations, and the port has no chat.
"schemas-associations" => r#"{"schemas":[]}"#.to_string(),
"defaultsettings" => default_settings_content.ok_or_else(|| not_found(resource))?,
_ => return Err(not_found(resource)),
};
Ok(content.into_bytes())
}
pub fn stat(settings: &Settings, resource: &Resource, default_settings_content: Option<String>) -> files::Result<Stat> {
let uri = uri_string(resource);
let is_default_settings = resource.authority == "defaultsettings" && default_settings_content.is_some();
if !is_default_settings && !REFERENCED_SCHEMAS.iter().any(|(id, _)| *id == uri) && schema(settings, &uri).is_none() && uri != SCHEMA_ASSOCIATIONS && uri != KEYBINDINGS_SCHEMA_ID && uri != INLINE_COMPLETION_PROVIDERS_SCHEMA_ID {
return Err(not_found(resource));
}
let now = SystemTime::now().duration_since(UNIX_EPOCH).expect("after 1970").as_millis() as u64;
Ok(Stat { file_type: FILE, ctime: now, mtime: now, size: 0, permissions: Some(READONLY) })
}
/// `onDidChangeSchema` after the registry changed: the `$onFileEvent` of the schemas whose content differs, so
/// json-language-features refetches them (jsonClient.ts `ensureFilesystemWatcherInstalled`).
pub fn schema_changes(before: &[(String, String)], after: &[(String, String)]) -> Option<serde_json::Value> {
let mut changed = Vec::new();
for (id, content) in after {
if !before.contains(&(id.clone(), content.clone())) {
let path = id.strip_prefix("vscode://schemas").expect("a vscode://schemas id");
changed.push(serde_json::json!({ "$mid": 1, "scheme": "vscode", "authority": "schemas", "path": path, "query": "" }));
}
}
(!changed.is_empty()).then(|| serde_json::json!({ "created": [], "changed": changed, "deleted": [] }))
}
/// Every `vscode://schemas/*` id with its content.
pub fn schema_contents(settings: &Settings) -> Vec<(String, String)> {
let mut ids: Vec<String> = REFERENCED_SCHEMAS.iter().map(|(id, _)| id.to_string()).collect();
ids.extend([KEYBINDINGS_SCHEMA_ID.to_string(), INLINE_COMPLETION_PROVIDERS_SCHEMA_ID.to_string()]);
ids.extend(settings_schemas(&settings.registry, in_workspace(settings)).into_iter().map(|(id, _)| id.to_string()));
ids.into_iter().map(|id| (id.clone(), schema_content(settings, &id))).collect()
}
/// `getSchemaContent`: an unregistered schema is the empty schema.
fn schema_content(settings: &Settings, uri: &str) -> String {
match referenced_schema(&settings.registry, uri) {
Some(content) => content,
None if uri == KEYBINDINGS_SCHEMA_ID => keybindings_schema(&settings.registry).to_string(),
None if uri == INLINE_COMPLETION_PROVIDERS_SCHEMA_ID => serde_json::json!({ "enum": settings.registry.inline_completion_providers }).to_string(),
None => schema(settings, uri).map_or_else(|| "{}".to_string(), |schema| compressed_content(&schema)),
}
}
fn schema(settings: &Settings, uri: &str) -> Option<serde_json::Value> {
settings_schemas(&settings.registry, in_workspace(settings)).into_iter().find(|(id, _)| *id == uri).map(|(_, schema)| schema)
}
fn in_workspace(settings: &Settings) -> bool {
settings.workspace.as_ref().is_some_and(|workspace| workspace.file.is_some())
}
fn uri_string(resource: &Resource) -> String {
format!("{}://{}{}", resource.scheme, resource.authority, resource.path)
}
fn not_found(resource: &Resource) -> files::FileError {
files::provider_error(FILE_NOT_FOUND, format!("{} not found", uri_string(resource)))
}
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use config::registry::Registry;
use super::*;
#[test]
fn default_settings_are_read_and_stated_with_the_workbench_content() {
let settings = Settings::load(Registry::with_extensions(&[]), PathBuf::from("/nonexistent/User"), None);
let resource = Resource { scheme: "vscode".into(), authority: "defaultsettings".into(), path: "/defaultSettings.jsonc".into(), query: String::new() };
assert_eq!(read_file(&settings, &resource, Some("{}".into())).unwrap(), b"{}");
assert_eq!(stat(&settings, &resource, Some("{}".into())).unwrap().file_type, FILE);
assert_eq!(files::provider_code(&read_file(&settings, &resource, None).unwrap_err()), FILE_NOT_FOUND);
assert_eq!(files::provider_code(&stat(&settings, &resource, None).unwrap_err()), FILE_NOT_FOUND);
}
#[test]
fn an_extension_s_contributions_change_the_schemas_it_extends() {
let mut settings = Settings::load(Registry::with_extensions(&[]), PathBuf::from("/nonexistent/User"), None);
let before = schema_contents(&settings);
assert_eq!(schema_changes(&before, &schema_contents(&settings)), None);
let package = serde_json::json!({ "contributes": {
"colors": [{ "id": "port.color", "description": "A color.", "defaults": { "dark": "#ffffff", "light": "#000000", "highContrast": null } }],
"configuration": { "properties": { "port.setting": { "type": "boolean", "default": false } } },
} });
settings.set_registry(Registry::with_extensions(&[("port.ext", &package)]));
let event = schema_changes(&before, &schema_contents(&settings)).unwrap();
let paths: Vec<&str> = event["changed"].as_array().unwrap().iter().map(|uri| uri["path"].as_str().unwrap()).collect();
assert_eq!(paths, ["/workbench-colors", "/settings/default", "/settings/user", "/settings/profile", "/settings/machine", "/settings/workspace", "/settings/folder", "/settings/configurationDefaults"]);
assert_eq!(event["changed"][0]["authority"], "schemas");
}
}