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