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