Skip to content

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

fix(config): keep default values written out in the file when a save doesn't change them (#4156)

Maximilian Roos718d26a85905
diff --git a/src/config/deprecation.rs b/src/config/deprecation.rs
index 4ece059c6..4c9d5cc1d 100644
--- a/src/config/deprecation.rs
+++ b/src/config/deprecation.rs
@@ -714,11 +714,7 @@ const DEPRECATION_RULES: &[DeprecationRule] = &[
// but in-memory migration to canonical keeps round-trip analysis
// (`unknown_tree`) coherent for the table and array-of-tables forms,
// where serde aliases on the field don't cover every shape.
- DeprecationRule::Silent(|doc| {
- let pre = rename_hook_key(doc, "pre-create", "pre-start");
- let post = rename_hook_key(doc, "post-create", "post-start");
- pre || post
- }),
+ DeprecationRule::Silent(canonicalize_hook_keys),
// [ci] → [forge]. Moves `platform` only; unrelated `[ci]` keys stay where
// the user wrote them, so they keep warning at their own path rather than
// being relocated (contrast the wholesale-move rules above, which drop
@@ -1433,35 +1429,37 @@ fn migrate_content_doc(doc: &mut toml_edit::DocumentMut) -> bool {
apply_rules(doc, RulePass::Load, &mut Vec::new())
}
-/// Rename `old_key` to `new_key` at the top level and under each `[projects."..."]`.
+/// Rename the `pre-create`/`post-create` hook aliases to `pre-start`/`post-start`,
+/// in every config scope (see [`for_each_config_table_mut`]).
///
-/// Skips any location where `new_key` already exists — the user has already
+/// Config saves run this on the file they merge into too
+/// (`UserConfig::save_to`): the config being saved serializes only the
+/// canonical names, so a hook left under its alias would be written a second
+/// time beside it, and serde rejects the duplicate on the next load.
+pub(crate) fn canonicalize_hook_keys(doc: &mut toml_edit::DocumentMut) -> bool {
+ for_each_config_table_mut(doc, |_, table| {
+ let pre = rename_hook_key(table, "pre-create", "pre-start");
+ let post = rename_hook_key(table, "post-create", "post-start");
+ pre || post
+ })
+}
+
+/// Rename `old_key` to `new_key` in `table`, keeping the comment lines above it.
+///
+/// Skips a table where `new_key` already exists — the user has already
/// consolidated there, and clobbering their canonical value would lose config.
/// The rewrite preserves the value shape (string, `[table]`, or
/// `[[array-of-tables]]`) since it moves the `Item` unchanged.
-fn rename_hook_key(doc: &mut toml_edit::DocumentMut, old_key: &str, new_key: &str) -> bool {
- let mut modified = false;
-
- if doc.get(new_key).is_none()
- && let Some(value) = doc.remove(old_key)
- {
- doc.insert(new_key, value);
- modified = true;
- }
-
- if let Some(projects) = doc.get_mut("projects").and_then(|p| p.as_table_mut()) {
- for (_key, project_value) in projects.iter_mut() {
- if let Some(project_table) = project_value.as_table_mut()
- && project_table.get(new_key).is_none()
- && let Some(value) = project_table.remove(old_key)
- {
- project_table.insert(new_key, value);
- modified = true;
- }
- }
+fn rename_hook_key(table: &mut toml_edit::Table, old_key: &str, new_key: &str) -> bool {
+ if table.contains_key(new_key) {
+ return false;
}
-
- modified
+ let Some((key, item)) = table.remove_entry(old_key) else {
+ return false;
+ };
+ let renamed = toml_edit::Key::new(new_key).with_leaf_decor(key.leaf_decor().clone());
+ table.insert_formatted(&renamed, item);
+ true
}
/// Remove `key` from a top-level `section` in a table, dropping a
@@ -4981,42 +4979,42 @@ pager = "delta --paging=never"
/// The silent create-hooks rule renames the deprecated `pre-create`/`post-create`
/// keys to canonical `pre-start`/`post-start`, preserving the value shape
- /// (string, `[table]`, `[[array-of-tables]]`) at both the top level and
- /// inside `[projects."..."]`.
+ /// (string, `[table]`, `[[array-of-tables]]`) and the comment above the key,
+ /// at the top level and inside `[projects."..."]` entries written either as
+ /// tables or inline.
#[test]
fn test_migrate_create_hooks_renames_every_shape() {
- let content = r#"pre-create = "npm install"
+ let content = r#"# install first
+pre-create = "npm install"
[[post-create]]
lint = "cargo clippy"
+[projects]
+"inline-project" = { post-create = "make" }
+
[projects."my-project"]
pre-create = "cargo build"
[projects."my-project".post-create]
server = "npm run dev"
"#;
- let result = migrate_content(content);
- assert!(
- !result.contains("pre-create") && !result.contains("post-create"),
- "no deprecated key may remain; got:\n{result}"
- );
- assert!(
- result.contains(r#"pre-start = "npm install""#),
- "top-level string renamed; got:\n{result}"
- );
- assert!(
- result.contains("[[post-start]]"),
- "top-level array-of-tables renamed; got:\n{result}"
- );
- assert!(
- result.contains(r#"pre-start = "cargo build""#),
- "per-project string renamed; got:\n{result}"
- );
- assert!(
- result.contains(r#"[projects."my-project".post-start]"#),
- "per-project table renamed; got:\n{result}"
- );
+ insta::assert_snapshot!(migrate_content(content), @r#"
+ # install first
+ pre-start = "npm install"
+
+ [[post-start]]
+ lint = "cargo clippy"
+
+ [projects]
+ "inline-project" = { post-start = "make" }
+
+ [projects."my-project"]
+ pre-start = "cargo build"
+
+ [projects."my-project".post-start]
+ server = "npm run dev"
+ "#);
}
/// When the canonical `-start` key already exists, the migrator leaves the
diff --git a/src/config/mod.rs b/src/config/mod.rs
index 08788e7bf..d6daeb8a3 100644
--- a/src/config/mod.rs
+++ b/src/config/mod.rs
@@ -156,7 +156,7 @@ pub fn is_user_project_override_key(key: &str) -> bool {
}
/// Replace a key's inline-table value with a standard table, carrying the line's
-/// comments onto the table header.
+/// comments onto the first header the table writes.
///
/// The key was parsed from `merge = { … }`, so its leaf decor holds whatever
/// preceded the line — comments, blank lines — plus the space before `=`. A
@@ -171,6 +171,10 @@ pub fn is_user_project_override_key(key: &str) -> bool {
/// carried only when it holds a comment; bare whitespace there would just trail
/// the header.
///
+/// An implicit table with no values of its own writes no header — `toml_edit`
+/// hides it — so both comments go on its first subtable's header instead:
+/// `commit = { generation = { … } }` becomes `[commit.generation]` alone.
+///
/// 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
@@ -185,17 +189,29 @@ pub(crate) fn replace_inline_with_table(
.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);
- }
let suffix = existing
.get(key)
.and_then(|item| item.as_inline_table())
.and_then(|inline| inline.decor().suffix())
.filter(|suffix| suffix.as_str().is_some_and(|s| s.contains('#')))
.cloned();
- if let Some(suffix) = suffix {
- table.decor_mut().set_suffix(suffix);
+ let first_subtable = (table.is_implicit() && table.get_values().is_empty())
+ .then(|| table.iter().find(|(_, item)| item.is_table()))
+ .flatten()
+ .map(|(subtable, _)| subtable.to_owned());
+ let header = match &first_subtable {
+ Some(subtable) => table
+ .get_mut(subtable)
+ .and_then(toml_edit::Item::as_table_mut),
+ None => Some(&mut table),
+ };
+ if let Some(header) = header {
+ if let Some(prefix) = prefix {
+ header.decor_mut().set_prefix(prefix);
+ }
+ if let Some(suffix) = suffix {
+ header.decor_mut().set_suffix(suffix);
+ }
}
if let Some(mut key_mut) = existing.key_mut(key) {
key_mut.leaf_decor_mut().clear();
@@ -255,7 +271,7 @@ pub use project::{
ProjectForgeConfig, ProjectListConfig, valid_project_config_keys,
};
pub use unknown_tree::{
- UnknownAnalysis, UnknownTree, UnknownWarning, collect_unknown_warnings, compute_unknown_tree,
+ UnknownTree, UnknownWarning, collect_unknown_warnings, compute_unknown_tree,
};
pub use user::LoadError;
pub(crate) use user::project_match::matching_keys as matching_project_keys;
@@ -672,17 +688,11 @@ task2 = "echo 'Task 2 running' > task2.txt"
}
fn project_warn_tree(contents: &str) -> UnknownTree {
- compute_unknown_tree::<ProjectConfig>(contents)
- .warn_tree()
- .cloned()
- .unwrap()
+ compute_unknown_tree::<ProjectConfig>(contents).unwrap()
}
fn user_warn_tree(contents: &str) -> UnknownTree {
- compute_unknown_tree::<UserConfig>(contents)
- .warn_tree()
- .cloned()
- .unwrap()
+ compute_unknown_tree::<UserConfig>(contents).unwrap()
}
#[test]
@@ -728,16 +738,8 @@ task2 = "echo 'Task 2 running' > task2.txt"
#[test]
fn test_unknown_tree_invalid_toml() {
let toml = "this is not valid toml {{{";
- assert!(
- compute_unknown_tree::<ProjectConfig>(toml)
- .warn_tree()
- .is_none()
- );
- assert!(
- compute_unknown_tree::<UserConfig>(toml)
- .warn_tree()
- .is_none()
- );
+ assert!(compute_unknown_tree::<ProjectConfig>(toml).is_none());
+ assert!(compute_unknown_tree::<UserConfig>(toml).is_none());
}
#[test]
diff --git a/src/config/unknown_tree.rs b/src/config/unknown_tree.rs
index 2e0b8054f..411670744 100644
--- a/src/config/unknown_tree.rs
+++ b/src/config/unknown_tree.rs
@@ -1,16 +1,11 @@
//! Nested schema-unknown analysis for worktrunk config files.
//!
-//! A single round-trip through a [`WorktrunkConfig`] type answers both
-//! load-time questions ("which keys does serde silently drop?") and save-time
-//! questions ("which keys must survive the diff-based merge?"). Reserializing
-//! the parsed config and diffing against the raw TOML identifies every
-//! schema-unknown path at any nesting depth.
+//! A round-trip through a [`WorktrunkConfig`] type answers "which keys does
+//! serde silently drop?": reserializing the parsed config and diffing against
+//! the raw TOML identifies every schema-unknown path at any nesting depth.
//!
-//! The same tree drives:
-//! - Unknown-key warnings (`warn_unknown_fields`, `config show`) — emits one
-//! message at the shallowest level where a path is unknown.
-//! - Save-path preservation (`UserConfig::save_to`) — prevents the merge from
-//! dropping hand-edited or forward-compat fields.
+//! The tree drives unknown-key warnings (`warn_unknown_fields`, `config show`),
+//! which emit one message at the shallowest level where a path is unknown.
use std::collections::{BTreeMap, BTreeSet};
@@ -18,11 +13,9 @@ use crate::config::WorktrunkConfig;
/// A nested set of schema-unknown paths within a config file.
///
-/// `keys` holds unknown keys at the current level. Entries in `nested` are for
-/// keys that are themselves *known* but contain unknown children. A key may
-/// appear in both when the entire subtree is unknown — `keys` captures the top
-/// of the unknown subtree, `nested` mirrors it so save-path merges still
-/// preserve individual descendants if a mutation later introduces the table.
+/// `keys` holds unknown keys at the current level, each covering its whole
+/// subtree. Entries in `nested` are for keys that are themselves *known* but
+/// contain unknown children.
#[derive(Default, Debug, Clone)]
pub struct UnknownTree {
pub keys: BTreeSet<String>,
@@ -35,69 +28,34 @@ impl UnknownTree {
}
}
-/// Outcome of analyzing a config file for schema-unknown paths.
-///
-/// The `Unreliable` variant covers both syntax errors and type mismatches
-/// (e.g., a hand edit like `commit = "scalar"`). In those cases we can't tell
-/// schema-unknown paths from schema-known-but-wrong-type ones, so:
-/// - Save paths must preserve every on-disk key (the tree marks everything).
-/// - Warning paths must stay silent (the parse/type error is surfaced by the
-/// regular load path with accurate line/column info).
-#[derive(Debug)]
-pub enum UnknownAnalysis {
- /// `try_into<C>` succeeded; the tree lists schema-unknown paths only.
- Parsed(UnknownTree),
- /// Raw TOML was unparsable or failed type-checking against `C`. The tree
- /// still marks every on-disk key so save-path merges preserve data.
- Unreliable(UnknownTree),
-}
-
-impl UnknownAnalysis {
- /// Tree suitable for the save-path merge (preserves unknowns, and
- /// preserves everything on unreliable input).
- pub fn preserve_tree(&self) -> &UnknownTree {
- match self {
- Self::Parsed(t) | Self::Unreliable(t) => t,
- }
- }
-
- /// Tree suitable for unknown-key warnings (empty on unreliable input).
- pub fn warn_tree(&self) -> Option<&UnknownTree> {
- match self {
- Self::Parsed(t) => Some(t),
- Self::Unreliable(_) => None,
- }
- }
-}
-
/// Analyze `contents` against config type `C` by round-tripping through serde.
///
-/// On success, the returned tree captures every path in `contents` that
+/// `None` when `contents` is unparsable or fails type-checking against `C`
+/// (e.g., a hand edit like `commit = "scalar"`): schema-unknown paths can't be
+/// told from schema-known-but-wrong-type ones, so warning callers stay silent
+/// and leave the error to the regular load path, which reports it with line
+/// and column.
+///
+/// Otherwise the returned tree captures every path in `contents` that
/// reserialization drops — i.e., every schema-unknown path. Top-level keys
/// that serialize away when empty (e.g., `[merge]` with only unknown children
/// leaves `MergeConfig::default()`, which `skip_serializing_if` omits) are
/// rescued by seeding the comparison with the JsonSchema key list: a known
/// section that isn't in the reserialized form is treated as present-but-empty
/// so only its unknown *children* get flagged, not the section itself.
-pub fn compute_unknown_tree<C>(contents: &str) -> UnknownAnalysis
+pub fn compute_unknown_tree<C>(contents: &str) -> Option<UnknownTree>
where
C: WorktrunkConfig,
{
- let Ok(raw) = contents.parse::<toml::Table>() else {
- return UnknownAnalysis::Unreliable(UnknownTree::default());
- };
-
- let parsed: Result<C, _> = toml::Value::Table(raw.clone()).try_into();
- let Ok(config) = parsed else {
- return UnknownAnalysis::Unreliable(diff_tables(&raw, &toml::Table::new()));
- };
+ let raw = contents.parse::<toml::Table>().ok()?;
+ let config: C = toml::Value::Table(raw.clone()).try_into().ok()?;
let mut reserialized: toml::Table = toml::to_string(&config)
.expect("config type is serializable")
.parse()
.expect("serialized config is valid TOML");
seed_schema_skeleton::<C>(&mut reserialized);
- UnknownAnalysis::Parsed(diff_tables(&raw, &reserialized))
+ Some(diff_tables(&raw, &reserialized))
}
/// Seed `reserialized` with every schema-valid top-level key as an empty
@@ -124,16 +82,6 @@ fn diff_tables(raw: &toml::Table, known: &toml::Table) -> UnknownTree {
}
}
(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());
}
@@ -232,8 +180,8 @@ impl<'a> OtherStatus<'a> {
///
/// A misplaced *nested* key is redirected to `C::Other` when it's valid there
/// — determined by walking `C::Other`'s own unknown tree for the same content
-/// (see the private `OtherStatus` helper). If that other-config analysis is
-/// unreliable, the walk falls back to treating nested keys as unknown, so only
+/// (see the private `OtherStatus` helper). If the content doesn't parse as
+/// `C::Other`, the walk falls back to treating nested keys as unknown, so only
/// the hard-coded
/// [`nested_key_belongs_in`](crate::config::nested_key_belongs_in) redirects
/// still fire.
@@ -242,25 +190,23 @@ impl<'a> OtherStatus<'a> {
/// when migration removed it; one that survived non-empty is reported here
/// (see the private `deprecated_key_declined` helper).
///
-/// Returns an empty vec if either analysis is unreliable — the load path
-/// surfaces parse/type errors elsewhere.
+/// Returns an empty vec if the raw or migrated content doesn't parse as `C` —
+/// the load path surfaces parse/type errors elsewhere.
pub fn collect_unknown_warnings<C: WorktrunkConfig>(raw_contents: &str) -> Vec<UnknownWarning> {
- let raw_tree = match compute_unknown_tree::<C>(raw_contents) {
- UnknownAnalysis::Parsed(t) => t,
- UnknownAnalysis::Unreliable(_) => return Vec::new(),
+ let Some(raw_tree) = compute_unknown_tree::<C>(raw_contents) else {
+ return Vec::new();
};
let migrated = crate::config::migrate_content(raw_contents);
- let migrated_tree = match compute_unknown_tree::<C>(&migrated) {
- UnknownAnalysis::Parsed(t) => t,
- UnknownAnalysis::Unreliable(_) => return Vec::new(),
+ let Some(migrated_tree) = compute_unknown_tree::<C>(&migrated) else {
+ return Vec::new();
};
- // `compute_unknown_tree` reached `Parsed` above, so this parse cannot
+ // `compute_unknown_tree` returned a tree above, so this parse cannot
// fail; the fallback just keeps the path panic-free.
let migrated_root = migrated.parse::<toml::Table>().unwrap_or_default();
// The same content viewed as the *other* config type: a nested key absent
- // from this tree is valid there. Unreliable → no generalized redirect.
- let other_analysis = compute_unknown_tree::<C::Other>(&migrated);
- let other_root = match other_analysis.warn_tree() {
+ // from this tree is valid there. No tree → no generalized redirect.
+ let other_tree = compute_unknown_tree::<C::Other>(&migrated);
+ let other_root = match &other_tree {
Some(t) => OtherStatus::Known(Some(t)),
None => OtherStatus::UnknownSection,
};
@@ -331,7 +277,7 @@ fn walk_nested<C: WorktrunkConfig>(
for key in &tree.keys {
let path = format!("{prefix}.{key}");
// Hard-coded redirects (commit.generation leaves) take precedence and
- // fire even when the other-config analysis is unreliable; otherwise
+ // fire even when the content doesn't parse as the other config; otherwise
// fall back to the general "valid in the other config" check.
let belongs = crate::config::nested_key_belongs_in::<C>(&path)
.or_else(|| other.key_is_valid_in_other(key).then(C::Other::description));
@@ -344,9 +290,6 @@ fn walk_nested<C: WorktrunkConfig>(
});
}
for (key, sub) in &tree.nested {
- if tree.keys.contains(key) {
- continue;
- }
let path = format!("{prefix}.{key}");
walk_nested::<C>(sub, &path, other.descend(key), out);
}
@@ -358,10 +301,7 @@ mod tests {
use crate::config::{ProjectConfig, UserConfig};
fn parsed<C: WorktrunkConfig>(contents: &str) -> UnknownTree {
- match compute_unknown_tree::<C>(contents) {
- UnknownAnalysis::Parsed(t) => t,
- UnknownAnalysis::Unreliable(_) => panic!("expected Parsed"),
- }
+ compute_unknown_tree::<C>(contents).expect("contents should parse as C")
}
#[test]
@@ -442,28 +382,20 @@ b = 2
}
#[test]
- fn syntax_error_yields_unreliable() {
- let analysis = compute_unknown_tree::<UserConfig>("not valid {{{");
- assert!(matches!(analysis, UnknownAnalysis::Unreliable(_)));
- assert!(analysis.warn_tree().is_none());
+ fn syntax_error_yields_no_tree() {
+ assert!(compute_unknown_tree::<UserConfig>("not valid {{{").is_none());
}
#[test]
- fn type_mismatch_yields_unreliable_but_preserves_all() {
+ fn type_mismatch_yields_no_tree() {
// A hand-edit like `commit = "scalar"` can't round-trip through
- // UserConfig. The warn tree must be empty (parse error is surfaced
- // elsewhere) but the preserve tree must mark every on-disk key so
- // save_to doesn't drop data.
- let analysis = compute_unknown_tree::<UserConfig>(
+ // UserConfig; the parse error is surfaced elsewhere.
+ let tree = compute_unknown_tree::<UserConfig>(
r#"
commit = "scalar"
skip-shell-integration-prompt = true
"#,
);
- assert!(matches!(analysis, UnknownAnalysis::Unreliable(_)));
- assert!(analysis.warn_tree().is_none());
- let preserve = analysis.preserve_tree();
- assert!(preserve.keys.contains("commit"));
- assert!(preserve.keys.contains("skip-shell-integration-prompt"));
+ assert!(tree.is_none());
}
}
diff --git a/src/config/user/persistence.rs b/src/config/user/persistence.rs
index 68a11e911..879e6c5e8 100644
--- a/src/config/user/persistence.rs
+++ b/src/config/user/persistence.rs
@@ -3,18 +3,40 @@
//! Handles TOML serialization with formatting (multiline arrays, implicit tables)
//! and preserves comments when updating existing files via diff-based merge.
//!
-//! The existing-file save path works by diffing the serialized in-memory state
-//! against the parsed file and merging only changed keys. This automatically
-//! handles any new fields without manual wiring — if a struct field is
-//! serializable, save_to persists it.
+//! The existing-file save path diffs the serialized in-memory state against the
+//! file's own config, serialized the same way, and applies only that difference
+//! to the parsed file (see `merge_tables`). This automatically handles any new
+//! fields without manual wiring — if a struct field is serializable, save_to
+//! persists it.
use std::borrow::Cow;
-use crate::config::{ConfigError, UnknownTree, compute_unknown_tree};
+use crate::config::ConfigError;
use super::UserConfig;
impl UserConfig {
+ /// Serialize to a document whose nested structs are standard tables.
+ ///
+ /// Two tables are implicit, so they write no bare header: `projects`, which
+ /// writes only its `[projects."…"]` entries, and a `commit` holding only
+ /// subtables, which writes only `[commit.generation]`. The flags go on the
+ /// serialized document, so a header the file already has stays as written.
+ fn to_expanded_document(&self) -> Result<toml_edit::DocumentMut, ConfigError> {
+ let mut doc = toml_edit::ser::to_document(self)
+ .map_err(|e| ConfigError(format!("Serialization error: {e}")))?;
+ Self::expand_inline_tables(doc.as_table_mut());
+ if let Some(projects) = doc.get_mut("projects").and_then(|p| p.as_table_mut()) {
+ projects.set_implicit(true);
+ }
+ if let Some(commit) = doc.get_mut("commit").and_then(|c| c.as_table_mut())
+ && commit.iter().all(|(_, v)| v.is_table())
+ {
+ commit.set_implicit(true);
+ }
+ Ok(doc)
+ }
+
/// Recursively convert inline tables to standard tables for readability.
///
/// When using `toml_edit::ser::to_document()`, nested structs are serialized as inline tables
@@ -32,64 +54,62 @@ impl UserConfig {
}
}
- /// If `[commit]` only contains subtables (like `[commit.generation]`), mark it implicit
- /// so TOML doesn't emit an empty `[commit]` header.
- fn make_commit_table_implicit_if_only_subtables(doc: &mut toml_edit::DocumentMut) {
- if let Some(commit) = doc.get_mut("commit").and_then(|c| c.as_table_mut()) {
- let has_only_subtables = commit.iter().all(|(_, v)| v.is_table());
- if has_only_subtables {
- commit.set_implicit(true);
- }
- }
- }
-
/// Recursively merge desired state into existing document.
///
+ /// `base` is the file's own config, serialized the same way as `desired`,
+ /// which is that config after the change being saved (`None` where it has
+ /// no table at this path). A key only `base` has is one the change reset.
+ /// A key neither has serializes to nothing — a value written out at its
+ /// default, an empty section — or is one serde doesn't know (a typo, a
+ /// field from a newer version); the change didn't touch it, so it stays.
+ ///
/// - Keys in desired but not existing: inserted
- /// - Keys in existing but not desired: removed (unless in `preserve`)
+ /// - Keys in existing and base but not desired: removed
/// - Both standard tables: recurse (preserves existing formatting and comments)
/// - Existing inline table, desired standard table: merge through the same
- /// recursive path, so nested `preserve` applies; the inline format is kept
+ /// recursive path, so the nested `base` applies; the inline format is kept
/// when that merge changed nothing
/// - A pipeline: compared in the spelling the file uses (see
- /// `in_existing_spelling`); `[[…]]` blocks merge block by block
+ /// `in_existing_spelling`), as is its `base`; `[[…]]` blocks merge block by
+ /// block
/// - Both exist, values differ: update existing to desired
/// - Both exist, values equal: leave existing unchanged (preserves comments)
fn merge_tables(
existing: &mut toml_edit::Table,
desired: &toml_edit::Table,
- preserve: &UnknownTree,
+ base: Option<&toml_edit::Table>,
) {
let stale_keys: Vec<_> = existing
.iter()
.map(|(k, _)| k.to_string())
- .filter(|k| !desired.contains_key(k) && !preserve.keys.contains(k))
+ .filter(|k| !desired.contains_key(k) && base.is_some_and(|b| b.contains_key(k)))
.collect();
for key in &stale_keys {
existing.remove(key);
}
- let empty_tree = UnknownTree::default();
for (key, desired_item) in desired.iter() {
let desired_item = &*Self::in_existing_spelling(existing.get(key), desired_item);
+ let base_item = base
+ .and_then(|b| b.get(key))
+ .map(|item| Self::in_existing_spelling(existing.get(key), item));
+ let nested_base = base_item.as_deref().and_then(toml_edit::Item::as_table);
// 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()
+ // something — an untouched inline table keeps its formatting. The
+ // rewrite takes `desired`'s implicit flag, so it writes no bare
+ // header a table the save inserted wouldn't.
+ if let Some(desired_table) = desired_item.as_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,
- );
+ Self::merge_tables(&mut merged, desired_table, nested_base);
+ merged.set_implicit(desired_table.is_implicit());
if !Self::tables_equal(&as_table, &merged) {
crate::config::replace_inline_with_table(existing, key, merged);
}
@@ -99,11 +119,10 @@ impl UserConfig {
match existing.get_mut(key) {
// Both standard tables: recurse
Some(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(),
- nested_preserve,
+ nested_base,
);
}
// Both `[[…]]` blocks, as many of each: merge block by block, so
@@ -114,8 +133,17 @@ impl UserConfig {
.is_some_and(|desired_blocks| desired_blocks.len() == blocks.len()) =>
{
let desired_blocks = desired_item.as_array_of_tables().unwrap();
- for (block, desired_block) in blocks.iter_mut().zip(desired_blocks.iter()) {
- Self::merge_tables(block, desired_block, &empty_tree);
+ let base_blocks = base_item
+ .as_deref()
+ .and_then(toml_edit::Item::as_array_of_tables);
+ for (i, (block, desired_block)) in
+ blocks.iter_mut().zip(desired_blocks.iter()).enumerate()
+ {
+ Self::merge_tables(
+ block,
+ desired_block,
+ base_blocks.and_then(|b| b.get(i)),
+ );
}
}
Some(existing_item) => {
@@ -252,9 +280,12 @@ 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. 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.
+ /// changed keys. A key is removed only when the change being saved reset
+ /// it (see `merge_tables`), so a value written out at its default keeps
+ /// its line, and schema-unknown keys at any nesting level (typos, fields
+ /// from newer wt versions) survive — older wt versions don't silently
+ /// strip forward-compatible config data. An existing file that doesn't
+ /// parse as a config fails the save.
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)
@@ -268,39 +299,27 @@ impl UserConfig {
let mut existing_doc: toml_edit::DocumentMut = existing_content
.parse()
.map_err(|e| ConfigError(format!("Failed to parse config file: {}", e)))?;
+ // Both configs below name these hooks only canonically.
+ crate::config::deprecation::canonicalize_hook_keys(&mut existing_doc);
- let mut desired_doc = toml_edit::ser::to_document(&self)
- .map_err(|e| ConfigError(format!("Serialization error: {e}")))?;
- Self::expand_inline_tables(desired_doc.as_table_mut());
+ let desired_doc = self.to_expanded_document()?;
- // Preserve unknown keys at every nesting level (typos, future
- // fields, deprecated keys not yet migrated) so they aren't
- // silently deleted on save. On type-mismatch we still preserve
- // every on-disk key — it's safer to round-trip the whole file
- // than to drop fields we can't interpret.
- let analysis = compute_unknown_tree::<UserConfig>(&existing_content);
- let preserve = analysis.preserve_tree();
+ // Parsed the way `with_locked_mutation` reloads it, so this
+ // differs from `desired` only by the change being saved.
+ let migrated = crate::config::deprecation::migrate_content(&existing_content);
+ let file_config: UserConfig = toml::from_str(&migrated)
+ .map_err(|e| ConfigError(format!("Failed to parse config file: {e}")))?;
+ let base_doc = file_config.to_expanded_document()?;
Self::merge_tables(
existing_doc.as_table_mut(),
desired_doc.as_table(),
- preserve,
+ Some(base_doc.as_table()),
);
- Self::make_commit_table_implicit_if_only_subtables(&mut existing_doc);
existing_doc.to_string()
} else {
- let mut doc = toml_edit::ser::to_document(&self)
- .map_err(|e| ConfigError(format!("Serialization error: {e}")))?;
-
- Self::expand_inline_tables(doc.as_table_mut());
- Self::make_commit_table_implicit_if_only_subtables(&mut doc);
-
- if let Some(projects) = doc.get_mut("projects").and_then(|p| p.as_table_mut()) {
- projects.set_implicit(true);
- }
-
- doc.to_string()
+ self.to_expanded_document()?.to_string()
};
crate::config::ensure_config_parses(&toml_string)?;
diff --git a/src/config/user/tests.rs b/src/config/user/tests.rs
index fb0a183c5..0e78d47f8 100644
--- a/src/config/user/tests.rs
+++ b/src/config/user/tests.rs
@@ -51,10 +51,7 @@ fn test_compute_unknown_tree_empty() {
let content = r#"
worktree-path = "../{{ main_worktree }}.{{ branch }}"
"#;
- let tree = crate::config::compute_unknown_tree::<UserConfig>(content)
- .warn_tree()
- .cloned()
- .unwrap();
+ let tree = crate::config::compute_unknown_tree::<UserConfig>(content).unwrap();
assert!(tree.is_empty(), "expected no unknowns, got {tree:?}");
}
@@ -66,10 +63,7 @@ worktree-path = "../{{ main_worktree }}.{{ branch }}"
unknown-key = "value"
another-unknown = 42
"#;
- let tree = crate::config::compute_unknown_tree::<UserConfig>(content)
- .warn_tree()
- .cloned()
- .unwrap();
+ let tree = crate::config::compute_unknown_tree::<UserConfig>(content).unwrap();
assert!(tree.keys.contains("unknown-key"));
assert!(tree.keys.contains("another-unknown"));
}
@@ -101,10 +95,7 @@ run = "npm install"
[post-switch]
rename-tab = "echo 'switched'"
"#;
- let tree = crate::config::compute_unknown_tree::<UserConfig>(content)
- .warn_tree()
- .cloned()
- .unwrap();
+ let tree = crate::config::compute_unknown_tree::<UserConfig>(content).unwrap();
assert!(tree.is_empty());
}
@@ -3119,153 +3110,22 @@ stage = "all"
}
#[test]
-fn test_save_to_existing_file_replaces_non_table_project_entry() {
- // When an existing file has a non-table value at projects."<id>",
- // the diff-based merge replaces it with the correct table structure
- // from the in-memory config. Only reachable via raw file edits.
- let dir = tempfile::tempdir().unwrap();
- let config_path = dir.path().join("config.toml");
- std::fs::write(
- &config_path,
- r#"[projects]
-bogus = "not-a-table"
-
-[projects."real"]
-worktree-path = "old"
-"#,
- )
- .unwrap();
-
- let mut config = UserConfig::default();
- config
- .projects
- .insert("bogus".to_string(), UserProjectOverrides::default());
- config.projects.insert(
- "real".to_string(),
- UserProjectOverrides {
- worktree_path: Some("new".to_string()),
- ..Default::default()
- },
- );
-
- config.save_to(&config_path).unwrap();
-
- let saved = std::fs::read_to_string(&config_path).unwrap();
- // The "real" project should be updated
- assert!(
- saved.contains("worktree-path = \"new\""),
- "real project not updated: {saved}"
- );
- // The bogus string entry is replaced with a proper (empty) table
- assert!(
- !saved.contains("bogus = \"not-a-table\""),
- "malformed entry should be replaced: {saved}"
- );
-}
-
-#[test]
-fn test_save_to_existing_file_where_commit_is_scalar() {
- // When the existing file has `commit` as a scalar (user-edited mistake),
- // the diff-based merge replaces it with the correct table structure.
- // Only reachable via raw file edits.
- let dir = tempfile::tempdir().unwrap();
- let config_path = dir.path().join("config.toml");
- std::fs::write(&config_path, "commit = \"hand-edited-mistake\"\n").unwrap();
-
- let config = UserConfig {
- commit: CommitConfig {
- stage: None,
- generation: Some(CommitGenerationConfig {
- command: Some("llm".to_string()),
- ..Default::default()
- }),
- },
- ..Default::default()
- };
-
- config.save_to(&config_path).unwrap();
-
- let saved = std::fs::read_to_string(&config_path).unwrap();
- // The scalar is replaced with a proper table
- assert!(
- !saved.contains("\"hand-edited-mistake\""),
- "malformed entry should be replaced: {saved}"
- );
- assert!(
- saved.contains("command = \"llm\""),
- "commit generation should be written: {saved}"
- );
-}
-
-#[test]
-fn test_save_to_existing_file_where_commit_generation_is_scalar() {
- // When `[commit]` is a valid table but `generation` is a scalar
- // (raw-edit mistake), the diff-based merge replaces the scalar with
- // the correct table. Only reachable via raw file edits.
- let dir = tempfile::tempdir().unwrap();
- let config_path = dir.path().join("config.toml");
- std::fs::write(
- &config_path,
- "[commit]\nstage = \"tracked\"\ngeneration = \"oops\"\n",
- )
- .unwrap();
-
- let config = UserConfig {
- commit: CommitConfig {
- stage: Some(StageMode::Tracked),
- generation: Some(CommitGenerationConfig {
- command: Some("llm".to_string()),
- ..Default::default()
- }),
- },
- ..Default::default()
- };
-
- config.save_to(&config_path).unwrap();
-
- let saved = std::fs::read_to_string(&config_path).unwrap();
- // The scalar generation is replaced with a proper table
- assert!(
- !saved.contains("generation = \"oops\""),
- "malformed generation should be replaced: {saved}"
- );
- assert!(
- saved.contains("command = \"llm\""),
- "generation command should be written: {saved}"
- );
- // The unrelated stage value is preserved
- assert!(saved.contains("stage = \"tracked\""), "stage lost: {saved}");
-}
-
-#[test]
-fn test_save_to_existing_file_where_projects_is_scalar() {
- // When the existing file has `projects` as a scalar (raw-edit mistake),
- // the diff-based merge replaces it with the correct table structure.
+fn test_save_to_existing_file_with_type_mismatch_fails_and_leaves_it() {
+ // A file that parses as TOML but not as a config (a hand edit like
+ // `commit = "oops"`, landing after the mutation reloaded it) gives the
+ // merge no config to tell a reset key from an untouched one, so the save
+ // fails rather than rewrite the file.
let dir = tempfile::tempdir().unwrap();
let config_path = dir.path().join("config.toml");
- std::fs::write(&config_path, "projects = \"oops\"\n").unwrap();
+ let content = "commit = \"oops\"\n";
+ std::fs::write(&config_path, content).unwrap();
- let mut config = UserConfig::default();
- config.projects.insert(
- "repo".to_string(),
- UserProjectOverrides {
- worktree_path: Some("../x".to_string()),
- ..Default::default()
- },
- );
-
- config.save_to(&config_path).unwrap();
-
- let saved = std::fs::read_to_string(&config_path).unwrap();
- // The scalar is replaced with a proper table
+ let err = UserConfig::default().save_to(&config_path).unwrap_err();
assert!(
- !saved.contains("projects = \"oops\""),
- "malformed projects should be replaced: {saved}"
- );
- assert!(
- saved.contains("worktree-path = \"../x\""),
- "project worktree-path should be written: {saved}"
+ err.to_string().contains("Failed to parse config file"),
+ "expected parse error, got: {err}"
);
+ assert_eq!(std::fs::read_to_string(&config_path).unwrap(), content);
}
#[test]
@@ -3605,7 +3465,7 @@ future-option = true
#[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.
+ // must also survive — the merge has to keep them at the right level.
let dir = tempfile::tempdir().unwrap();
let config_path = dir.path().join("config.toml");
std::fs::write(
@@ -3801,6 +3661,43 @@ fn test_save_to_rewrites_commented_inline_section_as_parseable_toml() {
);
}
+#[test]
+fn test_save_to_rewrites_inline_commit_and_projects_without_bare_headers() {
+ // `commit` and `projects` holding only subtables, written inline, become
+ // standard tables when a value inside changes. Like the tables a save
+ // inserts, they write only their subtables' headers, not an empty
+ // `[commit]` or `[projects]` — and the comments on each line move onto the
+ // first header that is written.
+ let dir = tempfile::tempdir().unwrap();
+ let config_path = dir.path().join("config.toml");
+ let original = r#"# why we generate
+commit = { generation = { command = "old" } } # trailing
+
+# per repo
+projects = { "example.com/org/repo" = { worktree-path = "old" } }
+"#;
+ std::fs::write(&config_path, original).unwrap();
+
+ let mut config = UserConfig::load_from_str(original).unwrap();
+ config.commit.generation.as_mut().unwrap().command = Some("new".to_string());
+ config
+ .projects
+ .get_mut("example.com/org/repo")
+ .unwrap()
+ .worktree_path = Some("new".to_string());
+ config.save_to(&config_path).unwrap();
+
+ insta::assert_snapshot!(std::fs::read_to_string(&config_path).unwrap(), @r#"
+ # why we generate
+ [commit.generation] # trailing
+ command = "new"
+
+ # per repo
+ [projects."example.com/org/repo"]
+ worktree-path = "new"
+ "#);
+}
+
#[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
diff --git a/tests/integration_tests/approval_save.rs b/tests/integration_tests/approval_save.rs
index 727c44afc..c632571ac 100644
--- a/tests/integration_tests/approval_save.rs
+++ b/tests/integration_tests/approval_save.rs
@@ -876,6 +876,96 @@ approved-commands = [
);
}
+/// A value written out at its default serializes to nothing, the same as a
+/// value that was never written, so a save can't tell the two apart from the
+/// config alone. A save that doesn't change them must leave them — and their
+/// comments — where the user put them.
+#[test]
+fn test_saving_config_mutation_keeps_explicit_defaults() {
+ let temp_dir = TempDir::new().unwrap();
+ let config_path = temp_dir.path().join("config.toml");
+
+ let initial_content = r#"skip-shell-integration-prompt = false # keep asking
+
+[list]
+columns = [] # pick later
+
+[merge]
+
+# fill in later
+[commit]
+
+[commit.generation]
+command = "llm -m claude-haiku-4.5"
+"#;
+ fs::write(&config_path, initial_content).unwrap();
+
+ let toml_str = fs::read_to_string(&config_path).unwrap();
+ let mut config: UserConfig = toml::from_str(&toml_str).unwrap();
+ config
+ .set_commit_generation_command("llm -m claude-sonnet-4".to_string(), &config_path)
+ .unwrap();
+
+ assert_snapshot!(fs::read_to_string(&config_path).unwrap(), @r#"
+ skip-shell-integration-prompt = false # keep asking
+
+ [list]
+ columns = [] # pick later
+
+ [merge]
+
+ # fill in later
+ [commit]
+
+ [commit.generation]
+ command = "llm -m claude-sonnet-4"
+ "#);
+}
+
+/// A hook under its `pre-create`/`post-create` alias loads as
+/// `pre-start`/`post-start`, which is the only name the saved config has. The
+/// save writes it under that name once, with its comment, at the top level and
+/// per project however the entry is written, rather than adding the canonical
+/// key beside the alias — a duplicate that fails the next load.
+#[test]
+fn test_saving_config_mutation_renames_hook_aliases() {
+ let temp_dir = TempDir::new().unwrap();
+ let config_path = temp_dir.path().join("config.toml");
+
+ let initial_content = r#"# greet
+pre-create = "echo top"
+
+[projects]
+"example.com/org/inline" = { pre-create = "make" }
+
+[projects."example.com/org/repo"]
+post-create = "npm install"
+"#;
+ fs::write(&config_path, initial_content).unwrap();
+
+ let toml_str = fs::read_to_string(&config_path).unwrap();
+ let mut config: UserConfig = toml::from_str(&toml_str).unwrap();
+ config
+ .set_commit_generation_command("llm -m claude-sonnet-4".to_string(), &config_path)
+ .unwrap();
+
+ let saved_content = fs::read_to_string(&config_path).unwrap();
+ toml::from_str::<UserConfig>(&saved_content).unwrap();
+ assert_snapshot!(saved_content, @r#"
+ # greet
+ pre-start = "echo top"
+
+ [projects]
+ "example.com/org/inline" = { pre-start = "make" }
+
+ [projects."example.com/org/repo"]
+ post-start = "npm install"
+
+ [commit.generation]
+ command = "llm -m claude-sonnet-4"
+ "#);
+}
+
/// The same line-decor guarantee for a `[projects]` entry written inline.
///
/// This entry is an inline table, which `toml_edit` holds as a value, and the
@@ -969,8 +1059,6 @@ install = "cd {{ repo_root }} && pnpm install" # after the copy
[[pre-start]]
install = "cd {{ repo_path }} && pnpm install" # after the copy
- [projects]
-
[commit.generation]
command = "llm -m claude-sonnet-4"
"#);