feat(config): preserve multiple option keys during bulk writes

Signed-off-by: fufesou <linlong1266@gmail.com>
This commit is contained in:
fufesou committed 2026-11-27 18:50:44 +08:00
1 parent e0e8340993
commit 8d6b5ff455
1 file changed
+31 -11
+31 -11
View File
@@ -641,10 +641,10 @@ impl Config2 {
true true
} }
/// Replaces the configuration while retaining the locally stored entry for `key`. /// Replaces the configuration while keeping each preserved key's stored value or absence.
pub fn set_preserving_option(mut incoming: Self, key: &str) -> bool { pub fn set_preserving_keys(mut incoming: Self, preserved_keys: &[&str]) -> bool {
let mut current = CONFIG2.write().unwrap(); let mut current = CONFIG2.write().unwrap();
current.preserve_option(&mut incoming.options, key); current.preserve_keys(&mut incoming.options, preserved_keys);
if *current == incoming { if *current == incoming {
return false; return false;
} }
@@ -653,11 +653,13 @@ impl Config2 {
true true
} }
fn preserve_option(&self, options: &mut HashMap<String, String>, key: &str) { fn preserve_keys(&self, options: &mut HashMap<String, String>, preserved_keys: &[&str]) {
if let Some(value) = self.options.get(key) { for &key in preserved_keys {
options.insert(key.to_owned(), value.clone()); if let Some(value) = self.options.get(key) {
} else { options.insert(key.to_owned(), value.clone());
options.remove(key); } else {
options.remove(key);
}
} }
} }
} }
@@ -1398,11 +1400,14 @@ impl Config {
config.store(); config.store();
} }
/// Replaces the options while retaining the locally stored entry for `key`. /// Replaces the options while keeping each preserved key's stored value or absence.
pub fn set_options_preserving_option(mut options: HashMap<String, String>, key: &str) { pub fn set_options_preserving_keys(
mut options: HashMap<String, String>,
preserved_keys: &[&str],
) {
Self::purify_options(&mut options); Self::purify_options(&mut options);
let mut current = CONFIG2.write().unwrap(); let mut current = CONFIG2.write().unwrap();
current.preserve_option(&mut options, key); current.preserve_keys(&mut options, preserved_keys);
if current.options != options { if current.options != options {
current.options = options; current.options = options;
current.store(); current.store();
@@ -3532,6 +3537,21 @@ mod tests {
assert_eq!(cfg.salt, "new-salt"); assert_eq!(cfg.salt, "new-salt");
} }
#[test]
fn preserves_multiple_option_keys() {
let mut stored = Config2::default();
stored.options.insert("present".into(), "local".into());
let mut incoming = HashMap::from([
("present".into(), "replacement".into()),
("absent".into(), "new".into()),
("editable".into(), "changed".into()),
]);
stored.preserve_keys(&mut incoming, &["present", "absent"]);
assert_eq!(incoming["present"], "local");
assert!(!incoming.contains_key("absent"));
assert_eq!(incoming["editable"], "changed");
}
#[test] #[test]
fn test_overwrite_settings() { fn test_overwrite_settings() {
DEFAULT_SETTINGS DEFAULT_SETTINGS