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