settings: Introduce PRESERVED_KEYS to write default values (#15474)

This adds the optional `PRESERVED_KEYS` constant to the `Settings`
trait,
which allows users of the trait to specify which keys should be written
to
the settings file, even if their current value matches the default
value.

That's useful for tagged settings that have, for example, a `"version"`
field
that should always be present in the user settings file, so we can then
reparse
the user settings based on the version.

Co-Authored-By: Thorsten <thorsten@zed.dev>

Release Notes:

- N/A

---------

Co-authored-by: Thorsten <thorsten@zed.dev>
This commit is contained in:
Bennet Bo Fenner 2024-07-30 13:09:50 +02:00 committed by GitHub
parent fa19bc98ac
commit 0540291204
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 85 additions and 96 deletions

View file

@ -28,6 +28,14 @@ pub trait Settings: 'static + Send + Sync {
/// from the root object.
const KEY: Option<&'static str>;
/// The name of the keys in the [`FileContent`] that should always be written to
/// a settings file, even if their value matches the default value.
///
/// This is useful for tagged [`FileContent`]s where the tag is a "version" field
/// that should always be persisted, even if the current user settings match the
/// current version of the settings.
const PRESERVED_KEYS: Option<&'static [&'static str]> = None;
/// The type that is stored in an individual JSON file.
type FileContent: Clone + Default + Serialize + DeserializeOwned + JsonSchema;
@ -407,6 +415,8 @@ impl SettingsStore {
) -> Vec<(Range<usize>, String)> {
let setting_type_id = TypeId::of::<T>();
let preserved_keys = T::PRESERVED_KEYS.unwrap_or_default();
let setting = self
.setting_values
.get(&setting_type_id)
@ -436,6 +446,7 @@ impl SettingsStore {
tab_size,
&old_value,
&new_value,
preserved_keys,
&mut edits,
);
edits
@ -874,6 +885,7 @@ fn update_value_in_json_text<'a>(
tab_size: usize,
old_value: &'a serde_json::Value,
new_value: &'a serde_json::Value,
preserved_keys: &[&str],
edits: &mut Vec<(Range<usize>, String)>,
) {
// If the old and new values are both objects, then compare them key by key,
@ -891,6 +903,7 @@ fn update_value_in_json_text<'a>(
tab_size,
old_sub_value,
new_sub_value,
preserved_keys,
edits,
);
key_path.pop();
@ -904,12 +917,17 @@ fn update_value_in_json_text<'a>(
tab_size,
&serde_json::Value::Null,
new_sub_value,
preserved_keys,
edits,
);
}
key_path.pop();
}
} else if old_value != new_value {
} else if key_path
.last()
.map_or(false, |key| preserved_keys.contains(&key))
|| old_value != new_value
{
let mut new_value = new_value.clone();
if let Some(new_object) = new_value.as_object_mut() {
new_object.retain(|_, v| !v.is_null());