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