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 /// Updates the value of a setting in a JSON file, returning the new text
537 /// for that JSON file.
538 pub fn new_text_for_update<T: Settings>(
539 &self,
540 old_text: String,
541 update: impl FnOnce(&mut T::FileContent),
542 ) -> String {
543 let edits = self.edits_for_update::<T>(&old_text, update);
544 let mut new_text = old_text;
545 for (range, replacement) in edits.into_iter() {
546 new_text.replace_range(range, &replacement);
547 }
548 new_text
549 }
550
551 pub fn get_vscode_edits(&self, mut old_text: String, vscode: &VsCodeSettings) -> String {
552 let mut new_text = old_text.clone();
553 let mut edits: Vec<(Range<usize>, String)> = Vec::new();
554 let raw_settings = parse_json_with_comments::<Value>(&old_text).unwrap_or_default();
555 let tab_size = self.json_tab_size();
556 for v in self.setting_values.values() {
557 v.edits_for_update(&raw_settings, tab_size, vscode, &mut old_text, &mut edits);
558 }
559 for (range, replacement) in edits.into_iter() {
560 new_text.replace_range(range, &replacement);
561 }
562 new_text
563 }
564
565 /// Updates the value of a setting in a JSON file, returning a list
566 /// of edits to apply to the JSON file.
567 pub fn edits_for_update<T: Settings>(
568 &self,
569 text: &str,
570 update: impl FnOnce(&mut T::FileContent),
571 ) -> Vec<(Range<usize>, String)> {
572 let setting_type_id = TypeId::of::<T>();
573
574 let preserved_keys = T::PRESERVED_KEYS.unwrap_or_default();
575
576 let setting = self
577 .setting_values
578 .get(&setting_type_id)
579 .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()));
580 let raw_settings = parse_json_with_comments::<Value>(text).unwrap_or_default();
581 let (key, deserialized_setting) = setting.deserialize_setting_with_key(&raw_settings);
582 let old_content = match deserialized_setting {
583 Ok(content) => content.0.downcast::<T::FileContent>().unwrap(),
584 Err(_) => Box::<<T as Settings>::FileContent>::default(),
585 };
586 let mut new_content = old_content.clone();
587 update(&mut new_content);
588
589 let old_value = serde_json::to_value(&old_content).unwrap();
590 let new_value = serde_json::to_value(new_content).unwrap();
591
592 let mut key_path = Vec::new();
593 if let Some(key) = key {
594 key_path.push(key);
595 }
596
597 let mut edits = Vec::new();
598 let tab_size = self.json_tab_size();
599 let mut text = text.to_string();
600 update_value_in_json_text(
601 &mut text,
602 &mut key_path,
603 tab_size,
604 &old_value,
605 &new_value,
606 preserved_keys,
607 &mut edits,
608 );
609 edits
610 }
611
612 /// Configure the tab sized when updating JSON files.
613 pub fn set_json_tab_size_callback<T: Settings>(
614 &mut self,
615 get_tab_size: fn(&T) -> Option<usize>,
616 ) {
617 self.tab_size_callback = Some((
618 TypeId::of::<T>(),
619 Box::new(move |value| get_tab_size(value.downcast_ref::<T>().unwrap())),
620 ));
621 }
622
623 pub fn json_tab_size(&self) -> usize {
624 const DEFAULT_JSON_TAB_SIZE: usize = 2;
625
626 if let Some((setting_type_id, callback)) = &self.tab_size_callback {
627 let setting_value = self.setting_values.get(setting_type_id).unwrap();
628 let value = setting_value.value_for_path(None);
629 if let Some(value) = callback(value) {
630 return value;
631 }
632 }
633
634 DEFAULT_JSON_TAB_SIZE
635 }
636
637 /// Sets the default settings via a JSON string.
638 ///
639 /// The string should contain a JSON object with a default value for every setting.
640 pub fn set_default_settings(
641 &mut self,
642 default_settings_content: &str,
643 cx: &mut App,
644 ) -> Result<()> {
645 let settings: Value = parse_json_with_comments(default_settings_content)?;
646 anyhow::ensure!(settings.is_object(), "settings must be an object");
647 self.raw_default_settings = settings;
648 self.recompute_values(None, cx)?;
649 Ok(())
650 }
651
652 /// Sets the user settings via a JSON string.
653 pub fn set_user_settings(
654 &mut self,
655 user_settings_content: &str,
656 cx: &mut App,
657 ) -> Result<Value> {
658 let settings: Value = if user_settings_content.is_empty() {
659 parse_json_with_comments("{}")?
660 } else {
661 parse_json_with_comments(user_settings_content)?
662 };
663
664 anyhow::ensure!(settings.is_object(), "settings must be an object");
665 self.raw_user_settings = settings.clone();
666 self.recompute_values(None, cx)?;
667 Ok(settings)
668 }
669
670 /// Sets the global settings via a JSON string.
671 pub fn set_global_settings(
672 &mut self,
673 global_settings_content: &str,
674 cx: &mut App,
675 ) -> Result<Value> {
676 let settings: Value = if global_settings_content.is_empty() {
677 parse_json_with_comments("{}")?
678 } else {
679 parse_json_with_comments(global_settings_content)?
680 };
681
682 anyhow::ensure!(settings.is_object(), "settings must be an object");
683 self.raw_global_settings = Some(settings.clone());
684 self.recompute_values(None, cx)?;
685 Ok(settings)
686 }
687
688 pub fn set_server_settings(
689 &mut self,
690 server_settings_content: &str,
691 cx: &mut App,
692 ) -> Result<()> {
693 let settings: Option<Value> = if server_settings_content.is_empty() {
694 None
695 } else {
696 parse_json_with_comments(server_settings_content)?
697 };
698
699 anyhow::ensure!(
700 settings
701 .as_ref()
702 .map(|value| value.is_object())
703 .unwrap_or(true),
704 "settings must be an object"
705 );
706 self.raw_server_settings = settings;
707 self.recompute_values(None, cx)?;
708 Ok(())
709 }
710
711 /// Add or remove a set of local settings via a JSON string.
712 pub fn set_local_settings(
713 &mut self,
714 root_id: WorktreeId,
715 directory_path: Arc<Path>,
716 kind: LocalSettingsKind,
717 settings_content: Option<&str>,
718 cx: &mut App,
719 ) -> std::result::Result<(), InvalidSettingsError> {
720 let mut zed_settings_changed = false;
721 match (
722 kind,
723 settings_content
724 .map(|content| content.trim())
725 .filter(|content| !content.is_empty()),
726 ) {
727 (LocalSettingsKind::Tasks, _) => {
728 return Err(InvalidSettingsError::Tasks {
729 message: "Attempted to submit tasks into the settings store".to_string(),
730 path: directory_path.join(task_file_name()),
731 });
732 }
733 (LocalSettingsKind::Debug, _) => {
734 return Err(InvalidSettingsError::Debug {
735 message: "Attempted to submit debugger config into the settings store"
736 .to_string(),
737 path: directory_path.join(task_file_name()),
738 });
739 }
740 (LocalSettingsKind::Settings, None) => {
741 zed_settings_changed = self
742 .raw_local_settings
743 .remove(&(root_id, directory_path.clone()))
744 .is_some()
745 }
746 (LocalSettingsKind::Editorconfig, None) => {
747 self.raw_editorconfig_settings
748 .remove(&(root_id, directory_path.clone()));
749 }
750 (LocalSettingsKind::Settings, Some(settings_contents)) => {
751 let new_settings =
752 parse_json_with_comments::<Value>(settings_contents).map_err(|e| {
753 InvalidSettingsError::LocalSettings {
754 path: directory_path.join(local_settings_file_relative_path()),
755 message: e.to_string(),
756 }
757 })?;
758 match self
759 .raw_local_settings
760 .entry((root_id, directory_path.clone()))
761 {
762 btree_map::Entry::Vacant(v) => {
763 v.insert(new_settings);
764 zed_settings_changed = true;
765 }
766 btree_map::Entry::Occupied(mut o) => {
767 if o.get() != &new_settings {
768 o.insert(new_settings);
769 zed_settings_changed = true;
770 }
771 }
772 }
773 }
774 (LocalSettingsKind::Editorconfig, Some(editorconfig_contents)) => {
775 match self
776 .raw_editorconfig_settings
777 .entry((root_id, directory_path.clone()))
778 {
779 btree_map::Entry::Vacant(v) => match editorconfig_contents.parse() {
780 Ok(new_contents) => {
781 v.insert((editorconfig_contents.to_owned(), Some(new_contents)));
782 }
783 Err(e) => {
784 v.insert((editorconfig_contents.to_owned(), None));
785 return Err(InvalidSettingsError::Editorconfig {
786 message: e.to_string(),
787 path: directory_path.join(EDITORCONFIG_NAME),
788 });
789 }
790 },
791 btree_map::Entry::Occupied(mut o) => {
792 if o.get().0 != editorconfig_contents {
793 match editorconfig_contents.parse() {
794 Ok(new_contents) => {
795 o.insert((
796 editorconfig_contents.to_owned(),
797 Some(new_contents),
798 ));
799 }
800 Err(e) => {
801 o.insert((editorconfig_contents.to_owned(), None));
802 return Err(InvalidSettingsError::Editorconfig {
803 message: e.to_string(),
804 path: directory_path.join(EDITORCONFIG_NAME),
805 });
806 }
807 }
808 }
809 }
810 }
811 }
812 };
813
814 if zed_settings_changed {
815 self.recompute_values(Some((root_id, &directory_path)), cx)?;
816 }
817 Ok(())
818 }
819
820 pub fn set_extension_settings<T: Serialize>(&mut self, content: T, cx: &mut App) -> Result<()> {
821 let settings: Value = serde_json::to_value(content)?;
822 anyhow::ensure!(settings.is_object(), "settings must be an object");
823 self.raw_extension_settings = settings;
824 self.recompute_values(None, cx)?;
825 Ok(())
826 }
827
828 /// Add or remove a set of local settings via a JSON string.
829 pub fn clear_local_settings(&mut self, root_id: WorktreeId, cx: &mut App) -> Result<()> {
830 self.raw_local_settings
831 .retain(|(worktree_id, _), _| worktree_id != &root_id);
832 self.recompute_values(Some((root_id, "".as_ref())), cx)?;
833 Ok(())
834 }
835
836 pub fn local_settings(
837 &self,
838 root_id: WorktreeId,
839 ) -> impl '_ + Iterator<Item = (Arc<Path>, String)> {
840 self.raw_local_settings
841 .range(
842 (root_id, Path::new("").into())
843 ..(
844 WorktreeId::from_usize(root_id.to_usize() + 1),
845 Path::new("").into(),
846 ),
847 )
848 .map(|((_, path), content)| (path.clone(), serde_json::to_string(content).unwrap()))
849 }
850
851 pub fn local_editorconfig_settings(
852 &self,
853 root_id: WorktreeId,
854 ) -> impl '_ + Iterator<Item = (Arc<Path>, String, Option<Editorconfig>)> {
855 self.raw_editorconfig_settings
856 .range(
857 (root_id, Path::new("").into())
858 ..(
859 WorktreeId::from_usize(root_id.to_usize() + 1),
860 Path::new("").into(),
861 ),
862 )
863 .map(|((_, path), (content, parsed_content))| {
864 (path.clone(), content.clone(), parsed_content.clone())
865 })
866 }
867
868 pub fn json_schema(&self, schema_params: &SettingsJsonSchemaParams, cx: &App) -> Value {
869 let mut generator = schemars::generate::SchemaSettings::draft2019_09()
870 .with_transform(DefaultDenyUnknownFields)
871 .into_generator();
872 let mut combined_schema = json!({
873 "type": "object",
874 "properties": {}
875 });
876
877 // Merge together settings schemas, similarly to json schema's "allOf". This merging is
878 // recursive, though at time of writing this recursive nature isn't used very much. An
879 // example of it is the schema for `jupyter` having contribution from both `EditorSettings`
880 // and `JupyterSettings`.
881 //
882 // This logic could be removed in favor of "allOf", but then there isn't the opportunity to
883 // validate and fully control the merge.
884 for setting_value in self.setting_values.values() {
885 let mut setting_schema = setting_value.json_schema(&mut generator);
886
887 if let Some(key) = setting_value.key() {
888 if let Some(properties) = combined_schema.get_mut("properties") {
889 if let Some(properties_obj) = properties.as_object_mut() {
890 if let Some(target) = properties_obj.get_mut(key) {
891 merge_schema(target, setting_schema.to_value());
892 } else {
893 properties_obj.insert(key.to_string(), setting_schema.to_value());
894 }
895 }
896 }
897 } else {
898 setting_schema.remove("description");
899 setting_schema.remove("additionalProperties");
900 merge_schema(&mut combined_schema, setting_schema.to_value());
901 }
902 }
903
904 fn merge_schema(target: &mut serde_json::Value, source: serde_json::Value) {
905 let (Some(target_obj), serde_json::Value::Object(source_obj)) =
906 (target.as_object_mut(), source)
907 else {
908 return;
909 };
910
911 for (source_key, source_value) in source_obj {
912 match source_key.as_str() {
913 "properties" => {
914 let serde_json::Value::Object(source_properties) = source_value else {
915 log::error!(
916 "bug: expected object for `{}` json schema field, but got: {}",
917 source_key,
918 source_value
919 );
920 continue;
921 };
922 let target_properties =
923 target_obj.entry(source_key.clone()).or_insert(json!({}));
924 let Some(target_properties) = target_properties.as_object_mut() else {
925 log::error!(
926 "bug: expected object for `{}` json schema field, but got: {}",
927 source_key,
928 target_properties
929 );
930 continue;
931 };
932 for (key, value) in source_properties {
933 if let Some(existing) = target_properties.get_mut(&key) {
934 merge_schema(existing, value);
935 } else {
936 target_properties.insert(key, value);
937 }
938 }
939 }
940 "allOf" | "anyOf" | "oneOf" => {
941 let serde_json::Value::Array(source_array) = source_value else {
942 log::error!(
943 "bug: expected array for `{}` json schema field, but got: {}",
944 source_key,
945 source_value,
946 );
947 continue;
948 };
949 let target_array =
950 target_obj.entry(source_key.clone()).or_insert(json!([]));
951 let Some(target_array) = target_array.as_array_mut() else {
952 log::error!(
953 "bug: expected array for `{}` json schema field, but got: {}",
954 source_key,
955 target_array,
956 );
957 continue;
958 };
959 target_array.extend(source_array);
960 }
961 "type"
962 | "$ref"
963 | "enum"
964 | "minimum"
965 | "maximum"
966 | "pattern"
967 | "description"
968 | "additionalProperties" => {
969 if let Some(old_value) =
970 target_obj.insert(source_key.clone(), source_value.clone())
971 {
972 if old_value != source_value {
973 log::error!(
974 "bug: while merging JSON schemas, \
975 mismatch `\"{}\": {}` (before was `{}`)",
976 source_key,
977 old_value,
978 source_value
979 );
980 }
981 }
982 }
983 _ => {
984 log::error!(
985 "bug: while merging settings JSON schemas, \
986 encountered unexpected `\"{}\": {}`",
987 source_key,
988 source_value
989 );
990 }
991 }
992 }
993 }
994
995 // add schemas which are determined at runtime
996 for parameterized_json_schema in inventory::iter::<ParameterizedJsonSchema>() {
997 (parameterized_json_schema.add_and_get_ref)(&mut generator, schema_params, cx);
998 }
999
1000 // add merged settings schema to the definitions
1001 const ZED_SETTINGS: &str = "ZedSettings";
1002 let zed_settings_ref = add_new_subschema(&mut generator, ZED_SETTINGS, combined_schema);
1003
1004 // add `ZedReleaseStageSettings` which is the same as `ZedSettings` except that unknown
1005 // fields are rejected.
1006 let mut zed_release_stage_settings = zed_settings_ref.clone();
1007 zed_release_stage_settings.insert("unevaluatedProperties".to_string(), false.into());
1008 let zed_release_stage_settings_ref = add_new_subschema(
1009 &mut generator,
1010 "ZedReleaseStageSettings",
1011 zed_release_stage_settings.to_value(),
1012 );
1013
1014 // Remove `"additionalProperties": false` added by `DefaultDenyUnknownFields` so that
1015 // unknown fields can be handled by the root schema and `ZedReleaseStageSettings`.
1016 let mut definitions = generator.take_definitions(true);
1017 definitions
1018 .get_mut(ZED_SETTINGS)
1019 .unwrap()
1020 .as_object_mut()
1021 .unwrap()
1022 .remove("additionalProperties");
1023
1024 let meta_schema = generator
1025 .settings()
1026 .meta_schema
1027 .as_ref()
1028 .expect("meta_schema should be present in schemars settings")
1029 .to_string();
1030
1031 json!({
1032 "$schema": meta_schema,
1033 "title": "Zed Settings",
1034 "unevaluatedProperties": false,
1035 // ZedSettings + settings overrides for each release stage
1036 "allOf": [
1037 zed_settings_ref,
1038 {
1039 "properties": {
1040 "dev": zed_release_stage_settings_ref,
1041 "nightly": zed_release_stage_settings_ref,
1042 "stable": zed_release_stage_settings_ref,
1043 "preview": zed_release_stage_settings_ref,
1044 }
1045 }
1046 ],
1047 "$defs": definitions,
1048 })
1049 }
1050
1051 fn recompute_values(
1052 &mut self,
1053 changed_local_path: Option<(WorktreeId, &Path)>,
1054 cx: &mut App,
1055 ) -> std::result::Result<(), InvalidSettingsError> {
1056 // Reload the global and local values for every setting.
1057 let mut project_settings_stack = Vec::<DeserializedSetting>::new();
1058 let mut paths_stack = Vec::<Option<(WorktreeId, &Path)>>::new();
1059 for setting_value in self.setting_values.values_mut() {
1060 let default_settings = setting_value
1061 .deserialize_setting(&self.raw_default_settings)
1062 .map_err(|e| InvalidSettingsError::DefaultSettings {
1063 message: e.to_string(),
1064 })?;
1065
1066 let global_settings = self
1067 .raw_global_settings
1068 .as_ref()
1069 .and_then(|setting| setting_value.deserialize_setting(setting).log_err());
1070
1071 let extension_settings = setting_value
1072 .deserialize_setting(&self.raw_extension_settings)
1073 .log_err();
1074
1075 let user_settings = match setting_value.deserialize_setting(&self.raw_user_settings) {
1076 Ok(settings) => Some(settings),
1077 Err(error) => {
1078 return Err(InvalidSettingsError::UserSettings {
1079 message: error.to_string(),
1080 });
1081 }
1082 };
1083
1084 let server_settings = self
1085 .raw_server_settings
1086 .as_ref()
1087 .and_then(|setting| setting_value.deserialize_setting(setting).log_err());
1088
1089 let mut release_channel_settings = None;
1090 if let Some(release_settings) = &self
1091 .raw_user_settings
1092 .get(release_channel::RELEASE_CHANNEL.dev_name())
1093 {
1094 if let Some(release_settings) = setting_value
1095 .deserialize_setting(release_settings)
1096 .log_err()
1097 {
1098 release_channel_settings = Some(release_settings);
1099 }
1100 }
1101
1102 // If the global settings file changed, reload the global value for the field.
1103 if changed_local_path.is_none() {
1104 if let Some(value) = setting_value
1105 .load_setting(
1106 SettingsSources {
1107 default: &default_settings,
1108 global: global_settings.as_ref(),
1109 extensions: extension_settings.as_ref(),
1110 user: user_settings.as_ref(),
1111 release_channel: release_channel_settings.as_ref(),
1112 server: server_settings.as_ref(),
1113 project: &[],
1114 },
1115 cx,
1116 )
1117 .log_err()
1118 {
1119 setting_value.set_global_value(value);
1120 }
1121 }
1122
1123 // Reload the local values for the setting.
1124 paths_stack.clear();
1125 project_settings_stack.clear();
1126 for ((root_id, directory_path), local_settings) in &self.raw_local_settings {
1127 // Build a stack of all of the local values for that setting.
1128 while let Some(prev_entry) = paths_stack.last() {
1129 if let Some((prev_root_id, prev_path)) = prev_entry {
1130 if root_id != prev_root_id || !directory_path.starts_with(prev_path) {
1131 paths_stack.pop();
1132 project_settings_stack.pop();
1133 continue;
1134 }
1135 }
1136 break;
1137 }
1138
1139 match setting_value.deserialize_setting(local_settings) {
1140 Ok(local_settings) => {
1141 paths_stack.push(Some((*root_id, directory_path.as_ref())));
1142 project_settings_stack.push(local_settings);
1143
1144 // If a local settings file changed, then avoid recomputing local
1145 // settings for any path outside of that directory.
1146 if changed_local_path.map_or(
1147 false,
1148 |(changed_root_id, changed_local_path)| {
1149 *root_id != changed_root_id
1150 || !directory_path.starts_with(changed_local_path)
1151 },
1152 ) {
1153 continue;
1154 }
1155
1156 if let Some(value) = setting_value
1157 .load_setting(
1158 SettingsSources {
1159 default: &default_settings,
1160 global: global_settings.as_ref(),
1161 extensions: extension_settings.as_ref(),
1162 user: user_settings.as_ref(),
1163 release_channel: release_channel_settings.as_ref(),
1164 server: server_settings.as_ref(),
1165 project: &project_settings_stack.iter().collect::<Vec<_>>(),
1166 },
1167 cx,
1168 )
1169 .log_err()
1170 {
1171 setting_value.set_local_value(*root_id, directory_path.clone(), value);
1172 }
1173 }
1174 Err(error) => {
1175 return Err(InvalidSettingsError::LocalSettings {
1176 path: directory_path.join(local_settings_file_relative_path()),
1177 message: error.to_string(),
1178 });
1179 }
1180 }
1181 }
1182 }
1183 Ok(())
1184 }
1185
1186 pub fn editorconfig_properties(
1187 &self,
1188 for_worktree: WorktreeId,
1189 for_path: &Path,
1190 ) -> Option<EditorconfigProperties> {
1191 let mut properties = EditorconfigProperties::new();
1192
1193 for (directory_with_config, _, parsed_editorconfig) in
1194 self.local_editorconfig_settings(for_worktree)
1195 {
1196 if !for_path.starts_with(&directory_with_config) {
1197 properties.use_fallbacks();
1198 return Some(properties);
1199 }
1200 let parsed_editorconfig = parsed_editorconfig?;
1201 if parsed_editorconfig.is_root {
1202 properties = EditorconfigProperties::new();
1203 }
1204 for section in parsed_editorconfig.sections {
1205 section.apply_to(&mut properties, for_path).log_err()?;
1206 }
1207 }
1208
1209 properties.use_fallbacks();
1210 Some(properties)
1211 }
1212}
1213
1214#[derive(Debug, Clone, PartialEq)]
1215pub enum InvalidSettingsError {
1216 LocalSettings { path: PathBuf, message: String },
1217 UserSettings { message: String },
1218 ServerSettings { message: String },
1219 DefaultSettings { message: String },
1220 Editorconfig { path: PathBuf, message: String },
1221 Tasks { path: PathBuf, message: String },
1222 Debug { path: PathBuf, message: String },
1223}
1224
1225impl std::fmt::Display for InvalidSettingsError {
1226 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1227 match self {
1228 InvalidSettingsError::LocalSettings { message, .. }
1229 | InvalidSettingsError::UserSettings { message }
1230 | InvalidSettingsError::ServerSettings { message }
1231 | InvalidSettingsError::DefaultSettings { message }
1232 | InvalidSettingsError::Tasks { message, .. }
1233 | InvalidSettingsError::Editorconfig { message, .. }
1234 | InvalidSettingsError::Debug { message, .. } => {
1235 write!(f, "{message}")
1236 }
1237 }
1238 }
1239}
1240impl std::error::Error for InvalidSettingsError {}
1241
1242impl Debug for SettingsStore {
1243 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1244 f.debug_struct("SettingsStore")
1245 .field(
1246 "types",
1247 &self
1248 .setting_values
1249 .values()
1250 .map(|value| value.setting_type_name())
1251 .collect::<Vec<_>>(),
1252 )
1253 .field("default_settings", &self.raw_default_settings)
1254 .field("user_settings", &self.raw_user_settings)
1255 .field("local_settings", &self.raw_local_settings)
1256 .finish_non_exhaustive()
1257 }
1258}
1259
1260impl<T: Settings> AnySettingValue for SettingValue<T> {
1261 fn key(&self) -> Option<&'static str> {
1262 T::KEY
1263 }
1264
1265 fn setting_type_name(&self) -> &'static str {
1266 type_name::<T>()
1267 }
1268
1269 fn load_setting(
1270 &self,
1271 values: SettingsSources<DeserializedSetting>,
1272 cx: &mut App,
1273 ) -> Result<Box<dyn Any>> {
1274 Ok(Box::new(T::load(
1275 SettingsSources {
1276 default: values.default.0.downcast_ref::<T::FileContent>().unwrap(),
1277 global: values
1278 .global
1279 .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
1280 extensions: values
1281 .extensions
1282 .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
1283 user: values
1284 .user
1285 .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
1286 release_channel: values
1287 .release_channel
1288 .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
1289 server: values
1290 .server
1291 .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
1292 project: values
1293 .project
1294 .iter()
1295 .map(|value| value.0.downcast_ref().unwrap())
1296 .collect::<SmallVec<[_; 3]>>()
1297 .as_slice(),
1298 },
1299 cx,
1300 )?))
1301 }
1302
1303 fn deserialize_setting_with_key(
1304 &self,
1305 mut json: &Value,
1306 ) -> (Option<&'static str>, Result<DeserializedSetting>) {
1307 let mut key = None;
1308 if let Some(k) = T::KEY {
1309 if let Some(value) = json.get(k) {
1310 json = value;
1311 key = Some(k);
1312 } else if let Some((k, value)) = T::FALLBACK_KEY.and_then(|k| Some((k, json.get(k)?))) {
1313 json = value;
1314 key = Some(k);
1315 } else {
1316 let value = T::FileContent::default();
1317 return (T::KEY, Ok(DeserializedSetting(Box::new(value))));
1318 }
1319 }
1320 let value = T::FileContent::deserialize(json)
1321 .map(|value| DeserializedSetting(Box::new(value)))
1322 .map_err(anyhow::Error::from);
1323 (key, value)
1324 }
1325
1326 fn all_local_values(&self) -> Vec<(WorktreeId, Arc<Path>, &dyn Any)> {
1327 self.local_values
1328 .iter()
1329 .map(|(id, path, value)| (*id, path.clone(), value as _))
1330 .collect()
1331 }
1332
1333 fn value_for_path(&self, path: Option<SettingsLocation>) -> &dyn Any {
1334 if let Some(SettingsLocation { worktree_id, path }) = path {
1335 for (settings_root_id, settings_path, value) in self.local_values.iter().rev() {
1336 if worktree_id == *settings_root_id && path.starts_with(settings_path) {
1337 return value;
1338 }
1339 }
1340 }
1341 self.global_value
1342 .as_ref()
1343 .unwrap_or_else(|| panic!("no default value for setting {}", self.setting_type_name()))
1344 }
1345
1346 fn set_global_value(&mut self, value: Box<dyn Any>) {
1347 self.global_value = Some(*value.downcast().unwrap());
1348 }
1349
1350 fn set_local_value(&mut self, root_id: WorktreeId, path: Arc<Path>, value: Box<dyn Any>) {
1351 let value = *value.downcast().unwrap();
1352 match self
1353 .local_values
1354 .binary_search_by_key(&(root_id, &path), |e| (e.0, &e.1))
1355 {
1356 Ok(ix) => self.local_values[ix].2 = value,
1357 Err(ix) => self.local_values.insert(ix, (root_id, path, value)),
1358 }
1359 }
1360
1361 fn json_schema(&self, generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
1362 T::FileContent::json_schema(generator)
1363 }
1364
1365 fn edits_for_update(
1366 &self,
1367 raw_settings: &serde_json::Value,
1368 tab_size: usize,
1369 vscode_settings: &VsCodeSettings,
1370 text: &mut String,
1371 edits: &mut Vec<(Range<usize>, String)>,
1372 ) {
1373 let (key, deserialized_setting) = self.deserialize_setting_with_key(raw_settings);
1374 let old_content = match deserialized_setting {
1375 Ok(content) => content.0.downcast::<T::FileContent>().unwrap(),
1376 Err(_) => Box::<<T as Settings>::FileContent>::default(),
1377 };
1378 let mut new_content = old_content.clone();
1379 T::import_from_vscode(vscode_settings, &mut new_content);
1380
1381 let old_value = serde_json::to_value(&old_content).unwrap();
1382 let new_value = serde_json::to_value(new_content).unwrap();
1383
1384 let mut key_path = Vec::new();
1385 if let Some(key) = key {
1386 key_path.push(key);
1387 }
1388
1389 update_value_in_json_text(
1390 text,
1391 &mut key_path,
1392 tab_size,
1393 &old_value,
1394 &new_value,
1395 T::PRESERVED_KEYS.unwrap_or_default(),
1396 edits,
1397 );
1398 }
1399}
1400
1401#[cfg(test)]
1402mod tests {
1403 use crate::VsCodeSettingsSource;
1404
1405 use super::*;
1406 use serde_derive::Deserialize;
1407 use unindent::Unindent;
1408
1409 #[gpui::test]
1410 fn test_settings_store_basic(cx: &mut App) {
1411 let mut store = SettingsStore::new(cx);
1412 store.register_setting::<UserSettings>(cx);
1413 store.register_setting::<TurboSetting>(cx);
1414 store.register_setting::<MultiKeySettings>(cx);
1415 store
1416 .set_default_settings(
1417 r#"{
1418 "turbo": false,
1419 "user": {
1420 "name": "John Doe",
1421 "age": 30,
1422 "staff": false
1423 }
1424 }"#,
1425 cx,
1426 )
1427 .unwrap();
1428
1429 assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(false));
1430 assert_eq!(
1431 store.get::<UserSettings>(None),
1432 &UserSettings {
1433 name: "John Doe".to_string(),
1434 age: 30,
1435 staff: false,
1436 }
1437 );
1438 assert_eq!(
1439 store.get::<MultiKeySettings>(None),
1440 &MultiKeySettings {
1441 key1: String::new(),
1442 key2: String::new(),
1443 }
1444 );
1445
1446 store
1447 .set_user_settings(
1448 r#"{
1449 "turbo": true,
1450 "user": { "age": 31 },
1451 "key1": "a"
1452 }"#,
1453 cx,
1454 )
1455 .unwrap();
1456
1457 assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(true));
1458 assert_eq!(
1459 store.get::<UserSettings>(None),
1460 &UserSettings {
1461 name: "John Doe".to_string(),
1462 age: 31,
1463 staff: false
1464 }
1465 );
1466
1467 store
1468 .set_local_settings(
1469 WorktreeId::from_usize(1),
1470 Path::new("/root1").into(),
1471 LocalSettingsKind::Settings,
1472 Some(r#"{ "user": { "staff": true } }"#),
1473 cx,
1474 )
1475 .unwrap();
1476 store
1477 .set_local_settings(
1478 WorktreeId::from_usize(1),
1479 Path::new("/root1/subdir").into(),
1480 LocalSettingsKind::Settings,
1481 Some(r#"{ "user": { "name": "Jane Doe" } }"#),
1482 cx,
1483 )
1484 .unwrap();
1485
1486 store
1487 .set_local_settings(
1488 WorktreeId::from_usize(1),
1489 Path::new("/root2").into(),
1490 LocalSettingsKind::Settings,
1491 Some(r#"{ "user": { "age": 42 }, "key2": "b" }"#),
1492 cx,
1493 )
1494 .unwrap();
1495
1496 assert_eq!(
1497 store.get::<UserSettings>(Some(SettingsLocation {
1498 worktree_id: WorktreeId::from_usize(1),
1499 path: Path::new("/root1/something"),
1500 })),
1501 &UserSettings {
1502 name: "John Doe".to_string(),
1503 age: 31,
1504 staff: true
1505 }
1506 );
1507 assert_eq!(
1508 store.get::<UserSettings>(Some(SettingsLocation {
1509 worktree_id: WorktreeId::from_usize(1),
1510 path: Path::new("/root1/subdir/something")
1511 })),
1512 &UserSettings {
1513 name: "Jane Doe".to_string(),
1514 age: 31,
1515 staff: true
1516 }
1517 );
1518 assert_eq!(
1519 store.get::<UserSettings>(Some(SettingsLocation {
1520 worktree_id: WorktreeId::from_usize(1),
1521 path: Path::new("/root2/something")
1522 })),
1523 &UserSettings {
1524 name: "John Doe".to_string(),
1525 age: 42,
1526 staff: false
1527 }
1528 );
1529 assert_eq!(
1530 store.get::<MultiKeySettings>(Some(SettingsLocation {
1531 worktree_id: WorktreeId::from_usize(1),
1532 path: Path::new("/root2/something")
1533 })),
1534 &MultiKeySettings {
1535 key1: "a".to_string(),
1536 key2: "b".to_string(),
1537 }
1538 );
1539 }
1540
1541 #[gpui::test]
1542 fn test_setting_store_assign_json_before_register(cx: &mut App) {
1543 let mut store = SettingsStore::new(cx);
1544 store
1545 .set_default_settings(
1546 r#"{
1547 "turbo": true,
1548 "user": {
1549 "name": "John Doe",
1550 "age": 30,
1551 "staff": false
1552 },
1553 "key1": "x"
1554 }"#,
1555 cx,
1556 )
1557 .unwrap();
1558 store
1559 .set_user_settings(r#"{ "turbo": false }"#, cx)
1560 .unwrap();
1561 store.register_setting::<UserSettings>(cx);
1562 store.register_setting::<TurboSetting>(cx);
1563
1564 assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(false));
1565 assert_eq!(
1566 store.get::<UserSettings>(None),
1567 &UserSettings {
1568 name: "John Doe".to_string(),
1569 age: 30,
1570 staff: false,
1571 }
1572 );
1573
1574 store.register_setting::<MultiKeySettings>(cx);
1575 assert_eq!(
1576 store.get::<MultiKeySettings>(None),
1577 &MultiKeySettings {
1578 key1: "x".into(),
1579 key2: String::new(),
1580 }
1581 );
1582 }
1583
1584 fn check_settings_update<T: Settings>(
1585 store: &mut SettingsStore,
1586 old_json: String,
1587 update: fn(&mut T::FileContent),
1588 expected_new_json: String,
1589 cx: &mut App,
1590 ) {
1591 store.set_user_settings(&old_json, cx).ok();
1592 let edits = store.edits_for_update::<T>(&old_json, update);
1593 let mut new_json = old_json;
1594 for (range, replacement) in edits.into_iter() {
1595 new_json.replace_range(range, &replacement);
1596 }
1597 pretty_assertions::assert_eq!(new_json, expected_new_json);
1598 }
1599
1600 #[gpui::test]
1601 fn test_setting_store_update(cx: &mut App) {
1602 let mut store = SettingsStore::new(cx);
1603 store.register_setting::<MultiKeySettings>(cx);
1604 store.register_setting::<UserSettings>(cx);
1605 store.register_setting::<LanguageSettings>(cx);
1606
1607 // entries added and updated
1608 check_settings_update::<LanguageSettings>(
1609 &mut store,
1610 r#"{
1611 "languages": {
1612 "JSON": {
1613 "language_setting_1": true
1614 }
1615 }
1616 }"#
1617 .unindent(),
1618 |settings| {
1619 settings
1620 .languages
1621 .get_mut("JSON")
1622 .unwrap()
1623 .language_setting_1 = Some(false);
1624 settings.languages.insert(
1625 "Rust".into(),
1626 LanguageSettingEntry {
1627 language_setting_2: Some(true),
1628 ..Default::default()
1629 },
1630 );
1631 },
1632 r#"{
1633 "languages": {
1634 "Rust": {
1635 "language_setting_2": true
1636 },
1637 "JSON": {
1638 "language_setting_1": false
1639 }
1640 }
1641 }"#
1642 .unindent(),
1643 cx,
1644 );
1645
1646 // entries removed
1647 check_settings_update::<LanguageSettings>(
1648 &mut store,
1649 r#"{
1650 "languages": {
1651 "Rust": {
1652 "language_setting_2": true
1653 },
1654 "JSON": {
1655 "language_setting_1": false
1656 }
1657 }
1658 }"#
1659 .unindent(),
1660 |settings| {
1661 settings.languages.remove("JSON").unwrap();
1662 },
1663 r#"{
1664 "languages": {
1665 "Rust": {
1666 "language_setting_2": true
1667 }
1668 }
1669 }"#
1670 .unindent(),
1671 cx,
1672 );
1673
1674 check_settings_update::<LanguageSettings>(
1675 &mut store,
1676 r#"{
1677 "languages": {
1678 "Rust": {
1679 "language_setting_2": true
1680 },
1681 "JSON": {
1682 "language_setting_1": false
1683 }
1684 }
1685 }"#
1686 .unindent(),
1687 |settings| {
1688 settings.languages.remove("Rust").unwrap();
1689 },
1690 r#"{
1691 "languages": {
1692 "JSON": {
1693 "language_setting_1": false
1694 }
1695 }
1696 }"#
1697 .unindent(),
1698 cx,
1699 );
1700
1701 // weird formatting
1702 check_settings_update::<UserSettings>(
1703 &mut store,
1704 r#"{
1705 "user": { "age": 36, "name": "Max", "staff": true }
1706 }"#
1707 .unindent(),
1708 |settings| settings.age = Some(37),
1709 r#"{
1710 "user": { "age": 37, "name": "Max", "staff": true }
1711 }"#
1712 .unindent(),
1713 cx,
1714 );
1715
1716 // single-line formatting, other keys
1717 check_settings_update::<MultiKeySettings>(
1718 &mut store,
1719 r#"{ "one": 1, "two": 2 }"#.unindent(),
1720 |settings| settings.key1 = Some("x".into()),
1721 r#"{ "key1": "x", "one": 1, "two": 2 }"#.unindent(),
1722 cx,
1723 );
1724
1725 // empty object
1726 check_settings_update::<UserSettings>(
1727 &mut store,
1728 r#"{
1729 "user": {}
1730 }"#
1731 .unindent(),
1732 |settings| settings.age = Some(37),
1733 r#"{
1734 "user": {
1735 "age": 37
1736 }
1737 }"#
1738 .unindent(),
1739 cx,
1740 );
1741
1742 // no content
1743 check_settings_update::<UserSettings>(
1744 &mut store,
1745 r#""#.unindent(),
1746 |settings| settings.age = Some(37),
1747 r#"{
1748 "user": {
1749 "age": 37
1750 }
1751 }
1752 "#
1753 .unindent(),
1754 cx,
1755 );
1756
1757 check_settings_update::<UserSettings>(
1758 &mut store,
1759 r#"{
1760 }
1761 "#
1762 .unindent(),
1763 |settings| settings.age = Some(37),
1764 r#"{
1765 "user": {
1766 "age": 37
1767 }
1768 }
1769 "#
1770 .unindent(),
1771 cx,
1772 );
1773 }
1774
1775 #[gpui::test]
1776 fn test_vscode_import(cx: &mut App) {
1777 let mut store = SettingsStore::new(cx);
1778 store.register_setting::<UserSettings>(cx);
1779 store.register_setting::<JournalSettings>(cx);
1780 store.register_setting::<LanguageSettings>(cx);
1781 store.register_setting::<MultiKeySettings>(cx);
1782
1783 // create settings that werent present
1784 check_vscode_import(
1785 &mut store,
1786 r#"{
1787 }
1788 "#
1789 .unindent(),
1790 r#" { "user.age": 37 } "#.to_owned(),
1791 r#"{
1792 "user": {
1793 "age": 37
1794 }
1795 }
1796 "#
1797 .unindent(),
1798 cx,
1799 );
1800
1801 // persist settings that were present
1802 check_vscode_import(
1803 &mut store,
1804 r#"{
1805 "user": {
1806 "staff": true,
1807 "age": 37
1808 }
1809 }
1810 "#
1811 .unindent(),
1812 r#"{ "user.age": 42 }"#.to_owned(),
1813 r#"{
1814 "user": {
1815 "staff": true,
1816 "age": 42
1817 }
1818 }
1819 "#
1820 .unindent(),
1821 cx,
1822 );
1823
1824 // don't clobber settings that aren't present in vscode
1825 check_vscode_import(
1826 &mut store,
1827 r#"{
1828 "user": {
1829 "staff": true,
1830 "age": 37
1831 }
1832 }
1833 "#
1834 .unindent(),
1835 r#"{}"#.to_owned(),
1836 r#"{
1837 "user": {
1838 "staff": true,
1839 "age": 37
1840 }
1841 }
1842 "#
1843 .unindent(),
1844 cx,
1845 );
1846
1847 // custom enum
1848 check_vscode_import(
1849 &mut store,
1850 r#"{
1851 "journal": {
1852 "hour_format": "hour12"
1853 }
1854 }
1855 "#
1856 .unindent(),
1857 r#"{ "time_format": "24" }"#.to_owned(),
1858 r#"{
1859 "journal": {
1860 "hour_format": "hour24"
1861 }
1862 }
1863 "#
1864 .unindent(),
1865 cx,
1866 );
1867
1868 // Multiple keys for one setting
1869 check_vscode_import(
1870 &mut store,
1871 r#"{
1872 "key1": "value"
1873 }
1874 "#
1875 .unindent(),
1876 r#"{
1877 "key_1_first": "hello",
1878 "key_1_second": "world"
1879 }"#
1880 .to_owned(),
1881 r#"{
1882 "key1": "hello world"
1883 }
1884 "#
1885 .unindent(),
1886 cx,
1887 );
1888
1889 // Merging lists together entries added and updated
1890 check_vscode_import(
1891 &mut store,
1892 r#"{
1893 "languages": {
1894 "JSON": {
1895 "language_setting_1": true
1896 },
1897 "Rust": {
1898 "language_setting_2": true
1899 }
1900 }
1901 }"#
1902 .unindent(),
1903 r#"{
1904 "vscode_languages": [
1905 {
1906 "name": "JavaScript",
1907 "language_setting_1": true
1908 },
1909 {
1910 "name": "Rust",
1911 "language_setting_2": false
1912 }
1913 ]
1914 }"#
1915 .to_owned(),
1916 r#"{
1917 "languages": {
1918 "JavaScript": {
1919 "language_setting_1": true
1920 },
1921 "JSON": {
1922 "language_setting_1": true
1923 },
1924 "Rust": {
1925 "language_setting_2": false
1926 }
1927 }
1928 }"#
1929 .unindent(),
1930 cx,
1931 );
1932 }
1933
1934 fn check_vscode_import(
1935 store: &mut SettingsStore,
1936 old: String,
1937 vscode: String,
1938 expected: String,
1939 cx: &mut App,
1940 ) {
1941 store.set_user_settings(&old, cx).ok();
1942 let new = store.get_vscode_edits(
1943 old,
1944 &VsCodeSettings::from_str(&vscode, VsCodeSettingsSource::VsCode).unwrap(),
1945 );
1946 pretty_assertions::assert_eq!(new, expected);
1947 }
1948
1949 #[derive(Debug, PartialEq, Deserialize)]
1950 struct UserSettings {
1951 name: String,
1952 age: u32,
1953 staff: bool,
1954 }
1955
1956 #[derive(Default, Clone, Serialize, Deserialize, JsonSchema)]
1957 struct UserSettingsContent {
1958 name: Option<String>,
1959 age: Option<u32>,
1960 staff: Option<bool>,
1961 }
1962
1963 impl Settings for UserSettings {
1964 const KEY: Option<&'static str> = Some("user");
1965 type FileContent = UserSettingsContent;
1966
1967 fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
1968 sources.json_merge()
1969 }
1970
1971 fn import_from_vscode(vscode: &VsCodeSettings, current: &mut Self::FileContent) {
1972 vscode.u32_setting("user.age", &mut current.age);
1973 }
1974 }
1975
1976 #[derive(Debug, Deserialize, PartialEq)]
1977 struct TurboSetting(bool);
1978
1979 impl Settings for TurboSetting {
1980 const KEY: Option<&'static str> = Some("turbo");
1981 type FileContent = Option<bool>;
1982
1983 fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
1984 sources.json_merge()
1985 }
1986
1987 fn import_from_vscode(_vscode: &VsCodeSettings, _current: &mut Self::FileContent) {}
1988 }
1989
1990 #[derive(Clone, Debug, PartialEq, Deserialize)]
1991 struct MultiKeySettings {
1992 #[serde(default)]
1993 key1: String,
1994 #[serde(default)]
1995 key2: String,
1996 }
1997
1998 #[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
1999 struct MultiKeySettingsJson {
2000 key1: Option<String>,
2001 key2: Option<String>,
2002 }
2003
2004 impl Settings for MultiKeySettings {
2005 const KEY: Option<&'static str> = None;
2006
2007 type FileContent = MultiKeySettingsJson;
2008
2009 fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
2010 sources.json_merge()
2011 }
2012
2013 fn import_from_vscode(vscode: &VsCodeSettings, current: &mut Self::FileContent) {
2014 let first_value = vscode.read_string("key_1_first");
2015 let second_value = vscode.read_string("key_1_second");
2016
2017 if let Some((first, second)) = first_value.zip(second_value) {
2018 current.key1 = Some(format!("{} {}", first, second));
2019 }
2020 }
2021 }
2022
2023 #[derive(Debug, Deserialize)]
2024 struct JournalSettings {
2025 pub path: String,
2026 pub hour_format: HourFormat,
2027 }
2028
2029 #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
2030 #[serde(rename_all = "snake_case")]
2031 enum HourFormat {
2032 Hour12,
2033 Hour24,
2034 }
2035
2036 #[derive(Clone, Default, Debug, Serialize, Deserialize, JsonSchema)]
2037 struct JournalSettingsJson {
2038 pub path: Option<String>,
2039 pub hour_format: Option<HourFormat>,
2040 }
2041
2042 impl Settings for JournalSettings {
2043 const KEY: Option<&'static str> = Some("journal");
2044
2045 type FileContent = JournalSettingsJson;
2046
2047 fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
2048 sources.json_merge()
2049 }
2050
2051 fn import_from_vscode(vscode: &VsCodeSettings, current: &mut Self::FileContent) {
2052 vscode.enum_setting("time_format", &mut current.hour_format, |s| match s {
2053 "12" => Some(HourFormat::Hour12),
2054 "24" => Some(HourFormat::Hour24),
2055 _ => None,
2056 });
2057 }
2058 }
2059
2060 #[gpui::test]
2061 fn test_global_settings(cx: &mut App) {
2062 let mut store = SettingsStore::new(cx);
2063 store.register_setting::<UserSettings>(cx);
2064 store
2065 .set_default_settings(
2066 r#"{
2067 "user": {
2068 "name": "John Doe",
2069 "age": 30,
2070 "staff": false
2071 }
2072 }"#,
2073 cx,
2074 )
2075 .unwrap();
2076
2077 // Set global settings - these should override defaults but not user settings
2078 store
2079 .set_global_settings(
2080 r#"{
2081 "user": {
2082 "name": "Global User",
2083 "age": 35,
2084 "staff": true
2085 }
2086 }"#,
2087 cx,
2088 )
2089 .unwrap();
2090
2091 // Before user settings, global settings should apply
2092 assert_eq!(
2093 store.get::<UserSettings>(None),
2094 &UserSettings {
2095 name: "Global User".to_string(),
2096 age: 35,
2097 staff: true,
2098 }
2099 );
2100
2101 // Set user settings - these should override both defaults and global
2102 store
2103 .set_user_settings(
2104 r#"{
2105 "user": {
2106 "age": 40
2107 }
2108 }"#,
2109 cx,
2110 )
2111 .unwrap();
2112
2113 // User settings should override global settings
2114 assert_eq!(
2115 store.get::<UserSettings>(None),
2116 &UserSettings {
2117 name: "Global User".to_string(), // Name from global settings
2118 age: 40, // Age from user settings
2119 staff: true, // Staff from global settings
2120 }
2121 );
2122 }
2123
2124 #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
2125 struct LanguageSettings {
2126 #[serde(default)]
2127 languages: HashMap<String, LanguageSettingEntry>,
2128 }
2129
2130 #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
2131 struct LanguageSettingEntry {
2132 language_setting_1: Option<bool>,
2133 language_setting_2: Option<bool>,
2134 }
2135
2136 impl Settings for LanguageSettings {
2137 const KEY: Option<&'static str> = None;
2138
2139 type FileContent = Self;
2140
2141 fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
2142 sources.json_merge()
2143 }
2144
2145 fn import_from_vscode(vscode: &VsCodeSettings, current: &mut Self::FileContent) {
2146 current.languages.extend(
2147 vscode
2148 .read_value("vscode_languages")
2149 .and_then(|value| value.as_array())
2150 .map(|languages| {
2151 languages
2152 .iter()
2153 .filter_map(|value| value.as_object())
2154 .filter_map(|item| {
2155 let mut rest = item.clone();
2156 let name = rest.remove("name")?.as_str()?.to_string();
2157 let entry = serde_json::from_value::<LanguageSettingEntry>(
2158 serde_json::Value::Object(rest),
2159 )
2160 .ok()?;
2161
2162 Some((name, entry))
2163 })
2164 })
2165 .into_iter()
2166 .flatten(),
2167 );
2168 }
2169 }
2170}