settings_store.rs

   1use anyhow::{anyhow, Context, Result};
   2use collections::{btree_map, hash_map, BTreeMap, HashMap};
   3use fs::Fs;
   4use futures::{channel::mpsc, future::LocalBoxFuture, FutureExt, StreamExt};
   5use gpui::{AppContext, AsyncAppContext, BorrowAppContext, Global, Task, UpdateGlobal};
   6use paths::local_settings_file_relative_path;
   7use schemars::{gen::SchemaGenerator, schema::RootSchema, JsonSchema};
   8use serde::{de::DeserializeOwned, Deserialize as _, Serialize};
   9use smallvec::SmallVec;
  10use std::{
  11    any::{type_name, Any, TypeId},
  12    fmt::Debug,
  13    ops::Range,
  14    path::{Path, PathBuf},
  15    str,
  16    sync::{Arc, LazyLock},
  17};
  18use tree_sitter::Query;
  19use util::{merge_non_null_json_value_into, RangeExt, ResultExt as _};
  20
  21use crate::{SettingsJsonSchemaParams, WorktreeId};
  22
  23/// A value that can be defined as a user setting.
  24///
  25/// Settings can be loaded from a combination of multiple JSON files.
  26pub trait Settings: 'static + Send + Sync {
  27    /// The name of a key within the JSON file from which this setting should
  28    /// be deserialized. If this is `None`, then the setting will be deserialized
  29    /// from the root object.
  30    const KEY: Option<&'static str>;
  31
  32    /// The name of the keys in the [`FileContent`] that should always be written to
  33    /// a settings file, even if their value matches the default value.
  34    ///
  35    /// This is useful for tagged [`FileContent`]s where the tag is a "version" field
  36    /// that should always be persisted, even if the current user settings match the
  37    /// current version of the settings.
  38    const PRESERVED_KEYS: Option<&'static [&'static str]> = None;
  39
  40    /// The type that is stored in an individual JSON file.
  41    type FileContent: Clone + Default + Serialize + DeserializeOwned + JsonSchema;
  42
  43    /// The logic for combining together values from one or more JSON files into the
  44    /// final value for this setting.
  45    fn load(sources: SettingsSources<Self::FileContent>, cx: &mut AppContext) -> Result<Self>
  46    where
  47        Self: Sized;
  48
  49    fn json_schema(
  50        generator: &mut SchemaGenerator,
  51        _: &SettingsJsonSchemaParams,
  52        _: &AppContext,
  53    ) -> RootSchema {
  54        generator.root_schema_for::<Self::FileContent>()
  55    }
  56
  57    fn missing_default() -> anyhow::Error {
  58        anyhow::anyhow!("missing default")
  59    }
  60
  61    fn register(cx: &mut AppContext)
  62    where
  63        Self: Sized,
  64    {
  65        SettingsStore::update_global(cx, |store, cx| {
  66            store.register_setting::<Self>(cx);
  67        });
  68    }
  69
  70    #[track_caller]
  71    fn get<'a>(path: Option<SettingsLocation>, cx: &'a AppContext) -> &'a Self
  72    where
  73        Self: Sized,
  74    {
  75        cx.global::<SettingsStore>().get(path)
  76    }
  77
  78    #[track_caller]
  79    fn get_global(cx: &AppContext) -> &Self
  80    where
  81        Self: Sized,
  82    {
  83        cx.global::<SettingsStore>().get(None)
  84    }
  85
  86    #[track_caller]
  87    fn try_read_global<R>(cx: &AsyncAppContext, f: impl FnOnce(&Self) -> R) -> Option<R>
  88    where
  89        Self: Sized,
  90    {
  91        cx.try_read_global(|s: &SettingsStore, _| f(s.get(None)))
  92    }
  93
  94    #[track_caller]
  95    fn override_global(settings: Self, cx: &mut AppContext)
  96    where
  97        Self: Sized,
  98    {
  99        cx.global_mut::<SettingsStore>().override_global(settings)
 100    }
 101}
 102
 103#[derive(Clone, Copy, Debug)]
 104pub struct SettingsSources<'a, T> {
 105    /// The default Zed settings.
 106    pub default: &'a T,
 107    /// Settings provided by extensions.
 108    pub extensions: Option<&'a T>,
 109    /// The user settings.
 110    pub user: Option<&'a T>,
 111    /// The user settings for the current release channel.
 112    pub release_channel: Option<&'a T>,
 113    /// The server's settings.
 114    pub server: Option<&'a T>,
 115    /// The project settings, ordered from least specific to most specific.
 116    pub project: &'a [&'a T],
 117}
 118
 119impl<'a, T: Serialize> SettingsSources<'a, T> {
 120    /// Returns an iterator over the default settings as well as all settings customizations.
 121    pub fn defaults_and_customizations(&self) -> impl Iterator<Item = &T> {
 122        [self.default].into_iter().chain(self.customizations())
 123    }
 124
 125    /// Returns an iterator over all of the settings customizations.
 126    pub fn customizations(&self) -> impl Iterator<Item = &T> {
 127        self.extensions
 128            .into_iter()
 129            .chain(self.user)
 130            .chain(self.release_channel)
 131            .chain(self.server)
 132            .chain(self.project.iter().copied())
 133    }
 134
 135    /// Returns the settings after performing a JSON merge of the provided customizations.
 136    ///
 137    /// Customizations later in the iterator win out over the earlier ones.
 138    pub fn json_merge_with<O: DeserializeOwned>(
 139        customizations: impl Iterator<Item = &'a T>,
 140    ) -> Result<O> {
 141        let mut merged = serde_json::Value::Null;
 142        for value in customizations {
 143            merge_non_null_json_value_into(serde_json::to_value(value).unwrap(), &mut merged);
 144        }
 145        Ok(serde_json::from_value(merged)?)
 146    }
 147
 148    /// Returns the settings after performing a JSON merge of the customizations into the
 149    /// default settings.
 150    ///
 151    /// More-specific customizations win out over the less-specific ones.
 152    pub fn json_merge<O: DeserializeOwned>(&'a self) -> Result<O> {
 153        Self::json_merge_with(self.defaults_and_customizations())
 154    }
 155}
 156
 157#[derive(Clone, Copy, Debug)]
 158pub struct SettingsLocation<'a> {
 159    pub worktree_id: WorktreeId,
 160    pub path: &'a Path,
 161}
 162
 163/// A set of strongly-typed setting values defined via multiple config files.
 164pub struct SettingsStore {
 165    setting_values: HashMap<TypeId, Box<dyn AnySettingValue>>,
 166    raw_default_settings: serde_json::Value,
 167    raw_user_settings: serde_json::Value,
 168    raw_server_settings: Option<serde_json::Value>,
 169    raw_extension_settings: serde_json::Value,
 170    raw_local_settings:
 171        BTreeMap<(WorktreeId, Arc<Path>), HashMap<LocalSettingsKind, serde_json::Value>>,
 172    tab_size_callback: Option<(
 173        TypeId,
 174        Box<dyn Fn(&dyn Any) -> Option<usize> + Send + Sync + 'static>,
 175    )>,
 176    _setting_file_updates: Task<()>,
 177    setting_file_updates_tx: mpsc::UnboundedSender<
 178        Box<dyn FnOnce(AsyncAppContext) -> LocalBoxFuture<'static, Result<()>>>,
 179    >,
 180}
 181
 182#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
 183pub enum LocalSettingsKind {
 184    Settings,
 185    Tasks,
 186    Editorconfig,
 187}
 188
 189impl Global for SettingsStore {}
 190
 191#[derive(Debug)]
 192struct SettingValue<T> {
 193    global_value: Option<T>,
 194    local_values: Vec<(WorktreeId, Arc<Path>, T)>,
 195}
 196
 197trait AnySettingValue: 'static + Send + Sync {
 198    fn key(&self) -> Option<&'static str>;
 199    fn setting_type_name(&self) -> &'static str;
 200    fn deserialize_setting(&self, json: &serde_json::Value) -> Result<DeserializedSetting>;
 201    fn load_setting(
 202        &self,
 203        sources: SettingsSources<DeserializedSetting>,
 204        cx: &mut AppContext,
 205    ) -> Result<Box<dyn Any>>;
 206    fn value_for_path(&self, path: Option<SettingsLocation>) -> &dyn Any;
 207    fn set_global_value(&mut self, value: Box<dyn Any>);
 208    fn set_local_value(&mut self, root_id: WorktreeId, path: Arc<Path>, value: Box<dyn Any>);
 209    fn json_schema(
 210        &self,
 211        generator: &mut SchemaGenerator,
 212        _: &SettingsJsonSchemaParams,
 213        cx: &AppContext,
 214    ) -> RootSchema;
 215}
 216
 217struct DeserializedSetting(Box<dyn Any>);
 218
 219impl SettingsStore {
 220    pub fn new(cx: &AppContext) -> Self {
 221        let (setting_file_updates_tx, mut setting_file_updates_rx) = mpsc::unbounded();
 222        Self {
 223            setting_values: Default::default(),
 224            raw_default_settings: serde_json::json!({}),
 225            raw_user_settings: serde_json::json!({}),
 226            raw_server_settings: None,
 227            raw_extension_settings: serde_json::json!({}),
 228            raw_local_settings: Default::default(),
 229            tab_size_callback: Default::default(),
 230            setting_file_updates_tx,
 231            _setting_file_updates: cx.spawn(|cx| async move {
 232                while let Some(setting_file_update) = setting_file_updates_rx.next().await {
 233                    (setting_file_update)(cx.clone()).await.log_err();
 234                }
 235            }),
 236        }
 237    }
 238
 239    pub fn update<C, R>(cx: &mut C, f: impl FnOnce(&mut Self, &mut C) -> R) -> R
 240    where
 241        C: BorrowAppContext,
 242    {
 243        cx.update_global(f)
 244    }
 245
 246    /// Add a new type of setting to the store.
 247    pub fn register_setting<T: Settings>(&mut self, cx: &mut AppContext) {
 248        let setting_type_id = TypeId::of::<T>();
 249        let entry = self.setting_values.entry(setting_type_id);
 250        if matches!(entry, hash_map::Entry::Occupied(_)) {
 251            return;
 252        }
 253
 254        let setting_value = entry.or_insert(Box::new(SettingValue::<T> {
 255            global_value: None,
 256            local_values: Vec::new(),
 257        }));
 258
 259        if let Some(default_settings) = setting_value
 260            .deserialize_setting(&self.raw_default_settings)
 261            .log_err()
 262        {
 263            let user_value = setting_value
 264                .deserialize_setting(&self.raw_user_settings)
 265                .log_err();
 266
 267            let mut release_channel_value = None;
 268            if let Some(release_settings) = &self
 269                .raw_user_settings
 270                .get(release_channel::RELEASE_CHANNEL.dev_name())
 271            {
 272                release_channel_value = setting_value
 273                    .deserialize_setting(release_settings)
 274                    .log_err();
 275            }
 276
 277            let server_value = self
 278                .raw_server_settings
 279                .as_ref()
 280                .and_then(|server_setting| {
 281                    setting_value.deserialize_setting(server_setting).log_err()
 282                });
 283
 284            let extension_value = setting_value
 285                .deserialize_setting(&self.raw_extension_settings)
 286                .log_err();
 287
 288            if let Some(setting) = setting_value
 289                .load_setting(
 290                    SettingsSources {
 291                        default: &default_settings,
 292                        extensions: extension_value.as_ref(),
 293                        user: user_value.as_ref(),
 294                        release_channel: release_channel_value.as_ref(),
 295                        server: server_value.as_ref(),
 296                        project: &[],
 297                    },
 298                    cx,
 299                )
 300                .context("A default setting must be added to the `default.json` file")
 301                .log_err()
 302            {
 303                setting_value.set_global_value(setting);
 304            }
 305        }
 306    }
 307
 308    /// Get the value of a setting.
 309    ///
 310    /// Panics if the given setting type has not been registered, or if there is no
 311    /// value for this setting.
 312    pub fn get<T: Settings>(&self, path: Option<SettingsLocation>) -> &T {
 313        self.setting_values
 314            .get(&TypeId::of::<T>())
 315            .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()))
 316            .value_for_path(path)
 317            .downcast_ref::<T>()
 318            .expect("no default value for setting type")
 319    }
 320
 321    /// Override the global value for a setting.
 322    ///
 323    /// The given value will be overwritten if the user settings file changes.
 324    pub fn override_global<T: Settings>(&mut self, value: T) {
 325        self.setting_values
 326            .get_mut(&TypeId::of::<T>())
 327            .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()))
 328            .set_global_value(Box::new(value))
 329    }
 330
 331    /// Get the user's settings as a raw JSON value.
 332    ///
 333    /// For user-facing functionality use the typed setting interface.
 334    /// (e.g. ProjectSettings::get_global(cx))
 335    pub fn raw_user_settings(&self) -> &serde_json::Value {
 336        &self.raw_user_settings
 337    }
 338
 339    #[cfg(any(test, feature = "test-support"))]
 340    pub fn test(cx: &mut AppContext) -> Self {
 341        let mut this = Self::new(cx);
 342        this.set_default_settings(&crate::test_settings(), cx)
 343            .unwrap();
 344        this.set_user_settings("{}", cx).unwrap();
 345        this
 346    }
 347
 348    /// Updates the value of a setting in the user's global configuration.
 349    ///
 350    /// This is only for tests. Normally, settings are only loaded from
 351    /// JSON files.
 352    #[cfg(any(test, feature = "test-support"))]
 353    pub fn update_user_settings<T: Settings>(
 354        &mut self,
 355        cx: &mut AppContext,
 356        update: impl FnOnce(&mut T::FileContent),
 357    ) {
 358        let old_text = serde_json::to_string(&self.raw_user_settings).unwrap();
 359        let new_text = self.new_text_for_update::<T>(old_text, update);
 360        self.set_user_settings(&new_text, cx).unwrap();
 361    }
 362
 363    async fn load_settings(fs: &Arc<dyn Fs>) -> Result<String> {
 364        match fs.load(paths::settings_file()).await {
 365            result @ Ok(_) => result,
 366            Err(err) => {
 367                if let Some(e) = err.downcast_ref::<std::io::Error>() {
 368                    if e.kind() == std::io::ErrorKind::NotFound {
 369                        return Ok(crate::initial_user_settings_content().to_string());
 370                    }
 371                }
 372                Err(err)
 373            }
 374        }
 375    }
 376
 377    pub fn update_settings_file<T: Settings>(
 378        &self,
 379        fs: Arc<dyn Fs>,
 380        update: impl 'static + Send + FnOnce(&mut T::FileContent, &AppContext),
 381    ) {
 382        self.setting_file_updates_tx
 383            .unbounded_send(Box::new(move |cx: AsyncAppContext| {
 384                async move {
 385                    let old_text = Self::load_settings(&fs).await?;
 386                    let new_text = cx.read_global(|store: &SettingsStore, cx| {
 387                        store.new_text_for_update::<T>(old_text, |content| update(content, cx))
 388                    })?;
 389                    let initial_path = paths::settings_file().as_path();
 390                    if fs.is_file(initial_path).await {
 391                        let resolved_path =
 392                            fs.canonicalize(initial_path).await.with_context(|| {
 393                                format!("Failed to canonicalize settings path {:?}", initial_path)
 394                            })?;
 395
 396                        fs.atomic_write(resolved_path.clone(), new_text)
 397                            .await
 398                            .with_context(|| {
 399                                format!("Failed to write settings to file {:?}", resolved_path)
 400                            })?;
 401                    } else {
 402                        fs.atomic_write(initial_path.to_path_buf(), new_text)
 403                            .await
 404                            .with_context(|| {
 405                                format!("Failed to write settings to file {:?}", initial_path)
 406                            })?;
 407                    }
 408
 409                    anyhow::Ok(())
 410                }
 411                .boxed_local()
 412            }))
 413            .ok();
 414    }
 415
 416    /// Updates the value of a setting in a JSON file, returning the new text
 417    /// for that JSON file.
 418    pub fn new_text_for_update<T: Settings>(
 419        &self,
 420        old_text: String,
 421        update: impl FnOnce(&mut T::FileContent),
 422    ) -> String {
 423        let edits = self.edits_for_update::<T>(&old_text, update);
 424        let mut new_text = old_text;
 425        for (range, replacement) in edits.into_iter() {
 426            new_text.replace_range(range, &replacement);
 427        }
 428        new_text
 429    }
 430
 431    /// Updates the value of a setting in a JSON file, returning a list
 432    /// of edits to apply to the JSON file.
 433    pub fn edits_for_update<T: Settings>(
 434        &self,
 435        text: &str,
 436        update: impl FnOnce(&mut T::FileContent),
 437    ) -> Vec<(Range<usize>, String)> {
 438        let setting_type_id = TypeId::of::<T>();
 439
 440        let preserved_keys = T::PRESERVED_KEYS.unwrap_or_default();
 441
 442        let setting = self
 443            .setting_values
 444            .get(&setting_type_id)
 445            .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()));
 446        let raw_settings = parse_json_with_comments::<serde_json::Value>(text).unwrap_or_default();
 447        let old_content = match setting.deserialize_setting(&raw_settings) {
 448            Ok(content) => content.0.downcast::<T::FileContent>().unwrap(),
 449            Err(_) => Box::<<T as Settings>::FileContent>::default(),
 450        };
 451        let mut new_content = old_content.clone();
 452        update(&mut new_content);
 453
 454        let old_value = serde_json::to_value(&old_content).unwrap();
 455        let new_value = serde_json::to_value(new_content).unwrap();
 456
 457        let mut key_path = Vec::new();
 458        if let Some(key) = T::KEY {
 459            key_path.push(key);
 460        }
 461
 462        let mut edits = Vec::new();
 463        let tab_size = self.json_tab_size();
 464        let mut text = text.to_string();
 465        update_value_in_json_text(
 466            &mut text,
 467            &mut key_path,
 468            tab_size,
 469            &old_value,
 470            &new_value,
 471            preserved_keys,
 472            &mut edits,
 473        );
 474        edits
 475    }
 476
 477    /// Configure the tab sized when updating JSON files.
 478    pub fn set_json_tab_size_callback<T: Settings>(
 479        &mut self,
 480        get_tab_size: fn(&T) -> Option<usize>,
 481    ) {
 482        self.tab_size_callback = Some((
 483            TypeId::of::<T>(),
 484            Box::new(move |value| get_tab_size(value.downcast_ref::<T>().unwrap())),
 485        ));
 486    }
 487
 488    fn json_tab_size(&self) -> usize {
 489        const DEFAULT_JSON_TAB_SIZE: usize = 2;
 490
 491        if let Some((setting_type_id, callback)) = &self.tab_size_callback {
 492            let setting_value = self.setting_values.get(setting_type_id).unwrap();
 493            let value = setting_value.value_for_path(None);
 494            if let Some(value) = callback(value) {
 495                return value;
 496            }
 497        }
 498
 499        DEFAULT_JSON_TAB_SIZE
 500    }
 501
 502    /// Sets the default settings via a JSON string.
 503    ///
 504    /// The string should contain a JSON object with a default value for every setting.
 505    pub fn set_default_settings(
 506        &mut self,
 507        default_settings_content: &str,
 508        cx: &mut AppContext,
 509    ) -> Result<()> {
 510        let settings: serde_json::Value = parse_json_with_comments(default_settings_content)?;
 511        if settings.is_object() {
 512            self.raw_default_settings = settings;
 513            self.recompute_values(None, cx)?;
 514            Ok(())
 515        } else {
 516            Err(anyhow!("settings must be an object"))
 517        }
 518    }
 519
 520    /// Sets the user settings via a JSON string.
 521    pub fn set_user_settings(
 522        &mut self,
 523        user_settings_content: &str,
 524        cx: &mut AppContext,
 525    ) -> Result<()> {
 526        let settings: serde_json::Value = if user_settings_content.is_empty() {
 527            parse_json_with_comments("{}")?
 528        } else {
 529            parse_json_with_comments(user_settings_content)?
 530        };
 531
 532        anyhow::ensure!(settings.is_object(), "settings must be an object");
 533        self.raw_user_settings = settings;
 534        self.recompute_values(None, cx)?;
 535        Ok(())
 536    }
 537
 538    pub fn set_server_settings(
 539        &mut self,
 540        server_settings_content: &str,
 541        cx: &mut AppContext,
 542    ) -> Result<()> {
 543        let settings: Option<serde_json::Value> = if server_settings_content.is_empty() {
 544            None
 545        } else {
 546            parse_json_with_comments(server_settings_content)?
 547        };
 548
 549        anyhow::ensure!(
 550            settings
 551                .as_ref()
 552                .map(|value| value.is_object())
 553                .unwrap_or(true),
 554            "settings must be an object"
 555        );
 556        self.raw_server_settings = settings;
 557        self.recompute_values(None, cx)?;
 558        Ok(())
 559    }
 560
 561    /// Add or remove a set of local settings via a JSON string.
 562    pub fn set_local_settings(
 563        &mut self,
 564        root_id: WorktreeId,
 565        directory_path: Arc<Path>,
 566        kind: LocalSettingsKind,
 567        settings_content: Option<&str>,
 568        cx: &mut AppContext,
 569    ) -> std::result::Result<(), InvalidSettingsError> {
 570        debug_assert!(
 571            kind != LocalSettingsKind::Tasks,
 572            "Attempted to submit tasks into the settings store"
 573        );
 574
 575        let raw_local_settings = self
 576            .raw_local_settings
 577            .entry((root_id, directory_path.clone()))
 578            .or_default();
 579        let changed = if settings_content.is_some_and(|content| !content.is_empty()) {
 580            let new_contents =
 581                parse_json_with_comments(settings_content.unwrap()).map_err(|e| {
 582                    InvalidSettingsError::LocalSettings {
 583                        path: directory_path.join(local_settings_file_relative_path()),
 584                        message: e.to_string(),
 585                    }
 586                })?;
 587            if Some(&new_contents) == raw_local_settings.get(&kind) {
 588                false
 589            } else {
 590                raw_local_settings.insert(kind, new_contents);
 591                true
 592            }
 593        } else {
 594            raw_local_settings.remove(&kind).is_some()
 595        };
 596        if changed {
 597            self.recompute_values(Some((root_id, &directory_path)), cx)?;
 598        }
 599        Ok(())
 600    }
 601
 602    pub fn set_extension_settings<T: Serialize>(
 603        &mut self,
 604        content: T,
 605        cx: &mut AppContext,
 606    ) -> Result<()> {
 607        let settings: serde_json::Value = serde_json::to_value(content)?;
 608        if settings.is_object() {
 609            self.raw_extension_settings = settings;
 610            self.recompute_values(None, cx)?;
 611            Ok(())
 612        } else {
 613            Err(anyhow!("settings must be an object"))
 614        }
 615    }
 616
 617    /// Add or remove a set of local settings via a JSON string.
 618    pub fn clear_local_settings(&mut self, root_id: WorktreeId, cx: &mut AppContext) -> Result<()> {
 619        self.raw_local_settings
 620            .retain(|(worktree_id, _), _| worktree_id != &root_id);
 621        self.recompute_values(Some((root_id, "".as_ref())), cx)?;
 622        Ok(())
 623    }
 624
 625    pub fn local_settings(
 626        &self,
 627        root_id: WorktreeId,
 628    ) -> impl '_ + Iterator<Item = (Arc<Path>, LocalSettingsKind, String)> {
 629        self.raw_local_settings
 630            .range(
 631                (root_id, Path::new("").into())
 632                    ..(
 633                        WorktreeId::from_usize(root_id.to_usize() + 1),
 634                        Path::new("").into(),
 635                    ),
 636            )
 637            .flat_map(|((_, path), content)| {
 638                content.iter().filter_map(|(&kind, raw_content)| {
 639                    let parsed_content = serde_json::to_string(raw_content).log_err()?;
 640                    Some((path.clone(), kind, parsed_content))
 641                })
 642            })
 643    }
 644
 645    pub fn json_schema(
 646        &self,
 647        schema_params: &SettingsJsonSchemaParams,
 648        cx: &AppContext,
 649    ) -> serde_json::Value {
 650        use schemars::{
 651            gen::SchemaSettings,
 652            schema::{Schema, SchemaObject},
 653        };
 654
 655        let settings = SchemaSettings::draft07().with(|settings| {
 656            settings.option_add_null_type = false;
 657        });
 658        let mut generator = SchemaGenerator::new(settings);
 659        let mut combined_schema = RootSchema::default();
 660
 661        for setting_value in self.setting_values.values() {
 662            let setting_schema = setting_value.json_schema(&mut generator, schema_params, cx);
 663            combined_schema
 664                .definitions
 665                .extend(setting_schema.definitions);
 666
 667            let target_schema = if let Some(key) = setting_value.key() {
 668                let key_schema = combined_schema
 669                    .schema
 670                    .object()
 671                    .properties
 672                    .entry(key.to_string())
 673                    .or_insert_with(|| Schema::Object(SchemaObject::default()));
 674                if let Schema::Object(key_schema) = key_schema {
 675                    key_schema
 676                } else {
 677                    continue;
 678                }
 679            } else {
 680                &mut combined_schema.schema
 681            };
 682
 683            merge_schema(target_schema, setting_schema.schema);
 684        }
 685
 686        fn merge_schema(target: &mut SchemaObject, mut source: SchemaObject) {
 687            let source_subschemas = source.subschemas();
 688            let target_subschemas = target.subschemas();
 689            if let Some(all_of) = source_subschemas.all_of.take() {
 690                target_subschemas
 691                    .all_of
 692                    .get_or_insert(Vec::new())
 693                    .extend(all_of);
 694            }
 695            if let Some(any_of) = source_subschemas.any_of.take() {
 696                target_subschemas
 697                    .any_of
 698                    .get_or_insert(Vec::new())
 699                    .extend(any_of);
 700            }
 701            if let Some(one_of) = source_subschemas.one_of.take() {
 702                target_subschemas
 703                    .one_of
 704                    .get_or_insert(Vec::new())
 705                    .extend(one_of);
 706            }
 707
 708            if let Some(source) = source.object {
 709                let target_properties = &mut target.object().properties;
 710                for (key, value) in source.properties {
 711                    match target_properties.entry(key) {
 712                        btree_map::Entry::Vacant(e) => {
 713                            e.insert(value);
 714                        }
 715                        btree_map::Entry::Occupied(e) => {
 716                            if let (Schema::Object(target), Schema::Object(src)) =
 717                                (e.into_mut(), value)
 718                            {
 719                                merge_schema(target, src);
 720                            }
 721                        }
 722                    }
 723                }
 724            }
 725
 726            overwrite(&mut target.instance_type, source.instance_type);
 727            overwrite(&mut target.string, source.string);
 728            overwrite(&mut target.number, source.number);
 729            overwrite(&mut target.reference, source.reference);
 730            overwrite(&mut target.array, source.array);
 731            overwrite(&mut target.enum_values, source.enum_values);
 732
 733            fn overwrite<T>(target: &mut Option<T>, source: Option<T>) {
 734                if let Some(source) = source {
 735                    *target = Some(source);
 736                }
 737            }
 738        }
 739
 740        for release_stage in ["dev", "nightly", "stable", "preview"] {
 741            let schema = combined_schema.schema.clone();
 742            combined_schema
 743                .schema
 744                .object()
 745                .properties
 746                .insert(release_stage.to_string(), schema.into());
 747        }
 748
 749        serde_json::to_value(&combined_schema).unwrap()
 750    }
 751
 752    fn recompute_values(
 753        &mut self,
 754        changed_local_path: Option<(WorktreeId, &Path)>,
 755        cx: &mut AppContext,
 756    ) -> Result<(), InvalidSettingsError> {
 757        // Reload the global and local values for every setting.
 758        let mut project_settings_stack = Vec::<DeserializedSetting>::new();
 759        let mut paths_stack = Vec::<Option<(WorktreeId, &Path)>>::new();
 760        for setting_value in self.setting_values.values_mut() {
 761            let default_settings = setting_value
 762                .deserialize_setting(&self.raw_default_settings)
 763                .map_err(|e| InvalidSettingsError::DefaultSettings {
 764                    message: e.to_string(),
 765                })?;
 766
 767            let extension_settings = setting_value
 768                .deserialize_setting(&self.raw_extension_settings)
 769                .log_err();
 770
 771            let user_settings = match setting_value.deserialize_setting(&self.raw_user_settings) {
 772                Ok(settings) => Some(settings),
 773                Err(error) => {
 774                    return Err(InvalidSettingsError::UserSettings {
 775                        message: error.to_string(),
 776                    });
 777                }
 778            };
 779
 780            let server_settings = self
 781                .raw_server_settings
 782                .as_ref()
 783                .and_then(|setting| setting_value.deserialize_setting(setting).log_err());
 784
 785            let mut release_channel_settings = None;
 786            if let Some(release_settings) = &self
 787                .raw_user_settings
 788                .get(release_channel::RELEASE_CHANNEL.dev_name())
 789            {
 790                if let Some(release_settings) = setting_value
 791                    .deserialize_setting(release_settings)
 792                    .log_err()
 793                {
 794                    release_channel_settings = Some(release_settings);
 795                }
 796            }
 797
 798            // If the global settings file changed, reload the global value for the field.
 799            if changed_local_path.is_none() {
 800                if let Some(value) = setting_value
 801                    .load_setting(
 802                        SettingsSources {
 803                            default: &default_settings,
 804                            extensions: extension_settings.as_ref(),
 805                            user: user_settings.as_ref(),
 806                            release_channel: release_channel_settings.as_ref(),
 807                            server: server_settings.as_ref(),
 808                            project: &[],
 809                        },
 810                        cx,
 811                    )
 812                    .log_err()
 813                {
 814                    setting_value.set_global_value(value);
 815                }
 816            }
 817
 818            // Reload the local values for the setting.
 819            paths_stack.clear();
 820            project_settings_stack.clear();
 821            for ((root_id, directory_path), local_settings) in &self.raw_local_settings {
 822                if let Some(local_settings) = local_settings.get(&LocalSettingsKind::Settings) {
 823                    // Build a stack of all of the local values for that setting.
 824                    while let Some(prev_entry) = paths_stack.last() {
 825                        if let Some((prev_root_id, prev_path)) = prev_entry {
 826                            if root_id != prev_root_id || !directory_path.starts_with(prev_path) {
 827                                paths_stack.pop();
 828                                project_settings_stack.pop();
 829                                continue;
 830                            }
 831                        }
 832                        break;
 833                    }
 834
 835                    match setting_value.deserialize_setting(local_settings) {
 836                        Ok(local_settings) => {
 837                            paths_stack.push(Some((*root_id, directory_path.as_ref())));
 838                            project_settings_stack.push(local_settings);
 839
 840                            // If a local settings file changed, then avoid recomputing local
 841                            // settings for any path outside of that directory.
 842                            if changed_local_path.map_or(
 843                                false,
 844                                |(changed_root_id, changed_local_path)| {
 845                                    *root_id != changed_root_id
 846                                        || !directory_path.starts_with(changed_local_path)
 847                                },
 848                            ) {
 849                                continue;
 850                            }
 851
 852                            if let Some(value) = setting_value
 853                                .load_setting(
 854                                    SettingsSources {
 855                                        default: &default_settings,
 856                                        extensions: extension_settings.as_ref(),
 857                                        user: user_settings.as_ref(),
 858                                        release_channel: release_channel_settings.as_ref(),
 859                                        server: server_settings.as_ref(),
 860                                        project: &project_settings_stack.iter().collect::<Vec<_>>(),
 861                                    },
 862                                    cx,
 863                                )
 864                                .log_err()
 865                            {
 866                                setting_value.set_local_value(
 867                                    *root_id,
 868                                    directory_path.clone(),
 869                                    value,
 870                                );
 871                            }
 872                        }
 873                        Err(error) => {
 874                            return Err(InvalidSettingsError::LocalSettings {
 875                                path: directory_path.join(local_settings_file_relative_path()),
 876                                message: error.to_string(),
 877                            });
 878                        }
 879                    }
 880                }
 881            }
 882        }
 883        Ok(())
 884    }
 885}
 886
 887#[derive(Debug, Clone, PartialEq)]
 888pub enum InvalidSettingsError {
 889    LocalSettings { path: PathBuf, message: String },
 890    UserSettings { message: String },
 891    ServerSettings { message: String },
 892    DefaultSettings { message: String },
 893}
 894
 895impl std::fmt::Display for InvalidSettingsError {
 896    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 897        match self {
 898            InvalidSettingsError::LocalSettings { message, .. }
 899            | InvalidSettingsError::UserSettings { message }
 900            | InvalidSettingsError::ServerSettings { message }
 901            | InvalidSettingsError::DefaultSettings { message } => {
 902                write!(f, "{}", message)
 903            }
 904        }
 905    }
 906}
 907impl std::error::Error for InvalidSettingsError {}
 908
 909impl Debug for SettingsStore {
 910    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 911        f.debug_struct("SettingsStore")
 912            .field(
 913                "types",
 914                &self
 915                    .setting_values
 916                    .values()
 917                    .map(|value| value.setting_type_name())
 918                    .collect::<Vec<_>>(),
 919            )
 920            .field("default_settings", &self.raw_default_settings)
 921            .field("user_settings", &self.raw_user_settings)
 922            .field("local_settings", &self.raw_local_settings)
 923            .finish_non_exhaustive()
 924    }
 925}
 926
 927impl<T: Settings> AnySettingValue for SettingValue<T> {
 928    fn key(&self) -> Option<&'static str> {
 929        T::KEY
 930    }
 931
 932    fn setting_type_name(&self) -> &'static str {
 933        type_name::<T>()
 934    }
 935
 936    fn load_setting(
 937        &self,
 938        values: SettingsSources<DeserializedSetting>,
 939        cx: &mut AppContext,
 940    ) -> Result<Box<dyn Any>> {
 941        Ok(Box::new(T::load(
 942            SettingsSources {
 943                default: values.default.0.downcast_ref::<T::FileContent>().unwrap(),
 944                extensions: values
 945                    .extensions
 946                    .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
 947                user: values
 948                    .user
 949                    .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
 950                release_channel: values
 951                    .release_channel
 952                    .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
 953                server: values
 954                    .server
 955                    .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
 956                project: values
 957                    .project
 958                    .iter()
 959                    .map(|value| value.0.downcast_ref().unwrap())
 960                    .collect::<SmallVec<[_; 3]>>()
 961                    .as_slice(),
 962            },
 963            cx,
 964        )?))
 965    }
 966
 967    fn deserialize_setting(&self, mut json: &serde_json::Value) -> Result<DeserializedSetting> {
 968        if let Some(key) = T::KEY {
 969            if let Some(value) = json.get(key) {
 970                json = value;
 971            } else {
 972                let value = T::FileContent::default();
 973                return Ok(DeserializedSetting(Box::new(value)));
 974            }
 975        }
 976        let value = T::FileContent::deserialize(json)?;
 977        Ok(DeserializedSetting(Box::new(value)))
 978    }
 979
 980    fn value_for_path(&self, path: Option<SettingsLocation>) -> &dyn Any {
 981        if let Some(SettingsLocation { worktree_id, path }) = path {
 982            for (settings_root_id, settings_path, value) in self.local_values.iter().rev() {
 983                if worktree_id == *settings_root_id && path.starts_with(settings_path) {
 984                    return value;
 985                }
 986            }
 987        }
 988        self.global_value
 989            .as_ref()
 990            .unwrap_or_else(|| panic!("no default value for setting {}", self.setting_type_name()))
 991    }
 992
 993    fn set_global_value(&mut self, value: Box<dyn Any>) {
 994        self.global_value = Some(*value.downcast().unwrap());
 995    }
 996
 997    fn set_local_value(&mut self, root_id: WorktreeId, path: Arc<Path>, value: Box<dyn Any>) {
 998        let value = *value.downcast().unwrap();
 999        match self
1000            .local_values
1001            .binary_search_by_key(&(root_id, &path), |e| (e.0, &e.1))
1002        {
1003            Ok(ix) => self.local_values[ix].2 = value,
1004            Err(ix) => self.local_values.insert(ix, (root_id, path, value)),
1005        }
1006    }
1007
1008    fn json_schema(
1009        &self,
1010        generator: &mut SchemaGenerator,
1011        params: &SettingsJsonSchemaParams,
1012        cx: &AppContext,
1013    ) -> RootSchema {
1014        T::json_schema(generator, params, cx)
1015    }
1016}
1017
1018fn update_value_in_json_text<'a>(
1019    text: &mut String,
1020    key_path: &mut Vec<&'a str>,
1021    tab_size: usize,
1022    old_value: &'a serde_json::Value,
1023    new_value: &'a serde_json::Value,
1024    preserved_keys: &[&str],
1025    edits: &mut Vec<(Range<usize>, String)>,
1026) {
1027    // If the old and new values are both objects, then compare them key by key,
1028    // preserving the comments and formatting of the unchanged parts. Otherwise,
1029    // replace the old value with the new value.
1030    if let (serde_json::Value::Object(old_object), serde_json::Value::Object(new_object)) =
1031        (old_value, new_value)
1032    {
1033        for (key, old_sub_value) in old_object.iter() {
1034            key_path.push(key);
1035            let new_sub_value = new_object.get(key).unwrap_or(&serde_json::Value::Null);
1036            update_value_in_json_text(
1037                text,
1038                key_path,
1039                tab_size,
1040                old_sub_value,
1041                new_sub_value,
1042                preserved_keys,
1043                edits,
1044            );
1045            key_path.pop();
1046        }
1047        for (key, new_sub_value) in new_object.iter() {
1048            key_path.push(key);
1049            if !old_object.contains_key(key) {
1050                update_value_in_json_text(
1051                    text,
1052                    key_path,
1053                    tab_size,
1054                    &serde_json::Value::Null,
1055                    new_sub_value,
1056                    preserved_keys,
1057                    edits,
1058                );
1059            }
1060            key_path.pop();
1061        }
1062    } else if key_path
1063        .last()
1064        .map_or(false, |key| preserved_keys.contains(key))
1065        || old_value != new_value
1066    {
1067        let mut new_value = new_value.clone();
1068        if let Some(new_object) = new_value.as_object_mut() {
1069            new_object.retain(|_, v| !v.is_null());
1070        }
1071        let (range, replacement) = replace_value_in_json_text(text, key_path, tab_size, &new_value);
1072        text.replace_range(range.clone(), &replacement);
1073        edits.push((range, replacement));
1074    }
1075}
1076
1077fn replace_value_in_json_text(
1078    text: &str,
1079    key_path: &[&str],
1080    tab_size: usize,
1081    new_value: &serde_json::Value,
1082) -> (Range<usize>, String) {
1083    static PAIR_QUERY: LazyLock<Query> = LazyLock::new(|| {
1084        Query::new(
1085            &tree_sitter_json::LANGUAGE.into(),
1086            "(pair key: (string) @key value: (_) @value)",
1087        )
1088        .expect("Failed to create PAIR_QUERY")
1089    });
1090
1091    let mut parser = tree_sitter::Parser::new();
1092    parser
1093        .set_language(&tree_sitter_json::LANGUAGE.into())
1094        .unwrap();
1095    let syntax_tree = parser.parse(text, None).unwrap();
1096
1097    let mut cursor = tree_sitter::QueryCursor::new();
1098
1099    let mut depth = 0;
1100    let mut last_value_range = 0..0;
1101    let mut first_key_start = None;
1102    let mut existing_value_range = 0..text.len();
1103    let matches = cursor.matches(&PAIR_QUERY, syntax_tree.root_node(), text.as_bytes());
1104    for mat in matches {
1105        if mat.captures.len() != 2 {
1106            continue;
1107        }
1108
1109        let key_range = mat.captures[0].node.byte_range();
1110        let value_range = mat.captures[1].node.byte_range();
1111
1112        // Don't enter sub objects until we find an exact
1113        // match for the current keypath
1114        if last_value_range.contains_inclusive(&value_range) {
1115            continue;
1116        }
1117
1118        last_value_range = value_range.clone();
1119
1120        if key_range.start > existing_value_range.end {
1121            break;
1122        }
1123
1124        first_key_start.get_or_insert(key_range.start);
1125
1126        let found_key = text
1127            .get(key_range.clone())
1128            .map(|key_text| key_text == format!("\"{}\"", key_path[depth]))
1129            .unwrap_or(false);
1130
1131        if found_key {
1132            existing_value_range = value_range;
1133            // Reset last value range when increasing in depth
1134            last_value_range = existing_value_range.start..existing_value_range.start;
1135            depth += 1;
1136
1137            if depth == key_path.len() {
1138                break;
1139            }
1140
1141            first_key_start = None;
1142        }
1143    }
1144
1145    // We found the exact key we want, insert the new value
1146    if depth == key_path.len() {
1147        let new_val = to_pretty_json(&new_value, tab_size, tab_size * depth);
1148        (existing_value_range, new_val)
1149    } else {
1150        // We have key paths, construct the sub objects
1151        let new_key = key_path[depth];
1152
1153        // We don't have the key, construct the nested objects
1154        let mut new_value = serde_json::to_value(new_value).unwrap();
1155        for key in key_path[(depth + 1)..].iter().rev() {
1156            new_value = serde_json::json!({ key.to_string(): new_value });
1157        }
1158
1159        if let Some(first_key_start) = first_key_start {
1160            let mut row = 0;
1161            let mut column = 0;
1162            for (ix, char) in text.char_indices() {
1163                if ix == first_key_start {
1164                    break;
1165                }
1166                if char == '\n' {
1167                    row += 1;
1168                    column = 0;
1169                } else {
1170                    column += char.len_utf8();
1171                }
1172            }
1173
1174            if row > 0 {
1175                // depth is 0 based, but division needs to be 1 based.
1176                let new_val = to_pretty_json(&new_value, column / (depth + 1), column);
1177                let space = ' ';
1178                let content = format!("\"{new_key}\": {new_val},\n{space:width$}", width = column);
1179                (first_key_start..first_key_start, content)
1180            } else {
1181                let new_val = serde_json::to_string(&new_value).unwrap();
1182                let mut content = format!(r#""{new_key}": {new_val},"#);
1183                content.push(' ');
1184                (first_key_start..first_key_start, content)
1185            }
1186        } else {
1187            new_value = serde_json::json!({ new_key.to_string(): new_value });
1188            let indent_prefix_len = 4 * depth;
1189            let mut new_val = to_pretty_json(&new_value, 4, indent_prefix_len);
1190            if depth == 0 {
1191                new_val.push('\n');
1192            }
1193
1194            (existing_value_range, new_val)
1195        }
1196    }
1197}
1198
1199fn to_pretty_json(value: &impl Serialize, indent_size: usize, indent_prefix_len: usize) -> String {
1200    const SPACES: [u8; 32] = [b' '; 32];
1201
1202    debug_assert!(indent_size <= SPACES.len());
1203    debug_assert!(indent_prefix_len <= SPACES.len());
1204
1205    let mut output = Vec::new();
1206    let mut ser = serde_json::Serializer::with_formatter(
1207        &mut output,
1208        serde_json::ser::PrettyFormatter::with_indent(&SPACES[0..indent_size.min(SPACES.len())]),
1209    );
1210
1211    value.serialize(&mut ser).unwrap();
1212    let text = String::from_utf8(output).unwrap();
1213
1214    let mut adjusted_text = String::new();
1215    for (i, line) in text.split('\n').enumerate() {
1216        if i > 0 {
1217            adjusted_text.push_str(str::from_utf8(&SPACES[0..indent_prefix_len]).unwrap());
1218        }
1219        adjusted_text.push_str(line);
1220        adjusted_text.push('\n');
1221    }
1222    adjusted_text.pop();
1223    adjusted_text
1224}
1225
1226pub fn parse_json_with_comments<T: DeserializeOwned>(content: &str) -> Result<T> {
1227    Ok(serde_json_lenient::from_str(content)?)
1228}
1229
1230#[cfg(test)]
1231mod tests {
1232    use super::*;
1233    use serde_derive::Deserialize;
1234    use unindent::Unindent;
1235
1236    #[gpui::test]
1237    fn test_settings_store_basic(cx: &mut AppContext) {
1238        let mut store = SettingsStore::new(cx);
1239        store.register_setting::<UserSettings>(cx);
1240        store.register_setting::<TurboSetting>(cx);
1241        store.register_setting::<MultiKeySettings>(cx);
1242        store
1243            .set_default_settings(
1244                r#"{
1245                    "turbo": false,
1246                    "user": {
1247                        "name": "John Doe",
1248                        "age": 30,
1249                        "staff": false
1250                    }
1251                }"#,
1252                cx,
1253            )
1254            .unwrap();
1255
1256        assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(false));
1257        assert_eq!(
1258            store.get::<UserSettings>(None),
1259            &UserSettings {
1260                name: "John Doe".to_string(),
1261                age: 30,
1262                staff: false,
1263            }
1264        );
1265        assert_eq!(
1266            store.get::<MultiKeySettings>(None),
1267            &MultiKeySettings {
1268                key1: String::new(),
1269                key2: String::new(),
1270            }
1271        );
1272
1273        store
1274            .set_user_settings(
1275                r#"{
1276                    "turbo": true,
1277                    "user": { "age": 31 },
1278                    "key1": "a"
1279                }"#,
1280                cx,
1281            )
1282            .unwrap();
1283
1284        assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(true));
1285        assert_eq!(
1286            store.get::<UserSettings>(None),
1287            &UserSettings {
1288                name: "John Doe".to_string(),
1289                age: 31,
1290                staff: false
1291            }
1292        );
1293
1294        store
1295            .set_local_settings(
1296                WorktreeId::from_usize(1),
1297                Path::new("/root1").into(),
1298                LocalSettingsKind::Settings,
1299                Some(r#"{ "user": { "staff": true } }"#),
1300                cx,
1301            )
1302            .unwrap();
1303        store
1304            .set_local_settings(
1305                WorktreeId::from_usize(1),
1306                Path::new("/root1/subdir").into(),
1307                LocalSettingsKind::Settings,
1308                Some(r#"{ "user": { "name": "Jane Doe" } }"#),
1309                cx,
1310            )
1311            .unwrap();
1312
1313        store
1314            .set_local_settings(
1315                WorktreeId::from_usize(1),
1316                Path::new("/root2").into(),
1317                LocalSettingsKind::Settings,
1318                Some(r#"{ "user": { "age": 42 }, "key2": "b" }"#),
1319                cx,
1320            )
1321            .unwrap();
1322
1323        assert_eq!(
1324            store.get::<UserSettings>(Some(SettingsLocation {
1325                worktree_id: WorktreeId::from_usize(1),
1326                path: Path::new("/root1/something"),
1327            })),
1328            &UserSettings {
1329                name: "John Doe".to_string(),
1330                age: 31,
1331                staff: true
1332            }
1333        );
1334        assert_eq!(
1335            store.get::<UserSettings>(Some(SettingsLocation {
1336                worktree_id: WorktreeId::from_usize(1),
1337                path: Path::new("/root1/subdir/something")
1338            })),
1339            &UserSettings {
1340                name: "Jane Doe".to_string(),
1341                age: 31,
1342                staff: true
1343            }
1344        );
1345        assert_eq!(
1346            store.get::<UserSettings>(Some(SettingsLocation {
1347                worktree_id: WorktreeId::from_usize(1),
1348                path: Path::new("/root2/something")
1349            })),
1350            &UserSettings {
1351                name: "John Doe".to_string(),
1352                age: 42,
1353                staff: false
1354            }
1355        );
1356        assert_eq!(
1357            store.get::<MultiKeySettings>(Some(SettingsLocation {
1358                worktree_id: WorktreeId::from_usize(1),
1359                path: Path::new("/root2/something")
1360            })),
1361            &MultiKeySettings {
1362                key1: "a".to_string(),
1363                key2: "b".to_string(),
1364            }
1365        );
1366    }
1367
1368    #[gpui::test]
1369    fn test_setting_store_assign_json_before_register(cx: &mut AppContext) {
1370        let mut store = SettingsStore::new(cx);
1371        store
1372            .set_default_settings(
1373                r#"{
1374                    "turbo": true,
1375                    "user": {
1376                        "name": "John Doe",
1377                        "age": 30,
1378                        "staff": false
1379                    },
1380                    "key1": "x"
1381                }"#,
1382                cx,
1383            )
1384            .unwrap();
1385        store
1386            .set_user_settings(r#"{ "turbo": false }"#, cx)
1387            .unwrap();
1388        store.register_setting::<UserSettings>(cx);
1389        store.register_setting::<TurboSetting>(cx);
1390
1391        assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(false));
1392        assert_eq!(
1393            store.get::<UserSettings>(None),
1394            &UserSettings {
1395                name: "John Doe".to_string(),
1396                age: 30,
1397                staff: false,
1398            }
1399        );
1400
1401        store.register_setting::<MultiKeySettings>(cx);
1402        assert_eq!(
1403            store.get::<MultiKeySettings>(None),
1404            &MultiKeySettings {
1405                key1: "x".into(),
1406                key2: String::new(),
1407            }
1408        );
1409    }
1410
1411    #[gpui::test]
1412    fn test_setting_store_update(cx: &mut AppContext) {
1413        let mut store = SettingsStore::new(cx);
1414        store.register_setting::<MultiKeySettings>(cx);
1415        store.register_setting::<UserSettings>(cx);
1416        store.register_setting::<LanguageSettings>(cx);
1417
1418        // entries added and updated
1419        check_settings_update::<LanguageSettings>(
1420            &mut store,
1421            r#"{
1422                "languages": {
1423                    "JSON": {
1424                        "language_setting_1": true
1425                    }
1426                }
1427            }"#
1428            .unindent(),
1429            |settings| {
1430                settings
1431                    .languages
1432                    .get_mut("JSON")
1433                    .unwrap()
1434                    .language_setting_1 = Some(false);
1435                settings.languages.insert(
1436                    "Rust".into(),
1437                    LanguageSettingEntry {
1438                        language_setting_2: Some(true),
1439                        ..Default::default()
1440                    },
1441                );
1442            },
1443            r#"{
1444                "languages": {
1445                    "Rust": {
1446                        "language_setting_2": true
1447                    },
1448                    "JSON": {
1449                        "language_setting_1": false
1450                    }
1451                }
1452            }"#
1453            .unindent(),
1454            cx,
1455        );
1456
1457        // weird formatting
1458        check_settings_update::<UserSettings>(
1459            &mut store,
1460            r#"{
1461                "user":   { "age": 36, "name": "Max", "staff": true }
1462            }"#
1463            .unindent(),
1464            |settings| settings.age = Some(37),
1465            r#"{
1466                "user":   { "age": 37, "name": "Max", "staff": true }
1467            }"#
1468            .unindent(),
1469            cx,
1470        );
1471
1472        // single-line formatting, other keys
1473        check_settings_update::<MultiKeySettings>(
1474            &mut store,
1475            r#"{ "one": 1, "two": 2 }"#.unindent(),
1476            |settings| settings.key1 = Some("x".into()),
1477            r#"{ "key1": "x", "one": 1, "two": 2 }"#.unindent(),
1478            cx,
1479        );
1480
1481        // empty object
1482        check_settings_update::<UserSettings>(
1483            &mut store,
1484            r#"{
1485                "user": {}
1486            }"#
1487            .unindent(),
1488            |settings| settings.age = Some(37),
1489            r#"{
1490                "user": {
1491                    "age": 37
1492                }
1493            }"#
1494            .unindent(),
1495            cx,
1496        );
1497
1498        // no content
1499        check_settings_update::<UserSettings>(
1500            &mut store,
1501            r#""#.unindent(),
1502            |settings| settings.age = Some(37),
1503            r#"{
1504                "user": {
1505                    "age": 37
1506                }
1507            }
1508            "#
1509            .unindent(),
1510            cx,
1511        );
1512
1513        check_settings_update::<UserSettings>(
1514            &mut store,
1515            r#"{
1516            }
1517            "#
1518            .unindent(),
1519            |settings| settings.age = Some(37),
1520            r#"{
1521                "user": {
1522                    "age": 37
1523                }
1524            }
1525            "#
1526            .unindent(),
1527            cx,
1528        );
1529    }
1530
1531    fn check_settings_update<T: Settings>(
1532        store: &mut SettingsStore,
1533        old_json: String,
1534        update: fn(&mut T::FileContent),
1535        expected_new_json: String,
1536        cx: &mut AppContext,
1537    ) {
1538        store.set_user_settings(&old_json, cx).ok();
1539        let edits = store.edits_for_update::<T>(&old_json, update);
1540        let mut new_json = old_json;
1541        for (range, replacement) in edits.into_iter() {
1542            new_json.replace_range(range, &replacement);
1543        }
1544        pretty_assertions::assert_eq!(new_json, expected_new_json);
1545    }
1546
1547    #[derive(Debug, PartialEq, Deserialize)]
1548    struct UserSettings {
1549        name: String,
1550        age: u32,
1551        staff: bool,
1552    }
1553
1554    #[derive(Default, Clone, Serialize, Deserialize, JsonSchema)]
1555    struct UserSettingsJson {
1556        name: Option<String>,
1557        age: Option<u32>,
1558        staff: Option<bool>,
1559    }
1560
1561    impl Settings for UserSettings {
1562        const KEY: Option<&'static str> = Some("user");
1563        type FileContent = UserSettingsJson;
1564
1565        fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1566            sources.json_merge()
1567        }
1568    }
1569
1570    #[derive(Debug, Deserialize, PartialEq)]
1571    struct TurboSetting(bool);
1572
1573    impl Settings for TurboSetting {
1574        const KEY: Option<&'static str> = Some("turbo");
1575        type FileContent = Option<bool>;
1576
1577        fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1578            sources.json_merge()
1579        }
1580    }
1581
1582    #[derive(Clone, Debug, PartialEq, Deserialize)]
1583    struct MultiKeySettings {
1584        #[serde(default)]
1585        key1: String,
1586        #[serde(default)]
1587        key2: String,
1588    }
1589
1590    #[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
1591    struct MultiKeySettingsJson {
1592        key1: Option<String>,
1593        key2: Option<String>,
1594    }
1595
1596    impl Settings for MultiKeySettings {
1597        const KEY: Option<&'static str> = None;
1598
1599        type FileContent = MultiKeySettingsJson;
1600
1601        fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1602            sources.json_merge()
1603        }
1604    }
1605
1606    #[derive(Debug, Deserialize)]
1607    struct JournalSettings {
1608        pub path: String,
1609        pub hour_format: HourFormat,
1610    }
1611
1612    #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
1613    #[serde(rename_all = "snake_case")]
1614    enum HourFormat {
1615        Hour12,
1616        Hour24,
1617    }
1618
1619    #[derive(Clone, Default, Debug, Serialize, Deserialize, JsonSchema)]
1620    struct JournalSettingsJson {
1621        pub path: Option<String>,
1622        pub hour_format: Option<HourFormat>,
1623    }
1624
1625    impl Settings for JournalSettings {
1626        const KEY: Option<&'static str> = Some("journal");
1627
1628        type FileContent = JournalSettingsJson;
1629
1630        fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1631            sources.json_merge()
1632        }
1633    }
1634
1635    #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
1636    struct LanguageSettings {
1637        #[serde(default)]
1638        languages: HashMap<String, LanguageSettingEntry>,
1639    }
1640
1641    #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
1642    struct LanguageSettingEntry {
1643        language_setting_1: Option<bool>,
1644        language_setting_2: Option<bool>,
1645    }
1646
1647    impl Settings for LanguageSettings {
1648        const KEY: Option<&'static str> = None;
1649
1650        type FileContent = Self;
1651
1652        fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1653            sources.json_merge()
1654        }
1655    }
1656}