Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(config): preserve nested unknown keys on save (#2180)
Maximilian Roos91dc9d679703
diff --git a/src/config/user/persistence.rs b/src/config/user/persistence.rsindex 7d1ed57f2..9bbfe7686 100644--- a/src/config/user/persistence.rs+++ b/src/config/user/persistence.rs@@ -13,6 +13,81 @@ use crate::config::ConfigError;use super::UserConfig;use super::sections::CommitGenerationConfig;+/// Keys to preserve during a diff-based merge, organized by nesting level.+///+/// Populated from schema-unknown paths in the existing TOML (keys that serde+/// would silently drop during deserialization). These survive the save so+/// hand-edited settings and fields from newer wt versions aren't lost.+#[derive(Default, Debug)]+struct PreserveTree {+ /// Keys at this level to keep even when absent from the serialized desired state.+ keys: std::collections::HashSet<String>,+ /// Sub-trees for nested tables, mirroring the TOML structure.+ nested: std::collections::HashMap<String, PreserveTree>,+}++impl PreserveTree {+ fn is_empty(&self) -> bool {+ self.keys.is_empty() && self.nested.is_empty()+ }+}++/// Build a [`PreserveTree`] from the on-disk content by round-tripping through+/// [`UserConfig`]. Any path present in the raw TOML but absent from the+/// reserialized form is schema-unknown and flagged for preservation.+///+/// `existing_content` is already-validated TOML (parsed as+/// `toml_edit::DocumentMut` earlier in `save_to`), so the parses here are+/// invariants. `try_into::<UserConfig>` can fail on type mismatches (e.g.,+/// `commit = "scalar"` from a hand edit) — the `unwrap_or_default()` fallback+/// marks every key as unknown so the merge preserves the file contents rather+/// than silently discarding data.+fn compute_preserve_tree(existing_content: &str) -> PreserveTree {+ let raw: toml::Table = existing_content+ .parse()+ .expect("existing content already validated by toml_edit");+ let config: UserConfig = toml::Value::Table(raw.clone())+ .try_into()+ .unwrap_or_default();+ let reserialized: toml::Table = toml::to_string(&config)+ .expect("UserConfig is serializable")+ .parse()+ .expect("UserConfig serializes to valid TOML");+ diff_tables(&raw, &reserialized)+}++/// Walk `raw` against `known` (the schema-projected view) and record keys+/// that exist only in `raw`. Recurses into nested tables so deeply-nested+/// unknown keys are captured at the right level.+fn diff_tables(raw: &toml::Table, known: &toml::Table) -> PreserveTree {+ let mut tree = PreserveTree::default();+ for (key, raw_val) in raw {+ match (known.get(key), raw_val) {+ (Some(toml::Value::Table(known_t)), toml::Value::Table(raw_t)) => {+ let nested = diff_tables(raw_t, known_t);+ if !nested.is_empty() {+ tree.nested.insert(key.clone(), nested);+ }+ }+ (Some(_), _) => {}+ (None, toml::Value::Table(raw_t)) => {+ // Whole subtree is schema-unknown. Mark the key at this level+ // and recurse so the preserve set is populated if a later+ // mutation causes `desired` to introduce this table.+ tree.keys.insert(key.clone());+ let nested = diff_tables(raw_t, &toml::Table::new());+ if !nested.is_empty() {+ tree.nested.insert(key.clone(), nested);+ }+ }+ (None, _) => {+ tree.keys.insert(key.clone());+ }+ }+ }+ tree+}+impl UserConfig {/// Recursively convert inline tables to standard tables for readability.///@@ -54,26 +129,27 @@ impl UserConfig {fn merge_tables(existing: &mut toml_edit::Table,desired: &toml_edit::Table,- preserve: &std::collections::HashSet<String>,+ preserve: &PreserveTree,) {let stale_keys: Vec<_> = existing.iter().map(|(k, _)| k.to_string())- .filter(|k| !desired.contains_key(k) && !preserve.contains(k))+ .filter(|k| !desired.contains_key(k) && !preserve.keys.contains(k)).collect();for key in &stale_keys {existing.remove(key);}- let empty = std::collections::HashSet::new();+ let empty_tree = PreserveTree::default();for (key, desired_item) in desired.iter() {match existing.get_mut(key) {// Both standard tables: recurseSome(existing_item) if existing_item.is_table() && desired_item.is_table() => {+ let nested_preserve = preserve.nested.get(key).unwrap_or(&empty_tree);Self::merge_tables(existing_item.as_table_mut().unwrap(),desired_item.as_table().unwrap(),- &empty,+ nested_preserve,);}// Existing inline table, desired standard table: compare contents@@ -137,7 +213,9 @@ impl UserConfig {////// Preserves comments and formatting in the existing file by diffing the/// serialized in-memory state against the parsed file and merging only- /// changed keys.+ /// changed keys. Schema-unknown keys at any nesting level (typos, fields+ /// from newer wt versions) are preserved so older wt versions don't+ /// silently strip forward-compatible config data.pub fn save_to(&self, config_path: &std::path::Path) -> Result<(), ConfigError> {if let Some(parent) = config_path.parent() {std::fs::create_dir_all(parent)@@ -156,17 +234,15 @@ impl UserConfig {.map_err(|e| ConfigError(format!("Serialization error: {e}")))?;Self::expand_inline_tables(desired_doc.as_table_mut());- // Preserve unknown top-level keys (typos, future fields, deprecated- // keys not yet migrated) so they aren't silently deleted on save.- let unknown_keys: std::collections::HashSet<String> =- super::find_unknown_keys(&existing_content)- .into_keys()- .collect();+ // Preserve unknown keys at every nesting level (typos, future+ // fields, deprecated keys not yet migrated) so they aren't+ // silently deleted on save.+ let preserve = compute_preserve_tree(&existing_content);Self::merge_tables(existing_doc.as_table_mut(),desired_doc.as_table(),- &unknown_keys,+ &preserve,);Self::make_commit_table_implicit_if_only_subtables(&mut existing_doc);diff --git a/src/config/user/tests.rs b/src/config/user/tests.rsindex 3418d7e8d..f7254a980 100644--- a/src/config/user/tests.rs+++ b/src/config/user/tests.rs@@ -3096,6 +3096,166 @@ skip-shell-integration-prompt = true);}+#[test]+fn test_save_to_existing_file_preserves_nested_unknown_keys() {+ // Unknown keys inside a known table (e.g., a newer-version field under+ // `[merge]`) must survive a save that touches unrelated settings. Older+ // wt versions should leave config data they don't recognize alone.+ let dir = tempfile::tempdir().unwrap();+ let config_path = dir.path().join("config.toml");+ std::fs::write(+ &config_path,+ r#"[merge]+squash = false+future-option = true+"#,+ )+ .unwrap();++ // Mutate an unrelated setting so save_to() writes the file.+ let config = UserConfig {+ skip_shell_integration_prompt: true,+ merge: MergeConfig {+ squash: Some(false),+ ..Default::default()+ },+ ..Default::default()+ };++ config.save_to(&config_path).unwrap();++ let saved = std::fs::read_to_string(&config_path).unwrap();+ assert!(+ saved.contains("future-option = true"),+ "nested unknown key should be preserved: {saved}"+ );+ assert!(+ saved.contains("squash = false"),+ "known sibling should be preserved: {saved}"+ );+ assert!(+ saved.contains("skip-shell-integration-prompt = true"),+ "new top-level key should be written: {saved}"+ );+}++#[test]+fn test_save_to_existing_file_preserves_section_with_only_unknown_fields() {+ // A section whose known fields are all absent/default (so reserialization+ // skips the whole section) but that still contains unknown keys must+ // survive the save — including when a mutation later introduces a known+ // field to the same section.+ let dir = tempfile::tempdir().unwrap();+ let config_path = dir.path().join("config.toml");+ std::fs::write(+ &config_path,+ r#"[merge]+future-option = true+"#,+ )+ .unwrap();++ // Mutation introduces a known field to `[merge]` that wasn't on disk.+ let config = UserConfig {+ merge: MergeConfig {+ squash: Some(false),+ ..Default::default()+ },+ ..Default::default()+ };++ config.save_to(&config_path).unwrap();++ let saved = std::fs::read_to_string(&config_path).unwrap();+ assert!(+ saved.contains("future-option = true"),+ "unknown key in otherwise-empty section should be preserved: {saved}"+ );+ assert!(+ saved.contains("squash = false"),+ "new known field should be written: {saved}"+ );+}++#[test]+fn test_save_to_existing_file_preserves_deeply_nested_unknown_keys() {+ // Unknown keys inside a doubly-nested table (e.g., `[commit.generation]`)+ // must also survive — the preserve set needs to traverse to the right level.+ let dir = tempfile::tempdir().unwrap();+ let config_path = dir.path().join("config.toml");+ std::fs::write(+ &config_path,+ r#"[commit.generation]+command = "old-llm"+future-knob = "from-newer-wt"+"#,+ )+ .unwrap();++ let config = UserConfig {+ commit: CommitConfig {+ stage: None,+ generation: Some(CommitGenerationConfig {+ command: Some("new-llm".to_string()),+ ..Default::default()+ }),+ },+ ..Default::default()+ };++ config.save_to(&config_path).unwrap();++ let saved = std::fs::read_to_string(&config_path).unwrap();+ assert!(+ saved.contains(r#"future-knob = "from-newer-wt""#),+ "nested unknown key should be preserved: {saved}"+ );+ assert!(+ saved.contains(r#"command = "new-llm""#),+ "known field should be updated: {saved}"+ );+ assert!(!saved.contains("old-llm"), "old value not removed: {saved}");+}++#[test]+fn test_save_to_existing_file_preserves_unknown_keys_in_project_section() {+ // Unknown keys inside a project entry (e.g., `[projects."name"]`) are also+ // at a nested level — the fix must cover entries inside the projects map too.+ let dir = tempfile::tempdir().unwrap();+ let config_path = dir.path().join("config.toml");+ std::fs::write(+ &config_path,+ r#"[projects."repo"]+worktree-path = "../custom"+future-per-project = "value"+"#,+ )+ .unwrap();++ let mut config = UserConfig::default();+ config.projects.insert(+ "repo".to_string(),+ UserProjectOverrides {+ worktree_path: Some("../custom".to_string()),+ ..Default::default()+ },+ );+ // Flip an unrelated flag so save_to() has a reason to write.+ config.skip_shell_integration_prompt = true;++ config.save_to(&config_path).unwrap();++ let saved = std::fs::read_to_string(&config_path).unwrap();+ assert!(+ saved.contains(r#"future-per-project = "value""#),+ "unknown key inside a project entry should be preserved: {saved}"+ );+ assert!(+ saved.contains(r#"worktree-path = "../custom""#),+ "known field should be preserved: {saved}"+ );+}+#[test]fn test_save_to_existing_file_preserves_inline_table_formatting() {// When a user writes a hook as an inline table (e.g., `post-start = { ... }`),