Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

fix(config): preserve unknown keys and comments when rewriting an inline config section (#4120)

Worktrunk Bot988e7aaa218a
diff --git a/src/config/deprecation.rs b/src/config/deprecation.rs
index 654c4ec93..e876ac7c9 100644
--- a/src/config/deprecation.rs
+++ b/src/config/deprecation.rs
@@ -903,6 +903,12 @@ fn has_table_like_child(item: Option<&toml_edit::Item>, key: &str) -> bool {
/// Inline tables can deserialize like tables, but TOML forbids extending them
/// with later subtables. Convert before inserting migrated nested sections so
/// existing inline parent fields survive alongside the new child table.
+///
+/// The conversion goes through [`super::replace_inline_with_table`] so the
+/// key's leading comments and blank lines land above the header rather than
+/// inside its brackets. These rules run on the load path, so a header the key's
+/// decor broke is a config file that stops parsing on every command, not just
+/// one `wt config update` writes back.
fn ensure_standard_table_parent<'a>(
table: &'a mut toml_edit::Table,
key: &str,
@@ -913,11 +919,14 @@ fn ensure_standard_table_parent<'a>(
table.insert(key, toml_edit::Item::Table(parent));
}
- let item = table.get_mut(key)?;
- if let Some(inline) = item.as_inline_table().cloned() {
- *item = toml_edit::Item::Table(inline.into_table());
+ if let Some(inline) = table
+ .get(key)
+ .and_then(|item| item.as_inline_table())
+ .cloned()
+ {
+ super::replace_inline_with_table(table, key, inline.into_table());
}
- item.as_table_mut()
+ table.get_mut(key)?.as_table_mut()
}
/// Convert a table-like TOML item into a `Table`. Returns `None` for other shapes.
@@ -4341,6 +4350,61 @@ pager = "delta --paging=never"
);
}
+ #[test]
+ fn test_migrate_commented_inline_parent_keeps_the_config_loadable() {
+ // The parent has to become a standard table before `[commit.generation]`
+ // can be added, and the key's decor — the comment above it — renders
+ // inside the header brackets. Left there it wrote
+ // `[# my commit settings\ncommit ]`, and because this rule runs before
+ // serde on every load, the user's config stopped parsing entirely.
+ let content = r#"# my commit settings
+commit = { stage = "tracked" }
+commit-generation = { command = "llm" }
+"#;
+ let result = migrate_content(content);
+ assert!(
+ result.contains("# my commit settings\n[commit]"),
+ "the comment belongs above the header, not inside it: {result}"
+ );
+
+ let config = crate::config::UserConfig::load_from_str(content)
+ .unwrap_or_else(|e| panic!("config must still load: {e}\n{result}"));
+ assert_eq!(config.commit.stage, Some(crate::config::StageMode::Tracked));
+ assert_eq!(
+ config
+ .commit
+ .generation
+ .and_then(|generation| generation.command)
+ .as_deref(),
+ Some("llm"),
+ );
+ }
+
+ #[test]
+ fn test_migrate_inline_parent_after_blank_line_keeps_the_config_loadable() {
+ // Same decor path with no comment: a blank line before the inline
+ // section is prefix decor too, which makes any inline section past the
+ // first line of the file a candidate.
+ let content = r#"skip-shell-integration-prompt = true
+
+switch = { cd = false }
+
+[select]
+pager = "delta"
+"#;
+ let config = crate::config::UserConfig::load_from_str(content)
+ .unwrap_or_else(|e| panic!("config must still load: {e}"));
+ assert_eq!(config.switch.cd, Some(false));
+ assert_eq!(
+ config
+ .switch
+ .picker
+ .and_then(|picker| picker.pager)
+ .as_deref(),
+ Some("delta"),
+ );
+ }
+
#[test]
fn test_migrate_select_when_switch_parent_is_inline_table() {
let content = r#"switch = { cd = false }
diff --git a/src/config/mod.rs b/src/config/mod.rs
index 2148baf4f..3d2c034c7 100644
--- a/src/config/mod.rs
+++ b/src/config/mod.rs
@@ -155,6 +155,41 @@ pub fn is_user_project_override_key(key: &str) -> bool {
.any(|k| k == key)
}
+/// Replace a key's inline-table value with a standard table, carrying the key's
+/// leading decor onto the table header.
+///
+/// The key was parsed from `merge = { … }`, so its leaf decor holds whatever
+/// preceded the line — comments, blank lines — plus the space before `=`. A
+/// standard table renders that decor *inside* its brackets, so leaving it in
+/// place writes `[# comment\nmerge ]`: a config file wt can no longer parse,
+/// and the user's own comment is what breaks it. Move the prefix to the header
+/// and drop the rest.
+///
+/// Both places that rewrite a table the user wrote inline go through here — the
+/// save-path merge in `user::persistence`, and `ensure_standard_table_parent`
+/// in `deprecation`, which has no choice but to convert because TOML forbids
+/// extending an inline table with a later subtable. The value's own decor (a
+/// trailing comment after the closing brace) is still dropped by
+/// `InlineTable::into_table`.
+pub(crate) fn replace_inline_with_table(
+ existing: &mut toml_edit::Table,
+ key: &str,
+ mut table: toml_edit::Table,
+) {
+ let prefix = existing
+ .key(key)
+ .and_then(|k| k.leaf_decor().prefix())
+ .filter(|prefix| prefix.as_str() != Some(""))
+ .cloned();
+ if let Some(prefix) = prefix {
+ table.decor_mut().set_prefix(prefix);
+ }
+ if let Some(mut key_mut) = existing.key_mut(key) {
+ key_mut.leaf_decor_mut().clear();
+ }
+ existing[key] = toml_edit::Item::Table(table);
+}
+
// Re-export public types
pub use approvals::{Approvals, approvals_path, require_approvals_path};
pub use commands::{Command, CommandConfig, HookStep, append_aliases};
diff --git a/src/config/user/persistence.rs b/src/config/user/persistence.rs
index 36e4ea8dc..394c4153b 100644
--- a/src/config/user/persistence.rs
+++ b/src/config/user/persistence.rs
@@ -46,8 +46,9 @@ impl UserConfig {
/// - Keys in desired but not existing: inserted
/// - Keys in existing but not desired: removed (unless in `preserve`)
/// - Both standard tables: recurse (preserves existing formatting and comments)
- /// - Existing inline table, desired standard table: compare contents, preserve
- /// inline format when semantically equal
+ /// - Existing inline table, desired standard table: merge through the same
+ /// recursive path, so nested `preserve` applies; the inline format is kept
+ /// when that merge changed nothing
/// - Both exist, values differ: update existing to desired
/// - Both exist, values equal: leave existing unchanged (preserves comments)
fn merge_tables(
@@ -66,6 +67,29 @@ impl UserConfig {
let empty_tree = UnknownTree::default();
for (key, desired_item) in desired.iter() {
+ // Existing inline table, desired standard table: merge into a table
+ // view so the same nested preservation applies as in the
+ // standard-table branch, then write back only if that changed
+ // something — an untouched inline table keeps its formatting.
+ if desired_item.is_table()
+ && let Some(as_table) = existing
+ .get(key)
+ .and_then(|item| item.as_inline_table())
+ .map(|inline| inline.clone().into_table())
+ {
+ let mut merged = as_table.clone();
+ let nested_preserve = preserve.nested.get(key).unwrap_or(&empty_tree);
+ Self::merge_tables(
+ &mut merged,
+ desired_item.as_table().unwrap(),
+ nested_preserve,
+ );
+ if !Self::tables_equal(&as_table, &merged) {
+ crate::config::replace_inline_with_table(existing, key, merged);
+ }
+ continue;
+ }
+
match existing.get_mut(key) {
// Both standard tables: recurse
Some(existing_item) if existing_item.is_table() && desired_item.is_table() => {
@@ -76,20 +100,6 @@ impl UserConfig {
nested_preserve,
);
}
- // Existing inline table, desired standard table: compare contents
- // to preserve the user's inline formatting when nothing changed
- Some(existing_item)
- if existing_item.is_inline_table() && desired_item.is_table() =>
- {
- let as_table = existing_item
- .as_inline_table()
- .unwrap()
- .clone()
- .into_table();
- if !Self::tables_equal(&as_table, desired_item.as_table().unwrap()) {
- *existing_item = desired_item.clone();
- }
- }
Some(existing_item) => {
if !Self::items_equal(existing_item, desired_item) {
*existing_item = desired_item.clone();
@@ -111,19 +121,44 @@ impl UserConfig {
}
}
+ /// Compare two Values for equality, ignoring formatting.
+ ///
+ /// A variant with no arm of its own answers "not equal" for a value that
+ /// never changed, and in the inline-table branch of `merge_tables` "not
+ /// equal" is what rewrites the user's inline section as a standard table.
+ /// So the mismatched-variant arm spells out every variant instead of using
+ /// `_`: adding one to `toml_edit::Value` is then a compile error here
+ /// rather than a section that silently stops keeping its formatting.
fn values_equal(a: &toml_edit::Value, b: &toml_edit::Value) -> bool {
use toml_edit::Value;
match (a, b) {
(Value::String(a), Value::String(b)) => a.value() == b.value(),
(Value::Integer(a), Value::Integer(b)) => a.value() == b.value(),
(Value::Boolean(a), Value::Boolean(b)) => a.value() == b.value(),
+ (Value::Float(a), Value::Float(b)) => a.value() == b.value(),
+ (Value::Datetime(a), Value::Datetime(b)) => a.value() == b.value(),
+ (Value::InlineTable(a), Value::InlineTable(b)) => {
+ a.len() == b.len()
+ && a.iter()
+ .all(|(k, v)| b.get(k).is_some_and(|bv| Self::values_equal(v, bv)))
+ }
(Value::Array(a), Value::Array(b)) => {
a.len() == b.len()
&& a.iter()
.zip(b.iter())
.all(|(a, b)| Self::values_equal(a, b))
}
- _ => false,
+ // Two different variants. Exhaustive on purpose — see above.
+ (
+ Value::String(_)
+ | Value::Integer(_)
+ | Value::Float(_)
+ | Value::Boolean(_)
+ | Value::Datetime(_)
+ | Value::Array(_)
+ | Value::InlineTable(_),
+ _,
+ ) => false,
}
}
diff --git a/src/config/user/tests.rs b/src/config/user/tests.rs
index ba3f9d520..fb0a183c5 100644
--- a/src/config/user/tests.rs
+++ b/src/config/user/tests.rs
@@ -3681,6 +3681,172 @@ future-per-project = "value"
);
}
+#[test]
+fn test_save_to_existing_file_preserves_unknown_keys_in_inline_table() {
+ // An unknown key inside an *inline* section must survive a save just as it
+ // does inside a standard `[merge]` table. The inline branch of the merge
+ // used to replace the whole item, so the unknown key went with it.
+ let dir = tempfile::tempdir().unwrap();
+ let config_path = dir.path().join("config.toml");
+ std::fs::write(
+ &config_path,
+ "merge = { squash = false, future-option = true }\n",
+ )
+ .unwrap();
+
+ let mut config =
+ UserConfig::load_from_str(&std::fs::read_to_string(&config_path).unwrap()).unwrap();
+ 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("future-option = true"),
+ "unknown key inside an inline table should be preserved: {saved}"
+ );
+ assert!(
+ saved.contains("skip-shell-integration-prompt = true"),
+ "the unrelated change should still be written: {saved}"
+ );
+ // Nothing in the inline table changed, so its formatting survives too.
+ assert!(
+ saved.contains("merge = { squash = false, future-option = true }"),
+ "unchanged inline table should keep its formatting: {saved}"
+ );
+}
+
+#[test]
+fn test_save_to_existing_file_preserves_unknown_keys_when_inline_table_changes() {
+ // Same preservation when a known value inside the inline table does change:
+ // `squash` is rewritten, `future-option` stays.
+ let dir = tempfile::tempdir().unwrap();
+ let config_path = dir.path().join("config.toml");
+ std::fs::write(
+ &config_path,
+ "merge = { squash = false, future-option = true }\n",
+ )
+ .unwrap();
+
+ let mut config =
+ UserConfig::load_from_str(&std::fs::read_to_string(&config_path).unwrap()).unwrap();
+ config.merge.squash = Some(true);
+ config.save_to(&config_path).unwrap();
+
+ let saved = std::fs::read_to_string(&config_path).unwrap();
+ assert!(
+ saved.contains("future-option = true"),
+ "unknown key should survive a changed inline table: {saved}"
+ );
+ assert!(
+ saved.contains("squash = true"),
+ "changed value should be written: {saved}"
+ );
+}
+
+#[test]
+fn test_save_to_existing_file_preserves_nested_inline_table_formatting() {
+ // An inline section whose child is itself an inline table must keep its
+ // formatting when nothing inside it changed. `values_equal` had no
+ // `InlineTable` arm, so two identical inline tables never compared equal
+ // and the whole section was rewritten as a standard table.
+ let dir = tempfile::tempdir().unwrap();
+ let config_path = dir.path().join("config.toml");
+ let original = "commit = { generation = { command = \"summarize\" } }\n";
+ std::fs::write(&config_path, original).unwrap();
+
+ let mut config = UserConfig::load_from_str(original).unwrap();
+ 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("commit = { generation = { command = \"summarize\" } }"),
+ "unchanged nested inline table should keep its formatting: {saved}"
+ );
+ assert!(
+ !saved.contains("[commit"),
+ "should not be expanded to a standard table: {saved}"
+ );
+ assert!(
+ saved.contains("skip-shell-integration-prompt = true"),
+ "the unrelated change should still be written: {saved}"
+ );
+}
+
+#[test]
+fn test_save_to_rewrites_commented_inline_section_as_parseable_toml() {
+ // Changing a value inside an inline section rewrites it as a standard
+ // table. The key's decor — the comment above it and the space before `=` —
+ // renders inside the table header, so the comment used to land between the
+ // brackets and the file wt wrote back no longer parsed.
+ let dir = tempfile::tempdir().unwrap();
+ let config_path = dir.path().join("config.toml");
+ let original = "# why squash is off\nmerge = { squash = false, future-option = true }\n";
+ std::fs::write(&config_path, original).unwrap();
+
+ let mut config = UserConfig::load_from_str(original).unwrap();
+ config.merge.squash = Some(true);
+ config.save_to(&config_path).unwrap();
+
+ let saved = std::fs::read_to_string(&config_path).unwrap();
+ UserConfig::load_from_str(&saved)
+ .unwrap_or_else(|e| panic!("saved config must still parse: {e}\n{saved}"));
+ assert!(
+ saved.contains("# why squash is off\n[merge]"),
+ "the comment belongs above the header, not inside it: {saved}"
+ );
+ assert!(
+ saved.contains("future-option = true"),
+ "unknown key should survive: {saved}"
+ );
+}
+
+#[test]
+fn test_save_to_rewrites_blank_line_separated_inline_section_as_parseable_toml() {
+ // Same decor path with no comment: a blank line before the inline section
+ // is prefix decor too, and rendered inside the brackets it broke the file.
+ let dir = tempfile::tempdir().unwrap();
+ let config_path = dir.path().join("config.toml");
+ let original = "skip-shell-integration-prompt = true\n\nmerge = { squash = false }\n";
+ std::fs::write(&config_path, original).unwrap();
+
+ let mut config = UserConfig::load_from_str(original).unwrap();
+ config.merge.squash = Some(true);
+ config.save_to(&config_path).unwrap();
+
+ let saved = std::fs::read_to_string(&config_path).unwrap();
+ let reloaded = UserConfig::load_from_str(&saved)
+ .unwrap_or_else(|e| panic!("saved config must still parse: {e}\n{saved}"));
+ assert_eq!(reloaded.merge.squash, Some(true));
+}
+
+#[test]
+fn test_save_to_existing_file_preserves_inline_table_with_float_and_datetime() {
+ // Every `Value` variant needs an arm in `values_equal`: a pair it doesn't
+ // match falls through to "not equal", which reports an untouched inline
+ // section as changed and expands it to a standard table. Floats and
+ // datetimes only reach a user config as unknown keys — a typo, or a field
+ // from a newer wt — which is exactly what the inline branch preserves.
+ let dir = tempfile::tempdir().unwrap();
+ let config_path = dir.path().join("config.toml");
+ let original = "merge = { squash = false, future-timeout = 1.5, future-since = 1979-05-27 }\n";
+ std::fs::write(&config_path, original).unwrap();
+
+ let mut config = UserConfig::load_from_str(original).unwrap();
+ 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(original.trim_end()),
+ "unchanged inline table should keep its formatting: {saved}"
+ );
+ assert!(
+ saved.contains("skip-shell-integration-prompt = true"),
+ "the unrelated change should still be written: {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 = { ... }`),