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