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 tree_sitter::Query;
  21use util::RangeExt;
  22
  23use util::{merge_non_null_json_value_into, ResultExt as _};
  24
  25pub type EditorconfigProperties = ec4rs::Properties;
  26
  27use crate::{SettingsJsonSchemaParams, WorktreeId};
  28
  29/// A value that can be defined as a user setting.
  30///
  31/// Settings can be loaded from a combination of multiple JSON files.
  32pub trait Settings: 'static + Send + Sync {
  33    /// The name of a key within the JSON file from which this setting should
  34    /// be deserialized. If this is `None`, then the setting will be deserialized
  35    /// from the root object.
  36    const KEY: Option<&'static str>;
  37
  38    /// The name of the keys in the [`FileContent`](Self::FileContent) that should
  39    /// always be written to a settings file, even if their value matches the default
  40    /// value.
  41    ///
  42    /// This is useful for tagged [`FileContent`](Self::FileContent)s where the tag
  43    /// is a "version" field that should always be persisted, even if the current
  44    /// user settings match the current version of the settings.
  45    const PRESERVED_KEYS: Option<&'static [&'static str]> = None;
  46
  47    /// The type that is stored in an individual JSON file.
  48    type FileContent: Clone + Default + Serialize + DeserializeOwned + JsonSchema;
  49
  50    /// The logic for combining together values from one or more JSON files into the
  51    /// final value for this setting.
  52    fn load(sources: SettingsSources<Self::FileContent>, cx: &mut App) -> Result<Self>
  53    where
  54        Self: Sized;
  55
  56    fn json_schema(
  57        generator: &mut SchemaGenerator,
  58        _: &SettingsJsonSchemaParams,
  59        _: &App,
  60    ) -> RootSchema {
  61        generator.root_schema_for::<Self::FileContent>()
  62    }
  63
  64    fn missing_default() -> anyhow::Error {
  65        anyhow::anyhow!("missing default")
  66    }
  67
  68    #[track_caller]
  69    fn register(cx: &mut App)
  70    where
  71        Self: Sized,
  72    {
  73        SettingsStore::update_global(cx, |store, cx| {
  74            store.register_setting::<Self>(cx);
  75        });
  76    }
  77
  78    #[track_caller]
  79    fn get<'a>(path: Option<SettingsLocation>, cx: &'a App) -> &'a Self
  80    where
  81        Self: Sized,
  82    {
  83        cx.global::<SettingsStore>().get(path)
  84    }
  85
  86    #[track_caller]
  87    fn get_global(cx: &App) -> &Self
  88    where
  89        Self: Sized,
  90    {
  91        cx.global::<SettingsStore>().get(None)
  92    }
  93
  94    #[track_caller]
  95    fn try_read_global<R>(cx: &AsyncApp, f: impl FnOnce(&Self) -> R) -> Option<R>
  96    where
  97        Self: Sized,
  98    {
  99        cx.try_read_global(|s: &SettingsStore, _| f(s.get(None)))
 100    }
 101
 102    #[track_caller]
 103    fn override_global(settings: Self, cx: &mut App)
 104    where
 105        Self: Sized,
 106    {
 107        cx.global_mut::<SettingsStore>().override_global(settings)
 108    }
 109}
 110
 111#[derive(Clone, Copy, Debug)]
 112pub struct SettingsSources<'a, T> {
 113    /// The default Zed settings.
 114    pub default: &'a T,
 115    /// Settings provided by extensions.
 116    pub extensions: Option<&'a T>,
 117    /// The user settings.
 118    pub user: Option<&'a T>,
 119    /// The user settings for the current release channel.
 120    pub release_channel: Option<&'a T>,
 121    /// The server's settings.
 122    pub server: Option<&'a T>,
 123    /// The project settings, ordered from least specific to most specific.
 124    pub project: &'a [&'a T],
 125}
 126
 127impl<'a, T: Serialize> SettingsSources<'a, T> {
 128    /// Returns an iterator over the default settings as well as all settings customizations.
 129    pub fn defaults_and_customizations(&self) -> impl Iterator<Item = &T> {
 130        [self.default].into_iter().chain(self.customizations())
 131    }
 132
 133    /// Returns an iterator over all of the settings customizations.
 134    pub fn customizations(&self) -> impl Iterator<Item = &T> {
 135        self.extensions
 136            .into_iter()
 137            .chain(self.user)
 138            .chain(self.release_channel)
 139            .chain(self.server)
 140            .chain(self.project.iter().copied())
 141    }
 142
 143    /// Returns the settings after performing a JSON merge of the provided customizations.
 144    ///
 145    /// Customizations later in the iterator win out over the earlier ones.
 146    pub fn json_merge_with<O: DeserializeOwned>(
 147        customizations: impl Iterator<Item = &'a T>,
 148    ) -> Result<O> {
 149        let mut merged = serde_json::Value::Null;
 150        for value in customizations {
 151            merge_non_null_json_value_into(serde_json::to_value(value).unwrap(), &mut merged);
 152        }
 153        Ok(serde_json::from_value(merged)?)
 154    }
 155
 156    /// Returns the settings after performing a JSON merge of the customizations into the
 157    /// default settings.
 158    ///
 159    /// More-specific customizations win out over the less-specific ones.
 160    pub fn json_merge<O: DeserializeOwned>(&'a self) -> Result<O> {
 161        Self::json_merge_with(self.defaults_and_customizations())
 162    }
 163}
 164
 165#[derive(Clone, Copy, Debug)]
 166pub struct SettingsLocation<'a> {
 167    pub worktree_id: WorktreeId,
 168    pub path: &'a Path,
 169}
 170
 171/// A set of strongly-typed setting values defined via multiple config files.
 172pub struct SettingsStore {
 173    setting_values: HashMap<TypeId, Box<dyn AnySettingValue>>,
 174    raw_default_settings: serde_json::Value,
 175    raw_user_settings: serde_json::Value,
 176    raw_server_settings: Option<serde_json::Value>,
 177    raw_extension_settings: serde_json::Value,
 178    raw_local_settings: BTreeMap<(WorktreeId, Arc<Path>), serde_json::Value>,
 179    raw_editorconfig_settings: BTreeMap<(WorktreeId, Arc<Path>), (String, Option<Editorconfig>)>,
 180    tab_size_callback: Option<(
 181        TypeId,
 182        Box<dyn Fn(&dyn Any) -> Option<usize> + Send + Sync + 'static>,
 183    )>,
 184    _setting_file_updates: Task<()>,
 185    setting_file_updates_tx:
 186        mpsc::UnboundedSender<Box<dyn FnOnce(AsyncApp) -> LocalBoxFuture<'static, Result<()>>>>,
 187}
 188
 189#[derive(Clone)]
 190pub struct Editorconfig {
 191    pub is_root: bool,
 192    pub sections: SmallVec<[Section; 5]>,
 193}
 194
 195impl FromStr for Editorconfig {
 196    type Err = anyhow::Error;
 197
 198    fn from_str(contents: &str) -> Result<Self, Self::Err> {
 199        let parser = ConfigParser::new_buffered(contents.as_bytes())
 200            .context("creating editorconfig parser")?;
 201        let is_root = parser.is_root;
 202        let sections = parser
 203            .collect::<Result<SmallVec<_>, _>>()
 204            .context("parsing editorconfig sections")?;
 205        Ok(Self { is_root, sections })
 206    }
 207}
 208
 209#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
 210pub enum LocalSettingsKind {
 211    Settings,
 212    Tasks,
 213    Editorconfig,
 214}
 215
 216impl Global for SettingsStore {}
 217
 218#[derive(Debug)]
 219struct SettingValue<T> {
 220    global_value: Option<T>,
 221    local_values: Vec<(WorktreeId, Arc<Path>, T)>,
 222}
 223
 224trait AnySettingValue: 'static + Send + Sync {
 225    fn key(&self) -> Option<&'static str>;
 226    fn setting_type_name(&self) -> &'static str;
 227    fn deserialize_setting(&self, json: &serde_json::Value) -> Result<DeserializedSetting>;
 228    fn load_setting(
 229        &self,
 230        sources: SettingsSources<DeserializedSetting>,
 231        cx: &mut App,
 232    ) -> Result<Box<dyn Any>>;
 233    fn value_for_path(&self, path: Option<SettingsLocation>) -> &dyn Any;
 234    fn set_global_value(&mut self, value: Box<dyn Any>);
 235    fn set_local_value(&mut self, root_id: WorktreeId, path: Arc<Path>, value: Box<dyn Any>);
 236    fn json_schema(
 237        &self,
 238        generator: &mut SchemaGenerator,
 239        _: &SettingsJsonSchemaParams,
 240        cx: &App,
 241    ) -> RootSchema;
 242}
 243
 244struct DeserializedSetting(Box<dyn Any>);
 245
 246impl SettingsStore {
 247    pub fn new(cx: &App) -> Self {
 248        let (setting_file_updates_tx, mut setting_file_updates_rx) = mpsc::unbounded();
 249        Self {
 250            setting_values: Default::default(),
 251            raw_default_settings: serde_json::json!({}),
 252            raw_user_settings: serde_json::json!({}),
 253            raw_server_settings: None,
 254            raw_extension_settings: serde_json::json!({}),
 255            raw_local_settings: Default::default(),
 256            raw_editorconfig_settings: BTreeMap::default(),
 257            tab_size_callback: Default::default(),
 258            setting_file_updates_tx,
 259            _setting_file_updates: cx.spawn(|cx| async move {
 260                while let Some(setting_file_update) = setting_file_updates_rx.next().await {
 261                    (setting_file_update)(cx.clone()).await.log_err();
 262                }
 263            }),
 264        }
 265    }
 266
 267    pub fn update<C, R>(cx: &mut C, f: impl FnOnce(&mut Self, &mut C) -> R) -> R
 268    where
 269        C: BorrowAppContext,
 270    {
 271        cx.update_global(f)
 272    }
 273
 274    /// Add a new type of setting to the store.
 275    pub fn register_setting<T: Settings>(&mut self, cx: &mut App) {
 276        let setting_type_id = TypeId::of::<T>();
 277        let entry = self.setting_values.entry(setting_type_id);
 278
 279        if matches!(entry, hash_map::Entry::Occupied(_)) {
 280            return;
 281        }
 282
 283        let setting_value = entry.or_insert(Box::new(SettingValue::<T> {
 284            global_value: None,
 285            local_values: Vec::new(),
 286        }));
 287
 288        if let Some(default_settings) = setting_value
 289            .deserialize_setting(&self.raw_default_settings)
 290            .log_err()
 291        {
 292            let user_value = setting_value
 293                .deserialize_setting(&self.raw_user_settings)
 294                .log_err();
 295
 296            let mut release_channel_value = None;
 297            if let Some(release_settings) = &self
 298                .raw_user_settings
 299                .get(release_channel::RELEASE_CHANNEL.dev_name())
 300            {
 301                release_channel_value = setting_value
 302                    .deserialize_setting(release_settings)
 303                    .log_err();
 304            }
 305
 306            let server_value = self
 307                .raw_server_settings
 308                .as_ref()
 309                .and_then(|server_setting| {
 310                    setting_value.deserialize_setting(server_setting).log_err()
 311                });
 312
 313            let extension_value = setting_value
 314                .deserialize_setting(&self.raw_extension_settings)
 315                .log_err();
 316
 317            if let Some(setting) = setting_value
 318                .load_setting(
 319                    SettingsSources {
 320                        default: &default_settings,
 321                        extensions: extension_value.as_ref(),
 322                        user: user_value.as_ref(),
 323                        release_channel: release_channel_value.as_ref(),
 324                        server: server_value.as_ref(),
 325                        project: &[],
 326                    },
 327                    cx,
 328                )
 329                .context("A default setting must be added to the `default.json` file")
 330                .log_err()
 331            {
 332                setting_value.set_global_value(setting);
 333            }
 334        }
 335    }
 336
 337    /// Get the value of a setting.
 338    ///
 339    /// Panics if the given setting type has not been registered, or if there is no
 340    /// value for this setting.
 341    pub fn get<T: Settings>(&self, path: Option<SettingsLocation>) -> &T {
 342        self.setting_values
 343            .get(&TypeId::of::<T>())
 344            .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()))
 345            .value_for_path(path)
 346            .downcast_ref::<T>()
 347            .expect("no default value for setting type")
 348    }
 349
 350    /// Override the global value for a setting.
 351    ///
 352    /// The given value will be overwritten if the user settings file changes.
 353    pub fn override_global<T: Settings>(&mut self, value: T) {
 354        self.setting_values
 355            .get_mut(&TypeId::of::<T>())
 356            .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()))
 357            .set_global_value(Box::new(value))
 358    }
 359
 360    /// Get the user's settings as a raw JSON value.
 361    ///
 362    /// For user-facing functionality use the typed setting interface.
 363    /// (e.g. ProjectSettings::get_global(cx))
 364    pub fn raw_user_settings(&self) -> &serde_json::Value {
 365        &self.raw_user_settings
 366    }
 367
 368    #[cfg(any(test, feature = "test-support"))]
 369    pub fn test(cx: &mut App) -> Self {
 370        let mut this = Self::new(cx);
 371        this.set_default_settings(&crate::test_settings(), cx)
 372            .unwrap();
 373        this.set_user_settings("{}", cx).unwrap();
 374        this
 375    }
 376
 377    /// Updates the value of a setting in the user's global configuration.
 378    ///
 379    /// This is only for tests. Normally, settings are only loaded from
 380    /// JSON files.
 381    #[cfg(any(test, feature = "test-support"))]
 382    pub fn update_user_settings<T: Settings>(
 383        &mut self,
 384        cx: &mut App,
 385        update: impl FnOnce(&mut T::FileContent),
 386    ) {
 387        let old_text = serde_json::to_string(&self.raw_user_settings).unwrap();
 388        let new_text = self.new_text_for_update::<T>(old_text, update);
 389        self.set_user_settings(&new_text, cx).unwrap();
 390    }
 391
 392    async fn load_settings(fs: &Arc<dyn Fs>) -> Result<String> {
 393        match fs.load(paths::settings_file()).await {
 394            result @ Ok(_) => result,
 395            Err(err) => {
 396                if let Some(e) = err.downcast_ref::<std::io::Error>() {
 397                    if e.kind() == std::io::ErrorKind::NotFound {
 398                        return Ok(crate::initial_user_settings_content().to_string());
 399                    }
 400                }
 401                Err(err)
 402            }
 403        }
 404    }
 405
 406    pub fn update_settings_file<T: Settings>(
 407        &self,
 408        fs: Arc<dyn Fs>,
 409        update: impl 'static + Send + FnOnce(&mut T::FileContent, &App),
 410    ) {
 411        self.setting_file_updates_tx
 412            .unbounded_send(Box::new(move |cx: AsyncApp| {
 413                async move {
 414                    let old_text = Self::load_settings(&fs).await?;
 415                    let new_text = cx.read_global(|store: &SettingsStore, cx| {
 416                        store.new_text_for_update::<T>(old_text, |content| update(content, cx))
 417                    })?;
 418                    let initial_path = paths::settings_file().as_path();
 419                    if fs.is_file(initial_path).await {
 420                        let resolved_path =
 421                            fs.canonicalize(initial_path).await.with_context(|| {
 422                                format!("Failed to canonicalize settings path {:?}", initial_path)
 423                            })?;
 424
 425                        fs.atomic_write(resolved_path.clone(), new_text)
 426                            .await
 427                            .with_context(|| {
 428                                format!("Failed to write settings to file {:?}", resolved_path)
 429                            })?;
 430                    } else {
 431                        fs.atomic_write(initial_path.to_path_buf(), new_text)
 432                            .await
 433                            .with_context(|| {
 434                                format!("Failed to write settings to file {:?}", initial_path)
 435                            })?;
 436                    }
 437
 438                    anyhow::Ok(())
 439                }
 440                .boxed_local()
 441            }))
 442            .ok();
 443    }
 444
 445    /// Updates the value of a setting in a JSON file, returning the new text
 446    /// for that JSON file.
 447    pub fn new_text_for_update<T: Settings>(
 448        &self,
 449        old_text: String,
 450        update: impl FnOnce(&mut T::FileContent),
 451    ) -> String {
 452        let edits = self.edits_for_update::<T>(&old_text, update);
 453        let mut new_text = old_text;
 454        for (range, replacement) in edits.into_iter() {
 455            new_text.replace_range(range, &replacement);
 456        }
 457        new_text
 458    }
 459
 460    /// Updates the value of a setting in a JSON file, returning a list
 461    /// of edits to apply to the JSON file.
 462    pub fn edits_for_update<T: Settings>(
 463        &self,
 464        text: &str,
 465        update: impl FnOnce(&mut T::FileContent),
 466    ) -> Vec<(Range<usize>, String)> {
 467        let setting_type_id = TypeId::of::<T>();
 468
 469        let preserved_keys = T::PRESERVED_KEYS.unwrap_or_default();
 470
 471        let setting = self
 472            .setting_values
 473            .get(&setting_type_id)
 474            .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()));
 475        let raw_settings = parse_json_with_comments::<serde_json::Value>(text).unwrap_or_default();
 476        let old_content = match setting.deserialize_setting(&raw_settings) {
 477            Ok(content) => content.0.downcast::<T::FileContent>().unwrap(),
 478            Err(_) => Box::<<T as Settings>::FileContent>::default(),
 479        };
 480        let mut new_content = old_content.clone();
 481        update(&mut new_content);
 482
 483        let old_value = serde_json::to_value(&old_content).unwrap();
 484        let new_value = serde_json::to_value(new_content).unwrap();
 485
 486        let mut key_path = Vec::new();
 487        if let Some(key) = T::KEY {
 488            key_path.push(key);
 489        }
 490
 491        let mut edits = Vec::new();
 492        let tab_size = self.json_tab_size();
 493        let mut text = text.to_string();
 494        update_value_in_json_text(
 495            &mut text,
 496            &mut key_path,
 497            tab_size,
 498            &old_value,
 499            &new_value,
 500            preserved_keys,
 501            &mut edits,
 502        );
 503        edits
 504    }
 505
 506    /// Configure the tab sized when updating JSON files.
 507    pub fn set_json_tab_size_callback<T: Settings>(
 508        &mut self,
 509        get_tab_size: fn(&T) -> Option<usize>,
 510    ) {
 511        self.tab_size_callback = Some((
 512            TypeId::of::<T>(),
 513            Box::new(move |value| get_tab_size(value.downcast_ref::<T>().unwrap())),
 514        ));
 515    }
 516
 517    fn json_tab_size(&self) -> usize {
 518        const DEFAULT_JSON_TAB_SIZE: usize = 2;
 519
 520        if let Some((setting_type_id, callback)) = &self.tab_size_callback {
 521            let setting_value = self.setting_values.get(setting_type_id).unwrap();
 522            let value = setting_value.value_for_path(None);
 523            if let Some(value) = callback(value) {
 524                return value;
 525            }
 526        }
 527
 528        DEFAULT_JSON_TAB_SIZE
 529    }
 530
 531    /// Sets the default settings via a JSON string.
 532    ///
 533    /// The string should contain a JSON object with a default value for every setting.
 534    pub fn set_default_settings(
 535        &mut self,
 536        default_settings_content: &str,
 537        cx: &mut App,
 538    ) -> Result<()> {
 539        let settings: serde_json::Value = parse_json_with_comments(default_settings_content)?;
 540        if settings.is_object() {
 541            self.raw_default_settings = settings;
 542            self.recompute_values(None, cx)?;
 543            Ok(())
 544        } else {
 545            Err(anyhow!("settings must be an object"))
 546        }
 547    }
 548
 549    /// Sets the user settings via a JSON string.
 550    pub fn set_user_settings(
 551        &mut self,
 552        user_settings_content: &str,
 553        cx: &mut App,
 554    ) -> Result<serde_json::Value> {
 555        let settings: serde_json::Value = if user_settings_content.is_empty() {
 556            parse_json_with_comments("{}")?
 557        } else {
 558            parse_json_with_comments(user_settings_content)?
 559        };
 560
 561        anyhow::ensure!(settings.is_object(), "settings must be an object");
 562        self.raw_user_settings = settings.clone();
 563        self.recompute_values(None, cx)?;
 564        Ok(settings)
 565    }
 566
 567    pub fn set_server_settings(
 568        &mut self,
 569        server_settings_content: &str,
 570        cx: &mut App,
 571    ) -> Result<()> {
 572        let settings: Option<serde_json::Value> = if server_settings_content.is_empty() {
 573            None
 574        } else {
 575            parse_json_with_comments(server_settings_content)?
 576        };
 577
 578        anyhow::ensure!(
 579            settings
 580                .as_ref()
 581                .map(|value| value.is_object())
 582                .unwrap_or(true),
 583            "settings must be an object"
 584        );
 585        self.raw_server_settings = settings;
 586        self.recompute_values(None, cx)?;
 587        Ok(())
 588    }
 589
 590    /// Add or remove a set of local settings via a JSON string.
 591    pub fn set_local_settings(
 592        &mut self,
 593        root_id: WorktreeId,
 594        directory_path: Arc<Path>,
 595        kind: LocalSettingsKind,
 596        settings_content: Option<&str>,
 597        cx: &mut App,
 598    ) -> std::result::Result<(), InvalidSettingsError> {
 599        let mut zed_settings_changed = false;
 600        match (
 601            kind,
 602            settings_content
 603                .map(|content| content.trim())
 604                .filter(|content| !content.is_empty()),
 605        ) {
 606            (LocalSettingsKind::Tasks, _) => {
 607                return Err(InvalidSettingsError::Tasks {
 608                    message: "Attempted to submit tasks into the settings store".to_string(),
 609                })
 610            }
 611            (LocalSettingsKind::Settings, None) => {
 612                zed_settings_changed = self
 613                    .raw_local_settings
 614                    .remove(&(root_id, directory_path.clone()))
 615                    .is_some()
 616            }
 617            (LocalSettingsKind::Editorconfig, None) => {
 618                self.raw_editorconfig_settings
 619                    .remove(&(root_id, directory_path.clone()));
 620            }
 621            (LocalSettingsKind::Settings, Some(settings_contents)) => {
 622                let new_settings = parse_json_with_comments::<serde_json::Value>(settings_contents)
 623                    .map_err(|e| InvalidSettingsError::LocalSettings {
 624                        path: directory_path.join(local_settings_file_relative_path()),
 625                        message: e.to_string(),
 626                    })?;
 627                match self
 628                    .raw_local_settings
 629                    .entry((root_id, directory_path.clone()))
 630                {
 631                    btree_map::Entry::Vacant(v) => {
 632                        v.insert(new_settings);
 633                        zed_settings_changed = true;
 634                    }
 635                    btree_map::Entry::Occupied(mut o) => {
 636                        if o.get() != &new_settings {
 637                            o.insert(new_settings);
 638                            zed_settings_changed = true;
 639                        }
 640                    }
 641                }
 642            }
 643            (LocalSettingsKind::Editorconfig, Some(editorconfig_contents)) => {
 644                match self
 645                    .raw_editorconfig_settings
 646                    .entry((root_id, directory_path.clone()))
 647                {
 648                    btree_map::Entry::Vacant(v) => match editorconfig_contents.parse() {
 649                        Ok(new_contents) => {
 650                            v.insert((editorconfig_contents.to_owned(), Some(new_contents)));
 651                        }
 652                        Err(e) => {
 653                            v.insert((editorconfig_contents.to_owned(), None));
 654                            return Err(InvalidSettingsError::Editorconfig {
 655                                message: e.to_string(),
 656                                path: directory_path.join(EDITORCONFIG_NAME),
 657                            });
 658                        }
 659                    },
 660                    btree_map::Entry::Occupied(mut o) => {
 661                        if o.get().0 != editorconfig_contents {
 662                            match editorconfig_contents.parse() {
 663                                Ok(new_contents) => {
 664                                    o.insert((
 665                                        editorconfig_contents.to_owned(),
 666                                        Some(new_contents),
 667                                    ));
 668                                }
 669                                Err(e) => {
 670                                    o.insert((editorconfig_contents.to_owned(), None));
 671                                    return Err(InvalidSettingsError::Editorconfig {
 672                                        message: e.to_string(),
 673                                        path: directory_path.join(EDITORCONFIG_NAME),
 674                                    });
 675                                }
 676                            }
 677                        }
 678                    }
 679                }
 680            }
 681        };
 682
 683        if zed_settings_changed {
 684            self.recompute_values(Some((root_id, &directory_path)), cx)?;
 685        }
 686        Ok(())
 687    }
 688
 689    pub fn set_extension_settings<T: Serialize>(&mut self, content: T, cx: &mut App) -> Result<()> {
 690        let settings: serde_json::Value = serde_json::to_value(content)?;
 691        anyhow::ensure!(settings.is_object(), "settings must be an object");
 692        self.raw_extension_settings = settings;
 693        self.recompute_values(None, cx)?;
 694        Ok(())
 695    }
 696
 697    /// Add or remove a set of local settings via a JSON string.
 698    pub fn clear_local_settings(&mut self, root_id: WorktreeId, cx: &mut App) -> Result<()> {
 699        self.raw_local_settings
 700            .retain(|(worktree_id, _), _| worktree_id != &root_id);
 701        self.recompute_values(Some((root_id, "".as_ref())), cx)?;
 702        Ok(())
 703    }
 704
 705    pub fn local_settings(
 706        &self,
 707        root_id: WorktreeId,
 708    ) -> impl '_ + Iterator<Item = (Arc<Path>, String)> {
 709        self.raw_local_settings
 710            .range(
 711                (root_id, Path::new("").into())
 712                    ..(
 713                        WorktreeId::from_usize(root_id.to_usize() + 1),
 714                        Path::new("").into(),
 715                    ),
 716            )
 717            .map(|((_, path), content)| (path.clone(), serde_json::to_string(content).unwrap()))
 718    }
 719
 720    pub fn local_editorconfig_settings(
 721        &self,
 722        root_id: WorktreeId,
 723    ) -> impl '_ + Iterator<Item = (Arc<Path>, String, Option<Editorconfig>)> {
 724        self.raw_editorconfig_settings
 725            .range(
 726                (root_id, Path::new("").into())
 727                    ..(
 728                        WorktreeId::from_usize(root_id.to_usize() + 1),
 729                        Path::new("").into(),
 730                    ),
 731            )
 732            .map(|((_, path), (content, parsed_content))| {
 733                (path.clone(), content.clone(), parsed_content.clone())
 734            })
 735    }
 736
 737    pub fn json_schema(
 738        &self,
 739        schema_params: &SettingsJsonSchemaParams,
 740        cx: &App,
 741    ) -> serde_json::Value {
 742        use schemars::{
 743            gen::SchemaSettings,
 744            schema::{Schema, SchemaObject},
 745        };
 746
 747        let settings = SchemaSettings::draft07().with(|settings| {
 748            settings.option_add_null_type = true;
 749        });
 750        let mut generator = SchemaGenerator::new(settings);
 751        let mut combined_schema = RootSchema::default();
 752
 753        for setting_value in self.setting_values.values() {
 754            let setting_schema = setting_value.json_schema(&mut generator, schema_params, cx);
 755            combined_schema
 756                .definitions
 757                .extend(setting_schema.definitions);
 758
 759            let target_schema = if let Some(key) = setting_value.key() {
 760                let key_schema = combined_schema
 761                    .schema
 762                    .object()
 763                    .properties
 764                    .entry(key.to_string())
 765                    .or_insert_with(|| Schema::Object(SchemaObject::default()));
 766                if let Schema::Object(key_schema) = key_schema {
 767                    key_schema
 768                } else {
 769                    continue;
 770                }
 771            } else {
 772                &mut combined_schema.schema
 773            };
 774
 775            merge_schema(target_schema, setting_schema.schema);
 776        }
 777
 778        fn merge_schema(target: &mut SchemaObject, mut source: SchemaObject) {
 779            let source_subschemas = source.subschemas();
 780            let target_subschemas = target.subschemas();
 781            if let Some(all_of) = source_subschemas.all_of.take() {
 782                target_subschemas
 783                    .all_of
 784                    .get_or_insert(Vec::new())
 785                    .extend(all_of);
 786            }
 787            if let Some(any_of) = source_subschemas.any_of.take() {
 788                target_subschemas
 789                    .any_of
 790                    .get_or_insert(Vec::new())
 791                    .extend(any_of);
 792            }
 793            if let Some(one_of) = source_subschemas.one_of.take() {
 794                target_subschemas
 795                    .one_of
 796                    .get_or_insert(Vec::new())
 797                    .extend(one_of);
 798            }
 799
 800            if let Some(source) = source.object {
 801                let target_properties = &mut target.object().properties;
 802                for (key, value) in source.properties {
 803                    match target_properties.entry(key) {
 804                        btree_map::Entry::Vacant(e) => {
 805                            e.insert(value);
 806                        }
 807                        btree_map::Entry::Occupied(e) => {
 808                            if let (Schema::Object(target), Schema::Object(src)) =
 809                                (e.into_mut(), value)
 810                            {
 811                                merge_schema(target, src);
 812                            }
 813                        }
 814                    }
 815                }
 816            }
 817
 818            overwrite(&mut target.instance_type, source.instance_type);
 819            overwrite(&mut target.string, source.string);
 820            overwrite(&mut target.number, source.number);
 821            overwrite(&mut target.reference, source.reference);
 822            overwrite(&mut target.array, source.array);
 823            overwrite(&mut target.enum_values, source.enum_values);
 824
 825            fn overwrite<T>(target: &mut Option<T>, source: Option<T>) {
 826                if let Some(source) = source {
 827                    *target = Some(source);
 828                }
 829            }
 830        }
 831
 832        for release_stage in ["dev", "nightly", "stable", "preview"] {
 833            let schema = combined_schema.schema.clone();
 834            combined_schema
 835                .schema
 836                .object()
 837                .properties
 838                .insert(release_stage.to_string(), schema.into());
 839        }
 840
 841        serde_json::to_value(&combined_schema).unwrap()
 842    }
 843
 844    fn recompute_values(
 845        &mut self,
 846        changed_local_path: Option<(WorktreeId, &Path)>,
 847        cx: &mut App,
 848    ) -> std::result::Result<(), InvalidSettingsError> {
 849        // Reload the global and local values for every setting.
 850        let mut project_settings_stack = Vec::<DeserializedSetting>::new();
 851        let mut paths_stack = Vec::<Option<(WorktreeId, &Path)>>::new();
 852        for setting_value in self.setting_values.values_mut() {
 853            let default_settings = setting_value
 854                .deserialize_setting(&self.raw_default_settings)
 855                .map_err(|e| InvalidSettingsError::DefaultSettings {
 856                    message: e.to_string(),
 857                })?;
 858
 859            let extension_settings = setting_value
 860                .deserialize_setting(&self.raw_extension_settings)
 861                .log_err();
 862
 863            let user_settings = match setting_value.deserialize_setting(&self.raw_user_settings) {
 864                Ok(settings) => Some(settings),
 865                Err(error) => {
 866                    return Err(InvalidSettingsError::UserSettings {
 867                        message: error.to_string(),
 868                    });
 869                }
 870            };
 871
 872            let server_settings = self
 873                .raw_server_settings
 874                .as_ref()
 875                .and_then(|setting| setting_value.deserialize_setting(setting).log_err());
 876
 877            let mut release_channel_settings = None;
 878            if let Some(release_settings) = &self
 879                .raw_user_settings
 880                .get(release_channel::RELEASE_CHANNEL.dev_name())
 881            {
 882                if let Some(release_settings) = setting_value
 883                    .deserialize_setting(release_settings)
 884                    .log_err()
 885                {
 886                    release_channel_settings = Some(release_settings);
 887                }
 888            }
 889
 890            // If the global settings file changed, reload the global value for the field.
 891            if changed_local_path.is_none() {
 892                if let Some(value) = setting_value
 893                    .load_setting(
 894                        SettingsSources {
 895                            default: &default_settings,
 896                            extensions: extension_settings.as_ref(),
 897                            user: user_settings.as_ref(),
 898                            release_channel: release_channel_settings.as_ref(),
 899                            server: server_settings.as_ref(),
 900                            project: &[],
 901                        },
 902                        cx,
 903                    )
 904                    .log_err()
 905                {
 906                    setting_value.set_global_value(value);
 907                }
 908            }
 909
 910            // Reload the local values for the setting.
 911            paths_stack.clear();
 912            project_settings_stack.clear();
 913            for ((root_id, directory_path), local_settings) in &self.raw_local_settings {
 914                // Build a stack of all of the local values for that setting.
 915                while let Some(prev_entry) = paths_stack.last() {
 916                    if let Some((prev_root_id, prev_path)) = prev_entry {
 917                        if root_id != prev_root_id || !directory_path.starts_with(prev_path) {
 918                            paths_stack.pop();
 919                            project_settings_stack.pop();
 920                            continue;
 921                        }
 922                    }
 923                    break;
 924                }
 925
 926                match setting_value.deserialize_setting(local_settings) {
 927                    Ok(local_settings) => {
 928                        paths_stack.push(Some((*root_id, directory_path.as_ref())));
 929                        project_settings_stack.push(local_settings);
 930
 931                        // If a local settings file changed, then avoid recomputing local
 932                        // settings for any path outside of that directory.
 933                        if changed_local_path.map_or(
 934                            false,
 935                            |(changed_root_id, changed_local_path)| {
 936                                *root_id != changed_root_id
 937                                    || !directory_path.starts_with(changed_local_path)
 938                            },
 939                        ) {
 940                            continue;
 941                        }
 942
 943                        if let Some(value) = setting_value
 944                            .load_setting(
 945                                SettingsSources {
 946                                    default: &default_settings,
 947                                    extensions: extension_settings.as_ref(),
 948                                    user: user_settings.as_ref(),
 949                                    release_channel: release_channel_settings.as_ref(),
 950                                    server: server_settings.as_ref(),
 951                                    project: &project_settings_stack.iter().collect::<Vec<_>>(),
 952                                },
 953                                cx,
 954                            )
 955                            .log_err()
 956                        {
 957                            setting_value.set_local_value(*root_id, directory_path.clone(), value);
 958                        }
 959                    }
 960                    Err(error) => {
 961                        return Err(InvalidSettingsError::LocalSettings {
 962                            path: directory_path.join(local_settings_file_relative_path()),
 963                            message: error.to_string(),
 964                        });
 965                    }
 966                }
 967            }
 968        }
 969        Ok(())
 970    }
 971
 972    pub fn editorconfig_properties(
 973        &self,
 974        for_worktree: WorktreeId,
 975        for_path: &Path,
 976    ) -> Option<EditorconfigProperties> {
 977        let mut properties = EditorconfigProperties::new();
 978
 979        for (directory_with_config, _, parsed_editorconfig) in
 980            self.local_editorconfig_settings(for_worktree)
 981        {
 982            if !for_path.starts_with(&directory_with_config) {
 983                properties.use_fallbacks();
 984                return Some(properties);
 985            }
 986            let parsed_editorconfig = parsed_editorconfig?;
 987            if parsed_editorconfig.is_root {
 988                properties = EditorconfigProperties::new();
 989            }
 990            for section in parsed_editorconfig.sections {
 991                section.apply_to(&mut properties, for_path).log_err()?;
 992            }
 993        }
 994
 995        properties.use_fallbacks();
 996        Some(properties)
 997    }
 998
 999    pub fn should_migrate_settings(settings: &serde_json::Value) -> bool {
1000        let Ok(old_text) = serde_json::to_string(settings) else {
1001            return false;
1002        };
1003        migrate_settings(&old_text).is_some()
1004    }
1005
1006    pub fn migrate_settings(&self, fs: Arc<dyn Fs>) {
1007        self.setting_file_updates_tx
1008            .unbounded_send(Box::new(move |_: AsyncApp| {
1009                async move {
1010                    let old_text = Self::load_settings(&fs).await?;
1011                    let Some(new_text) = migrate_settings(&old_text) else {
1012                        return anyhow::Ok(());
1013                    };
1014                    let initial_path = paths::settings_file().as_path();
1015                    if fs.is_file(initial_path).await {
1016                        let backup_path = paths::home_dir().join(".zed_settings_backup");
1017                        fs.atomic_write(backup_path, 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(initial_path).await.with_context(|| {
1024                                format!("Failed to canonicalize settings path {:?}", initial_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(initial_path.to_path_buf(), new_text)
1033                            .await
1034                            .with_context(|| {
1035                                format!("Failed to write settings to file {:?}", initial_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 matches = cursor.matches(&PAIR_QUERY, syntax_tree.root_node(), text.as_bytes());
1267    for mat in matches {
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}