settings_store.rs

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