settings_store.rs

   1use anyhow::{Context as _, Result, anyhow};
   2use collections::{BTreeMap, HashMap, btree_map, hash_map};
   3use ec4rs::{ConfigParser, PropertiesSource, Section};
   4use fs::Fs;
   5use futures::{FutureExt, StreamExt, channel::mpsc, future::LocalBoxFuture};
   6use gpui::{App, AsyncApp, BorrowAppContext, Global, Task, UpdateGlobal};
   7
   8use paths::{EDITORCONFIG_NAME, local_settings_file_relative_path, task_file_name};
   9use schemars::{JsonSchema, r#gen::SchemaGenerator, schema::RootSchema};
  10use serde::{Deserialize, Serialize, de::DeserializeOwned};
  11use serde_json::Value;
  12use smallvec::SmallVec;
  13use std::{
  14    any::{Any, TypeId, type_name},
  15    fmt::Debug,
  16    ops::Range,
  17    path::{Path, PathBuf},
  18    str::{self, FromStr},
  19    sync::{Arc, LazyLock},
  20};
  21use streaming_iterator::StreamingIterator;
  22use tree_sitter::Query;
  23use util::RangeExt;
  24
  25use util::{ResultExt as _, merge_non_null_json_value_into};
  26
  27pub type EditorconfigProperties = ec4rs::Properties;
  28
  29use crate::{SettingsJsonSchemaParams, VsCodeSettings, WorktreeId};
  30
  31/// A value that can be defined as a user setting.
  32///
  33/// Settings can be loaded from a combination of multiple JSON files.
  34pub trait Settings: 'static + Send + Sync {
  35    /// The name of a key within the JSON file from which this setting should
  36    /// be deserialized. If this is `None`, then the setting will be deserialized
  37    /// from the root object.
  38    const KEY: Option<&'static str>;
  39
  40    const FALLBACK_KEY: Option<&'static str> = None;
  41
  42    /// The name of the keys in the [`FileContent`](Self::FileContent) that should
  43    /// always be written to a settings file, even if their value matches the default
  44    /// value.
  45    ///
  46    /// This is useful for tagged [`FileContent`](Self::FileContent)s where the tag
  47    /// is a "version" field that should always be persisted, even if the current
  48    /// user settings match the current version of the settings.
  49    const PRESERVED_KEYS: Option<&'static [&'static str]> = None;
  50
  51    /// The type that is stored in an individual JSON file.
  52    type FileContent: Clone + Default + Serialize + DeserializeOwned + JsonSchema;
  53
  54    /// The logic for combining together values from one or more JSON files into the
  55    /// final value for this setting.
  56    fn load(sources: SettingsSources<Self::FileContent>, cx: &mut App) -> Result<Self>
  57    where
  58        Self: Sized;
  59
  60    fn json_schema(
  61        generator: &mut SchemaGenerator,
  62        _: &SettingsJsonSchemaParams,
  63        _: &App,
  64    ) -> RootSchema {
  65        generator.root_schema_for::<Self::FileContent>()
  66    }
  67
  68    fn missing_default() -> anyhow::Error {
  69        anyhow::anyhow!("missing default")
  70    }
  71
  72    /// Use [the helpers in the vscode_import module](crate::vscode_import) to apply known
  73    /// equivalent settings from a vscode config to our config
  74    fn import_from_vscode(vscode: &VsCodeSettings, current: &mut Self::FileContent);
  75
  76    #[track_caller]
  77    fn register(cx: &mut App)
  78    where
  79        Self: Sized,
  80    {
  81        SettingsStore::update_global(cx, |store, cx| {
  82            store.register_setting::<Self>(cx);
  83        });
  84    }
  85
  86    #[track_caller]
  87    fn get<'a>(path: Option<SettingsLocation>, cx: &'a App) -> &'a Self
  88    where
  89        Self: Sized,
  90    {
  91        cx.global::<SettingsStore>().get(path)
  92    }
  93
  94    #[track_caller]
  95    fn get_global(cx: &App) -> &Self
  96    where
  97        Self: Sized,
  98    {
  99        cx.global::<SettingsStore>().get(None)
 100    }
 101
 102    #[track_caller]
 103    fn try_read_global<R>(cx: &AsyncApp, f: impl FnOnce(&Self) -> R) -> Option<R>
 104    where
 105        Self: Sized,
 106    {
 107        cx.try_read_global(|s: &SettingsStore, _| f(s.get(None)))
 108    }
 109
 110    #[track_caller]
 111    fn override_global(settings: Self, cx: &mut App)
 112    where
 113        Self: Sized,
 114    {
 115        cx.global_mut::<SettingsStore>().override_global(settings)
 116    }
 117}
 118
 119#[derive(Clone, Copy, Debug)]
 120pub struct SettingsSources<'a, T> {
 121    /// The default Zed settings.
 122    pub default: &'a T,
 123    /// Global settings (loaded before user settings).
 124    pub global: Option<&'a T>,
 125    /// Settings provided by extensions.
 126    pub extensions: Option<&'a T>,
 127    /// The user settings.
 128    pub user: Option<&'a T>,
 129    /// The user settings for the current release channel.
 130    pub release_channel: Option<&'a T>,
 131    /// The server's settings.
 132    pub server: Option<&'a T>,
 133    /// The project settings, ordered from least specific to most specific.
 134    pub project: &'a [&'a T],
 135}
 136
 137impl<'a, T: Serialize> SettingsSources<'a, T> {
 138    /// Returns an iterator over the default settings as well as all settings customizations.
 139    pub fn defaults_and_customizations(&self) -> impl Iterator<Item = &T> {
 140        [self.default].into_iter().chain(self.customizations())
 141    }
 142
 143    /// Returns an iterator over all of the settings customizations.
 144    pub fn customizations(&self) -> impl Iterator<Item = &T> {
 145        self.global
 146            .into_iter()
 147            .chain(self.extensions)
 148            .chain(self.user)
 149            .chain(self.release_channel)
 150            .chain(self.server)
 151            .chain(self.project.iter().copied())
 152    }
 153
 154    /// Returns the settings after performing a JSON merge of the provided customizations.
 155    ///
 156    /// Customizations later in the iterator win out over the earlier ones.
 157    pub fn json_merge_with<O: DeserializeOwned>(
 158        customizations: impl Iterator<Item = &'a T>,
 159    ) -> Result<O> {
 160        let mut merged = Value::Null;
 161        for value in customizations {
 162            merge_non_null_json_value_into(serde_json::to_value(value).unwrap(), &mut merged);
 163        }
 164        Ok(serde_json::from_value(merged)?)
 165    }
 166
 167    /// Returns the settings after performing a JSON merge of the customizations into the
 168    /// default settings.
 169    ///
 170    /// More-specific customizations win out over the less-specific ones.
 171    pub fn json_merge<O: DeserializeOwned>(&'a self) -> Result<O> {
 172        Self::json_merge_with(self.defaults_and_customizations())
 173    }
 174}
 175
 176#[derive(Clone, Copy, Debug)]
 177pub struct SettingsLocation<'a> {
 178    pub worktree_id: WorktreeId,
 179    pub path: &'a Path,
 180}
 181
 182/// A set of strongly-typed setting values defined via multiple config files.
 183pub struct SettingsStore {
 184    setting_values: HashMap<TypeId, Box<dyn AnySettingValue>>,
 185    raw_default_settings: Value,
 186    raw_global_settings: Option<Value>,
 187    raw_user_settings: Value,
 188    raw_server_settings: Option<Value>,
 189    raw_extension_settings: Value,
 190    raw_local_settings: BTreeMap<(WorktreeId, Arc<Path>), Value>,
 191    raw_editorconfig_settings: BTreeMap<(WorktreeId, Arc<Path>), (String, Option<Editorconfig>)>,
 192    tab_size_callback: Option<(
 193        TypeId,
 194        Box<dyn Fn(&dyn Any) -> Option<usize> + Send + Sync + 'static>,
 195    )>,
 196    _setting_file_updates: Task<()>,
 197    setting_file_updates_tx:
 198        mpsc::UnboundedSender<Box<dyn FnOnce(AsyncApp) -> LocalBoxFuture<'static, Result<()>>>>,
 199}
 200
 201#[derive(Clone)]
 202pub struct Editorconfig {
 203    pub is_root: bool,
 204    pub sections: SmallVec<[Section; 5]>,
 205}
 206
 207impl FromStr for Editorconfig {
 208    type Err = anyhow::Error;
 209
 210    fn from_str(contents: &str) -> Result<Self, Self::Err> {
 211        let parser = ConfigParser::new_buffered(contents.as_bytes())
 212            .context("creating editorconfig parser")?;
 213        let is_root = parser.is_root;
 214        let sections = parser
 215            .collect::<Result<SmallVec<_>, _>>()
 216            .context("parsing editorconfig sections")?;
 217        Ok(Self { is_root, sections })
 218    }
 219}
 220
 221#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
 222pub enum LocalSettingsKind {
 223    Settings,
 224    Tasks,
 225    Editorconfig,
 226    Debug,
 227}
 228
 229impl Global for SettingsStore {}
 230
 231#[derive(Debug)]
 232struct SettingValue<T> {
 233    global_value: Option<T>,
 234    local_values: Vec<(WorktreeId, Arc<Path>, T)>,
 235}
 236
 237trait AnySettingValue: 'static + Send + Sync {
 238    fn key(&self) -> Option<&'static str>;
 239    fn setting_type_name(&self) -> &'static str;
 240    fn deserialize_setting(&self, json: &Value) -> Result<DeserializedSetting> {
 241        self.deserialize_setting_with_key(json).1
 242    }
 243    fn deserialize_setting_with_key(
 244        &self,
 245        json: &Value,
 246    ) -> (Option<&'static str>, Result<DeserializedSetting>);
 247    fn load_setting(
 248        &self,
 249        sources: SettingsSources<DeserializedSetting>,
 250        cx: &mut App,
 251    ) -> Result<Box<dyn Any>>;
 252    fn value_for_path(&self, path: Option<SettingsLocation>) -> &dyn Any;
 253    fn set_global_value(&mut self, value: Box<dyn Any>);
 254    fn set_local_value(&mut self, root_id: WorktreeId, path: Arc<Path>, value: Box<dyn Any>);
 255    fn json_schema(
 256        &self,
 257        generator: &mut SchemaGenerator,
 258        _: &SettingsJsonSchemaParams,
 259        cx: &App,
 260    ) -> RootSchema;
 261    fn edits_for_update(
 262        &self,
 263        raw_settings: &serde_json::Value,
 264        tab_size: usize,
 265        vscode_settings: &VsCodeSettings,
 266        text: &mut String,
 267        edits: &mut Vec<(Range<usize>, String)>,
 268    );
 269}
 270
 271struct DeserializedSetting(Box<dyn Any>);
 272
 273impl SettingsStore {
 274    pub fn new(cx: &App) -> Self {
 275        let (setting_file_updates_tx, mut setting_file_updates_rx) = mpsc::unbounded();
 276        Self {
 277            setting_values: Default::default(),
 278            raw_default_settings: serde_json::json!({}),
 279            raw_global_settings: None,
 280            raw_user_settings: serde_json::json!({}),
 281            raw_server_settings: None,
 282            raw_extension_settings: serde_json::json!({}),
 283            raw_local_settings: Default::default(),
 284            raw_editorconfig_settings: BTreeMap::default(),
 285            tab_size_callback: Default::default(),
 286            setting_file_updates_tx,
 287            _setting_file_updates: cx.spawn(async move |cx| {
 288                while let Some(setting_file_update) = setting_file_updates_rx.next().await {
 289                    (setting_file_update)(cx.clone()).await.log_err();
 290                }
 291            }),
 292        }
 293    }
 294
 295    pub fn update<C, R>(cx: &mut C, f: impl FnOnce(&mut Self, &mut C) -> R) -> R
 296    where
 297        C: BorrowAppContext,
 298    {
 299        cx.update_global(f)
 300    }
 301
 302    /// Add a new type of setting to the store.
 303    pub fn register_setting<T: Settings>(&mut self, cx: &mut App) {
 304        let setting_type_id = TypeId::of::<T>();
 305        let entry = self.setting_values.entry(setting_type_id);
 306
 307        if matches!(entry, hash_map::Entry::Occupied(_)) {
 308            return;
 309        }
 310
 311        let setting_value = entry.or_insert(Box::new(SettingValue::<T> {
 312            global_value: None,
 313            local_values: Vec::new(),
 314        }));
 315
 316        if let Some(default_settings) = setting_value
 317            .deserialize_setting(&self.raw_default_settings)
 318            .log_err()
 319        {
 320            let user_value = setting_value
 321                .deserialize_setting(&self.raw_user_settings)
 322                .log_err();
 323
 324            let mut release_channel_value = None;
 325            if let Some(release_settings) = &self
 326                .raw_user_settings
 327                .get(release_channel::RELEASE_CHANNEL.dev_name())
 328            {
 329                release_channel_value = setting_value
 330                    .deserialize_setting(release_settings)
 331                    .log_err();
 332            }
 333
 334            let server_value = self
 335                .raw_server_settings
 336                .as_ref()
 337                .and_then(|server_setting| {
 338                    setting_value.deserialize_setting(server_setting).log_err()
 339                });
 340
 341            let extension_value = setting_value
 342                .deserialize_setting(&self.raw_extension_settings)
 343                .log_err();
 344
 345            if let Some(setting) = setting_value
 346                .load_setting(
 347                    SettingsSources {
 348                        default: &default_settings,
 349                        global: None,
 350                        extensions: extension_value.as_ref(),
 351                        user: user_value.as_ref(),
 352                        release_channel: release_channel_value.as_ref(),
 353                        server: server_value.as_ref(),
 354                        project: &[],
 355                    },
 356                    cx,
 357                )
 358                .context("A default setting must be added to the `default.json` file")
 359                .log_err()
 360            {
 361                setting_value.set_global_value(setting);
 362            }
 363        }
 364    }
 365
 366    /// Get the value of a setting.
 367    ///
 368    /// Panics if the given setting type has not been registered, or if there is no
 369    /// value for this setting.
 370    pub fn get<T: Settings>(&self, path: Option<SettingsLocation>) -> &T {
 371        self.setting_values
 372            .get(&TypeId::of::<T>())
 373            .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()))
 374            .value_for_path(path)
 375            .downcast_ref::<T>()
 376            .expect("no default value for setting type")
 377    }
 378
 379    /// Override the global value for a setting.
 380    ///
 381    /// The given value will be overwritten if the user settings file changes.
 382    pub fn override_global<T: Settings>(&mut self, value: T) {
 383        self.setting_values
 384            .get_mut(&TypeId::of::<T>())
 385            .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()))
 386            .set_global_value(Box::new(value))
 387    }
 388
 389    /// Get the user's settings as a raw JSON value.
 390    ///
 391    /// For user-facing functionality use the typed setting interface.
 392    /// (e.g. ProjectSettings::get_global(cx))
 393    pub fn raw_user_settings(&self) -> &Value {
 394        &self.raw_user_settings
 395    }
 396
 397    /// Access the raw JSON value of the global settings.
 398    pub fn raw_global_settings(&self) -> Option<&Value> {
 399        self.raw_global_settings.as_ref()
 400    }
 401
 402    #[cfg(any(test, feature = "test-support"))]
 403    pub fn test(cx: &mut App) -> Self {
 404        let mut this = Self::new(cx);
 405        this.set_default_settings(&crate::test_settings(), cx)
 406            .unwrap();
 407        this.set_user_settings("{}", cx).unwrap();
 408        this
 409    }
 410
 411    /// Updates the value of a setting in the user's global configuration.
 412    ///
 413    /// This is only for tests. Normally, settings are only loaded from
 414    /// JSON files.
 415    #[cfg(any(test, feature = "test-support"))]
 416    pub fn update_user_settings<T: Settings>(
 417        &mut self,
 418        cx: &mut App,
 419        update: impl FnOnce(&mut T::FileContent),
 420    ) {
 421        let old_text = serde_json::to_string(&self.raw_user_settings).unwrap();
 422        let new_text = self.new_text_for_update::<T>(old_text, update);
 423        self.set_user_settings(&new_text, cx).unwrap();
 424    }
 425
 426    pub async fn load_settings(fs: &Arc<dyn Fs>) -> Result<String> {
 427        match fs.load(paths::settings_file()).await {
 428            result @ Ok(_) => result,
 429            Err(err) => {
 430                if let Some(e) = err.downcast_ref::<std::io::Error>() {
 431                    if e.kind() == std::io::ErrorKind::NotFound {
 432                        return Ok(crate::initial_user_settings_content().to_string());
 433                    }
 434                }
 435                Err(err)
 436            }
 437        }
 438    }
 439
 440    pub async fn load_global_settings(fs: &Arc<dyn Fs>) -> Result<String> {
 441        match fs.load(paths::global_settings_file()).await {
 442            result @ Ok(_) => result,
 443            Err(err) => {
 444                if let Some(e) = err.downcast_ref::<std::io::Error>() {
 445                    if e.kind() == std::io::ErrorKind::NotFound {
 446                        return Ok("{}".to_string());
 447                    }
 448                }
 449                Err(err)
 450            }
 451        }
 452    }
 453
 454    pub fn update_settings_file<T: Settings>(
 455        &self,
 456        fs: Arc<dyn Fs>,
 457        update: impl 'static + Send + FnOnce(&mut T::FileContent, &App),
 458    ) {
 459        self.setting_file_updates_tx
 460            .unbounded_send(Box::new(move |cx: AsyncApp| {
 461                async move {
 462                    let old_text = Self::load_settings(&fs).await?;
 463                    let new_text = cx.read_global(|store: &SettingsStore, cx| {
 464                        store.new_text_for_update::<T>(old_text, |content| update(content, cx))
 465                    })?;
 466                    let settings_path = paths::settings_file().as_path();
 467                    if fs.is_file(settings_path).await {
 468                        let resolved_path =
 469                            fs.canonicalize(settings_path).await.with_context(|| {
 470                                format!("Failed to canonicalize settings path {:?}", settings_path)
 471                            })?;
 472
 473                        fs.atomic_write(resolved_path.clone(), new_text)
 474                            .await
 475                            .with_context(|| {
 476                                format!("Failed to write settings to file {:?}", resolved_path)
 477                            })?;
 478                    } else {
 479                        fs.atomic_write(settings_path.to_path_buf(), new_text)
 480                            .await
 481                            .with_context(|| {
 482                                format!("Failed to write settings to file {:?}", settings_path)
 483                            })?;
 484                    }
 485
 486                    anyhow::Ok(())
 487                }
 488                .boxed_local()
 489            }))
 490            .ok();
 491    }
 492
 493    pub fn import_vscode_settings(&self, fs: Arc<dyn Fs>, vscode_settings: VsCodeSettings) {
 494        self.setting_file_updates_tx
 495            .unbounded_send(Box::new(move |cx: AsyncApp| {
 496                async move {
 497                    let old_text = Self::load_settings(&fs).await?;
 498                    let new_text = cx.read_global(|store: &SettingsStore, _cx| {
 499                        store.get_vscode_edits(old_text, &vscode_settings)
 500                    })?;
 501                    let settings_path = paths::settings_file().as_path();
 502                    if fs.is_file(settings_path).await {
 503                        let resolved_path =
 504                            fs.canonicalize(settings_path).await.with_context(|| {
 505                                format!("Failed to canonicalize settings path {:?}", settings_path)
 506                            })?;
 507
 508                        fs.atomic_write(resolved_path.clone(), new_text)
 509                            .await
 510                            .with_context(|| {
 511                                format!("Failed to write settings to file {:?}", resolved_path)
 512                            })?;
 513                    } else {
 514                        fs.atomic_write(settings_path.to_path_buf(), new_text)
 515                            .await
 516                            .with_context(|| {
 517                                format!("Failed to write settings to file {:?}", settings_path)
 518                            })?;
 519                    }
 520
 521                    anyhow::Ok(())
 522                }
 523                .boxed_local()
 524            }))
 525            .ok();
 526    }
 527
 528    /// Updates the value of a setting in a JSON file, returning the new text
 529    /// for that JSON file.
 530    pub fn new_text_for_update<T: Settings>(
 531        &self,
 532        old_text: String,
 533        update: impl FnOnce(&mut T::FileContent),
 534    ) -> String {
 535        let edits = self.edits_for_update::<T>(&old_text, update);
 536        let mut new_text = old_text;
 537        for (range, replacement) in edits.into_iter() {
 538            new_text.replace_range(range, &replacement);
 539        }
 540        new_text
 541    }
 542
 543    pub fn get_vscode_edits(&self, mut old_text: String, vscode: &VsCodeSettings) -> String {
 544        let mut new_text = old_text.clone();
 545        let mut edits: Vec<(Range<usize>, String)> = Vec::new();
 546        let raw_settings = parse_json_with_comments::<Value>(&old_text).unwrap_or_default();
 547        let tab_size = self.json_tab_size();
 548        for v in self.setting_values.values() {
 549            v.edits_for_update(&raw_settings, tab_size, vscode, &mut old_text, &mut edits);
 550        }
 551        for (range, replacement) in edits.into_iter() {
 552            new_text.replace_range(range, &replacement);
 553        }
 554        new_text
 555    }
 556
 557    /// Updates the value of a setting in a JSON file, returning a list
 558    /// of edits to apply to the JSON file.
 559    pub fn edits_for_update<T: Settings>(
 560        &self,
 561        text: &str,
 562        update: impl FnOnce(&mut T::FileContent),
 563    ) -> Vec<(Range<usize>, String)> {
 564        let setting_type_id = TypeId::of::<T>();
 565
 566        let preserved_keys = T::PRESERVED_KEYS.unwrap_or_default();
 567
 568        let setting = self
 569            .setting_values
 570            .get(&setting_type_id)
 571            .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()));
 572        let raw_settings = parse_json_with_comments::<Value>(text).unwrap_or_default();
 573        let (key, deserialized_setting) = setting.deserialize_setting_with_key(&raw_settings);
 574        let old_content = match deserialized_setting {
 575            Ok(content) => content.0.downcast::<T::FileContent>().unwrap(),
 576            Err(_) => Box::<<T as Settings>::FileContent>::default(),
 577        };
 578        let mut new_content = old_content.clone();
 579        update(&mut new_content);
 580
 581        let old_value = serde_json::to_value(&old_content).unwrap();
 582        let new_value = serde_json::to_value(new_content).unwrap();
 583
 584        let mut key_path = Vec::new();
 585        if let Some(key) = key {
 586            key_path.push(key);
 587        }
 588
 589        let mut edits = Vec::new();
 590        let tab_size = self.json_tab_size();
 591        let mut text = text.to_string();
 592        update_value_in_json_text(
 593            &mut text,
 594            &mut key_path,
 595            tab_size,
 596            &old_value,
 597            &new_value,
 598            preserved_keys,
 599            &mut edits,
 600        );
 601        edits
 602    }
 603
 604    /// Configure the tab sized when updating JSON files.
 605    pub fn set_json_tab_size_callback<T: Settings>(
 606        &mut self,
 607        get_tab_size: fn(&T) -> Option<usize>,
 608    ) {
 609        self.tab_size_callback = Some((
 610            TypeId::of::<T>(),
 611            Box::new(move |value| get_tab_size(value.downcast_ref::<T>().unwrap())),
 612        ));
 613    }
 614
 615    fn json_tab_size(&self) -> usize {
 616        const DEFAULT_JSON_TAB_SIZE: usize = 2;
 617
 618        if let Some((setting_type_id, callback)) = &self.tab_size_callback {
 619            let setting_value = self.setting_values.get(setting_type_id).unwrap();
 620            let value = setting_value.value_for_path(None);
 621            if let Some(value) = callback(value) {
 622                return value;
 623            }
 624        }
 625
 626        DEFAULT_JSON_TAB_SIZE
 627    }
 628
 629    /// Sets the default settings via a JSON string.
 630    ///
 631    /// The string should contain a JSON object with a default value for every setting.
 632    pub fn set_default_settings(
 633        &mut self,
 634        default_settings_content: &str,
 635        cx: &mut App,
 636    ) -> Result<()> {
 637        let settings: Value = parse_json_with_comments(default_settings_content)?;
 638        if settings.is_object() {
 639            self.raw_default_settings = settings;
 640            self.recompute_values(None, cx)?;
 641            Ok(())
 642        } else {
 643            Err(anyhow!("settings must be an object"))
 644        }
 645    }
 646
 647    /// Sets the user settings via a JSON string.
 648    pub fn set_user_settings(
 649        &mut self,
 650        user_settings_content: &str,
 651        cx: &mut App,
 652    ) -> Result<Value> {
 653        let settings: Value = if user_settings_content.is_empty() {
 654            parse_json_with_comments("{}")?
 655        } else {
 656            parse_json_with_comments(user_settings_content)?
 657        };
 658
 659        anyhow::ensure!(settings.is_object(), "settings must be an object");
 660        self.raw_user_settings = settings.clone();
 661        self.recompute_values(None, cx)?;
 662        Ok(settings)
 663    }
 664
 665    /// Sets the global settings via a JSON string.
 666    pub fn set_global_settings(
 667        &mut self,
 668        global_settings_content: &str,
 669        cx: &mut App,
 670    ) -> Result<Value> {
 671        let settings: Value = if global_settings_content.is_empty() {
 672            parse_json_with_comments("{}")?
 673        } else {
 674            parse_json_with_comments(global_settings_content)?
 675        };
 676
 677        anyhow::ensure!(settings.is_object(), "settings must be an object");
 678        self.raw_global_settings = Some(settings.clone());
 679        self.recompute_values(None, cx)?;
 680        Ok(settings)
 681    }
 682
 683    pub fn set_server_settings(
 684        &mut self,
 685        server_settings_content: &str,
 686        cx: &mut App,
 687    ) -> Result<()> {
 688        let settings: Option<Value> = if server_settings_content.is_empty() {
 689            None
 690        } else {
 691            parse_json_with_comments(server_settings_content)?
 692        };
 693
 694        anyhow::ensure!(
 695            settings
 696                .as_ref()
 697                .map(|value| value.is_object())
 698                .unwrap_or(true),
 699            "settings must be an object"
 700        );
 701        self.raw_server_settings = settings;
 702        self.recompute_values(None, cx)?;
 703        Ok(())
 704    }
 705
 706    /// Add or remove a set of local settings via a JSON string.
 707    pub fn set_local_settings(
 708        &mut self,
 709        root_id: WorktreeId,
 710        directory_path: Arc<Path>,
 711        kind: LocalSettingsKind,
 712        settings_content: Option<&str>,
 713        cx: &mut App,
 714    ) -> std::result::Result<(), InvalidSettingsError> {
 715        let mut zed_settings_changed = false;
 716        match (
 717            kind,
 718            settings_content
 719                .map(|content| content.trim())
 720                .filter(|content| !content.is_empty()),
 721        ) {
 722            (LocalSettingsKind::Tasks, _) => {
 723                return Err(InvalidSettingsError::Tasks {
 724                    message: "Attempted to submit tasks into the settings store".to_string(),
 725                    path: directory_path.join(task_file_name()),
 726                });
 727            }
 728            (LocalSettingsKind::Debug, _) => {
 729                return Err(InvalidSettingsError::Debug {
 730                    message: "Attempted to submit debugger config into the settings store"
 731                        .to_string(),
 732                    path: directory_path.join(task_file_name()),
 733                });
 734            }
 735            (LocalSettingsKind::Settings, None) => {
 736                zed_settings_changed = self
 737                    .raw_local_settings
 738                    .remove(&(root_id, directory_path.clone()))
 739                    .is_some()
 740            }
 741            (LocalSettingsKind::Editorconfig, None) => {
 742                self.raw_editorconfig_settings
 743                    .remove(&(root_id, directory_path.clone()));
 744            }
 745            (LocalSettingsKind::Settings, Some(settings_contents)) => {
 746                let new_settings =
 747                    parse_json_with_comments::<Value>(settings_contents).map_err(|e| {
 748                        InvalidSettingsError::LocalSettings {
 749                            path: directory_path.join(local_settings_file_relative_path()),
 750                            message: e.to_string(),
 751                        }
 752                    })?;
 753                match self
 754                    .raw_local_settings
 755                    .entry((root_id, directory_path.clone()))
 756                {
 757                    btree_map::Entry::Vacant(v) => {
 758                        v.insert(new_settings);
 759                        zed_settings_changed = true;
 760                    }
 761                    btree_map::Entry::Occupied(mut o) => {
 762                        if o.get() != &new_settings {
 763                            o.insert(new_settings);
 764                            zed_settings_changed = true;
 765                        }
 766                    }
 767                }
 768            }
 769            (LocalSettingsKind::Editorconfig, Some(editorconfig_contents)) => {
 770                match self
 771                    .raw_editorconfig_settings
 772                    .entry((root_id, directory_path.clone()))
 773                {
 774                    btree_map::Entry::Vacant(v) => match editorconfig_contents.parse() {
 775                        Ok(new_contents) => {
 776                            v.insert((editorconfig_contents.to_owned(), Some(new_contents)));
 777                        }
 778                        Err(e) => {
 779                            v.insert((editorconfig_contents.to_owned(), None));
 780                            return Err(InvalidSettingsError::Editorconfig {
 781                                message: e.to_string(),
 782                                path: directory_path.join(EDITORCONFIG_NAME),
 783                            });
 784                        }
 785                    },
 786                    btree_map::Entry::Occupied(mut o) => {
 787                        if o.get().0 != editorconfig_contents {
 788                            match editorconfig_contents.parse() {
 789                                Ok(new_contents) => {
 790                                    o.insert((
 791                                        editorconfig_contents.to_owned(),
 792                                        Some(new_contents),
 793                                    ));
 794                                }
 795                                Err(e) => {
 796                                    o.insert((editorconfig_contents.to_owned(), None));
 797                                    return Err(InvalidSettingsError::Editorconfig {
 798                                        message: e.to_string(),
 799                                        path: directory_path.join(EDITORCONFIG_NAME),
 800                                    });
 801                                }
 802                            }
 803                        }
 804                    }
 805                }
 806            }
 807        };
 808
 809        if zed_settings_changed {
 810            self.recompute_values(Some((root_id, &directory_path)), cx)?;
 811        }
 812        Ok(())
 813    }
 814
 815    pub fn set_extension_settings<T: Serialize>(&mut self, content: T, cx: &mut App) -> Result<()> {
 816        let settings: Value = serde_json::to_value(content)?;
 817        anyhow::ensure!(settings.is_object(), "settings must be an object");
 818        self.raw_extension_settings = settings;
 819        self.recompute_values(None, cx)?;
 820        Ok(())
 821    }
 822
 823    /// Add or remove a set of local settings via a JSON string.
 824    pub fn clear_local_settings(&mut self, root_id: WorktreeId, cx: &mut App) -> Result<()> {
 825        self.raw_local_settings
 826            .retain(|(worktree_id, _), _| worktree_id != &root_id);
 827        self.recompute_values(Some((root_id, "".as_ref())), cx)?;
 828        Ok(())
 829    }
 830
 831    pub fn local_settings(
 832        &self,
 833        root_id: WorktreeId,
 834    ) -> impl '_ + Iterator<Item = (Arc<Path>, String)> {
 835        self.raw_local_settings
 836            .range(
 837                (root_id, Path::new("").into())
 838                    ..(
 839                        WorktreeId::from_usize(root_id.to_usize() + 1),
 840                        Path::new("").into(),
 841                    ),
 842            )
 843            .map(|((_, path), content)| (path.clone(), serde_json::to_string(content).unwrap()))
 844    }
 845
 846    pub fn local_editorconfig_settings(
 847        &self,
 848        root_id: WorktreeId,
 849    ) -> impl '_ + Iterator<Item = (Arc<Path>, String, Option<Editorconfig>)> {
 850        self.raw_editorconfig_settings
 851            .range(
 852                (root_id, Path::new("").into())
 853                    ..(
 854                        WorktreeId::from_usize(root_id.to_usize() + 1),
 855                        Path::new("").into(),
 856                    ),
 857            )
 858            .map(|((_, path), (content, parsed_content))| {
 859                (path.clone(), content.clone(), parsed_content.clone())
 860            })
 861    }
 862
 863    pub fn json_schema(&self, schema_params: &SettingsJsonSchemaParams, cx: &App) -> Value {
 864        use schemars::{
 865            r#gen::SchemaSettings,
 866            schema::{Schema, SchemaObject},
 867        };
 868
 869        let settings = SchemaSettings::draft07().with(|settings| {
 870            settings.option_add_null_type = true;
 871        });
 872        let mut generator = SchemaGenerator::new(settings);
 873        let mut combined_schema = RootSchema::default();
 874
 875        for setting_value in self.setting_values.values() {
 876            let setting_schema = setting_value.json_schema(&mut generator, schema_params, cx);
 877            combined_schema
 878                .definitions
 879                .extend(setting_schema.definitions);
 880
 881            let target_schema = if let Some(key) = setting_value.key() {
 882                let key_schema = combined_schema
 883                    .schema
 884                    .object()
 885                    .properties
 886                    .entry(key.to_string())
 887                    .or_insert_with(|| Schema::Object(SchemaObject::default()));
 888                if let Schema::Object(key_schema) = key_schema {
 889                    key_schema
 890                } else {
 891                    continue;
 892                }
 893            } else {
 894                &mut combined_schema.schema
 895            };
 896
 897            merge_schema(target_schema, setting_schema.schema);
 898        }
 899
 900        fn merge_schema(target: &mut SchemaObject, mut source: SchemaObject) {
 901            let source_subschemas = source.subschemas();
 902            let target_subschemas = target.subschemas();
 903            if let Some(all_of) = source_subschemas.all_of.take() {
 904                target_subschemas
 905                    .all_of
 906                    .get_or_insert(Vec::new())
 907                    .extend(all_of);
 908            }
 909            if let Some(any_of) = source_subschemas.any_of.take() {
 910                target_subschemas
 911                    .any_of
 912                    .get_or_insert(Vec::new())
 913                    .extend(any_of);
 914            }
 915            if let Some(one_of) = source_subschemas.one_of.take() {
 916                target_subschemas
 917                    .one_of
 918                    .get_or_insert(Vec::new())
 919                    .extend(one_of);
 920            }
 921
 922            if let Some(source) = source.object {
 923                let target_properties = &mut target.object().properties;
 924                for (key, value) in source.properties {
 925                    match target_properties.entry(key) {
 926                        btree_map::Entry::Vacant(e) => {
 927                            e.insert(value);
 928                        }
 929                        btree_map::Entry::Occupied(e) => {
 930                            if let (Schema::Object(target), Schema::Object(src)) =
 931                                (e.into_mut(), value)
 932                            {
 933                                merge_schema(target, src);
 934                            }
 935                        }
 936                    }
 937                }
 938            }
 939
 940            overwrite(&mut target.instance_type, source.instance_type);
 941            overwrite(&mut target.string, source.string);
 942            overwrite(&mut target.number, source.number);
 943            overwrite(&mut target.reference, source.reference);
 944            overwrite(&mut target.array, source.array);
 945            overwrite(&mut target.enum_values, source.enum_values);
 946
 947            fn overwrite<T>(target: &mut Option<T>, source: Option<T>) {
 948                if let Some(source) = source {
 949                    *target = Some(source);
 950                }
 951            }
 952        }
 953
 954        for release_stage in ["dev", "nightly", "stable", "preview"] {
 955            let schema = combined_schema.schema.clone();
 956            combined_schema
 957                .schema
 958                .object()
 959                .properties
 960                .insert(release_stage.to_string(), schema.into());
 961        }
 962
 963        serde_json::to_value(&combined_schema).unwrap()
 964    }
 965
 966    fn recompute_values(
 967        &mut self,
 968        changed_local_path: Option<(WorktreeId, &Path)>,
 969        cx: &mut App,
 970    ) -> std::result::Result<(), InvalidSettingsError> {
 971        // Reload the global and local values for every setting.
 972        let mut project_settings_stack = Vec::<DeserializedSetting>::new();
 973        let mut paths_stack = Vec::<Option<(WorktreeId, &Path)>>::new();
 974        for setting_value in self.setting_values.values_mut() {
 975            let default_settings = setting_value
 976                .deserialize_setting(&self.raw_default_settings)
 977                .map_err(|e| InvalidSettingsError::DefaultSettings {
 978                    message: e.to_string(),
 979                })?;
 980
 981            let global_settings = self
 982                .raw_global_settings
 983                .as_ref()
 984                .and_then(|setting| setting_value.deserialize_setting(setting).log_err());
 985
 986            let extension_settings = setting_value
 987                .deserialize_setting(&self.raw_extension_settings)
 988                .log_err();
 989
 990            let user_settings = match setting_value.deserialize_setting(&self.raw_user_settings) {
 991                Ok(settings) => Some(settings),
 992                Err(error) => {
 993                    return Err(InvalidSettingsError::UserSettings {
 994                        message: error.to_string(),
 995                    });
 996                }
 997            };
 998
 999            let server_settings = self
1000                .raw_server_settings
1001                .as_ref()
1002                .and_then(|setting| setting_value.deserialize_setting(setting).log_err());
1003
1004            let mut release_channel_settings = None;
1005            if let Some(release_settings) = &self
1006                .raw_user_settings
1007                .get(release_channel::RELEASE_CHANNEL.dev_name())
1008            {
1009                if let Some(release_settings) = setting_value
1010                    .deserialize_setting(release_settings)
1011                    .log_err()
1012                {
1013                    release_channel_settings = Some(release_settings);
1014                }
1015            }
1016
1017            // If the global settings file changed, reload the global value for the field.
1018            if changed_local_path.is_none() {
1019                if let Some(value) = setting_value
1020                    .load_setting(
1021                        SettingsSources {
1022                            default: &default_settings,
1023                            global: global_settings.as_ref(),
1024                            extensions: extension_settings.as_ref(),
1025                            user: user_settings.as_ref(),
1026                            release_channel: release_channel_settings.as_ref(),
1027                            server: server_settings.as_ref(),
1028                            project: &[],
1029                        },
1030                        cx,
1031                    )
1032                    .log_err()
1033                {
1034                    setting_value.set_global_value(value);
1035                }
1036            }
1037
1038            // Reload the local values for the setting.
1039            paths_stack.clear();
1040            project_settings_stack.clear();
1041            for ((root_id, directory_path), local_settings) in &self.raw_local_settings {
1042                // Build a stack of all of the local values for that setting.
1043                while let Some(prev_entry) = paths_stack.last() {
1044                    if let Some((prev_root_id, prev_path)) = prev_entry {
1045                        if root_id != prev_root_id || !directory_path.starts_with(prev_path) {
1046                            paths_stack.pop();
1047                            project_settings_stack.pop();
1048                            continue;
1049                        }
1050                    }
1051                    break;
1052                }
1053
1054                match setting_value.deserialize_setting(local_settings) {
1055                    Ok(local_settings) => {
1056                        paths_stack.push(Some((*root_id, directory_path.as_ref())));
1057                        project_settings_stack.push(local_settings);
1058
1059                        // If a local settings file changed, then avoid recomputing local
1060                        // settings for any path outside of that directory.
1061                        if changed_local_path.map_or(
1062                            false,
1063                            |(changed_root_id, changed_local_path)| {
1064                                *root_id != changed_root_id
1065                                    || !directory_path.starts_with(changed_local_path)
1066                            },
1067                        ) {
1068                            continue;
1069                        }
1070
1071                        if let Some(value) = setting_value
1072                            .load_setting(
1073                                SettingsSources {
1074                                    default: &default_settings,
1075                                    global: global_settings.as_ref(),
1076                                    extensions: extension_settings.as_ref(),
1077                                    user: user_settings.as_ref(),
1078                                    release_channel: release_channel_settings.as_ref(),
1079                                    server: server_settings.as_ref(),
1080                                    project: &project_settings_stack.iter().collect::<Vec<_>>(),
1081                                },
1082                                cx,
1083                            )
1084                            .log_err()
1085                        {
1086                            setting_value.set_local_value(*root_id, directory_path.clone(), value);
1087                        }
1088                    }
1089                    Err(error) => {
1090                        return Err(InvalidSettingsError::LocalSettings {
1091                            path: directory_path.join(local_settings_file_relative_path()),
1092                            message: error.to_string(),
1093                        });
1094                    }
1095                }
1096            }
1097        }
1098        Ok(())
1099    }
1100
1101    pub fn editorconfig_properties(
1102        &self,
1103        for_worktree: WorktreeId,
1104        for_path: &Path,
1105    ) -> Option<EditorconfigProperties> {
1106        let mut properties = EditorconfigProperties::new();
1107
1108        for (directory_with_config, _, parsed_editorconfig) in
1109            self.local_editorconfig_settings(for_worktree)
1110        {
1111            if !for_path.starts_with(&directory_with_config) {
1112                properties.use_fallbacks();
1113                return Some(properties);
1114            }
1115            let parsed_editorconfig = parsed_editorconfig?;
1116            if parsed_editorconfig.is_root {
1117                properties = EditorconfigProperties::new();
1118            }
1119            for section in parsed_editorconfig.sections {
1120                section.apply_to(&mut properties, for_path).log_err()?;
1121            }
1122        }
1123
1124        properties.use_fallbacks();
1125        Some(properties)
1126    }
1127}
1128
1129#[derive(Debug, Clone, PartialEq)]
1130pub enum InvalidSettingsError {
1131    LocalSettings { path: PathBuf, message: String },
1132    UserSettings { message: String },
1133    ServerSettings { message: String },
1134    DefaultSettings { message: String },
1135    Editorconfig { path: PathBuf, message: String },
1136    Tasks { path: PathBuf, message: String },
1137    Debug { path: PathBuf, message: String },
1138}
1139
1140impl std::fmt::Display for InvalidSettingsError {
1141    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1142        match self {
1143            InvalidSettingsError::LocalSettings { message, .. }
1144            | InvalidSettingsError::UserSettings { message }
1145            | InvalidSettingsError::ServerSettings { message }
1146            | InvalidSettingsError::DefaultSettings { message }
1147            | InvalidSettingsError::Tasks { message, .. }
1148            | InvalidSettingsError::Editorconfig { message, .. }
1149            | InvalidSettingsError::Debug { message, .. } => {
1150                write!(f, "{message}")
1151            }
1152        }
1153    }
1154}
1155impl std::error::Error for InvalidSettingsError {}
1156
1157impl Debug for SettingsStore {
1158    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1159        f.debug_struct("SettingsStore")
1160            .field(
1161                "types",
1162                &self
1163                    .setting_values
1164                    .values()
1165                    .map(|value| value.setting_type_name())
1166                    .collect::<Vec<_>>(),
1167            )
1168            .field("default_settings", &self.raw_default_settings)
1169            .field("user_settings", &self.raw_user_settings)
1170            .field("local_settings", &self.raw_local_settings)
1171            .finish_non_exhaustive()
1172    }
1173}
1174
1175impl<T: Settings> AnySettingValue for SettingValue<T> {
1176    fn key(&self) -> Option<&'static str> {
1177        T::KEY
1178    }
1179
1180    fn setting_type_name(&self) -> &'static str {
1181        type_name::<T>()
1182    }
1183
1184    fn load_setting(
1185        &self,
1186        values: SettingsSources<DeserializedSetting>,
1187        cx: &mut App,
1188    ) -> Result<Box<dyn Any>> {
1189        Ok(Box::new(T::load(
1190            SettingsSources {
1191                default: values.default.0.downcast_ref::<T::FileContent>().unwrap(),
1192                global: values
1193                    .global
1194                    .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
1195                extensions: values
1196                    .extensions
1197                    .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
1198                user: values
1199                    .user
1200                    .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
1201                release_channel: values
1202                    .release_channel
1203                    .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
1204                server: values
1205                    .server
1206                    .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
1207                project: values
1208                    .project
1209                    .iter()
1210                    .map(|value| value.0.downcast_ref().unwrap())
1211                    .collect::<SmallVec<[_; 3]>>()
1212                    .as_slice(),
1213            },
1214            cx,
1215        )?))
1216    }
1217
1218    fn deserialize_setting_with_key(
1219        &self,
1220        mut json: &Value,
1221    ) -> (Option<&'static str>, Result<DeserializedSetting>) {
1222        let mut key = None;
1223        if let Some(k) = T::KEY {
1224            if let Some(value) = json.get(k) {
1225                json = value;
1226                key = Some(k);
1227            } else if let Some((k, value)) = T::FALLBACK_KEY.and_then(|k| Some((k, json.get(k)?))) {
1228                json = value;
1229                key = Some(k);
1230            } else {
1231                let value = T::FileContent::default();
1232                return (T::KEY, Ok(DeserializedSetting(Box::new(value))));
1233            }
1234        }
1235        let value = T::FileContent::deserialize(json)
1236            .map(|value| DeserializedSetting(Box::new(value)))
1237            .map_err(anyhow::Error::from);
1238        (key, value)
1239    }
1240
1241    fn value_for_path(&self, path: Option<SettingsLocation>) -> &dyn Any {
1242        if let Some(SettingsLocation { worktree_id, path }) = path {
1243            for (settings_root_id, settings_path, value) in self.local_values.iter().rev() {
1244                if worktree_id == *settings_root_id && path.starts_with(settings_path) {
1245                    return value;
1246                }
1247            }
1248        }
1249        self.global_value
1250            .as_ref()
1251            .unwrap_or_else(|| panic!("no default value for setting {}", self.setting_type_name()))
1252    }
1253
1254    fn set_global_value(&mut self, value: Box<dyn Any>) {
1255        self.global_value = Some(*value.downcast().unwrap());
1256    }
1257
1258    fn set_local_value(&mut self, root_id: WorktreeId, path: Arc<Path>, value: Box<dyn Any>) {
1259        let value = *value.downcast().unwrap();
1260        match self
1261            .local_values
1262            .binary_search_by_key(&(root_id, &path), |e| (e.0, &e.1))
1263        {
1264            Ok(ix) => self.local_values[ix].2 = value,
1265            Err(ix) => self.local_values.insert(ix, (root_id, path, value)),
1266        }
1267    }
1268
1269    fn json_schema(
1270        &self,
1271        generator: &mut SchemaGenerator,
1272        params: &SettingsJsonSchemaParams,
1273        cx: &App,
1274    ) -> RootSchema {
1275        T::json_schema(generator, params, cx)
1276    }
1277
1278    fn edits_for_update(
1279        &self,
1280        raw_settings: &serde_json::Value,
1281        tab_size: usize,
1282        vscode_settings: &VsCodeSettings,
1283        text: &mut String,
1284        edits: &mut Vec<(Range<usize>, String)>,
1285    ) {
1286        let (key, deserialized_setting) = self.deserialize_setting_with_key(raw_settings);
1287        let old_content = match deserialized_setting {
1288            Ok(content) => content.0.downcast::<T::FileContent>().unwrap(),
1289            Err(_) => Box::<<T as Settings>::FileContent>::default(),
1290        };
1291        let mut new_content = old_content.clone();
1292        T::import_from_vscode(vscode_settings, &mut new_content);
1293
1294        let old_value = serde_json::to_value(&old_content).unwrap();
1295        let new_value = serde_json::to_value(new_content).unwrap();
1296
1297        let mut key_path = Vec::new();
1298        if let Some(key) = key {
1299            key_path.push(key);
1300        }
1301
1302        update_value_in_json_text(
1303            text,
1304            &mut key_path,
1305            tab_size,
1306            &old_value,
1307            &new_value,
1308            T::PRESERVED_KEYS.unwrap_or_default(),
1309            edits,
1310        );
1311    }
1312}
1313
1314fn update_value_in_json_text<'a>(
1315    text: &mut String,
1316    key_path: &mut Vec<&'a str>,
1317    tab_size: usize,
1318    old_value: &'a Value,
1319    new_value: &'a Value,
1320    preserved_keys: &[&str],
1321    edits: &mut Vec<(Range<usize>, String)>,
1322) {
1323    // If the old and new values are both objects, then compare them key by key,
1324    // preserving the comments and formatting of the unchanged parts. Otherwise,
1325    // replace the old value with the new value.
1326    if let (Value::Object(old_object), Value::Object(new_object)) = (old_value, new_value) {
1327        for (key, old_sub_value) in old_object.iter() {
1328            key_path.push(key);
1329            let new_sub_value = new_object.get(key).unwrap_or(&Value::Null);
1330            update_value_in_json_text(
1331                text,
1332                key_path,
1333                tab_size,
1334                old_sub_value,
1335                new_sub_value,
1336                preserved_keys,
1337                edits,
1338            );
1339            key_path.pop();
1340        }
1341        for (key, new_sub_value) in new_object.iter() {
1342            key_path.push(key);
1343            if !old_object.contains_key(key) {
1344                update_value_in_json_text(
1345                    text,
1346                    key_path,
1347                    tab_size,
1348                    &Value::Null,
1349                    new_sub_value,
1350                    preserved_keys,
1351                    edits,
1352                );
1353            }
1354            key_path.pop();
1355        }
1356    } else if key_path
1357        .last()
1358        .map_or(false, |key| preserved_keys.contains(key))
1359        || old_value != new_value
1360    {
1361        let mut new_value = new_value.clone();
1362        if let Some(new_object) = new_value.as_object_mut() {
1363            new_object.retain(|_, v| !v.is_null());
1364        }
1365        let (range, replacement) = replace_value_in_json_text(text, key_path, tab_size, &new_value);
1366        text.replace_range(range.clone(), &replacement);
1367        edits.push((range, replacement));
1368    }
1369}
1370
1371fn replace_value_in_json_text(
1372    text: &str,
1373    key_path: &[&str],
1374    tab_size: usize,
1375    new_value: &Value,
1376) -> (Range<usize>, String) {
1377    static PAIR_QUERY: LazyLock<Query> = LazyLock::new(|| {
1378        Query::new(
1379            &tree_sitter_json::LANGUAGE.into(),
1380            "(pair key: (string) @key value: (_) @value)",
1381        )
1382        .expect("Failed to create PAIR_QUERY")
1383    });
1384
1385    let mut parser = tree_sitter::Parser::new();
1386    parser
1387        .set_language(&tree_sitter_json::LANGUAGE.into())
1388        .unwrap();
1389    let syntax_tree = parser.parse(text, None).unwrap();
1390
1391    let mut cursor = tree_sitter::QueryCursor::new();
1392
1393    let mut depth = 0;
1394    let mut last_value_range = 0..0;
1395    let mut first_key_start = None;
1396    let mut existing_value_range = 0..text.len();
1397    let mut matches = cursor.matches(&PAIR_QUERY, syntax_tree.root_node(), text.as_bytes());
1398    while let Some(mat) = matches.next() {
1399        if mat.captures.len() != 2 {
1400            continue;
1401        }
1402
1403        let key_range = mat.captures[0].node.byte_range();
1404        let value_range = mat.captures[1].node.byte_range();
1405
1406        // Don't enter sub objects until we find an exact
1407        // match for the current keypath
1408        if last_value_range.contains_inclusive(&value_range) {
1409            continue;
1410        }
1411
1412        last_value_range = value_range.clone();
1413
1414        if key_range.start > existing_value_range.end {
1415            break;
1416        }
1417
1418        first_key_start.get_or_insert(key_range.start);
1419
1420        let found_key = text
1421            .get(key_range.clone())
1422            .map(|key_text| {
1423                depth < key_path.len() && key_text == format!("\"{}\"", key_path[depth])
1424            })
1425            .unwrap_or(false);
1426
1427        if found_key {
1428            existing_value_range = value_range;
1429            // Reset last value range when increasing in depth
1430            last_value_range = existing_value_range.start..existing_value_range.start;
1431            depth += 1;
1432
1433            if depth == key_path.len() {
1434                break;
1435            }
1436
1437            first_key_start = None;
1438        }
1439    }
1440
1441    // We found the exact key we want, insert the new value
1442    if depth == key_path.len() {
1443        let new_val = to_pretty_json(&new_value, tab_size, tab_size * depth);
1444        (existing_value_range, new_val)
1445    } else {
1446        // We have key paths, construct the sub objects
1447        let new_key = key_path[depth];
1448
1449        // We don't have the key, construct the nested objects
1450        let mut new_value = serde_json::to_value(new_value).unwrap();
1451        for key in key_path[(depth + 1)..].iter().rev() {
1452            new_value = serde_json::json!({ key.to_string(): new_value });
1453        }
1454
1455        if let Some(first_key_start) = first_key_start {
1456            let mut row = 0;
1457            let mut column = 0;
1458            for (ix, char) in text.char_indices() {
1459                if ix == first_key_start {
1460                    break;
1461                }
1462                if char == '\n' {
1463                    row += 1;
1464                    column = 0;
1465                } else {
1466                    column += char.len_utf8();
1467                }
1468            }
1469
1470            if row > 0 {
1471                // depth is 0 based, but division needs to be 1 based.
1472                let new_val = to_pretty_json(&new_value, column / (depth + 1), column);
1473                let space = ' ';
1474                let content = format!("\"{new_key}\": {new_val},\n{space:width$}", width = column);
1475                (first_key_start..first_key_start, content)
1476            } else {
1477                let new_val = serde_json::to_string(&new_value).unwrap();
1478                let mut content = format!(r#""{new_key}": {new_val},"#);
1479                content.push(' ');
1480                (first_key_start..first_key_start, content)
1481            }
1482        } else {
1483            new_value = serde_json::json!({ new_key.to_string(): new_value });
1484            let indent_prefix_len = 4 * depth;
1485            let mut new_val = to_pretty_json(&new_value, 4, indent_prefix_len);
1486            if depth == 0 {
1487                new_val.push('\n');
1488            }
1489
1490            (existing_value_range, new_val)
1491        }
1492    }
1493}
1494
1495fn to_pretty_json(value: &impl Serialize, indent_size: usize, indent_prefix_len: usize) -> String {
1496    const SPACES: [u8; 32] = [b' '; 32];
1497
1498    debug_assert!(indent_size <= SPACES.len());
1499    debug_assert!(indent_prefix_len <= SPACES.len());
1500
1501    let mut output = Vec::new();
1502    let mut ser = serde_json::Serializer::with_formatter(
1503        &mut output,
1504        serde_json::ser::PrettyFormatter::with_indent(&SPACES[0..indent_size.min(SPACES.len())]),
1505    );
1506
1507    value.serialize(&mut ser).unwrap();
1508    let text = String::from_utf8(output).unwrap();
1509
1510    let mut adjusted_text = String::new();
1511    for (i, line) in text.split('\n').enumerate() {
1512        if i > 0 {
1513            adjusted_text.push_str(str::from_utf8(&SPACES[0..indent_prefix_len]).unwrap());
1514        }
1515        adjusted_text.push_str(line);
1516        adjusted_text.push('\n');
1517    }
1518    adjusted_text.pop();
1519    adjusted_text
1520}
1521
1522pub fn parse_json_with_comments<T: DeserializeOwned>(content: &str) -> Result<T> {
1523    Ok(serde_json_lenient::from_str(content)?)
1524}
1525
1526#[cfg(test)]
1527mod tests {
1528    use super::*;
1529    use serde_derive::Deserialize;
1530    use unindent::Unindent;
1531
1532    #[gpui::test]
1533    fn test_settings_store_basic(cx: &mut App) {
1534        let mut store = SettingsStore::new(cx);
1535        store.register_setting::<UserSettings>(cx);
1536        store.register_setting::<TurboSetting>(cx);
1537        store.register_setting::<MultiKeySettings>(cx);
1538        store
1539            .set_default_settings(
1540                r#"{
1541                    "turbo": false,
1542                    "user": {
1543                        "name": "John Doe",
1544                        "age": 30,
1545                        "staff": false
1546                    }
1547                }"#,
1548                cx,
1549            )
1550            .unwrap();
1551
1552        assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(false));
1553        assert_eq!(
1554            store.get::<UserSettings>(None),
1555            &UserSettings {
1556                name: "John Doe".to_string(),
1557                age: 30,
1558                staff: false,
1559            }
1560        );
1561        assert_eq!(
1562            store.get::<MultiKeySettings>(None),
1563            &MultiKeySettings {
1564                key1: String::new(),
1565                key2: String::new(),
1566            }
1567        );
1568
1569        store
1570            .set_user_settings(
1571                r#"{
1572                    "turbo": true,
1573                    "user": { "age": 31 },
1574                    "key1": "a"
1575                }"#,
1576                cx,
1577            )
1578            .unwrap();
1579
1580        assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(true));
1581        assert_eq!(
1582            store.get::<UserSettings>(None),
1583            &UserSettings {
1584                name: "John Doe".to_string(),
1585                age: 31,
1586                staff: false
1587            }
1588        );
1589
1590        store
1591            .set_local_settings(
1592                WorktreeId::from_usize(1),
1593                Path::new("/root1").into(),
1594                LocalSettingsKind::Settings,
1595                Some(r#"{ "user": { "staff": true } }"#),
1596                cx,
1597            )
1598            .unwrap();
1599        store
1600            .set_local_settings(
1601                WorktreeId::from_usize(1),
1602                Path::new("/root1/subdir").into(),
1603                LocalSettingsKind::Settings,
1604                Some(r#"{ "user": { "name": "Jane Doe" } }"#),
1605                cx,
1606            )
1607            .unwrap();
1608
1609        store
1610            .set_local_settings(
1611                WorktreeId::from_usize(1),
1612                Path::new("/root2").into(),
1613                LocalSettingsKind::Settings,
1614                Some(r#"{ "user": { "age": 42 }, "key2": "b" }"#),
1615                cx,
1616            )
1617            .unwrap();
1618
1619        assert_eq!(
1620            store.get::<UserSettings>(Some(SettingsLocation {
1621                worktree_id: WorktreeId::from_usize(1),
1622                path: Path::new("/root1/something"),
1623            })),
1624            &UserSettings {
1625                name: "John Doe".to_string(),
1626                age: 31,
1627                staff: true
1628            }
1629        );
1630        assert_eq!(
1631            store.get::<UserSettings>(Some(SettingsLocation {
1632                worktree_id: WorktreeId::from_usize(1),
1633                path: Path::new("/root1/subdir/something")
1634            })),
1635            &UserSettings {
1636                name: "Jane Doe".to_string(),
1637                age: 31,
1638                staff: true
1639            }
1640        );
1641        assert_eq!(
1642            store.get::<UserSettings>(Some(SettingsLocation {
1643                worktree_id: WorktreeId::from_usize(1),
1644                path: Path::new("/root2/something")
1645            })),
1646            &UserSettings {
1647                name: "John Doe".to_string(),
1648                age: 42,
1649                staff: false
1650            }
1651        );
1652        assert_eq!(
1653            store.get::<MultiKeySettings>(Some(SettingsLocation {
1654                worktree_id: WorktreeId::from_usize(1),
1655                path: Path::new("/root2/something")
1656            })),
1657            &MultiKeySettings {
1658                key1: "a".to_string(),
1659                key2: "b".to_string(),
1660            }
1661        );
1662    }
1663
1664    #[gpui::test]
1665    fn test_setting_store_assign_json_before_register(cx: &mut App) {
1666        let mut store = SettingsStore::new(cx);
1667        store
1668            .set_default_settings(
1669                r#"{
1670                    "turbo": true,
1671                    "user": {
1672                        "name": "John Doe",
1673                        "age": 30,
1674                        "staff": false
1675                    },
1676                    "key1": "x"
1677                }"#,
1678                cx,
1679            )
1680            .unwrap();
1681        store
1682            .set_user_settings(r#"{ "turbo": false }"#, cx)
1683            .unwrap();
1684        store.register_setting::<UserSettings>(cx);
1685        store.register_setting::<TurboSetting>(cx);
1686
1687        assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(false));
1688        assert_eq!(
1689            store.get::<UserSettings>(None),
1690            &UserSettings {
1691                name: "John Doe".to_string(),
1692                age: 30,
1693                staff: false,
1694            }
1695        );
1696
1697        store.register_setting::<MultiKeySettings>(cx);
1698        assert_eq!(
1699            store.get::<MultiKeySettings>(None),
1700            &MultiKeySettings {
1701                key1: "x".into(),
1702                key2: String::new(),
1703            }
1704        );
1705    }
1706
1707    #[gpui::test]
1708    fn test_setting_store_update(cx: &mut App) {
1709        let mut store = SettingsStore::new(cx);
1710        store.register_setting::<MultiKeySettings>(cx);
1711        store.register_setting::<UserSettings>(cx);
1712        store.register_setting::<LanguageSettings>(cx);
1713
1714        // entries added and updated
1715        check_settings_update::<LanguageSettings>(
1716            &mut store,
1717            r#"{
1718                "languages": {
1719                    "JSON": {
1720                        "language_setting_1": true
1721                    }
1722                }
1723            }"#
1724            .unindent(),
1725            |settings| {
1726                settings
1727                    .languages
1728                    .get_mut("JSON")
1729                    .unwrap()
1730                    .language_setting_1 = Some(false);
1731                settings.languages.insert(
1732                    "Rust".into(),
1733                    LanguageSettingEntry {
1734                        language_setting_2: Some(true),
1735                        ..Default::default()
1736                    },
1737                );
1738            },
1739            r#"{
1740                "languages": {
1741                    "Rust": {
1742                        "language_setting_2": true
1743                    },
1744                    "JSON": {
1745                        "language_setting_1": false
1746                    }
1747                }
1748            }"#
1749            .unindent(),
1750            cx,
1751        );
1752
1753        // weird formatting
1754        check_settings_update::<UserSettings>(
1755            &mut store,
1756            r#"{
1757                "user":   { "age": 36, "name": "Max", "staff": true }
1758            }"#
1759            .unindent(),
1760            |settings| settings.age = Some(37),
1761            r#"{
1762                "user":   { "age": 37, "name": "Max", "staff": true }
1763            }"#
1764            .unindent(),
1765            cx,
1766        );
1767
1768        // single-line formatting, other keys
1769        check_settings_update::<MultiKeySettings>(
1770            &mut store,
1771            r#"{ "one": 1, "two": 2 }"#.unindent(),
1772            |settings| settings.key1 = Some("x".into()),
1773            r#"{ "key1": "x", "one": 1, "two": 2 }"#.unindent(),
1774            cx,
1775        );
1776
1777        // empty object
1778        check_settings_update::<UserSettings>(
1779            &mut store,
1780            r#"{
1781                "user": {}
1782            }"#
1783            .unindent(),
1784            |settings| settings.age = Some(37),
1785            r#"{
1786                "user": {
1787                    "age": 37
1788                }
1789            }"#
1790            .unindent(),
1791            cx,
1792        );
1793
1794        // no content
1795        check_settings_update::<UserSettings>(
1796            &mut store,
1797            r#""#.unindent(),
1798            |settings| settings.age = Some(37),
1799            r#"{
1800                "user": {
1801                    "age": 37
1802                }
1803            }
1804            "#
1805            .unindent(),
1806            cx,
1807        );
1808
1809        check_settings_update::<UserSettings>(
1810            &mut store,
1811            r#"{
1812            }
1813            "#
1814            .unindent(),
1815            |settings| settings.age = Some(37),
1816            r#"{
1817                "user": {
1818                    "age": 37
1819                }
1820            }
1821            "#
1822            .unindent(),
1823            cx,
1824        );
1825    }
1826
1827    #[gpui::test]
1828    fn test_vscode_import(cx: &mut App) {
1829        let mut store = SettingsStore::new(cx);
1830        store.register_setting::<UserSettings>(cx);
1831        store.register_setting::<JournalSettings>(cx);
1832        store.register_setting::<LanguageSettings>(cx);
1833        store.register_setting::<MultiKeySettings>(cx);
1834
1835        // create settings that werent present
1836        check_vscode_import(
1837            &mut store,
1838            r#"{
1839            }
1840            "#
1841            .unindent(),
1842            r#" { "user.age": 37 } "#.to_owned(),
1843            r#"{
1844                "user": {
1845                    "age": 37
1846                }
1847            }
1848            "#
1849            .unindent(),
1850            cx,
1851        );
1852
1853        // persist settings that were present
1854        check_vscode_import(
1855            &mut store,
1856            r#"{
1857                "user": {
1858                    "staff": true,
1859                    "age": 37
1860                }
1861            }
1862            "#
1863            .unindent(),
1864            r#"{ "user.age": 42 }"#.to_owned(),
1865            r#"{
1866                "user": {
1867                    "staff": true,
1868                    "age": 42
1869                }
1870            }
1871            "#
1872            .unindent(),
1873            cx,
1874        );
1875
1876        // don't clobber settings that aren't present in vscode
1877        check_vscode_import(
1878            &mut store,
1879            r#"{
1880                "user": {
1881                    "staff": true,
1882                    "age": 37
1883                }
1884            }
1885            "#
1886            .unindent(),
1887            r#"{}"#.to_owned(),
1888            r#"{
1889                "user": {
1890                    "staff": true,
1891                    "age": 37
1892                }
1893            }
1894            "#
1895            .unindent(),
1896            cx,
1897        );
1898
1899        // custom enum
1900        check_vscode_import(
1901            &mut store,
1902            r#"{
1903                "journal": {
1904                "hour_format": "hour12"
1905                }
1906            }
1907            "#
1908            .unindent(),
1909            r#"{ "time_format": "24" }"#.to_owned(),
1910            r#"{
1911                "journal": {
1912                "hour_format": "hour24"
1913                }
1914            }
1915            "#
1916            .unindent(),
1917            cx,
1918        );
1919
1920        // Multiple keys for one setting
1921        check_vscode_import(
1922            &mut store,
1923            r#"{
1924                "key1": "value"
1925            }
1926            "#
1927            .unindent(),
1928            r#"{
1929                "key_1_first": "hello",
1930                "key_1_second": "world"
1931            }"#
1932            .to_owned(),
1933            r#"{
1934                "key1": "hello world"
1935            }
1936            "#
1937            .unindent(),
1938            cx,
1939        );
1940
1941        // Merging lists together entries added and updated
1942        check_vscode_import(
1943            &mut store,
1944            r#"{
1945                "languages": {
1946                    "JSON": {
1947                        "language_setting_1": true
1948                    },
1949                    "Rust": {
1950                        "language_setting_2": true
1951                    }
1952                }
1953            }"#
1954            .unindent(),
1955            r#"{
1956                "vscode_languages": [
1957                    {
1958                        "name": "JavaScript",
1959                        "language_setting_1": true
1960                    },
1961                    {
1962                        "name": "Rust",
1963                        "language_setting_2": false
1964                    }
1965                ]
1966            }"#
1967            .to_owned(),
1968            r#"{
1969                "languages": {
1970                    "JavaScript": {
1971                        "language_setting_1": true
1972                    },
1973                    "JSON": {
1974                        "language_setting_1": true
1975                    },
1976                    "Rust": {
1977                        "language_setting_2": false
1978                    }
1979                }
1980            }"#
1981            .unindent(),
1982            cx,
1983        );
1984    }
1985
1986    fn check_settings_update<T: Settings>(
1987        store: &mut SettingsStore,
1988        old_json: String,
1989        update: fn(&mut T::FileContent),
1990        expected_new_json: String,
1991        cx: &mut App,
1992    ) {
1993        store.set_user_settings(&old_json, cx).ok();
1994        let edits = store.edits_for_update::<T>(&old_json, update);
1995        let mut new_json = old_json;
1996        for (range, replacement) in edits.into_iter() {
1997            new_json.replace_range(range, &replacement);
1998        }
1999        pretty_assertions::assert_eq!(new_json, expected_new_json);
2000    }
2001
2002    fn check_vscode_import(
2003        store: &mut SettingsStore,
2004        old: String,
2005        vscode: String,
2006        expected: String,
2007        cx: &mut App,
2008    ) {
2009        store.set_user_settings(&old, cx).ok();
2010        let new = store.get_vscode_edits(old, &VsCodeSettings::from_str(&vscode).unwrap());
2011        pretty_assertions::assert_eq!(new, expected);
2012    }
2013
2014    #[derive(Debug, PartialEq, Deserialize)]
2015    struct UserSettings {
2016        name: String,
2017        age: u32,
2018        staff: bool,
2019    }
2020
2021    #[derive(Default, Clone, Serialize, Deserialize, JsonSchema)]
2022    #[schemars(deny_unknown_fields)]
2023    struct UserSettingsContent {
2024        name: Option<String>,
2025        age: Option<u32>,
2026        staff: Option<bool>,
2027    }
2028
2029    impl Settings for UserSettings {
2030        const KEY: Option<&'static str> = Some("user");
2031        type FileContent = UserSettingsContent;
2032
2033        fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
2034            sources.json_merge()
2035        }
2036
2037        fn import_from_vscode(vscode: &VsCodeSettings, current: &mut Self::FileContent) {
2038            vscode.u32_setting("user.age", &mut current.age);
2039        }
2040    }
2041
2042    #[derive(Debug, Deserialize, PartialEq)]
2043    struct TurboSetting(bool);
2044
2045    impl Settings for TurboSetting {
2046        const KEY: Option<&'static str> = Some("turbo");
2047        type FileContent = Option<bool>;
2048
2049        fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
2050            sources.json_merge()
2051        }
2052
2053        fn import_from_vscode(_vscode: &VsCodeSettings, _current: &mut Self::FileContent) {}
2054    }
2055
2056    #[derive(Clone, Debug, PartialEq, Deserialize)]
2057    struct MultiKeySettings {
2058        #[serde(default)]
2059        key1: String,
2060        #[serde(default)]
2061        key2: String,
2062    }
2063
2064    #[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
2065    #[schemars(deny_unknown_fields)]
2066    struct MultiKeySettingsJson {
2067        key1: Option<String>,
2068        key2: Option<String>,
2069    }
2070
2071    impl Settings for MultiKeySettings {
2072        const KEY: Option<&'static str> = None;
2073
2074        type FileContent = MultiKeySettingsJson;
2075
2076        fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
2077            sources.json_merge()
2078        }
2079
2080        fn import_from_vscode(vscode: &VsCodeSettings, current: &mut Self::FileContent) {
2081            let first_value = vscode.read_string("key_1_first");
2082            let second_value = vscode.read_string("key_1_second");
2083
2084            if let Some((first, second)) = first_value.zip(second_value) {
2085                current.key1 = Some(format!("{} {}", first, second));
2086            }
2087        }
2088    }
2089
2090    #[derive(Debug, Deserialize)]
2091    struct JournalSettings {
2092        pub path: String,
2093        pub hour_format: HourFormat,
2094    }
2095
2096    #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
2097    #[serde(rename_all = "snake_case")]
2098    enum HourFormat {
2099        Hour12,
2100        Hour24,
2101    }
2102
2103    #[derive(Clone, Default, Debug, Serialize, Deserialize, JsonSchema)]
2104    #[schemars(deny_unknown_fields)]
2105    struct JournalSettingsJson {
2106        pub path: Option<String>,
2107        pub hour_format: Option<HourFormat>,
2108    }
2109
2110    impl Settings for JournalSettings {
2111        const KEY: Option<&'static str> = Some("journal");
2112
2113        type FileContent = JournalSettingsJson;
2114
2115        fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
2116            sources.json_merge()
2117        }
2118
2119        fn import_from_vscode(vscode: &VsCodeSettings, current: &mut Self::FileContent) {
2120            vscode.enum_setting("time_format", &mut current.hour_format, |s| match s {
2121                "12" => Some(HourFormat::Hour12),
2122                "24" => Some(HourFormat::Hour24),
2123                _ => None,
2124            });
2125        }
2126    }
2127
2128    #[gpui::test]
2129    fn test_global_settings(cx: &mut App) {
2130        let mut store = SettingsStore::new(cx);
2131        store.register_setting::<UserSettings>(cx);
2132        store
2133            .set_default_settings(
2134                r#"{
2135                    "user": {
2136                        "name": "John Doe",
2137                        "age": 30,
2138                        "staff": false
2139                    }
2140                }"#,
2141                cx,
2142            )
2143            .unwrap();
2144
2145        // Set global settings - these should override defaults but not user settings
2146        store
2147            .set_global_settings(
2148                r#"{
2149                    "user": {
2150                        "name": "Global User",
2151                        "age": 35,
2152                        "staff": true
2153                    }
2154                }"#,
2155                cx,
2156            )
2157            .unwrap();
2158
2159        // Before user settings, global settings should apply
2160        assert_eq!(
2161            store.get::<UserSettings>(None),
2162            &UserSettings {
2163                name: "Global User".to_string(),
2164                age: 35,
2165                staff: true,
2166            }
2167        );
2168
2169        // Set user settings - these should override both defaults and global
2170        store
2171            .set_user_settings(
2172                r#"{
2173                    "user": {
2174                        "age": 40
2175                    }
2176                }"#,
2177                cx,
2178            )
2179            .unwrap();
2180
2181        // User settings should override global settings
2182        assert_eq!(
2183            store.get::<UserSettings>(None),
2184            &UserSettings {
2185                name: "Global User".to_string(), // Name from global settings
2186                age: 40,                         // Age from user settings
2187                staff: true,                     // Staff from global settings
2188            }
2189        );
2190    }
2191
2192    #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
2193    struct LanguageSettings {
2194        #[serde(default)]
2195        languages: HashMap<String, LanguageSettingEntry>,
2196    }
2197
2198    #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
2199    #[schemars(deny_unknown_fields)]
2200    struct LanguageSettingEntry {
2201        language_setting_1: Option<bool>,
2202        language_setting_2: Option<bool>,
2203    }
2204
2205    impl Settings for LanguageSettings {
2206        const KEY: Option<&'static str> = None;
2207
2208        type FileContent = Self;
2209
2210        fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
2211            sources.json_merge()
2212        }
2213
2214        fn import_from_vscode(vscode: &VsCodeSettings, current: &mut Self::FileContent) {
2215            current.languages.extend(
2216                vscode
2217                    .read_value("vscode_languages")
2218                    .and_then(|value| value.as_array())
2219                    .map(|languages| {
2220                        languages
2221                            .iter()
2222                            .filter_map(|value| value.as_object())
2223                            .filter_map(|item| {
2224                                let mut rest = item.clone();
2225                                let name = rest.remove("name")?.as_str()?.to_string();
2226                                let entry = serde_json::from_value::<LanguageSettingEntry>(
2227                                    serde_json::Value::Object(rest),
2228                                )
2229                                .ok()?;
2230
2231                                Some((name, entry))
2232                            })
2233                    })
2234                    .into_iter()
2235                    .flatten(),
2236            );
2237        }
2238    }
2239}