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