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