settings_store.rs

   1use anyhow::{anyhow, Context, 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::{AppContext, AsyncAppContext, BorrowAppContext, Global, Task, UpdateGlobal};
   7use paths::{local_settings_file_relative_path, EDITORCONFIG_NAME};
   8use schemars::{gen::SchemaGenerator, schema::RootSchema, JsonSchema};
   9use serde::{de::DeserializeOwned, Deserialize as _, Serialize};
  10use smallvec::SmallVec;
  11use std::{
  12    any::{type_name, Any, TypeId},
  13    fmt::Debug,
  14    ops::Range,
  15    path::{Path, PathBuf},
  16    str::{self, FromStr},
  17    sync::{Arc, LazyLock},
  18};
  19use tree_sitter::Query;
  20use util::{merge_non_null_json_value_into, RangeExt, ResultExt as _};
  21
  22pub type EditorconfigProperties = ec4rs::Properties;
  23
  24use crate::{SettingsJsonSchemaParams, WorktreeId};
  25
  26/// A value that can be defined as a user setting.
  27///
  28/// Settings can be loaded from a combination of multiple JSON files.
  29pub trait Settings: 'static + Send + Sync {
  30    /// The name of a key within the JSON file from which this setting should
  31    /// be deserialized. If this is `None`, then the setting will be deserialized
  32    /// from the root object.
  33    const KEY: Option<&'static str>;
  34
  35    /// The name of the keys in the [`FileContent`] that should always be written to
  36    /// a settings file, even if their value matches the default value.
  37    ///
  38    /// This is useful for tagged [`FileContent`]s where the tag is a "version" field
  39    /// that should always be persisted, even if the current user settings match the
  40    /// current version of the settings.
  41    const PRESERVED_KEYS: Option<&'static [&'static str]> = None;
  42
  43    /// The type that is stored in an individual JSON file.
  44    type FileContent: Clone + Default + Serialize + DeserializeOwned + JsonSchema;
  45
  46    /// The logic for combining together values from one or more JSON files into the
  47    /// final value for this setting.
  48    fn load(sources: SettingsSources<Self::FileContent>, cx: &mut AppContext) -> Result<Self>
  49    where
  50        Self: Sized;
  51
  52    fn json_schema(
  53        generator: &mut SchemaGenerator,
  54        _: &SettingsJsonSchemaParams,
  55        _: &AppContext,
  56    ) -> RootSchema {
  57        generator.root_schema_for::<Self::FileContent>()
  58    }
  59
  60    fn missing_default() -> anyhow::Error {
  61        anyhow::anyhow!("missing default")
  62    }
  63
  64    #[track_caller]
  65    fn register(cx: &mut AppContext)
  66    where
  67        Self: Sized,
  68    {
  69        SettingsStore::update_global(cx, |store, cx| {
  70            store.register_setting::<Self>(cx);
  71        });
  72    }
  73
  74    #[track_caller]
  75    fn get<'a>(path: Option<SettingsLocation>, cx: &'a AppContext) -> &'a Self
  76    where
  77        Self: Sized,
  78    {
  79        cx.global::<SettingsStore>().get(path)
  80    }
  81
  82    #[track_caller]
  83    fn get_global(cx: &AppContext) -> &Self
  84    where
  85        Self: Sized,
  86    {
  87        cx.global::<SettingsStore>().get(None)
  88    }
  89
  90    #[track_caller]
  91    fn try_read_global<R>(cx: &AsyncAppContext, f: impl FnOnce(&Self) -> R) -> Option<R>
  92    where
  93        Self: Sized,
  94    {
  95        cx.try_read_global(|s: &SettingsStore, _| f(s.get(None)))
  96    }
  97
  98    #[track_caller]
  99    fn override_global(settings: Self, cx: &mut AppContext)
 100    where
 101        Self: Sized,
 102    {
 103        cx.global_mut::<SettingsStore>().override_global(settings)
 104    }
 105}
 106
 107#[derive(Clone, Copy, Debug)]
 108pub struct SettingsSources<'a, T> {
 109    /// The default Zed settings.
 110    pub default: &'a T,
 111    /// Settings provided by extensions.
 112    pub extensions: Option<&'a T>,
 113    /// The user settings.
 114    pub user: Option<&'a T>,
 115    /// The user settings for the current release channel.
 116    pub release_channel: Option<&'a T>,
 117    /// The server's settings.
 118    pub server: Option<&'a T>,
 119    /// The project settings, ordered from least specific to most specific.
 120    pub project: &'a [&'a T],
 121}
 122
 123impl<'a, T: Serialize> SettingsSources<'a, T> {
 124    /// Returns an iterator over the default settings as well as all settings customizations.
 125    pub fn defaults_and_customizations(&self) -> impl Iterator<Item = &T> {
 126        [self.default].into_iter().chain(self.customizations())
 127    }
 128
 129    /// Returns an iterator over all of the settings customizations.
 130    pub fn customizations(&self) -> impl Iterator<Item = &T> {
 131        self.extensions
 132            .into_iter()
 133            .chain(self.user)
 134            .chain(self.release_channel)
 135            .chain(self.server)
 136            .chain(self.project.iter().copied())
 137    }
 138
 139    /// Returns the settings after performing a JSON merge of the provided customizations.
 140    ///
 141    /// Customizations later in the iterator win out over the earlier ones.
 142    pub fn json_merge_with<O: DeserializeOwned>(
 143        customizations: impl Iterator<Item = &'a T>,
 144    ) -> Result<O> {
 145        let mut merged = serde_json::Value::Null;
 146        for value in customizations {
 147            merge_non_null_json_value_into(serde_json::to_value(value).unwrap(), &mut merged);
 148        }
 149        Ok(serde_json::from_value(merged)?)
 150    }
 151
 152    /// Returns the settings after performing a JSON merge of the customizations into the
 153    /// default settings.
 154    ///
 155    /// More-specific customizations win out over the less-specific ones.
 156    pub fn json_merge<O: DeserializeOwned>(&'a self) -> Result<O> {
 157        Self::json_merge_with(self.defaults_and_customizations())
 158    }
 159}
 160
 161#[derive(Clone, Copy, Debug)]
 162pub struct SettingsLocation<'a> {
 163    pub worktree_id: WorktreeId,
 164    pub path: &'a Path,
 165}
 166
 167/// A set of strongly-typed setting values defined via multiple config files.
 168pub struct SettingsStore {
 169    setting_values: HashMap<TypeId, Box<dyn AnySettingValue>>,
 170    raw_default_settings: serde_json::Value,
 171    raw_user_settings: serde_json::Value,
 172    raw_server_settings: Option<serde_json::Value>,
 173    raw_extension_settings: serde_json::Value,
 174    raw_local_settings: BTreeMap<(WorktreeId, Arc<Path>), serde_json::Value>,
 175    raw_editorconfig_settings: BTreeMap<(WorktreeId, Arc<Path>), (String, Option<Editorconfig>)>,
 176    tab_size_callback: Option<(
 177        TypeId,
 178        Box<dyn Fn(&dyn Any) -> Option<usize> + Send + Sync + 'static>,
 179    )>,
 180    _setting_file_updates: Task<()>,
 181    setting_file_updates_tx: mpsc::UnboundedSender<
 182        Box<dyn FnOnce(AsyncAppContext) -> LocalBoxFuture<'static, Result<()>>>,
 183    >,
 184}
 185
 186#[derive(Clone)]
 187pub struct Editorconfig {
 188    pub is_root: bool,
 189    pub sections: SmallVec<[Section; 5]>,
 190}
 191
 192impl FromStr for Editorconfig {
 193    type Err = anyhow::Error;
 194
 195    fn from_str(contents: &str) -> Result<Self, Self::Err> {
 196        let parser = ConfigParser::new_buffered(contents.as_bytes())
 197            .context("creating editorconfig parser")?;
 198        let is_root = parser.is_root;
 199        let sections = parser
 200            .collect::<Result<SmallVec<_>, _>>()
 201            .context("parsing editorconfig sections")?;
 202        Ok(Self { is_root, sections })
 203    }
 204}
 205
 206#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
 207pub enum LocalSettingsKind {
 208    Settings,
 209    Tasks,
 210    Editorconfig,
 211}
 212
 213impl Global for SettingsStore {}
 214
 215#[derive(Debug)]
 216struct SettingValue<T> {
 217    global_value: Option<T>,
 218    local_values: Vec<(WorktreeId, Arc<Path>, T)>,
 219}
 220
 221trait AnySettingValue: 'static + Send + Sync {
 222    fn key(&self) -> Option<&'static str>;
 223    fn setting_type_name(&self) -> &'static str;
 224    fn deserialize_setting(&self, json: &serde_json::Value) -> Result<DeserializedSetting>;
 225    fn load_setting(
 226        &self,
 227        sources: SettingsSources<DeserializedSetting>,
 228        cx: &mut AppContext,
 229    ) -> Result<Box<dyn Any>>;
 230    fn value_for_path(&self, path: Option<SettingsLocation>) -> &dyn Any;
 231    fn set_global_value(&mut self, value: Box<dyn Any>);
 232    fn set_local_value(&mut self, root_id: WorktreeId, path: Arc<Path>, value: Box<dyn Any>);
 233    fn json_schema(
 234        &self,
 235        generator: &mut SchemaGenerator,
 236        _: &SettingsJsonSchemaParams,
 237        cx: &AppContext,
 238    ) -> RootSchema;
 239}
 240
 241struct DeserializedSetting(Box<dyn Any>);
 242
 243impl SettingsStore {
 244    pub fn new(cx: &AppContext) -> Self {
 245        let (setting_file_updates_tx, mut setting_file_updates_rx) = mpsc::unbounded();
 246        Self {
 247            setting_values: Default::default(),
 248            raw_default_settings: serde_json::json!({}),
 249            raw_user_settings: serde_json::json!({}),
 250            raw_server_settings: None,
 251            raw_extension_settings: serde_json::json!({}),
 252            raw_local_settings: Default::default(),
 253            raw_editorconfig_settings: BTreeMap::default(),
 254            tab_size_callback: Default::default(),
 255            setting_file_updates_tx,
 256            _setting_file_updates: cx.spawn(|cx| async move {
 257                while let Some(setting_file_update) = setting_file_updates_rx.next().await {
 258                    (setting_file_update)(cx.clone()).await.log_err();
 259                }
 260            }),
 261        }
 262    }
 263
 264    pub fn update<C, R>(cx: &mut C, f: impl FnOnce(&mut Self, &mut C) -> R) -> R
 265    where
 266        C: BorrowAppContext,
 267    {
 268        cx.update_global(f)
 269    }
 270
 271    /// Add a new type of setting to the store.
 272    pub fn register_setting<T: Settings>(&mut self, cx: &mut AppContext) {
 273        let setting_type_id = TypeId::of::<T>();
 274        let entry = self.setting_values.entry(setting_type_id);
 275
 276        if matches!(entry, hash_map::Entry::Occupied(_)) {
 277            return;
 278        }
 279
 280        let setting_value = entry.or_insert(Box::new(SettingValue::<T> {
 281            global_value: None,
 282            local_values: Vec::new(),
 283        }));
 284
 285        if let Some(default_settings) = setting_value
 286            .deserialize_setting(&self.raw_default_settings)
 287            .log_err()
 288        {
 289            let user_value = setting_value
 290                .deserialize_setting(&self.raw_user_settings)
 291                .log_err();
 292
 293            let mut release_channel_value = None;
 294            if let Some(release_settings) = &self
 295                .raw_user_settings
 296                .get(release_channel::RELEASE_CHANNEL.dev_name())
 297            {
 298                release_channel_value = setting_value
 299                    .deserialize_setting(release_settings)
 300                    .log_err();
 301            }
 302
 303            let server_value = self
 304                .raw_server_settings
 305                .as_ref()
 306                .and_then(|server_setting| {
 307                    setting_value.deserialize_setting(server_setting).log_err()
 308                });
 309
 310            let extension_value = setting_value
 311                .deserialize_setting(&self.raw_extension_settings)
 312                .log_err();
 313
 314            if let Some(setting) = setting_value
 315                .load_setting(
 316                    SettingsSources {
 317                        default: &default_settings,
 318                        extensions: extension_value.as_ref(),
 319                        user: user_value.as_ref(),
 320                        release_channel: release_channel_value.as_ref(),
 321                        server: server_value.as_ref(),
 322                        project: &[],
 323                    },
 324                    cx,
 325                )
 326                .context("A default setting must be added to the `default.json` file")
 327                .log_err()
 328            {
 329                setting_value.set_global_value(setting);
 330            }
 331        }
 332    }
 333
 334    /// Get the value of a setting.
 335    ///
 336    /// Panics if the given setting type has not been registered, or if there is no
 337    /// value for this setting.
 338    pub fn get<T: Settings>(&self, path: Option<SettingsLocation>) -> &T {
 339        self.setting_values
 340            .get(&TypeId::of::<T>())
 341            .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()))
 342            .value_for_path(path)
 343            .downcast_ref::<T>()
 344            .expect("no default value for setting type")
 345    }
 346
 347    /// Override the global value for a setting.
 348    ///
 349    /// The given value will be overwritten if the user settings file changes.
 350    pub fn override_global<T: Settings>(&mut self, value: T) {
 351        self.setting_values
 352            .get_mut(&TypeId::of::<T>())
 353            .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()))
 354            .set_global_value(Box::new(value))
 355    }
 356
 357    /// Get the user's settings as a raw JSON value.
 358    ///
 359    /// For user-facing functionality use the typed setting interface.
 360    /// (e.g. ProjectSettings::get_global(cx))
 361    pub fn raw_user_settings(&self) -> &serde_json::Value {
 362        &self.raw_user_settings
 363    }
 364
 365    #[cfg(any(test, feature = "test-support"))]
 366    pub fn test(cx: &mut AppContext) -> Self {
 367        let mut this = Self::new(cx);
 368        this.set_default_settings(&crate::test_settings(), cx)
 369            .unwrap();
 370        this.set_user_settings("{}", cx).unwrap();
 371        this
 372    }
 373
 374    /// Updates the value of a setting in the user's global configuration.
 375    ///
 376    /// This is only for tests. Normally, settings are only loaded from
 377    /// JSON files.
 378    #[cfg(any(test, feature = "test-support"))]
 379    pub fn update_user_settings<T: Settings>(
 380        &mut self,
 381        cx: &mut AppContext,
 382        update: impl FnOnce(&mut T::FileContent),
 383    ) {
 384        let old_text = serde_json::to_string(&self.raw_user_settings).unwrap();
 385        let new_text = self.new_text_for_update::<T>(old_text, update);
 386        self.set_user_settings(&new_text, cx).unwrap();
 387    }
 388
 389    async fn load_settings(fs: &Arc<dyn Fs>) -> Result<String> {
 390        match fs.load(paths::settings_file()).await {
 391            result @ Ok(_) => result,
 392            Err(err) => {
 393                if let Some(e) = err.downcast_ref::<std::io::Error>() {
 394                    if e.kind() == std::io::ErrorKind::NotFound {
 395                        return Ok(crate::initial_user_settings_content().to_string());
 396                    }
 397                }
 398                Err(err)
 399            }
 400        }
 401    }
 402
 403    pub fn update_settings_file<T: Settings>(
 404        &self,
 405        fs: Arc<dyn Fs>,
 406        update: impl 'static + Send + FnOnce(&mut T::FileContent, &AppContext),
 407    ) {
 408        self.setting_file_updates_tx
 409            .unbounded_send(Box::new(move |cx: AsyncAppContext| {
 410                async move {
 411                    let old_text = Self::load_settings(&fs).await?;
 412                    let new_text = cx.read_global(|store: &SettingsStore, cx| {
 413                        store.new_text_for_update::<T>(old_text, |content| update(content, cx))
 414                    })?;
 415                    let initial_path = paths::settings_file().as_path();
 416                    if fs.is_file(initial_path).await {
 417                        let resolved_path =
 418                            fs.canonicalize(initial_path).await.with_context(|| {
 419                                format!("Failed to canonicalize settings path {:?}", initial_path)
 420                            })?;
 421
 422                        fs.atomic_write(resolved_path.clone(), new_text)
 423                            .await
 424                            .with_context(|| {
 425                                format!("Failed to write settings to file {:?}", resolved_path)
 426                            })?;
 427                    } else {
 428                        fs.atomic_write(initial_path.to_path_buf(), new_text)
 429                            .await
 430                            .with_context(|| {
 431                                format!("Failed to write settings to file {:?}", initial_path)
 432                            })?;
 433                    }
 434
 435                    anyhow::Ok(())
 436                }
 437                .boxed_local()
 438            }))
 439            .ok();
 440    }
 441
 442    /// Updates the value of a setting in a JSON file, returning the new text
 443    /// for that JSON file.
 444    pub fn new_text_for_update<T: Settings>(
 445        &self,
 446        old_text: String,
 447        update: impl FnOnce(&mut T::FileContent),
 448    ) -> String {
 449        let edits = self.edits_for_update::<T>(&old_text, update);
 450        let mut new_text = old_text;
 451        for (range, replacement) in edits.into_iter() {
 452            new_text.replace_range(range, &replacement);
 453        }
 454        new_text
 455    }
 456
 457    /// Updates the value of a setting in a JSON file, returning a list
 458    /// of edits to apply to the JSON file.
 459    pub fn edits_for_update<T: Settings>(
 460        &self,
 461        text: &str,
 462        update: impl FnOnce(&mut T::FileContent),
 463    ) -> Vec<(Range<usize>, String)> {
 464        let setting_type_id = TypeId::of::<T>();
 465
 466        let preserved_keys = T::PRESERVED_KEYS.unwrap_or_default();
 467
 468        let setting = self
 469            .setting_values
 470            .get(&setting_type_id)
 471            .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()));
 472        let raw_settings = parse_json_with_comments::<serde_json::Value>(text).unwrap_or_default();
 473        let old_content = match setting.deserialize_setting(&raw_settings) {
 474            Ok(content) => content.0.downcast::<T::FileContent>().unwrap(),
 475            Err(_) => Box::<<T as Settings>::FileContent>::default(),
 476        };
 477        let mut new_content = old_content.clone();
 478        update(&mut new_content);
 479
 480        let old_value = serde_json::to_value(&old_content).unwrap();
 481        let new_value = serde_json::to_value(new_content).unwrap();
 482
 483        let mut key_path = Vec::new();
 484        if let Some(key) = T::KEY {
 485            key_path.push(key);
 486        }
 487
 488        let mut edits = Vec::new();
 489        let tab_size = self.json_tab_size();
 490        let mut text = text.to_string();
 491        update_value_in_json_text(
 492            &mut text,
 493            &mut key_path,
 494            tab_size,
 495            &old_value,
 496            &new_value,
 497            preserved_keys,
 498            &mut edits,
 499        );
 500        edits
 501    }
 502
 503    /// Configure the tab sized when updating JSON files.
 504    pub fn set_json_tab_size_callback<T: Settings>(
 505        &mut self,
 506        get_tab_size: fn(&T) -> Option<usize>,
 507    ) {
 508        self.tab_size_callback = Some((
 509            TypeId::of::<T>(),
 510            Box::new(move |value| get_tab_size(value.downcast_ref::<T>().unwrap())),
 511        ));
 512    }
 513
 514    fn json_tab_size(&self) -> usize {
 515        const DEFAULT_JSON_TAB_SIZE: usize = 2;
 516
 517        if let Some((setting_type_id, callback)) = &self.tab_size_callback {
 518            let setting_value = self.setting_values.get(setting_type_id).unwrap();
 519            let value = setting_value.value_for_path(None);
 520            if let Some(value) = callback(value) {
 521                return value;
 522            }
 523        }
 524
 525        DEFAULT_JSON_TAB_SIZE
 526    }
 527
 528    /// Sets the default settings via a JSON string.
 529    ///
 530    /// The string should contain a JSON object with a default value for every setting.
 531    pub fn set_default_settings(
 532        &mut self,
 533        default_settings_content: &str,
 534        cx: &mut AppContext,
 535    ) -> Result<()> {
 536        let settings: serde_json::Value = parse_json_with_comments(default_settings_content)?;
 537        if settings.is_object() {
 538            self.raw_default_settings = settings;
 539            self.recompute_values(None, cx)?;
 540            Ok(())
 541        } else {
 542            Err(anyhow!("settings must be an object"))
 543        }
 544    }
 545
 546    /// Sets the user settings via a JSON string.
 547    pub fn set_user_settings(
 548        &mut self,
 549        user_settings_content: &str,
 550        cx: &mut AppContext,
 551    ) -> Result<()> {
 552        let settings: serde_json::Value = if user_settings_content.is_empty() {
 553            parse_json_with_comments("{}")?
 554        } else {
 555            parse_json_with_comments(user_settings_content)?
 556        };
 557
 558        anyhow::ensure!(settings.is_object(), "settings must be an object");
 559        self.raw_user_settings = settings;
 560        self.recompute_values(None, cx)?;
 561        Ok(())
 562    }
 563
 564    pub fn set_server_settings(
 565        &mut self,
 566        server_settings_content: &str,
 567        cx: &mut AppContext,
 568    ) -> Result<()> {
 569        let settings: Option<serde_json::Value> = if server_settings_content.is_empty() {
 570            None
 571        } else {
 572            parse_json_with_comments(server_settings_content)?
 573        };
 574
 575        anyhow::ensure!(
 576            settings
 577                .as_ref()
 578                .map(|value| value.is_object())
 579                .unwrap_or(true),
 580            "settings must be an object"
 581        );
 582        self.raw_server_settings = settings;
 583        self.recompute_values(None, cx)?;
 584        Ok(())
 585    }
 586
 587    /// Add or remove a set of local settings via a JSON string.
 588    pub fn set_local_settings(
 589        &mut self,
 590        root_id: WorktreeId,
 591        directory_path: Arc<Path>,
 592        kind: LocalSettingsKind,
 593        settings_content: Option<&str>,
 594        cx: &mut AppContext,
 595    ) -> std::result::Result<(), InvalidSettingsError> {
 596        let mut zed_settings_changed = false;
 597        match (
 598            kind,
 599            settings_content
 600                .map(|content| content.trim())
 601                .filter(|content| !content.is_empty()),
 602        ) {
 603            (LocalSettingsKind::Tasks, _) => {
 604                return Err(InvalidSettingsError::Tasks {
 605                    message: "Attempted to submit tasks into the settings store".to_string(),
 606                })
 607            }
 608            (LocalSettingsKind::Settings, None) => {
 609                zed_settings_changed = self
 610                    .raw_local_settings
 611                    .remove(&(root_id, directory_path.clone()))
 612                    .is_some()
 613            }
 614            (LocalSettingsKind::Editorconfig, None) => {
 615                self.raw_editorconfig_settings
 616                    .remove(&(root_id, directory_path.clone()));
 617            }
 618            (LocalSettingsKind::Settings, Some(settings_contents)) => {
 619                let new_settings = parse_json_with_comments::<serde_json::Value>(settings_contents)
 620                    .map_err(|e| InvalidSettingsError::LocalSettings {
 621                        path: directory_path.join(local_settings_file_relative_path()),
 622                        message: e.to_string(),
 623                    })?;
 624                match self
 625                    .raw_local_settings
 626                    .entry((root_id, directory_path.clone()))
 627                {
 628                    btree_map::Entry::Vacant(v) => {
 629                        v.insert(new_settings);
 630                        zed_settings_changed = true;
 631                    }
 632                    btree_map::Entry::Occupied(mut o) => {
 633                        if o.get() != &new_settings {
 634                            o.insert(new_settings);
 635                            zed_settings_changed = true;
 636                        }
 637                    }
 638                }
 639            }
 640            (LocalSettingsKind::Editorconfig, Some(editorconfig_contents)) => {
 641                match self
 642                    .raw_editorconfig_settings
 643                    .entry((root_id, directory_path.clone()))
 644                {
 645                    btree_map::Entry::Vacant(v) => match editorconfig_contents.parse() {
 646                        Ok(new_contents) => {
 647                            v.insert((editorconfig_contents.to_owned(), Some(new_contents)));
 648                        }
 649                        Err(e) => {
 650                            v.insert((editorconfig_contents.to_owned(), None));
 651                            return Err(InvalidSettingsError::Editorconfig {
 652                                message: e.to_string(),
 653                                path: directory_path.join(EDITORCONFIG_NAME),
 654                            });
 655                        }
 656                    },
 657                    btree_map::Entry::Occupied(mut o) => {
 658                        if o.get().0 != editorconfig_contents {
 659                            match editorconfig_contents.parse() {
 660                                Ok(new_contents) => {
 661                                    o.insert((
 662                                        editorconfig_contents.to_owned(),
 663                                        Some(new_contents),
 664                                    ));
 665                                }
 666                                Err(e) => {
 667                                    o.insert((editorconfig_contents.to_owned(), None));
 668                                    return Err(InvalidSettingsError::Editorconfig {
 669                                        message: e.to_string(),
 670                                        path: directory_path.join(EDITORCONFIG_NAME),
 671                                    });
 672                                }
 673                            }
 674                        }
 675                    }
 676                }
 677            }
 678        };
 679
 680        if zed_settings_changed {
 681            self.recompute_values(Some((root_id, &directory_path)), cx)?;
 682        }
 683        Ok(())
 684    }
 685
 686    pub fn set_extension_settings<T: Serialize>(
 687        &mut self,
 688        content: T,
 689        cx: &mut AppContext,
 690    ) -> 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 AppContext) -> 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: &AppContext,
 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 AppContext,
 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 AppContext,
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: &AppContext,
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 matches = cursor.matches(&PAIR_QUERY, syntax_tree.root_node(), text.as_bytes());
1222    for mat in matches {
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| key_text == format!("\"{}\"", key_path[depth]))
1247            .unwrap_or(false);
1248
1249        if found_key {
1250            existing_value_range = value_range;
1251            // Reset last value range when increasing in depth
1252            last_value_range = existing_value_range.start..existing_value_range.start;
1253            depth += 1;
1254
1255            if depth == key_path.len() {
1256                break;
1257            }
1258
1259            first_key_start = None;
1260        }
1261    }
1262
1263    // We found the exact key we want, insert the new value
1264    if depth == key_path.len() {
1265        let new_val = to_pretty_json(&new_value, tab_size, tab_size * depth);
1266        (existing_value_range, new_val)
1267    } else {
1268        // We have key paths, construct the sub objects
1269        let new_key = key_path[depth];
1270
1271        // We don't have the key, construct the nested objects
1272        let mut new_value = serde_json::to_value(new_value).unwrap();
1273        for key in key_path[(depth + 1)..].iter().rev() {
1274            new_value = serde_json::json!({ key.to_string(): new_value });
1275        }
1276
1277        if let Some(first_key_start) = first_key_start {
1278            let mut row = 0;
1279            let mut column = 0;
1280            for (ix, char) in text.char_indices() {
1281                if ix == first_key_start {
1282                    break;
1283                }
1284                if char == '\n' {
1285                    row += 1;
1286                    column = 0;
1287                } else {
1288                    column += char.len_utf8();
1289                }
1290            }
1291
1292            if row > 0 {
1293                // depth is 0 based, but division needs to be 1 based.
1294                let new_val = to_pretty_json(&new_value, column / (depth + 1), column);
1295                let space = ' ';
1296                let content = format!("\"{new_key}\": {new_val},\n{space:width$}", width = column);
1297                (first_key_start..first_key_start, content)
1298            } else {
1299                let new_val = serde_json::to_string(&new_value).unwrap();
1300                let mut content = format!(r#""{new_key}": {new_val},"#);
1301                content.push(' ');
1302                (first_key_start..first_key_start, content)
1303            }
1304        } else {
1305            new_value = serde_json::json!({ new_key.to_string(): new_value });
1306            let indent_prefix_len = 4 * depth;
1307            let mut new_val = to_pretty_json(&new_value, 4, indent_prefix_len);
1308            if depth == 0 {
1309                new_val.push('\n');
1310            }
1311
1312            (existing_value_range, new_val)
1313        }
1314    }
1315}
1316
1317fn to_pretty_json(value: &impl Serialize, indent_size: usize, indent_prefix_len: usize) -> String {
1318    const SPACES: [u8; 32] = [b' '; 32];
1319
1320    debug_assert!(indent_size <= SPACES.len());
1321    debug_assert!(indent_prefix_len <= SPACES.len());
1322
1323    let mut output = Vec::new();
1324    let mut ser = serde_json::Serializer::with_formatter(
1325        &mut output,
1326        serde_json::ser::PrettyFormatter::with_indent(&SPACES[0..indent_size.min(SPACES.len())]),
1327    );
1328
1329    value.serialize(&mut ser).unwrap();
1330    let text = String::from_utf8(output).unwrap();
1331
1332    let mut adjusted_text = String::new();
1333    for (i, line) in text.split('\n').enumerate() {
1334        if i > 0 {
1335            adjusted_text.push_str(str::from_utf8(&SPACES[0..indent_prefix_len]).unwrap());
1336        }
1337        adjusted_text.push_str(line);
1338        adjusted_text.push('\n');
1339    }
1340    adjusted_text.pop();
1341    adjusted_text
1342}
1343
1344pub fn parse_json_with_comments<T: DeserializeOwned>(content: &str) -> Result<T> {
1345    Ok(serde_json_lenient::from_str(content)?)
1346}
1347
1348#[cfg(test)]
1349mod tests {
1350    use super::*;
1351    use serde_derive::Deserialize;
1352    use unindent::Unindent;
1353
1354    #[gpui::test]
1355    fn test_settings_store_basic(cx: &mut AppContext) {
1356        let mut store = SettingsStore::new(cx);
1357        store.register_setting::<UserSettings>(cx);
1358        store.register_setting::<TurboSetting>(cx);
1359        store.register_setting::<MultiKeySettings>(cx);
1360        store
1361            .set_default_settings(
1362                r#"{
1363                    "turbo": false,
1364                    "user": {
1365                        "name": "John Doe",
1366                        "age": 30,
1367                        "staff": false
1368                    }
1369                }"#,
1370                cx,
1371            )
1372            .unwrap();
1373
1374        assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(false));
1375        assert_eq!(
1376            store.get::<UserSettings>(None),
1377            &UserSettings {
1378                name: "John Doe".to_string(),
1379                age: 30,
1380                staff: false,
1381            }
1382        );
1383        assert_eq!(
1384            store.get::<MultiKeySettings>(None),
1385            &MultiKeySettings {
1386                key1: String::new(),
1387                key2: String::new(),
1388            }
1389        );
1390
1391        store
1392            .set_user_settings(
1393                r#"{
1394                    "turbo": true,
1395                    "user": { "age": 31 },
1396                    "key1": "a"
1397                }"#,
1398                cx,
1399            )
1400            .unwrap();
1401
1402        assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(true));
1403        assert_eq!(
1404            store.get::<UserSettings>(None),
1405            &UserSettings {
1406                name: "John Doe".to_string(),
1407                age: 31,
1408                staff: false
1409            }
1410        );
1411
1412        store
1413            .set_local_settings(
1414                WorktreeId::from_usize(1),
1415                Path::new("/root1").into(),
1416                LocalSettingsKind::Settings,
1417                Some(r#"{ "user": { "staff": true } }"#),
1418                cx,
1419            )
1420            .unwrap();
1421        store
1422            .set_local_settings(
1423                WorktreeId::from_usize(1),
1424                Path::new("/root1/subdir").into(),
1425                LocalSettingsKind::Settings,
1426                Some(r#"{ "user": { "name": "Jane Doe" } }"#),
1427                cx,
1428            )
1429            .unwrap();
1430
1431        store
1432            .set_local_settings(
1433                WorktreeId::from_usize(1),
1434                Path::new("/root2").into(),
1435                LocalSettingsKind::Settings,
1436                Some(r#"{ "user": { "age": 42 }, "key2": "b" }"#),
1437                cx,
1438            )
1439            .unwrap();
1440
1441        assert_eq!(
1442            store.get::<UserSettings>(Some(SettingsLocation {
1443                worktree_id: WorktreeId::from_usize(1),
1444                path: Path::new("/root1/something"),
1445            })),
1446            &UserSettings {
1447                name: "John Doe".to_string(),
1448                age: 31,
1449                staff: true
1450            }
1451        );
1452        assert_eq!(
1453            store.get::<UserSettings>(Some(SettingsLocation {
1454                worktree_id: WorktreeId::from_usize(1),
1455                path: Path::new("/root1/subdir/something")
1456            })),
1457            &UserSettings {
1458                name: "Jane Doe".to_string(),
1459                age: 31,
1460                staff: true
1461            }
1462        );
1463        assert_eq!(
1464            store.get::<UserSettings>(Some(SettingsLocation {
1465                worktree_id: WorktreeId::from_usize(1),
1466                path: Path::new("/root2/something")
1467            })),
1468            &UserSettings {
1469                name: "John Doe".to_string(),
1470                age: 42,
1471                staff: false
1472            }
1473        );
1474        assert_eq!(
1475            store.get::<MultiKeySettings>(Some(SettingsLocation {
1476                worktree_id: WorktreeId::from_usize(1),
1477                path: Path::new("/root2/something")
1478            })),
1479            &MultiKeySettings {
1480                key1: "a".to_string(),
1481                key2: "b".to_string(),
1482            }
1483        );
1484    }
1485
1486    #[gpui::test]
1487    fn test_setting_store_assign_json_before_register(cx: &mut AppContext) {
1488        let mut store = SettingsStore::new(cx);
1489        store
1490            .set_default_settings(
1491                r#"{
1492                    "turbo": true,
1493                    "user": {
1494                        "name": "John Doe",
1495                        "age": 30,
1496                        "staff": false
1497                    },
1498                    "key1": "x"
1499                }"#,
1500                cx,
1501            )
1502            .unwrap();
1503        store
1504            .set_user_settings(r#"{ "turbo": false }"#, cx)
1505            .unwrap();
1506        store.register_setting::<UserSettings>(cx);
1507        store.register_setting::<TurboSetting>(cx);
1508
1509        assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(false));
1510        assert_eq!(
1511            store.get::<UserSettings>(None),
1512            &UserSettings {
1513                name: "John Doe".to_string(),
1514                age: 30,
1515                staff: false,
1516            }
1517        );
1518
1519        store.register_setting::<MultiKeySettings>(cx);
1520        assert_eq!(
1521            store.get::<MultiKeySettings>(None),
1522            &MultiKeySettings {
1523                key1: "x".into(),
1524                key2: String::new(),
1525            }
1526        );
1527    }
1528
1529    #[gpui::test]
1530    fn test_setting_store_update(cx: &mut AppContext) {
1531        let mut store = SettingsStore::new(cx);
1532        store.register_setting::<MultiKeySettings>(cx);
1533        store.register_setting::<UserSettings>(cx);
1534        store.register_setting::<LanguageSettings>(cx);
1535
1536        // entries added and updated
1537        check_settings_update::<LanguageSettings>(
1538            &mut store,
1539            r#"{
1540                "languages": {
1541                    "JSON": {
1542                        "language_setting_1": true
1543                    }
1544                }
1545            }"#
1546            .unindent(),
1547            |settings| {
1548                settings
1549                    .languages
1550                    .get_mut("JSON")
1551                    .unwrap()
1552                    .language_setting_1 = Some(false);
1553                settings.languages.insert(
1554                    "Rust".into(),
1555                    LanguageSettingEntry {
1556                        language_setting_2: Some(true),
1557                        ..Default::default()
1558                    },
1559                );
1560            },
1561            r#"{
1562                "languages": {
1563                    "Rust": {
1564                        "language_setting_2": true
1565                    },
1566                    "JSON": {
1567                        "language_setting_1": false
1568                    }
1569                }
1570            }"#
1571            .unindent(),
1572            cx,
1573        );
1574
1575        // weird formatting
1576        check_settings_update::<UserSettings>(
1577            &mut store,
1578            r#"{
1579                "user":   { "age": 36, "name": "Max", "staff": true }
1580            }"#
1581            .unindent(),
1582            |settings| settings.age = Some(37),
1583            r#"{
1584                "user":   { "age": 37, "name": "Max", "staff": true }
1585            }"#
1586            .unindent(),
1587            cx,
1588        );
1589
1590        // single-line formatting, other keys
1591        check_settings_update::<MultiKeySettings>(
1592            &mut store,
1593            r#"{ "one": 1, "two": 2 }"#.unindent(),
1594            |settings| settings.key1 = Some("x".into()),
1595            r#"{ "key1": "x", "one": 1, "two": 2 }"#.unindent(),
1596            cx,
1597        );
1598
1599        // empty object
1600        check_settings_update::<UserSettings>(
1601            &mut store,
1602            r#"{
1603                "user": {}
1604            }"#
1605            .unindent(),
1606            |settings| settings.age = Some(37),
1607            r#"{
1608                "user": {
1609                    "age": 37
1610                }
1611            }"#
1612            .unindent(),
1613            cx,
1614        );
1615
1616        // no content
1617        check_settings_update::<UserSettings>(
1618            &mut store,
1619            r#""#.unindent(),
1620            |settings| settings.age = Some(37),
1621            r#"{
1622                "user": {
1623                    "age": 37
1624                }
1625            }
1626            "#
1627            .unindent(),
1628            cx,
1629        );
1630
1631        check_settings_update::<UserSettings>(
1632            &mut store,
1633            r#"{
1634            }
1635            "#
1636            .unindent(),
1637            |settings| settings.age = Some(37),
1638            r#"{
1639                "user": {
1640                    "age": 37
1641                }
1642            }
1643            "#
1644            .unindent(),
1645            cx,
1646        );
1647    }
1648
1649    fn check_settings_update<T: Settings>(
1650        store: &mut SettingsStore,
1651        old_json: String,
1652        update: fn(&mut T::FileContent),
1653        expected_new_json: String,
1654        cx: &mut AppContext,
1655    ) {
1656        store.set_user_settings(&old_json, cx).ok();
1657        let edits = store.edits_for_update::<T>(&old_json, update);
1658        let mut new_json = old_json;
1659        for (range, replacement) in edits.into_iter() {
1660            new_json.replace_range(range, &replacement);
1661        }
1662        pretty_assertions::assert_eq!(new_json, expected_new_json);
1663    }
1664
1665    #[derive(Debug, PartialEq, Deserialize)]
1666    struct UserSettings {
1667        name: String,
1668        age: u32,
1669        staff: bool,
1670    }
1671
1672    #[derive(Default, Clone, Serialize, Deserialize, JsonSchema)]
1673    struct UserSettingsJson {
1674        name: Option<String>,
1675        age: Option<u32>,
1676        staff: Option<bool>,
1677    }
1678
1679    impl Settings for UserSettings {
1680        const KEY: Option<&'static str> = Some("user");
1681        type FileContent = UserSettingsJson;
1682
1683        fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1684            sources.json_merge()
1685        }
1686    }
1687
1688    #[derive(Debug, Deserialize, PartialEq)]
1689    struct TurboSetting(bool);
1690
1691    impl Settings for TurboSetting {
1692        const KEY: Option<&'static str> = Some("turbo");
1693        type FileContent = Option<bool>;
1694
1695        fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1696            sources.json_merge()
1697        }
1698    }
1699
1700    #[derive(Clone, Debug, PartialEq, Deserialize)]
1701    struct MultiKeySettings {
1702        #[serde(default)]
1703        key1: String,
1704        #[serde(default)]
1705        key2: String,
1706    }
1707
1708    #[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
1709    struct MultiKeySettingsJson {
1710        key1: Option<String>,
1711        key2: Option<String>,
1712    }
1713
1714    impl Settings for MultiKeySettings {
1715        const KEY: Option<&'static str> = None;
1716
1717        type FileContent = MultiKeySettingsJson;
1718
1719        fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1720            sources.json_merge()
1721        }
1722    }
1723
1724    #[derive(Debug, Deserialize)]
1725    struct JournalSettings {
1726        pub path: String,
1727        pub hour_format: HourFormat,
1728    }
1729
1730    #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
1731    #[serde(rename_all = "snake_case")]
1732    enum HourFormat {
1733        Hour12,
1734        Hour24,
1735    }
1736
1737    #[derive(Clone, Default, Debug, Serialize, Deserialize, JsonSchema)]
1738    struct JournalSettingsJson {
1739        pub path: Option<String>,
1740        pub hour_format: Option<HourFormat>,
1741    }
1742
1743    impl Settings for JournalSettings {
1744        const KEY: Option<&'static str> = Some("journal");
1745
1746        type FileContent = JournalSettingsJson;
1747
1748        fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1749            sources.json_merge()
1750        }
1751    }
1752
1753    #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
1754    struct LanguageSettings {
1755        #[serde(default)]
1756        languages: HashMap<String, LanguageSettingEntry>,
1757    }
1758
1759    #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
1760    struct LanguageSettingEntry {
1761        language_setting_1: Option<bool>,
1762        language_setting_2: Option<bool>,
1763    }
1764
1765    impl Settings for LanguageSettings {
1766        const KEY: Option<&'static str> = None;
1767
1768        type FileContent = Self;
1769
1770        fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1771            sources.json_merge()
1772        }
1773    }
1774}