settings_store.rs

   1use anyhow::Result;
   2use collections::{btree_map, hash_map, BTreeMap, HashMap};
   3use gpui::AppContext;
   4use lazy_static::lazy_static;
   5use schemars::{gen::SchemaGenerator, schema::RootSchema, JsonSchema};
   6use serde::{de::DeserializeOwned, Deserialize as _, Serialize};
   7use smallvec::SmallVec;
   8use std::{
   9    any::{type_name, Any, TypeId},
  10    fmt::Debug,
  11    ops::Range,
  12    path::Path,
  13    str,
  14    sync::Arc,
  15};
  16use util::{merge_non_null_json_value_into, RangeExt, ResultExt as _};
  17
  18/// A value that can be defined as a user setting.
  19///
  20/// Settings can be loaded from a combination of multiple JSON files.
  21pub trait Setting: 'static {
  22    /// The name of a key within the JSON file from which this setting should
  23    /// be deserialized. If this is `None`, then the setting will be deserialized
  24    /// from the root object.
  25    const KEY: Option<&'static str>;
  26
  27    /// The type that is stored in an individual JSON file.
  28    type FileContent: Clone + Serialize + DeserializeOwned + JsonSchema;
  29
  30    /// The logic for combining together values from one or more JSON files into the
  31    /// final value for this setting.
  32    ///
  33    /// The user values are ordered from least specific (the global settings file)
  34    /// to most specific (the innermost local settings file).
  35    fn load(
  36        default_value: &Self::FileContent,
  37        user_values: &[&Self::FileContent],
  38        cx: &AppContext,
  39    ) -> Result<Self>
  40    where
  41        Self: Sized;
  42
  43    fn json_schema(generator: &mut SchemaGenerator, _: &SettingsJsonSchemaParams) -> RootSchema {
  44        generator.root_schema_for::<Self::FileContent>()
  45    }
  46
  47    fn json_merge(
  48        default_value: &Self::FileContent,
  49        user_values: &[&Self::FileContent],
  50    ) -> Result<Self::FileContent> {
  51        let mut merged = serde_json::Value::Null;
  52        for value in [default_value].iter().chain(user_values) {
  53            merge_non_null_json_value_into(serde_json::to_value(value).unwrap(), &mut merged);
  54        }
  55        Ok(serde_json::from_value(merged)?)
  56    }
  57
  58    fn load_via_json_merge(
  59        default_value: &Self::FileContent,
  60        user_values: &[&Self::FileContent],
  61    ) -> Result<Self>
  62    where
  63        Self: DeserializeOwned,
  64    {
  65        let mut merged = serde_json::Value::Null;
  66        for value in [default_value].iter().chain(user_values) {
  67            merge_non_null_json_value_into(serde_json::to_value(value).unwrap(), &mut merged);
  68        }
  69        Ok(serde_json::from_value(merged)?)
  70    }
  71
  72    fn missing_default() -> anyhow::Error {
  73        anyhow::anyhow!("missing default")
  74    }
  75}
  76
  77pub struct SettingsJsonSchemaParams<'a> {
  78    pub theme_names: &'a [String],
  79    pub language_names: &'a [String],
  80}
  81
  82/// A set of strongly-typed setting values defined via multiple JSON files.
  83#[derive(Default)]
  84pub struct SettingsStore {
  85    setting_values: HashMap<TypeId, Box<dyn AnySettingValue>>,
  86    default_deserialized_settings: Option<serde_json::Value>,
  87    user_deserialized_settings: Option<serde_json::Value>,
  88    local_deserialized_settings: BTreeMap<Arc<Path>, serde_json::Value>,
  89    tab_size_callback: Option<(TypeId, Box<dyn Fn(&dyn Any) -> Option<usize>>)>,
  90}
  91
  92#[derive(Debug)]
  93struct SettingValue<T> {
  94    global_value: Option<T>,
  95    local_values: Vec<(Arc<Path>, T)>,
  96}
  97
  98trait AnySettingValue {
  99    fn key(&self) -> Option<&'static str>;
 100    fn setting_type_name(&self) -> &'static str;
 101    fn deserialize_setting(&self, json: &serde_json::Value) -> Result<DeserializedSetting>;
 102    fn load_setting(
 103        &self,
 104        default_value: &DeserializedSetting,
 105        custom: &[DeserializedSetting],
 106        cx: &AppContext,
 107    ) -> Result<Box<dyn Any>>;
 108    fn value_for_path(&self, path: Option<&Path>) -> &dyn Any;
 109    fn set_global_value(&mut self, value: Box<dyn Any>);
 110    fn set_local_value(&mut self, path: Arc<Path>, value: Box<dyn Any>);
 111    fn json_schema(
 112        &self,
 113        generator: &mut SchemaGenerator,
 114        _: &SettingsJsonSchemaParams,
 115    ) -> RootSchema;
 116}
 117
 118struct DeserializedSetting(Box<dyn Any>);
 119
 120impl SettingsStore {
 121    /// Add a new type of setting to the store.
 122    pub fn register_setting<T: Setting>(&mut self, cx: &AppContext) {
 123        let setting_type_id = TypeId::of::<T>();
 124        let entry = self.setting_values.entry(setting_type_id);
 125        if matches!(entry, hash_map::Entry::Occupied(_)) {
 126            return;
 127        }
 128
 129        let setting_value = entry.or_insert(Box::new(SettingValue::<T> {
 130            global_value: None,
 131            local_values: Vec::new(),
 132        }));
 133
 134        if let Some(default_settings) = &self.default_deserialized_settings {
 135            if let Some(default_settings) = setting_value
 136                .deserialize_setting(default_settings)
 137                .log_err()
 138            {
 139                let mut user_values_stack = Vec::new();
 140
 141                if let Some(user_settings) = &self.user_deserialized_settings {
 142                    if let Some(user_settings) =
 143                        setting_value.deserialize_setting(user_settings).log_err()
 144                    {
 145                        user_values_stack = vec![user_settings];
 146                    }
 147                }
 148
 149                if let Some(setting) = setting_value
 150                    .load_setting(&default_settings, &user_values_stack, cx)
 151                    .log_err()
 152                {
 153                    setting_value.set_global_value(setting);
 154                }
 155            }
 156        }
 157    }
 158
 159    /// Get the value of a setting.
 160    ///
 161    /// Panics if the given setting type has not been registered, or if there is no
 162    /// value for this setting.
 163    pub fn get<T: Setting>(&self, path: Option<&Path>) -> &T {
 164        self.setting_values
 165            .get(&TypeId::of::<T>())
 166            .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()))
 167            .value_for_path(path)
 168            .downcast_ref::<T>()
 169            .expect("no default value for setting type")
 170    }
 171
 172    /// Get the user's settings as a raw JSON value.
 173    ///
 174    /// This is only for debugging and reporting. For user-facing functionality,
 175    /// use the typed setting interface.
 176    pub fn untyped_user_settings(&self) -> &serde_json::Value {
 177        self.user_deserialized_settings
 178            .as_ref()
 179            .unwrap_or(&serde_json::Value::Null)
 180    }
 181
 182    #[cfg(any(test, feature = "test-support"))]
 183    pub fn test(cx: &AppContext) -> Self {
 184        let mut this = Self::default();
 185        this.set_default_settings(&crate::test_settings(), cx)
 186            .unwrap();
 187        this.set_user_settings("{}", cx).unwrap();
 188        this
 189    }
 190
 191    /// Update the value of a setting in the user's global configuration.
 192    ///
 193    /// This is only for tests. Normally, settings are only loaded from
 194    /// JSON files.
 195    #[cfg(any(test, feature = "test-support"))]
 196    pub fn update_user_settings<T: Setting>(
 197        &mut self,
 198        cx: &AppContext,
 199        update: impl FnOnce(&mut T::FileContent),
 200    ) {
 201        if self.user_deserialized_settings.is_none() {
 202            self.set_user_settings("{}", cx).unwrap();
 203        }
 204        let old_text =
 205            serde_json::to_string(self.user_deserialized_settings.as_ref().unwrap()).unwrap();
 206        let new_text = self.new_text_for_update::<T>(old_text, update);
 207        self.set_user_settings(&new_text, cx).unwrap();
 208    }
 209
 210    /// Update the value of a setting in a JSON file, returning the new text
 211    /// for that JSON file.
 212    pub fn new_text_for_update<T: Setting>(
 213        &self,
 214        old_text: String,
 215        update: impl FnOnce(&mut T::FileContent),
 216    ) -> String {
 217        let edits = self.edits_for_update::<T>(&old_text, update);
 218        let mut new_text = old_text;
 219        for (range, replacement) in edits.into_iter() {
 220            new_text.replace_range(range, &replacement);
 221        }
 222        new_text
 223    }
 224
 225    /// Update the value of a setting in a JSON file, returning a list
 226    /// of edits to apply to the JSON file.
 227    pub fn edits_for_update<T: Setting>(
 228        &self,
 229        text: &str,
 230        update: impl FnOnce(&mut T::FileContent),
 231    ) -> Vec<(Range<usize>, String)> {
 232        let setting_type_id = TypeId::of::<T>();
 233
 234        let old_content = self
 235            .setting_values
 236            .get(&setting_type_id)
 237            .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()))
 238            .deserialize_setting(
 239                self.user_deserialized_settings
 240                    .as_ref()
 241                    .expect("no user settings loaded"),
 242            )
 243            .unwrap_or_else(|e| {
 244                panic!(
 245                    "could not deserialize setting type {} from user settings: {}",
 246                    type_name::<T>(),
 247                    e
 248                )
 249            })
 250            .0
 251            .downcast::<T::FileContent>()
 252            .unwrap();
 253        let mut new_content = old_content.clone();
 254        update(&mut new_content);
 255
 256        let old_value = &serde_json::to_value(&old_content).unwrap();
 257        let new_value = serde_json::to_value(new_content).unwrap();
 258
 259        let mut key_path = Vec::new();
 260        if let Some(key) = T::KEY {
 261            key_path.push(key);
 262        }
 263
 264        let mut edits = Vec::new();
 265        let tab_size = self.json_tab_size();
 266        let mut text = text.to_string();
 267        update_value_in_json_text(
 268            &mut text,
 269            &mut key_path,
 270            tab_size,
 271            &old_value,
 272            &new_value,
 273            &mut edits,
 274        );
 275        return edits;
 276    }
 277
 278    /// Configure the tab sized when updating JSON files.
 279    pub fn set_json_tab_size_callback<T: Setting>(
 280        &mut self,
 281        get_tab_size: fn(&T) -> Option<usize>,
 282    ) {
 283        self.tab_size_callback = Some((
 284            TypeId::of::<T>(),
 285            Box::new(move |value| get_tab_size(value.downcast_ref::<T>().unwrap())),
 286        ));
 287    }
 288
 289    fn json_tab_size(&self) -> usize {
 290        const DEFAULT_JSON_TAB_SIZE: usize = 2;
 291
 292        if let Some((setting_type_id, callback)) = &self.tab_size_callback {
 293            let setting_value = self.setting_values.get(setting_type_id).unwrap();
 294            let value = setting_value.value_for_path(None);
 295            if let Some(value) = callback(value) {
 296                return value;
 297            }
 298        }
 299
 300        DEFAULT_JSON_TAB_SIZE
 301    }
 302
 303    /// Set the default settings via a JSON string.
 304    ///
 305    /// The string should contain a JSON object with a default value for every setting.
 306    pub fn set_default_settings(
 307        &mut self,
 308        default_settings_content: &str,
 309        cx: &AppContext,
 310    ) -> Result<()> {
 311        self.default_deserialized_settings =
 312            Some(parse_json_with_comments(default_settings_content)?);
 313        self.recompute_values(None, cx)?;
 314        Ok(())
 315    }
 316
 317    /// Set the user settings via a JSON string.
 318    pub fn set_user_settings(
 319        &mut self,
 320        user_settings_content: &str,
 321        cx: &AppContext,
 322    ) -> Result<()> {
 323        self.user_deserialized_settings = Some(parse_json_with_comments(user_settings_content)?);
 324        self.recompute_values(None, cx)?;
 325        Ok(())
 326    }
 327
 328    /// Add or remove a set of local settings via a JSON string.
 329    pub fn set_local_settings(
 330        &mut self,
 331        path: Arc<Path>,
 332        settings_content: Option<&str>,
 333        cx: &AppContext,
 334    ) -> Result<()> {
 335        if let Some(content) = settings_content {
 336            self.local_deserialized_settings
 337                .insert(path.clone(), parse_json_with_comments(content)?);
 338        } else {
 339            self.local_deserialized_settings.remove(&path);
 340        }
 341        self.recompute_values(Some(&path), cx)?;
 342        Ok(())
 343    }
 344
 345    pub fn json_schema(&self, schema_params: &SettingsJsonSchemaParams) -> serde_json::Value {
 346        use schemars::{
 347            gen::SchemaSettings,
 348            schema::{Schema, SchemaObject},
 349        };
 350
 351        let settings = SchemaSettings::draft07().with(|settings| {
 352            settings.option_add_null_type = false;
 353        });
 354        let mut generator = SchemaGenerator::new(settings);
 355        let mut combined_schema = RootSchema::default();
 356
 357        for setting_value in self.setting_values.values() {
 358            let setting_schema = setting_value.json_schema(&mut generator, schema_params);
 359            combined_schema
 360                .definitions
 361                .extend(setting_schema.definitions);
 362
 363            let target_schema = if let Some(key) = setting_value.key() {
 364                let key_schema = combined_schema
 365                    .schema
 366                    .object()
 367                    .properties
 368                    .entry(key.to_string())
 369                    .or_insert_with(|| Schema::Object(SchemaObject::default()));
 370                if let Schema::Object(key_schema) = key_schema {
 371                    key_schema
 372                } else {
 373                    continue;
 374                }
 375            } else {
 376                &mut combined_schema.schema
 377            };
 378
 379            merge_schema(target_schema, setting_schema.schema);
 380        }
 381
 382        fn merge_schema(target: &mut SchemaObject, source: SchemaObject) {
 383            if let Some(source) = source.object {
 384                let target_properties = &mut target.object().properties;
 385                for (key, value) in source.properties {
 386                    match target_properties.entry(key) {
 387                        btree_map::Entry::Vacant(e) => {
 388                            e.insert(value);
 389                        }
 390                        btree_map::Entry::Occupied(e) => {
 391                            if let (Schema::Object(target), Schema::Object(src)) =
 392                                (e.into_mut(), value)
 393                            {
 394                                merge_schema(target, src);
 395                            }
 396                        }
 397                    }
 398                }
 399            }
 400
 401            overwrite(&mut target.instance_type, source.instance_type);
 402            overwrite(&mut target.string, source.string);
 403            overwrite(&mut target.number, source.number);
 404            overwrite(&mut target.reference, source.reference);
 405            overwrite(&mut target.array, source.array);
 406            overwrite(&mut target.enum_values, source.enum_values);
 407
 408            fn overwrite<T>(target: &mut Option<T>, source: Option<T>) {
 409                if let Some(source) = source {
 410                    *target = Some(source);
 411                }
 412            }
 413        }
 414
 415        serde_json::to_value(&combined_schema).unwrap()
 416    }
 417
 418    fn recompute_values(
 419        &mut self,
 420        changed_local_path: Option<&Path>,
 421        cx: &AppContext,
 422    ) -> Result<()> {
 423        // Reload the global and local values for every setting.
 424        let mut user_settings_stack = Vec::<DeserializedSetting>::new();
 425        let mut paths_stack = Vec::<Option<&Path>>::new();
 426        for setting_value in self.setting_values.values_mut() {
 427            if let Some(default_settings) = &self.default_deserialized_settings {
 428                let default_settings = setting_value.deserialize_setting(default_settings)?;
 429
 430                user_settings_stack.clear();
 431                paths_stack.clear();
 432
 433                if let Some(user_settings) = &self.user_deserialized_settings {
 434                    if let Some(user_settings) =
 435                        setting_value.deserialize_setting(user_settings).log_err()
 436                    {
 437                        user_settings_stack.push(user_settings);
 438                        paths_stack.push(None);
 439                    }
 440                }
 441
 442                // If the global settings file changed, reload the global value for the field.
 443                if changed_local_path.is_none() {
 444                    setting_value.set_global_value(setting_value.load_setting(
 445                        &default_settings,
 446                        &user_settings_stack,
 447                        cx,
 448                    )?);
 449                }
 450
 451                // Reload the local values for the setting.
 452                for (path, local_settings) in &self.local_deserialized_settings {
 453                    // Build a stack of all of the local values for that setting.
 454                    while let Some(prev_path) = paths_stack.last() {
 455                        if let Some(prev_path) = prev_path {
 456                            if !path.starts_with(prev_path) {
 457                                paths_stack.pop();
 458                                user_settings_stack.pop();
 459                                continue;
 460                            }
 461                        }
 462                        break;
 463                    }
 464
 465                    if let Some(local_settings) =
 466                        setting_value.deserialize_setting(&local_settings).log_err()
 467                    {
 468                        paths_stack.push(Some(path.as_ref()));
 469                        user_settings_stack.push(local_settings);
 470
 471                        // If a local settings file changed, then avoid recomputing local
 472                        // settings for any path outside of that directory.
 473                        if changed_local_path.map_or(false, |changed_local_path| {
 474                            !path.starts_with(changed_local_path)
 475                        }) {
 476                            continue;
 477                        }
 478
 479                        setting_value.set_local_value(
 480                            path.clone(),
 481                            setting_value.load_setting(
 482                                &default_settings,
 483                                &user_settings_stack,
 484                                cx,
 485                            )?,
 486                        );
 487                    }
 488                }
 489            }
 490        }
 491        Ok(())
 492    }
 493}
 494
 495impl<T: Setting> AnySettingValue for SettingValue<T> {
 496    fn key(&self) -> Option<&'static str> {
 497        T::KEY
 498    }
 499
 500    fn setting_type_name(&self) -> &'static str {
 501        type_name::<T>()
 502    }
 503
 504    fn load_setting(
 505        &self,
 506        default_value: &DeserializedSetting,
 507        user_values: &[DeserializedSetting],
 508        cx: &AppContext,
 509    ) -> Result<Box<dyn Any>> {
 510        let default_value = default_value.0.downcast_ref::<T::FileContent>().unwrap();
 511        let values: SmallVec<[&T::FileContent; 6]> = user_values
 512            .iter()
 513            .map(|value| value.0.downcast_ref().unwrap())
 514            .collect();
 515        Ok(Box::new(T::load(default_value, &values, cx)?))
 516    }
 517
 518    fn deserialize_setting(&self, mut json: &serde_json::Value) -> Result<DeserializedSetting> {
 519        if let Some(key) = T::KEY {
 520            json = json.get(key).unwrap_or(&serde_json::Value::Null);
 521        }
 522        let value = T::FileContent::deserialize(json)?;
 523        Ok(DeserializedSetting(Box::new(value)))
 524    }
 525
 526    fn value_for_path(&self, path: Option<&Path>) -> &dyn Any {
 527        if let Some(path) = path {
 528            for (settings_path, value) in self.local_values.iter().rev() {
 529                if path.starts_with(&settings_path) {
 530                    return value;
 531                }
 532            }
 533        }
 534        self.global_value
 535            .as_ref()
 536            .unwrap_or_else(|| panic!("no default value for setting {}", self.setting_type_name()))
 537    }
 538
 539    fn set_global_value(&mut self, value: Box<dyn Any>) {
 540        self.global_value = Some(*value.downcast().unwrap());
 541    }
 542
 543    fn set_local_value(&mut self, path: Arc<Path>, value: Box<dyn Any>) {
 544        let value = *value.downcast().unwrap();
 545        match self.local_values.binary_search_by_key(&&path, |e| &e.0) {
 546            Ok(ix) => self.local_values[ix].1 = value,
 547            Err(ix) => self.local_values.insert(ix, (path, value)),
 548        }
 549    }
 550
 551    fn json_schema(
 552        &self,
 553        generator: &mut SchemaGenerator,
 554        params: &SettingsJsonSchemaParams,
 555    ) -> RootSchema {
 556        T::json_schema(generator, params)
 557    }
 558}
 559
 560// impl Debug for SettingsStore {
 561//     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 562//         return f
 563//             .debug_struct("SettingsStore")
 564//             .field(
 565//                 "setting_value_sets_by_type",
 566//                 &self
 567//                     .setting_values
 568//                     .values()
 569//                     .map(|set| (set.setting_type_name(), set))
 570//                     .collect::<HashMap<_, _>>(),
 571//             )
 572//             .finish_non_exhaustive();
 573//     }
 574// }
 575
 576fn update_value_in_json_text<'a>(
 577    text: &mut String,
 578    key_path: &mut Vec<&'a str>,
 579    tab_size: usize,
 580    old_value: &'a serde_json::Value,
 581    new_value: &'a serde_json::Value,
 582    edits: &mut Vec<(Range<usize>, String)>,
 583) {
 584    // If the old and new values are both objects, then compare them key by key,
 585    // preserving the comments and formatting of the unchanged parts. Otherwise,
 586    // replace the old value with the new value.
 587    if let (serde_json::Value::Object(old_object), serde_json::Value::Object(new_object)) =
 588        (old_value, new_value)
 589    {
 590        for (key, old_sub_value) in old_object.iter() {
 591            key_path.push(key);
 592            let new_sub_value = new_object.get(key).unwrap_or(&serde_json::Value::Null);
 593            update_value_in_json_text(
 594                text,
 595                key_path,
 596                tab_size,
 597                old_sub_value,
 598                new_sub_value,
 599                edits,
 600            );
 601            key_path.pop();
 602        }
 603        for (key, new_sub_value) in new_object.iter() {
 604            key_path.push(key);
 605            if !old_object.contains_key(key) {
 606                update_value_in_json_text(
 607                    text,
 608                    key_path,
 609                    tab_size,
 610                    &serde_json::Value::Null,
 611                    new_sub_value,
 612                    edits,
 613                );
 614            }
 615            key_path.pop();
 616        }
 617    } else if old_value != new_value {
 618        let (range, replacement) =
 619            replace_value_in_json_text(text, &key_path, tab_size, &new_value);
 620        text.replace_range(range.clone(), &replacement);
 621        edits.push((range, replacement));
 622    }
 623}
 624
 625fn replace_value_in_json_text(
 626    text: &str,
 627    key_path: &[&str],
 628    tab_size: usize,
 629    new_value: impl Serialize,
 630) -> (Range<usize>, String) {
 631    const LANGUAGE_OVERRIDES: &'static str = "language_overrides";
 632    const LANGUAGES: &'static str = "languages";
 633
 634    lazy_static! {
 635        static ref PAIR_QUERY: tree_sitter::Query = tree_sitter::Query::new(
 636            tree_sitter_json::language(),
 637            "(pair key: (string) @key value: (_) @value)",
 638        )
 639        .unwrap();
 640    }
 641
 642    let mut parser = tree_sitter::Parser::new();
 643    parser.set_language(tree_sitter_json::language()).unwrap();
 644    let syntax_tree = parser.parse(text, None).unwrap();
 645
 646    let mut cursor = tree_sitter::QueryCursor::new();
 647
 648    let has_language_overrides = text.contains(LANGUAGE_OVERRIDES);
 649
 650    let mut depth = 0;
 651    let mut last_value_range = 0..0;
 652    let mut first_key_start = None;
 653    let mut existing_value_range = 0..text.len();
 654    let matches = cursor.matches(&PAIR_QUERY, syntax_tree.root_node(), text.as_bytes());
 655    for mat in matches {
 656        if mat.captures.len() != 2 {
 657            continue;
 658        }
 659
 660        let key_range = mat.captures[0].node.byte_range();
 661        let value_range = mat.captures[1].node.byte_range();
 662
 663        // Don't enter sub objects until we find an exact
 664        // match for the current keypath
 665        if last_value_range.contains_inclusive(&value_range) {
 666            continue;
 667        }
 668
 669        last_value_range = value_range.clone();
 670
 671        if key_range.start > existing_value_range.end {
 672            break;
 673        }
 674
 675        first_key_start.get_or_insert_with(|| key_range.start);
 676
 677        let found_key = text
 678            .get(key_range.clone())
 679            .map(|key_text| {
 680                if key_path[depth] == LANGUAGES && has_language_overrides {
 681                    return key_text == format!("\"{}\"", LANGUAGE_OVERRIDES);
 682                } else {
 683                    return key_text == format!("\"{}\"", key_path[depth]);
 684                }
 685            })
 686            .unwrap_or(false);
 687
 688        if found_key {
 689            existing_value_range = value_range;
 690            // Reset last value range when increasing in depth
 691            last_value_range = existing_value_range.start..existing_value_range.start;
 692            depth += 1;
 693
 694            if depth == key_path.len() {
 695                break;
 696            } else {
 697                first_key_start = None;
 698            }
 699        }
 700    }
 701
 702    // We found the exact key we want, insert the new value
 703    if depth == key_path.len() {
 704        let new_val = to_pretty_json(&new_value, tab_size, tab_size * depth);
 705        (existing_value_range, new_val)
 706    } else {
 707        // We have key paths, construct the sub objects
 708        let new_key = if has_language_overrides && key_path[depth] == LANGUAGES {
 709            LANGUAGE_OVERRIDES
 710        } else {
 711            key_path[depth]
 712        };
 713
 714        // We don't have the key, construct the nested objects
 715        let mut new_value = serde_json::to_value(new_value).unwrap();
 716        for key in key_path[(depth + 1)..].iter().rev() {
 717            if has_language_overrides && key == &LANGUAGES {
 718                new_value = serde_json::json!({ LANGUAGE_OVERRIDES.to_string(): new_value });
 719            } else {
 720                new_value = serde_json::json!({ key.to_string(): new_value });
 721            }
 722        }
 723
 724        if let Some(first_key_start) = first_key_start {
 725            let mut row = 0;
 726            let mut column = 0;
 727            for (ix, char) in text.char_indices() {
 728                if ix == first_key_start {
 729                    break;
 730                }
 731                if char == '\n' {
 732                    row += 1;
 733                    column = 0;
 734                } else {
 735                    column += char.len_utf8();
 736                }
 737            }
 738
 739            if row > 0 {
 740                // depth is 0 based, but division needs to be 1 based.
 741                let new_val = to_pretty_json(&new_value, column / (depth + 1), column);
 742                let space = ' ';
 743                let content = format!("\"{new_key}\": {new_val},\n{space:width$}", width = column);
 744                (first_key_start..first_key_start, content)
 745            } else {
 746                let new_val = serde_json::to_string(&new_value).unwrap();
 747                let mut content = format!(r#""{new_key}": {new_val},"#);
 748                content.push(' ');
 749                (first_key_start..first_key_start, content)
 750            }
 751        } else {
 752            new_value = serde_json::json!({ new_key.to_string(): new_value });
 753            let indent_prefix_len = 4 * depth;
 754            let mut new_val = to_pretty_json(&new_value, 4, indent_prefix_len);
 755            if depth == 0 {
 756                new_val.push('\n');
 757            }
 758
 759            (existing_value_range, new_val)
 760        }
 761    }
 762}
 763
 764fn to_pretty_json(value: &impl Serialize, indent_size: usize, indent_prefix_len: usize) -> String {
 765    const SPACES: [u8; 32] = [b' '; 32];
 766
 767    debug_assert!(indent_size <= SPACES.len());
 768    debug_assert!(indent_prefix_len <= SPACES.len());
 769
 770    let mut output = Vec::new();
 771    let mut ser = serde_json::Serializer::with_formatter(
 772        &mut output,
 773        serde_json::ser::PrettyFormatter::with_indent(&SPACES[0..indent_size.min(SPACES.len())]),
 774    );
 775
 776    value.serialize(&mut ser).unwrap();
 777    let text = String::from_utf8(output).unwrap();
 778
 779    let mut adjusted_text = String::new();
 780    for (i, line) in text.split('\n').enumerate() {
 781        if i > 0 {
 782            adjusted_text.push_str(str::from_utf8(&SPACES[0..indent_prefix_len]).unwrap());
 783        }
 784        adjusted_text.push_str(line);
 785        adjusted_text.push('\n');
 786    }
 787    adjusted_text.pop();
 788    adjusted_text
 789}
 790
 791pub fn parse_json_with_comments<T: DeserializeOwned>(content: &str) -> Result<T> {
 792    Ok(serde_json::from_reader(
 793        json_comments::CommentSettings::c_style().strip_comments(content.as_bytes()),
 794    )?)
 795}
 796
 797#[cfg(test)]
 798mod tests {
 799    use super::*;
 800    use serde_derive::Deserialize;
 801    use unindent::Unindent;
 802
 803    #[gpui::test]
 804    fn test_settings_store_basic(cx: &mut AppContext) {
 805        let mut store = SettingsStore::default();
 806        store.register_setting::<UserSettings>(cx);
 807        store.register_setting::<TurboSetting>(cx);
 808        store.register_setting::<MultiKeySettings>(cx);
 809
 810        // error - missing required field in default settings
 811        store
 812            .set_default_settings(
 813                r#"{
 814                    "user": {
 815                        "name": "John Doe",
 816                        "age": 30,
 817                        "staff": false
 818                    }
 819                }"#,
 820                cx,
 821            )
 822            .unwrap_err();
 823
 824        // error - type error in default settings
 825        store
 826            .set_default_settings(
 827                r#"{
 828                    "turbo": "the-wrong-type",
 829                    "user": {
 830                        "name": "John Doe",
 831                        "age": 30,
 832                        "staff": false
 833                    }
 834                }"#,
 835                cx,
 836            )
 837            .unwrap_err();
 838
 839        // valid default settings.
 840        store
 841            .set_default_settings(
 842                r#"{
 843                    "turbo": false,
 844                    "user": {
 845                        "name": "John Doe",
 846                        "age": 30,
 847                        "staff": false
 848                    }
 849                }"#,
 850                cx,
 851            )
 852            .unwrap();
 853
 854        assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(false));
 855        assert_eq!(
 856            store.get::<UserSettings>(None),
 857            &UserSettings {
 858                name: "John Doe".to_string(),
 859                age: 30,
 860                staff: false,
 861            }
 862        );
 863        assert_eq!(
 864            store.get::<MultiKeySettings>(None),
 865            &MultiKeySettings {
 866                key1: String::new(),
 867                key2: String::new(),
 868            }
 869        );
 870
 871        store
 872            .set_user_settings(
 873                r#"{
 874                    "turbo": true,
 875                    "user": { "age": 31 },
 876                    "key1": "a"
 877                }"#,
 878                cx,
 879            )
 880            .unwrap();
 881
 882        assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(true));
 883        assert_eq!(
 884            store.get::<UserSettings>(None),
 885            &UserSettings {
 886                name: "John Doe".to_string(),
 887                age: 31,
 888                staff: false
 889            }
 890        );
 891
 892        store
 893            .set_local_settings(
 894                Path::new("/root1").into(),
 895                Some(r#"{ "user": { "staff": true } }"#),
 896                cx,
 897            )
 898            .unwrap();
 899        store
 900            .set_local_settings(
 901                Path::new("/root1/subdir").into(),
 902                Some(r#"{ "user": { "name": "Jane Doe" } }"#),
 903                cx,
 904            )
 905            .unwrap();
 906
 907        store
 908            .set_local_settings(
 909                Path::new("/root2").into(),
 910                Some(r#"{ "user": { "age": 42 }, "key2": "b" }"#),
 911                cx,
 912            )
 913            .unwrap();
 914
 915        assert_eq!(
 916            store.get::<UserSettings>(Some(Path::new("/root1/something"))),
 917            &UserSettings {
 918                name: "John Doe".to_string(),
 919                age: 31,
 920                staff: true
 921            }
 922        );
 923        assert_eq!(
 924            store.get::<UserSettings>(Some(Path::new("/root1/subdir/something"))),
 925            &UserSettings {
 926                name: "Jane Doe".to_string(),
 927                age: 31,
 928                staff: true
 929            }
 930        );
 931        assert_eq!(
 932            store.get::<UserSettings>(Some(Path::new("/root2/something"))),
 933            &UserSettings {
 934                name: "John Doe".to_string(),
 935                age: 42,
 936                staff: false
 937            }
 938        );
 939        assert_eq!(
 940            store.get::<MultiKeySettings>(Some(Path::new("/root2/something"))),
 941            &MultiKeySettings {
 942                key1: "a".to_string(),
 943                key2: "b".to_string(),
 944            }
 945        );
 946    }
 947
 948    #[gpui::test]
 949    fn test_setting_store_assign_json_before_register(cx: &mut AppContext) {
 950        let mut store = SettingsStore::default();
 951        store
 952            .set_default_settings(
 953                r#"{
 954                    "turbo": true,
 955                    "user": {
 956                        "name": "John Doe",
 957                        "age": 30,
 958                        "staff": false
 959                    },
 960                    "key1": "x"
 961                }"#,
 962                cx,
 963            )
 964            .unwrap();
 965        store
 966            .set_user_settings(r#"{ "turbo": false }"#, cx)
 967            .unwrap();
 968        store.register_setting::<UserSettings>(cx);
 969        store.register_setting::<TurboSetting>(cx);
 970
 971        assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(false));
 972        assert_eq!(
 973            store.get::<UserSettings>(None),
 974            &UserSettings {
 975                name: "John Doe".to_string(),
 976                age: 30,
 977                staff: false,
 978            }
 979        );
 980
 981        store.register_setting::<MultiKeySettings>(cx);
 982        assert_eq!(
 983            store.get::<MultiKeySettings>(None),
 984            &MultiKeySettings {
 985                key1: "x".into(),
 986                key2: String::new(),
 987            }
 988        );
 989    }
 990
 991    #[gpui::test]
 992    fn test_setting_store_update(cx: &mut AppContext) {
 993        let mut store = SettingsStore::default();
 994        store.register_setting::<MultiKeySettings>(cx);
 995        store.register_setting::<UserSettings>(cx);
 996        store.register_setting::<LanguageSettings>(cx);
 997
 998        // entries added and updated
 999        check_settings_update::<LanguageSettings>(
1000            &mut store,
1001            r#"{
1002                "languages": {
1003                    "JSON": {
1004                        "is_enabled": true
1005                    }
1006                }
1007            }"#
1008            .unindent(),
1009            |settings| {
1010                settings.languages.get_mut("JSON").unwrap().is_enabled = false;
1011                settings
1012                    .languages
1013                    .insert("Rust".into(), LanguageSettingEntry { is_enabled: true });
1014            },
1015            r#"{
1016                "languages": {
1017                    "Rust": {
1018                        "is_enabled": true
1019                    },
1020                    "JSON": {
1021                        "is_enabled": false
1022                    }
1023                }
1024            }"#
1025            .unindent(),
1026            cx,
1027        );
1028
1029        // weird formatting
1030        check_settings_update::<UserSettings>(
1031            &mut store,
1032            r#"{
1033                "user":   { "age": 36, "name": "Max", "staff": true }
1034            }"#
1035            .unindent(),
1036            |settings| settings.age = Some(37),
1037            r#"{
1038                "user":   { "age": 37, "name": "Max", "staff": true }
1039            }"#
1040            .unindent(),
1041            cx,
1042        );
1043
1044        // single-line formatting, other keys
1045        check_settings_update::<MultiKeySettings>(
1046            &mut store,
1047            r#"{ "one": 1, "two": 2 }"#.unindent(),
1048            |settings| settings.key1 = Some("x".into()),
1049            r#"{ "key1": "x", "one": 1, "two": 2 }"#.unindent(),
1050            cx,
1051        );
1052
1053        // empty object
1054        check_settings_update::<UserSettings>(
1055            &mut store,
1056            r#"{
1057                "user": {}
1058            }"#
1059            .unindent(),
1060            |settings| settings.age = Some(37),
1061            r#"{
1062                "user": {
1063                    "age": 37
1064                }
1065            }"#
1066            .unindent(),
1067            cx,
1068        );
1069
1070        // no content
1071        check_settings_update::<UserSettings>(
1072            &mut store,
1073            r#""#.unindent(),
1074            |settings| settings.age = Some(37),
1075            r#"{
1076                "user": {
1077                    "age": 37
1078                }
1079            }
1080            "#
1081            .unindent(),
1082            cx,
1083        );
1084    }
1085
1086    fn check_settings_update<T: Setting>(
1087        store: &mut SettingsStore,
1088        old_json: String,
1089        update: fn(&mut T::FileContent),
1090        expected_new_json: String,
1091        cx: &mut AppContext,
1092    ) {
1093        store.set_user_settings(&old_json, cx).ok();
1094        let edits = store.edits_for_update::<T>(&old_json, update);
1095        let mut new_json = old_json;
1096        for (range, replacement) in edits.into_iter() {
1097            new_json.replace_range(range, &replacement);
1098        }
1099        pretty_assertions::assert_eq!(new_json, expected_new_json);
1100    }
1101
1102    #[derive(Debug, PartialEq, Deserialize)]
1103    struct UserSettings {
1104        name: String,
1105        age: u32,
1106        staff: bool,
1107    }
1108
1109    #[derive(Clone, Serialize, Deserialize, JsonSchema)]
1110    struct UserSettingsJson {
1111        name: Option<String>,
1112        age: Option<u32>,
1113        staff: Option<bool>,
1114    }
1115
1116    impl Setting for UserSettings {
1117        const KEY: Option<&'static str> = Some("user");
1118        type FileContent = UserSettingsJson;
1119
1120        fn load(
1121            default_value: &UserSettingsJson,
1122            user_values: &[&UserSettingsJson],
1123            _: &AppContext,
1124        ) -> Result<Self> {
1125            Self::load_via_json_merge(default_value, user_values)
1126        }
1127    }
1128
1129    #[derive(Debug, Deserialize, PartialEq)]
1130    struct TurboSetting(bool);
1131
1132    impl Setting for TurboSetting {
1133        const KEY: Option<&'static str> = Some("turbo");
1134        type FileContent = Option<bool>;
1135
1136        fn load(
1137            default_value: &Option<bool>,
1138            user_values: &[&Option<bool>],
1139            _: &AppContext,
1140        ) -> Result<Self> {
1141            Self::load_via_json_merge(default_value, user_values)
1142        }
1143    }
1144
1145    #[derive(Clone, Debug, PartialEq, Deserialize)]
1146    struct MultiKeySettings {
1147        #[serde(default)]
1148        key1: String,
1149        #[serde(default)]
1150        key2: String,
1151    }
1152
1153    #[derive(Clone, Serialize, Deserialize, JsonSchema)]
1154    struct MultiKeySettingsJson {
1155        key1: Option<String>,
1156        key2: Option<String>,
1157    }
1158
1159    impl Setting for MultiKeySettings {
1160        const KEY: Option<&'static str> = None;
1161
1162        type FileContent = MultiKeySettingsJson;
1163
1164        fn load(
1165            default_value: &MultiKeySettingsJson,
1166            user_values: &[&MultiKeySettingsJson],
1167            _: &AppContext,
1168        ) -> Result<Self> {
1169            Self::load_via_json_merge(default_value, user_values)
1170        }
1171    }
1172
1173    #[derive(Debug, Deserialize)]
1174    struct JournalSettings {
1175        pub path: String,
1176        pub hour_format: HourFormat,
1177    }
1178
1179    #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
1180    #[serde(rename_all = "snake_case")]
1181    enum HourFormat {
1182        Hour12,
1183        Hour24,
1184    }
1185
1186    #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
1187    struct JournalSettingsJson {
1188        pub path: Option<String>,
1189        pub hour_format: Option<HourFormat>,
1190    }
1191
1192    impl Setting for JournalSettings {
1193        const KEY: Option<&'static str> = Some("journal");
1194
1195        type FileContent = JournalSettingsJson;
1196
1197        fn load(
1198            default_value: &JournalSettingsJson,
1199            user_values: &[&JournalSettingsJson],
1200            _: &AppContext,
1201        ) -> Result<Self> {
1202            Self::load_via_json_merge(default_value, user_values)
1203        }
1204    }
1205
1206    #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
1207    struct LanguageSettings {
1208        #[serde(default)]
1209        languages: HashMap<String, LanguageSettingEntry>,
1210    }
1211
1212    #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
1213    struct LanguageSettingEntry {
1214        is_enabled: bool,
1215    }
1216
1217    impl Setting for LanguageSettings {
1218        const KEY: Option<&'static str> = None;
1219
1220        type FileContent = Self;
1221
1222        fn load(default_value: &Self, user_values: &[&Self], _: &AppContext) -> Result<Self> {
1223            Self::load_via_json_merge(default_value, user_values)
1224        }
1225    }
1226}