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 + 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.
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 if let Some(value) = setting_value
464 .load_setting(&default_settings, &user_settings_stack, cx)
465 .log_err()
466 {
467 setting_value.set_global_value(value);
468 }
469 }
470
471 // Reload the local values for the setting.
472 for (path, local_settings) in &self.local_deserialized_settings {
473 // Build a stack of all of the local values for that setting.
474 while let Some(prev_path) = paths_stack.last() {
475 if let Some(prev_path) = prev_path {
476 if !path.starts_with(prev_path) {
477 paths_stack.pop();
478 user_settings_stack.pop();
479 continue;
480 }
481 }
482 break;
483 }
484
485 if let Some(local_settings) =
486 setting_value.deserialize_setting(&local_settings).log_err()
487 {
488 paths_stack.push(Some(path.as_ref()));
489 user_settings_stack.push(local_settings);
490
491 // If a local settings file changed, then avoid recomputing local
492 // settings for any path outside of that directory.
493 if changed_local_path.map_or(false, |changed_local_path| {
494 !path.starts_with(changed_local_path)
495 }) {
496 continue;
497 }
498
499 if let Some(value) = setting_value
500 .load_setting(&default_settings, &user_settings_stack, cx)
501 .log_err()
502 {
503 setting_value.set_local_value(path.clone(), value);
504 }
505 }
506 }
507 }
508 }
509 Ok(())
510 }
511}
512
513impl<T: Setting> AnySettingValue for SettingValue<T> {
514 fn key(&self) -> Option<&'static str> {
515 T::KEY
516 }
517
518 fn setting_type_name(&self) -> &'static str {
519 type_name::<T>()
520 }
521
522 fn load_setting(
523 &self,
524 default_value: &DeserializedSetting,
525 user_values: &[DeserializedSetting],
526 cx: &AppContext,
527 ) -> Result<Box<dyn Any>> {
528 let default_value = default_value.0.downcast_ref::<T::FileContent>().unwrap();
529 let values: SmallVec<[&T::FileContent; 6]> = user_values
530 .iter()
531 .map(|value| value.0.downcast_ref().unwrap())
532 .collect();
533 Ok(Box::new(T::load(default_value, &values, cx)?))
534 }
535
536 fn deserialize_setting(&self, mut json: &serde_json::Value) -> Result<DeserializedSetting> {
537 if let Some(key) = T::KEY {
538 if let Some(value) = json.get(key) {
539 json = value;
540 } else {
541 let value = T::FileContent::default();
542 return Ok(DeserializedSetting(Box::new(value)));
543 }
544 }
545 let value = T::FileContent::deserialize(json)?;
546 Ok(DeserializedSetting(Box::new(value)))
547 }
548
549 fn value_for_path(&self, path: Option<&Path>) -> &dyn Any {
550 if let Some(path) = path {
551 for (settings_path, value) in self.local_values.iter().rev() {
552 if path.starts_with(&settings_path) {
553 return value;
554 }
555 }
556 }
557 self.global_value
558 .as_ref()
559 .unwrap_or_else(|| panic!("no default value for setting {}", self.setting_type_name()))
560 }
561
562 fn set_global_value(&mut self, value: Box<dyn Any>) {
563 self.global_value = Some(*value.downcast().unwrap());
564 }
565
566 fn set_local_value(&mut self, path: Arc<Path>, value: Box<dyn Any>) {
567 let value = *value.downcast().unwrap();
568 match self.local_values.binary_search_by_key(&&path, |e| &e.0) {
569 Ok(ix) => self.local_values[ix].1 = value,
570 Err(ix) => self.local_values.insert(ix, (path, value)),
571 }
572 }
573
574 fn json_schema(
575 &self,
576 generator: &mut SchemaGenerator,
577 params: &SettingsJsonSchemaParams,
578 cx: &AppContext,
579 ) -> RootSchema {
580 T::json_schema(generator, params, cx)
581 }
582}
583
584// impl Debug for SettingsStore {
585// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
586// return f
587// .debug_struct("SettingsStore")
588// .field(
589// "setting_value_sets_by_type",
590// &self
591// .setting_values
592// .values()
593// .map(|set| (set.setting_type_name(), set))
594// .collect::<HashMap<_, _>>(),
595// )
596// .finish_non_exhaustive();
597// }
598// }
599
600fn update_value_in_json_text<'a>(
601 text: &mut String,
602 key_path: &mut Vec<&'a str>,
603 tab_size: usize,
604 old_value: &'a serde_json::Value,
605 new_value: &'a serde_json::Value,
606 edits: &mut Vec<(Range<usize>, String)>,
607) {
608 // If the old and new values are both objects, then compare them key by key,
609 // preserving the comments and formatting of the unchanged parts. Otherwise,
610 // replace the old value with the new value.
611 if let (serde_json::Value::Object(old_object), serde_json::Value::Object(new_object)) =
612 (old_value, new_value)
613 {
614 for (key, old_sub_value) in old_object.iter() {
615 key_path.push(key);
616 let new_sub_value = new_object.get(key).unwrap_or(&serde_json::Value::Null);
617 update_value_in_json_text(
618 text,
619 key_path,
620 tab_size,
621 old_sub_value,
622 new_sub_value,
623 edits,
624 );
625 key_path.pop();
626 }
627 for (key, new_sub_value) in new_object.iter() {
628 key_path.push(key);
629 if !old_object.contains_key(key) {
630 update_value_in_json_text(
631 text,
632 key_path,
633 tab_size,
634 &serde_json::Value::Null,
635 new_sub_value,
636 edits,
637 );
638 }
639 key_path.pop();
640 }
641 } else if old_value != new_value {
642 let (range, replacement) =
643 replace_value_in_json_text(text, &key_path, tab_size, &new_value);
644 text.replace_range(range.clone(), &replacement);
645 edits.push((range, replacement));
646 }
647}
648
649fn replace_value_in_json_text(
650 text: &str,
651 key_path: &[&str],
652 tab_size: usize,
653 new_value: impl Serialize,
654) -> (Range<usize>, String) {
655 const LANGUAGE_OVERRIDES: &'static str = "language_overrides";
656 const LANGUAGES: &'static str = "languages";
657
658 lazy_static! {
659 static ref PAIR_QUERY: tree_sitter::Query = tree_sitter::Query::new(
660 tree_sitter_json::language(),
661 "(pair key: (string) @key value: (_) @value)",
662 )
663 .unwrap();
664 }
665
666 let mut parser = tree_sitter::Parser::new();
667 parser.set_language(tree_sitter_json::language()).unwrap();
668 let syntax_tree = parser.parse(text, None).unwrap();
669
670 let mut cursor = tree_sitter::QueryCursor::new();
671
672 let has_language_overrides = text.contains(LANGUAGE_OVERRIDES);
673
674 let mut depth = 0;
675 let mut last_value_range = 0..0;
676 let mut first_key_start = None;
677 let mut existing_value_range = 0..text.len();
678 let matches = cursor.matches(&PAIR_QUERY, syntax_tree.root_node(), text.as_bytes());
679 for mat in matches {
680 if mat.captures.len() != 2 {
681 continue;
682 }
683
684 let key_range = mat.captures[0].node.byte_range();
685 let value_range = mat.captures[1].node.byte_range();
686
687 // Don't enter sub objects until we find an exact
688 // match for the current keypath
689 if last_value_range.contains_inclusive(&value_range) {
690 continue;
691 }
692
693 last_value_range = value_range.clone();
694
695 if key_range.start > existing_value_range.end {
696 break;
697 }
698
699 first_key_start.get_or_insert_with(|| key_range.start);
700
701 let found_key = text
702 .get(key_range.clone())
703 .map(|key_text| {
704 if key_path[depth] == LANGUAGES && has_language_overrides {
705 return key_text == format!("\"{}\"", LANGUAGE_OVERRIDES);
706 } else {
707 return key_text == format!("\"{}\"", key_path[depth]);
708 }
709 })
710 .unwrap_or(false);
711
712 if found_key {
713 existing_value_range = value_range;
714 // Reset last value range when increasing in depth
715 last_value_range = existing_value_range.start..existing_value_range.start;
716 depth += 1;
717
718 if depth == key_path.len() {
719 break;
720 } else {
721 first_key_start = None;
722 }
723 }
724 }
725
726 // We found the exact key we want, insert the new value
727 if depth == key_path.len() {
728 let new_val = to_pretty_json(&new_value, tab_size, tab_size * depth);
729 (existing_value_range, new_val)
730 } else {
731 // We have key paths, construct the sub objects
732 let new_key = if has_language_overrides && key_path[depth] == LANGUAGES {
733 LANGUAGE_OVERRIDES
734 } else {
735 key_path[depth]
736 };
737
738 // We don't have the key, construct the nested objects
739 let mut new_value = serde_json::to_value(new_value).unwrap();
740 for key in key_path[(depth + 1)..].iter().rev() {
741 if has_language_overrides && key == &LANGUAGES {
742 new_value = serde_json::json!({ LANGUAGE_OVERRIDES.to_string(): new_value });
743 } else {
744 new_value = serde_json::json!({ key.to_string(): new_value });
745 }
746 }
747
748 if let Some(first_key_start) = first_key_start {
749 let mut row = 0;
750 let mut column = 0;
751 for (ix, char) in text.char_indices() {
752 if ix == first_key_start {
753 break;
754 }
755 if char == '\n' {
756 row += 1;
757 column = 0;
758 } else {
759 column += char.len_utf8();
760 }
761 }
762
763 if row > 0 {
764 // depth is 0 based, but division needs to be 1 based.
765 let new_val = to_pretty_json(&new_value, column / (depth + 1), column);
766 let space = ' ';
767 let content = format!("\"{new_key}\": {new_val},\n{space:width$}", width = column);
768 (first_key_start..first_key_start, content)
769 } else {
770 let new_val = serde_json::to_string(&new_value).unwrap();
771 let mut content = format!(r#""{new_key}": {new_val},"#);
772 content.push(' ');
773 (first_key_start..first_key_start, content)
774 }
775 } else {
776 new_value = serde_json::json!({ new_key.to_string(): new_value });
777 let indent_prefix_len = 4 * depth;
778 let mut new_val = to_pretty_json(&new_value, 4, indent_prefix_len);
779 if depth == 0 {
780 new_val.push('\n');
781 }
782
783 (existing_value_range, new_val)
784 }
785 }
786}
787
788fn to_pretty_json(value: &impl Serialize, indent_size: usize, indent_prefix_len: usize) -> String {
789 const SPACES: [u8; 32] = [b' '; 32];
790
791 debug_assert!(indent_size <= SPACES.len());
792 debug_assert!(indent_prefix_len <= SPACES.len());
793
794 let mut output = Vec::new();
795 let mut ser = serde_json::Serializer::with_formatter(
796 &mut output,
797 serde_json::ser::PrettyFormatter::with_indent(&SPACES[0..indent_size.min(SPACES.len())]),
798 );
799
800 value.serialize(&mut ser).unwrap();
801 let text = String::from_utf8(output).unwrap();
802
803 let mut adjusted_text = String::new();
804 for (i, line) in text.split('\n').enumerate() {
805 if i > 0 {
806 adjusted_text.push_str(str::from_utf8(&SPACES[0..indent_prefix_len]).unwrap());
807 }
808 adjusted_text.push_str(line);
809 adjusted_text.push('\n');
810 }
811 adjusted_text.pop();
812 adjusted_text
813}
814
815pub fn parse_json_with_comments<T: DeserializeOwned>(content: &str) -> Result<T> {
816 Ok(serde_json::from_reader(
817 json_comments::CommentSettings::c_style().strip_comments(content.as_bytes()),
818 )?)
819}
820
821#[cfg(test)]
822mod tests {
823 use super::*;
824 use serde_derive::Deserialize;
825 use unindent::Unindent;
826
827 #[gpui::test]
828 fn test_settings_store_basic(cx: &mut AppContext) {
829 let mut store = SettingsStore::default();
830 store.register_setting::<UserSettings>(cx);
831 store.register_setting::<TurboSetting>(cx);
832 store.register_setting::<MultiKeySettings>(cx);
833 store
834 .set_default_settings(
835 r#"{
836 "turbo": false,
837 "user": {
838 "name": "John Doe",
839 "age": 30,
840 "staff": false
841 }
842 }"#,
843 cx,
844 )
845 .unwrap();
846
847 assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(false));
848 assert_eq!(
849 store.get::<UserSettings>(None),
850 &UserSettings {
851 name: "John Doe".to_string(),
852 age: 30,
853 staff: false,
854 }
855 );
856 assert_eq!(
857 store.get::<MultiKeySettings>(None),
858 &MultiKeySettings {
859 key1: String::new(),
860 key2: String::new(),
861 }
862 );
863
864 store
865 .set_user_settings(
866 r#"{
867 "turbo": true,
868 "user": { "age": 31 },
869 "key1": "a"
870 }"#,
871 cx,
872 )
873 .unwrap();
874
875 assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(true));
876 assert_eq!(
877 store.get::<UserSettings>(None),
878 &UserSettings {
879 name: "John Doe".to_string(),
880 age: 31,
881 staff: false
882 }
883 );
884
885 store
886 .set_local_settings(
887 Path::new("/root1").into(),
888 Some(r#"{ "user": { "staff": true } }"#),
889 cx,
890 )
891 .unwrap();
892 store
893 .set_local_settings(
894 Path::new("/root1/subdir").into(),
895 Some(r#"{ "user": { "name": "Jane Doe" } }"#),
896 cx,
897 )
898 .unwrap();
899
900 store
901 .set_local_settings(
902 Path::new("/root2").into(),
903 Some(r#"{ "user": { "age": 42 }, "key2": "b" }"#),
904 cx,
905 )
906 .unwrap();
907
908 assert_eq!(
909 store.get::<UserSettings>(Some(Path::new("/root1/something"))),
910 &UserSettings {
911 name: "John Doe".to_string(),
912 age: 31,
913 staff: true
914 }
915 );
916 assert_eq!(
917 store.get::<UserSettings>(Some(Path::new("/root1/subdir/something"))),
918 &UserSettings {
919 name: "Jane Doe".to_string(),
920 age: 31,
921 staff: true
922 }
923 );
924 assert_eq!(
925 store.get::<UserSettings>(Some(Path::new("/root2/something"))),
926 &UserSettings {
927 name: "John Doe".to_string(),
928 age: 42,
929 staff: false
930 }
931 );
932 assert_eq!(
933 store.get::<MultiKeySettings>(Some(Path::new("/root2/something"))),
934 &MultiKeySettings {
935 key1: "a".to_string(),
936 key2: "b".to_string(),
937 }
938 );
939 }
940
941 #[gpui::test]
942 fn test_setting_store_assign_json_before_register(cx: &mut AppContext) {
943 let mut store = SettingsStore::default();
944 store
945 .set_default_settings(
946 r#"{
947 "turbo": true,
948 "user": {
949 "name": "John Doe",
950 "age": 30,
951 "staff": false
952 },
953 "key1": "x"
954 }"#,
955 cx,
956 )
957 .unwrap();
958 store
959 .set_user_settings(r#"{ "turbo": false }"#, cx)
960 .unwrap();
961 store.register_setting::<UserSettings>(cx);
962 store.register_setting::<TurboSetting>(cx);
963
964 assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(false));
965 assert_eq!(
966 store.get::<UserSettings>(None),
967 &UserSettings {
968 name: "John Doe".to_string(),
969 age: 30,
970 staff: false,
971 }
972 );
973
974 store.register_setting::<MultiKeySettings>(cx);
975 assert_eq!(
976 store.get::<MultiKeySettings>(None),
977 &MultiKeySettings {
978 key1: "x".into(),
979 key2: String::new(),
980 }
981 );
982 }
983
984 #[gpui::test]
985 fn test_setting_store_update(cx: &mut AppContext) {
986 let mut store = SettingsStore::default();
987 store.register_setting::<MultiKeySettings>(cx);
988 store.register_setting::<UserSettings>(cx);
989 store.register_setting::<LanguageSettings>(cx);
990
991 // entries added and updated
992 check_settings_update::<LanguageSettings>(
993 &mut store,
994 r#"{
995 "languages": {
996 "JSON": {
997 "is_enabled": true
998 }
999 }
1000 }"#
1001 .unindent(),
1002 |settings| {
1003 settings.languages.get_mut("JSON").unwrap().is_enabled = false;
1004 settings
1005 .languages
1006 .insert("Rust".into(), LanguageSettingEntry { is_enabled: true });
1007 },
1008 r#"{
1009 "languages": {
1010 "Rust": {
1011 "is_enabled": true
1012 },
1013 "JSON": {
1014 "is_enabled": false
1015 }
1016 }
1017 }"#
1018 .unindent(),
1019 cx,
1020 );
1021
1022 // weird formatting
1023 check_settings_update::<UserSettings>(
1024 &mut store,
1025 r#"{
1026 "user": { "age": 36, "name": "Max", "staff": true }
1027 }"#
1028 .unindent(),
1029 |settings| settings.age = Some(37),
1030 r#"{
1031 "user": { "age": 37, "name": "Max", "staff": true }
1032 }"#
1033 .unindent(),
1034 cx,
1035 );
1036
1037 // single-line formatting, other keys
1038 check_settings_update::<MultiKeySettings>(
1039 &mut store,
1040 r#"{ "one": 1, "two": 2 }"#.unindent(),
1041 |settings| settings.key1 = Some("x".into()),
1042 r#"{ "key1": "x", "one": 1, "two": 2 }"#.unindent(),
1043 cx,
1044 );
1045
1046 // empty object
1047 check_settings_update::<UserSettings>(
1048 &mut store,
1049 r#"{
1050 "user": {}
1051 }"#
1052 .unindent(),
1053 |settings| settings.age = Some(37),
1054 r#"{
1055 "user": {
1056 "age": 37
1057 }
1058 }"#
1059 .unindent(),
1060 cx,
1061 );
1062
1063 // no content
1064 check_settings_update::<UserSettings>(
1065 &mut store,
1066 r#""#.unindent(),
1067 |settings| settings.age = Some(37),
1068 r#"{
1069 "user": {
1070 "age": 37
1071 }
1072 }
1073 "#
1074 .unindent(),
1075 cx,
1076 );
1077 }
1078
1079 fn check_settings_update<T: Setting>(
1080 store: &mut SettingsStore,
1081 old_json: String,
1082 update: fn(&mut T::FileContent),
1083 expected_new_json: String,
1084 cx: &mut AppContext,
1085 ) {
1086 store.set_user_settings(&old_json, cx).ok();
1087 let edits = store.edits_for_update::<T>(&old_json, update);
1088 let mut new_json = old_json;
1089 for (range, replacement) in edits.into_iter() {
1090 new_json.replace_range(range, &replacement);
1091 }
1092 pretty_assertions::assert_eq!(new_json, expected_new_json);
1093 }
1094
1095 #[derive(Debug, PartialEq, Deserialize)]
1096 struct UserSettings {
1097 name: String,
1098 age: u32,
1099 staff: bool,
1100 }
1101
1102 #[derive(Default, Clone, Serialize, Deserialize, JsonSchema)]
1103 struct UserSettingsJson {
1104 name: Option<String>,
1105 age: Option<u32>,
1106 staff: Option<bool>,
1107 }
1108
1109 impl Setting for UserSettings {
1110 const KEY: Option<&'static str> = Some("user");
1111 type FileContent = UserSettingsJson;
1112
1113 fn load(
1114 default_value: &UserSettingsJson,
1115 user_values: &[&UserSettingsJson],
1116 _: &AppContext,
1117 ) -> Result<Self> {
1118 Self::load_via_json_merge(default_value, user_values)
1119 }
1120 }
1121
1122 #[derive(Debug, Deserialize, PartialEq)]
1123 struct TurboSetting(bool);
1124
1125 impl Setting for TurboSetting {
1126 const KEY: Option<&'static str> = Some("turbo");
1127 type FileContent = Option<bool>;
1128
1129 fn load(
1130 default_value: &Option<bool>,
1131 user_values: &[&Option<bool>],
1132 _: &AppContext,
1133 ) -> Result<Self> {
1134 Self::load_via_json_merge(default_value, user_values)
1135 }
1136 }
1137
1138 #[derive(Clone, Debug, PartialEq, Deserialize)]
1139 struct MultiKeySettings {
1140 #[serde(default)]
1141 key1: String,
1142 #[serde(default)]
1143 key2: String,
1144 }
1145
1146 #[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
1147 struct MultiKeySettingsJson {
1148 key1: Option<String>,
1149 key2: Option<String>,
1150 }
1151
1152 impl Setting for MultiKeySettings {
1153 const KEY: Option<&'static str> = None;
1154
1155 type FileContent = MultiKeySettingsJson;
1156
1157 fn load(
1158 default_value: &MultiKeySettingsJson,
1159 user_values: &[&MultiKeySettingsJson],
1160 _: &AppContext,
1161 ) -> Result<Self> {
1162 Self::load_via_json_merge(default_value, user_values)
1163 }
1164 }
1165
1166 #[derive(Debug, Deserialize)]
1167 struct JournalSettings {
1168 pub path: String,
1169 pub hour_format: HourFormat,
1170 }
1171
1172 #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
1173 #[serde(rename_all = "snake_case")]
1174 enum HourFormat {
1175 Hour12,
1176 Hour24,
1177 }
1178
1179 #[derive(Clone, Default, Debug, Serialize, Deserialize, JsonSchema)]
1180 struct JournalSettingsJson {
1181 pub path: Option<String>,
1182 pub hour_format: Option<HourFormat>,
1183 }
1184
1185 impl Setting for JournalSettings {
1186 const KEY: Option<&'static str> = Some("journal");
1187
1188 type FileContent = JournalSettingsJson;
1189
1190 fn load(
1191 default_value: &JournalSettingsJson,
1192 user_values: &[&JournalSettingsJson],
1193 _: &AppContext,
1194 ) -> Result<Self> {
1195 Self::load_via_json_merge(default_value, user_values)
1196 }
1197 }
1198
1199 #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
1200 struct LanguageSettings {
1201 #[serde(default)]
1202 languages: HashMap<String, LanguageSettingEntry>,
1203 }
1204
1205 #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
1206 struct LanguageSettingEntry {
1207 is_enabled: bool,
1208 }
1209
1210 impl Setting for LanguageSettings {
1211 const KEY: Option<&'static str> = None;
1212
1213 type FileContent = Self;
1214
1215 fn load(default_value: &Self, user_values: &[&Self], _: &AppContext) -> Result<Self> {
1216 Self::load_via_json_merge(default_value, user_values)
1217 }
1218 }
1219}