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.map_or(
1237 false,
1238 |(changed_root_id, changed_local_path)| {
1239 *root_id != changed_root_id
1240 || !directory_path.starts_with(changed_local_path)
1241 },
1242 ) {
1243 continue;
1244 }
1245
1246 if let Some(value) = setting_value
1247 .load_setting(
1248 SettingsSources {
1249 default: &default_settings,
1250 global: global_settings.as_ref(),
1251 extensions: extension_settings.as_ref(),
1252 user: user_settings.as_ref(),
1253 release_channel: release_channel_settings.as_ref(),
1254 operating_system: os_settings.as_ref(),
1255 profile: profile_settings.as_ref(),
1256 server: server_settings.as_ref(),
1257 project: &project_settings_stack.iter().collect::<Vec<_>>(),
1258 },
1259 cx,
1260 )
1261 .log_err()
1262 {
1263 setting_value.set_local_value(*root_id, directory_path.clone(), value);
1264 }
1265 }
1266 Err(error) => {
1267 return Err(InvalidSettingsError::LocalSettings {
1268 path: directory_path.join(local_settings_file_relative_path()),
1269 message: error.to_string(),
1270 });
1271 }
1272 }
1273 }
1274 }
1275 Ok(())
1276 }
1277
1278 pub fn editorconfig_properties(
1279 &self,
1280 for_worktree: WorktreeId,
1281 for_path: &Path,
1282 ) -> Option<EditorconfigProperties> {
1283 let mut properties = EditorconfigProperties::new();
1284
1285 for (directory_with_config, _, parsed_editorconfig) in
1286 self.local_editorconfig_settings(for_worktree)
1287 {
1288 if !for_path.starts_with(&directory_with_config) {
1289 properties.use_fallbacks();
1290 return Some(properties);
1291 }
1292 let parsed_editorconfig = parsed_editorconfig?;
1293 if parsed_editorconfig.is_root {
1294 properties = EditorconfigProperties::new();
1295 }
1296 for section in parsed_editorconfig.sections {
1297 section.apply_to(&mut properties, for_path).log_err()?;
1298 }
1299 }
1300
1301 properties.use_fallbacks();
1302 Some(properties)
1303 }
1304}
1305
1306#[derive(Debug, Clone, PartialEq)]
1307pub enum InvalidSettingsError {
1308 LocalSettings { path: PathBuf, message: String },
1309 UserSettings { message: String },
1310 ServerSettings { message: String },
1311 DefaultSettings { message: String },
1312 Editorconfig { path: PathBuf, message: String },
1313 Tasks { path: PathBuf, message: String },
1314 Debug { path: PathBuf, message: String },
1315}
1316
1317impl std::fmt::Display for InvalidSettingsError {
1318 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1319 match self {
1320 InvalidSettingsError::LocalSettings { message, .. }
1321 | InvalidSettingsError::UserSettings { message }
1322 | InvalidSettingsError::ServerSettings { message }
1323 | InvalidSettingsError::DefaultSettings { message }
1324 | InvalidSettingsError::Tasks { message, .. }
1325 | InvalidSettingsError::Editorconfig { message, .. }
1326 | InvalidSettingsError::Debug { message, .. } => {
1327 write!(f, "{message}")
1328 }
1329 }
1330 }
1331}
1332impl std::error::Error for InvalidSettingsError {}
1333
1334impl Debug for SettingsStore {
1335 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1336 f.debug_struct("SettingsStore")
1337 .field(
1338 "types",
1339 &self
1340 .setting_values
1341 .values()
1342 .map(|value| value.setting_type_name())
1343 .collect::<Vec<_>>(),
1344 )
1345 .field("default_settings", &self.raw_default_settings)
1346 .field("user_settings", &self.raw_user_settings)
1347 .field("local_settings", &self.raw_local_settings)
1348 .finish_non_exhaustive()
1349 }
1350}
1351
1352impl<T: Settings> AnySettingValue for SettingValue<T> {
1353 fn key(&self) -> Option<&'static str> {
1354 T::KEY
1355 }
1356
1357 fn setting_type_name(&self) -> &'static str {
1358 type_name::<T>()
1359 }
1360
1361 fn load_setting(
1362 &self,
1363 values: SettingsSources<DeserializedSetting>,
1364 cx: &mut App,
1365 ) -> Result<Box<dyn Any>> {
1366 Ok(Box::new(T::load(
1367 SettingsSources {
1368 default: values.default.0.downcast_ref::<T::FileContent>().unwrap(),
1369 global: values
1370 .global
1371 .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
1372 extensions: values
1373 .extensions
1374 .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
1375 user: values
1376 .user
1377 .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
1378 release_channel: values
1379 .release_channel
1380 .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
1381 operating_system: values
1382 .operating_system
1383 .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
1384 profile: values
1385 .profile
1386 .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
1387 server: values
1388 .server
1389 .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
1390 project: values
1391 .project
1392 .iter()
1393 .map(|value| value.0.downcast_ref().unwrap())
1394 .collect::<SmallVec<[_; 3]>>()
1395 .as_slice(),
1396 },
1397 cx,
1398 )?))
1399 }
1400
1401 fn deserialize_setting_with_key(
1402 &self,
1403 mut json: &Value,
1404 ) -> (Option<&'static str>, Result<DeserializedSetting>) {
1405 let mut key = None;
1406 if let Some(k) = T::KEY {
1407 if let Some(value) = json.get(k) {
1408 json = value;
1409 key = Some(k);
1410 } else if let Some((k, value)) = T::FALLBACK_KEY.and_then(|k| Some((k, json.get(k)?))) {
1411 json = value;
1412 key = Some(k);
1413 } else {
1414 let value = T::FileContent::default();
1415 return (T::KEY, Ok(DeserializedSetting(Box::new(value))));
1416 }
1417 }
1418 let value = T::FileContent::deserialize(json)
1419 .map(|value| DeserializedSetting(Box::new(value)))
1420 .map_err(anyhow::Error::from);
1421 (key, value)
1422 }
1423
1424 fn all_local_values(&self) -> Vec<(WorktreeId, Arc<Path>, &dyn Any)> {
1425 self.local_values
1426 .iter()
1427 .map(|(id, path, value)| (*id, path.clone(), value as _))
1428 .collect()
1429 }
1430
1431 fn value_for_path(&self, path: Option<SettingsLocation>) -> &dyn Any {
1432 if let Some(SettingsLocation { worktree_id, path }) = path {
1433 for (settings_root_id, settings_path, value) in self.local_values.iter().rev() {
1434 if worktree_id == *settings_root_id && path.starts_with(settings_path) {
1435 return value;
1436 }
1437 }
1438 }
1439 self.global_value
1440 .as_ref()
1441 .unwrap_or_else(|| panic!("no default value for setting {}", self.setting_type_name()))
1442 }
1443
1444 fn set_global_value(&mut self, value: Box<dyn Any>) {
1445 self.global_value = Some(*value.downcast().unwrap());
1446 }
1447
1448 fn set_local_value(&mut self, root_id: WorktreeId, path: Arc<Path>, value: Box<dyn Any>) {
1449 let value = *value.downcast().unwrap();
1450 match self
1451 .local_values
1452 .binary_search_by_key(&(root_id, &path), |e| (e.0, &e.1))
1453 {
1454 Ok(ix) => self.local_values[ix].2 = value,
1455 Err(ix) => self.local_values.insert(ix, (root_id, path, value)),
1456 }
1457 }
1458
1459 fn json_schema(&self, generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
1460 T::FileContent::json_schema(generator)
1461 }
1462
1463 fn edits_for_update(
1464 &self,
1465 raw_settings: &serde_json::Value,
1466 tab_size: usize,
1467 vscode_settings: &VsCodeSettings,
1468 text: &mut String,
1469 edits: &mut Vec<(Range<usize>, String)>,
1470 ) {
1471 let (key, deserialized_setting) = self.deserialize_setting_with_key(raw_settings);
1472 let old_content = match deserialized_setting {
1473 Ok(content) => content.0.downcast::<T::FileContent>().unwrap(),
1474 Err(_) => Box::<<T as Settings>::FileContent>::default(),
1475 };
1476 let mut new_content = old_content.clone();
1477 T::import_from_vscode(vscode_settings, &mut new_content);
1478
1479 let old_value = serde_json::to_value(&old_content).unwrap();
1480 let new_value = serde_json::to_value(new_content).unwrap();
1481
1482 let mut key_path = Vec::new();
1483 if let Some(key) = key {
1484 key_path.push(key);
1485 }
1486
1487 update_value_in_json_text(
1488 text,
1489 &mut key_path,
1490 tab_size,
1491 &old_value,
1492 &new_value,
1493 T::PRESERVED_KEYS.unwrap_or_default(),
1494 edits,
1495 );
1496 }
1497}
1498
1499#[cfg(test)]
1500mod tests {
1501 use crate::VsCodeSettingsSource;
1502
1503 use super::*;
1504 use serde_derive::Deserialize;
1505 use unindent::Unindent;
1506
1507 #[gpui::test]
1508 fn test_settings_store_basic(cx: &mut App) {
1509 let mut store = SettingsStore::new(cx);
1510 store.register_setting::<UserSettings>(cx);
1511 store.register_setting::<TurboSetting>(cx);
1512 store.register_setting::<MultiKeySettings>(cx);
1513 store
1514 .set_default_settings(
1515 r#"{
1516 "turbo": false,
1517 "user": {
1518 "name": "John Doe",
1519 "age": 30,
1520 "staff": false
1521 }
1522 }"#,
1523 cx,
1524 )
1525 .unwrap();
1526
1527 assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(false));
1528 assert_eq!(
1529 store.get::<UserSettings>(None),
1530 &UserSettings {
1531 name: "John Doe".to_string(),
1532 age: 30,
1533 staff: false,
1534 }
1535 );
1536 assert_eq!(
1537 store.get::<MultiKeySettings>(None),
1538 &MultiKeySettings {
1539 key1: String::new(),
1540 key2: String::new(),
1541 }
1542 );
1543
1544 store
1545 .set_user_settings(
1546 r#"{
1547 "turbo": true,
1548 "user": { "age": 31 },
1549 "key1": "a"
1550 }"#,
1551 cx,
1552 )
1553 .unwrap();
1554
1555 assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(true));
1556 assert_eq!(
1557 store.get::<UserSettings>(None),
1558 &UserSettings {
1559 name: "John Doe".to_string(),
1560 age: 31,
1561 staff: false
1562 }
1563 );
1564
1565 store
1566 .set_local_settings(
1567 WorktreeId::from_usize(1),
1568 Path::new("/root1").into(),
1569 LocalSettingsKind::Settings,
1570 Some(r#"{ "user": { "staff": true } }"#),
1571 cx,
1572 )
1573 .unwrap();
1574 store
1575 .set_local_settings(
1576 WorktreeId::from_usize(1),
1577 Path::new("/root1/subdir").into(),
1578 LocalSettingsKind::Settings,
1579 Some(r#"{ "user": { "name": "Jane Doe" } }"#),
1580 cx,
1581 )
1582 .unwrap();
1583
1584 store
1585 .set_local_settings(
1586 WorktreeId::from_usize(1),
1587 Path::new("/root2").into(),
1588 LocalSettingsKind::Settings,
1589 Some(r#"{ "user": { "age": 42 }, "key2": "b" }"#),
1590 cx,
1591 )
1592 .unwrap();
1593
1594 assert_eq!(
1595 store.get::<UserSettings>(Some(SettingsLocation {
1596 worktree_id: WorktreeId::from_usize(1),
1597 path: Path::new("/root1/something"),
1598 })),
1599 &UserSettings {
1600 name: "John Doe".to_string(),
1601 age: 31,
1602 staff: true
1603 }
1604 );
1605 assert_eq!(
1606 store.get::<UserSettings>(Some(SettingsLocation {
1607 worktree_id: WorktreeId::from_usize(1),
1608 path: Path::new("/root1/subdir/something")
1609 })),
1610 &UserSettings {
1611 name: "Jane Doe".to_string(),
1612 age: 31,
1613 staff: true
1614 }
1615 );
1616 assert_eq!(
1617 store.get::<UserSettings>(Some(SettingsLocation {
1618 worktree_id: WorktreeId::from_usize(1),
1619 path: Path::new("/root2/something")
1620 })),
1621 &UserSettings {
1622 name: "John Doe".to_string(),
1623 age: 42,
1624 staff: false
1625 }
1626 );
1627 assert_eq!(
1628 store.get::<MultiKeySettings>(Some(SettingsLocation {
1629 worktree_id: WorktreeId::from_usize(1),
1630 path: Path::new("/root2/something")
1631 })),
1632 &MultiKeySettings {
1633 key1: "a".to_string(),
1634 key2: "b".to_string(),
1635 }
1636 );
1637 }
1638
1639 #[gpui::test]
1640 fn test_setting_store_assign_json_before_register(cx: &mut App) {
1641 let mut store = SettingsStore::new(cx);
1642 store
1643 .set_default_settings(
1644 r#"{
1645 "turbo": true,
1646 "user": {
1647 "name": "John Doe",
1648 "age": 30,
1649 "staff": false
1650 },
1651 "key1": "x"
1652 }"#,
1653 cx,
1654 )
1655 .unwrap();
1656 store
1657 .set_user_settings(r#"{ "turbo": false }"#, cx)
1658 .unwrap();
1659 store.register_setting::<UserSettings>(cx);
1660 store.register_setting::<TurboSetting>(cx);
1661
1662 assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(false));
1663 assert_eq!(
1664 store.get::<UserSettings>(None),
1665 &UserSettings {
1666 name: "John Doe".to_string(),
1667 age: 30,
1668 staff: false,
1669 }
1670 );
1671
1672 store.register_setting::<MultiKeySettings>(cx);
1673 assert_eq!(
1674 store.get::<MultiKeySettings>(None),
1675 &MultiKeySettings {
1676 key1: "x".into(),
1677 key2: String::new(),
1678 }
1679 );
1680 }
1681
1682 fn check_settings_update<T: Settings>(
1683 store: &mut SettingsStore,
1684 old_json: String,
1685 update: fn(&mut T::FileContent),
1686 expected_new_json: String,
1687 cx: &mut App,
1688 ) {
1689 store.set_user_settings(&old_json, cx).ok();
1690 let edits = store.edits_for_update::<T>(&old_json, update);
1691 let mut new_json = old_json;
1692 for (range, replacement) in edits.into_iter() {
1693 new_json.replace_range(range, &replacement);
1694 }
1695 pretty_assertions::assert_eq!(new_json, expected_new_json);
1696 }
1697
1698 #[gpui::test]
1699 fn test_setting_store_update(cx: &mut App) {
1700 let mut store = SettingsStore::new(cx);
1701 store.register_setting::<MultiKeySettings>(cx);
1702 store.register_setting::<UserSettings>(cx);
1703 store.register_setting::<LanguageSettings>(cx);
1704
1705 // entries added and updated
1706 check_settings_update::<LanguageSettings>(
1707 &mut store,
1708 r#"{
1709 "languages": {
1710 "JSON": {
1711 "language_setting_1": true
1712 }
1713 }
1714 }"#
1715 .unindent(),
1716 |settings| {
1717 settings
1718 .languages
1719 .get_mut("JSON")
1720 .unwrap()
1721 .language_setting_1 = Some(false);
1722 settings.languages.insert(
1723 "Rust".into(),
1724 LanguageSettingEntry {
1725 language_setting_2: Some(true),
1726 ..Default::default()
1727 },
1728 );
1729 },
1730 r#"{
1731 "languages": {
1732 "Rust": {
1733 "language_setting_2": true
1734 },
1735 "JSON": {
1736 "language_setting_1": false
1737 }
1738 }
1739 }"#
1740 .unindent(),
1741 cx,
1742 );
1743
1744 // entries removed
1745 check_settings_update::<LanguageSettings>(
1746 &mut store,
1747 r#"{
1748 "languages": {
1749 "Rust": {
1750 "language_setting_2": true
1751 },
1752 "JSON": {
1753 "language_setting_1": false
1754 }
1755 }
1756 }"#
1757 .unindent(),
1758 |settings| {
1759 settings.languages.remove("JSON").unwrap();
1760 },
1761 r#"{
1762 "languages": {
1763 "Rust": {
1764 "language_setting_2": true
1765 }
1766 }
1767 }"#
1768 .unindent(),
1769 cx,
1770 );
1771
1772 check_settings_update::<LanguageSettings>(
1773 &mut store,
1774 r#"{
1775 "languages": {
1776 "Rust": {
1777 "language_setting_2": true
1778 },
1779 "JSON": {
1780 "language_setting_1": false
1781 }
1782 }
1783 }"#
1784 .unindent(),
1785 |settings| {
1786 settings.languages.remove("Rust").unwrap();
1787 },
1788 r#"{
1789 "languages": {
1790 "JSON": {
1791 "language_setting_1": false
1792 }
1793 }
1794 }"#
1795 .unindent(),
1796 cx,
1797 );
1798
1799 // weird formatting
1800 check_settings_update::<UserSettings>(
1801 &mut store,
1802 r#"{
1803 "user": { "age": 36, "name": "Max", "staff": true }
1804 }"#
1805 .unindent(),
1806 |settings| settings.age = Some(37),
1807 r#"{
1808 "user": { "age": 37, "name": "Max", "staff": true }
1809 }"#
1810 .unindent(),
1811 cx,
1812 );
1813
1814 // single-line formatting, other keys
1815 check_settings_update::<MultiKeySettings>(
1816 &mut store,
1817 r#"{ "one": 1, "two": 2 }"#.unindent(),
1818 |settings| settings.key1 = Some("x".into()),
1819 r#"{ "key1": "x", "one": 1, "two": 2 }"#.unindent(),
1820 cx,
1821 );
1822
1823 // empty object
1824 check_settings_update::<UserSettings>(
1825 &mut store,
1826 r#"{
1827 "user": {}
1828 }"#
1829 .unindent(),
1830 |settings| settings.age = Some(37),
1831 r#"{
1832 "user": {
1833 "age": 37
1834 }
1835 }"#
1836 .unindent(),
1837 cx,
1838 );
1839
1840 // no content
1841 check_settings_update::<UserSettings>(
1842 &mut store,
1843 r#""#.unindent(),
1844 |settings| settings.age = Some(37),
1845 r#"{
1846 "user": {
1847 "age": 37
1848 }
1849 }
1850 "#
1851 .unindent(),
1852 cx,
1853 );
1854
1855 check_settings_update::<UserSettings>(
1856 &mut store,
1857 r#"{
1858 }
1859 "#
1860 .unindent(),
1861 |settings| settings.age = Some(37),
1862 r#"{
1863 "user": {
1864 "age": 37
1865 }
1866 }
1867 "#
1868 .unindent(),
1869 cx,
1870 );
1871 }
1872
1873 #[gpui::test]
1874 fn test_vscode_import(cx: &mut App) {
1875 let mut store = SettingsStore::new(cx);
1876 store.register_setting::<UserSettings>(cx);
1877 store.register_setting::<JournalSettings>(cx);
1878 store.register_setting::<LanguageSettings>(cx);
1879 store.register_setting::<MultiKeySettings>(cx);
1880
1881 // create settings that werent present
1882 check_vscode_import(
1883 &mut store,
1884 r#"{
1885 }
1886 "#
1887 .unindent(),
1888 r#" { "user.age": 37 } "#.to_owned(),
1889 r#"{
1890 "user": {
1891 "age": 37
1892 }
1893 }
1894 "#
1895 .unindent(),
1896 cx,
1897 );
1898
1899 // persist settings that were present
1900 check_vscode_import(
1901 &mut store,
1902 r#"{
1903 "user": {
1904 "staff": true,
1905 "age": 37
1906 }
1907 }
1908 "#
1909 .unindent(),
1910 r#"{ "user.age": 42 }"#.to_owned(),
1911 r#"{
1912 "user": {
1913 "staff": true,
1914 "age": 42
1915 }
1916 }
1917 "#
1918 .unindent(),
1919 cx,
1920 );
1921
1922 // don't clobber settings that aren't present in vscode
1923 check_vscode_import(
1924 &mut store,
1925 r#"{
1926 "user": {
1927 "staff": true,
1928 "age": 37
1929 }
1930 }
1931 "#
1932 .unindent(),
1933 r#"{}"#.to_owned(),
1934 r#"{
1935 "user": {
1936 "staff": true,
1937 "age": 37
1938 }
1939 }
1940 "#
1941 .unindent(),
1942 cx,
1943 );
1944
1945 // custom enum
1946 check_vscode_import(
1947 &mut store,
1948 r#"{
1949 "journal": {
1950 "hour_format": "hour12"
1951 }
1952 }
1953 "#
1954 .unindent(),
1955 r#"{ "time_format": "24" }"#.to_owned(),
1956 r#"{
1957 "journal": {
1958 "hour_format": "hour24"
1959 }
1960 }
1961 "#
1962 .unindent(),
1963 cx,
1964 );
1965
1966 // Multiple keys for one setting
1967 check_vscode_import(
1968 &mut store,
1969 r#"{
1970 "key1": "value"
1971 }
1972 "#
1973 .unindent(),
1974 r#"{
1975 "key_1_first": "hello",
1976 "key_1_second": "world"
1977 }"#
1978 .to_owned(),
1979 r#"{
1980 "key1": "hello world"
1981 }
1982 "#
1983 .unindent(),
1984 cx,
1985 );
1986
1987 // Merging lists together entries added and updated
1988 check_vscode_import(
1989 &mut store,
1990 r#"{
1991 "languages": {
1992 "JSON": {
1993 "language_setting_1": true
1994 },
1995 "Rust": {
1996 "language_setting_2": true
1997 }
1998 }
1999 }"#
2000 .unindent(),
2001 r#"{
2002 "vscode_languages": [
2003 {
2004 "name": "JavaScript",
2005 "language_setting_1": true
2006 },
2007 {
2008 "name": "Rust",
2009 "language_setting_2": false
2010 }
2011 ]
2012 }"#
2013 .to_owned(),
2014 r#"{
2015 "languages": {
2016 "JavaScript": {
2017 "language_setting_1": true
2018 },
2019 "JSON": {
2020 "language_setting_1": true
2021 },
2022 "Rust": {
2023 "language_setting_2": false
2024 }
2025 }
2026 }"#
2027 .unindent(),
2028 cx,
2029 );
2030 }
2031
2032 fn check_vscode_import(
2033 store: &mut SettingsStore,
2034 old: String,
2035 vscode: String,
2036 expected: String,
2037 cx: &mut App,
2038 ) {
2039 store.set_user_settings(&old, cx).ok();
2040 let new = store.get_vscode_edits(
2041 old,
2042 &VsCodeSettings::from_str(&vscode, VsCodeSettingsSource::VsCode).unwrap(),
2043 );
2044 pretty_assertions::assert_eq!(new, expected);
2045 }
2046
2047 #[derive(Debug, PartialEq, Deserialize)]
2048 struct UserSettings {
2049 name: String,
2050 age: u32,
2051 staff: bool,
2052 }
2053
2054 #[derive(Default, Clone, Serialize, Deserialize, JsonSchema)]
2055 struct UserSettingsContent {
2056 name: Option<String>,
2057 age: Option<u32>,
2058 staff: Option<bool>,
2059 }
2060
2061 impl Settings for UserSettings {
2062 const KEY: Option<&'static str> = Some("user");
2063 type FileContent = UserSettingsContent;
2064
2065 fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
2066 sources.json_merge()
2067 }
2068
2069 fn import_from_vscode(vscode: &VsCodeSettings, current: &mut Self::FileContent) {
2070 vscode.u32_setting("user.age", &mut current.age);
2071 }
2072 }
2073
2074 #[derive(Debug, Deserialize, PartialEq)]
2075 struct TurboSetting(bool);
2076
2077 impl Settings for TurboSetting {
2078 const KEY: Option<&'static str> = Some("turbo");
2079 type FileContent = Option<bool>;
2080
2081 fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
2082 sources.json_merge()
2083 }
2084
2085 fn import_from_vscode(_vscode: &VsCodeSettings, _current: &mut Self::FileContent) {}
2086 }
2087
2088 #[derive(Clone, Debug, PartialEq, Deserialize)]
2089 struct MultiKeySettings {
2090 #[serde(default)]
2091 key1: String,
2092 #[serde(default)]
2093 key2: String,
2094 }
2095
2096 #[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
2097 struct MultiKeySettingsJson {
2098 key1: Option<String>,
2099 key2: Option<String>,
2100 }
2101
2102 impl Settings for MultiKeySettings {
2103 const KEY: Option<&'static str> = None;
2104
2105 type FileContent = MultiKeySettingsJson;
2106
2107 fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
2108 sources.json_merge()
2109 }
2110
2111 fn import_from_vscode(vscode: &VsCodeSettings, current: &mut Self::FileContent) {
2112 let first_value = vscode.read_string("key_1_first");
2113 let second_value = vscode.read_string("key_1_second");
2114
2115 if let Some((first, second)) = first_value.zip(second_value) {
2116 current.key1 = Some(format!("{} {}", first, second));
2117 }
2118 }
2119 }
2120
2121 #[derive(Debug, Deserialize)]
2122 struct JournalSettings {
2123 pub path: String,
2124 pub hour_format: HourFormat,
2125 }
2126
2127 #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
2128 #[serde(rename_all = "snake_case")]
2129 enum HourFormat {
2130 Hour12,
2131 Hour24,
2132 }
2133
2134 #[derive(Clone, Default, Debug, Serialize, Deserialize, JsonSchema)]
2135 struct JournalSettingsJson {
2136 pub path: Option<String>,
2137 pub hour_format: Option<HourFormat>,
2138 }
2139
2140 impl Settings for JournalSettings {
2141 const KEY: Option<&'static str> = Some("journal");
2142
2143 type FileContent = JournalSettingsJson;
2144
2145 fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
2146 sources.json_merge()
2147 }
2148
2149 fn import_from_vscode(vscode: &VsCodeSettings, current: &mut Self::FileContent) {
2150 vscode.enum_setting("time_format", &mut current.hour_format, |s| match s {
2151 "12" => Some(HourFormat::Hour12),
2152 "24" => Some(HourFormat::Hour24),
2153 _ => None,
2154 });
2155 }
2156 }
2157
2158 #[gpui::test]
2159 fn test_global_settings(cx: &mut App) {
2160 let mut store = SettingsStore::new(cx);
2161 store.register_setting::<UserSettings>(cx);
2162 store
2163 .set_default_settings(
2164 r#"{
2165 "user": {
2166 "name": "John Doe",
2167 "age": 30,
2168 "staff": false
2169 }
2170 }"#,
2171 cx,
2172 )
2173 .unwrap();
2174
2175 // Set global settings - these should override defaults but not user settings
2176 store
2177 .set_global_settings(
2178 r#"{
2179 "user": {
2180 "name": "Global User",
2181 "age": 35,
2182 "staff": true
2183 }
2184 }"#,
2185 cx,
2186 )
2187 .unwrap();
2188
2189 // Before user settings, global settings should apply
2190 assert_eq!(
2191 store.get::<UserSettings>(None),
2192 &UserSettings {
2193 name: "Global User".to_string(),
2194 age: 35,
2195 staff: true,
2196 }
2197 );
2198
2199 // Set user settings - these should override both defaults and global
2200 store
2201 .set_user_settings(
2202 r#"{
2203 "user": {
2204 "age": 40
2205 }
2206 }"#,
2207 cx,
2208 )
2209 .unwrap();
2210
2211 // User settings should override global settings
2212 assert_eq!(
2213 store.get::<UserSettings>(None),
2214 &UserSettings {
2215 name: "Global User".to_string(), // Name from global settings
2216 age: 40, // Age from user settings
2217 staff: true, // Staff from global settings
2218 }
2219 );
2220 }
2221
2222 #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
2223 struct LanguageSettings {
2224 #[serde(default)]
2225 languages: HashMap<String, LanguageSettingEntry>,
2226 }
2227
2228 #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
2229 struct LanguageSettingEntry {
2230 language_setting_1: Option<bool>,
2231 language_setting_2: Option<bool>,
2232 }
2233
2234 impl Settings for LanguageSettings {
2235 const KEY: Option<&'static str> = None;
2236
2237 type FileContent = Self;
2238
2239 fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
2240 sources.json_merge()
2241 }
2242
2243 fn import_from_vscode(vscode: &VsCodeSettings, current: &mut Self::FileContent) {
2244 current.languages.extend(
2245 vscode
2246 .read_value("vscode_languages")
2247 .and_then(|value| value.as_array())
2248 .map(|languages| {
2249 languages
2250 .iter()
2251 .filter_map(|value| value.as_object())
2252 .filter_map(|item| {
2253 let mut rest = item.clone();
2254 let name = rest.remove("name")?.as_str()?.to_string();
2255 let entry = serde_json::from_value::<LanguageSettingEntry>(
2256 serde_json::Value::Object(rest),
2257 )
2258 .ok()?;
2259
2260 Some((name, entry))
2261 })
2262 })
2263 .into_iter()
2264 .flatten(),
2265 );
2266 }
2267 }
2268}