1use anyhow::{anyhow, Context, Result};
2use collections::{btree_map, hash_map, BTreeMap, HashMap};
3use fs::Fs;
4use futures::{channel::mpsc, future::LocalBoxFuture, FutureExt, StreamExt};
5use gpui::{AppContext, AsyncAppContext, BorrowAppContext, Global, Task, UpdateGlobal};
6use lazy_static::lazy_static;
7use schemars::{gen::SchemaGenerator, schema::RootSchema, JsonSchema};
8use serde::{de::DeserializeOwned, Deserialize as _, Serialize};
9use smallvec::SmallVec;
10use std::{
11 any::{type_name, Any, TypeId},
12 fmt::Debug,
13 ops::Range,
14 path::Path,
15 str,
16 sync::Arc,
17};
18use util::{merge_non_null_json_value_into, RangeExt, ResultExt as _};
19
20use crate::SettingsJsonSchemaParams;
21
22/// A value that can be defined as a user setting.
23///
24/// Settings can be loaded from a combination of multiple JSON files.
25pub trait Settings: 'static + Send + Sync {
26 /// The name of a key within the JSON file from which this setting should
27 /// be deserialized. If this is `None`, then the setting will be deserialized
28 /// from the root object.
29 const KEY: Option<&'static str>;
30
31 /// The type that is stored in an individual JSON file.
32 type FileContent: Clone + Default + Serialize + DeserializeOwned + JsonSchema;
33
34 /// The logic for combining together values from one or more JSON files into the
35 /// final value for this setting.
36 fn load(sources: SettingsSources<Self::FileContent>, cx: &mut AppContext) -> Result<Self>
37 where
38 Self: Sized;
39
40 fn json_schema(
41 generator: &mut SchemaGenerator,
42 _: &SettingsJsonSchemaParams,
43 _: &AppContext,
44 ) -> RootSchema {
45 generator.root_schema_for::<Self::FileContent>()
46 }
47
48 fn missing_default() -> anyhow::Error {
49 anyhow::anyhow!("missing default")
50 }
51
52 fn register(cx: &mut AppContext)
53 where
54 Self: Sized,
55 {
56 SettingsStore::update_global(cx, |store, cx| {
57 store.register_setting::<Self>(cx);
58 });
59 }
60
61 #[track_caller]
62 fn get<'a>(path: Option<SettingsLocation>, cx: &'a AppContext) -> &'a Self
63 where
64 Self: Sized,
65 {
66 cx.global::<SettingsStore>().get(path)
67 }
68
69 #[track_caller]
70 fn get_global(cx: &AppContext) -> &Self
71 where
72 Self: Sized,
73 {
74 cx.global::<SettingsStore>().get(None)
75 }
76
77 #[track_caller]
78 fn try_read_global<R>(cx: &AsyncAppContext, f: impl FnOnce(&Self) -> R) -> Option<R>
79 where
80 Self: Sized,
81 {
82 cx.try_read_global(|s: &SettingsStore, _| f(s.get(None)))
83 }
84
85 #[track_caller]
86 fn override_global(settings: Self, cx: &mut AppContext)
87 where
88 Self: Sized,
89 {
90 cx.global_mut::<SettingsStore>().override_global(settings)
91 }
92}
93
94#[derive(Clone, Copy, Debug)]
95pub struct SettingsSources<'a, T> {
96 /// The default Zed settings.
97 pub default: &'a T,
98 /// Settings provided by extensions.
99 pub extensions: Option<&'a T>,
100 /// The user settings.
101 pub user: Option<&'a T>,
102 /// The user settings for the current release channel.
103 pub release_channel: Option<&'a T>,
104 /// The project settings, ordered from least specific to most specific.
105 pub project: &'a [&'a T],
106}
107
108impl<'a, T: Serialize> SettingsSources<'a, T> {
109 /// Returns an iterator over the default settings as well as all settings customizations.
110 pub fn defaults_and_customizations(&self) -> impl Iterator<Item = &T> {
111 [self.default].into_iter().chain(self.customizations())
112 }
113
114 /// Returns an iterator over all of the settings customizations.
115 pub fn customizations(&self) -> impl Iterator<Item = &T> {
116 self.extensions
117 .into_iter()
118 .chain(self.user)
119 .chain(self.release_channel)
120 .chain(self.project.iter().copied())
121 }
122
123 /// Returns the settings after performing a JSON merge of the provided customizations.
124 ///
125 /// Customizations later in the iterator win out over the earlier ones.
126 pub fn json_merge_with<O: DeserializeOwned>(
127 customizations: impl Iterator<Item = &'a T>,
128 ) -> Result<O> {
129 let mut merged = serde_json::Value::Null;
130 for value in customizations {
131 merge_non_null_json_value_into(serde_json::to_value(value).unwrap(), &mut merged);
132 }
133 Ok(serde_json::from_value(merged)?)
134 }
135
136 /// Returns the settings after performing a JSON merge of the customizations into the
137 /// default settings.
138 ///
139 /// More-specific customizations win out over the less-specific ones.
140 pub fn json_merge<O: DeserializeOwned>(&'a self) -> Result<O> {
141 Self::json_merge_with(self.defaults_and_customizations())
142 }
143}
144
145#[derive(Clone, Copy)]
146pub struct SettingsLocation<'a> {
147 pub worktree_id: usize,
148 pub path: &'a Path,
149}
150
151/// A set of strongly-typed setting values defined via multiple JSON files.
152pub struct SettingsStore {
153 setting_values: HashMap<TypeId, Box<dyn AnySettingValue>>,
154 raw_default_settings: serde_json::Value,
155 raw_user_settings: serde_json::Value,
156 raw_extension_settings: serde_json::Value,
157 raw_local_settings: BTreeMap<(usize, Arc<Path>), serde_json::Value>,
158 tab_size_callback: Option<(
159 TypeId,
160 Box<dyn Fn(&dyn Any) -> Option<usize> + Send + Sync + 'static>,
161 )>,
162 _setting_file_updates: Task<()>,
163 setting_file_updates_tx: mpsc::UnboundedSender<
164 Box<dyn FnOnce(AsyncAppContext) -> LocalBoxFuture<'static, Result<()>>>,
165 >,
166}
167
168impl Global for SettingsStore {}
169
170#[derive(Debug)]
171struct SettingValue<T> {
172 global_value: Option<T>,
173 local_values: Vec<(usize, Arc<Path>, T)>,
174}
175
176trait AnySettingValue: 'static + Send + Sync {
177 fn key(&self) -> Option<&'static str>;
178 fn setting_type_name(&self) -> &'static str;
179 fn deserialize_setting(&self, json: &serde_json::Value) -> Result<DeserializedSetting>;
180 fn load_setting(
181 &self,
182 sources: SettingsSources<DeserializedSetting>,
183 cx: &mut AppContext,
184 ) -> Result<Box<dyn Any>>;
185 fn value_for_path(&self, path: Option<SettingsLocation>) -> &dyn Any;
186 fn set_global_value(&mut self, value: Box<dyn Any>);
187 fn set_local_value(&mut self, root_id: usize, path: Arc<Path>, value: Box<dyn Any>);
188 fn json_schema(
189 &self,
190 generator: &mut SchemaGenerator,
191 _: &SettingsJsonSchemaParams,
192 cx: &AppContext,
193 ) -> RootSchema;
194}
195
196struct DeserializedSetting(Box<dyn Any>);
197
198impl SettingsStore {
199 pub fn new(cx: &AppContext) -> Self {
200 let (setting_file_updates_tx, mut setting_file_updates_rx) = mpsc::unbounded();
201 Self {
202 setting_values: Default::default(),
203 raw_default_settings: serde_json::json!({}),
204 raw_user_settings: serde_json::json!({}),
205 raw_extension_settings: serde_json::json!({}),
206 raw_local_settings: Default::default(),
207 tab_size_callback: Default::default(),
208 setting_file_updates_tx,
209 _setting_file_updates: cx.spawn(|cx| async move {
210 while let Some(setting_file_update) = setting_file_updates_rx.next().await {
211 (setting_file_update)(cx.clone()).await.log_err();
212 }
213 }),
214 }
215 }
216
217 pub fn update<C, R>(cx: &mut C, f: impl FnOnce(&mut Self, &mut C) -> R) -> R
218 where
219 C: BorrowAppContext,
220 {
221 cx.update_global(f)
222 }
223
224 /// Add a new type of setting to the store.
225 pub fn register_setting<T: Settings>(&mut self, cx: &mut AppContext) {
226 let setting_type_id = TypeId::of::<T>();
227 let entry = self.setting_values.entry(setting_type_id);
228 if matches!(entry, hash_map::Entry::Occupied(_)) {
229 return;
230 }
231
232 let setting_value = entry.or_insert(Box::new(SettingValue::<T> {
233 global_value: None,
234 local_values: Vec::new(),
235 }));
236
237 if let Some(default_settings) = setting_value
238 .deserialize_setting(&self.raw_default_settings)
239 .log_err()
240 {
241 let user_value = setting_value
242 .deserialize_setting(&self.raw_user_settings)
243 .log_err();
244
245 let mut release_channel_value = None;
246 if let Some(release_settings) = &self
247 .raw_user_settings
248 .get(release_channel::RELEASE_CHANNEL.dev_name())
249 {
250 release_channel_value = setting_value
251 .deserialize_setting(release_settings)
252 .log_err();
253 }
254
255 let extension_value = setting_value
256 .deserialize_setting(&self.raw_extension_settings)
257 .log_err();
258
259 if let Some(setting) = setting_value
260 .load_setting(
261 SettingsSources {
262 default: &default_settings,
263 release_channel: release_channel_value.as_ref(),
264 extensions: extension_value.as_ref(),
265 user: user_value.as_ref(),
266 project: &[],
267 },
268 cx,
269 )
270 .context("A default setting must be added to the `default.json` file")
271 .log_err()
272 {
273 setting_value.set_global_value(setting);
274 }
275 }
276 }
277
278 /// Get the value of a setting.
279 ///
280 /// Panics if the given setting type has not been registered, or if there is no
281 /// value for this setting.
282 pub fn get<T: Settings>(&self, path: Option<SettingsLocation>) -> &T {
283 self.setting_values
284 .get(&TypeId::of::<T>())
285 .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()))
286 .value_for_path(path)
287 .downcast_ref::<T>()
288 .expect("no default value for setting type")
289 }
290
291 /// Override the global value for a setting.
292 ///
293 /// The given value will be overwritten if the user settings file changes.
294 pub fn override_global<T: Settings>(&mut self, value: T) {
295 self.setting_values
296 .get_mut(&TypeId::of::<T>())
297 .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()))
298 .set_global_value(Box::new(value))
299 }
300
301 /// Get the user's settings as a raw JSON value.
302 ///
303 /// This is only for debugging and reporting. For user-facing functionality,
304 /// use the typed setting interface.
305 pub fn raw_user_settings(&self) -> &serde_json::Value {
306 &self.raw_user_settings
307 }
308
309 #[cfg(any(test, feature = "test-support"))]
310 pub fn test(cx: &mut AppContext) -> Self {
311 let mut this = Self::new(cx);
312 this.set_default_settings(&crate::test_settings(), cx)
313 .unwrap();
314 this.set_user_settings("{}", cx).unwrap();
315 this
316 }
317
318 /// Updates the value of a setting in the user's global configuration.
319 ///
320 /// This is only for tests. Normally, settings are only loaded from
321 /// JSON files.
322 #[cfg(any(test, feature = "test-support"))]
323 pub fn update_user_settings<T: Settings>(
324 &mut self,
325 cx: &mut AppContext,
326 update: impl FnOnce(&mut T::FileContent),
327 ) {
328 let old_text = serde_json::to_string(&self.raw_user_settings).unwrap();
329 let new_text = self.new_text_for_update::<T>(old_text, update);
330 self.set_user_settings(&new_text, cx).unwrap();
331 }
332
333 async fn load_settings(fs: &Arc<dyn Fs>) -> Result<String> {
334 match fs.load(paths::settings_file()).await {
335 result @ Ok(_) => result,
336 Err(err) => {
337 if let Some(e) = err.downcast_ref::<std::io::Error>() {
338 if e.kind() == std::io::ErrorKind::NotFound {
339 return Ok(crate::initial_user_settings_content().to_string());
340 }
341 }
342 Err(err)
343 }
344 }
345 }
346
347 pub fn update_settings_file<T: Settings>(
348 &self,
349 fs: Arc<dyn Fs>,
350 update: impl 'static + Send + FnOnce(&mut T::FileContent, &AppContext),
351 ) {
352 self.setting_file_updates_tx
353 .unbounded_send(Box::new(move |cx: AsyncAppContext| {
354 async move {
355 let old_text = Self::load_settings(&fs).await?;
356 let new_text = cx.read_global(|store: &SettingsStore, cx| {
357 store.new_text_for_update::<T>(old_text, |content| update(content, cx))
358 })?;
359 let initial_path = paths::settings_file().as_path();
360 if fs.is_file(initial_path).await {
361 let resolved_path =
362 fs.canonicalize(initial_path).await.with_context(|| {
363 format!("Failed to canonicalize settings path {:?}", initial_path)
364 })?;
365
366 fs.atomic_write(resolved_path.clone(), new_text)
367 .await
368 .with_context(|| {
369 format!("Failed to write settings to file {:?}", resolved_path)
370 })?;
371 } else {
372 fs.atomic_write(initial_path.to_path_buf(), new_text)
373 .await
374 .with_context(|| {
375 format!("Failed to write settings to file {:?}", initial_path)
376 })?;
377 }
378
379 anyhow::Ok(())
380 }
381 .boxed_local()
382 }))
383 .ok();
384 }
385
386 /// Updates the value of a setting in a JSON file, returning the new text
387 /// for that JSON file.
388 pub fn new_text_for_update<T: Settings>(
389 &self,
390 old_text: String,
391 update: impl FnOnce(&mut T::FileContent),
392 ) -> String {
393 let edits = self.edits_for_update::<T>(&old_text, update);
394 let mut new_text = old_text;
395 for (range, replacement) in edits.into_iter() {
396 new_text.replace_range(range, &replacement);
397 }
398 new_text
399 }
400
401 /// Updates the value of a setting in a JSON file, returning a list
402 /// of edits to apply to the JSON file.
403 pub fn edits_for_update<T: Settings>(
404 &self,
405 text: &str,
406 update: impl FnOnce(&mut T::FileContent),
407 ) -> Vec<(Range<usize>, String)> {
408 let setting_type_id = TypeId::of::<T>();
409
410 let setting = self
411 .setting_values
412 .get(&setting_type_id)
413 .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()));
414 let raw_settings = parse_json_with_comments::<serde_json::Value>(text).unwrap_or_default();
415 let old_content = match setting.deserialize_setting(&raw_settings) {
416 Ok(content) => content.0.downcast::<T::FileContent>().unwrap(),
417 Err(_) => Box::<<T as Settings>::FileContent>::default(),
418 };
419 let mut new_content = old_content.clone();
420 update(&mut new_content);
421
422 let old_value = serde_json::to_value(&old_content).unwrap();
423 let new_value = serde_json::to_value(new_content).unwrap();
424
425 let mut key_path = Vec::new();
426 if let Some(key) = T::KEY {
427 key_path.push(key);
428 }
429
430 let mut edits = Vec::new();
431 let tab_size = self.json_tab_size();
432 let mut text = text.to_string();
433 update_value_in_json_text(
434 &mut text,
435 &mut key_path,
436 tab_size,
437 &old_value,
438 &new_value,
439 &mut edits,
440 );
441 edits
442 }
443
444 /// Configure the tab sized when updating JSON files.
445 pub fn set_json_tab_size_callback<T: Settings>(
446 &mut self,
447 get_tab_size: fn(&T) -> Option<usize>,
448 ) {
449 self.tab_size_callback = Some((
450 TypeId::of::<T>(),
451 Box::new(move |value| get_tab_size(value.downcast_ref::<T>().unwrap())),
452 ));
453 }
454
455 fn json_tab_size(&self) -> usize {
456 const DEFAULT_JSON_TAB_SIZE: usize = 2;
457
458 if let Some((setting_type_id, callback)) = &self.tab_size_callback {
459 let setting_value = self.setting_values.get(setting_type_id).unwrap();
460 let value = setting_value.value_for_path(None);
461 if let Some(value) = callback(value) {
462 return value;
463 }
464 }
465
466 DEFAULT_JSON_TAB_SIZE
467 }
468
469 /// Sets the default settings via a JSON string.
470 ///
471 /// The string should contain a JSON object with a default value for every setting.
472 pub fn set_default_settings(
473 &mut self,
474 default_settings_content: &str,
475 cx: &mut AppContext,
476 ) -> Result<()> {
477 let settings: serde_json::Value = parse_json_with_comments(default_settings_content)?;
478 if settings.is_object() {
479 self.raw_default_settings = settings;
480 self.recompute_values(None, cx)?;
481 Ok(())
482 } else {
483 Err(anyhow!("settings must be an object"))
484 }
485 }
486
487 /// Sets the user settings via a JSON string.
488 pub fn set_user_settings(
489 &mut self,
490 user_settings_content: &str,
491 cx: &mut AppContext,
492 ) -> Result<()> {
493 let settings: serde_json::Value = if user_settings_content.is_empty() {
494 parse_json_with_comments("{}")?
495 } else {
496 parse_json_with_comments(user_settings_content)?
497 };
498 if settings.is_object() {
499 self.raw_user_settings = settings;
500 self.recompute_values(None, cx)?;
501 Ok(())
502 } else {
503 Err(anyhow!("settings must be an object"))
504 }
505 }
506
507 /// Add or remove a set of local settings via a JSON string.
508 pub fn set_local_settings(
509 &mut self,
510 root_id: usize,
511 path: Arc<Path>,
512 settings_content: Option<&str>,
513 cx: &mut AppContext,
514 ) -> Result<()> {
515 if settings_content.is_some_and(|content| !content.is_empty()) {
516 self.raw_local_settings.insert(
517 (root_id, path.clone()),
518 parse_json_with_comments(settings_content.unwrap())?,
519 );
520 } else {
521 self.raw_local_settings.remove(&(root_id, path.clone()));
522 }
523 self.recompute_values(Some((root_id, &path)), cx)?;
524 Ok(())
525 }
526
527 pub fn set_extension_settings<T: Serialize>(
528 &mut self,
529 content: T,
530 cx: &mut AppContext,
531 ) -> Result<()> {
532 let settings: serde_json::Value = serde_json::to_value(content)?;
533 if settings.is_object() {
534 self.raw_extension_settings = settings;
535 self.recompute_values(None, cx)?;
536 Ok(())
537 } else {
538 Err(anyhow!("settings must be an object"))
539 }
540 }
541
542 /// Add or remove a set of local settings via a JSON string.
543 pub fn clear_local_settings(&mut self, root_id: usize, cx: &mut AppContext) -> Result<()> {
544 self.raw_local_settings.retain(|k, _| k.0 != root_id);
545 self.recompute_values(Some((root_id, "".as_ref())), cx)?;
546 Ok(())
547 }
548
549 pub fn local_settings(&self, root_id: usize) -> impl '_ + Iterator<Item = (Arc<Path>, String)> {
550 self.raw_local_settings
551 .range((root_id, Path::new("").into())..(root_id + 1, Path::new("").into()))
552 .map(|((_, path), content)| (path.clone(), serde_json::to_string(content).unwrap()))
553 }
554
555 pub fn json_schema(
556 &self,
557 schema_params: &SettingsJsonSchemaParams,
558 cx: &AppContext,
559 ) -> serde_json::Value {
560 use schemars::{
561 gen::SchemaSettings,
562 schema::{Schema, SchemaObject},
563 };
564
565 let settings = SchemaSettings::draft07().with(|settings| {
566 settings.option_add_null_type = false;
567 });
568 let mut generator = SchemaGenerator::new(settings);
569 let mut combined_schema = RootSchema::default();
570
571 for setting_value in self.setting_values.values() {
572 let setting_schema = setting_value.json_schema(&mut generator, schema_params, cx);
573 combined_schema
574 .definitions
575 .extend(setting_schema.definitions);
576
577 let target_schema = if let Some(key) = setting_value.key() {
578 let key_schema = combined_schema
579 .schema
580 .object()
581 .properties
582 .entry(key.to_string())
583 .or_insert_with(|| Schema::Object(SchemaObject::default()));
584 if let Schema::Object(key_schema) = key_schema {
585 key_schema
586 } else {
587 continue;
588 }
589 } else {
590 &mut combined_schema.schema
591 };
592
593 merge_schema(target_schema, setting_schema.schema);
594 }
595
596 fn merge_schema(target: &mut SchemaObject, mut source: SchemaObject) {
597 let source_subschemas = source.subschemas();
598 let target_subschemas = target.subschemas();
599 if let Some(all_of) = source_subschemas.all_of.take() {
600 target_subschemas
601 .all_of
602 .get_or_insert(Vec::new())
603 .extend(all_of);
604 }
605 if let Some(any_of) = source_subschemas.any_of.take() {
606 target_subschemas
607 .any_of
608 .get_or_insert(Vec::new())
609 .extend(any_of);
610 }
611 if let Some(one_of) = source_subschemas.one_of.take() {
612 target_subschemas
613 .one_of
614 .get_or_insert(Vec::new())
615 .extend(one_of);
616 }
617
618 if let Some(source) = source.object {
619 let target_properties = &mut target.object().properties;
620 for (key, value) in source.properties {
621 match target_properties.entry(key) {
622 btree_map::Entry::Vacant(e) => {
623 e.insert(value);
624 }
625 btree_map::Entry::Occupied(e) => {
626 if let (Schema::Object(target), Schema::Object(src)) =
627 (e.into_mut(), value)
628 {
629 merge_schema(target, src);
630 }
631 }
632 }
633 }
634 }
635
636 overwrite(&mut target.instance_type, source.instance_type);
637 overwrite(&mut target.string, source.string);
638 overwrite(&mut target.number, source.number);
639 overwrite(&mut target.reference, source.reference);
640 overwrite(&mut target.array, source.array);
641 overwrite(&mut target.enum_values, source.enum_values);
642
643 fn overwrite<T>(target: &mut Option<T>, source: Option<T>) {
644 if let Some(source) = source {
645 *target = Some(source);
646 }
647 }
648 }
649
650 for release_stage in ["dev", "nightly", "stable", "preview"] {
651 let schema = combined_schema.schema.clone();
652 combined_schema
653 .schema
654 .object()
655 .properties
656 .insert(release_stage.to_string(), schema.into());
657 }
658
659 serde_json::to_value(&combined_schema).unwrap()
660 }
661
662 fn recompute_values(
663 &mut self,
664 changed_local_path: Option<(usize, &Path)>,
665 cx: &mut AppContext,
666 ) -> Result<()> {
667 // Reload the global and local values for every setting.
668 let mut project_settings_stack = Vec::<DeserializedSetting>::new();
669 let mut paths_stack = Vec::<Option<(usize, &Path)>>::new();
670 for setting_value in self.setting_values.values_mut() {
671 let default_settings = setting_value.deserialize_setting(&self.raw_default_settings)?;
672
673 let extension_settings = setting_value
674 .deserialize_setting(&self.raw_extension_settings)
675 .log_err();
676
677 let user_settings = setting_value
678 .deserialize_setting(&self.raw_user_settings)
679 .log_err();
680
681 let mut release_channel_settings = None;
682 if let Some(release_settings) = &self
683 .raw_user_settings
684 .get(release_channel::RELEASE_CHANNEL.dev_name())
685 {
686 if let Some(release_settings) = setting_value
687 .deserialize_setting(release_settings)
688 .log_err()
689 {
690 release_channel_settings = Some(release_settings);
691 }
692 }
693
694 // If the global settings file changed, reload the global value for the field.
695 if changed_local_path.is_none() {
696 if let Some(value) = setting_value
697 .load_setting(
698 SettingsSources {
699 default: &default_settings,
700 extensions: extension_settings.as_ref(),
701 user: user_settings.as_ref(),
702 release_channel: release_channel_settings.as_ref(),
703 project: &[],
704 },
705 cx,
706 )
707 .log_err()
708 {
709 setting_value.set_global_value(value);
710 }
711 }
712
713 // Reload the local values for the setting.
714 paths_stack.clear();
715 project_settings_stack.clear();
716 for ((root_id, path), local_settings) in &self.raw_local_settings {
717 // Build a stack of all of the local values for that setting.
718 while let Some(prev_entry) = paths_stack.last() {
719 if let Some((prev_root_id, prev_path)) = prev_entry {
720 if root_id != prev_root_id || !path.starts_with(prev_path) {
721 paths_stack.pop();
722 project_settings_stack.pop();
723 continue;
724 }
725 }
726 break;
727 }
728
729 if let Some(local_settings) =
730 setting_value.deserialize_setting(local_settings).log_err()
731 {
732 paths_stack.push(Some((*root_id, path.as_ref())));
733 project_settings_stack.push(local_settings);
734
735 // If a local settings file changed, then avoid recomputing local
736 // settings for any path outside of that directory.
737 if changed_local_path.map_or(false, |(changed_root_id, changed_local_path)| {
738 *root_id != changed_root_id || !path.starts_with(changed_local_path)
739 }) {
740 continue;
741 }
742
743 if let Some(value) = setting_value
744 .load_setting(
745 SettingsSources {
746 default: &default_settings,
747 extensions: extension_settings.as_ref(),
748 user: user_settings.as_ref(),
749 release_channel: release_channel_settings.as_ref(),
750 project: &project_settings_stack.iter().collect::<Vec<_>>(),
751 },
752 cx,
753 )
754 .log_err()
755 {
756 setting_value.set_local_value(*root_id, path.clone(), value);
757 }
758 }
759 }
760 }
761 Ok(())
762 }
763}
764
765impl Debug for SettingsStore {
766 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
767 f.debug_struct("SettingsStore")
768 .field(
769 "types",
770 &self
771 .setting_values
772 .values()
773 .map(|value| value.setting_type_name())
774 .collect::<Vec<_>>(),
775 )
776 .field("default_settings", &self.raw_default_settings)
777 .field("user_settings", &self.raw_user_settings)
778 .field("local_settings", &self.raw_local_settings)
779 .finish_non_exhaustive()
780 }
781}
782
783impl<T: Settings> AnySettingValue for SettingValue<T> {
784 fn key(&self) -> Option<&'static str> {
785 T::KEY
786 }
787
788 fn setting_type_name(&self) -> &'static str {
789 type_name::<T>()
790 }
791
792 fn load_setting(
793 &self,
794 values: SettingsSources<DeserializedSetting>,
795 cx: &mut AppContext,
796 ) -> Result<Box<dyn Any>> {
797 Ok(Box::new(T::load(
798 SettingsSources {
799 default: values.default.0.downcast_ref::<T::FileContent>().unwrap(),
800 extensions: values
801 .extensions
802 .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
803 user: values
804 .user
805 .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
806 release_channel: values
807 .release_channel
808 .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
809 project: values
810 .project
811 .iter()
812 .map(|value| value.0.downcast_ref().unwrap())
813 .collect::<SmallVec<[_; 3]>>()
814 .as_slice(),
815 },
816 cx,
817 )?))
818 }
819
820 fn deserialize_setting(&self, mut json: &serde_json::Value) -> Result<DeserializedSetting> {
821 if let Some(key) = T::KEY {
822 if let Some(value) = json.get(key) {
823 json = value;
824 } else {
825 let value = T::FileContent::default();
826 return Ok(DeserializedSetting(Box::new(value)));
827 }
828 }
829 let value = T::FileContent::deserialize(json)?;
830 Ok(DeserializedSetting(Box::new(value)))
831 }
832
833 fn value_for_path(&self, path: Option<SettingsLocation>) -> &dyn Any {
834 if let Some(SettingsLocation { worktree_id, path }) = path {
835 for (settings_root_id, settings_path, value) in self.local_values.iter().rev() {
836 if worktree_id == *settings_root_id && path.starts_with(settings_path) {
837 return value;
838 }
839 }
840 }
841 self.global_value
842 .as_ref()
843 .unwrap_or_else(|| panic!("no default value for setting {}", self.setting_type_name()))
844 }
845
846 fn set_global_value(&mut self, value: Box<dyn Any>) {
847 self.global_value = Some(*value.downcast().unwrap());
848 }
849
850 fn set_local_value(&mut self, root_id: usize, path: Arc<Path>, value: Box<dyn Any>) {
851 let value = *value.downcast().unwrap();
852 match self
853 .local_values
854 .binary_search_by_key(&(root_id, &path), |e| (e.0, &e.1))
855 {
856 Ok(ix) => self.local_values[ix].2 = value,
857 Err(ix) => self.local_values.insert(ix, (root_id, path, value)),
858 }
859 }
860
861 fn json_schema(
862 &self,
863 generator: &mut SchemaGenerator,
864 params: &SettingsJsonSchemaParams,
865 cx: &AppContext,
866 ) -> RootSchema {
867 T::json_schema(generator, params, cx)
868 }
869}
870
871fn update_value_in_json_text<'a>(
872 text: &mut String,
873 key_path: &mut Vec<&'a str>,
874 tab_size: usize,
875 old_value: &'a serde_json::Value,
876 new_value: &'a serde_json::Value,
877 edits: &mut Vec<(Range<usize>, String)>,
878) {
879 // If the old and new values are both objects, then compare them key by key,
880 // preserving the comments and formatting of the unchanged parts. Otherwise,
881 // replace the old value with the new value.
882 if let (serde_json::Value::Object(old_object), serde_json::Value::Object(new_object)) =
883 (old_value, new_value)
884 {
885 for (key, old_sub_value) in old_object.iter() {
886 key_path.push(key);
887 let new_sub_value = new_object.get(key).unwrap_or(&serde_json::Value::Null);
888 update_value_in_json_text(
889 text,
890 key_path,
891 tab_size,
892 old_sub_value,
893 new_sub_value,
894 edits,
895 );
896 key_path.pop();
897 }
898 for (key, new_sub_value) in new_object.iter() {
899 key_path.push(key);
900 if !old_object.contains_key(key) {
901 update_value_in_json_text(
902 text,
903 key_path,
904 tab_size,
905 &serde_json::Value::Null,
906 new_sub_value,
907 edits,
908 );
909 }
910 key_path.pop();
911 }
912 } else if old_value != new_value {
913 let mut new_value = new_value.clone();
914 if let Some(new_object) = new_value.as_object_mut() {
915 new_object.retain(|_, v| !v.is_null());
916 }
917 let (range, replacement) = replace_value_in_json_text(text, key_path, tab_size, &new_value);
918 text.replace_range(range.clone(), &replacement);
919 edits.push((range, replacement));
920 }
921}
922
923fn replace_value_in_json_text(
924 text: &str,
925 key_path: &[&str],
926 tab_size: usize,
927 new_value: &serde_json::Value,
928) -> (Range<usize>, String) {
929 lazy_static! {
930 static ref PAIR_QUERY: tree_sitter::Query = tree_sitter::Query::new(
931 &tree_sitter_json::language(),
932 "(pair key: (string) @key value: (_) @value)",
933 )
934 .unwrap();
935 }
936
937 let mut parser = tree_sitter::Parser::new();
938 parser.set_language(&tree_sitter_json::language()).unwrap();
939 let syntax_tree = parser.parse(text, None).unwrap();
940
941 let mut cursor = tree_sitter::QueryCursor::new();
942
943 let mut depth = 0;
944 let mut last_value_range = 0..0;
945 let mut first_key_start = None;
946 let mut existing_value_range = 0..text.len();
947 let matches = cursor.matches(&PAIR_QUERY, syntax_tree.root_node(), text.as_bytes());
948 for mat in matches {
949 if mat.captures.len() != 2 {
950 continue;
951 }
952
953 let key_range = mat.captures[0].node.byte_range();
954 let value_range = mat.captures[1].node.byte_range();
955
956 // Don't enter sub objects until we find an exact
957 // match for the current keypath
958 if last_value_range.contains_inclusive(&value_range) {
959 continue;
960 }
961
962 last_value_range = value_range.clone();
963
964 if key_range.start > existing_value_range.end {
965 break;
966 }
967
968 first_key_start.get_or_insert(key_range.start);
969
970 let found_key = text
971 .get(key_range.clone())
972 .map(|key_text| key_text == format!("\"{}\"", key_path[depth]))
973 .unwrap_or(false);
974
975 if found_key {
976 existing_value_range = value_range;
977 // Reset last value range when increasing in depth
978 last_value_range = existing_value_range.start..existing_value_range.start;
979 depth += 1;
980
981 if depth == key_path.len() {
982 break;
983 }
984
985 first_key_start = None;
986 }
987 }
988
989 // We found the exact key we want, insert the new value
990 if depth == key_path.len() {
991 let new_val = to_pretty_json(&new_value, tab_size, tab_size * depth);
992 (existing_value_range, new_val)
993 } else {
994 // We have key paths, construct the sub objects
995 let new_key = key_path[depth];
996
997 // We don't have the key, construct the nested objects
998 let mut new_value = serde_json::to_value(new_value).unwrap();
999 for key in key_path[(depth + 1)..].iter().rev() {
1000 new_value = serde_json::json!({ key.to_string(): new_value });
1001 }
1002
1003 if let Some(first_key_start) = first_key_start {
1004 let mut row = 0;
1005 let mut column = 0;
1006 for (ix, char) in text.char_indices() {
1007 if ix == first_key_start {
1008 break;
1009 }
1010 if char == '\n' {
1011 row += 1;
1012 column = 0;
1013 } else {
1014 column += char.len_utf8();
1015 }
1016 }
1017
1018 if row > 0 {
1019 // depth is 0 based, but division needs to be 1 based.
1020 let new_val = to_pretty_json(&new_value, column / (depth + 1), column);
1021 let space = ' ';
1022 let content = format!("\"{new_key}\": {new_val},\n{space:width$}", width = column);
1023 (first_key_start..first_key_start, content)
1024 } else {
1025 let new_val = serde_json::to_string(&new_value).unwrap();
1026 let mut content = format!(r#""{new_key}": {new_val},"#);
1027 content.push(' ');
1028 (first_key_start..first_key_start, content)
1029 }
1030 } else {
1031 new_value = serde_json::json!({ new_key.to_string(): new_value });
1032 let indent_prefix_len = 4 * depth;
1033 let mut new_val = to_pretty_json(&new_value, 4, indent_prefix_len);
1034 if depth == 0 {
1035 new_val.push('\n');
1036 }
1037
1038 (existing_value_range, new_val)
1039 }
1040 }
1041}
1042
1043fn to_pretty_json(value: &impl Serialize, indent_size: usize, indent_prefix_len: usize) -> String {
1044 const SPACES: [u8; 32] = [b' '; 32];
1045
1046 debug_assert!(indent_size <= SPACES.len());
1047 debug_assert!(indent_prefix_len <= SPACES.len());
1048
1049 let mut output = Vec::new();
1050 let mut ser = serde_json::Serializer::with_formatter(
1051 &mut output,
1052 serde_json::ser::PrettyFormatter::with_indent(&SPACES[0..indent_size.min(SPACES.len())]),
1053 );
1054
1055 value.serialize(&mut ser).unwrap();
1056 let text = String::from_utf8(output).unwrap();
1057
1058 let mut adjusted_text = String::new();
1059 for (i, line) in text.split('\n').enumerate() {
1060 if i > 0 {
1061 adjusted_text.push_str(str::from_utf8(&SPACES[0..indent_prefix_len]).unwrap());
1062 }
1063 adjusted_text.push_str(line);
1064 adjusted_text.push('\n');
1065 }
1066 adjusted_text.pop();
1067 adjusted_text
1068}
1069
1070pub fn parse_json_with_comments<T: DeserializeOwned>(content: &str) -> Result<T> {
1071 Ok(serde_json_lenient::from_str(content)?)
1072}
1073
1074#[cfg(test)]
1075mod tests {
1076 use super::*;
1077 use serde_derive::Deserialize;
1078 use unindent::Unindent;
1079
1080 #[gpui::test]
1081 fn test_settings_store_basic(cx: &mut AppContext) {
1082 let mut store = SettingsStore::new(cx);
1083 store.register_setting::<UserSettings>(cx);
1084 store.register_setting::<TurboSetting>(cx);
1085 store.register_setting::<MultiKeySettings>(cx);
1086 store
1087 .set_default_settings(
1088 r#"{
1089 "turbo": false,
1090 "user": {
1091 "name": "John Doe",
1092 "age": 30,
1093 "staff": false
1094 }
1095 }"#,
1096 cx,
1097 )
1098 .unwrap();
1099
1100 assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(false));
1101 assert_eq!(
1102 store.get::<UserSettings>(None),
1103 &UserSettings {
1104 name: "John Doe".to_string(),
1105 age: 30,
1106 staff: false,
1107 }
1108 );
1109 assert_eq!(
1110 store.get::<MultiKeySettings>(None),
1111 &MultiKeySettings {
1112 key1: String::new(),
1113 key2: String::new(),
1114 }
1115 );
1116
1117 store
1118 .set_user_settings(
1119 r#"{
1120 "turbo": true,
1121 "user": { "age": 31 },
1122 "key1": "a"
1123 }"#,
1124 cx,
1125 )
1126 .unwrap();
1127
1128 assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(true));
1129 assert_eq!(
1130 store.get::<UserSettings>(None),
1131 &UserSettings {
1132 name: "John Doe".to_string(),
1133 age: 31,
1134 staff: false
1135 }
1136 );
1137
1138 store
1139 .set_local_settings(
1140 1,
1141 Path::new("/root1").into(),
1142 Some(r#"{ "user": { "staff": true } }"#),
1143 cx,
1144 )
1145 .unwrap();
1146 store
1147 .set_local_settings(
1148 1,
1149 Path::new("/root1/subdir").into(),
1150 Some(r#"{ "user": { "name": "Jane Doe" } }"#),
1151 cx,
1152 )
1153 .unwrap();
1154
1155 store
1156 .set_local_settings(
1157 1,
1158 Path::new("/root2").into(),
1159 Some(r#"{ "user": { "age": 42 }, "key2": "b" }"#),
1160 cx,
1161 )
1162 .unwrap();
1163
1164 assert_eq!(
1165 store.get::<UserSettings>(Some(SettingsLocation {
1166 worktree_id: 1,
1167 path: Path::new("/root1/something"),
1168 })),
1169 &UserSettings {
1170 name: "John Doe".to_string(),
1171 age: 31,
1172 staff: true
1173 }
1174 );
1175 assert_eq!(
1176 store.get::<UserSettings>(Some(SettingsLocation {
1177 worktree_id: 1,
1178 path: Path::new("/root1/subdir/something")
1179 })),
1180 &UserSettings {
1181 name: "Jane Doe".to_string(),
1182 age: 31,
1183 staff: true
1184 }
1185 );
1186 assert_eq!(
1187 store.get::<UserSettings>(Some(SettingsLocation {
1188 worktree_id: 1,
1189 path: Path::new("/root2/something")
1190 })),
1191 &UserSettings {
1192 name: "John Doe".to_string(),
1193 age: 42,
1194 staff: false
1195 }
1196 );
1197 assert_eq!(
1198 store.get::<MultiKeySettings>(Some(SettingsLocation {
1199 worktree_id: 1,
1200 path: Path::new("/root2/something")
1201 })),
1202 &MultiKeySettings {
1203 key1: "a".to_string(),
1204 key2: "b".to_string(),
1205 }
1206 );
1207 }
1208
1209 #[gpui::test]
1210 fn test_setting_store_assign_json_before_register(cx: &mut AppContext) {
1211 let mut store = SettingsStore::new(cx);
1212 store
1213 .set_default_settings(
1214 r#"{
1215 "turbo": true,
1216 "user": {
1217 "name": "John Doe",
1218 "age": 30,
1219 "staff": false
1220 },
1221 "key1": "x"
1222 }"#,
1223 cx,
1224 )
1225 .unwrap();
1226 store
1227 .set_user_settings(r#"{ "turbo": false }"#, cx)
1228 .unwrap();
1229 store.register_setting::<UserSettings>(cx);
1230 store.register_setting::<TurboSetting>(cx);
1231
1232 assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(false));
1233 assert_eq!(
1234 store.get::<UserSettings>(None),
1235 &UserSettings {
1236 name: "John Doe".to_string(),
1237 age: 30,
1238 staff: false,
1239 }
1240 );
1241
1242 store.register_setting::<MultiKeySettings>(cx);
1243 assert_eq!(
1244 store.get::<MultiKeySettings>(None),
1245 &MultiKeySettings {
1246 key1: "x".into(),
1247 key2: String::new(),
1248 }
1249 );
1250 }
1251
1252 #[gpui::test]
1253 fn test_setting_store_update(cx: &mut AppContext) {
1254 let mut store = SettingsStore::new(cx);
1255 store.register_setting::<MultiKeySettings>(cx);
1256 store.register_setting::<UserSettings>(cx);
1257 store.register_setting::<LanguageSettings>(cx);
1258
1259 // entries added and updated
1260 check_settings_update::<LanguageSettings>(
1261 &mut store,
1262 r#"{
1263 "languages": {
1264 "JSON": {
1265 "language_setting_1": true
1266 }
1267 }
1268 }"#
1269 .unindent(),
1270 |settings| {
1271 settings
1272 .languages
1273 .get_mut("JSON")
1274 .unwrap()
1275 .language_setting_1 = Some(false);
1276 settings.languages.insert(
1277 "Rust".into(),
1278 LanguageSettingEntry {
1279 language_setting_2: Some(true),
1280 ..Default::default()
1281 },
1282 );
1283 },
1284 r#"{
1285 "languages": {
1286 "Rust": {
1287 "language_setting_2": true
1288 },
1289 "JSON": {
1290 "language_setting_1": false
1291 }
1292 }
1293 }"#
1294 .unindent(),
1295 cx,
1296 );
1297
1298 // weird formatting
1299 check_settings_update::<UserSettings>(
1300 &mut store,
1301 r#"{
1302 "user": { "age": 36, "name": "Max", "staff": true }
1303 }"#
1304 .unindent(),
1305 |settings| settings.age = Some(37),
1306 r#"{
1307 "user": { "age": 37, "name": "Max", "staff": true }
1308 }"#
1309 .unindent(),
1310 cx,
1311 );
1312
1313 // single-line formatting, other keys
1314 check_settings_update::<MultiKeySettings>(
1315 &mut store,
1316 r#"{ "one": 1, "two": 2 }"#.unindent(),
1317 |settings| settings.key1 = Some("x".into()),
1318 r#"{ "key1": "x", "one": 1, "two": 2 }"#.unindent(),
1319 cx,
1320 );
1321
1322 // empty object
1323 check_settings_update::<UserSettings>(
1324 &mut store,
1325 r#"{
1326 "user": {}
1327 }"#
1328 .unindent(),
1329 |settings| settings.age = Some(37),
1330 r#"{
1331 "user": {
1332 "age": 37
1333 }
1334 }"#
1335 .unindent(),
1336 cx,
1337 );
1338
1339 // no content
1340 check_settings_update::<UserSettings>(
1341 &mut store,
1342 r#""#.unindent(),
1343 |settings| settings.age = Some(37),
1344 r#"{
1345 "user": {
1346 "age": 37
1347 }
1348 }
1349 "#
1350 .unindent(),
1351 cx,
1352 );
1353
1354 check_settings_update::<UserSettings>(
1355 &mut store,
1356 r#"{
1357 }
1358 "#
1359 .unindent(),
1360 |settings| settings.age = Some(37),
1361 r#"{
1362 "user": {
1363 "age": 37
1364 }
1365 }
1366 "#
1367 .unindent(),
1368 cx,
1369 );
1370 }
1371
1372 fn check_settings_update<T: Settings>(
1373 store: &mut SettingsStore,
1374 old_json: String,
1375 update: fn(&mut T::FileContent),
1376 expected_new_json: String,
1377 cx: &mut AppContext,
1378 ) {
1379 store.set_user_settings(&old_json, cx).ok();
1380 let edits = store.edits_for_update::<T>(&old_json, update);
1381 let mut new_json = old_json;
1382 for (range, replacement) in edits.into_iter() {
1383 new_json.replace_range(range, &replacement);
1384 }
1385 pretty_assertions::assert_eq!(new_json, expected_new_json);
1386 }
1387
1388 #[derive(Debug, PartialEq, Deserialize)]
1389 struct UserSettings {
1390 name: String,
1391 age: u32,
1392 staff: bool,
1393 }
1394
1395 #[derive(Default, Clone, Serialize, Deserialize, JsonSchema)]
1396 struct UserSettingsJson {
1397 name: Option<String>,
1398 age: Option<u32>,
1399 staff: Option<bool>,
1400 }
1401
1402 impl Settings for UserSettings {
1403 const KEY: Option<&'static str> = Some("user");
1404 type FileContent = UserSettingsJson;
1405
1406 fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1407 sources.json_merge()
1408 }
1409 }
1410
1411 #[derive(Debug, Deserialize, PartialEq)]
1412 struct TurboSetting(bool);
1413
1414 impl Settings for TurboSetting {
1415 const KEY: Option<&'static str> = Some("turbo");
1416 type FileContent = Option<bool>;
1417
1418 fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1419 sources.json_merge()
1420 }
1421 }
1422
1423 #[derive(Clone, Debug, PartialEq, Deserialize)]
1424 struct MultiKeySettings {
1425 #[serde(default)]
1426 key1: String,
1427 #[serde(default)]
1428 key2: String,
1429 }
1430
1431 #[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
1432 struct MultiKeySettingsJson {
1433 key1: Option<String>,
1434 key2: Option<String>,
1435 }
1436
1437 impl Settings for MultiKeySettings {
1438 const KEY: Option<&'static str> = None;
1439
1440 type FileContent = MultiKeySettingsJson;
1441
1442 fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1443 sources.json_merge()
1444 }
1445 }
1446
1447 #[derive(Debug, Deserialize)]
1448 struct JournalSettings {
1449 pub path: String,
1450 pub hour_format: HourFormat,
1451 }
1452
1453 #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
1454 #[serde(rename_all = "snake_case")]
1455 enum HourFormat {
1456 Hour12,
1457 Hour24,
1458 }
1459
1460 #[derive(Clone, Default, Debug, Serialize, Deserialize, JsonSchema)]
1461 struct JournalSettingsJson {
1462 pub path: Option<String>,
1463 pub hour_format: Option<HourFormat>,
1464 }
1465
1466 impl Settings for JournalSettings {
1467 const KEY: Option<&'static str> = Some("journal");
1468
1469 type FileContent = JournalSettingsJson;
1470
1471 fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1472 sources.json_merge()
1473 }
1474 }
1475
1476 #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
1477 struct LanguageSettings {
1478 #[serde(default)]
1479 languages: HashMap<String, LanguageSettingEntry>,
1480 }
1481
1482 #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
1483 struct LanguageSettingEntry {
1484 language_setting_1: Option<bool>,
1485 language_setting_2: Option<bool>,
1486 }
1487
1488 impl Settings for LanguageSettings {
1489 const KEY: Option<&'static str> = None;
1490
1491 type FileContent = Self;
1492
1493 fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1494 sources.json_merge()
1495 }
1496 }
1497}