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