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