settings_store.rs

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