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::new(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::new(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.join(RelPath::new(EDITORCONFIG_NAME).unwrap()),
702 });
703 }
704 },
705 btree_map::Entry::Occupied(mut o) => {
706 if o.get().0 != editorconfig_contents {
707 match editorconfig_contents.parse() {
708 Ok(new_contents) => {
709 o.insert((
710 editorconfig_contents.to_owned(),
711 Some(new_contents),
712 ));
713 }
714 Err(e) => {
715 o.insert((editorconfig_contents.to_owned(), None));
716 return Err(InvalidSettingsError::Editorconfig {
717 message: e.to_string(),
718 path: directory_path
719 .join(RelPath::new(EDITORCONFIG_NAME).unwrap()),
720 });
721 }
722 }
723 }
724 }
725 }
726 }
727 };
728
729 if zed_settings_changed {
730 self.recompute_values(Some((root_id, &directory_path)), cx)?;
731 }
732 Ok(())
733 }
734
735 pub fn set_extension_settings(
736 &mut self,
737 content: ExtensionsSettingsContent,
738 cx: &mut App,
739 ) -> Result<()> {
740 self.extension_settings = Some(Box::new(SettingsContent {
741 project: ProjectSettingsContent {
742 all_languages: content.all_languages,
743 ..Default::default()
744 },
745 ..Default::default()
746 }));
747 self.recompute_values(None, cx)?;
748 Ok(())
749 }
750
751 /// Add or remove a set of local settings via a JSON string.
752 pub fn clear_local_settings(&mut self, root_id: WorktreeId, cx: &mut App) -> Result<()> {
753 self.local_settings
754 .retain(|(worktree_id, _), _| worktree_id != &root_id);
755 self.recompute_values(Some((root_id, RelPath::empty())), cx)?;
756 Ok(())
757 }
758
759 pub fn local_settings(
760 &self,
761 root_id: WorktreeId,
762 ) -> impl '_ + Iterator<Item = (Arc<RelPath>, &ProjectSettingsContent)> {
763 self.local_settings
764 .range(
765 (root_id, RelPath::empty().into())
766 ..(
767 WorktreeId::from_usize(root_id.to_usize() + 1),
768 RelPath::empty().into(),
769 ),
770 )
771 .map(|((_, path), content)| (path.clone(), &content.project))
772 }
773
774 pub fn local_editorconfig_settings(
775 &self,
776 root_id: WorktreeId,
777 ) -> impl '_ + Iterator<Item = (Arc<RelPath>, String, Option<Editorconfig>)> {
778 self.raw_editorconfig_settings
779 .range(
780 (root_id, RelPath::empty().into())
781 ..(
782 WorktreeId::from_usize(root_id.to_usize() + 1),
783 RelPath::empty().into(),
784 ),
785 )
786 .map(|((_, path), (content, parsed_content))| {
787 (path.clone(), content.clone(), parsed_content.clone())
788 })
789 }
790
791 pub fn json_schema(&self, params: &SettingsJsonSchemaParams) -> Value {
792 let mut generator = schemars::generate::SchemaSettings::draft2019_09()
793 .with_transform(DefaultDenyUnknownFields)
794 .into_generator();
795
796 UserSettingsContent::json_schema(&mut generator);
797
798 let language_settings_content_ref = generator
799 .subschema_for::<LanguageSettingsContent>()
800 .to_value();
801 replace_subschema::<LanguageToSettingsMap>(&mut generator, || {
802 json_schema!({
803 "type": "object",
804 "properties": params
805 .language_names
806 .iter()
807 .map(|name| {
808 (
809 name.clone(),
810 language_settings_content_ref.clone(),
811 )
812 })
813 .collect::<serde_json::Map<_, _>>()
814 })
815 });
816
817 replace_subschema::<FontFamilyName>(&mut generator, || {
818 json_schema!({
819 "type": "string",
820 "enum": params.font_names,
821 })
822 });
823
824 replace_subschema::<ThemeName>(&mut generator, || {
825 json_schema!({
826 "type": "string",
827 "enum": params.theme_names,
828 })
829 });
830
831 replace_subschema::<IconThemeName>(&mut generator, || {
832 json_schema!({
833 "type": "string",
834 "enum": params.icon_theme_names,
835 })
836 });
837
838 generator
839 .root_schema_for::<UserSettingsContent>()
840 .to_value()
841 }
842
843 fn recompute_values(
844 &mut self,
845 changed_local_path: Option<(WorktreeId, &RelPath)>,
846 cx: &mut App,
847 ) -> std::result::Result<(), InvalidSettingsError> {
848 // Reload the global and local values for every setting.
849 let mut project_settings_stack = Vec::<SettingsContent>::new();
850 let mut paths_stack = Vec::<Option<(WorktreeId, &RelPath)>>::new();
851
852 if changed_local_path.is_none() {
853 let mut merged = self.default_settings.as_ref().clone();
854 merged.merge_from_option(self.extension_settings.as_deref());
855 merged.merge_from_option(self.global_settings.as_deref());
856 if let Some(user_settings) = self.user_settings.as_ref() {
857 merged.merge_from(&user_settings.content);
858 merged.merge_from_option(user_settings.for_release_channel());
859 merged.merge_from_option(user_settings.for_os());
860 merged.merge_from_option(user_settings.for_profile(cx));
861 }
862 merged.merge_from_option(self.server_settings.as_deref());
863 self.merged_settings = Rc::new(merged);
864
865 for setting_value in self.setting_values.values_mut() {
866 let value = setting_value.from_settings(&self.merged_settings, cx);
867 setting_value.set_global_value(value);
868 }
869 }
870
871 for ((root_id, directory_path), local_settings) in &self.local_settings {
872 // Build a stack of all of the local values for that setting.
873 while let Some(prev_entry) = paths_stack.last() {
874 if let Some((prev_root_id, prev_path)) = prev_entry
875 && (root_id != prev_root_id || !directory_path.starts_with(prev_path))
876 {
877 paths_stack.pop();
878 project_settings_stack.pop();
879 continue;
880 }
881 break;
882 }
883
884 paths_stack.push(Some((*root_id, directory_path.as_ref())));
885 let mut merged_local_settings = if let Some(deepest) = project_settings_stack.last() {
886 (*deepest).clone()
887 } else {
888 self.merged_settings.as_ref().clone()
889 };
890 merged_local_settings.merge_from(local_settings);
891
892 project_settings_stack.push(merged_local_settings);
893
894 // If a local settings file changed, then avoid recomputing local
895 // settings for any path outside of that directory.
896 if changed_local_path.is_some_and(|(changed_root_id, changed_local_path)| {
897 *root_id != changed_root_id || !directory_path.starts_with(changed_local_path)
898 }) {
899 continue;
900 }
901
902 for setting_value in self.setting_values.values_mut() {
903 let value =
904 setting_value.from_settings(&project_settings_stack.last().unwrap(), cx);
905 setting_value.set_local_value(*root_id, directory_path.clone(), value);
906 }
907 }
908 Ok(())
909 }
910
911 pub fn editorconfig_properties(
912 &self,
913 for_worktree: WorktreeId,
914 for_path: &RelPath,
915 ) -> Option<EditorconfigProperties> {
916 let mut properties = EditorconfigProperties::new();
917
918 for (directory_with_config, _, parsed_editorconfig) in
919 self.local_editorconfig_settings(for_worktree)
920 {
921 if !for_path.starts_with(&directory_with_config) {
922 properties.use_fallbacks();
923 return Some(properties);
924 }
925 let parsed_editorconfig = parsed_editorconfig?;
926 if parsed_editorconfig.is_root {
927 properties = EditorconfigProperties::new();
928 }
929 for section in parsed_editorconfig.sections {
930 section
931 .apply_to(&mut properties, for_path.as_std_path())
932 .log_err()?;
933 }
934 }
935
936 properties.use_fallbacks();
937 Some(properties)
938 }
939}
940
941#[derive(Debug, Clone, PartialEq)]
942pub enum InvalidSettingsError {
943 LocalSettings { path: Arc<RelPath>, message: String },
944 UserSettings { message: String },
945 ServerSettings { message: String },
946 DefaultSettings { message: String },
947 Editorconfig { path: Arc<RelPath>, message: String },
948 Tasks { path: PathBuf, message: String },
949 Debug { path: PathBuf, message: String },
950}
951
952impl std::fmt::Display for InvalidSettingsError {
953 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
954 match self {
955 InvalidSettingsError::LocalSettings { message, .. }
956 | InvalidSettingsError::UserSettings { message }
957 | InvalidSettingsError::ServerSettings { message }
958 | InvalidSettingsError::DefaultSettings { message }
959 | InvalidSettingsError::Tasks { message, .. }
960 | InvalidSettingsError::Editorconfig { message, .. }
961 | InvalidSettingsError::Debug { message, .. } => {
962 write!(f, "{message}")
963 }
964 }
965 }
966}
967impl std::error::Error for InvalidSettingsError {}
968
969impl Debug for SettingsStore {
970 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
971 f.debug_struct("SettingsStore")
972 .field(
973 "types",
974 &self
975 .setting_values
976 .values()
977 .map(|value| value.setting_type_name())
978 .collect::<Vec<_>>(),
979 )
980 .field("default_settings", &self.default_settings)
981 .field("user_settings", &self.user_settings)
982 .field("local_settings", &self.local_settings)
983 .finish_non_exhaustive()
984 }
985}
986
987impl<T: Settings> AnySettingValue for SettingValue<T> {
988 fn from_settings(&self, s: &SettingsContent, cx: &mut App) -> Box<dyn Any> {
989 Box::new(T::from_settings(s, cx)) as _
990 }
991
992 fn setting_type_name(&self) -> &'static str {
993 type_name::<T>()
994 }
995
996 fn all_local_values(&self) -> Vec<(WorktreeId, Arc<RelPath>, &dyn Any)> {
997 self.local_values
998 .iter()
999 .map(|(id, path, value)| (*id, path.clone(), value as _))
1000 .collect()
1001 }
1002
1003 fn value_for_path(&self, path: Option<SettingsLocation>) -> &dyn Any {
1004 if let Some(SettingsLocation { worktree_id, path }) = path {
1005 for (settings_root_id, settings_path, value) in self.local_values.iter().rev() {
1006 if worktree_id == *settings_root_id && path.starts_with(settings_path) {
1007 return value;
1008 }
1009 }
1010 }
1011
1012 self.global_value
1013 .as_ref()
1014 .unwrap_or_else(|| panic!("no default value for setting {}", self.setting_type_name()))
1015 }
1016
1017 fn set_global_value(&mut self, value: Box<dyn Any>) {
1018 self.global_value = Some(*value.downcast().unwrap());
1019 }
1020
1021 fn set_local_value(&mut self, root_id: WorktreeId, path: Arc<RelPath>, value: Box<dyn Any>) {
1022 let value = *value.downcast().unwrap();
1023 match self
1024 .local_values
1025 .binary_search_by_key(&(root_id, &path), |e| (e.0, &e.1))
1026 {
1027 Ok(ix) => self.local_values[ix].2 = value,
1028 Err(ix) => self.local_values.insert(ix, (root_id, path, value)),
1029 }
1030 }
1031
1032 fn import_from_vscode(
1033 &self,
1034 vscode_settings: &VsCodeSettings,
1035 settings_content: &mut SettingsContent,
1036 ) {
1037 T::import_from_vscode(vscode_settings, settings_content);
1038 }
1039}
1040
1041#[cfg(test)]
1042mod tests {
1043 use std::num::NonZeroU32;
1044
1045 use crate::{
1046 ClosePosition, ItemSettingsContent, VsCodeSettingsSource, default_settings,
1047 settings_content::LanguageSettingsContent, test_settings,
1048 };
1049
1050 use super::*;
1051 use unindent::Unindent;
1052 use util::rel_path::rel_path;
1053
1054 #[derive(Debug, PartialEq)]
1055 struct AutoUpdateSetting {
1056 auto_update: bool,
1057 }
1058
1059 impl Settings for AutoUpdateSetting {
1060 fn from_settings(content: &SettingsContent, _: &mut App) -> Self {
1061 AutoUpdateSetting {
1062 auto_update: content.auto_update.unwrap(),
1063 }
1064 }
1065 }
1066
1067 #[derive(Debug, PartialEq)]
1068 struct ItemSettings {
1069 close_position: ClosePosition,
1070 git_status: bool,
1071 }
1072
1073 impl Settings for ItemSettings {
1074 fn from_settings(content: &SettingsContent, _: &mut App) -> Self {
1075 let content = content.tabs.clone().unwrap();
1076 ItemSettings {
1077 close_position: content.close_position.unwrap(),
1078 git_status: content.git_status.unwrap(),
1079 }
1080 }
1081
1082 fn import_from_vscode(vscode: &VsCodeSettings, content: &mut SettingsContent) {
1083 let mut show = None;
1084
1085 vscode.bool_setting("workbench.editor.decorations.colors", &mut show);
1086 if let Some(show) = show {
1087 content
1088 .tabs
1089 .get_or_insert_default()
1090 .git_status
1091 .replace(show);
1092 }
1093 }
1094 }
1095
1096 #[derive(Debug, PartialEq)]
1097 struct DefaultLanguageSettings {
1098 tab_size: NonZeroU32,
1099 preferred_line_length: u32,
1100 }
1101
1102 impl Settings for DefaultLanguageSettings {
1103 fn from_settings(content: &SettingsContent, _: &mut App) -> Self {
1104 let content = &content.project.all_languages.defaults;
1105 DefaultLanguageSettings {
1106 tab_size: content.tab_size.unwrap(),
1107 preferred_line_length: content.preferred_line_length.unwrap(),
1108 }
1109 }
1110
1111 fn import_from_vscode(vscode: &VsCodeSettings, content: &mut SettingsContent) {
1112 let content = &mut content.project.all_languages.defaults;
1113
1114 if let Some(size) = vscode
1115 .read_value("editor.tabSize")
1116 .and_then(|v| v.as_u64())
1117 .and_then(|n| NonZeroU32::new(n as u32))
1118 {
1119 content.tab_size = Some(size);
1120 }
1121 }
1122 }
1123
1124 #[gpui::test]
1125 fn test_settings_store_basic(cx: &mut App) {
1126 let mut store = SettingsStore::new(cx, &default_settings());
1127 store.register_setting::<AutoUpdateSetting>(cx);
1128 store.register_setting::<ItemSettings>(cx);
1129 store.register_setting::<DefaultLanguageSettings>(cx);
1130
1131 assert_eq!(
1132 store.get::<AutoUpdateSetting>(None),
1133 &AutoUpdateSetting { auto_update: true }
1134 );
1135 assert_eq!(
1136 store.get::<ItemSettings>(None).close_position,
1137 ClosePosition::Right
1138 );
1139
1140 store
1141 .set_user_settings(
1142 r#"{
1143 "auto_update": false,
1144 "tabs": {
1145 "close_position": "left"
1146 }
1147 }"#,
1148 cx,
1149 )
1150 .unwrap();
1151
1152 assert_eq!(
1153 store.get::<AutoUpdateSetting>(None),
1154 &AutoUpdateSetting { auto_update: false }
1155 );
1156 assert_eq!(
1157 store.get::<ItemSettings>(None).close_position,
1158 ClosePosition::Left
1159 );
1160
1161 store
1162 .set_local_settings(
1163 WorktreeId::from_usize(1),
1164 rel_path("root1").into(),
1165 LocalSettingsKind::Settings,
1166 Some(r#"{ "tab_size": 5 }"#),
1167 cx,
1168 )
1169 .unwrap();
1170 store
1171 .set_local_settings(
1172 WorktreeId::from_usize(1),
1173 rel_path("root1/subdir").into(),
1174 LocalSettingsKind::Settings,
1175 Some(r#"{ "preferred_line_length": 50 }"#),
1176 cx,
1177 )
1178 .unwrap();
1179
1180 store
1181 .set_local_settings(
1182 WorktreeId::from_usize(1),
1183 rel_path("root2").into(),
1184 LocalSettingsKind::Settings,
1185 Some(r#"{ "tab_size": 9, "auto_update": true}"#),
1186 cx,
1187 )
1188 .unwrap();
1189
1190 assert_eq!(
1191 store.get::<DefaultLanguageSettings>(Some(SettingsLocation {
1192 worktree_id: WorktreeId::from_usize(1),
1193 path: rel_path("root1/something"),
1194 })),
1195 &DefaultLanguageSettings {
1196 preferred_line_length: 80,
1197 tab_size: 5.try_into().unwrap(),
1198 }
1199 );
1200 assert_eq!(
1201 store.get::<DefaultLanguageSettings>(Some(SettingsLocation {
1202 worktree_id: WorktreeId::from_usize(1),
1203 path: rel_path("root1/subdir/something"),
1204 })),
1205 &DefaultLanguageSettings {
1206 preferred_line_length: 50,
1207 tab_size: 5.try_into().unwrap(),
1208 }
1209 );
1210 assert_eq!(
1211 store.get::<DefaultLanguageSettings>(Some(SettingsLocation {
1212 worktree_id: WorktreeId::from_usize(1),
1213 path: rel_path("root2/something"),
1214 })),
1215 &DefaultLanguageSettings {
1216 preferred_line_length: 80,
1217 tab_size: 9.try_into().unwrap(),
1218 }
1219 );
1220 assert_eq!(
1221 store.get::<AutoUpdateSetting>(Some(SettingsLocation {
1222 worktree_id: WorktreeId::from_usize(1),
1223 path: rel_path("root2/something")
1224 })),
1225 &AutoUpdateSetting { auto_update: false }
1226 );
1227 }
1228
1229 #[gpui::test]
1230 fn test_setting_store_assign_json_before_register(cx: &mut App) {
1231 let mut store = SettingsStore::new(cx, &test_settings());
1232 store
1233 .set_user_settings(r#"{ "auto_update": false }"#, cx)
1234 .unwrap();
1235 store.register_setting::<AutoUpdateSetting>(cx);
1236
1237 assert_eq!(
1238 store.get::<AutoUpdateSetting>(None),
1239 &AutoUpdateSetting { auto_update: false }
1240 );
1241 }
1242
1243 #[track_caller]
1244 fn check_settings_update(
1245 store: &mut SettingsStore,
1246 old_json: String,
1247 update: fn(&mut SettingsContent),
1248 expected_new_json: String,
1249 cx: &mut App,
1250 ) {
1251 store.set_user_settings(&old_json, cx).ok();
1252 let edits = store.edits_for_update(&old_json, update);
1253 let mut new_json = old_json;
1254 for (range, replacement) in edits.into_iter() {
1255 new_json.replace_range(range, &replacement);
1256 }
1257 pretty_assertions::assert_eq!(new_json, expected_new_json);
1258 }
1259
1260 #[gpui::test]
1261 fn test_setting_store_update(cx: &mut App) {
1262 let mut store = SettingsStore::new(cx, &test_settings());
1263
1264 // entries added and updated
1265 check_settings_update(
1266 &mut store,
1267 r#"{
1268 "languages": {
1269 "JSON": {
1270 "auto_indent": true
1271 }
1272 }
1273 }"#
1274 .unindent(),
1275 |settings| {
1276 settings
1277 .languages_mut()
1278 .get_mut("JSON")
1279 .unwrap()
1280 .auto_indent = Some(false);
1281
1282 settings.languages_mut().insert(
1283 "Rust".into(),
1284 LanguageSettingsContent {
1285 auto_indent: Some(true),
1286 ..Default::default()
1287 },
1288 );
1289 },
1290 r#"{
1291 "languages": {
1292 "Rust": {
1293 "auto_indent": true
1294 },
1295 "JSON": {
1296 "auto_indent": false
1297 }
1298 }
1299 }"#
1300 .unindent(),
1301 cx,
1302 );
1303
1304 // entries removed
1305 check_settings_update(
1306 &mut store,
1307 r#"{
1308 "languages": {
1309 "Rust": {
1310 "language_setting_2": true
1311 },
1312 "JSON": {
1313 "language_setting_1": false
1314 }
1315 }
1316 }"#
1317 .unindent(),
1318 |settings| {
1319 settings.languages_mut().remove("JSON").unwrap();
1320 },
1321 r#"{
1322 "languages": {
1323 "Rust": {
1324 "language_setting_2": true
1325 }
1326 }
1327 }"#
1328 .unindent(),
1329 cx,
1330 );
1331
1332 check_settings_update(
1333 &mut store,
1334 r#"{
1335 "languages": {
1336 "Rust": {
1337 "language_setting_2": true
1338 },
1339 "JSON": {
1340 "language_setting_1": false
1341 }
1342 }
1343 }"#
1344 .unindent(),
1345 |settings| {
1346 settings.languages_mut().remove("Rust").unwrap();
1347 },
1348 r#"{
1349 "languages": {
1350 "JSON": {
1351 "language_setting_1": false
1352 }
1353 }
1354 }"#
1355 .unindent(),
1356 cx,
1357 );
1358
1359 // weird formatting
1360 check_settings_update(
1361 &mut store,
1362 r#"{
1363 "tabs": { "close_position": "left", "name": "Max" }
1364 }"#
1365 .unindent(),
1366 |settings| {
1367 settings.tabs.as_mut().unwrap().close_position = Some(ClosePosition::Left);
1368 },
1369 r#"{
1370 "tabs": { "close_position": "left", "name": "Max" }
1371 }"#
1372 .unindent(),
1373 cx,
1374 );
1375
1376 // single-line formatting, other keys
1377 check_settings_update(
1378 &mut store,
1379 r#"{ "one": 1, "two": 2 }"#.to_owned(),
1380 |settings| settings.auto_update = Some(true),
1381 r#"{ "auto_update": true, "one": 1, "two": 2 }"#.to_owned(),
1382 cx,
1383 );
1384
1385 // empty object
1386 check_settings_update(
1387 &mut store,
1388 r#"{
1389 "tabs": {}
1390 }"#
1391 .unindent(),
1392 |settings| settings.tabs.as_mut().unwrap().close_position = Some(ClosePosition::Left),
1393 r#"{
1394 "tabs": {
1395 "close_position": "left"
1396 }
1397 }"#
1398 .unindent(),
1399 cx,
1400 );
1401
1402 // no content
1403 check_settings_update(
1404 &mut store,
1405 r#""#.unindent(),
1406 |settings| {
1407 settings.tabs = Some(ItemSettingsContent {
1408 git_status: Some(true),
1409 ..Default::default()
1410 })
1411 },
1412 r#"{
1413 "tabs": {
1414 "git_status": true
1415 }
1416 }
1417 "#
1418 .unindent(),
1419 cx,
1420 );
1421
1422 check_settings_update(
1423 &mut store,
1424 r#"{
1425 }
1426 "#
1427 .unindent(),
1428 |settings| settings.title_bar.get_or_insert_default().show_branch_name = Some(true),
1429 r#"{
1430 "title_bar": {
1431 "show_branch_name": true
1432 }
1433 }
1434 "#
1435 .unindent(),
1436 cx,
1437 );
1438 }
1439
1440 #[gpui::test]
1441 fn test_vscode_import(cx: &mut App) {
1442 let mut store = SettingsStore::new(cx, &test_settings());
1443 store.register_setting::<DefaultLanguageSettings>(cx);
1444 store.register_setting::<ItemSettings>(cx);
1445 store.register_setting::<AutoUpdateSetting>(cx);
1446
1447 // create settings that werent present
1448 check_vscode_import(
1449 &mut store,
1450 r#"{
1451 }
1452 "#
1453 .unindent(),
1454 r#" { "editor.tabSize": 37 } "#.to_owned(),
1455 r#"{
1456 "tab_size": 37
1457 }
1458 "#
1459 .unindent(),
1460 cx,
1461 );
1462
1463 // persist settings that were present
1464 check_vscode_import(
1465 &mut store,
1466 r#"{
1467 "preferred_line_length": 99,
1468 }
1469 "#
1470 .unindent(),
1471 r#"{ "editor.tabSize": 42 }"#.to_owned(),
1472 r#"{
1473 "tab_size": 42,
1474 "preferred_line_length": 99,
1475 }
1476 "#
1477 .unindent(),
1478 cx,
1479 );
1480
1481 // don't clobber settings that aren't present in vscode
1482 check_vscode_import(
1483 &mut store,
1484 r#"{
1485 "preferred_line_length": 99,
1486 "tab_size": 42
1487 }
1488 "#
1489 .unindent(),
1490 r#"{}"#.to_owned(),
1491 r#"{
1492 "preferred_line_length": 99,
1493 "tab_size": 42
1494 }
1495 "#
1496 .unindent(),
1497 cx,
1498 );
1499
1500 // custom enum
1501 check_vscode_import(
1502 &mut store,
1503 r#"{
1504 }
1505 "#
1506 .unindent(),
1507 r#"{ "workbench.editor.decorations.colors": true }"#.to_owned(),
1508 r#"{
1509 "tabs": {
1510 "git_status": true
1511 }
1512 }
1513 "#
1514 .unindent(),
1515 cx,
1516 );
1517 }
1518
1519 #[track_caller]
1520 fn check_vscode_import(
1521 store: &mut SettingsStore,
1522 old: String,
1523 vscode: String,
1524 expected: String,
1525 cx: &mut App,
1526 ) {
1527 store.set_user_settings(&old, cx).ok();
1528 let new = store.get_vscode_edits(
1529 old,
1530 &VsCodeSettings::from_str(&vscode, VsCodeSettingsSource::VsCode).unwrap(),
1531 );
1532 pretty_assertions::assert_eq!(new, expected);
1533 }
1534
1535 #[gpui::test]
1536 fn test_update_git_settings(cx: &mut App) {
1537 let store = SettingsStore::new(cx, &test_settings());
1538
1539 let actual = store.new_text_for_update("{}".to_string(), |current| {
1540 current
1541 .git
1542 .get_or_insert_default()
1543 .inline_blame
1544 .get_or_insert_default()
1545 .enabled = Some(true);
1546 });
1547 assert_eq!(
1548 actual,
1549 r#"{
1550 "git": {
1551 "inline_blame": {
1552 "enabled": true
1553 }
1554 }
1555 }
1556 "#
1557 .unindent()
1558 );
1559 }
1560
1561 #[gpui::test]
1562 fn test_global_settings(cx: &mut App) {
1563 let mut store = SettingsStore::new(cx, &test_settings());
1564 store.register_setting::<ItemSettings>(cx);
1565
1566 // Set global settings - these should override defaults but not user settings
1567 store
1568 .set_global_settings(
1569 r#"{
1570 "tabs": {
1571 "close_position": "right",
1572 "git_status": true,
1573 }
1574 }"#,
1575 cx,
1576 )
1577 .unwrap();
1578
1579 // Before user settings, global settings should apply
1580 assert_eq!(
1581 store.get::<ItemSettings>(None),
1582 &ItemSettings {
1583 close_position: ClosePosition::Right,
1584 git_status: true,
1585 }
1586 );
1587
1588 // Set user settings - these should override both defaults and global
1589 store
1590 .set_user_settings(
1591 r#"{
1592 "tabs": {
1593 "close_position": "left"
1594 }
1595 }"#,
1596 cx,
1597 )
1598 .unwrap();
1599
1600 // User settings should override global settings
1601 assert_eq!(
1602 store.get::<ItemSettings>(None),
1603 &ItemSettings {
1604 close_position: ClosePosition::Left,
1605 git_status: true, // Staff from global settings
1606 }
1607 );
1608 }
1609}