settings_store.rs

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