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