1use anyhow::{Context as _, Result};
2use collections::{BTreeMap, HashMap, btree_map, hash_map};
3use ec4rs::{ConfigParser, PropertiesSource, Section};
4use fs::Fs;
5use futures::{FutureExt, StreamExt, channel::mpsc, future::LocalBoxFuture};
6use gpui::{App, AsyncApp, BorrowAppContext, Global, Task, UpdateGlobal};
7
8use paths::{EDITORCONFIG_NAME, local_settings_file_relative_path, task_file_name};
9use schemars::JsonSchema;
10use serde::{Deserialize, Serialize, de::DeserializeOwned};
11use serde_json::{Value, json};
12use smallvec::SmallVec;
13use std::{
14 any::{Any, TypeId, type_name},
15 fmt::Debug,
16 ops::Range,
17 path::{Path, PathBuf},
18 str::{self, FromStr},
19 sync::Arc,
20};
21use util::{
22 ResultExt as _, merge_non_null_json_value_into,
23 schemars::{DefaultDenyUnknownFields, add_new_subschema},
24};
25
26pub type EditorconfigProperties = ec4rs::Properties;
27
28use crate::{
29 ParameterizedJsonSchema, SettingsJsonSchemaParams, VsCodeSettings, WorktreeId,
30 parse_json_with_comments, update_value_in_json_text,
31};
32
33/// A value that can be defined as a user setting.
34///
35/// Settings can be loaded from a combination of multiple JSON files.
36pub trait Settings: 'static + Send + Sync {
37 /// The name of a key within the JSON file from which this setting should
38 /// be deserialized. If this is `None`, then the setting will be deserialized
39 /// from the root object.
40 const KEY: Option<&'static str>;
41
42 const FALLBACK_KEY: Option<&'static str> = None;
43
44 /// The name of the keys in the [`FileContent`](Self::FileContent) that should
45 /// always be written to a settings file, even if their value matches the default
46 /// value.
47 ///
48 /// This is useful for tagged [`FileContent`](Self::FileContent)s where the tag
49 /// is a "version" field that should always be persisted, even if the current
50 /// user settings match the current version of the settings.
51 const PRESERVED_KEYS: Option<&'static [&'static str]> = None;
52
53 /// The type that is stored in an individual JSON file.
54 type FileContent: Clone + Default + Serialize + DeserializeOwned + JsonSchema;
55
56 /// The logic for combining together values from one or more JSON files into the
57 /// final value for this setting.
58 fn load(sources: SettingsSources<Self::FileContent>, cx: &mut App) -> Result<Self>
59 where
60 Self: Sized;
61
62 fn missing_default() -> anyhow::Error {
63 anyhow::anyhow!("missing default")
64 }
65
66 /// Use [the helpers in the vscode_import module](crate::vscode_import) to apply known
67 /// equivalent settings from a vscode config to our config
68 fn import_from_vscode(vscode: &VsCodeSettings, current: &mut Self::FileContent);
69
70 #[track_caller]
71 fn register(cx: &mut App)
72 where
73 Self: Sized,
74 {
75 SettingsStore::update_global(cx, |store, cx| {
76 store.register_setting::<Self>(cx);
77 });
78 }
79
80 #[track_caller]
81 fn get<'a>(path: Option<SettingsLocation>, cx: &'a App) -> &'a Self
82 where
83 Self: Sized,
84 {
85 cx.global::<SettingsStore>().get(path)
86 }
87
88 #[track_caller]
89 fn get_global(cx: &App) -> &Self
90 where
91 Self: Sized,
92 {
93 cx.global::<SettingsStore>().get(None)
94 }
95
96 #[track_caller]
97 fn try_read_global<R>(cx: &AsyncApp, f: impl FnOnce(&Self) -> R) -> Option<R>
98 where
99 Self: Sized,
100 {
101 cx.try_read_global(|s: &SettingsStore, _| f(s.get(None)))
102 }
103
104 #[track_caller]
105 fn override_global(settings: Self, cx: &mut App)
106 where
107 Self: Sized,
108 {
109 cx.global_mut::<SettingsStore>().override_global(settings)
110 }
111}
112
113#[derive(Clone, Copy, Debug)]
114pub struct SettingsSources<'a, T> {
115 /// The default Zed settings.
116 pub default: &'a T,
117 /// Global settings (loaded before user settings).
118 pub global: Option<&'a T>,
119 /// Settings provided by extensions.
120 pub extensions: Option<&'a T>,
121 /// The user settings.
122 pub user: Option<&'a T>,
123 /// The user settings for the current release channel.
124 pub release_channel: Option<&'a T>,
125 /// The server's settings.
126 pub server: Option<&'a T>,
127 /// The project settings, ordered from least specific to most specific.
128 pub project: &'a [&'a T],
129}
130
131impl<'a, T: Serialize> SettingsSources<'a, T> {
132 /// Returns an iterator over the default settings as well as all settings customizations.
133 pub fn defaults_and_customizations(&self) -> impl Iterator<Item = &T> {
134 [self.default].into_iter().chain(self.customizations())
135 }
136
137 /// Returns an iterator over all of the settings customizations.
138 pub fn customizations(&self) -> impl Iterator<Item = &T> {
139 self.global
140 .into_iter()
141 .chain(self.extensions)
142 .chain(self.user)
143 .chain(self.release_channel)
144 .chain(self.server)
145 .chain(self.project.iter().copied())
146 }
147
148 /// Returns the settings after performing a JSON merge of the provided customizations.
149 ///
150 /// Customizations later in the iterator win out over the earlier ones.
151 pub fn json_merge_with<O: DeserializeOwned>(
152 customizations: impl Iterator<Item = &'a T>,
153 ) -> Result<O> {
154 let mut merged = Value::Null;
155 for value in customizations {
156 merge_non_null_json_value_into(serde_json::to_value(value).unwrap(), &mut merged);
157 }
158 Ok(serde_json::from_value(merged)?)
159 }
160
161 /// Returns the settings after performing a JSON merge of the customizations into the
162 /// default settings.
163 ///
164 /// More-specific customizations win out over the less-specific ones.
165 pub fn json_merge<O: DeserializeOwned>(&'a self) -> Result<O> {
166 Self::json_merge_with(self.defaults_and_customizations())
167 }
168}
169
170#[derive(Clone, Copy, Debug)]
171pub struct SettingsLocation<'a> {
172 pub worktree_id: WorktreeId,
173 pub path: &'a Path,
174}
175
176/// A set of strongly-typed setting values defined via multiple config files.
177pub struct SettingsStore {
178 setting_values: HashMap<TypeId, Box<dyn AnySettingValue>>,
179 raw_default_settings: Value,
180 raw_global_settings: Option<Value>,
181 raw_user_settings: Value,
182 raw_server_settings: Option<Value>,
183 raw_extension_settings: Value,
184 raw_local_settings: BTreeMap<(WorktreeId, Arc<Path>), Value>,
185 raw_editorconfig_settings: BTreeMap<(WorktreeId, Arc<Path>), (String, Option<Editorconfig>)>,
186 tab_size_callback: Option<(
187 TypeId,
188 Box<dyn Fn(&dyn Any) -> Option<usize> + Send + Sync + 'static>,
189 )>,
190 _setting_file_updates: Task<()>,
191 setting_file_updates_tx:
192 mpsc::UnboundedSender<Box<dyn FnOnce(AsyncApp) -> LocalBoxFuture<'static, Result<()>>>>,
193}
194
195#[derive(Clone)]
196pub struct Editorconfig {
197 pub is_root: bool,
198 pub sections: SmallVec<[Section; 5]>,
199}
200
201impl FromStr for Editorconfig {
202 type Err = anyhow::Error;
203
204 fn from_str(contents: &str) -> Result<Self, Self::Err> {
205 let parser = ConfigParser::new_buffered(contents.as_bytes())
206 .context("creating editorconfig parser")?;
207 let is_root = parser.is_root;
208 let sections = parser
209 .collect::<Result<SmallVec<_>, _>>()
210 .context("parsing editorconfig sections")?;
211 Ok(Self { is_root, sections })
212 }
213}
214
215#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
216pub enum LocalSettingsKind {
217 Settings,
218 Tasks,
219 Editorconfig,
220 Debug,
221}
222
223impl Global for SettingsStore {}
224
225#[derive(Debug)]
226struct SettingValue<T> {
227 global_value: Option<T>,
228 local_values: Vec<(WorktreeId, Arc<Path>, T)>,
229}
230
231trait AnySettingValue: 'static + Send + Sync {
232 fn key(&self) -> Option<&'static str>;
233 fn setting_type_name(&self) -> &'static str;
234 fn deserialize_setting(&self, json: &Value) -> Result<DeserializedSetting> {
235 self.deserialize_setting_with_key(json).1
236 }
237 fn deserialize_setting_with_key(
238 &self,
239 json: &Value,
240 ) -> (Option<&'static str>, Result<DeserializedSetting>);
241 fn load_setting(
242 &self,
243 sources: SettingsSources<DeserializedSetting>,
244 cx: &mut App,
245 ) -> Result<Box<dyn Any>>;
246 fn value_for_path(&self, path: Option<SettingsLocation>) -> &dyn Any;
247 fn all_local_values(&self) -> Vec<(WorktreeId, Arc<Path>, &dyn Any)>;
248 fn set_global_value(&mut self, value: Box<dyn Any>);
249 fn set_local_value(&mut self, root_id: WorktreeId, path: Arc<Path>, value: Box<dyn Any>);
250 fn json_schema(&self, generator: &mut schemars::SchemaGenerator) -> schemars::Schema;
251 fn edits_for_update(
252 &self,
253 raw_settings: &serde_json::Value,
254 tab_size: usize,
255 vscode_settings: &VsCodeSettings,
256 text: &mut String,
257 edits: &mut Vec<(Range<usize>, String)>,
258 );
259}
260
261struct DeserializedSetting(Box<dyn Any>);
262
263impl SettingsStore {
264 pub fn new(cx: &App) -> Self {
265 let (setting_file_updates_tx, mut setting_file_updates_rx) = mpsc::unbounded();
266 Self {
267 setting_values: Default::default(),
268 raw_default_settings: json!({}),
269 raw_global_settings: None,
270 raw_user_settings: json!({}),
271 raw_server_settings: None,
272 raw_extension_settings: json!({}),
273 raw_local_settings: Default::default(),
274 raw_editorconfig_settings: BTreeMap::default(),
275 tab_size_callback: Default::default(),
276 setting_file_updates_tx,
277 _setting_file_updates: cx.spawn(async move |cx| {
278 while let Some(setting_file_update) = setting_file_updates_rx.next().await {
279 (setting_file_update)(cx.clone()).await.log_err();
280 }
281 }),
282 }
283 }
284
285 pub fn update<C, R>(cx: &mut C, f: impl FnOnce(&mut Self, &mut C) -> R) -> R
286 where
287 C: BorrowAppContext,
288 {
289 cx.update_global(f)
290 }
291
292 /// Add a new type of setting to the store.
293 pub fn register_setting<T: Settings>(&mut self, cx: &mut App) {
294 let setting_type_id = TypeId::of::<T>();
295 let entry = self.setting_values.entry(setting_type_id);
296
297 if matches!(entry, hash_map::Entry::Occupied(_)) {
298 return;
299 }
300
301 let setting_value = entry.or_insert(Box::new(SettingValue::<T> {
302 global_value: None,
303 local_values: Vec::new(),
304 }));
305
306 if let Some(default_settings) = setting_value
307 .deserialize_setting(&self.raw_default_settings)
308 .log_err()
309 {
310 let user_value = setting_value
311 .deserialize_setting(&self.raw_user_settings)
312 .log_err();
313
314 let mut release_channel_value = None;
315 if let Some(release_settings) = &self
316 .raw_user_settings
317 .get(release_channel::RELEASE_CHANNEL.dev_name())
318 {
319 release_channel_value = setting_value
320 .deserialize_setting(release_settings)
321 .log_err();
322 }
323
324 let server_value = self
325 .raw_server_settings
326 .as_ref()
327 .and_then(|server_setting| {
328 setting_value.deserialize_setting(server_setting).log_err()
329 });
330
331 let extension_value = setting_value
332 .deserialize_setting(&self.raw_extension_settings)
333 .log_err();
334
335 if let Some(setting) = setting_value
336 .load_setting(
337 SettingsSources {
338 default: &default_settings,
339 global: None,
340 extensions: extension_value.as_ref(),
341 user: user_value.as_ref(),
342 release_channel: release_channel_value.as_ref(),
343 server: server_value.as_ref(),
344 project: &[],
345 },
346 cx,
347 )
348 .context("A default setting must be added to the `default.json` file")
349 .log_err()
350 {
351 setting_value.set_global_value(setting);
352 }
353 }
354 }
355
356 /// Get the value of a setting.
357 ///
358 /// Panics if the given setting type has not been registered, or if there is no
359 /// value for this setting.
360 pub fn get<T: Settings>(&self, path: Option<SettingsLocation>) -> &T {
361 self.setting_values
362 .get(&TypeId::of::<T>())
363 .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()))
364 .value_for_path(path)
365 .downcast_ref::<T>()
366 .expect("no default value for setting type")
367 }
368
369 /// Get all values from project specific settings
370 pub fn get_all_locals<T: Settings>(&self) -> Vec<(WorktreeId, Arc<Path>, &T)> {
371 self.setting_values
372 .get(&TypeId::of::<T>())
373 .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()))
374 .all_local_values()
375 .into_iter()
376 .map(|(id, path, any)| {
377 (
378 id,
379 path,
380 any.downcast_ref::<T>()
381 .expect("wrong value type for setting"),
382 )
383 })
384 .collect()
385 }
386
387 /// Override the global value for a setting.
388 ///
389 /// The given value will be overwritten if the user settings file changes.
390 pub fn override_global<T: Settings>(&mut self, value: T) {
391 self.setting_values
392 .get_mut(&TypeId::of::<T>())
393 .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()))
394 .set_global_value(Box::new(value))
395 }
396
397 /// Get the user's settings as a raw JSON value.
398 ///
399 /// For user-facing functionality use the typed setting interface.
400 /// (e.g. ProjectSettings::get_global(cx))
401 pub fn raw_user_settings(&self) -> &Value {
402 &self.raw_user_settings
403 }
404
405 /// Access the raw JSON value of the global settings.
406 pub fn raw_global_settings(&self) -> Option<&Value> {
407 self.raw_global_settings.as_ref()
408 }
409
410 #[cfg(any(test, feature = "test-support"))]
411 pub fn test(cx: &mut App) -> Self {
412 let mut this = Self::new(cx);
413 this.set_default_settings(&crate::test_settings(), cx)
414 .unwrap();
415 this.set_user_settings("{}", cx).unwrap();
416 this
417 }
418
419 /// Updates the value of a setting in the user's global configuration.
420 ///
421 /// This is only for tests. Normally, settings are only loaded from
422 /// JSON files.
423 #[cfg(any(test, feature = "test-support"))]
424 pub fn update_user_settings<T: Settings>(
425 &mut self,
426 cx: &mut App,
427 update: impl FnOnce(&mut T::FileContent),
428 ) {
429 let old_text = serde_json::to_string(&self.raw_user_settings).unwrap();
430 let new_text = self.new_text_for_update::<T>(old_text, update);
431 self.set_user_settings(&new_text, cx).unwrap();
432 }
433
434 pub async fn load_settings(fs: &Arc<dyn Fs>) -> Result<String> {
435 match fs.load(paths::settings_file()).await {
436 result @ Ok(_) => result,
437 Err(err) => {
438 if let Some(e) = err.downcast_ref::<std::io::Error>() {
439 if e.kind() == std::io::ErrorKind::NotFound {
440 return Ok(crate::initial_user_settings_content().to_string());
441 }
442 }
443 Err(err)
444 }
445 }
446 }
447
448 pub async fn load_global_settings(fs: &Arc<dyn Fs>) -> Result<String> {
449 match fs.load(paths::global_settings_file()).await {
450 result @ Ok(_) => result,
451 Err(err) => {
452 if let Some(e) = err.downcast_ref::<std::io::Error>() {
453 if e.kind() == std::io::ErrorKind::NotFound {
454 return Ok("{}".to_string());
455 }
456 }
457 Err(err)
458 }
459 }
460 }
461
462 pub fn update_settings_file<T: Settings>(
463 &self,
464 fs: Arc<dyn Fs>,
465 update: impl 'static + Send + FnOnce(&mut T::FileContent, &App),
466 ) {
467 self.setting_file_updates_tx
468 .unbounded_send(Box::new(move |cx: AsyncApp| {
469 async move {
470 let old_text = Self::load_settings(&fs).await?;
471 let new_text = cx.read_global(|store: &SettingsStore, cx| {
472 store.new_text_for_update::<T>(old_text, |content| update(content, cx))
473 })?;
474 let settings_path = paths::settings_file().as_path();
475 if fs.is_file(settings_path).await {
476 let resolved_path =
477 fs.canonicalize(settings_path).await.with_context(|| {
478 format!("Failed to canonicalize settings path {:?}", settings_path)
479 })?;
480
481 fs.atomic_write(resolved_path.clone(), new_text)
482 .await
483 .with_context(|| {
484 format!("Failed to write settings to file {:?}", resolved_path)
485 })?;
486 } else {
487 fs.atomic_write(settings_path.to_path_buf(), new_text)
488 .await
489 .with_context(|| {
490 format!("Failed to write settings to file {:?}", settings_path)
491 })?;
492 }
493
494 anyhow::Ok(())
495 }
496 .boxed_local()
497 }))
498 .ok();
499 }
500
501 pub fn import_vscode_settings(&self, fs: Arc<dyn Fs>, vscode_settings: VsCodeSettings) {
502 self.setting_file_updates_tx
503 .unbounded_send(Box::new(move |cx: AsyncApp| {
504 async move {
505 let old_text = Self::load_settings(&fs).await?;
506 let new_text = cx.read_global(|store: &SettingsStore, _cx| {
507 store.get_vscode_edits(old_text, &vscode_settings)
508 })?;
509 let settings_path = paths::settings_file().as_path();
510 if fs.is_file(settings_path).await {
511 let resolved_path =
512 fs.canonicalize(settings_path).await.with_context(|| {
513 format!("Failed to canonicalize settings path {:?}", settings_path)
514 })?;
515
516 fs.atomic_write(resolved_path.clone(), new_text)
517 .await
518 .with_context(|| {
519 format!("Failed to write settings to file {:?}", resolved_path)
520 })?;
521 } else {
522 fs.atomic_write(settings_path.to_path_buf(), new_text)
523 .await
524 .with_context(|| {
525 format!("Failed to write settings to file {:?}", settings_path)
526 })?;
527 }
528
529 anyhow::Ok(())
530 }
531 .boxed_local()
532 }))
533 .ok();
534 }
535}
536
537impl SettingsStore {
538 /// Updates the value of a setting in a JSON file, returning the new text
539 /// for that JSON file.
540 pub fn new_text_for_update<T: Settings>(
541 &self,
542 old_text: String,
543 update: impl FnOnce(&mut T::FileContent),
544 ) -> String {
545 let edits = self.edits_for_update::<T>(&old_text, update);
546 let mut new_text = old_text;
547 for (range, replacement) in edits.into_iter() {
548 new_text.replace_range(range, &replacement);
549 }
550 new_text
551 }
552
553 pub fn get_vscode_edits(&self, mut old_text: String, vscode: &VsCodeSettings) -> String {
554 let mut new_text = old_text.clone();
555 let mut edits: Vec<(Range<usize>, String)> = Vec::new();
556 let raw_settings = parse_json_with_comments::<Value>(&old_text).unwrap_or_default();
557 let tab_size = self.json_tab_size();
558 for v in self.setting_values.values() {
559 v.edits_for_update(&raw_settings, tab_size, vscode, &mut old_text, &mut edits);
560 }
561 for (range, replacement) in edits.into_iter() {
562 new_text.replace_range(range, &replacement);
563 }
564 new_text
565 }
566
567 /// Updates the value of a setting in a JSON file, returning a list
568 /// of edits to apply to the JSON file.
569 pub fn edits_for_update<T: Settings>(
570 &self,
571 text: &str,
572 update: impl FnOnce(&mut T::FileContent),
573 ) -> Vec<(Range<usize>, String)> {
574 let setting_type_id = TypeId::of::<T>();
575
576 let preserved_keys = T::PRESERVED_KEYS.unwrap_or_default();
577
578 let setting = self
579 .setting_values
580 .get(&setting_type_id)
581 .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()));
582 let raw_settings = parse_json_with_comments::<Value>(text).unwrap_or_default();
583 let (key, deserialized_setting) = setting.deserialize_setting_with_key(&raw_settings);
584 let old_content = match deserialized_setting {
585 Ok(content) => content.0.downcast::<T::FileContent>().unwrap(),
586 Err(_) => Box::<<T as Settings>::FileContent>::default(),
587 };
588 let mut new_content = old_content.clone();
589 update(&mut new_content);
590
591 let old_value = serde_json::to_value(&old_content).unwrap();
592 let new_value = serde_json::to_value(new_content).unwrap();
593
594 let mut key_path = Vec::new();
595 if let Some(key) = key {
596 key_path.push(key);
597 }
598
599 let mut edits = Vec::new();
600 let tab_size = self.json_tab_size();
601 let mut text = text.to_string();
602 update_value_in_json_text(
603 &mut text,
604 &mut key_path,
605 tab_size,
606 &old_value,
607 &new_value,
608 preserved_keys,
609 &mut edits,
610 );
611 edits
612 }
613
614 /// Configure the tab sized when updating JSON files.
615 pub fn set_json_tab_size_callback<T: Settings>(
616 &mut self,
617 get_tab_size: fn(&T) -> Option<usize>,
618 ) {
619 self.tab_size_callback = Some((
620 TypeId::of::<T>(),
621 Box::new(move |value| get_tab_size(value.downcast_ref::<T>().unwrap())),
622 ));
623 }
624
625 pub fn json_tab_size(&self) -> usize {
626 const DEFAULT_JSON_TAB_SIZE: usize = 2;
627
628 if let Some((setting_type_id, callback)) = &self.tab_size_callback {
629 let setting_value = self.setting_values.get(setting_type_id).unwrap();
630 let value = setting_value.value_for_path(None);
631 if let Some(value) = callback(value) {
632 return value;
633 }
634 }
635
636 DEFAULT_JSON_TAB_SIZE
637 }
638
639 /// Sets the default settings via a JSON string.
640 ///
641 /// The string should contain a JSON object with a default value for every setting.
642 pub fn set_default_settings(
643 &mut self,
644 default_settings_content: &str,
645 cx: &mut App,
646 ) -> Result<()> {
647 let settings: Value = parse_json_with_comments(default_settings_content)?;
648 anyhow::ensure!(settings.is_object(), "settings must be an object");
649 self.raw_default_settings = settings;
650 self.recompute_values(None, cx)?;
651 Ok(())
652 }
653
654 /// Sets the user settings via a JSON string.
655 pub fn set_user_settings(
656 &mut self,
657 user_settings_content: &str,
658 cx: &mut App,
659 ) -> Result<Value> {
660 let settings: Value = if user_settings_content.is_empty() {
661 parse_json_with_comments("{}")?
662 } else {
663 parse_json_with_comments(user_settings_content)?
664 };
665
666 anyhow::ensure!(settings.is_object(), "settings must be an object");
667 self.raw_user_settings = settings.clone();
668 self.recompute_values(None, cx)?;
669 Ok(settings)
670 }
671
672 /// Sets the global settings via a JSON string.
673 pub fn set_global_settings(
674 &mut self,
675 global_settings_content: &str,
676 cx: &mut App,
677 ) -> Result<Value> {
678 let settings: Value = if global_settings_content.is_empty() {
679 parse_json_with_comments("{}")?
680 } else {
681 parse_json_with_comments(global_settings_content)?
682 };
683
684 anyhow::ensure!(settings.is_object(), "settings must be an object");
685 self.raw_global_settings = Some(settings.clone());
686 self.recompute_values(None, cx)?;
687 Ok(settings)
688 }
689
690 pub fn set_server_settings(
691 &mut self,
692 server_settings_content: &str,
693 cx: &mut App,
694 ) -> Result<()> {
695 let settings: Option<Value> = if server_settings_content.is_empty() {
696 None
697 } else {
698 parse_json_with_comments(server_settings_content)?
699 };
700
701 anyhow::ensure!(
702 settings
703 .as_ref()
704 .map(|value| value.is_object())
705 .unwrap_or(true),
706 "settings must be an object"
707 );
708 self.raw_server_settings = settings;
709 self.recompute_values(None, cx)?;
710 Ok(())
711 }
712
713 /// Add or remove a set of local settings via a JSON string.
714 pub fn set_local_settings(
715 &mut self,
716 root_id: WorktreeId,
717 directory_path: Arc<Path>,
718 kind: LocalSettingsKind,
719 settings_content: Option<&str>,
720 cx: &mut App,
721 ) -> std::result::Result<(), InvalidSettingsError> {
722 let mut zed_settings_changed = false;
723 match (
724 kind,
725 settings_content
726 .map(|content| content.trim())
727 .filter(|content| !content.is_empty()),
728 ) {
729 (LocalSettingsKind::Tasks, _) => {
730 return Err(InvalidSettingsError::Tasks {
731 message: "Attempted to submit tasks into the settings store".to_string(),
732 path: directory_path.join(task_file_name()),
733 });
734 }
735 (LocalSettingsKind::Debug, _) => {
736 return Err(InvalidSettingsError::Debug {
737 message: "Attempted to submit debugger config into the settings store"
738 .to_string(),
739 path: directory_path.join(task_file_name()),
740 });
741 }
742 (LocalSettingsKind::Settings, None) => {
743 zed_settings_changed = self
744 .raw_local_settings
745 .remove(&(root_id, directory_path.clone()))
746 .is_some()
747 }
748 (LocalSettingsKind::Editorconfig, None) => {
749 self.raw_editorconfig_settings
750 .remove(&(root_id, directory_path.clone()));
751 }
752 (LocalSettingsKind::Settings, Some(settings_contents)) => {
753 let new_settings =
754 parse_json_with_comments::<Value>(settings_contents).map_err(|e| {
755 InvalidSettingsError::LocalSettings {
756 path: directory_path.join(local_settings_file_relative_path()),
757 message: e.to_string(),
758 }
759 })?;
760 match self
761 .raw_local_settings
762 .entry((root_id, directory_path.clone()))
763 {
764 btree_map::Entry::Vacant(v) => {
765 v.insert(new_settings);
766 zed_settings_changed = true;
767 }
768 btree_map::Entry::Occupied(mut o) => {
769 if o.get() != &new_settings {
770 o.insert(new_settings);
771 zed_settings_changed = true;
772 }
773 }
774 }
775 }
776 (LocalSettingsKind::Editorconfig, Some(editorconfig_contents)) => {
777 match self
778 .raw_editorconfig_settings
779 .entry((root_id, directory_path.clone()))
780 {
781 btree_map::Entry::Vacant(v) => match editorconfig_contents.parse() {
782 Ok(new_contents) => {
783 v.insert((editorconfig_contents.to_owned(), Some(new_contents)));
784 }
785 Err(e) => {
786 v.insert((editorconfig_contents.to_owned(), None));
787 return Err(InvalidSettingsError::Editorconfig {
788 message: e.to_string(),
789 path: directory_path.join(EDITORCONFIG_NAME),
790 });
791 }
792 },
793 btree_map::Entry::Occupied(mut o) => {
794 if o.get().0 != editorconfig_contents {
795 match editorconfig_contents.parse() {
796 Ok(new_contents) => {
797 o.insert((
798 editorconfig_contents.to_owned(),
799 Some(new_contents),
800 ));
801 }
802 Err(e) => {
803 o.insert((editorconfig_contents.to_owned(), None));
804 return Err(InvalidSettingsError::Editorconfig {
805 message: e.to_string(),
806 path: directory_path.join(EDITORCONFIG_NAME),
807 });
808 }
809 }
810 }
811 }
812 }
813 }
814 };
815
816 if zed_settings_changed {
817 self.recompute_values(Some((root_id, &directory_path)), cx)?;
818 }
819 Ok(())
820 }
821
822 pub fn set_extension_settings<T: Serialize>(&mut self, content: T, cx: &mut App) -> Result<()> {
823 let settings: Value = serde_json::to_value(content)?;
824 anyhow::ensure!(settings.is_object(), "settings must be an object");
825 self.raw_extension_settings = settings;
826 self.recompute_values(None, cx)?;
827 Ok(())
828 }
829
830 /// Add or remove a set of local settings via a JSON string.
831 pub fn clear_local_settings(&mut self, root_id: WorktreeId, cx: &mut App) -> Result<()> {
832 self.raw_local_settings
833 .retain(|(worktree_id, _), _| worktree_id != &root_id);
834 self.recompute_values(Some((root_id, "".as_ref())), cx)?;
835 Ok(())
836 }
837
838 pub fn local_settings(
839 &self,
840 root_id: WorktreeId,
841 ) -> impl '_ + Iterator<Item = (Arc<Path>, String)> {
842 self.raw_local_settings
843 .range(
844 (root_id, Path::new("").into())
845 ..(
846 WorktreeId::from_usize(root_id.to_usize() + 1),
847 Path::new("").into(),
848 ),
849 )
850 .map(|((_, path), content)| (path.clone(), serde_json::to_string(content).unwrap()))
851 }
852
853 pub fn local_editorconfig_settings(
854 &self,
855 root_id: WorktreeId,
856 ) -> impl '_ + Iterator<Item = (Arc<Path>, String, Option<Editorconfig>)> {
857 self.raw_editorconfig_settings
858 .range(
859 (root_id, Path::new("").into())
860 ..(
861 WorktreeId::from_usize(root_id.to_usize() + 1),
862 Path::new("").into(),
863 ),
864 )
865 .map(|((_, path), (content, parsed_content))| {
866 (path.clone(), content.clone(), parsed_content.clone())
867 })
868 }
869
870 pub fn json_schema(&self, schema_params: &SettingsJsonSchemaParams, cx: &App) -> Value {
871 let mut generator = schemars::generate::SchemaSettings::draft2019_09()
872 .with_transform(DefaultDenyUnknownFields)
873 .into_generator();
874 let mut combined_schema = json!({
875 "type": "object",
876 "properties": {}
877 });
878
879 // Merge together settings schemas, similarly to json schema's "allOf". This merging is
880 // recursive, though at time of writing this recursive nature isn't used very much. An
881 // example of it is the schema for `jupyter` having contribution from both `EditorSettings`
882 // and `JupyterSettings`.
883 //
884 // This logic could be removed in favor of "allOf", but then there isn't the opportunity to
885 // validate and fully control the merge.
886 for setting_value in self.setting_values.values() {
887 let mut setting_schema = setting_value.json_schema(&mut generator);
888
889 if let Some(key) = setting_value.key() {
890 if let Some(properties) = combined_schema.get_mut("properties") {
891 if let Some(properties_obj) = properties.as_object_mut() {
892 if let Some(target) = properties_obj.get_mut(key) {
893 merge_schema(target, setting_schema.to_value());
894 } else {
895 properties_obj.insert(key.to_string(), setting_schema.to_value());
896 }
897 }
898 }
899 } else {
900 setting_schema.remove("description");
901 setting_schema.remove("additionalProperties");
902 merge_schema(&mut combined_schema, setting_schema.to_value());
903 }
904 }
905
906 fn merge_schema(target: &mut serde_json::Value, source: serde_json::Value) {
907 let (Some(target_obj), serde_json::Value::Object(source_obj)) =
908 (target.as_object_mut(), source)
909 else {
910 return;
911 };
912
913 for (source_key, source_value) in source_obj {
914 match source_key.as_str() {
915 "properties" => {
916 let serde_json::Value::Object(source_properties) = source_value else {
917 log::error!(
918 "bug: expected object for `{}` json schema field, but got: {}",
919 source_key,
920 source_value
921 );
922 continue;
923 };
924 let target_properties =
925 target_obj.entry(source_key.clone()).or_insert(json!({}));
926 let Some(target_properties) = target_properties.as_object_mut() else {
927 log::error!(
928 "bug: expected object for `{}` json schema field, but got: {}",
929 source_key,
930 target_properties
931 );
932 continue;
933 };
934 for (key, value) in source_properties {
935 if let Some(existing) = target_properties.get_mut(&key) {
936 merge_schema(existing, value);
937 } else {
938 target_properties.insert(key, value);
939 }
940 }
941 }
942 "allOf" | "anyOf" | "oneOf" => {
943 let serde_json::Value::Array(source_array) = source_value else {
944 log::error!(
945 "bug: expected array for `{}` json schema field, but got: {}",
946 source_key,
947 source_value,
948 );
949 continue;
950 };
951 let target_array =
952 target_obj.entry(source_key.clone()).or_insert(json!([]));
953 let Some(target_array) = target_array.as_array_mut() else {
954 log::error!(
955 "bug: expected array for `{}` json schema field, but got: {}",
956 source_key,
957 target_array,
958 );
959 continue;
960 };
961 target_array.extend(source_array);
962 }
963 "type"
964 | "$ref"
965 | "enum"
966 | "minimum"
967 | "maximum"
968 | "pattern"
969 | "description"
970 | "additionalProperties" => {
971 if let Some(old_value) =
972 target_obj.insert(source_key.clone(), source_value.clone())
973 {
974 if old_value != source_value {
975 log::error!(
976 "bug: while merging JSON schemas, \
977 mismatch `\"{}\": {}` (before was `{}`)",
978 source_key,
979 old_value,
980 source_value
981 );
982 }
983 }
984 }
985 _ => {
986 log::error!(
987 "bug: while merging settings JSON schemas, \
988 encountered unexpected `\"{}\": {}`",
989 source_key,
990 source_value
991 );
992 }
993 }
994 }
995 }
996
997 // add schemas which are determined at runtime
998 for parameterized_json_schema in inventory::iter::<ParameterizedJsonSchema>() {
999 (parameterized_json_schema.add_and_get_ref)(&mut generator, schema_params, cx);
1000 }
1001
1002 // add merged settings schema to the definitions
1003 const ZED_SETTINGS: &str = "ZedSettings";
1004 let zed_settings_ref = add_new_subschema(&mut generator, ZED_SETTINGS, combined_schema);
1005
1006 // add `ZedReleaseStageSettings` which is the same as `ZedSettings` except that unknown
1007 // fields are rejected.
1008 let mut zed_release_stage_settings = zed_settings_ref.clone();
1009 zed_release_stage_settings.insert("unevaluatedProperties".to_string(), false.into());
1010 let zed_release_stage_settings_ref = add_new_subschema(
1011 &mut generator,
1012 "ZedReleaseStageSettings",
1013 zed_release_stage_settings.to_value(),
1014 );
1015
1016 // Remove `"additionalProperties": false` added by `DefaultDenyUnknownFields` so that
1017 // unknown fields can be handled by the root schema and `ZedReleaseStageSettings`.
1018 let mut definitions = generator.take_definitions(true);
1019 definitions
1020 .get_mut(ZED_SETTINGS)
1021 .unwrap()
1022 .as_object_mut()
1023 .unwrap()
1024 .remove("additionalProperties");
1025
1026 let meta_schema = generator
1027 .settings()
1028 .meta_schema
1029 .as_ref()
1030 .expect("meta_schema should be present in schemars settings")
1031 .to_string();
1032
1033 json!({
1034 "$schema": meta_schema,
1035 "title": "Zed Settings",
1036 "unevaluatedProperties": false,
1037 // ZedSettings + settings overrides for each release stage
1038 "allOf": [
1039 zed_settings_ref,
1040 {
1041 "properties": {
1042 "dev": zed_release_stage_settings_ref,
1043 "nightly": zed_release_stage_settings_ref,
1044 "stable": zed_release_stage_settings_ref,
1045 "preview": zed_release_stage_settings_ref,
1046 }
1047 }
1048 ],
1049 "$defs": definitions,
1050 })
1051 }
1052
1053 fn recompute_values(
1054 &mut self,
1055 changed_local_path: Option<(WorktreeId, &Path)>,
1056 cx: &mut App,
1057 ) -> std::result::Result<(), InvalidSettingsError> {
1058 // Reload the global and local values for every setting.
1059 let mut project_settings_stack = Vec::<DeserializedSetting>::new();
1060 let mut paths_stack = Vec::<Option<(WorktreeId, &Path)>>::new();
1061 for setting_value in self.setting_values.values_mut() {
1062 let default_settings = setting_value
1063 .deserialize_setting(&self.raw_default_settings)
1064 .map_err(|e| InvalidSettingsError::DefaultSettings {
1065 message: e.to_string(),
1066 })?;
1067
1068 let global_settings = self
1069 .raw_global_settings
1070 .as_ref()
1071 .and_then(|setting| setting_value.deserialize_setting(setting).log_err());
1072
1073 let extension_settings = setting_value
1074 .deserialize_setting(&self.raw_extension_settings)
1075 .log_err();
1076
1077 let user_settings = match setting_value.deserialize_setting(&self.raw_user_settings) {
1078 Ok(settings) => Some(settings),
1079 Err(error) => {
1080 return Err(InvalidSettingsError::UserSettings {
1081 message: error.to_string(),
1082 });
1083 }
1084 };
1085
1086 let server_settings = self
1087 .raw_server_settings
1088 .as_ref()
1089 .and_then(|setting| setting_value.deserialize_setting(setting).log_err());
1090
1091 let mut release_channel_settings = None;
1092 if let Some(release_settings) = &self
1093 .raw_user_settings
1094 .get(release_channel::RELEASE_CHANNEL.dev_name())
1095 {
1096 if let Some(release_settings) = setting_value
1097 .deserialize_setting(release_settings)
1098 .log_err()
1099 {
1100 release_channel_settings = Some(release_settings);
1101 }
1102 }
1103
1104 // If the global settings file changed, reload the global value for the field.
1105 if changed_local_path.is_none() {
1106 if let Some(value) = setting_value
1107 .load_setting(
1108 SettingsSources {
1109 default: &default_settings,
1110 global: global_settings.as_ref(),
1111 extensions: extension_settings.as_ref(),
1112 user: user_settings.as_ref(),
1113 release_channel: release_channel_settings.as_ref(),
1114 server: server_settings.as_ref(),
1115 project: &[],
1116 },
1117 cx,
1118 )
1119 .log_err()
1120 {
1121 setting_value.set_global_value(value);
1122 }
1123 }
1124
1125 // Reload the local values for the setting.
1126 paths_stack.clear();
1127 project_settings_stack.clear();
1128 for ((root_id, directory_path), local_settings) in &self.raw_local_settings {
1129 // Build a stack of all of the local values for that setting.
1130 while let Some(prev_entry) = paths_stack.last() {
1131 if let Some((prev_root_id, prev_path)) = prev_entry {
1132 if root_id != prev_root_id || !directory_path.starts_with(prev_path) {
1133 paths_stack.pop();
1134 project_settings_stack.pop();
1135 continue;
1136 }
1137 }
1138 break;
1139 }
1140
1141 match setting_value.deserialize_setting(local_settings) {
1142 Ok(local_settings) => {
1143 paths_stack.push(Some((*root_id, directory_path.as_ref())));
1144 project_settings_stack.push(local_settings);
1145
1146 // If a local settings file changed, then avoid recomputing local
1147 // settings for any path outside of that directory.
1148 if changed_local_path.map_or(
1149 false,
1150 |(changed_root_id, changed_local_path)| {
1151 *root_id != changed_root_id
1152 || !directory_path.starts_with(changed_local_path)
1153 },
1154 ) {
1155 continue;
1156 }
1157
1158 if let Some(value) = setting_value
1159 .load_setting(
1160 SettingsSources {
1161 default: &default_settings,
1162 global: global_settings.as_ref(),
1163 extensions: extension_settings.as_ref(),
1164 user: user_settings.as_ref(),
1165 release_channel: release_channel_settings.as_ref(),
1166 server: server_settings.as_ref(),
1167 project: &project_settings_stack.iter().collect::<Vec<_>>(),
1168 },
1169 cx,
1170 )
1171 .log_err()
1172 {
1173 setting_value.set_local_value(*root_id, directory_path.clone(), value);
1174 }
1175 }
1176 Err(error) => {
1177 return Err(InvalidSettingsError::LocalSettings {
1178 path: directory_path.join(local_settings_file_relative_path()),
1179 message: error.to_string(),
1180 });
1181 }
1182 }
1183 }
1184 }
1185 Ok(())
1186 }
1187
1188 pub fn editorconfig_properties(
1189 &self,
1190 for_worktree: WorktreeId,
1191 for_path: &Path,
1192 ) -> Option<EditorconfigProperties> {
1193 let mut properties = EditorconfigProperties::new();
1194
1195 for (directory_with_config, _, parsed_editorconfig) in
1196 self.local_editorconfig_settings(for_worktree)
1197 {
1198 if !for_path.starts_with(&directory_with_config) {
1199 properties.use_fallbacks();
1200 return Some(properties);
1201 }
1202 let parsed_editorconfig = parsed_editorconfig?;
1203 if parsed_editorconfig.is_root {
1204 properties = EditorconfigProperties::new();
1205 }
1206 for section in parsed_editorconfig.sections {
1207 section.apply_to(&mut properties, for_path).log_err()?;
1208 }
1209 }
1210
1211 properties.use_fallbacks();
1212 Some(properties)
1213 }
1214}
1215
1216#[derive(Debug, Clone, PartialEq)]
1217pub enum InvalidSettingsError {
1218 LocalSettings { path: PathBuf, message: String },
1219 UserSettings { message: String },
1220 ServerSettings { message: String },
1221 DefaultSettings { message: String },
1222 Editorconfig { path: PathBuf, message: String },
1223 Tasks { path: PathBuf, message: String },
1224 Debug { path: PathBuf, message: String },
1225}
1226
1227impl std::fmt::Display for InvalidSettingsError {
1228 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1229 match self {
1230 InvalidSettingsError::LocalSettings { message, .. }
1231 | InvalidSettingsError::UserSettings { message }
1232 | InvalidSettingsError::ServerSettings { message }
1233 | InvalidSettingsError::DefaultSettings { message }
1234 | InvalidSettingsError::Tasks { message, .. }
1235 | InvalidSettingsError::Editorconfig { message, .. }
1236 | InvalidSettingsError::Debug { message, .. } => {
1237 write!(f, "{message}")
1238 }
1239 }
1240 }
1241}
1242impl std::error::Error for InvalidSettingsError {}
1243
1244impl Debug for SettingsStore {
1245 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1246 f.debug_struct("SettingsStore")
1247 .field(
1248 "types",
1249 &self
1250 .setting_values
1251 .values()
1252 .map(|value| value.setting_type_name())
1253 .collect::<Vec<_>>(),
1254 )
1255 .field("default_settings", &self.raw_default_settings)
1256 .field("user_settings", &self.raw_user_settings)
1257 .field("local_settings", &self.raw_local_settings)
1258 .finish_non_exhaustive()
1259 }
1260}
1261
1262impl<T: Settings> AnySettingValue for SettingValue<T> {
1263 fn key(&self) -> Option<&'static str> {
1264 T::KEY
1265 }
1266
1267 fn setting_type_name(&self) -> &'static str {
1268 type_name::<T>()
1269 }
1270
1271 fn load_setting(
1272 &self,
1273 values: SettingsSources<DeserializedSetting>,
1274 cx: &mut App,
1275 ) -> Result<Box<dyn Any>> {
1276 Ok(Box::new(T::load(
1277 SettingsSources {
1278 default: values.default.0.downcast_ref::<T::FileContent>().unwrap(),
1279 global: values
1280 .global
1281 .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
1282 extensions: values
1283 .extensions
1284 .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
1285 user: values
1286 .user
1287 .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
1288 release_channel: values
1289 .release_channel
1290 .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
1291 server: values
1292 .server
1293 .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
1294 project: values
1295 .project
1296 .iter()
1297 .map(|value| value.0.downcast_ref().unwrap())
1298 .collect::<SmallVec<[_; 3]>>()
1299 .as_slice(),
1300 },
1301 cx,
1302 )?))
1303 }
1304
1305 fn deserialize_setting_with_key(
1306 &self,
1307 mut json: &Value,
1308 ) -> (Option<&'static str>, Result<DeserializedSetting>) {
1309 let mut key = None;
1310 if let Some(k) = T::KEY {
1311 if let Some(value) = json.get(k) {
1312 json = value;
1313 key = Some(k);
1314 } else if let Some((k, value)) = T::FALLBACK_KEY.and_then(|k| Some((k, json.get(k)?))) {
1315 json = value;
1316 key = Some(k);
1317 } else {
1318 let value = T::FileContent::default();
1319 return (T::KEY, Ok(DeserializedSetting(Box::new(value))));
1320 }
1321 }
1322 let value = T::FileContent::deserialize(json)
1323 .map(|value| DeserializedSetting(Box::new(value)))
1324 .map_err(anyhow::Error::from);
1325 (key, value)
1326 }
1327
1328 fn all_local_values(&self) -> Vec<(WorktreeId, Arc<Path>, &dyn Any)> {
1329 self.local_values
1330 .iter()
1331 .map(|(id, path, value)| (*id, path.clone(), value as _))
1332 .collect()
1333 }
1334
1335 fn value_for_path(&self, path: Option<SettingsLocation>) -> &dyn Any {
1336 if let Some(SettingsLocation { worktree_id, path }) = path {
1337 for (settings_root_id, settings_path, value) in self.local_values.iter().rev() {
1338 if worktree_id == *settings_root_id && path.starts_with(settings_path) {
1339 return value;
1340 }
1341 }
1342 }
1343 self.global_value
1344 .as_ref()
1345 .unwrap_or_else(|| panic!("no default value for setting {}", self.setting_type_name()))
1346 }
1347
1348 fn set_global_value(&mut self, value: Box<dyn Any>) {
1349 self.global_value = Some(*value.downcast().unwrap());
1350 }
1351
1352 fn set_local_value(&mut self, root_id: WorktreeId, path: Arc<Path>, value: Box<dyn Any>) {
1353 let value = *value.downcast().unwrap();
1354 match self
1355 .local_values
1356 .binary_search_by_key(&(root_id, &path), |e| (e.0, &e.1))
1357 {
1358 Ok(ix) => self.local_values[ix].2 = value,
1359 Err(ix) => self.local_values.insert(ix, (root_id, path, value)),
1360 }
1361 }
1362
1363 fn json_schema(&self, generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
1364 T::FileContent::json_schema(generator)
1365 }
1366
1367 fn edits_for_update(
1368 &self,
1369 raw_settings: &serde_json::Value,
1370 tab_size: usize,
1371 vscode_settings: &VsCodeSettings,
1372 text: &mut String,
1373 edits: &mut Vec<(Range<usize>, String)>,
1374 ) {
1375 let (key, deserialized_setting) = self.deserialize_setting_with_key(raw_settings);
1376 let old_content = match deserialized_setting {
1377 Ok(content) => content.0.downcast::<T::FileContent>().unwrap(),
1378 Err(_) => Box::<<T as Settings>::FileContent>::default(),
1379 };
1380 let mut new_content = old_content.clone();
1381 T::import_from_vscode(vscode_settings, &mut new_content);
1382
1383 let old_value = serde_json::to_value(&old_content).unwrap();
1384 let new_value = serde_json::to_value(new_content).unwrap();
1385
1386 let mut key_path = Vec::new();
1387 if let Some(key) = key {
1388 key_path.push(key);
1389 }
1390
1391 update_value_in_json_text(
1392 text,
1393 &mut key_path,
1394 tab_size,
1395 &old_value,
1396 &new_value,
1397 T::PRESERVED_KEYS.unwrap_or_default(),
1398 edits,
1399 );
1400 }
1401}
1402
1403#[cfg(test)]
1404mod tests {
1405 use crate::VsCodeSettingsSource;
1406
1407 use super::*;
1408 use serde_derive::Deserialize;
1409 use unindent::Unindent;
1410
1411 #[gpui::test]
1412 fn test_settings_store_basic(cx: &mut App) {
1413 let mut store = SettingsStore::new(cx);
1414 store.register_setting::<UserSettings>(cx);
1415 store.register_setting::<TurboSetting>(cx);
1416 store.register_setting::<MultiKeySettings>(cx);
1417 store
1418 .set_default_settings(
1419 r#"{
1420 "turbo": false,
1421 "user": {
1422 "name": "John Doe",
1423 "age": 30,
1424 "staff": false
1425 }
1426 }"#,
1427 cx,
1428 )
1429 .unwrap();
1430
1431 assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(false));
1432 assert_eq!(
1433 store.get::<UserSettings>(None),
1434 &UserSettings {
1435 name: "John Doe".to_string(),
1436 age: 30,
1437 staff: false,
1438 }
1439 );
1440 assert_eq!(
1441 store.get::<MultiKeySettings>(None),
1442 &MultiKeySettings {
1443 key1: String::new(),
1444 key2: String::new(),
1445 }
1446 );
1447
1448 store
1449 .set_user_settings(
1450 r#"{
1451 "turbo": true,
1452 "user": { "age": 31 },
1453 "key1": "a"
1454 }"#,
1455 cx,
1456 )
1457 .unwrap();
1458
1459 assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(true));
1460 assert_eq!(
1461 store.get::<UserSettings>(None),
1462 &UserSettings {
1463 name: "John Doe".to_string(),
1464 age: 31,
1465 staff: false
1466 }
1467 );
1468
1469 store
1470 .set_local_settings(
1471 WorktreeId::from_usize(1),
1472 Path::new("/root1").into(),
1473 LocalSettingsKind::Settings,
1474 Some(r#"{ "user": { "staff": true } }"#),
1475 cx,
1476 )
1477 .unwrap();
1478 store
1479 .set_local_settings(
1480 WorktreeId::from_usize(1),
1481 Path::new("/root1/subdir").into(),
1482 LocalSettingsKind::Settings,
1483 Some(r#"{ "user": { "name": "Jane Doe" } }"#),
1484 cx,
1485 )
1486 .unwrap();
1487
1488 store
1489 .set_local_settings(
1490 WorktreeId::from_usize(1),
1491 Path::new("/root2").into(),
1492 LocalSettingsKind::Settings,
1493 Some(r#"{ "user": { "age": 42 }, "key2": "b" }"#),
1494 cx,
1495 )
1496 .unwrap();
1497
1498 assert_eq!(
1499 store.get::<UserSettings>(Some(SettingsLocation {
1500 worktree_id: WorktreeId::from_usize(1),
1501 path: Path::new("/root1/something"),
1502 })),
1503 &UserSettings {
1504 name: "John 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("/root1/subdir/something")
1513 })),
1514 &UserSettings {
1515 name: "Jane Doe".to_string(),
1516 age: 31,
1517 staff: true
1518 }
1519 );
1520 assert_eq!(
1521 store.get::<UserSettings>(Some(SettingsLocation {
1522 worktree_id: WorktreeId::from_usize(1),
1523 path: Path::new("/root2/something")
1524 })),
1525 &UserSettings {
1526 name: "John Doe".to_string(),
1527 age: 42,
1528 staff: false
1529 }
1530 );
1531 assert_eq!(
1532 store.get::<MultiKeySettings>(Some(SettingsLocation {
1533 worktree_id: WorktreeId::from_usize(1),
1534 path: Path::new("/root2/something")
1535 })),
1536 &MultiKeySettings {
1537 key1: "a".to_string(),
1538 key2: "b".to_string(),
1539 }
1540 );
1541 }
1542
1543 #[gpui::test]
1544 fn test_setting_store_assign_json_before_register(cx: &mut App) {
1545 let mut store = SettingsStore::new(cx);
1546 store
1547 .set_default_settings(
1548 r#"{
1549 "turbo": true,
1550 "user": {
1551 "name": "John Doe",
1552 "age": 30,
1553 "staff": false
1554 },
1555 "key1": "x"
1556 }"#,
1557 cx,
1558 )
1559 .unwrap();
1560 store
1561 .set_user_settings(r#"{ "turbo": false }"#, cx)
1562 .unwrap();
1563 store.register_setting::<UserSettings>(cx);
1564 store.register_setting::<TurboSetting>(cx);
1565
1566 assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(false));
1567 assert_eq!(
1568 store.get::<UserSettings>(None),
1569 &UserSettings {
1570 name: "John Doe".to_string(),
1571 age: 30,
1572 staff: false,
1573 }
1574 );
1575
1576 store.register_setting::<MultiKeySettings>(cx);
1577 assert_eq!(
1578 store.get::<MultiKeySettings>(None),
1579 &MultiKeySettings {
1580 key1: "x".into(),
1581 key2: String::new(),
1582 }
1583 );
1584 }
1585
1586 fn check_settings_update<T: Settings>(
1587 store: &mut SettingsStore,
1588 old_json: String,
1589 update: fn(&mut T::FileContent),
1590 expected_new_json: String,
1591 cx: &mut App,
1592 ) {
1593 store.set_user_settings(&old_json, cx).ok();
1594 let edits = store.edits_for_update::<T>(&old_json, update);
1595 let mut new_json = old_json;
1596 for (range, replacement) in edits.into_iter() {
1597 new_json.replace_range(range, &replacement);
1598 }
1599 pretty_assertions::assert_eq!(new_json, expected_new_json);
1600 }
1601
1602 #[gpui::test]
1603 fn test_setting_store_update(cx: &mut App) {
1604 let mut store = SettingsStore::new(cx);
1605 store.register_setting::<MultiKeySettings>(cx);
1606 store.register_setting::<UserSettings>(cx);
1607 store.register_setting::<LanguageSettings>(cx);
1608
1609 // entries added and updated
1610 check_settings_update::<LanguageSettings>(
1611 &mut store,
1612 r#"{
1613 "languages": {
1614 "JSON": {
1615 "language_setting_1": true
1616 }
1617 }
1618 }"#
1619 .unindent(),
1620 |settings| {
1621 settings
1622 .languages
1623 .get_mut("JSON")
1624 .unwrap()
1625 .language_setting_1 = Some(false);
1626 settings.languages.insert(
1627 "Rust".into(),
1628 LanguageSettingEntry {
1629 language_setting_2: Some(true),
1630 ..Default::default()
1631 },
1632 );
1633 },
1634 r#"{
1635 "languages": {
1636 "Rust": {
1637 "language_setting_2": true
1638 },
1639 "JSON": {
1640 "language_setting_1": false
1641 }
1642 }
1643 }"#
1644 .unindent(),
1645 cx,
1646 );
1647
1648 // entries removed
1649 check_settings_update::<LanguageSettings>(
1650 &mut store,
1651 r#"{
1652 "languages": {
1653 "Rust": {
1654 "language_setting_2": true
1655 },
1656 "JSON": {
1657 "language_setting_1": false
1658 }
1659 }
1660 }"#
1661 .unindent(),
1662 |settings| {
1663 settings.languages.remove("JSON").unwrap();
1664 },
1665 r#"{
1666 "languages": {
1667 "Rust": {
1668 "language_setting_2": true
1669 }
1670 }
1671 }"#
1672 .unindent(),
1673 cx,
1674 );
1675
1676 check_settings_update::<LanguageSettings>(
1677 &mut store,
1678 r#"{
1679 "languages": {
1680 "Rust": {
1681 "language_setting_2": true
1682 },
1683 "JSON": {
1684 "language_setting_1": false
1685 }
1686 }
1687 }"#
1688 .unindent(),
1689 |settings| {
1690 settings.languages.remove("Rust").unwrap();
1691 },
1692 r#"{
1693 "languages": {
1694 "JSON": {
1695 "language_setting_1": false
1696 }
1697 }
1698 }"#
1699 .unindent(),
1700 cx,
1701 );
1702
1703 // weird formatting
1704 check_settings_update::<UserSettings>(
1705 &mut store,
1706 r#"{
1707 "user": { "age": 36, "name": "Max", "staff": true }
1708 }"#
1709 .unindent(),
1710 |settings| settings.age = Some(37),
1711 r#"{
1712 "user": { "age": 37, "name": "Max", "staff": true }
1713 }"#
1714 .unindent(),
1715 cx,
1716 );
1717
1718 // single-line formatting, other keys
1719 check_settings_update::<MultiKeySettings>(
1720 &mut store,
1721 r#"{ "one": 1, "two": 2 }"#.unindent(),
1722 |settings| settings.key1 = Some("x".into()),
1723 r#"{ "key1": "x", "one": 1, "two": 2 }"#.unindent(),
1724 cx,
1725 );
1726
1727 // empty object
1728 check_settings_update::<UserSettings>(
1729 &mut store,
1730 r#"{
1731 "user": {}
1732 }"#
1733 .unindent(),
1734 |settings| settings.age = Some(37),
1735 r#"{
1736 "user": {
1737 "age": 37
1738 }
1739 }"#
1740 .unindent(),
1741 cx,
1742 );
1743
1744 // no content
1745 check_settings_update::<UserSettings>(
1746 &mut store,
1747 r#""#.unindent(),
1748 |settings| settings.age = Some(37),
1749 r#"{
1750 "user": {
1751 "age": 37
1752 }
1753 }
1754 "#
1755 .unindent(),
1756 cx,
1757 );
1758
1759 check_settings_update::<UserSettings>(
1760 &mut store,
1761 r#"{
1762 }
1763 "#
1764 .unindent(),
1765 |settings| settings.age = Some(37),
1766 r#"{
1767 "user": {
1768 "age": 37
1769 }
1770 }
1771 "#
1772 .unindent(),
1773 cx,
1774 );
1775 }
1776
1777 #[gpui::test]
1778 fn test_vscode_import(cx: &mut App) {
1779 let mut store = SettingsStore::new(cx);
1780 store.register_setting::<UserSettings>(cx);
1781 store.register_setting::<JournalSettings>(cx);
1782 store.register_setting::<LanguageSettings>(cx);
1783 store.register_setting::<MultiKeySettings>(cx);
1784
1785 // create settings that werent present
1786 check_vscode_import(
1787 &mut store,
1788 r#"{
1789 }
1790 "#
1791 .unindent(),
1792 r#" { "user.age": 37 } "#.to_owned(),
1793 r#"{
1794 "user": {
1795 "age": 37
1796 }
1797 }
1798 "#
1799 .unindent(),
1800 cx,
1801 );
1802
1803 // persist settings that were present
1804 check_vscode_import(
1805 &mut store,
1806 r#"{
1807 "user": {
1808 "staff": true,
1809 "age": 37
1810 }
1811 }
1812 "#
1813 .unindent(),
1814 r#"{ "user.age": 42 }"#.to_owned(),
1815 r#"{
1816 "user": {
1817 "staff": true,
1818 "age": 42
1819 }
1820 }
1821 "#
1822 .unindent(),
1823 cx,
1824 );
1825
1826 // don't clobber settings that aren't present in vscode
1827 check_vscode_import(
1828 &mut store,
1829 r#"{
1830 "user": {
1831 "staff": true,
1832 "age": 37
1833 }
1834 }
1835 "#
1836 .unindent(),
1837 r#"{}"#.to_owned(),
1838 r#"{
1839 "user": {
1840 "staff": true,
1841 "age": 37
1842 }
1843 }
1844 "#
1845 .unindent(),
1846 cx,
1847 );
1848
1849 // custom enum
1850 check_vscode_import(
1851 &mut store,
1852 r#"{
1853 "journal": {
1854 "hour_format": "hour12"
1855 }
1856 }
1857 "#
1858 .unindent(),
1859 r#"{ "time_format": "24" }"#.to_owned(),
1860 r#"{
1861 "journal": {
1862 "hour_format": "hour24"
1863 }
1864 }
1865 "#
1866 .unindent(),
1867 cx,
1868 );
1869
1870 // Multiple keys for one setting
1871 check_vscode_import(
1872 &mut store,
1873 r#"{
1874 "key1": "value"
1875 }
1876 "#
1877 .unindent(),
1878 r#"{
1879 "key_1_first": "hello",
1880 "key_1_second": "world"
1881 }"#
1882 .to_owned(),
1883 r#"{
1884 "key1": "hello world"
1885 }
1886 "#
1887 .unindent(),
1888 cx,
1889 );
1890
1891 // Merging lists together entries added and updated
1892 check_vscode_import(
1893 &mut store,
1894 r#"{
1895 "languages": {
1896 "JSON": {
1897 "language_setting_1": true
1898 },
1899 "Rust": {
1900 "language_setting_2": true
1901 }
1902 }
1903 }"#
1904 .unindent(),
1905 r#"{
1906 "vscode_languages": [
1907 {
1908 "name": "JavaScript",
1909 "language_setting_1": true
1910 },
1911 {
1912 "name": "Rust",
1913 "language_setting_2": false
1914 }
1915 ]
1916 }"#
1917 .to_owned(),
1918 r#"{
1919 "languages": {
1920 "JavaScript": {
1921 "language_setting_1": true
1922 },
1923 "JSON": {
1924 "language_setting_1": true
1925 },
1926 "Rust": {
1927 "language_setting_2": false
1928 }
1929 }
1930 }"#
1931 .unindent(),
1932 cx,
1933 );
1934 }
1935
1936 fn check_vscode_import(
1937 store: &mut SettingsStore,
1938 old: String,
1939 vscode: String,
1940 expected: String,
1941 cx: &mut App,
1942 ) {
1943 store.set_user_settings(&old, cx).ok();
1944 let new = store.get_vscode_edits(
1945 old,
1946 &VsCodeSettings::from_str(&vscode, VsCodeSettingsSource::VsCode).unwrap(),
1947 );
1948 pretty_assertions::assert_eq!(new, expected);
1949 }
1950
1951 #[derive(Debug, PartialEq, Deserialize)]
1952 struct UserSettings {
1953 name: String,
1954 age: u32,
1955 staff: bool,
1956 }
1957
1958 #[derive(Default, Clone, Serialize, Deserialize, JsonSchema)]
1959 struct UserSettingsContent {
1960 name: Option<String>,
1961 age: Option<u32>,
1962 staff: Option<bool>,
1963 }
1964
1965 impl Settings for UserSettings {
1966 const KEY: Option<&'static str> = Some("user");
1967 type FileContent = UserSettingsContent;
1968
1969 fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
1970 sources.json_merge()
1971 }
1972
1973 fn import_from_vscode(vscode: &VsCodeSettings, current: &mut Self::FileContent) {
1974 vscode.u32_setting("user.age", &mut current.age);
1975 }
1976 }
1977
1978 #[derive(Debug, Deserialize, PartialEq)]
1979 struct TurboSetting(bool);
1980
1981 impl Settings for TurboSetting {
1982 const KEY: Option<&'static str> = Some("turbo");
1983 type FileContent = Option<bool>;
1984
1985 fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
1986 sources.json_merge()
1987 }
1988
1989 fn import_from_vscode(_vscode: &VsCodeSettings, _current: &mut Self::FileContent) {}
1990 }
1991
1992 #[derive(Clone, Debug, PartialEq, Deserialize)]
1993 struct MultiKeySettings {
1994 #[serde(default)]
1995 key1: String,
1996 #[serde(default)]
1997 key2: String,
1998 }
1999
2000 #[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
2001 struct MultiKeySettingsJson {
2002 key1: Option<String>,
2003 key2: Option<String>,
2004 }
2005
2006 impl Settings for MultiKeySettings {
2007 const KEY: Option<&'static str> = None;
2008
2009 type FileContent = MultiKeySettingsJson;
2010
2011 fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
2012 sources.json_merge()
2013 }
2014
2015 fn import_from_vscode(vscode: &VsCodeSettings, current: &mut Self::FileContent) {
2016 let first_value = vscode.read_string("key_1_first");
2017 let second_value = vscode.read_string("key_1_second");
2018
2019 if let Some((first, second)) = first_value.zip(second_value) {
2020 current.key1 = Some(format!("{} {}", first, second));
2021 }
2022 }
2023 }
2024
2025 #[derive(Debug, Deserialize)]
2026 struct JournalSettings {
2027 pub path: String,
2028 pub hour_format: HourFormat,
2029 }
2030
2031 #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
2032 #[serde(rename_all = "snake_case")]
2033 enum HourFormat {
2034 Hour12,
2035 Hour24,
2036 }
2037
2038 #[derive(Clone, Default, Debug, Serialize, Deserialize, JsonSchema)]
2039 struct JournalSettingsJson {
2040 pub path: Option<String>,
2041 pub hour_format: Option<HourFormat>,
2042 }
2043
2044 impl Settings for JournalSettings {
2045 const KEY: Option<&'static str> = Some("journal");
2046
2047 type FileContent = JournalSettingsJson;
2048
2049 fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
2050 sources.json_merge()
2051 }
2052
2053 fn import_from_vscode(vscode: &VsCodeSettings, current: &mut Self::FileContent) {
2054 vscode.enum_setting("time_format", &mut current.hour_format, |s| match s {
2055 "12" => Some(HourFormat::Hour12),
2056 "24" => Some(HourFormat::Hour24),
2057 _ => None,
2058 });
2059 }
2060 }
2061
2062 #[gpui::test]
2063 fn test_global_settings(cx: &mut App) {
2064 let mut store = SettingsStore::new(cx);
2065 store.register_setting::<UserSettings>(cx);
2066 store
2067 .set_default_settings(
2068 r#"{
2069 "user": {
2070 "name": "John Doe",
2071 "age": 30,
2072 "staff": false
2073 }
2074 }"#,
2075 cx,
2076 )
2077 .unwrap();
2078
2079 // Set global settings - these should override defaults but not user settings
2080 store
2081 .set_global_settings(
2082 r#"{
2083 "user": {
2084 "name": "Global User",
2085 "age": 35,
2086 "staff": true
2087 }
2088 }"#,
2089 cx,
2090 )
2091 .unwrap();
2092
2093 // Before user settings, global settings should apply
2094 assert_eq!(
2095 store.get::<UserSettings>(None),
2096 &UserSettings {
2097 name: "Global User".to_string(),
2098 age: 35,
2099 staff: true,
2100 }
2101 );
2102
2103 // Set user settings - these should override both defaults and global
2104 store
2105 .set_user_settings(
2106 r#"{
2107 "user": {
2108 "age": 40
2109 }
2110 }"#,
2111 cx,
2112 )
2113 .unwrap();
2114
2115 // User settings should override global settings
2116 assert_eq!(
2117 store.get::<UserSettings>(None),
2118 &UserSettings {
2119 name: "Global User".to_string(), // Name from global settings
2120 age: 40, // Age from user settings
2121 staff: true, // Staff from global settings
2122 }
2123 );
2124 }
2125
2126 #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
2127 struct LanguageSettings {
2128 #[serde(default)]
2129 languages: HashMap<String, LanguageSettingEntry>,
2130 }
2131
2132 #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
2133 struct LanguageSettingEntry {
2134 language_setting_1: Option<bool>,
2135 language_setting_2: Option<bool>,
2136 }
2137
2138 impl Settings for LanguageSettings {
2139 const KEY: Option<&'static str> = None;
2140
2141 type FileContent = Self;
2142
2143 fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
2144 sources.json_merge()
2145 }
2146
2147 fn import_from_vscode(vscode: &VsCodeSettings, current: &mut Self::FileContent) {
2148 current.languages.extend(
2149 vscode
2150 .read_value("vscode_languages")
2151 .and_then(|value| value.as_array())
2152 .map(|languages| {
2153 languages
2154 .iter()
2155 .filter_map(|value| value.as_object())
2156 .filter_map(|item| {
2157 let mut rest = item.clone();
2158 let name = rest.remove("name")?.as_str()?.to_string();
2159 let entry = serde_json::from_value::<LanguageSettingEntry>(
2160 serde_json::Value::Object(rest),
2161 )
2162 .ok()?;
2163
2164 Some((name, entry))
2165 })
2166 })
2167 .into_iter()
2168 .flatten(),
2169 );
2170 }
2171 }
2172}