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