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