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