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