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