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