1use anyhow::{Context as _, Result};
2use collections::{BTreeMap, HashMap, btree_map, hash_map};
3use fs::Fs;
4use futures::{
5 FutureExt, StreamExt,
6 channel::{mpsc, oneshot},
7 future::LocalBoxFuture,
8};
9use gpui::{
10 App, AppContext, AsyncApp, BorrowAppContext, Entity, Global, SharedString, Task, UpdateGlobal,
11};
12
13use paths::{local_settings_file_relative_path, task_file_name};
14use schemars::{JsonSchema, json_schema};
15use serde_json::Value;
16use settings_content::ParseStatus;
17use std::{
18 any::{Any, TypeId, type_name},
19 fmt::Debug,
20 ops::Range,
21 path::{Path, PathBuf},
22 rc::Rc,
23 str,
24 sync::Arc,
25};
26use util::{
27 ResultExt as _,
28 rel_path::RelPath,
29 schemars::{AllowTrailingCommas, DefaultDenyUnknownFields, replace_subschema},
30};
31
32use crate::editorconfig_store::EditorconfigStore;
33
34use crate::{
35 ActiveSettingsProfileName, FontFamilyName, IconThemeName, LanguageSettingsContent,
36 LanguageToSettingsMap, LspSettings, LspSettingsMap, SemanticTokenRules, ThemeName,
37 UserSettingsContentExt, VsCodeSettings, WorktreeId,
38 settings_content::{
39 ExtensionsSettingsContent, ProjectSettingsContent, RootUserSettings, SettingsContent,
40 UserSettingsContent, merge_from::MergeFrom,
41 },
42};
43
44use settings_json::{infer_json_indent_size, update_value_in_json_text};
45
46pub const LSP_SETTINGS_SCHEMA_URL_PREFIX: &str = "zed://schemas/settings/lsp/";
47
48pub trait SettingsKey: 'static + Send + Sync {
49 /// The name of a key within the JSON file from which this setting should
50 /// be deserialized. If this is `None`, then the setting will be deserialized
51 /// from the root object.
52 const KEY: Option<&'static str>;
53
54 const FALLBACK_KEY: Option<&'static str> = None;
55}
56
57/// A value that can be defined as a user setting.
58///
59/// Settings can be loaded from a combination of multiple JSON files.
60pub trait Settings: 'static + Send + Sync + Sized {
61 /// The name of the keys in the [`FileContent`](Self::FileContent) that should
62 /// always be written to a settings file, even if their value matches the default
63 /// value.
64 ///
65 /// This is useful for tagged [`FileContent`](Self::FileContent)s where the tag
66 /// is a "version" field that should always be persisted, even if the current
67 /// user settings match the current version of the settings.
68 const PRESERVED_KEYS: Option<&'static [&'static str]> = None;
69
70 /// Read the value from default.json.
71 ///
72 /// This function *should* panic if default values are missing,
73 /// and you should add a default to default.json for documentation.
74 fn from_settings(content: &SettingsContent) -> Self;
75
76 #[track_caller]
77 fn register(cx: &mut App)
78 where
79 Self: Sized,
80 {
81 SettingsStore::update_global(cx, |store, _| {
82 store.register_setting::<Self>();
83 });
84 }
85
86 #[track_caller]
87 fn get<'a>(path: Option<SettingsLocation>, cx: &'a App) -> &'a Self
88 where
89 Self: Sized,
90 {
91 cx.global::<SettingsStore>().get(path)
92 }
93
94 #[track_caller]
95 fn get_global(cx: &App) -> &Self
96 where
97 Self: Sized,
98 {
99 cx.global::<SettingsStore>().get(None)
100 }
101
102 #[track_caller]
103 fn try_get(cx: &App) -> Option<&Self>
104 where
105 Self: Sized,
106 {
107 if cx.has_global::<SettingsStore>() {
108 cx.global::<SettingsStore>().try_get(None)
109 } else {
110 None
111 }
112 }
113
114 #[track_caller]
115 fn try_read_global<R>(cx: &AsyncApp, f: impl FnOnce(&Self) -> R) -> Option<R>
116 where
117 Self: Sized,
118 {
119 cx.try_read_global(|s: &SettingsStore, _| f(s.get(None)))
120 }
121
122 #[track_caller]
123 fn override_global(settings: Self, cx: &mut App)
124 where
125 Self: Sized,
126 {
127 cx.global_mut::<SettingsStore>().override_global(settings)
128 }
129}
130
131pub struct RegisteredSetting {
132 pub settings_value: fn() -> Box<dyn AnySettingValue>,
133 pub from_settings: fn(&SettingsContent) -> Box<dyn Any>,
134 pub id: fn() -> TypeId,
135}
136
137inventory::collect!(RegisteredSetting);
138
139#[derive(Clone, Copy, Debug)]
140pub struct SettingsLocation<'a> {
141 pub worktree_id: WorktreeId,
142 pub path: &'a RelPath,
143}
144
145pub struct SettingsStore {
146 setting_values: HashMap<TypeId, Box<dyn AnySettingValue>>,
147 default_settings: Rc<SettingsContent>,
148 user_settings: Option<UserSettingsContent>,
149 global_settings: Option<Box<SettingsContent>>,
150
151 extension_settings: Option<Box<SettingsContent>>,
152 server_settings: Option<Box<SettingsContent>>,
153
154 language_semantic_token_rules: HashMap<SharedString, SemanticTokenRules>,
155
156 merged_settings: Rc<SettingsContent>,
157
158 local_settings: BTreeMap<(WorktreeId, Arc<RelPath>), SettingsContent>,
159 pub editorconfig_store: Entity<EditorconfigStore>,
160
161 _setting_file_updates: Task<()>,
162 setting_file_updates_tx:
163 mpsc::UnboundedSender<Box<dyn FnOnce(AsyncApp) -> LocalBoxFuture<'static, Result<()>>>>,
164 file_errors: BTreeMap<SettingsFile, SettingsParseResult>,
165}
166
167#[derive(Clone, PartialEq, Eq, Debug)]
168pub enum SettingsFile {
169 Default,
170 Global,
171 User,
172 Server,
173 /// Represents project settings in ssh projects as well as local projects
174 Project((WorktreeId, Arc<RelPath>)),
175}
176
177impl PartialOrd for SettingsFile {
178 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
179 Some(self.cmp(other))
180 }
181}
182
183/// Sorted in order of precedence
184impl Ord for SettingsFile {
185 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
186 use SettingsFile::*;
187 use std::cmp::Ordering;
188 match (self, other) {
189 (User, User) => Ordering::Equal,
190 (Server, Server) => Ordering::Equal,
191 (Default, Default) => Ordering::Equal,
192 (Project((id1, rel_path1)), Project((id2, rel_path2))) => id1
193 .cmp(id2)
194 .then_with(|| rel_path1.cmp(rel_path2).reverse()),
195 (Project(_), _) => Ordering::Less,
196 (_, Project(_)) => Ordering::Greater,
197 (Server, _) => Ordering::Less,
198 (_, Server) => Ordering::Greater,
199 (User, _) => Ordering::Less,
200 (_, User) => Ordering::Greater,
201 (Global, _) => Ordering::Less,
202 (_, Global) => Ordering::Greater,
203 }
204 }
205}
206
207#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
208pub enum LocalSettingsKind {
209 Settings,
210 Tasks,
211 Editorconfig,
212 Debug,
213}
214
215#[derive(Clone, Debug, PartialEq, Eq, Hash)]
216pub enum LocalSettingsPath {
217 InWorktree(Arc<RelPath>),
218 OutsideWorktree(Arc<Path>),
219}
220
221impl LocalSettingsPath {
222 pub fn is_outside_worktree(&self) -> bool {
223 matches!(self, Self::OutsideWorktree(_))
224 }
225
226 pub fn to_proto(&self) -> String {
227 match self {
228 Self::InWorktree(path) => path.to_proto(),
229 Self::OutsideWorktree(path) => path.to_string_lossy().to_string(),
230 }
231 }
232
233 pub fn from_proto(path: &str, is_outside_worktree: bool) -> anyhow::Result<Self> {
234 if is_outside_worktree {
235 Ok(Self::OutsideWorktree(PathBuf::from(path).into()))
236 } else {
237 Ok(Self::InWorktree(RelPath::from_proto(path)?))
238 }
239 }
240}
241
242impl Global for SettingsStore {}
243
244#[doc(hidden)]
245#[derive(Debug)]
246pub struct SettingValue<T> {
247 #[doc(hidden)]
248 pub global_value: Option<T>,
249 #[doc(hidden)]
250 pub local_values: Vec<(WorktreeId, Arc<RelPath>, T)>,
251}
252
253#[doc(hidden)]
254pub trait AnySettingValue: 'static + Send + Sync {
255 fn setting_type_name(&self) -> &'static str;
256
257 fn from_settings(&self, s: &SettingsContent) -> Box<dyn Any>;
258
259 fn value_for_path(&self, path: Option<SettingsLocation>) -> &dyn Any;
260 fn all_local_values(&self) -> Vec<(WorktreeId, Arc<RelPath>, &dyn Any)>;
261 fn set_global_value(&mut self, value: Box<dyn Any>);
262 fn set_local_value(&mut self, root_id: WorktreeId, path: Arc<RelPath>, value: Box<dyn Any>);
263 fn clear_local_values(&mut self, root_id: WorktreeId);
264}
265
266/// Parameters that are used when generating some JSON schemas at runtime.
267pub struct SettingsJsonSchemaParams<'a> {
268 pub language_names: &'a [String],
269 pub font_names: &'a [String],
270 pub theme_names: &'a [SharedString],
271 pub icon_theme_names: &'a [SharedString],
272 pub lsp_adapter_names: &'a [String],
273}
274
275impl SettingsStore {
276 pub fn new(cx: &mut App, default_settings: &str) -> Self {
277 Self::new_with_semantic_tokens(cx, default_settings, &crate::default_semantic_token_rules())
278 }
279
280 pub fn new_with_semantic_tokens(
281 cx: &mut App,
282 default_settings: &str,
283 default_semantic_tokens: &str,
284 ) -> Self {
285 let (setting_file_updates_tx, mut setting_file_updates_rx) = mpsc::unbounded();
286 let mut default_settings: SettingsContent =
287 SettingsContent::parse_json_with_comments(default_settings).unwrap();
288 if let Ok(semantic_token_rules) =
289 crate::parse_json_with_comments::<SemanticTokenRules>(default_semantic_tokens)
290 {
291 let global_lsp = default_settings
292 .global_lsp_settings
293 .get_or_insert_with(Default::default);
294 let existing_rules = global_lsp
295 .semantic_token_rules
296 .get_or_insert_with(Default::default);
297 existing_rules.rules.extend(semantic_token_rules.rules);
298 }
299
300 let default_settings: Rc<SettingsContent> = default_settings.into();
301 let mut this = Self {
302 setting_values: Default::default(),
303 default_settings: default_settings.clone(),
304 global_settings: None,
305 server_settings: None,
306 user_settings: None,
307 extension_settings: None,
308 language_semantic_token_rules: HashMap::default(),
309
310 merged_settings: default_settings,
311 local_settings: BTreeMap::default(),
312 editorconfig_store: cx.new(|_| EditorconfigStore::default()),
313 setting_file_updates_tx,
314 _setting_file_updates: cx.spawn(async move |cx| {
315 while let Some(setting_file_update) = setting_file_updates_rx.next().await {
316 (setting_file_update)(cx.clone()).await.log_err();
317 }
318 }),
319 file_errors: BTreeMap::default(),
320 };
321
322 this.load_settings_types();
323
324 this
325 }
326
327 pub fn observe_active_settings_profile_name(cx: &mut App) -> gpui::Subscription {
328 cx.observe_global::<ActiveSettingsProfileName>(|cx| {
329 Self::update_global(cx, |store, cx| {
330 store.recompute_values(None, cx);
331 });
332 })
333 }
334
335 pub fn update<C, R>(cx: &mut C, f: impl FnOnce(&mut Self, &mut C) -> R) -> R
336 where
337 C: BorrowAppContext,
338 {
339 cx.update_global(f)
340 }
341
342 /// Add a new type of setting to the store.
343 pub fn register_setting<T: Settings>(&mut self) {
344 self.register_setting_internal(&RegisteredSetting {
345 settings_value: || {
346 Box::new(SettingValue::<T> {
347 global_value: None,
348 local_values: Vec::new(),
349 })
350 },
351 from_settings: |content| Box::new(T::from_settings(content)),
352 id: || TypeId::of::<T>(),
353 });
354 }
355
356 fn load_settings_types(&mut self) {
357 for registered_setting in inventory::iter::<RegisteredSetting>() {
358 self.register_setting_internal(registered_setting);
359 }
360 }
361
362 fn register_setting_internal(&mut self, registered_setting: &RegisteredSetting) {
363 let entry = self.setting_values.entry((registered_setting.id)());
364
365 if matches!(entry, hash_map::Entry::Occupied(_)) {
366 return;
367 }
368
369 let setting_value = entry.or_insert((registered_setting.settings_value)());
370 let value = (registered_setting.from_settings)(&self.merged_settings);
371 setting_value.set_global_value(value);
372 }
373
374 /// Get the value of a setting.
375 ///
376 /// Panics if the given setting type has not been registered, or if there is no
377 /// value for this setting.
378 pub fn get<T: Settings>(&self, path: Option<SettingsLocation>) -> &T {
379 self.setting_values
380 .get(&TypeId::of::<T>())
381 .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()))
382 .value_for_path(path)
383 .downcast_ref::<T>()
384 .expect("no default value for setting type")
385 }
386
387 /// Get the value of a setting.
388 ///
389 /// Does not panic
390 pub fn try_get<T: Settings>(&self, path: Option<SettingsLocation>) -> Option<&T> {
391 self.setting_values
392 .get(&TypeId::of::<T>())
393 .map(|value| value.value_for_path(path))
394 .and_then(|value| value.downcast_ref::<T>())
395 }
396
397 /// Get all values from project specific settings
398 pub fn get_all_locals<T: Settings>(&self) -> Vec<(WorktreeId, Arc<RelPath>, &T)> {
399 self.setting_values
400 .get(&TypeId::of::<T>())
401 .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()))
402 .all_local_values()
403 .into_iter()
404 .map(|(id, path, any)| {
405 (
406 id,
407 path,
408 any.downcast_ref::<T>()
409 .expect("wrong value type for setting"),
410 )
411 })
412 .collect()
413 }
414
415 /// Override the global value for a setting.
416 ///
417 /// The given value will be overwritten if the user settings file changes.
418 pub fn override_global<T: Settings>(&mut self, value: T) {
419 self.setting_values
420 .get_mut(&TypeId::of::<T>())
421 .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()))
422 .set_global_value(Box::new(value))
423 }
424
425 /// Get the user's settings content.
426 ///
427 /// For user-facing functionality use the typed setting interface.
428 /// (e.g. ProjectSettings::get_global(cx))
429 pub fn raw_user_settings(&self) -> Option<&UserSettingsContent> {
430 self.user_settings.as_ref()
431 }
432
433 /// Get the default settings content as a raw JSON value.
434 pub fn raw_default_settings(&self) -> &SettingsContent {
435 &self.default_settings
436 }
437
438 /// Get the configured settings profile names.
439 pub fn configured_settings_profiles(&self) -> impl Iterator<Item = &str> {
440 self.user_settings
441 .iter()
442 .flat_map(|settings| settings.profiles.keys().map(|k| k.as_str()))
443 }
444
445 #[cfg(any(test, feature = "test-support"))]
446 pub fn test(cx: &mut App) -> Self {
447 Self::new(cx, &crate::test_settings())
448 }
449
450 /// Updates the value of a setting in the user's global configuration.
451 ///
452 /// This is only for tests. Normally, settings are only loaded from
453 /// JSON files.
454 #[cfg(any(test, feature = "test-support"))]
455 pub fn update_user_settings(
456 &mut self,
457 cx: &mut App,
458 update: impl FnOnce(&mut SettingsContent),
459 ) {
460 let mut content = self.user_settings.clone().unwrap_or_default().content;
461 update(&mut content);
462 fn trail(this: &mut SettingsStore, content: Box<SettingsContent>, cx: &mut App) {
463 let new_text = serde_json::to_string(&UserSettingsContent {
464 content,
465 ..Default::default()
466 })
467 .unwrap();
468 _ = this.set_user_settings(&new_text, cx);
469 }
470 trail(self, content, cx);
471 }
472
473 pub async fn load_settings(fs: &Arc<dyn Fs>) -> Result<String> {
474 match fs.load(paths::settings_file()).await {
475 result @ Ok(_) => result,
476 Err(err) => {
477 if let Some(e) = err.downcast_ref::<std::io::Error>()
478 && e.kind() == std::io::ErrorKind::NotFound
479 {
480 return Ok(crate::initial_user_settings_content().to_string());
481 }
482 Err(err)
483 }
484 }
485 }
486
487 fn update_settings_file_inner(
488 &self,
489 fs: Arc<dyn Fs>,
490 update: impl 'static + Send + FnOnce(String, AsyncApp) -> Result<String>,
491 ) -> oneshot::Receiver<Result<()>> {
492 let (tx, rx) = oneshot::channel::<Result<()>>();
493 self.setting_file_updates_tx
494 .unbounded_send(Box::new(move |cx: AsyncApp| {
495 async move {
496 let res = async move {
497 let old_text = Self::load_settings(&fs).await?;
498 let new_text = update(old_text, cx)?;
499 let settings_path = paths::settings_file().as_path();
500 if fs.is_file(settings_path).await {
501 let resolved_path =
502 fs.canonicalize(settings_path).await.with_context(|| {
503 format!(
504 "Failed to canonicalize settings path {:?}",
505 settings_path
506 )
507 })?;
508
509 fs.atomic_write(resolved_path.clone(), new_text)
510 .await
511 .with_context(|| {
512 format!("Failed to write settings to file {:?}", resolved_path)
513 })?;
514 } else {
515 fs.atomic_write(settings_path.to_path_buf(), new_text)
516 .await
517 .with_context(|| {
518 format!("Failed to write settings to file {:?}", settings_path)
519 })?;
520 }
521 anyhow::Ok(())
522 }
523 .await;
524
525 let new_res = match &res {
526 Ok(_) => anyhow::Ok(()),
527 Err(e) => Err(anyhow::anyhow!("Failed to write settings to file {:?}", e)),
528 };
529
530 _ = tx.send(new_res);
531 res
532 }
533 .boxed_local()
534 }))
535 .map_err(|err| anyhow::format_err!("Failed to update settings file: {}", err))
536 .log_with_level(log::Level::Warn);
537 return rx;
538 }
539
540 pub fn update_settings_file(
541 &self,
542 fs: Arc<dyn Fs>,
543 update: impl 'static + Send + FnOnce(&mut SettingsContent, &App),
544 ) {
545 _ = self.update_settings_file_inner(fs, move |old_text: String, cx: AsyncApp| {
546 Ok(cx.read_global(|store: &SettingsStore, cx| {
547 store.new_text_for_update(old_text, |content| update(content, cx))
548 }))
549 });
550 }
551
552 pub fn import_vscode_settings(
553 &self,
554 fs: Arc<dyn Fs>,
555 vscode_settings: VsCodeSettings,
556 ) -> oneshot::Receiver<Result<()>> {
557 self.update_settings_file_inner(fs, move |old_text: String, cx: AsyncApp| {
558 Ok(cx.read_global(|store: &SettingsStore, _cx| {
559 store.get_vscode_edits(old_text, &vscode_settings)
560 }))
561 })
562 }
563
564 pub fn get_all_files(&self) -> Vec<SettingsFile> {
565 let mut files = Vec::from_iter(
566 self.local_settings
567 .keys()
568 // rev because these are sorted by path, so highest precedence is last
569 .rev()
570 .cloned()
571 .map(SettingsFile::Project),
572 );
573
574 if self.server_settings.is_some() {
575 files.push(SettingsFile::Server);
576 }
577 // ignoring profiles
578 // ignoring os profiles
579 // ignoring release channel profiles
580 // ignoring global
581 // ignoring extension
582
583 if self.user_settings.is_some() {
584 files.push(SettingsFile::User);
585 }
586 files.push(SettingsFile::Default);
587 files
588 }
589
590 pub fn get_content_for_file(&self, file: SettingsFile) -> Option<&SettingsContent> {
591 match file {
592 SettingsFile::User => self
593 .user_settings
594 .as_ref()
595 .map(|settings| settings.content.as_ref()),
596 SettingsFile::Default => Some(self.default_settings.as_ref()),
597 SettingsFile::Server => self.server_settings.as_deref(),
598 SettingsFile::Project(ref key) => self.local_settings.get(key),
599 SettingsFile::Global => self.global_settings.as_deref(),
600 }
601 }
602
603 pub fn get_overrides_for_field<T>(
604 &self,
605 target_file: SettingsFile,
606 get: fn(&SettingsContent) -> &Option<T>,
607 ) -> Vec<SettingsFile> {
608 let all_files = self.get_all_files();
609 let mut found_file = false;
610 let mut overrides = Vec::new();
611
612 for file in all_files.into_iter().rev() {
613 if !found_file {
614 found_file = file == target_file;
615 continue;
616 }
617
618 if let SettingsFile::Project((wt_id, ref path)) = file
619 && let SettingsFile::Project((target_wt_id, ref target_path)) = target_file
620 && (wt_id != target_wt_id || !target_path.starts_with(path))
621 {
622 // if requesting value from a local file, don't return values from local files in different worktrees
623 continue;
624 }
625
626 let Some(content) = self.get_content_for_file(file.clone()) else {
627 continue;
628 };
629 if get(content).is_some() {
630 overrides.push(file);
631 }
632 }
633
634 overrides
635 }
636
637 /// Checks the given file, and files that the passed file overrides for the given field.
638 /// Returns the first file found that contains the value.
639 /// The value will only be None if no file contains the value.
640 /// I.e. if no file contains the value, returns `(File::Default, None)`
641 pub fn get_value_from_file<'a, T: 'a>(
642 &'a self,
643 target_file: SettingsFile,
644 pick: fn(&'a SettingsContent) -> Option<T>,
645 ) -> (SettingsFile, Option<T>) {
646 self.get_value_from_file_inner(target_file, pick, true)
647 }
648
649 /// Same as `Self::get_value_from_file` except that it does not include the current file.
650 /// Therefore it returns the value that was potentially overloaded by the target file.
651 pub fn get_value_up_to_file<'a, T: 'a>(
652 &'a self,
653 target_file: SettingsFile,
654 pick: fn(&'a SettingsContent) -> Option<T>,
655 ) -> (SettingsFile, Option<T>) {
656 self.get_value_from_file_inner(target_file, pick, false)
657 }
658
659 fn get_value_from_file_inner<'a, T: 'a>(
660 &'a self,
661 target_file: SettingsFile,
662 pick: fn(&'a SettingsContent) -> Option<T>,
663 include_target_file: bool,
664 ) -> (SettingsFile, Option<T>) {
665 // todo(settings_ui): Add a metadata field for overriding the "overrides" tag, for contextually different settings
666 // e.g. disable AI isn't overridden, or a vec that gets extended instead or some such
667
668 // todo(settings_ui) cache all files
669 let all_files = self.get_all_files();
670 let mut found_file = false;
671
672 for file in all_files.into_iter() {
673 if !found_file && file != SettingsFile::Default {
674 if file != target_file {
675 continue;
676 }
677 found_file = true;
678 if !include_target_file {
679 continue;
680 }
681 }
682
683 if let SettingsFile::Project((worktree_id, ref path)) = file
684 && let SettingsFile::Project((target_worktree_id, ref target_path)) = target_file
685 && (worktree_id != target_worktree_id || !target_path.starts_with(&path))
686 {
687 // if requesting value from a local file, don't return values from local files in different worktrees
688 continue;
689 }
690
691 let Some(content) = self.get_content_for_file(file.clone()) else {
692 continue;
693 };
694 if let Some(value) = pick(content) {
695 return (file, Some(value));
696 }
697 }
698
699 (SettingsFile::Default, None)
700 }
701
702 #[inline(always)]
703 fn parse_and_migrate_zed_settings<SettingsContentType: RootUserSettings>(
704 &mut self,
705 user_settings_content: &str,
706 file: SettingsFile,
707 ) -> (Option<SettingsContentType>, SettingsParseResult) {
708 let mut migration_status = MigrationStatus::NotNeeded;
709 let (settings, parse_status) = if user_settings_content.is_empty() {
710 SettingsContentType::parse_json("{}")
711 } else {
712 let migration_res = migrator::migrate_settings(user_settings_content);
713 migration_status = match &migration_res {
714 Ok(Some(_)) => MigrationStatus::Succeeded,
715 Ok(None) => MigrationStatus::NotNeeded,
716 Err(err) => MigrationStatus::Failed {
717 error: err.to_string(),
718 },
719 };
720 let content = match &migration_res {
721 Ok(Some(content)) => content,
722 Ok(None) => user_settings_content,
723 Err(_) => user_settings_content,
724 };
725 SettingsContentType::parse_json(content)
726 };
727
728 let result = SettingsParseResult {
729 parse_status,
730 migration_status,
731 };
732 self.file_errors.insert(file, result.clone());
733 return (settings, result);
734 }
735
736 pub fn error_for_file(&self, file: SettingsFile) -> Option<SettingsParseResult> {
737 self.file_errors
738 .get(&file)
739 .filter(|parse_result| parse_result.requires_user_action())
740 .cloned()
741 }
742}
743
744impl SettingsStore {
745 /// Updates the value of a setting in a JSON file, returning the new text
746 /// for that JSON file.
747 pub fn new_text_for_update(
748 &self,
749 old_text: String,
750 update: impl FnOnce(&mut SettingsContent),
751 ) -> String {
752 let edits = self.edits_for_update(&old_text, update);
753 let mut new_text = old_text;
754 for (range, replacement) in edits.into_iter() {
755 new_text.replace_range(range, &replacement);
756 }
757 new_text
758 }
759
760 pub fn get_vscode_edits(&self, old_text: String, vscode: &VsCodeSettings) -> String {
761 self.new_text_for_update(old_text, |content| {
762 content.merge_from(&vscode.settings_content())
763 })
764 }
765
766 /// Updates the value of a setting in a JSON file, returning a list
767 /// of edits to apply to the JSON file.
768 pub fn edits_for_update(
769 &self,
770 text: &str,
771 update: impl FnOnce(&mut SettingsContent),
772 ) -> Vec<(Range<usize>, String)> {
773 let old_content = UserSettingsContent::parse_json_with_comments(text)
774 .log_err()
775 .unwrap_or_default();
776 let mut new_content = old_content.clone();
777 update(&mut new_content.content);
778
779 let old_value = serde_json::to_value(&old_content).unwrap();
780 let new_value = serde_json::to_value(new_content).unwrap();
781
782 let mut key_path = Vec::new();
783 let mut edits = Vec::new();
784 let tab_size = infer_json_indent_size(&text);
785 let mut text = text.to_string();
786 update_value_in_json_text(
787 &mut text,
788 &mut key_path,
789 tab_size,
790 &old_value,
791 &new_value,
792 &mut edits,
793 );
794 edits
795 }
796
797 /// Sets the default settings via a JSON string.
798 ///
799 /// The string should contain a JSON object with a default value for every setting.
800 pub fn set_default_settings(
801 &mut self,
802 default_settings_content: &str,
803 cx: &mut App,
804 ) -> Result<()> {
805 self.default_settings =
806 SettingsContent::parse_json_with_comments(default_settings_content)?.into();
807 self.recompute_values(None, cx);
808 Ok(())
809 }
810
811 /// Sets the user settings via a JSON string.
812 #[must_use]
813 pub fn set_user_settings(
814 &mut self,
815 user_settings_content: &str,
816 cx: &mut App,
817 ) -> SettingsParseResult {
818 let (settings, parse_result) = self.parse_and_migrate_zed_settings::<UserSettingsContent>(
819 user_settings_content,
820 SettingsFile::User,
821 );
822
823 if let Some(settings) = settings {
824 self.user_settings = Some(settings);
825 self.recompute_values(None, cx);
826 }
827 return parse_result;
828 }
829
830 /// Sets the global settings via a JSON string.
831 #[must_use]
832 pub fn set_global_settings(
833 &mut self,
834 global_settings_content: &str,
835 cx: &mut App,
836 ) -> SettingsParseResult {
837 let (settings, parse_result) = self.parse_and_migrate_zed_settings::<SettingsContent>(
838 global_settings_content,
839 SettingsFile::Global,
840 );
841
842 if let Some(settings) = settings {
843 self.global_settings = Some(Box::new(settings));
844 self.recompute_values(None, cx);
845 }
846 return parse_result;
847 }
848
849 pub fn set_server_settings(
850 &mut self,
851 server_settings_content: &str,
852 cx: &mut App,
853 ) -> Result<()> {
854 let settings = if server_settings_content.is_empty() {
855 None
856 } else {
857 Option::<SettingsContent>::parse_json_with_comments(server_settings_content)?
858 };
859
860 // Rewrite the server settings into a content type
861 self.server_settings = settings.map(|settings| Box::new(settings));
862
863 self.recompute_values(None, cx);
864 Ok(())
865 }
866
867 /// Sets language-specific semantic token rules.
868 ///
869 /// These rules are registered by language modules (e.g. the Rust language module)
870 /// and are stored separately from the global rules. They are only applied to
871 /// buffers of the matching language by the `SemanticTokenStylizer`.
872 ///
873 /// These should be registered before any `SemanticTokenStylizer` instances are
874 /// created (typically during `languages::init`), as existing cached stylizers
875 /// are not automatically invalidated.
876 pub fn set_language_semantic_token_rules(
877 &mut self,
878 language: SharedString,
879 rules: SemanticTokenRules,
880 ) {
881 self.language_semantic_token_rules.insert(language, rules);
882 }
883
884 /// Returns the language-specific semantic token rules for the given language,
885 /// if any have been registered.
886 pub fn language_semantic_token_rules(&self, language: &str) -> Option<&SemanticTokenRules> {
887 self.language_semantic_token_rules.get(language)
888 }
889
890 /// Add or remove a set of local settings via a JSON string.
891 pub fn set_local_settings(
892 &mut self,
893 root_id: WorktreeId,
894 path: LocalSettingsPath,
895 kind: LocalSettingsKind,
896 settings_content: Option<&str>,
897 cx: &mut App,
898 ) -> std::result::Result<(), InvalidSettingsError> {
899 let content = settings_content
900 .map(|content| content.trim())
901 .filter(|content| !content.is_empty());
902 let mut zed_settings_changed = false;
903 match (path.clone(), kind, content) {
904 (LocalSettingsPath::InWorktree(directory_path), LocalSettingsKind::Tasks, _) => {
905 return Err(InvalidSettingsError::Tasks {
906 message: "Attempted to submit tasks into the settings store".to_string(),
907 path: directory_path
908 .join(RelPath::unix(task_file_name()).unwrap())
909 .as_std_path()
910 .to_path_buf(),
911 });
912 }
913 (LocalSettingsPath::InWorktree(directory_path), LocalSettingsKind::Debug, _) => {
914 return Err(InvalidSettingsError::Debug {
915 message: "Attempted to submit debugger config into the settings store"
916 .to_string(),
917 path: directory_path
918 .join(RelPath::unix(task_file_name()).unwrap())
919 .as_std_path()
920 .to_path_buf(),
921 });
922 }
923 (LocalSettingsPath::InWorktree(directory_path), LocalSettingsKind::Settings, None) => {
924 zed_settings_changed = self
925 .local_settings
926 .remove(&(root_id, directory_path.clone()))
927 .is_some();
928 self.file_errors
929 .remove(&SettingsFile::Project((root_id, directory_path)));
930 }
931 (
932 LocalSettingsPath::InWorktree(directory_path),
933 LocalSettingsKind::Settings,
934 Some(settings_contents),
935 ) => {
936 let (new_settings, parse_result) = self
937 .parse_and_migrate_zed_settings::<ProjectSettingsContent>(
938 settings_contents,
939 SettingsFile::Project((root_id, directory_path.clone())),
940 );
941 match parse_result.parse_status {
942 ParseStatus::Success => Ok(()),
943 ParseStatus::Failed { error } => Err(InvalidSettingsError::LocalSettings {
944 path: directory_path.join(local_settings_file_relative_path()),
945 message: error,
946 }),
947 }?;
948 if let Some(new_settings) = new_settings {
949 match self.local_settings.entry((root_id, directory_path)) {
950 btree_map::Entry::Vacant(v) => {
951 v.insert(SettingsContent {
952 project: new_settings,
953 ..Default::default()
954 });
955 zed_settings_changed = true;
956 }
957 btree_map::Entry::Occupied(mut o) => {
958 if &o.get().project != &new_settings {
959 o.insert(SettingsContent {
960 project: new_settings,
961 ..Default::default()
962 });
963 zed_settings_changed = true;
964 }
965 }
966 }
967 }
968 }
969 (directory_path, LocalSettingsKind::Editorconfig, editorconfig_contents) => {
970 self.editorconfig_store.update(cx, |store, _| {
971 store.set_configs(root_id, directory_path, editorconfig_contents)
972 })?;
973 }
974 (LocalSettingsPath::OutsideWorktree(path), kind, _) => {
975 log::error!(
976 "OutsideWorktree path {:?} with kind {:?} is only supported by editorconfig",
977 path,
978 kind
979 );
980 return Ok(());
981 }
982 }
983 if let LocalSettingsPath::InWorktree(directory_path) = &path {
984 if zed_settings_changed {
985 self.recompute_values(Some((root_id, &directory_path)), cx);
986 }
987 }
988 Ok(())
989 }
990
991 pub fn set_extension_settings(
992 &mut self,
993 content: ExtensionsSettingsContent,
994 cx: &mut App,
995 ) -> Result<()> {
996 self.extension_settings = Some(Box::new(SettingsContent {
997 project: ProjectSettingsContent {
998 all_languages: content.all_languages,
999 ..Default::default()
1000 },
1001 ..Default::default()
1002 }));
1003 self.recompute_values(None, cx);
1004 Ok(())
1005 }
1006
1007 /// Add or remove a set of local settings via a JSON string.
1008 pub fn clear_local_settings(&mut self, root_id: WorktreeId, cx: &mut App) -> Result<()> {
1009 self.local_settings
1010 .retain(|(worktree_id, _), _| worktree_id != &root_id);
1011
1012 self.editorconfig_store
1013 .update(cx, |store, _cx| store.remove_for_worktree(root_id));
1014
1015 for setting_value in self.setting_values.values_mut() {
1016 setting_value.clear_local_values(root_id);
1017 }
1018 self.recompute_values(Some((root_id, RelPath::empty())), cx);
1019 Ok(())
1020 }
1021
1022 pub fn local_settings(
1023 &self,
1024 root_id: WorktreeId,
1025 ) -> impl '_ + Iterator<Item = (Arc<RelPath>, &ProjectSettingsContent)> {
1026 self.local_settings
1027 .range(
1028 (root_id, RelPath::empty().into())
1029 ..(
1030 WorktreeId::from_usize(root_id.to_usize() + 1),
1031 RelPath::empty().into(),
1032 ),
1033 )
1034 .map(|((_, path), content)| (path.clone(), &content.project))
1035 }
1036
1037 /// Configures common schema replacements shared between user and project
1038 /// settings schemas.
1039 ///
1040 /// This sets up language-specific settings and LSP adapter settings that
1041 /// are valid in both user and project settings.
1042 fn configure_schema_generator(
1043 generator: &mut schemars::SchemaGenerator,
1044 params: &SettingsJsonSchemaParams,
1045 ) {
1046 let language_settings_content_ref = generator
1047 .subschema_for::<LanguageSettingsContent>()
1048 .to_value();
1049
1050 replace_subschema::<LanguageToSettingsMap>(generator, || {
1051 json_schema!({
1052 "type": "object",
1053 "errorMessage": "No language with this name is installed.",
1054 "properties": params.language_names.iter().map(|name| (name.clone(), language_settings_content_ref.clone())).collect::<serde_json::Map<_, _>>()
1055 })
1056 });
1057
1058 generator.subschema_for::<LspSettings>();
1059
1060 let lsp_settings_definition = generator
1061 .definitions()
1062 .get("LspSettings")
1063 .expect("LspSettings should be defined")
1064 .clone();
1065
1066 replace_subschema::<LspSettingsMap>(generator, || {
1067 let mut lsp_properties = serde_json::Map::new();
1068
1069 for adapter_name in params.lsp_adapter_names {
1070 let mut base_lsp_settings = lsp_settings_definition
1071 .as_object()
1072 .expect("LspSettings should be an object")
1073 .clone();
1074
1075 if let Some(properties) = base_lsp_settings.get_mut("properties") {
1076 if let Some(properties_object) = properties.as_object_mut() {
1077 properties_object.insert(
1078 "initialization_options".to_string(),
1079 serde_json::json!({
1080 "$ref": format!("{LSP_SETTINGS_SCHEMA_URL_PREFIX}{adapter_name}/initialization_options")
1081 }),
1082 );
1083 properties_object.insert(
1084 "settings".to_string(),
1085 serde_json::json!({
1086 "$ref": format!("{LSP_SETTINGS_SCHEMA_URL_PREFIX}{adapter_name}/settings")
1087 }),
1088 );
1089 }
1090 }
1091
1092 lsp_properties.insert(
1093 adapter_name.clone(),
1094 serde_json::Value::Object(base_lsp_settings),
1095 );
1096 }
1097
1098 json_schema!({
1099 "type": "object",
1100 "properties": lsp_properties
1101 })
1102 });
1103 }
1104
1105 pub fn json_schema(&self, params: &SettingsJsonSchemaParams) -> Value {
1106 let mut generator = schemars::generate::SchemaSettings::draft2019_09()
1107 .with_transform(DefaultDenyUnknownFields)
1108 .with_transform(AllowTrailingCommas)
1109 .into_generator();
1110
1111 UserSettingsContent::json_schema(&mut generator);
1112 Self::configure_schema_generator(&mut generator, params);
1113
1114 replace_subschema::<FontFamilyName>(&mut generator, || {
1115 json_schema!({
1116 "type": "string",
1117 "enum": params.font_names,
1118 })
1119 });
1120
1121 replace_subschema::<ThemeName>(&mut generator, || {
1122 json_schema!({
1123 "type": "string",
1124 "enum": params.theme_names,
1125 })
1126 });
1127
1128 replace_subschema::<IconThemeName>(&mut generator, || {
1129 json_schema!({
1130 "type": "string",
1131 "enum": params.icon_theme_names,
1132 })
1133 });
1134
1135 generator
1136 .root_schema_for::<UserSettingsContent>()
1137 .to_value()
1138 }
1139
1140 /// Generate JSON schema for project settings, including only settings valid
1141 /// for project-level configurations.
1142 pub fn project_json_schema(&self, params: &SettingsJsonSchemaParams) -> Value {
1143 let mut generator = schemars::generate::SchemaSettings::draft2019_09()
1144 .with_transform(DefaultDenyUnknownFields)
1145 .with_transform(AllowTrailingCommas)
1146 .into_generator();
1147
1148 ProjectSettingsContent::json_schema(&mut generator);
1149 Self::configure_schema_generator(&mut generator, params);
1150
1151 generator
1152 .root_schema_for::<ProjectSettingsContent>()
1153 .to_value()
1154 }
1155
1156 fn recompute_values(
1157 &mut self,
1158 changed_local_path: Option<(WorktreeId, &RelPath)>,
1159 cx: &mut App,
1160 ) {
1161 // Reload the global and local values for every setting.
1162 let mut project_settings_stack = Vec::<SettingsContent>::new();
1163 let mut paths_stack = Vec::<Option<(WorktreeId, &RelPath)>>::new();
1164
1165 if changed_local_path.is_none() {
1166 let mut merged = self.default_settings.as_ref().clone();
1167 merged.merge_from_option(self.extension_settings.as_deref());
1168 merged.merge_from_option(self.global_settings.as_deref());
1169 if let Some(user_settings) = self.user_settings.as_ref() {
1170 merged.merge_from(&user_settings.content);
1171 merged.merge_from_option(user_settings.for_release_channel());
1172 merged.merge_from_option(user_settings.for_os());
1173 merged.merge_from_option(user_settings.for_profile(cx));
1174 }
1175 merged.merge_from_option(self.server_settings.as_deref());
1176 self.merged_settings = Rc::new(merged);
1177
1178 for setting_value in self.setting_values.values_mut() {
1179 let value = setting_value.from_settings(&self.merged_settings);
1180 setting_value.set_global_value(value);
1181 }
1182 }
1183
1184 for ((root_id, directory_path), local_settings) in &self.local_settings {
1185 // Build a stack of all of the local values for that setting.
1186 while let Some(prev_entry) = paths_stack.last() {
1187 if let Some((prev_root_id, prev_path)) = prev_entry
1188 && (root_id != prev_root_id || !directory_path.starts_with(prev_path))
1189 {
1190 paths_stack.pop();
1191 project_settings_stack.pop();
1192 continue;
1193 }
1194 break;
1195 }
1196
1197 paths_stack.push(Some((*root_id, directory_path.as_ref())));
1198 let mut merged_local_settings = if let Some(deepest) = project_settings_stack.last() {
1199 (*deepest).clone()
1200 } else {
1201 self.merged_settings.as_ref().clone()
1202 };
1203 merged_local_settings.merge_from(local_settings);
1204
1205 project_settings_stack.push(merged_local_settings);
1206
1207 // If a local settings file changed, then avoid recomputing local
1208 // settings for any path outside of that directory.
1209 if changed_local_path.is_some_and(|(changed_root_id, changed_local_path)| {
1210 *root_id != changed_root_id || !directory_path.starts_with(changed_local_path)
1211 }) {
1212 continue;
1213 }
1214
1215 for setting_value in self.setting_values.values_mut() {
1216 let value = setting_value.from_settings(&project_settings_stack.last().unwrap());
1217 setting_value.set_local_value(*root_id, directory_path.clone(), value);
1218 }
1219 }
1220 }
1221}
1222
1223/// The result of parsing settings, including any migration attempts
1224#[derive(Debug, Clone, PartialEq, Eq)]
1225pub struct SettingsParseResult {
1226 /// The result of parsing the settings file (possibly after migration)
1227 pub parse_status: ParseStatus,
1228 /// The result of attempting to migrate the settings file
1229 pub migration_status: MigrationStatus,
1230}
1231
1232#[derive(Debug, Clone, PartialEq, Eq)]
1233pub enum MigrationStatus {
1234 /// No migration was needed - settings are up to date
1235 NotNeeded,
1236 /// Settings were automatically migrated in memory, but the file needs to be updated
1237 Succeeded,
1238 /// Migration was attempted but failed. Original settings were parsed instead.
1239 Failed { error: String },
1240}
1241
1242impl Default for SettingsParseResult {
1243 fn default() -> Self {
1244 Self {
1245 parse_status: ParseStatus::Success,
1246 migration_status: MigrationStatus::NotNeeded,
1247 }
1248 }
1249}
1250
1251impl SettingsParseResult {
1252 pub fn unwrap(self) -> bool {
1253 self.result().unwrap()
1254 }
1255
1256 pub fn expect(self, message: &str) -> bool {
1257 self.result().expect(message)
1258 }
1259
1260 /// Formats the ParseResult as a Result type. This is a lossy conversion
1261 pub fn result(self) -> Result<bool> {
1262 let migration_result = match self.migration_status {
1263 MigrationStatus::NotNeeded => Ok(false),
1264 MigrationStatus::Succeeded => Ok(true),
1265 MigrationStatus::Failed { error } => {
1266 Err(anyhow::format_err!(error)).context("Failed to migrate settings")
1267 }
1268 };
1269
1270 let parse_result = match self.parse_status {
1271 ParseStatus::Success => Ok(()),
1272 ParseStatus::Failed { error } => {
1273 Err(anyhow::format_err!(error)).context("Failed to parse settings")
1274 }
1275 };
1276
1277 match (migration_result, parse_result) {
1278 (migration_result @ Ok(_), Ok(())) => migration_result,
1279 (Err(migration_err), Ok(())) => Err(migration_err),
1280 (_, Err(parse_err)) => Err(parse_err),
1281 }
1282 }
1283
1284 /// Returns true if there were any errors migrating and parsing the settings content or if migration was required but there were no errors
1285 pub fn requires_user_action(&self) -> bool {
1286 matches!(self.parse_status, ParseStatus::Failed { .. })
1287 || matches!(
1288 self.migration_status,
1289 MigrationStatus::Succeeded | MigrationStatus::Failed { .. }
1290 )
1291 }
1292
1293 pub fn ok(self) -> Option<bool> {
1294 self.result().ok()
1295 }
1296
1297 pub fn parse_error(&self) -> Option<String> {
1298 match &self.parse_status {
1299 ParseStatus::Failed { error } => Some(error.clone()),
1300 ParseStatus::Success => None,
1301 }
1302 }
1303}
1304
1305#[derive(Debug, Clone, PartialEq)]
1306pub enum InvalidSettingsError {
1307 LocalSettings {
1308 path: Arc<RelPath>,
1309 message: String,
1310 },
1311 UserSettings {
1312 message: String,
1313 },
1314 ServerSettings {
1315 message: String,
1316 },
1317 DefaultSettings {
1318 message: String,
1319 },
1320 Editorconfig {
1321 path: LocalSettingsPath,
1322 message: String,
1323 },
1324 Tasks {
1325 path: PathBuf,
1326 message: String,
1327 },
1328 Debug {
1329 path: PathBuf,
1330 message: String,
1331 },
1332}
1333
1334impl std::fmt::Display for InvalidSettingsError {
1335 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1336 match self {
1337 InvalidSettingsError::LocalSettings { message, .. }
1338 | InvalidSettingsError::UserSettings { message }
1339 | InvalidSettingsError::ServerSettings { message }
1340 | InvalidSettingsError::DefaultSettings { message }
1341 | InvalidSettingsError::Tasks { message, .. }
1342 | InvalidSettingsError::Editorconfig { message, .. }
1343 | InvalidSettingsError::Debug { message, .. } => {
1344 write!(f, "{message}")
1345 }
1346 }
1347 }
1348}
1349impl std::error::Error for InvalidSettingsError {}
1350
1351impl Debug for SettingsStore {
1352 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1353 f.debug_struct("SettingsStore")
1354 .field(
1355 "types",
1356 &self
1357 .setting_values
1358 .values()
1359 .map(|value| value.setting_type_name())
1360 .collect::<Vec<_>>(),
1361 )
1362 .field("default_settings", &self.default_settings)
1363 .field("user_settings", &self.user_settings)
1364 .field("local_settings", &self.local_settings)
1365 .finish_non_exhaustive()
1366 }
1367}
1368
1369impl<T: Settings> AnySettingValue for SettingValue<T> {
1370 fn from_settings(&self, s: &SettingsContent) -> Box<dyn Any> {
1371 Box::new(T::from_settings(s)) as _
1372 }
1373
1374 fn setting_type_name(&self) -> &'static str {
1375 type_name::<T>()
1376 }
1377
1378 fn all_local_values(&self) -> Vec<(WorktreeId, Arc<RelPath>, &dyn Any)> {
1379 self.local_values
1380 .iter()
1381 .map(|(id, path, value)| (*id, path.clone(), value as _))
1382 .collect()
1383 }
1384
1385 fn value_for_path(&self, path: Option<SettingsLocation>) -> &dyn Any {
1386 if let Some(SettingsLocation { worktree_id, path }) = path {
1387 for (settings_root_id, settings_path, value) in self.local_values.iter().rev() {
1388 if worktree_id == *settings_root_id && path.starts_with(settings_path) {
1389 return value;
1390 }
1391 }
1392 }
1393
1394 self.global_value
1395 .as_ref()
1396 .unwrap_or_else(|| panic!("no default value for setting {}", self.setting_type_name()))
1397 }
1398
1399 fn set_global_value(&mut self, value: Box<dyn Any>) {
1400 self.global_value = Some(*value.downcast().unwrap());
1401 }
1402
1403 fn set_local_value(&mut self, root_id: WorktreeId, path: Arc<RelPath>, value: Box<dyn Any>) {
1404 let value = *value.downcast().unwrap();
1405 match self
1406 .local_values
1407 .binary_search_by_key(&(root_id, &path), |e| (e.0, &e.1))
1408 {
1409 Ok(ix) => self.local_values[ix].2 = value,
1410 Err(ix) => self.local_values.insert(ix, (root_id, path, value)),
1411 }
1412 }
1413
1414 fn clear_local_values(&mut self, root_id: WorktreeId) {
1415 self.local_values
1416 .retain(|(worktree_id, _, _)| *worktree_id != root_id);
1417 }
1418}
1419
1420#[cfg(test)]
1421mod tests {
1422 use std::num::NonZeroU32;
1423
1424 use crate::{
1425 ClosePosition, ItemSettingsContent, VsCodeSettingsSource, default_settings,
1426 settings_content::LanguageSettingsContent, test_settings,
1427 };
1428
1429 use super::*;
1430 use unindent::Unindent;
1431 use util::rel_path::rel_path;
1432
1433 #[derive(Debug, PartialEq)]
1434 struct AutoUpdateSetting {
1435 auto_update: bool,
1436 }
1437
1438 impl Settings for AutoUpdateSetting {
1439 fn from_settings(content: &SettingsContent) -> Self {
1440 AutoUpdateSetting {
1441 auto_update: content.auto_update.unwrap(),
1442 }
1443 }
1444 }
1445
1446 #[derive(Debug, PartialEq)]
1447 struct ItemSettings {
1448 close_position: ClosePosition,
1449 git_status: bool,
1450 }
1451
1452 impl Settings for ItemSettings {
1453 fn from_settings(content: &SettingsContent) -> Self {
1454 let content = content.tabs.clone().unwrap();
1455 ItemSettings {
1456 close_position: content.close_position.unwrap(),
1457 git_status: content.git_status.unwrap(),
1458 }
1459 }
1460 }
1461
1462 #[derive(Debug, PartialEq)]
1463 struct DefaultLanguageSettings {
1464 tab_size: NonZeroU32,
1465 preferred_line_length: u32,
1466 }
1467
1468 impl Settings for DefaultLanguageSettings {
1469 fn from_settings(content: &SettingsContent) -> Self {
1470 let content = &content.project.all_languages.defaults;
1471 DefaultLanguageSettings {
1472 tab_size: content.tab_size.unwrap(),
1473 preferred_line_length: content.preferred_line_length.unwrap(),
1474 }
1475 }
1476 }
1477
1478 #[derive(Debug, PartialEq)]
1479 struct ThemeSettings {
1480 buffer_font_family: FontFamilyName,
1481 buffer_font_fallbacks: Vec<FontFamilyName>,
1482 }
1483
1484 impl Settings for ThemeSettings {
1485 fn from_settings(content: &SettingsContent) -> Self {
1486 let content = content.theme.clone();
1487 ThemeSettings {
1488 buffer_font_family: content.buffer_font_family.unwrap(),
1489 buffer_font_fallbacks: content.buffer_font_fallbacks.unwrap(),
1490 }
1491 }
1492 }
1493
1494 #[gpui::test]
1495 fn test_settings_store_basic(cx: &mut App) {
1496 let mut store = SettingsStore::new(cx, &default_settings());
1497 store.register_setting::<AutoUpdateSetting>();
1498 store.register_setting::<ItemSettings>();
1499 store.register_setting::<DefaultLanguageSettings>();
1500
1501 assert_eq!(
1502 store.get::<AutoUpdateSetting>(None),
1503 &AutoUpdateSetting { auto_update: true }
1504 );
1505 assert_eq!(
1506 store.get::<ItemSettings>(None).close_position,
1507 ClosePosition::Right
1508 );
1509
1510 store
1511 .set_user_settings(
1512 r#"{
1513 "auto_update": false,
1514 "tabs": {
1515 "close_position": "left"
1516 }
1517 }"#,
1518 cx,
1519 )
1520 .unwrap();
1521
1522 assert_eq!(
1523 store.get::<AutoUpdateSetting>(None),
1524 &AutoUpdateSetting { auto_update: false }
1525 );
1526 assert_eq!(
1527 store.get::<ItemSettings>(None).close_position,
1528 ClosePosition::Left
1529 );
1530
1531 store
1532 .set_local_settings(
1533 WorktreeId::from_usize(1),
1534 LocalSettingsPath::InWorktree(rel_path("root1").into()),
1535 LocalSettingsKind::Settings,
1536 Some(r#"{ "tab_size": 5 }"#),
1537 cx,
1538 )
1539 .unwrap();
1540 store
1541 .set_local_settings(
1542 WorktreeId::from_usize(1),
1543 LocalSettingsPath::InWorktree(rel_path("root1/subdir").into()),
1544 LocalSettingsKind::Settings,
1545 Some(r#"{ "preferred_line_length": 50 }"#),
1546 cx,
1547 )
1548 .unwrap();
1549
1550 store
1551 .set_local_settings(
1552 WorktreeId::from_usize(1),
1553 LocalSettingsPath::InWorktree(rel_path("root2").into()),
1554 LocalSettingsKind::Settings,
1555 Some(r#"{ "tab_size": 9, "auto_update": true}"#),
1556 cx,
1557 )
1558 .unwrap();
1559
1560 assert_eq!(
1561 store.get::<DefaultLanguageSettings>(Some(SettingsLocation {
1562 worktree_id: WorktreeId::from_usize(1),
1563 path: rel_path("root1/something"),
1564 })),
1565 &DefaultLanguageSettings {
1566 preferred_line_length: 80,
1567 tab_size: 5.try_into().unwrap(),
1568 }
1569 );
1570 assert_eq!(
1571 store.get::<DefaultLanguageSettings>(Some(SettingsLocation {
1572 worktree_id: WorktreeId::from_usize(1),
1573 path: rel_path("root1/subdir/something"),
1574 })),
1575 &DefaultLanguageSettings {
1576 preferred_line_length: 50,
1577 tab_size: 5.try_into().unwrap(),
1578 }
1579 );
1580 assert_eq!(
1581 store.get::<DefaultLanguageSettings>(Some(SettingsLocation {
1582 worktree_id: WorktreeId::from_usize(1),
1583 path: rel_path("root2/something"),
1584 })),
1585 &DefaultLanguageSettings {
1586 preferred_line_length: 80,
1587 tab_size: 9.try_into().unwrap(),
1588 }
1589 );
1590 assert_eq!(
1591 store.get::<AutoUpdateSetting>(Some(SettingsLocation {
1592 worktree_id: WorktreeId::from_usize(1),
1593 path: rel_path("root2/something")
1594 })),
1595 &AutoUpdateSetting { auto_update: false }
1596 );
1597 }
1598
1599 #[gpui::test]
1600 fn test_setting_store_assign_json_before_register(cx: &mut App) {
1601 let mut store = SettingsStore::new(cx, &test_settings());
1602 store
1603 .set_user_settings(r#"{ "auto_update": false }"#, cx)
1604 .unwrap();
1605 store.register_setting::<AutoUpdateSetting>();
1606
1607 assert_eq!(
1608 store.get::<AutoUpdateSetting>(None),
1609 &AutoUpdateSetting { auto_update: false }
1610 );
1611 }
1612
1613 #[track_caller]
1614 fn check_settings_update(
1615 store: &mut SettingsStore,
1616 old_json: String,
1617 update: fn(&mut SettingsContent),
1618 expected_new_json: String,
1619 cx: &mut App,
1620 ) {
1621 store.set_user_settings(&old_json, cx).ok();
1622 let edits = store.edits_for_update(&old_json, update);
1623 let mut new_json = old_json;
1624 for (range, replacement) in edits.into_iter() {
1625 new_json.replace_range(range, &replacement);
1626 }
1627 pretty_assertions::assert_eq!(new_json, expected_new_json);
1628 }
1629
1630 #[gpui::test]
1631 fn test_setting_store_update(cx: &mut App) {
1632 let mut store = SettingsStore::new(cx, &test_settings());
1633
1634 // entries added and updated
1635 check_settings_update(
1636 &mut store,
1637 r#"{
1638 "languages": {
1639 "JSON": {
1640 "auto_indent": true
1641 }
1642 }
1643 }"#
1644 .unindent(),
1645 |settings| {
1646 settings
1647 .languages_mut()
1648 .get_mut("JSON")
1649 .unwrap()
1650 .auto_indent = Some(false);
1651
1652 settings.languages_mut().insert(
1653 "Rust".into(),
1654 LanguageSettingsContent {
1655 auto_indent: Some(true),
1656 ..Default::default()
1657 },
1658 );
1659 },
1660 r#"{
1661 "languages": {
1662 "Rust": {
1663 "auto_indent": true
1664 },
1665 "JSON": {
1666 "auto_indent": false
1667 }
1668 }
1669 }"#
1670 .unindent(),
1671 cx,
1672 );
1673
1674 // entries removed
1675 check_settings_update(
1676 &mut store,
1677 r#"{
1678 "languages": {
1679 "Rust": {
1680 "language_setting_2": true
1681 },
1682 "JSON": {
1683 "language_setting_1": false
1684 }
1685 }
1686 }"#
1687 .unindent(),
1688 |settings| {
1689 settings.languages_mut().remove("JSON").unwrap();
1690 },
1691 r#"{
1692 "languages": {
1693 "Rust": {
1694 "language_setting_2": true
1695 }
1696 }
1697 }"#
1698 .unindent(),
1699 cx,
1700 );
1701
1702 check_settings_update(
1703 &mut store,
1704 r#"{
1705 "languages": {
1706 "Rust": {
1707 "language_setting_2": true
1708 },
1709 "JSON": {
1710 "language_setting_1": false
1711 }
1712 }
1713 }"#
1714 .unindent(),
1715 |settings| {
1716 settings.languages_mut().remove("Rust").unwrap();
1717 },
1718 r#"{
1719 "languages": {
1720 "JSON": {
1721 "language_setting_1": false
1722 }
1723 }
1724 }"#
1725 .unindent(),
1726 cx,
1727 );
1728
1729 // weird formatting
1730 check_settings_update(
1731 &mut store,
1732 r#"{
1733 "tabs": { "close_position": "left", "name": "Max" }
1734 }"#
1735 .unindent(),
1736 |settings| {
1737 settings.tabs.as_mut().unwrap().close_position = Some(ClosePosition::Left);
1738 },
1739 r#"{
1740 "tabs": { "close_position": "left", "name": "Max" }
1741 }"#
1742 .unindent(),
1743 cx,
1744 );
1745
1746 // single-line formatting, other keys
1747 check_settings_update(
1748 &mut store,
1749 r#"{ "one": 1, "two": 2 }"#.to_owned(),
1750 |settings| settings.auto_update = Some(true),
1751 r#"{ "auto_update": true, "one": 1, "two": 2 }"#.to_owned(),
1752 cx,
1753 );
1754
1755 // empty object
1756 check_settings_update(
1757 &mut store,
1758 r#"{
1759 "tabs": {}
1760 }"#
1761 .unindent(),
1762 |settings| settings.tabs.as_mut().unwrap().close_position = Some(ClosePosition::Left),
1763 r#"{
1764 "tabs": {
1765 "close_position": "left"
1766 }
1767 }"#
1768 .unindent(),
1769 cx,
1770 );
1771
1772 // no content
1773 check_settings_update(
1774 &mut store,
1775 r#""#.unindent(),
1776 |settings| {
1777 settings.tabs = Some(ItemSettingsContent {
1778 git_status: Some(true),
1779 ..Default::default()
1780 })
1781 },
1782 r#"{
1783 "tabs": {
1784 "git_status": true
1785 }
1786 }
1787 "#
1788 .unindent(),
1789 cx,
1790 );
1791
1792 check_settings_update(
1793 &mut store,
1794 r#"{
1795 }
1796 "#
1797 .unindent(),
1798 |settings| settings.title_bar.get_or_insert_default().show_branch_name = Some(true),
1799 r#"{
1800 "title_bar": {
1801 "show_branch_name": true
1802 }
1803 }
1804 "#
1805 .unindent(),
1806 cx,
1807 );
1808 }
1809
1810 #[gpui::test]
1811 fn test_vscode_import(cx: &mut App) {
1812 let mut store = SettingsStore::new(cx, &test_settings());
1813 store.register_setting::<DefaultLanguageSettings>();
1814 store.register_setting::<ItemSettings>();
1815 store.register_setting::<AutoUpdateSetting>();
1816 store.register_setting::<ThemeSettings>();
1817
1818 // create settings that werent present
1819 check_vscode_import(
1820 &mut store,
1821 r#"{
1822 }
1823 "#
1824 .unindent(),
1825 r#" { "editor.tabSize": 37 } "#.to_owned(),
1826 r#"{
1827 "base_keymap": "VSCode",
1828 "tab_size": 37
1829 }
1830 "#
1831 .unindent(),
1832 cx,
1833 );
1834
1835 // persist settings that were present
1836 check_vscode_import(
1837 &mut store,
1838 r#"{
1839 "preferred_line_length": 99,
1840 }
1841 "#
1842 .unindent(),
1843 r#"{ "editor.tabSize": 42 }"#.to_owned(),
1844 r#"{
1845 "base_keymap": "VSCode",
1846 "tab_size": 42,
1847 "preferred_line_length": 99,
1848 }
1849 "#
1850 .unindent(),
1851 cx,
1852 );
1853
1854 // don't clobber settings that aren't present in vscode
1855 check_vscode_import(
1856 &mut store,
1857 r#"{
1858 "preferred_line_length": 99,
1859 "tab_size": 42
1860 }
1861 "#
1862 .unindent(),
1863 r#"{}"#.to_owned(),
1864 r#"{
1865 "base_keymap": "VSCode",
1866 "preferred_line_length": 99,
1867 "tab_size": 42
1868 }
1869 "#
1870 .unindent(),
1871 cx,
1872 );
1873
1874 // custom enum
1875 check_vscode_import(
1876 &mut store,
1877 r#"{
1878 }
1879 "#
1880 .unindent(),
1881 r#"{ "git.decorations.enabled": true }"#.to_owned(),
1882 r#"{
1883 "project_panel": {
1884 "git_status": true
1885 },
1886 "outline_panel": {
1887 "git_status": true
1888 },
1889 "base_keymap": "VSCode",
1890 "tabs": {
1891 "git_status": true
1892 }
1893 }
1894 "#
1895 .unindent(),
1896 cx,
1897 );
1898
1899 // font-family
1900 check_vscode_import(
1901 &mut store,
1902 r#"{
1903 }
1904 "#
1905 .unindent(),
1906 r#"{ "editor.fontFamily": "Cascadia Code, 'Consolas', Courier New" }"#.to_owned(),
1907 r#"{
1908 "base_keymap": "VSCode",
1909 "buffer_font_fallbacks": [
1910 "Consolas",
1911 "Courier New"
1912 ],
1913 "buffer_font_family": "Cascadia Code"
1914 }
1915 "#
1916 .unindent(),
1917 cx,
1918 );
1919 }
1920
1921 #[track_caller]
1922 fn check_vscode_import(
1923 store: &mut SettingsStore,
1924 old: String,
1925 vscode: String,
1926 expected: String,
1927 cx: &mut App,
1928 ) {
1929 store.set_user_settings(&old, cx).ok();
1930 let new = store.get_vscode_edits(
1931 old,
1932 &VsCodeSettings::from_str(&vscode, VsCodeSettingsSource::VsCode).unwrap(),
1933 );
1934 pretty_assertions::assert_eq!(new, expected);
1935 }
1936
1937 #[gpui::test]
1938 fn test_update_git_settings(cx: &mut App) {
1939 let store = SettingsStore::new(cx, &test_settings());
1940
1941 let actual = store.new_text_for_update("{}".to_string(), |current| {
1942 current
1943 .git
1944 .get_or_insert_default()
1945 .inline_blame
1946 .get_or_insert_default()
1947 .enabled = Some(true);
1948 });
1949 pretty_assertions::assert_str_eq!(
1950 actual,
1951 r#"{
1952 "git": {
1953 "inline_blame": {
1954 "enabled": true
1955 }
1956 }
1957 }
1958 "#
1959 .unindent()
1960 );
1961 }
1962
1963 #[gpui::test]
1964 fn test_global_settings(cx: &mut App) {
1965 let mut store = SettingsStore::new(cx, &test_settings());
1966 store.register_setting::<ItemSettings>();
1967
1968 // Set global settings - these should override defaults but not user settings
1969 store
1970 .set_global_settings(
1971 r#"{
1972 "tabs": {
1973 "close_position": "right",
1974 "git_status": true,
1975 }
1976 }"#,
1977 cx,
1978 )
1979 .unwrap();
1980
1981 // Before user settings, global settings should apply
1982 assert_eq!(
1983 store.get::<ItemSettings>(None),
1984 &ItemSettings {
1985 close_position: ClosePosition::Right,
1986 git_status: true,
1987 }
1988 );
1989
1990 // Set user settings - these should override both defaults and global
1991 store
1992 .set_user_settings(
1993 r#"{
1994 "tabs": {
1995 "close_position": "left"
1996 }
1997 }"#,
1998 cx,
1999 )
2000 .unwrap();
2001
2002 // User settings should override global settings
2003 assert_eq!(
2004 store.get::<ItemSettings>(None),
2005 &ItemSettings {
2006 close_position: ClosePosition::Left,
2007 git_status: true, // Staff from global settings
2008 }
2009 );
2010 }
2011
2012 #[gpui::test]
2013 fn test_get_value_for_field_basic(cx: &mut App) {
2014 let mut store = SettingsStore::new(cx, &test_settings());
2015 store.register_setting::<DefaultLanguageSettings>();
2016
2017 store
2018 .set_user_settings(r#"{"preferred_line_length": 0}"#, cx)
2019 .unwrap();
2020 let local = (WorktreeId::from_usize(0), RelPath::empty().into_arc());
2021 store
2022 .set_local_settings(
2023 local.0,
2024 LocalSettingsPath::InWorktree(local.1.clone()),
2025 LocalSettingsKind::Settings,
2026 Some(r#"{}"#),
2027 cx,
2028 )
2029 .unwrap();
2030
2031 fn get(content: &SettingsContent) -> Option<&u32> {
2032 content
2033 .project
2034 .all_languages
2035 .defaults
2036 .preferred_line_length
2037 .as_ref()
2038 }
2039
2040 let default_value = *get(&store.default_settings).unwrap();
2041
2042 assert_eq!(
2043 store.get_value_from_file(SettingsFile::Project(local.clone()), get),
2044 (SettingsFile::User, Some(&0))
2045 );
2046 assert_eq!(
2047 store.get_value_from_file(SettingsFile::User, get),
2048 (SettingsFile::User, Some(&0))
2049 );
2050 store.set_user_settings(r#"{}"#, cx).unwrap();
2051 assert_eq!(
2052 store.get_value_from_file(SettingsFile::Project(local.clone()), get),
2053 (SettingsFile::Default, Some(&default_value))
2054 );
2055 store
2056 .set_local_settings(
2057 local.0,
2058 LocalSettingsPath::InWorktree(local.1.clone()),
2059 LocalSettingsKind::Settings,
2060 Some(r#"{"preferred_line_length": 80}"#),
2061 cx,
2062 )
2063 .unwrap();
2064 assert_eq!(
2065 store.get_value_from_file(SettingsFile::Project(local.clone()), get),
2066 (SettingsFile::Project(local), Some(&80))
2067 );
2068 assert_eq!(
2069 store.get_value_from_file(SettingsFile::User, get),
2070 (SettingsFile::Default, Some(&default_value))
2071 );
2072 }
2073
2074 #[gpui::test]
2075 fn test_get_value_for_field_local_worktrees_dont_interfere(cx: &mut App) {
2076 let mut store = SettingsStore::new(cx, &test_settings());
2077 store.register_setting::<DefaultLanguageSettings>();
2078 store.register_setting::<AutoUpdateSetting>();
2079
2080 let local_1 = (WorktreeId::from_usize(0), RelPath::empty().into_arc());
2081
2082 let local_1_child = (
2083 WorktreeId::from_usize(0),
2084 RelPath::new(
2085 std::path::Path::new("child1"),
2086 util::paths::PathStyle::Posix,
2087 )
2088 .unwrap()
2089 .into_arc(),
2090 );
2091
2092 let local_2 = (WorktreeId::from_usize(1), RelPath::empty().into_arc());
2093 let local_2_child = (
2094 WorktreeId::from_usize(1),
2095 RelPath::new(
2096 std::path::Path::new("child2"),
2097 util::paths::PathStyle::Posix,
2098 )
2099 .unwrap()
2100 .into_arc(),
2101 );
2102
2103 fn get(content: &SettingsContent) -> Option<&u32> {
2104 content
2105 .project
2106 .all_languages
2107 .defaults
2108 .preferred_line_length
2109 .as_ref()
2110 }
2111
2112 store
2113 .set_local_settings(
2114 local_1.0,
2115 LocalSettingsPath::InWorktree(local_1.1.clone()),
2116 LocalSettingsKind::Settings,
2117 Some(r#"{"preferred_line_length": 1}"#),
2118 cx,
2119 )
2120 .unwrap();
2121 store
2122 .set_local_settings(
2123 local_1_child.0,
2124 LocalSettingsPath::InWorktree(local_1_child.1.clone()),
2125 LocalSettingsKind::Settings,
2126 Some(r#"{}"#),
2127 cx,
2128 )
2129 .unwrap();
2130 store
2131 .set_local_settings(
2132 local_2.0,
2133 LocalSettingsPath::InWorktree(local_2.1.clone()),
2134 LocalSettingsKind::Settings,
2135 Some(r#"{"preferred_line_length": 2}"#),
2136 cx,
2137 )
2138 .unwrap();
2139 store
2140 .set_local_settings(
2141 local_2_child.0,
2142 LocalSettingsPath::InWorktree(local_2_child.1.clone()),
2143 LocalSettingsKind::Settings,
2144 Some(r#"{}"#),
2145 cx,
2146 )
2147 .unwrap();
2148
2149 // each local child should only inherit from it's parent
2150 assert_eq!(
2151 store.get_value_from_file(SettingsFile::Project(local_2_child), get),
2152 (SettingsFile::Project(local_2), Some(&2))
2153 );
2154 assert_eq!(
2155 store.get_value_from_file(SettingsFile::Project(local_1_child.clone()), get),
2156 (SettingsFile::Project(local_1.clone()), Some(&1))
2157 );
2158
2159 // adjacent children should be treated as siblings not inherit from each other
2160 let local_1_adjacent_child = (local_1.0, rel_path("adjacent_child").into_arc());
2161 store
2162 .set_local_settings(
2163 local_1_adjacent_child.0,
2164 LocalSettingsPath::InWorktree(local_1_adjacent_child.1.clone()),
2165 LocalSettingsKind::Settings,
2166 Some(r#"{}"#),
2167 cx,
2168 )
2169 .unwrap();
2170 store
2171 .set_local_settings(
2172 local_1_child.0,
2173 LocalSettingsPath::InWorktree(local_1_child.1.clone()),
2174 LocalSettingsKind::Settings,
2175 Some(r#"{"preferred_line_length": 3}"#),
2176 cx,
2177 )
2178 .unwrap();
2179
2180 assert_eq!(
2181 store.get_value_from_file(SettingsFile::Project(local_1_adjacent_child.clone()), get),
2182 (SettingsFile::Project(local_1.clone()), Some(&1))
2183 );
2184 store
2185 .set_local_settings(
2186 local_1_adjacent_child.0,
2187 LocalSettingsPath::InWorktree(local_1_adjacent_child.1),
2188 LocalSettingsKind::Settings,
2189 Some(r#"{"preferred_line_length": 3}"#),
2190 cx,
2191 )
2192 .unwrap();
2193 store
2194 .set_local_settings(
2195 local_1_child.0,
2196 LocalSettingsPath::InWorktree(local_1_child.1.clone()),
2197 LocalSettingsKind::Settings,
2198 Some(r#"{}"#),
2199 cx,
2200 )
2201 .unwrap();
2202 assert_eq!(
2203 store.get_value_from_file(SettingsFile::Project(local_1_child), get),
2204 (SettingsFile::Project(local_1), Some(&1))
2205 );
2206 }
2207
2208 #[gpui::test]
2209 fn test_get_overrides_for_field(cx: &mut App) {
2210 let mut store = SettingsStore::new(cx, &test_settings());
2211 store.register_setting::<DefaultLanguageSettings>();
2212
2213 let wt0_root = (WorktreeId::from_usize(0), RelPath::empty().into_arc());
2214 let wt0_child1 = (WorktreeId::from_usize(0), rel_path("child1").into_arc());
2215 let wt0_child2 = (WorktreeId::from_usize(0), rel_path("child2").into_arc());
2216
2217 let wt1_root = (WorktreeId::from_usize(1), RelPath::empty().into_arc());
2218 let wt1_subdir = (WorktreeId::from_usize(1), rel_path("subdir").into_arc());
2219
2220 fn get(content: &SettingsContent) -> &Option<u32> {
2221 &content.project.all_languages.defaults.preferred_line_length
2222 }
2223
2224 store
2225 .set_user_settings(r#"{"preferred_line_length": 100}"#, cx)
2226 .unwrap();
2227
2228 store
2229 .set_local_settings(
2230 wt0_root.0,
2231 LocalSettingsPath::InWorktree(wt0_root.1.clone()),
2232 LocalSettingsKind::Settings,
2233 Some(r#"{"preferred_line_length": 80}"#),
2234 cx,
2235 )
2236 .unwrap();
2237 store
2238 .set_local_settings(
2239 wt0_child1.0,
2240 LocalSettingsPath::InWorktree(wt0_child1.1.clone()),
2241 LocalSettingsKind::Settings,
2242 Some(r#"{"preferred_line_length": 120}"#),
2243 cx,
2244 )
2245 .unwrap();
2246 store
2247 .set_local_settings(
2248 wt0_child2.0,
2249 LocalSettingsPath::InWorktree(wt0_child2.1.clone()),
2250 LocalSettingsKind::Settings,
2251 Some(r#"{}"#),
2252 cx,
2253 )
2254 .unwrap();
2255
2256 store
2257 .set_local_settings(
2258 wt1_root.0,
2259 LocalSettingsPath::InWorktree(wt1_root.1.clone()),
2260 LocalSettingsKind::Settings,
2261 Some(r#"{"preferred_line_length": 90}"#),
2262 cx,
2263 )
2264 .unwrap();
2265 store
2266 .set_local_settings(
2267 wt1_subdir.0,
2268 LocalSettingsPath::InWorktree(wt1_subdir.1.clone()),
2269 LocalSettingsKind::Settings,
2270 Some(r#"{}"#),
2271 cx,
2272 )
2273 .unwrap();
2274
2275 let overrides = store.get_overrides_for_field(SettingsFile::Default, get);
2276 assert_eq!(
2277 overrides,
2278 vec![
2279 SettingsFile::User,
2280 SettingsFile::Project(wt0_root.clone()),
2281 SettingsFile::Project(wt0_child1.clone()),
2282 SettingsFile::Project(wt1_root.clone()),
2283 ]
2284 );
2285
2286 let overrides = store.get_overrides_for_field(SettingsFile::User, get);
2287 assert_eq!(
2288 overrides,
2289 vec![
2290 SettingsFile::Project(wt0_root.clone()),
2291 SettingsFile::Project(wt0_child1.clone()),
2292 SettingsFile::Project(wt1_root.clone()),
2293 ]
2294 );
2295
2296 let overrides = store.get_overrides_for_field(SettingsFile::Project(wt0_root), get);
2297 assert_eq!(overrides, vec![]);
2298
2299 let overrides =
2300 store.get_overrides_for_field(SettingsFile::Project(wt0_child1.clone()), get);
2301 assert_eq!(overrides, vec![]);
2302
2303 let overrides = store.get_overrides_for_field(SettingsFile::Project(wt0_child2), get);
2304 assert_eq!(overrides, vec![]);
2305
2306 let overrides = store.get_overrides_for_field(SettingsFile::Project(wt1_root), get);
2307 assert_eq!(overrides, vec![]);
2308
2309 let overrides = store.get_overrides_for_field(SettingsFile::Project(wt1_subdir), get);
2310 assert_eq!(overrides, vec![]);
2311
2312 let wt0_deep_child = (
2313 WorktreeId::from_usize(0),
2314 rel_path("child1/subdir").into_arc(),
2315 );
2316 store
2317 .set_local_settings(
2318 wt0_deep_child.0,
2319 LocalSettingsPath::InWorktree(wt0_deep_child.1.clone()),
2320 LocalSettingsKind::Settings,
2321 Some(r#"{"preferred_line_length": 140}"#),
2322 cx,
2323 )
2324 .unwrap();
2325
2326 let overrides = store.get_overrides_for_field(SettingsFile::Project(wt0_deep_child), get);
2327 assert_eq!(overrides, vec![]);
2328
2329 let overrides = store.get_overrides_for_field(SettingsFile::Project(wt0_child1), get);
2330 assert_eq!(overrides, vec![]);
2331 }
2332
2333 #[test]
2334 fn test_file_ord() {
2335 let wt0_root =
2336 SettingsFile::Project((WorktreeId::from_usize(0), RelPath::empty().into_arc()));
2337 let wt0_child1 =
2338 SettingsFile::Project((WorktreeId::from_usize(0), rel_path("child1").into_arc()));
2339 let wt0_child2 =
2340 SettingsFile::Project((WorktreeId::from_usize(0), rel_path("child2").into_arc()));
2341
2342 let wt1_root =
2343 SettingsFile::Project((WorktreeId::from_usize(1), RelPath::empty().into_arc()));
2344 let wt1_subdir =
2345 SettingsFile::Project((WorktreeId::from_usize(1), rel_path("subdir").into_arc()));
2346
2347 let mut files = vec![
2348 &wt1_root,
2349 &SettingsFile::Default,
2350 &wt0_root,
2351 &wt1_subdir,
2352 &wt0_child2,
2353 &SettingsFile::Server,
2354 &wt0_child1,
2355 &SettingsFile::User,
2356 ];
2357
2358 files.sort();
2359 pretty_assertions::assert_eq!(
2360 files,
2361 vec![
2362 &wt0_child2,
2363 &wt0_child1,
2364 &wt0_root,
2365 &wt1_subdir,
2366 &wt1_root,
2367 &SettingsFile::Server,
2368 &SettingsFile::User,
2369 &SettingsFile::Default,
2370 ]
2371 )
2372 }
2373
2374 #[gpui::test]
2375 fn test_lsp_settings_schema_generation(cx: &mut App) {
2376 let store = SettingsStore::test(cx);
2377
2378 let schema = store.json_schema(&SettingsJsonSchemaParams {
2379 language_names: &["Rust".to_string(), "TypeScript".to_string()],
2380 font_names: &["Zed Mono".to_string()],
2381 theme_names: &["One Dark".into()],
2382 icon_theme_names: &["Zed Icons".into()],
2383 lsp_adapter_names: &[
2384 "rust-analyzer".to_string(),
2385 "typescript-language-server".to_string(),
2386 ],
2387 });
2388
2389 let properties = schema
2390 .pointer("/$defs/LspSettingsMap/properties")
2391 .expect("LspSettingsMap should have properties")
2392 .as_object()
2393 .unwrap();
2394
2395 assert!(properties.contains_key("rust-analyzer"));
2396 assert!(properties.contains_key("typescript-language-server"));
2397
2398 let init_options_ref = properties
2399 .get("rust-analyzer")
2400 .unwrap()
2401 .pointer("/properties/initialization_options/$ref")
2402 .expect("initialization_options should have a $ref")
2403 .as_str()
2404 .unwrap();
2405
2406 assert_eq!(
2407 init_options_ref,
2408 "zed://schemas/settings/lsp/rust-analyzer/initialization_options"
2409 );
2410
2411 let settings_ref = properties
2412 .get("rust-analyzer")
2413 .unwrap()
2414 .pointer("/properties/settings/$ref")
2415 .expect("settings should have a $ref")
2416 .as_str()
2417 .unwrap();
2418
2419 assert_eq!(
2420 settings_ref,
2421 "zed://schemas/settings/lsp/rust-analyzer/settings"
2422 );
2423 }
2424
2425 #[gpui::test]
2426 fn test_lsp_project_settings_schema_generation(cx: &mut App) {
2427 let store = SettingsStore::test(cx);
2428
2429 let schema = store.project_json_schema(&SettingsJsonSchemaParams {
2430 language_names: &["Rust".to_string(), "TypeScript".to_string()],
2431 font_names: &["Zed Mono".to_string()],
2432 theme_names: &["One Dark".into()],
2433 icon_theme_names: &["Zed Icons".into()],
2434 lsp_adapter_names: &[
2435 "rust-analyzer".to_string(),
2436 "typescript-language-server".to_string(),
2437 ],
2438 });
2439
2440 let properties = schema
2441 .pointer("/$defs/LspSettingsMap/properties")
2442 .expect("LspSettingsMap should have properties")
2443 .as_object()
2444 .unwrap();
2445
2446 assert!(properties.contains_key("rust-analyzer"));
2447 assert!(properties.contains_key("typescript-language-server"));
2448
2449 let init_options_ref = properties
2450 .get("rust-analyzer")
2451 .unwrap()
2452 .pointer("/properties/initialization_options/$ref")
2453 .expect("initialization_options should have a $ref")
2454 .as_str()
2455 .unwrap();
2456
2457 assert_eq!(
2458 init_options_ref,
2459 "zed://schemas/settings/lsp/rust-analyzer/initialization_options"
2460 );
2461
2462 let settings_ref = properties
2463 .get("rust-analyzer")
2464 .unwrap()
2465 .pointer("/properties/settings/$ref")
2466 .expect("settings should have a $ref")
2467 .as_str()
2468 .unwrap();
2469
2470 assert_eq!(
2471 settings_ref,
2472 "zed://schemas/settings/lsp/rust-analyzer/settings"
2473 );
2474 }
2475
2476 #[gpui::test]
2477 fn test_project_json_schema_differs_from_user_schema(cx: &mut App) {
2478 let store = SettingsStore::test(cx);
2479
2480 let params = SettingsJsonSchemaParams {
2481 language_names: &["Rust".to_string()],
2482 font_names: &["Zed Mono".to_string()],
2483 theme_names: &["One Dark".into()],
2484 icon_theme_names: &["Zed Icons".into()],
2485 lsp_adapter_names: &["rust-analyzer".to_string()],
2486 };
2487
2488 let user_schema = store.json_schema(¶ms);
2489 let project_schema = store.project_json_schema(¶ms);
2490
2491 assert_ne!(user_schema, project_schema);
2492
2493 let user_schema_str = serde_json::to_string(&user_schema).unwrap();
2494 let project_schema_str = serde_json::to_string(&project_schema).unwrap();
2495
2496 assert!(user_schema_str.contains("\"auto_update\""));
2497 assert!(!project_schema_str.contains("\"auto_update\""));
2498 }
2499}