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 crate::VsCodeSettingsSource;
1526
1527 use super::*;
1528 use serde_derive::Deserialize;
1529 use unindent::Unindent;
1530
1531 #[gpui::test]
1532 fn test_settings_store_basic(cx: &mut App) {
1533 let mut store = SettingsStore::new(cx);
1534 store.register_setting::<UserSettings>(cx);
1535 store.register_setting::<TurboSetting>(cx);
1536 store.register_setting::<MultiKeySettings>(cx);
1537 store
1538 .set_default_settings(
1539 r#"{
1540 "turbo": false,
1541 "user": {
1542 "name": "John Doe",
1543 "age": 30,
1544 "staff": false
1545 }
1546 }"#,
1547 cx,
1548 )
1549 .unwrap();
1550
1551 assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(false));
1552 assert_eq!(
1553 store.get::<UserSettings>(None),
1554 &UserSettings {
1555 name: "John Doe".to_string(),
1556 age: 30,
1557 staff: false,
1558 }
1559 );
1560 assert_eq!(
1561 store.get::<MultiKeySettings>(None),
1562 &MultiKeySettings {
1563 key1: String::new(),
1564 key2: String::new(),
1565 }
1566 );
1567
1568 store
1569 .set_user_settings(
1570 r#"{
1571 "turbo": true,
1572 "user": { "age": 31 },
1573 "key1": "a"
1574 }"#,
1575 cx,
1576 )
1577 .unwrap();
1578
1579 assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(true));
1580 assert_eq!(
1581 store.get::<UserSettings>(None),
1582 &UserSettings {
1583 name: "John Doe".to_string(),
1584 age: 31,
1585 staff: false
1586 }
1587 );
1588
1589 store
1590 .set_local_settings(
1591 WorktreeId::from_usize(1),
1592 Path::new("/root1").into(),
1593 LocalSettingsKind::Settings,
1594 Some(r#"{ "user": { "staff": true } }"#),
1595 cx,
1596 )
1597 .unwrap();
1598 store
1599 .set_local_settings(
1600 WorktreeId::from_usize(1),
1601 Path::new("/root1/subdir").into(),
1602 LocalSettingsKind::Settings,
1603 Some(r#"{ "user": { "name": "Jane Doe" } }"#),
1604 cx,
1605 )
1606 .unwrap();
1607
1608 store
1609 .set_local_settings(
1610 WorktreeId::from_usize(1),
1611 Path::new("/root2").into(),
1612 LocalSettingsKind::Settings,
1613 Some(r#"{ "user": { "age": 42 }, "key2": "b" }"#),
1614 cx,
1615 )
1616 .unwrap();
1617
1618 assert_eq!(
1619 store.get::<UserSettings>(Some(SettingsLocation {
1620 worktree_id: WorktreeId::from_usize(1),
1621 path: Path::new("/root1/something"),
1622 })),
1623 &UserSettings {
1624 name: "John Doe".to_string(),
1625 age: 31,
1626 staff: true
1627 }
1628 );
1629 assert_eq!(
1630 store.get::<UserSettings>(Some(SettingsLocation {
1631 worktree_id: WorktreeId::from_usize(1),
1632 path: Path::new("/root1/subdir/something")
1633 })),
1634 &UserSettings {
1635 name: "Jane Doe".to_string(),
1636 age: 31,
1637 staff: true
1638 }
1639 );
1640 assert_eq!(
1641 store.get::<UserSettings>(Some(SettingsLocation {
1642 worktree_id: WorktreeId::from_usize(1),
1643 path: Path::new("/root2/something")
1644 })),
1645 &UserSettings {
1646 name: "John Doe".to_string(),
1647 age: 42,
1648 staff: false
1649 }
1650 );
1651 assert_eq!(
1652 store.get::<MultiKeySettings>(Some(SettingsLocation {
1653 worktree_id: WorktreeId::from_usize(1),
1654 path: Path::new("/root2/something")
1655 })),
1656 &MultiKeySettings {
1657 key1: "a".to_string(),
1658 key2: "b".to_string(),
1659 }
1660 );
1661 }
1662
1663 #[gpui::test]
1664 fn test_setting_store_assign_json_before_register(cx: &mut App) {
1665 let mut store = SettingsStore::new(cx);
1666 store
1667 .set_default_settings(
1668 r#"{
1669 "turbo": true,
1670 "user": {
1671 "name": "John Doe",
1672 "age": 30,
1673 "staff": false
1674 },
1675 "key1": "x"
1676 }"#,
1677 cx,
1678 )
1679 .unwrap();
1680 store
1681 .set_user_settings(r#"{ "turbo": false }"#, cx)
1682 .unwrap();
1683 store.register_setting::<UserSettings>(cx);
1684 store.register_setting::<TurboSetting>(cx);
1685
1686 assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(false));
1687 assert_eq!(
1688 store.get::<UserSettings>(None),
1689 &UserSettings {
1690 name: "John Doe".to_string(),
1691 age: 30,
1692 staff: false,
1693 }
1694 );
1695
1696 store.register_setting::<MultiKeySettings>(cx);
1697 assert_eq!(
1698 store.get::<MultiKeySettings>(None),
1699 &MultiKeySettings {
1700 key1: "x".into(),
1701 key2: String::new(),
1702 }
1703 );
1704 }
1705
1706 #[gpui::test]
1707 fn test_setting_store_update(cx: &mut App) {
1708 let mut store = SettingsStore::new(cx);
1709 store.register_setting::<MultiKeySettings>(cx);
1710 store.register_setting::<UserSettings>(cx);
1711 store.register_setting::<LanguageSettings>(cx);
1712
1713 // entries added and updated
1714 check_settings_update::<LanguageSettings>(
1715 &mut store,
1716 r#"{
1717 "languages": {
1718 "JSON": {
1719 "language_setting_1": true
1720 }
1721 }
1722 }"#
1723 .unindent(),
1724 |settings| {
1725 settings
1726 .languages
1727 .get_mut("JSON")
1728 .unwrap()
1729 .language_setting_1 = Some(false);
1730 settings.languages.insert(
1731 "Rust".into(),
1732 LanguageSettingEntry {
1733 language_setting_2: Some(true),
1734 ..Default::default()
1735 },
1736 );
1737 },
1738 r#"{
1739 "languages": {
1740 "Rust": {
1741 "language_setting_2": true
1742 },
1743 "JSON": {
1744 "language_setting_1": false
1745 }
1746 }
1747 }"#
1748 .unindent(),
1749 cx,
1750 );
1751
1752 // weird formatting
1753 check_settings_update::<UserSettings>(
1754 &mut store,
1755 r#"{
1756 "user": { "age": 36, "name": "Max", "staff": true }
1757 }"#
1758 .unindent(),
1759 |settings| settings.age = Some(37),
1760 r#"{
1761 "user": { "age": 37, "name": "Max", "staff": true }
1762 }"#
1763 .unindent(),
1764 cx,
1765 );
1766
1767 // single-line formatting, other keys
1768 check_settings_update::<MultiKeySettings>(
1769 &mut store,
1770 r#"{ "one": 1, "two": 2 }"#.unindent(),
1771 |settings| settings.key1 = Some("x".into()),
1772 r#"{ "key1": "x", "one": 1, "two": 2 }"#.unindent(),
1773 cx,
1774 );
1775
1776 // empty object
1777 check_settings_update::<UserSettings>(
1778 &mut store,
1779 r#"{
1780 "user": {}
1781 }"#
1782 .unindent(),
1783 |settings| settings.age = Some(37),
1784 r#"{
1785 "user": {
1786 "age": 37
1787 }
1788 }"#
1789 .unindent(),
1790 cx,
1791 );
1792
1793 // no content
1794 check_settings_update::<UserSettings>(
1795 &mut store,
1796 r#""#.unindent(),
1797 |settings| settings.age = Some(37),
1798 r#"{
1799 "user": {
1800 "age": 37
1801 }
1802 }
1803 "#
1804 .unindent(),
1805 cx,
1806 );
1807
1808 check_settings_update::<UserSettings>(
1809 &mut store,
1810 r#"{
1811 }
1812 "#
1813 .unindent(),
1814 |settings| settings.age = Some(37),
1815 r#"{
1816 "user": {
1817 "age": 37
1818 }
1819 }
1820 "#
1821 .unindent(),
1822 cx,
1823 );
1824 }
1825
1826 #[gpui::test]
1827 fn test_vscode_import(cx: &mut App) {
1828 let mut store = SettingsStore::new(cx);
1829 store.register_setting::<UserSettings>(cx);
1830 store.register_setting::<JournalSettings>(cx);
1831 store.register_setting::<LanguageSettings>(cx);
1832 store.register_setting::<MultiKeySettings>(cx);
1833
1834 // create settings that werent present
1835 check_vscode_import(
1836 &mut store,
1837 r#"{
1838 }
1839 "#
1840 .unindent(),
1841 r#" { "user.age": 37 } "#.to_owned(),
1842 r#"{
1843 "user": {
1844 "age": 37
1845 }
1846 }
1847 "#
1848 .unindent(),
1849 cx,
1850 );
1851
1852 // persist settings that were present
1853 check_vscode_import(
1854 &mut store,
1855 r#"{
1856 "user": {
1857 "staff": true,
1858 "age": 37
1859 }
1860 }
1861 "#
1862 .unindent(),
1863 r#"{ "user.age": 42 }"#.to_owned(),
1864 r#"{
1865 "user": {
1866 "staff": true,
1867 "age": 42
1868 }
1869 }
1870 "#
1871 .unindent(),
1872 cx,
1873 );
1874
1875 // don't clobber settings that aren't present in vscode
1876 check_vscode_import(
1877 &mut store,
1878 r#"{
1879 "user": {
1880 "staff": true,
1881 "age": 37
1882 }
1883 }
1884 "#
1885 .unindent(),
1886 r#"{}"#.to_owned(),
1887 r#"{
1888 "user": {
1889 "staff": true,
1890 "age": 37
1891 }
1892 }
1893 "#
1894 .unindent(),
1895 cx,
1896 );
1897
1898 // custom enum
1899 check_vscode_import(
1900 &mut store,
1901 r#"{
1902 "journal": {
1903 "hour_format": "hour12"
1904 }
1905 }
1906 "#
1907 .unindent(),
1908 r#"{ "time_format": "24" }"#.to_owned(),
1909 r#"{
1910 "journal": {
1911 "hour_format": "hour24"
1912 }
1913 }
1914 "#
1915 .unindent(),
1916 cx,
1917 );
1918
1919 // Multiple keys for one setting
1920 check_vscode_import(
1921 &mut store,
1922 r#"{
1923 "key1": "value"
1924 }
1925 "#
1926 .unindent(),
1927 r#"{
1928 "key_1_first": "hello",
1929 "key_1_second": "world"
1930 }"#
1931 .to_owned(),
1932 r#"{
1933 "key1": "hello world"
1934 }
1935 "#
1936 .unindent(),
1937 cx,
1938 );
1939
1940 // Merging lists together entries added and updated
1941 check_vscode_import(
1942 &mut store,
1943 r#"{
1944 "languages": {
1945 "JSON": {
1946 "language_setting_1": true
1947 },
1948 "Rust": {
1949 "language_setting_2": true
1950 }
1951 }
1952 }"#
1953 .unindent(),
1954 r#"{
1955 "vscode_languages": [
1956 {
1957 "name": "JavaScript",
1958 "language_setting_1": true
1959 },
1960 {
1961 "name": "Rust",
1962 "language_setting_2": false
1963 }
1964 ]
1965 }"#
1966 .to_owned(),
1967 r#"{
1968 "languages": {
1969 "JavaScript": {
1970 "language_setting_1": true
1971 },
1972 "JSON": {
1973 "language_setting_1": true
1974 },
1975 "Rust": {
1976 "language_setting_2": false
1977 }
1978 }
1979 }"#
1980 .unindent(),
1981 cx,
1982 );
1983 }
1984
1985 fn check_settings_update<T: Settings>(
1986 store: &mut SettingsStore,
1987 old_json: String,
1988 update: fn(&mut T::FileContent),
1989 expected_new_json: String,
1990 cx: &mut App,
1991 ) {
1992 store.set_user_settings(&old_json, cx).ok();
1993 let edits = store.edits_for_update::<T>(&old_json, update);
1994 let mut new_json = old_json;
1995 for (range, replacement) in edits.into_iter() {
1996 new_json.replace_range(range, &replacement);
1997 }
1998 pretty_assertions::assert_eq!(new_json, expected_new_json);
1999 }
2000
2001 fn check_vscode_import(
2002 store: &mut SettingsStore,
2003 old: String,
2004 vscode: String,
2005 expected: String,
2006 cx: &mut App,
2007 ) {
2008 store.set_user_settings(&old, cx).ok();
2009 let new = store.get_vscode_edits(
2010 old,
2011 &VsCodeSettings::from_str(&vscode, VsCodeSettingsSource::VsCode).unwrap(),
2012 );
2013 pretty_assertions::assert_eq!(new, expected);
2014 }
2015
2016 #[derive(Debug, PartialEq, Deserialize)]
2017 struct UserSettings {
2018 name: String,
2019 age: u32,
2020 staff: bool,
2021 }
2022
2023 #[derive(Default, Clone, Serialize, Deserialize, JsonSchema)]
2024 #[schemars(deny_unknown_fields)]
2025 struct UserSettingsContent {
2026 name: Option<String>,
2027 age: Option<u32>,
2028 staff: Option<bool>,
2029 }
2030
2031 impl Settings for UserSettings {
2032 const KEY: Option<&'static str> = Some("user");
2033 type FileContent = UserSettingsContent;
2034
2035 fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
2036 sources.json_merge()
2037 }
2038
2039 fn import_from_vscode(vscode: &VsCodeSettings, current: &mut Self::FileContent) {
2040 vscode.u32_setting("user.age", &mut current.age);
2041 }
2042 }
2043
2044 #[derive(Debug, Deserialize, PartialEq)]
2045 struct TurboSetting(bool);
2046
2047 impl Settings for TurboSetting {
2048 const KEY: Option<&'static str> = Some("turbo");
2049 type FileContent = Option<bool>;
2050
2051 fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
2052 sources.json_merge()
2053 }
2054
2055 fn import_from_vscode(_vscode: &VsCodeSettings, _current: &mut Self::FileContent) {}
2056 }
2057
2058 #[derive(Clone, Debug, PartialEq, Deserialize)]
2059 struct MultiKeySettings {
2060 #[serde(default)]
2061 key1: String,
2062 #[serde(default)]
2063 key2: String,
2064 }
2065
2066 #[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
2067 #[schemars(deny_unknown_fields)]
2068 struct MultiKeySettingsJson {
2069 key1: Option<String>,
2070 key2: Option<String>,
2071 }
2072
2073 impl Settings for MultiKeySettings {
2074 const KEY: Option<&'static str> = None;
2075
2076 type FileContent = MultiKeySettingsJson;
2077
2078 fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
2079 sources.json_merge()
2080 }
2081
2082 fn import_from_vscode(vscode: &VsCodeSettings, current: &mut Self::FileContent) {
2083 let first_value = vscode.read_string("key_1_first");
2084 let second_value = vscode.read_string("key_1_second");
2085
2086 if let Some((first, second)) = first_value.zip(second_value) {
2087 current.key1 = Some(format!("{} {}", first, second));
2088 }
2089 }
2090 }
2091
2092 #[derive(Debug, Deserialize)]
2093 struct JournalSettings {
2094 pub path: String,
2095 pub hour_format: HourFormat,
2096 }
2097
2098 #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
2099 #[serde(rename_all = "snake_case")]
2100 enum HourFormat {
2101 Hour12,
2102 Hour24,
2103 }
2104
2105 #[derive(Clone, Default, Debug, Serialize, Deserialize, JsonSchema)]
2106 #[schemars(deny_unknown_fields)]
2107 struct JournalSettingsJson {
2108 pub path: Option<String>,
2109 pub hour_format: Option<HourFormat>,
2110 }
2111
2112 impl Settings for JournalSettings {
2113 const KEY: Option<&'static str> = Some("journal");
2114
2115 type FileContent = JournalSettingsJson;
2116
2117 fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
2118 sources.json_merge()
2119 }
2120
2121 fn import_from_vscode(vscode: &VsCodeSettings, current: &mut Self::FileContent) {
2122 vscode.enum_setting("time_format", &mut current.hour_format, |s| match s {
2123 "12" => Some(HourFormat::Hour12),
2124 "24" => Some(HourFormat::Hour24),
2125 _ => None,
2126 });
2127 }
2128 }
2129
2130 #[gpui::test]
2131 fn test_global_settings(cx: &mut App) {
2132 let mut store = SettingsStore::new(cx);
2133 store.register_setting::<UserSettings>(cx);
2134 store
2135 .set_default_settings(
2136 r#"{
2137 "user": {
2138 "name": "John Doe",
2139 "age": 30,
2140 "staff": false
2141 }
2142 }"#,
2143 cx,
2144 )
2145 .unwrap();
2146
2147 // Set global settings - these should override defaults but not user settings
2148 store
2149 .set_global_settings(
2150 r#"{
2151 "user": {
2152 "name": "Global User",
2153 "age": 35,
2154 "staff": true
2155 }
2156 }"#,
2157 cx,
2158 )
2159 .unwrap();
2160
2161 // Before user settings, global settings should apply
2162 assert_eq!(
2163 store.get::<UserSettings>(None),
2164 &UserSettings {
2165 name: "Global User".to_string(),
2166 age: 35,
2167 staff: true,
2168 }
2169 );
2170
2171 // Set user settings - these should override both defaults and global
2172 store
2173 .set_user_settings(
2174 r#"{
2175 "user": {
2176 "age": 40
2177 }
2178 }"#,
2179 cx,
2180 )
2181 .unwrap();
2182
2183 // User settings should override global settings
2184 assert_eq!(
2185 store.get::<UserSettings>(None),
2186 &UserSettings {
2187 name: "Global User".to_string(), // Name from global settings
2188 age: 40, // Age from user settings
2189 staff: true, // Staff from global settings
2190 }
2191 );
2192 }
2193
2194 #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
2195 struct LanguageSettings {
2196 #[serde(default)]
2197 languages: HashMap<String, LanguageSettingEntry>,
2198 }
2199
2200 #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
2201 #[schemars(deny_unknown_fields)]
2202 struct LanguageSettingEntry {
2203 language_setting_1: Option<bool>,
2204 language_setting_2: Option<bool>,
2205 }
2206
2207 impl Settings for LanguageSettings {
2208 const KEY: Option<&'static str> = None;
2209
2210 type FileContent = Self;
2211
2212 fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
2213 sources.json_merge()
2214 }
2215
2216 fn import_from_vscode(vscode: &VsCodeSettings, current: &mut Self::FileContent) {
2217 current.languages.extend(
2218 vscode
2219 .read_value("vscode_languages")
2220 .and_then(|value| value.as_array())
2221 .map(|languages| {
2222 languages
2223 .iter()
2224 .filter_map(|value| value.as_object())
2225 .filter_map(|item| {
2226 let mut rest = item.clone();
2227 let name = rest.remove("name")?.as_str()?.to_string();
2228 let entry = serde_json::from_value::<LanguageSettingEntry>(
2229 serde_json::Value::Object(rest),
2230 )
2231 .ok()?;
2232
2233 Some((name, entry))
2234 })
2235 })
2236 .into_iter()
2237 .flatten(),
2238 );
2239 }
2240 }
2241}