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, json_schema};
14use serde_json::Value;
15use smallvec::SmallVec;
16use std::{
17 any::{Any, TypeId, type_name},
18 fmt::Debug,
19 ops::Range,
20 path::PathBuf,
21 rc::Rc,
22 str::{self, FromStr},
23 sync::Arc,
24};
25use util::{
26 ResultExt as _,
27 rel_path::RelPath,
28 schemars::{DefaultDenyUnknownFields, replace_subschema},
29};
30
31pub type EditorconfigProperties = ec4rs::Properties;
32
33use crate::{
34 ActiveSettingsProfileName, FontFamilyName, IconThemeName, LanguageSettingsContent,
35 LanguageToSettingsMap, SettingsJsonSchemaParams, ThemeName, VsCodeSettings, WorktreeId,
36 merge_from::MergeFrom,
37 parse_json_with_comments,
38 settings_content::{
39 ExtensionsSettingsContent, ProjectSettingsContent, SettingsContent, UserSettingsContent,
40 },
41 update_value_in_json_text,
42};
43
44pub trait SettingsKey: 'static + Send + Sync {
45 /// The name of a key within the JSON file from which this setting should
46 /// be deserialized. If this is `None`, then the setting will be deserialized
47 /// from the root object.
48 const KEY: Option<&'static str>;
49
50 const FALLBACK_KEY: Option<&'static str> = None;
51}
52
53/// A value that can be defined as a user setting.
54///
55/// Settings can be loaded from a combination of multiple JSON files.
56pub trait Settings: 'static + Send + Sync + Sized {
57 /// The name of the keys in the [`FileContent`](Self::FileContent) that should
58 /// always be written to a settings file, even if their value matches the default
59 /// value.
60 ///
61 /// This is useful for tagged [`FileContent`](Self::FileContent)s where the tag
62 /// is a "version" field that should always be persisted, even if the current
63 /// user settings match the current version of the settings.
64 const PRESERVED_KEYS: Option<&'static [&'static str]> = None;
65
66 /// Read the value from default.json.
67 ///
68 /// This function *should* panic if default values are missing,
69 /// and you should add a default to default.json for documentation.
70 fn from_settings(content: &SettingsContent, cx: &mut App) -> Self;
71
72 fn missing_default() -> anyhow::Error {
73 anyhow::anyhow!("missing default for: {}", std::any::type_name::<Self>())
74 }
75
76 /// Use [the helpers in the vscode_import module](crate::vscode_import) to apply known
77 /// equivalent settings from a vscode config to our config
78 fn import_from_vscode(_vscode: &VsCodeSettings, _current: &mut SettingsContent) {}
79
80 #[track_caller]
81 fn register(cx: &mut App)
82 where
83 Self: Sized,
84 {
85 SettingsStore::update_global(cx, |store, cx| {
86 store.register_setting::<Self>(cx);
87 });
88 }
89
90 #[track_caller]
91 fn get<'a>(path: Option<SettingsLocation>, cx: &'a App) -> &'a Self
92 where
93 Self: Sized,
94 {
95 cx.global::<SettingsStore>().get(path)
96 }
97
98 #[track_caller]
99 fn get_global(cx: &App) -> &Self
100 where
101 Self: Sized,
102 {
103 cx.global::<SettingsStore>().get(None)
104 }
105
106 #[track_caller]
107 fn try_get(cx: &App) -> Option<&Self>
108 where
109 Self: Sized,
110 {
111 if cx.has_global::<SettingsStore>() {
112 cx.global::<SettingsStore>().try_get(None)
113 } else {
114 None
115 }
116 }
117
118 #[track_caller]
119 fn try_read_global<R>(cx: &AsyncApp, f: impl FnOnce(&Self) -> R) -> Option<R>
120 where
121 Self: Sized,
122 {
123 cx.try_read_global(|s: &SettingsStore, _| f(s.get(None)))
124 }
125
126 #[track_caller]
127 fn override_global(settings: Self, cx: &mut App)
128 where
129 Self: Sized,
130 {
131 cx.global_mut::<SettingsStore>().override_global(settings)
132 }
133}
134
135#[derive(Clone, Copy, Debug)]
136pub struct SettingsLocation<'a> {
137 pub worktree_id: WorktreeId,
138 pub path: &'a RelPath,
139}
140
141pub struct SettingsStore {
142 setting_values: HashMap<TypeId, Box<dyn AnySettingValue>>,
143 default_settings: Rc<SettingsContent>,
144 user_settings: Option<UserSettingsContent>,
145 global_settings: Option<Box<SettingsContent>>,
146
147 extension_settings: Option<Box<SettingsContent>>,
148 server_settings: Option<Box<SettingsContent>>,
149
150 merged_settings: Rc<SettingsContent>,
151
152 local_settings: BTreeMap<(WorktreeId, Arc<RelPath>), SettingsContent>,
153 raw_editorconfig_settings: BTreeMap<(WorktreeId, Arc<RelPath>), (String, Option<Editorconfig>)>,
154
155 _setting_file_updates: Task<()>,
156 setting_file_updates_tx:
157 mpsc::UnboundedSender<Box<dyn FnOnce(AsyncApp) -> LocalBoxFuture<'static, Result<()>>>>,
158}
159
160#[derive(Clone, PartialEq)]
161pub enum SettingsFile {
162 User,
163 Global,
164 Extension,
165 Server,
166 Default,
167 Local((WorktreeId, Arc<RelPath>)),
168}
169
170#[derive(Clone)]
171pub struct Editorconfig {
172 pub is_root: bool,
173 pub sections: SmallVec<[Section; 5]>,
174}
175
176impl FromStr for Editorconfig {
177 type Err = anyhow::Error;
178
179 fn from_str(contents: &str) -> Result<Self, Self::Err> {
180 let parser = ConfigParser::new_buffered(contents.as_bytes())
181 .context("creating editorconfig parser")?;
182 let is_root = parser.is_root;
183 let sections = parser
184 .collect::<Result<SmallVec<_>, _>>()
185 .context("parsing editorconfig sections")?;
186 Ok(Self { is_root, sections })
187 }
188}
189
190#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
191pub enum LocalSettingsKind {
192 Settings,
193 Tasks,
194 Editorconfig,
195 Debug,
196}
197
198impl Global for SettingsStore {}
199
200#[derive(Debug)]
201struct SettingValue<T> {
202 global_value: Option<T>,
203 local_values: Vec<(WorktreeId, Arc<RelPath>, T)>,
204}
205
206trait AnySettingValue: 'static + Send + Sync {
207 fn setting_type_name(&self) -> &'static str;
208
209 fn from_settings(&self, s: &SettingsContent, cx: &mut App) -> Box<dyn Any>;
210
211 fn value_for_path(&self, path: Option<SettingsLocation>) -> &dyn Any;
212 fn all_local_values(&self) -> Vec<(WorktreeId, Arc<RelPath>, &dyn Any)>;
213 fn set_global_value(&mut self, value: Box<dyn Any>);
214 fn set_local_value(&mut self, root_id: WorktreeId, path: Arc<RelPath>, value: Box<dyn Any>);
215 fn import_from_vscode(
216 &self,
217 vscode_settings: &VsCodeSettings,
218 settings_content: &mut SettingsContent,
219 );
220}
221
222impl SettingsStore {
223 pub fn new(cx: &App, default_settings: &str) -> Self {
224 let (setting_file_updates_tx, mut setting_file_updates_rx) = mpsc::unbounded();
225 let default_settings: Rc<SettingsContent> =
226 parse_json_with_comments(default_settings).unwrap();
227 Self {
228 setting_values: Default::default(),
229 default_settings: default_settings.clone(),
230 global_settings: None,
231 server_settings: None,
232 user_settings: None,
233 extension_settings: None,
234
235 merged_settings: default_settings,
236 local_settings: BTreeMap::default(),
237 raw_editorconfig_settings: BTreeMap::default(),
238 setting_file_updates_tx,
239 _setting_file_updates: cx.spawn(async move |cx| {
240 while let Some(setting_file_update) = setting_file_updates_rx.next().await {
241 (setting_file_update)(cx.clone()).await.log_err();
242 }
243 }),
244 }
245 }
246
247 pub fn observe_active_settings_profile_name(cx: &mut App) -> gpui::Subscription {
248 cx.observe_global::<ActiveSettingsProfileName>(|cx| {
249 Self::update_global(cx, |store, cx| {
250 store.recompute_values(None, cx).log_err();
251 });
252 })
253 }
254
255 pub fn update<C, R>(cx: &mut C, f: impl FnOnce(&mut Self, &mut C) -> R) -> R
256 where
257 C: BorrowAppContext,
258 {
259 cx.update_global(f)
260 }
261
262 /// Add a new type of setting to the store.
263 pub fn register_setting<T: Settings>(&mut self, cx: &mut App) {
264 let setting_type_id = TypeId::of::<T>();
265 let entry = self.setting_values.entry(setting_type_id);
266
267 if matches!(entry, hash_map::Entry::Occupied(_)) {
268 return;
269 }
270
271 let setting_value = entry.or_insert(Box::new(SettingValue::<T> {
272 global_value: None,
273 local_values: Vec::new(),
274 }));
275 let value = T::from_settings(&self.merged_settings, cx);
276 setting_value.set_global_value(Box::new(value));
277 }
278
279 /// Get the value of a setting.
280 ///
281 /// Panics if the given setting type has not been registered, or if there is no
282 /// value for this setting.
283 pub fn get<T: Settings>(&self, path: Option<SettingsLocation>) -> &T {
284 self.setting_values
285 .get(&TypeId::of::<T>())
286 .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()))
287 .value_for_path(path)
288 .downcast_ref::<T>()
289 .expect("no default value for setting type")
290 }
291
292 /// Get the value of a setting.
293 ///
294 /// Does not panic
295 pub fn try_get<T: Settings>(&self, path: Option<SettingsLocation>) -> Option<&T> {
296 self.setting_values
297 .get(&TypeId::of::<T>())
298 .map(|value| value.value_for_path(path))
299 .and_then(|value| value.downcast_ref::<T>())
300 }
301
302 /// Get all values from project specific settings
303 pub fn get_all_locals<T: Settings>(&self) -> Vec<(WorktreeId, Arc<RelPath>, &T)> {
304 self.setting_values
305 .get(&TypeId::of::<T>())
306 .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()))
307 .all_local_values()
308 .into_iter()
309 .map(|(id, path, any)| {
310 (
311 id,
312 path,
313 any.downcast_ref::<T>()
314 .expect("wrong value type for setting"),
315 )
316 })
317 .collect()
318 }
319
320 /// Override the global value for a setting.
321 ///
322 /// The given value will be overwritten if the user settings file changes.
323 pub fn override_global<T: Settings>(&mut self, value: T) {
324 self.setting_values
325 .get_mut(&TypeId::of::<T>())
326 .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()))
327 .set_global_value(Box::new(value))
328 }
329
330 /// Get the user's settings content.
331 ///
332 /// For user-facing functionality use the typed setting interface.
333 /// (e.g. ProjectSettings::get_global(cx))
334 pub fn raw_user_settings(&self) -> Option<&UserSettingsContent> {
335 self.user_settings.as_ref()
336 }
337
338 /// Get the default settings content as a raw JSON value.
339 pub fn raw_default_settings(&self) -> &SettingsContent {
340 &self.default_settings
341 }
342
343 /// Get the configured settings profile names.
344 pub fn configured_settings_profiles(&self) -> impl Iterator<Item = &str> {
345 self.user_settings
346 .iter()
347 .flat_map(|settings| settings.profiles.keys().map(|k| k.as_str()))
348 }
349
350 #[cfg(any(test, feature = "test-support"))]
351 pub fn test(cx: &mut App) -> Self {
352 Self::new(cx, &crate::test_settings())
353 }
354
355 /// Updates the value of a setting in the user's global configuration.
356 ///
357 /// This is only for tests. Normally, settings are only loaded from
358 /// JSON files.
359 #[cfg(any(test, feature = "test-support"))]
360 pub fn update_user_settings(
361 &mut self,
362 cx: &mut App,
363 update: impl FnOnce(&mut SettingsContent),
364 ) {
365 let mut content = self.user_settings.clone().unwrap_or_default().content;
366 update(&mut content);
367 let new_text = serde_json::to_string(&UserSettingsContent {
368 content,
369 ..Default::default()
370 })
371 .unwrap();
372 self.set_user_settings(&new_text, cx).unwrap();
373 }
374
375 pub async fn load_settings(fs: &Arc<dyn Fs>) -> Result<String> {
376 match fs.load(paths::settings_file()).await {
377 result @ Ok(_) => result,
378 Err(err) => {
379 if let Some(e) = err.downcast_ref::<std::io::Error>()
380 && e.kind() == std::io::ErrorKind::NotFound
381 {
382 return Ok(crate::initial_user_settings_content().to_string());
383 }
384 Err(err)
385 }
386 }
387 }
388
389 fn update_settings_file_inner(
390 &self,
391 fs: Arc<dyn Fs>,
392 update: impl 'static + Send + FnOnce(String, AsyncApp) -> Result<String>,
393 ) -> oneshot::Receiver<Result<()>> {
394 let (tx, rx) = oneshot::channel::<Result<()>>();
395 self.setting_file_updates_tx
396 .unbounded_send(Box::new(move |cx: AsyncApp| {
397 async move {
398 let res = async move {
399 let old_text = Self::load_settings(&fs).await?;
400 let new_text = update(old_text, cx)?;
401 let settings_path = paths::settings_file().as_path();
402 if fs.is_file(settings_path).await {
403 let resolved_path =
404 fs.canonicalize(settings_path).await.with_context(|| {
405 format!(
406 "Failed to canonicalize settings path {:?}",
407 settings_path
408 )
409 })?;
410
411 fs.atomic_write(resolved_path.clone(), new_text)
412 .await
413 .with_context(|| {
414 format!("Failed to write settings to file {:?}", resolved_path)
415 })?;
416 } else {
417 fs.atomic_write(settings_path.to_path_buf(), new_text)
418 .await
419 .with_context(|| {
420 format!("Failed to write settings to file {:?}", settings_path)
421 })?;
422 }
423 anyhow::Ok(())
424 }
425 .await;
426
427 let new_res = match &res {
428 Ok(_) => anyhow::Ok(()),
429 Err(e) => Err(anyhow::anyhow!("Failed to write settings to file {:?}", e)),
430 };
431
432 _ = tx.send(new_res);
433 res
434 }
435 .boxed_local()
436 }))
437 .map_err(|err| anyhow::format_err!("Failed to update settings file: {}", err))
438 .log_with_level(log::Level::Warn);
439 return rx;
440 }
441
442 pub fn update_settings_file(
443 &self,
444 fs: Arc<dyn Fs>,
445 update: impl 'static + Send + FnOnce(&mut SettingsContent, &App),
446 ) {
447 _ = self.update_settings_file_inner(fs, move |old_text: String, cx: AsyncApp| {
448 cx.read_global(|store: &SettingsStore, cx| {
449 store.new_text_for_update(old_text, |content| update(content, cx))
450 })
451 });
452 }
453
454 pub fn import_vscode_settings(
455 &self,
456 fs: Arc<dyn Fs>,
457 vscode_settings: VsCodeSettings,
458 ) -> oneshot::Receiver<Result<()>> {
459 self.update_settings_file_inner(fs, move |old_text: String, cx: AsyncApp| {
460 cx.read_global(|store: &SettingsStore, _cx| {
461 store.get_vscode_edits(old_text, &vscode_settings)
462 })
463 })
464 }
465
466 pub fn get_all_files(&self) -> Vec<SettingsFile> {
467 let mut files = Vec::from_iter(
468 self.local_settings
469 .keys()
470 // rev because these are sorted by path, so highest precedence is last
471 .rev()
472 .cloned()
473 .map(SettingsFile::Local),
474 );
475
476 if self.server_settings.is_some() {
477 files.push(SettingsFile::Server);
478 }
479 // ignoring profiles
480 // ignoring os profiles
481 // ignoring release channel profiles
482
483 if self.user_settings.is_some() {
484 files.push(SettingsFile::User);
485 }
486 if self.extension_settings.is_some() {
487 files.push(SettingsFile::Extension);
488 }
489 if self.global_settings.is_some() {
490 files.push(SettingsFile::Global);
491 }
492 files.push(SettingsFile::Default);
493 files
494 }
495}
496
497impl SettingsStore {
498 /// Updates the value of a setting in a JSON file, returning the new text
499 /// for that JSON file.
500 pub fn new_text_for_update(
501 &self,
502 old_text: String,
503 update: impl FnOnce(&mut SettingsContent),
504 ) -> String {
505 let edits = self.edits_for_update(&old_text, update);
506 let mut new_text = old_text;
507 for (range, replacement) in edits.into_iter() {
508 new_text.replace_range(range, &replacement);
509 }
510 new_text
511 }
512
513 pub fn get_vscode_edits(&self, old_text: String, vscode: &VsCodeSettings) -> String {
514 self.new_text_for_update(old_text, |settings_content| {
515 for v in self.setting_values.values() {
516 v.import_from_vscode(vscode, settings_content)
517 }
518 })
519 }
520
521 /// Updates the value of a setting in a JSON file, returning a list
522 /// of edits to apply to the JSON file.
523 pub fn edits_for_update(
524 &self,
525 text: &str,
526 update: impl FnOnce(&mut SettingsContent),
527 ) -> Vec<(Range<usize>, String)> {
528 let old_content: UserSettingsContent =
529 parse_json_with_comments(text).log_err().unwrap_or_default();
530 let mut new_content = old_content.clone();
531 update(&mut new_content.content);
532
533 let old_value = serde_json::to_value(&old_content).unwrap();
534 let new_value = serde_json::to_value(new_content).unwrap();
535
536 let mut key_path = Vec::new();
537 let mut edits = Vec::new();
538 let tab_size = self.json_tab_size();
539 let mut text = text.to_string();
540 update_value_in_json_text(
541 &mut text,
542 &mut key_path,
543 tab_size,
544 &old_value,
545 &new_value,
546 &mut edits,
547 );
548 edits
549 }
550
551 pub fn json_tab_size(&self) -> usize {
552 2
553 }
554
555 /// Sets the default settings via a JSON string.
556 ///
557 /// The string should contain a JSON object with a default value for every setting.
558 pub fn set_default_settings(
559 &mut self,
560 default_settings_content: &str,
561 cx: &mut App,
562 ) -> Result<()> {
563 self.default_settings = parse_json_with_comments(default_settings_content)?;
564 self.recompute_values(None, cx)?;
565 Ok(())
566 }
567
568 /// Sets the user settings via a JSON string.
569 pub fn set_user_settings(&mut self, user_settings_content: &str, cx: &mut App) -> Result<()> {
570 let settings: UserSettingsContent = if user_settings_content.is_empty() {
571 parse_json_with_comments("{}")?
572 } else {
573 parse_json_with_comments(user_settings_content)?
574 };
575
576 self.user_settings = Some(settings);
577 self.recompute_values(None, cx)?;
578 Ok(())
579 }
580
581 /// Sets the global settings via a JSON string.
582 pub fn set_global_settings(
583 &mut self,
584 global_settings_content: &str,
585 cx: &mut App,
586 ) -> Result<()> {
587 let settings: SettingsContent = if global_settings_content.is_empty() {
588 parse_json_with_comments("{}")?
589 } else {
590 parse_json_with_comments(global_settings_content)?
591 };
592
593 self.global_settings = Some(Box::new(settings));
594 self.recompute_values(None, cx)?;
595 Ok(())
596 }
597
598 pub fn set_server_settings(
599 &mut self,
600 server_settings_content: &str,
601 cx: &mut App,
602 ) -> Result<()> {
603 let settings: Option<SettingsContent> = if server_settings_content.is_empty() {
604 None
605 } else {
606 parse_json_with_comments(server_settings_content)?
607 };
608
609 // Rewrite the server settings into a content type
610 self.server_settings = settings.map(|settings| Box::new(settings));
611
612 self.recompute_values(None, cx)?;
613 Ok(())
614 }
615
616 /// Add or remove a set of local settings via a JSON string.
617 pub fn set_local_settings(
618 &mut self,
619 root_id: WorktreeId,
620 directory_path: Arc<RelPath>,
621 kind: LocalSettingsKind,
622 settings_content: Option<&str>,
623 cx: &mut App,
624 ) -> std::result::Result<(), InvalidSettingsError> {
625 let mut zed_settings_changed = false;
626 match (
627 kind,
628 settings_content
629 .map(|content| content.trim())
630 .filter(|content| !content.is_empty()),
631 ) {
632 (LocalSettingsKind::Tasks, _) => {
633 return Err(InvalidSettingsError::Tasks {
634 message: "Attempted to submit tasks into the settings store".to_string(),
635 path: directory_path
636 .join(RelPath::unix(task_file_name()).unwrap())
637 .as_std_path()
638 .to_path_buf(),
639 });
640 }
641 (LocalSettingsKind::Debug, _) => {
642 return Err(InvalidSettingsError::Debug {
643 message: "Attempted to submit debugger config into the settings store"
644 .to_string(),
645 path: directory_path
646 .join(RelPath::unix(task_file_name()).unwrap())
647 .as_std_path()
648 .to_path_buf(),
649 });
650 }
651 (LocalSettingsKind::Settings, None) => {
652 zed_settings_changed = self
653 .local_settings
654 .remove(&(root_id, directory_path.clone()))
655 .is_some()
656 }
657 (LocalSettingsKind::Editorconfig, None) => {
658 self.raw_editorconfig_settings
659 .remove(&(root_id, directory_path.clone()));
660 }
661 (LocalSettingsKind::Settings, Some(settings_contents)) => {
662 let new_settings = parse_json_with_comments::<ProjectSettingsContent>(
663 settings_contents,
664 )
665 .map_err(|e| InvalidSettingsError::LocalSettings {
666 path: directory_path.join(local_settings_file_relative_path()),
667 message: e.to_string(),
668 })?;
669 match self.local_settings.entry((root_id, directory_path.clone())) {
670 btree_map::Entry::Vacant(v) => {
671 v.insert(SettingsContent {
672 project: new_settings,
673 ..Default::default()
674 });
675 zed_settings_changed = true;
676 }
677 btree_map::Entry::Occupied(mut o) => {
678 if &o.get().project != &new_settings {
679 o.insert(SettingsContent {
680 project: new_settings,
681 ..Default::default()
682 });
683 zed_settings_changed = true;
684 }
685 }
686 }
687 }
688 (LocalSettingsKind::Editorconfig, Some(editorconfig_contents)) => {
689 match self
690 .raw_editorconfig_settings
691 .entry((root_id, directory_path.clone()))
692 {
693 btree_map::Entry::Vacant(v) => match editorconfig_contents.parse() {
694 Ok(new_contents) => {
695 v.insert((editorconfig_contents.to_owned(), Some(new_contents)));
696 }
697 Err(e) => {
698 v.insert((editorconfig_contents.to_owned(), None));
699 return Err(InvalidSettingsError::Editorconfig {
700 message: e.to_string(),
701 path: directory_path
702 .join(RelPath::unix(EDITORCONFIG_NAME).unwrap()),
703 });
704 }
705 },
706 btree_map::Entry::Occupied(mut o) => {
707 if o.get().0 != editorconfig_contents {
708 match editorconfig_contents.parse() {
709 Ok(new_contents) => {
710 o.insert((
711 editorconfig_contents.to_owned(),
712 Some(new_contents),
713 ));
714 }
715 Err(e) => {
716 o.insert((editorconfig_contents.to_owned(), None));
717 return Err(InvalidSettingsError::Editorconfig {
718 message: e.to_string(),
719 path: directory_path
720 .join(RelPath::unix(EDITORCONFIG_NAME).unwrap()),
721 });
722 }
723 }
724 }
725 }
726 }
727 }
728 };
729
730 if zed_settings_changed {
731 self.recompute_values(Some((root_id, &directory_path)), cx)?;
732 }
733 Ok(())
734 }
735
736 pub fn set_extension_settings(
737 &mut self,
738 content: ExtensionsSettingsContent,
739 cx: &mut App,
740 ) -> Result<()> {
741 self.extension_settings = Some(Box::new(SettingsContent {
742 project: ProjectSettingsContent {
743 all_languages: content.all_languages,
744 ..Default::default()
745 },
746 ..Default::default()
747 }));
748 self.recompute_values(None, cx)?;
749 Ok(())
750 }
751
752 /// Add or remove a set of local settings via a JSON string.
753 pub fn clear_local_settings(&mut self, root_id: WorktreeId, cx: &mut App) -> Result<()> {
754 self.local_settings
755 .retain(|(worktree_id, _), _| worktree_id != &root_id);
756 self.recompute_values(Some((root_id, RelPath::empty())), cx)?;
757 Ok(())
758 }
759
760 pub fn local_settings(
761 &self,
762 root_id: WorktreeId,
763 ) -> impl '_ + Iterator<Item = (Arc<RelPath>, &ProjectSettingsContent)> {
764 self.local_settings
765 .range(
766 (root_id, RelPath::empty().into())
767 ..(
768 WorktreeId::from_usize(root_id.to_usize() + 1),
769 RelPath::empty().into(),
770 ),
771 )
772 .map(|((_, path), content)| (path.clone(), &content.project))
773 }
774
775 pub fn local_editorconfig_settings(
776 &self,
777 root_id: WorktreeId,
778 ) -> impl '_ + Iterator<Item = (Arc<RelPath>, String, Option<Editorconfig>)> {
779 self.raw_editorconfig_settings
780 .range(
781 (root_id, RelPath::empty().into())
782 ..(
783 WorktreeId::from_usize(root_id.to_usize() + 1),
784 RelPath::empty().into(),
785 ),
786 )
787 .map(|((_, path), (content, parsed_content))| {
788 (path.clone(), content.clone(), parsed_content.clone())
789 })
790 }
791
792 pub fn json_schema(&self, params: &SettingsJsonSchemaParams) -> Value {
793 let mut generator = schemars::generate::SchemaSettings::draft2019_09()
794 .with_transform(DefaultDenyUnknownFields)
795 .into_generator();
796
797 UserSettingsContent::json_schema(&mut generator);
798
799 let language_settings_content_ref = generator
800 .subschema_for::<LanguageSettingsContent>()
801 .to_value();
802
803 replace_subschema::<LanguageToSettingsMap>(&mut generator, || {
804 json_schema!({
805 "type": "object",
806 "properties": params
807 .language_names
808 .iter()
809 .map(|name| {
810 (
811 name.clone(),
812 language_settings_content_ref.clone(),
813 )
814 })
815 .collect::<serde_json::Map<_, _>>(),
816 "errorMessage": "No language with this name is installed."
817 })
818 });
819
820 replace_subschema::<FontFamilyName>(&mut generator, || {
821 json_schema!({
822 "type": "string",
823 "enum": params.font_names,
824 })
825 });
826
827 replace_subschema::<ThemeName>(&mut generator, || {
828 json_schema!({
829 "type": "string",
830 "enum": params.theme_names,
831 })
832 });
833
834 replace_subschema::<IconThemeName>(&mut generator, || {
835 json_schema!({
836 "type": "string",
837 "enum": params.icon_theme_names,
838 })
839 });
840
841 generator
842 .root_schema_for::<UserSettingsContent>()
843 .to_value()
844 }
845
846 fn recompute_values(
847 &mut self,
848 changed_local_path: Option<(WorktreeId, &RelPath)>,
849 cx: &mut App,
850 ) -> std::result::Result<(), InvalidSettingsError> {
851 // Reload the global and local values for every setting.
852 let mut project_settings_stack = Vec::<SettingsContent>::new();
853 let mut paths_stack = Vec::<Option<(WorktreeId, &RelPath)>>::new();
854
855 if changed_local_path.is_none() {
856 let mut merged = self.default_settings.as_ref().clone();
857 merged.merge_from_option(self.extension_settings.as_deref());
858 merged.merge_from_option(self.global_settings.as_deref());
859 if let Some(user_settings) = self.user_settings.as_ref() {
860 merged.merge_from(&user_settings.content);
861 merged.merge_from_option(user_settings.for_release_channel());
862 merged.merge_from_option(user_settings.for_os());
863 merged.merge_from_option(user_settings.for_profile(cx));
864 }
865 merged.merge_from_option(self.server_settings.as_deref());
866 self.merged_settings = Rc::new(merged);
867
868 for setting_value in self.setting_values.values_mut() {
869 let value = setting_value.from_settings(&self.merged_settings, cx);
870 setting_value.set_global_value(value);
871 }
872 }
873
874 for ((root_id, directory_path), local_settings) in &self.local_settings {
875 // Build a stack of all of the local values for that setting.
876 while let Some(prev_entry) = paths_stack.last() {
877 if let Some((prev_root_id, prev_path)) = prev_entry
878 && (root_id != prev_root_id || !directory_path.starts_with(prev_path))
879 {
880 paths_stack.pop();
881 project_settings_stack.pop();
882 continue;
883 }
884 break;
885 }
886
887 paths_stack.push(Some((*root_id, directory_path.as_ref())));
888 let mut merged_local_settings = if let Some(deepest) = project_settings_stack.last() {
889 (*deepest).clone()
890 } else {
891 self.merged_settings.as_ref().clone()
892 };
893 merged_local_settings.merge_from(local_settings);
894
895 project_settings_stack.push(merged_local_settings);
896
897 // If a local settings file changed, then avoid recomputing local
898 // settings for any path outside of that directory.
899 if changed_local_path.is_some_and(|(changed_root_id, changed_local_path)| {
900 *root_id != changed_root_id || !directory_path.starts_with(changed_local_path)
901 }) {
902 continue;
903 }
904
905 for setting_value in self.setting_values.values_mut() {
906 let value =
907 setting_value.from_settings(&project_settings_stack.last().unwrap(), cx);
908 setting_value.set_local_value(*root_id, directory_path.clone(), value);
909 }
910 }
911 Ok(())
912 }
913
914 pub fn editorconfig_properties(
915 &self,
916 for_worktree: WorktreeId,
917 for_path: &RelPath,
918 ) -> Option<EditorconfigProperties> {
919 let mut properties = EditorconfigProperties::new();
920
921 for (directory_with_config, _, parsed_editorconfig) in
922 self.local_editorconfig_settings(for_worktree)
923 {
924 if !for_path.starts_with(&directory_with_config) {
925 properties.use_fallbacks();
926 return Some(properties);
927 }
928 let parsed_editorconfig = parsed_editorconfig?;
929 if parsed_editorconfig.is_root {
930 properties = EditorconfigProperties::new();
931 }
932 for section in parsed_editorconfig.sections {
933 section
934 .apply_to(&mut properties, for_path.as_std_path())
935 .log_err()?;
936 }
937 }
938
939 properties.use_fallbacks();
940 Some(properties)
941 }
942}
943
944#[derive(Debug, Clone, PartialEq)]
945pub enum InvalidSettingsError {
946 LocalSettings { path: Arc<RelPath>, message: String },
947 UserSettings { message: String },
948 ServerSettings { message: String },
949 DefaultSettings { message: String },
950 Editorconfig { path: Arc<RelPath>, message: String },
951 Tasks { path: PathBuf, message: String },
952 Debug { path: PathBuf, message: String },
953}
954
955impl std::fmt::Display for InvalidSettingsError {
956 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
957 match self {
958 InvalidSettingsError::LocalSettings { message, .. }
959 | InvalidSettingsError::UserSettings { message }
960 | InvalidSettingsError::ServerSettings { message }
961 | InvalidSettingsError::DefaultSettings { message }
962 | InvalidSettingsError::Tasks { message, .. }
963 | InvalidSettingsError::Editorconfig { message, .. }
964 | InvalidSettingsError::Debug { message, .. } => {
965 write!(f, "{message}")
966 }
967 }
968 }
969}
970impl std::error::Error for InvalidSettingsError {}
971
972impl Debug for SettingsStore {
973 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
974 f.debug_struct("SettingsStore")
975 .field(
976 "types",
977 &self
978 .setting_values
979 .values()
980 .map(|value| value.setting_type_name())
981 .collect::<Vec<_>>(),
982 )
983 .field("default_settings", &self.default_settings)
984 .field("user_settings", &self.user_settings)
985 .field("local_settings", &self.local_settings)
986 .finish_non_exhaustive()
987 }
988}
989
990impl<T: Settings> AnySettingValue for SettingValue<T> {
991 fn from_settings(&self, s: &SettingsContent, cx: &mut App) -> Box<dyn Any> {
992 Box::new(T::from_settings(s, cx)) as _
993 }
994
995 fn setting_type_name(&self) -> &'static str {
996 type_name::<T>()
997 }
998
999 fn all_local_values(&self) -> Vec<(WorktreeId, Arc<RelPath>, &dyn Any)> {
1000 self.local_values
1001 .iter()
1002 .map(|(id, path, value)| (*id, path.clone(), value as _))
1003 .collect()
1004 }
1005
1006 fn value_for_path(&self, path: Option<SettingsLocation>) -> &dyn Any {
1007 if let Some(SettingsLocation { worktree_id, path }) = path {
1008 for (settings_root_id, settings_path, value) in self.local_values.iter().rev() {
1009 if worktree_id == *settings_root_id && path.starts_with(settings_path) {
1010 return value;
1011 }
1012 }
1013 }
1014
1015 self.global_value
1016 .as_ref()
1017 .unwrap_or_else(|| panic!("no default value for setting {}", self.setting_type_name()))
1018 }
1019
1020 fn set_global_value(&mut self, value: Box<dyn Any>) {
1021 self.global_value = Some(*value.downcast().unwrap());
1022 }
1023
1024 fn set_local_value(&mut self, root_id: WorktreeId, path: Arc<RelPath>, value: Box<dyn Any>) {
1025 let value = *value.downcast().unwrap();
1026 match self
1027 .local_values
1028 .binary_search_by_key(&(root_id, &path), |e| (e.0, &e.1))
1029 {
1030 Ok(ix) => self.local_values[ix].2 = value,
1031 Err(ix) => self.local_values.insert(ix, (root_id, path, value)),
1032 }
1033 }
1034
1035 fn import_from_vscode(
1036 &self,
1037 vscode_settings: &VsCodeSettings,
1038 settings_content: &mut SettingsContent,
1039 ) {
1040 T::import_from_vscode(vscode_settings, settings_content);
1041 }
1042}
1043
1044#[cfg(test)]
1045mod tests {
1046 use std::num::NonZeroU32;
1047
1048 use crate::{
1049 ClosePosition, ItemSettingsContent, VsCodeSettingsSource, default_settings,
1050 settings_content::LanguageSettingsContent, test_settings,
1051 };
1052
1053 use super::*;
1054 use unindent::Unindent;
1055 use util::rel_path::rel_path;
1056
1057 #[derive(Debug, PartialEq)]
1058 struct AutoUpdateSetting {
1059 auto_update: bool,
1060 }
1061
1062 impl Settings for AutoUpdateSetting {
1063 fn from_settings(content: &SettingsContent, _: &mut App) -> Self {
1064 AutoUpdateSetting {
1065 auto_update: content.auto_update.unwrap(),
1066 }
1067 }
1068 }
1069
1070 #[derive(Debug, PartialEq)]
1071 struct ItemSettings {
1072 close_position: ClosePosition,
1073 git_status: bool,
1074 }
1075
1076 impl Settings for ItemSettings {
1077 fn from_settings(content: &SettingsContent, _: &mut App) -> Self {
1078 let content = content.tabs.clone().unwrap();
1079 ItemSettings {
1080 close_position: content.close_position.unwrap(),
1081 git_status: content.git_status.unwrap(),
1082 }
1083 }
1084
1085 fn import_from_vscode(vscode: &VsCodeSettings, content: &mut SettingsContent) {
1086 let mut show = None;
1087
1088 vscode.bool_setting("workbench.editor.decorations.colors", &mut show);
1089 if let Some(show) = show {
1090 content
1091 .tabs
1092 .get_or_insert_default()
1093 .git_status
1094 .replace(show);
1095 }
1096 }
1097 }
1098
1099 #[derive(Debug, PartialEq)]
1100 struct DefaultLanguageSettings {
1101 tab_size: NonZeroU32,
1102 preferred_line_length: u32,
1103 }
1104
1105 impl Settings for DefaultLanguageSettings {
1106 fn from_settings(content: &SettingsContent, _: &mut App) -> Self {
1107 let content = &content.project.all_languages.defaults;
1108 DefaultLanguageSettings {
1109 tab_size: content.tab_size.unwrap(),
1110 preferred_line_length: content.preferred_line_length.unwrap(),
1111 }
1112 }
1113
1114 fn import_from_vscode(vscode: &VsCodeSettings, content: &mut SettingsContent) {
1115 let content = &mut content.project.all_languages.defaults;
1116
1117 if let Some(size) = vscode
1118 .read_value("editor.tabSize")
1119 .and_then(|v| v.as_u64())
1120 .and_then(|n| NonZeroU32::new(n as u32))
1121 {
1122 content.tab_size = Some(size);
1123 }
1124 }
1125 }
1126
1127 #[gpui::test]
1128 fn test_settings_store_basic(cx: &mut App) {
1129 let mut store = SettingsStore::new(cx, &default_settings());
1130 store.register_setting::<AutoUpdateSetting>(cx);
1131 store.register_setting::<ItemSettings>(cx);
1132 store.register_setting::<DefaultLanguageSettings>(cx);
1133
1134 assert_eq!(
1135 store.get::<AutoUpdateSetting>(None),
1136 &AutoUpdateSetting { auto_update: true }
1137 );
1138 assert_eq!(
1139 store.get::<ItemSettings>(None).close_position,
1140 ClosePosition::Right
1141 );
1142
1143 store
1144 .set_user_settings(
1145 r#"{
1146 "auto_update": false,
1147 "tabs": {
1148 "close_position": "left"
1149 }
1150 }"#,
1151 cx,
1152 )
1153 .unwrap();
1154
1155 assert_eq!(
1156 store.get::<AutoUpdateSetting>(None),
1157 &AutoUpdateSetting { auto_update: false }
1158 );
1159 assert_eq!(
1160 store.get::<ItemSettings>(None).close_position,
1161 ClosePosition::Left
1162 );
1163
1164 store
1165 .set_local_settings(
1166 WorktreeId::from_usize(1),
1167 rel_path("root1").into(),
1168 LocalSettingsKind::Settings,
1169 Some(r#"{ "tab_size": 5 }"#),
1170 cx,
1171 )
1172 .unwrap();
1173 store
1174 .set_local_settings(
1175 WorktreeId::from_usize(1),
1176 rel_path("root1/subdir").into(),
1177 LocalSettingsKind::Settings,
1178 Some(r#"{ "preferred_line_length": 50 }"#),
1179 cx,
1180 )
1181 .unwrap();
1182
1183 store
1184 .set_local_settings(
1185 WorktreeId::from_usize(1),
1186 rel_path("root2").into(),
1187 LocalSettingsKind::Settings,
1188 Some(r#"{ "tab_size": 9, "auto_update": true}"#),
1189 cx,
1190 )
1191 .unwrap();
1192
1193 assert_eq!(
1194 store.get::<DefaultLanguageSettings>(Some(SettingsLocation {
1195 worktree_id: WorktreeId::from_usize(1),
1196 path: rel_path("root1/something"),
1197 })),
1198 &DefaultLanguageSettings {
1199 preferred_line_length: 80,
1200 tab_size: 5.try_into().unwrap(),
1201 }
1202 );
1203 assert_eq!(
1204 store.get::<DefaultLanguageSettings>(Some(SettingsLocation {
1205 worktree_id: WorktreeId::from_usize(1),
1206 path: rel_path("root1/subdir/something"),
1207 })),
1208 &DefaultLanguageSettings {
1209 preferred_line_length: 50,
1210 tab_size: 5.try_into().unwrap(),
1211 }
1212 );
1213 assert_eq!(
1214 store.get::<DefaultLanguageSettings>(Some(SettingsLocation {
1215 worktree_id: WorktreeId::from_usize(1),
1216 path: rel_path("root2/something"),
1217 })),
1218 &DefaultLanguageSettings {
1219 preferred_line_length: 80,
1220 tab_size: 9.try_into().unwrap(),
1221 }
1222 );
1223 assert_eq!(
1224 store.get::<AutoUpdateSetting>(Some(SettingsLocation {
1225 worktree_id: WorktreeId::from_usize(1),
1226 path: rel_path("root2/something")
1227 })),
1228 &AutoUpdateSetting { auto_update: false }
1229 );
1230 }
1231
1232 #[gpui::test]
1233 fn test_setting_store_assign_json_before_register(cx: &mut App) {
1234 let mut store = SettingsStore::new(cx, &test_settings());
1235 store
1236 .set_user_settings(r#"{ "auto_update": false }"#, cx)
1237 .unwrap();
1238 store.register_setting::<AutoUpdateSetting>(cx);
1239
1240 assert_eq!(
1241 store.get::<AutoUpdateSetting>(None),
1242 &AutoUpdateSetting { auto_update: false }
1243 );
1244 }
1245
1246 #[track_caller]
1247 fn check_settings_update(
1248 store: &mut SettingsStore,
1249 old_json: String,
1250 update: fn(&mut SettingsContent),
1251 expected_new_json: String,
1252 cx: &mut App,
1253 ) {
1254 store.set_user_settings(&old_json, cx).ok();
1255 let edits = store.edits_for_update(&old_json, update);
1256 let mut new_json = old_json;
1257 for (range, replacement) in edits.into_iter() {
1258 new_json.replace_range(range, &replacement);
1259 }
1260 pretty_assertions::assert_eq!(new_json, expected_new_json);
1261 }
1262
1263 #[gpui::test]
1264 fn test_setting_store_update(cx: &mut App) {
1265 let mut store = SettingsStore::new(cx, &test_settings());
1266
1267 // entries added and updated
1268 check_settings_update(
1269 &mut store,
1270 r#"{
1271 "languages": {
1272 "JSON": {
1273 "auto_indent": true
1274 }
1275 }
1276 }"#
1277 .unindent(),
1278 |settings| {
1279 settings
1280 .languages_mut()
1281 .get_mut("JSON")
1282 .unwrap()
1283 .auto_indent = Some(false);
1284
1285 settings.languages_mut().insert(
1286 "Rust".into(),
1287 LanguageSettingsContent {
1288 auto_indent: Some(true),
1289 ..Default::default()
1290 },
1291 );
1292 },
1293 r#"{
1294 "languages": {
1295 "Rust": {
1296 "auto_indent": true
1297 },
1298 "JSON": {
1299 "auto_indent": false
1300 }
1301 }
1302 }"#
1303 .unindent(),
1304 cx,
1305 );
1306
1307 // entries removed
1308 check_settings_update(
1309 &mut store,
1310 r#"{
1311 "languages": {
1312 "Rust": {
1313 "language_setting_2": true
1314 },
1315 "JSON": {
1316 "language_setting_1": false
1317 }
1318 }
1319 }"#
1320 .unindent(),
1321 |settings| {
1322 settings.languages_mut().remove("JSON").unwrap();
1323 },
1324 r#"{
1325 "languages": {
1326 "Rust": {
1327 "language_setting_2": true
1328 }
1329 }
1330 }"#
1331 .unindent(),
1332 cx,
1333 );
1334
1335 check_settings_update(
1336 &mut store,
1337 r#"{
1338 "languages": {
1339 "Rust": {
1340 "language_setting_2": true
1341 },
1342 "JSON": {
1343 "language_setting_1": false
1344 }
1345 }
1346 }"#
1347 .unindent(),
1348 |settings| {
1349 settings.languages_mut().remove("Rust").unwrap();
1350 },
1351 r#"{
1352 "languages": {
1353 "JSON": {
1354 "language_setting_1": false
1355 }
1356 }
1357 }"#
1358 .unindent(),
1359 cx,
1360 );
1361
1362 // weird formatting
1363 check_settings_update(
1364 &mut store,
1365 r#"{
1366 "tabs": { "close_position": "left", "name": "Max" }
1367 }"#
1368 .unindent(),
1369 |settings| {
1370 settings.tabs.as_mut().unwrap().close_position = Some(ClosePosition::Left);
1371 },
1372 r#"{
1373 "tabs": { "close_position": "left", "name": "Max" }
1374 }"#
1375 .unindent(),
1376 cx,
1377 );
1378
1379 // single-line formatting, other keys
1380 check_settings_update(
1381 &mut store,
1382 r#"{ "one": 1, "two": 2 }"#.to_owned(),
1383 |settings| settings.auto_update = Some(true),
1384 r#"{ "auto_update": true, "one": 1, "two": 2 }"#.to_owned(),
1385 cx,
1386 );
1387
1388 // empty object
1389 check_settings_update(
1390 &mut store,
1391 r#"{
1392 "tabs": {}
1393 }"#
1394 .unindent(),
1395 |settings| settings.tabs.as_mut().unwrap().close_position = Some(ClosePosition::Left),
1396 r#"{
1397 "tabs": {
1398 "close_position": "left"
1399 }
1400 }"#
1401 .unindent(),
1402 cx,
1403 );
1404
1405 // no content
1406 check_settings_update(
1407 &mut store,
1408 r#""#.unindent(),
1409 |settings| {
1410 settings.tabs = Some(ItemSettingsContent {
1411 git_status: Some(true),
1412 ..Default::default()
1413 })
1414 },
1415 r#"{
1416 "tabs": {
1417 "git_status": true
1418 }
1419 }
1420 "#
1421 .unindent(),
1422 cx,
1423 );
1424
1425 check_settings_update(
1426 &mut store,
1427 r#"{
1428 }
1429 "#
1430 .unindent(),
1431 |settings| settings.title_bar.get_or_insert_default().show_branch_name = Some(true),
1432 r#"{
1433 "title_bar": {
1434 "show_branch_name": true
1435 }
1436 }
1437 "#
1438 .unindent(),
1439 cx,
1440 );
1441 }
1442
1443 #[gpui::test]
1444 fn test_vscode_import(cx: &mut App) {
1445 let mut store = SettingsStore::new(cx, &test_settings());
1446 store.register_setting::<DefaultLanguageSettings>(cx);
1447 store.register_setting::<ItemSettings>(cx);
1448 store.register_setting::<AutoUpdateSetting>(cx);
1449
1450 // create settings that werent present
1451 check_vscode_import(
1452 &mut store,
1453 r#"{
1454 }
1455 "#
1456 .unindent(),
1457 r#" { "editor.tabSize": 37 } "#.to_owned(),
1458 r#"{
1459 "tab_size": 37
1460 }
1461 "#
1462 .unindent(),
1463 cx,
1464 );
1465
1466 // persist settings that were present
1467 check_vscode_import(
1468 &mut store,
1469 r#"{
1470 "preferred_line_length": 99,
1471 }
1472 "#
1473 .unindent(),
1474 r#"{ "editor.tabSize": 42 }"#.to_owned(),
1475 r#"{
1476 "tab_size": 42,
1477 "preferred_line_length": 99,
1478 }
1479 "#
1480 .unindent(),
1481 cx,
1482 );
1483
1484 // don't clobber settings that aren't present in vscode
1485 check_vscode_import(
1486 &mut store,
1487 r#"{
1488 "preferred_line_length": 99,
1489 "tab_size": 42
1490 }
1491 "#
1492 .unindent(),
1493 r#"{}"#.to_owned(),
1494 r#"{
1495 "preferred_line_length": 99,
1496 "tab_size": 42
1497 }
1498 "#
1499 .unindent(),
1500 cx,
1501 );
1502
1503 // custom enum
1504 check_vscode_import(
1505 &mut store,
1506 r#"{
1507 }
1508 "#
1509 .unindent(),
1510 r#"{ "workbench.editor.decorations.colors": true }"#.to_owned(),
1511 r#"{
1512 "tabs": {
1513 "git_status": true
1514 }
1515 }
1516 "#
1517 .unindent(),
1518 cx,
1519 );
1520 }
1521
1522 #[track_caller]
1523 fn check_vscode_import(
1524 store: &mut SettingsStore,
1525 old: String,
1526 vscode: String,
1527 expected: String,
1528 cx: &mut App,
1529 ) {
1530 store.set_user_settings(&old, cx).ok();
1531 let new = store.get_vscode_edits(
1532 old,
1533 &VsCodeSettings::from_str(&vscode, VsCodeSettingsSource::VsCode).unwrap(),
1534 );
1535 pretty_assertions::assert_eq!(new, expected);
1536 }
1537
1538 #[gpui::test]
1539 fn test_update_git_settings(cx: &mut App) {
1540 let store = SettingsStore::new(cx, &test_settings());
1541
1542 let actual = store.new_text_for_update("{}".to_string(), |current| {
1543 current
1544 .git
1545 .get_or_insert_default()
1546 .inline_blame
1547 .get_or_insert_default()
1548 .enabled = Some(true);
1549 });
1550 assert_eq!(
1551 actual,
1552 r#"{
1553 "git": {
1554 "inline_blame": {
1555 "enabled": true
1556 }
1557 }
1558 }
1559 "#
1560 .unindent()
1561 );
1562 }
1563
1564 #[gpui::test]
1565 fn test_global_settings(cx: &mut App) {
1566 let mut store = SettingsStore::new(cx, &test_settings());
1567 store.register_setting::<ItemSettings>(cx);
1568
1569 // Set global settings - these should override defaults but not user settings
1570 store
1571 .set_global_settings(
1572 r#"{
1573 "tabs": {
1574 "close_position": "right",
1575 "git_status": true,
1576 }
1577 }"#,
1578 cx,
1579 )
1580 .unwrap();
1581
1582 // Before user settings, global settings should apply
1583 assert_eq!(
1584 store.get::<ItemSettings>(None),
1585 &ItemSettings {
1586 close_position: ClosePosition::Right,
1587 git_status: true,
1588 }
1589 );
1590
1591 // Set user settings - these should override both defaults and global
1592 store
1593 .set_user_settings(
1594 r#"{
1595 "tabs": {
1596 "close_position": "left"
1597 }
1598 }"#,
1599 cx,
1600 )
1601 .unwrap();
1602
1603 // User settings should override global settings
1604 assert_eq!(
1605 store.get::<ItemSettings>(None),
1606 &ItemSettings {
1607 close_position: ClosePosition::Left,
1608 git_status: true, // Staff from global settings
1609 }
1610 );
1611 }
1612}