settings_store.rs

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