Skip to content

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

refactor(config): write a mutation's one value instead of merging the whole config (#4160)

Maximilian Roosacf50b72589f
diff --git a/CLAUDE.md b/CLAUDE.md
index 7a8dd2588..d9225a790 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -219,7 +219,7 @@ its own section.
All config deprecation lives in one layer: pre-deserialization TOML migration in `src/config/deprecation.rs`. `migrate_content()` rewrites deprecated patterns into canonical form before serde parses; `check_and_migrate()` reuses it, and additionally detects patterns and emits per-process-deduped warnings (the user materializes migrations via `wt config update`). **Never silently drop an old config key** — that's a silent behavior change for users; migrate it.
-Every deprecation is one row in the `DEPRECATION_RULES` table: a single idempotent function that rewrites the pattern AND returns the `DeprecationKind`s for what it changed — there is no separate detection function, so detection and migration share one predicate and cannot drift. Detection runs the same functions against a scratch copy of the document (progressively, so a rule sees earlier rules' rewrites); the invariant for warning rules is **a warning fires exactly when `wt config update` would change the file**, pinned by `test_warning_fires_iff_update_changes` — add new edge cases to its battery. The row variant decides when the rewrite applies: `Structural` rewrites on every load; `UpdateOnly` only via `wt config update`, for deprecated forms that still work at runtime; `Silent` rewrites on every load with no warning — its function signature has no channel for a kind, which is what scopes the invariant to `Structural` and `UpdateOnly`. Table order is both the warning-emission order and the migration order. Each `DeprecationKind` carries its own display payload, so `format_deprecation_warnings()` is one match over the kinds. A config that can't be rewritten safely (a malformed value, an occupied destination key) is left untouched and unwarned — serde's type or unknown-field error is the messaging; an empty deprecated section is also left alone, with no message at all (it contributes no config). Adding a deprecation: (1) one idempotent migrate-and-report function; (2) a `DeprecationKind` variant plus its match arm in `format_deprecation_warnings()`; (3) a `DEPRECATION_RULES` row; (4) for a removed top-level section, add a `DeprecatedSection` to `DEPRECATED_SECTION_KEYS` (canonical key plus display form) so `warn_unknown_fields` defers to the deprecation messaging and suggests the correct config file. A silently-migrated rename (e.g. `pre-create` → `pre-start`) is a `Silent` row with no variant. Renaming a field within a section follows the same shape via a TOML-level rename function (see `migrate_negated_bool`); the struct never needs the old field since migration precedes serde.
+Every deprecation is one row in the `DEPRECATION_RULES` table: a single idempotent function that rewrites the pattern AND returns the `DeprecationKind`s for what it changed — there is no separate detection function, so detection and migration share one predicate and cannot drift. Detection runs the same functions against a scratch copy of the document (progressively, so a rule sees earlier rules' rewrites); the invariant for warning rules is **a warning fires exactly when `wt config update` would change the file**, pinned by `test_warning_fires_iff_update_changes` — add new edge cases to its battery. The row variant decides when the rewrite applies: `Structural` rewrites on every load; `UpdateOnly` only via `wt config update`, for deprecated forms that still work at runtime; `Silent` rewrites on every load with no warning — its function signature has no channel for a kind, which is what scopes the invariant to `Structural` and `UpdateOnly`. Table order is both the warning-emission order and the migration order. Each `DeprecationKind` carries its own display payload, so wording it is a match over the kinds — twice, in one file: `format_warning_lines()` names what a load still has ahead of it, `format_applied_lines()` what a config mutation's write already did. A config that can't be rewritten safely (a malformed value, an occupied destination key) is left untouched and unwarned — serde's type or unknown-field error is the messaging; an empty deprecated section is also left alone, with no message at all (it contributes no config). Adding a deprecation: (1) one idempotent migrate-and-report function; (2) a `DeprecationKind` variant plus its match arm in each of those two renderers; (3) a `DEPRECATION_RULES` row; (4) for a removed top-level section, add a `DeprecatedSection` to `DEPRECATED_SECTION_KEYS` (canonical key plus display form) so `warn_unknown_fields` defers to the deprecation messaging and suggests the correct config file. A silently-migrated rename (e.g. `pre-create` → `pre-start`) is a `Silent` row with no variant. Renaming a field within a section follows the same shape via a TOML-level rename function (see `migrate_negated_bool`); the struct never needs the old field since migration precedes serde.
**What an update writes must load clean.** A rule that moves a section's table wholesale (`[select]` → `[switch.picker]`) removes the keys its destination struct has no field for and reports each one (`drop_unsupported_keys`); a key removal that empties a `[projects."<id>"]`-scoped section removes the section too. Otherwise the key or the empty section ends up at a path the user never typed, `warn_unknown_fields` names that path on every command, and `wt config update` — the command the deprecation hint points at — writes it into the file rather than clearing it, so the warning outlives every fix available to the user. `test_warning_fires_iff_update_changes` pins both halves: what the update writes raises no deprecation warning and no unknown-field warning. The removal is reported and the key had no home in either config file, so this does not conflict with "never silently drop a key". A key that is merely *misplaced* (valid in the other config, such as a user-only `commit.generation.command` in project config) stays, and keeps its redirect warning; that is why `drop_unsupported_keys` gets the union of the destination's schemas across config types. Those schemas must carry no `#[serde(alias)]`, which `schema_property_names` cannot see.
diff --git a/src/config/deprecation.rs b/src/config/deprecation.rs
index 4c9d5cc1d..0911e67fd 100644
--- a/src/config/deprecation.rs
+++ b/src/config/deprecation.rs
@@ -1031,13 +1031,56 @@ fn has_table_like_child(item: Option<&toml_edit::Item>, key: &str) -> bool {
}
}
+/// Replace a key's inline-table value with a standard table, carrying the line's
+/// comments 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.
+///
+/// A trailing comment after the closing brace sits in the inline value's own
+/// decor, which `InlineTable::into_table` discards, so it is read from
+/// `existing` before the replacement and lands after the header's `]`. It is
+/// carried only when it holds a comment; bare whitespace there would just trail
+/// the header.
+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();
+ 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(prefix) = prefix {
+ table.decor_mut().set_prefix(prefix);
+ }
+ if let Some(suffix) = suffix {
+ table.decor_mut().set_suffix(suffix);
+ }
+ if let Some(mut key_mut) = existing.key_mut(key) {
+ key_mut.leaf_decor_mut().clear();
+ }
+ existing[key] = toml_edit::Item::Table(table);
+}
+
/// Ensure a table-like parent is writable as a standard table.
///
/// 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
+/// The conversion goes through [`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
@@ -1057,7 +1100,7 @@ fn ensure_standard_table_parent<'a>(
.and_then(|item| item.as_inline_table())
.cloned()
{
- super::replace_inline_with_table(table, key, inline.into_table());
+ replace_inline_with_table(table, key, inline.into_table());
}
table.get_mut(key)?.as_table_mut()
}
@@ -1429,14 +1472,20 @@ fn migrate_content_doc(doc: &mut toml_edit::DocumentMut) -> bool {
apply_rules(doc, RulePass::Load, &mut Vec::new())
}
+/// Apply the load-path migrations to `doc`, reporting what they changed.
+///
+/// The config mutations use this where [`migrate_content_doc`]'s bool isn't
+/// enough: writing an edit into a migrated file removes the keys the
+/// destinations have no field for, which the mutation names to the user.
+pub(crate) fn migrate_doc(doc: &mut toml_edit::DocumentMut) -> Deprecations {
+ let mut deprecations = Vec::new();
+ apply_rules(doc, RulePass::Load, &mut deprecations);
+ deprecations
+}
+
/// Rename the `pre-create`/`post-create` hook aliases to `pre-start`/`post-start`,
/// in every config scope (see [`for_each_config_table_mut`]).
-///
-/// 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 {
+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");
@@ -1915,6 +1964,9 @@ pub fn format_deprecation_warnings(info: &DeprecationInfo) -> String {
/// Render one `warning_message` line per kind (the commit-generation kind can
/// emit several). The kinds arrive in emission order, so a single pass
/// reproduces the original output verbatim.
+///
+/// A rewrite that has already happened is named by [`format_applied_lines`]
+/// instead: these lines say what is still outstanding.
fn format_warning_lines<'a>(
kinds: impl IntoIterator<Item = &'a DeprecationKind>,
label: &str,
@@ -2033,6 +2085,72 @@ fn format_warning_lines<'a>(
out
}
+/// Render one `warning_message` line per kind, for migrations already applied.
+///
+/// The sibling of [`format_warning_lines`], in the tense the config mutations
+/// need: they report what their write just did to the file, where the load
+/// path's "is deprecated in favor of" and "will be removed" name work still
+/// ahead. Both live here so a new [`DeprecationKind`] is worded in one place.
+pub(crate) fn format_applied_lines<'a>(
+ kinds: impl IntoIterator<Item = &'a DeprecationKind>,
+) -> String {
+ use std::fmt::Write;
+ let mut out = String::new();
+ let mut line = |text: String| {
+ let _ = writeln!(out, "{}", warning_message(text));
+ };
+
+ for kind in kinds {
+ match kind {
+ DeprecationKind::TemplateVar { old, new } => line(cformat!(
+ "Renamed template variable <bold>{old}</> to <bold>{new}</>"
+ )),
+ DeprecationKind::CommitGeneration(scopes) => {
+ if scopes.has_top_level {
+ line(cformat!(
+ "Moved <bold>[commit-generation]</> to <bold>[commit.generation]</>"
+ ));
+ }
+ for k in &scopes.project_keys {
+ line(cformat!(
+ "Moved <bold>[projects.\"{k}\".commit-generation]</> to <bold>[projects.\"{k}\".commit.generation]</>"
+ ));
+ }
+ }
+ DeprecationKind::ApprovedCommands => line(cformat!(
+ "Moved <bold>approved-commands</> under <bold>[projects]</> to <bold>approvals.toml</>"
+ )),
+ DeprecationKind::Select(scopes) => {
+ if scopes.has_top_level {
+ line(cformat!(
+ "Moved <bold>[select]</> to <bold>[switch.picker]</>"
+ ));
+ }
+ for k in &scopes.project_keys {
+ line(cformat!(
+ "Moved <bold>[projects.\"{k}\".select]</> to <bold>[projects.\"{k}\".switch.picker]</>"
+ ));
+ }
+ }
+ DeprecationKind::UnsupportedKey { section, key } => line(cformat!(
+ "Removed <bold>{section} {key}</>, which its replacement has no field for"
+ )),
+ DeprecationKind::CiSection => line(cformat!("Moved <bold>[ci]</> to <bold>[forge]</>")),
+ DeprecationKind::NoFf => line(cformat!(
+ "Replaced <bold>merge.no-ff</> with <bold>merge.ff</> (inverted)"
+ )),
+ DeprecationKind::NoCd => line(cformat!(
+ "Replaced <bold>switch.no-cd</> with <bold>switch.cd</> (inverted)"
+ )),
+ DeprecationKind::ListTaskTimeout => line(cformat!(
+ "Removed <bold>list.task-timeout-ms</>, which nothing reads"
+ )),
+ }
+ }
+
+ out
+}
+
/// Format deprecation details for display (for use by `wt config show`).
///
/// Returns formatted output including:
@@ -4977,6 +5095,25 @@ pager = "delta --paging=never"
);
}
+ /// `[commit-generation]` migrates into `commit`, which TOML forbids
+ /// extending when the file wrote it inline — so it becomes a standard
+ /// table, and the line's trailing comment lands after the new header's `]`.
+ #[test]
+ fn test_migrate_carries_an_inline_parent_comment_onto_its_header() {
+ let content = r#"commit = { stage = "all" } # how to stage
+
+[commit-generation]
+template = "MINE"
+"#;
+ insta::assert_snapshot!(migrate_content(content), @r#"
+ [commit] # how to stage
+ stage = "all"
+
+ [commit.generation]
+ template = "MINE"
+ "#);
+ }
+
/// 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]]`) and the comment above the key,
@@ -5199,6 +5336,48 @@ timeout-ms = 500
"#);
}
+ /// The same kinds as above, in the tense a config mutation reports its
+ /// write in — the second half of what "Adding a deprecation" words.
+ #[test]
+ fn test_format_applied_lines_all_kinds() {
+ let kinds = vec![
+ DeprecationKind::TemplateVar {
+ old: "repo_root",
+ new: "repo_path",
+ },
+ DeprecationKind::CommitGeneration(ScopedSections {
+ has_top_level: true,
+ project_keys: vec!["github.com/user/repo".to_string()],
+ }),
+ DeprecationKind::ApprovedCommands,
+ DeprecationKind::Select(ScopedSections {
+ has_top_level: true,
+ project_keys: vec!["github.com/user/repo".to_string()],
+ }),
+ DeprecationKind::UnsupportedKey {
+ section: "[select]".to_string(),
+ key: "height".to_string(),
+ },
+ DeprecationKind::CiSection,
+ DeprecationKind::NoFf,
+ DeprecationKind::NoCd,
+ DeprecationKind::ListTaskTimeout,
+ ];
+ assert_snapshot!(format_applied_lines(&kinds).ansi_strip(), @r#"
+ ▲ Renamed template variable repo_root to repo_path
+ ▲ Moved [commit-generation] to [commit.generation]
+ ▲ Moved [projects."github.com/user/repo".commit-generation] to [projects."github.com/user/repo".commit.generation]
+ ▲ Moved approved-commands under [projects] to approvals.toml
+ ▲ Moved [select] to [switch.picker]
+ ▲ Moved [projects."github.com/user/repo".select] to [projects."github.com/user/repo".switch.picker]
+ ▲ Removed [select] height, which its replacement has no field for
+ ▲ Moved [ci] to [forge]
+ ▲ Replaced merge.no-ff with merge.ff (inverted)
+ ▲ Replaced switch.no-cd with switch.cd (inverted)
+ ▲ Removed list.task-timeout-ms, which nothing reads
+ "#);
+ }
+
#[test]
fn test_detect_no_ff_deprecation() {
let deprecations = detect_deprecations("[merge]\nno-ff = true\n");
diff --git a/src/config/mod.rs b/src/config/mod.rs
index d6daeb8a3..76479f949 100644
--- a/src/config/mod.rs
+++ b/src/config/mod.rs
@@ -155,78 +155,14 @@ 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 line's
-/// 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
-/// 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.
-///
-/// A trailing comment after the closing brace sits in the inline value's own
-/// decor, which `InlineTable::into_table` discards, so it is read from
-/// `existing` before the replacement and lands after the header's `]`. It is
-/// 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
-/// extending an inline table with a later subtable.
-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();
- 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();
- 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();
- }
- existing[key] = toml_edit::Item::Table(table);
-}
-
/// Refuse to write a config file that is not valid TOML.
///
/// wt can't load such a file: every later command skips user config with a
/// warning, and the commands that need project config fail, until the user
-/// hand-edits it. Both writers that rewrite a config file the user owns
-/// check the content they are about to write: `UserConfig::save_to` and
+/// hand-edits it. Both writers of a config file the user owns check the
+/// content they are about to write: the `UserConfig` mutations and
/// `wt config update`. Neither starts from invalid TOML, so this fires only when
-/// the rewrite itself broke the syntax, and the file on disk stays as it was.
+/// the edit itself broke the syntax, and the file on disk stays as it was.
pub fn ensure_config_parses(content: &str) -> Result<(), ConfigError> {
content.parse::<toml::Table>().map(|_| ()).map_err(|e| {
ConfigError(format!(
diff --git a/src/config/user/mod.rs b/src/config/user/mod.rs
index a2cf7f6b4..96e98e72b 100644
--- a/src/config/user/mod.rs
+++ b/src/config/user/mod.rs
@@ -506,7 +506,7 @@ fn load_config_file(
///
/// Environment variables can override config file settings using `WORKTRUNK_` prefix with
/// `__` separator for nested fields (e.g., `WORKTRUNK_COMMIT__GENERATION__COMMAND`).
-#[derive(Debug, Default, Clone, Serialize, Deserialize, JsonSchema)]
+#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct UserConfig {
/// Per-project configuration (approved commands, etc.)
/// Uses BTreeMap for deterministic serialization order and better diff readability
diff --git a/src/config/user/mutation.rs b/src/config/user/mutation.rs
index 166b6cf5f..969acaf63 100644
--- a/src/config/user/mutation.rs
+++ b/src/config/user/mutation.rs
@@ -1,6 +1,6 @@
//! Config mutation methods with file locking.
//!
-//! These methods modify the UserConfig and persist changes to disk,
+//! These methods modify the UserConfig and write the changed value to disk,
//! using file locking to prevent race conditions between concurrent processes.
use fs2::FileExt;
@@ -8,8 +8,11 @@ use fs2::FileExt;
use crate::config::ConfigError;
use crate::path::format_path_for_display;
+use crate::styling::{eprint, eprintln, warning_message};
+use color_print::cformat;
use super::UserConfig;
+use super::persistence::{ConfigEdit, ConfigFile, Edited};
use super::sections::CommitGenerationConfig;
/// Acquire an exclusive lock on the config file for read-modify-write operations.
@@ -44,93 +47,102 @@ pub(crate) fn acquire_config_lock(
impl UserConfig {
/// Execute a mutation under an exclusive file lock.
///
- /// Acquires lock, reloads from disk, calls the mutator, and saves if mutator returns true.
- pub(super) fn with_locked_mutation<F>(
+ /// Acquires the lock and reads the config file. The mutator runs on the
+ /// file's config, returning the value it changed or `None` when the file
+ /// already has it, and that value alone is written into the file (see
+ /// [`ConfigFile::edited`]). The mutator also runs on `self`, which is not
+ /// replaced by the file's config: it carries system config, environment
+ /// variables, and `--config-set` too, which the rest of the command still
+ /// reads.
+ pub(super) fn with_locked_mutation<'a, F>(
&mut self,
config_path: &std::path::Path,
mutate: F,
) -> Result<(), ConfigError>
where
- F: FnOnce(&mut Self) -> bool,
+ F: Fn(&mut Self) -> Option<ConfigEdit<'a>>,
{
let _lock = acquire_config_lock(config_path)?;
- self.reload_from(config_path)?;
+ let file = ConfigFile::read(config_path)?;
+ let mut changed = file.config.clone();
+ let edit = mutate(&mut changed);
+ mutate(self);
- if mutate(self) {
- self.save_to(config_path)?;
- }
- Ok(())
- }
-
- /// Reload all fields from disk so the in-memory config matches the current
- /// file state before applying mutations.
- ///
- /// The diff-based `save_to` writes ALL serializable fields, so the reload
- /// must refresh everything to avoid overwriting concurrent manual edits
- /// with stale in-memory data. After reload, the mutator applies its
- /// specific change, and `save_to` persists the full state.
- fn reload_from(&mut self, path: &std::path::Path) -> Result<(), ConfigError> {
- if !path.exists() {
+ let Some(edit) = edit else {
return Ok(());
- }
-
- let content = std::fs::read_to_string(path).map_err(|e| {
+ };
+ let edited = file.edited(&edit, &changed)?;
+ crate::config::ensure_config_parses(edited.content())?;
+ crate::utils::write_atomically(config_path, edited.content()).map_err(|e| {
ConfigError(format!(
- "Failed to read config file {}: {}",
- format_path_for_display(path),
+ "Failed to write config file {}: {}",
+ format_path_for_display(config_path),
e
))
})?;
- let migrated = crate::config::deprecation::migrate_content(&content);
- let disk_config: UserConfig = toml::from_str(&migrated).map_err(|e| {
- ConfigError(format!(
- "Failed to parse config file {}: {}",
- format_path_for_display(path),
- e
- ))
- })?;
-
- *self = disk_config;
-
+ // Reported only once the file is written, and only for the fallback:
+ // `wt config update` is otherwise what materializes migrations.
+ if let Edited::Migrated { changes, .. } = &edited {
+ eprintln!(
+ "{}",
+ warning_message(cformat!(
+ "Migrated deprecated settings @ <bold>{}</> — the setting being written can't be read beside them",
+ format_path_for_display(config_path)
+ ))
+ );
+ eprint!(
+ "{}",
+ crate::config::deprecation::format_applied_lines(changes)
+ );
+ }
Ok(())
}
- /// Set `skip-shell-integration-prompt = true` and save.
+ /// Set `skip-shell-integration-prompt = true` in the config file.
///
- /// Acquires lock, reloads from disk, sets flag if not already set, and saves.
+ /// Under the lock, writes the flag unless the file already has it.
pub fn set_skip_shell_integration_prompt(
&mut self,
config_path: &std::path::Path,
) -> Result<(), ConfigError> {
self.with_locked_mutation(config_path, |config| {
if config.skip_shell_integration_prompt {
- return false;
+ return None;
}
config.skip_shell_integration_prompt = true;
- true
+ Some(ConfigEdit {
+ tables: vec![],
+ key: "skip-shell-integration-prompt",
+ value: true.into(),
+ })
})
}
- /// Set `skip-commit-generation-prompt = true` and save.
+ /// Set `skip-commit-generation-prompt = true` in the config file.
///
- /// Acquires lock, reloads from disk, sets flag if not already set, and saves.
+ /// Under the lock, writes the flag unless the file already has it.
pub fn set_skip_commit_generation_prompt(
&mut self,
config_path: &std::path::Path,
) -> Result<(), ConfigError> {
self.with_locked_mutation(config_path, |config| {
if config.skip_commit_generation_prompt {
- return false;
+ return None;
}
config.skip_commit_generation_prompt = true;
- true
+ Some(ConfigEdit {
+ tables: vec![],
+ key: "skip-commit-generation-prompt",
+ value: true.into(),
+ })
})
}
- /// Set worktree-path for a specific project and save.
+ /// Set `worktree-path` for a specific project in the config file.
///
- /// Creates the project entry if it doesn't exist.
+ /// Under the lock, writes the path unless the file already has it, creating
+ /// the project entry if it doesn't exist.
pub fn set_project_worktree_path(
&mut self,
project: &str,
@@ -140,17 +152,20 @@ impl UserConfig {
self.with_locked_mutation(config_path, |config| {
let entry = config.projects.entry(project.to_string()).or_default();
if entry.worktree_path.as_ref() == Some(&worktree_path) {
- return false;
+ return None;
}
- entry.worktree_path = Some(worktree_path);
- true
+ entry.worktree_path = Some(worktree_path.clone());
+ Some(ConfigEdit {
+ tables: vec!["projects", project],
+ key: "worktree-path",
+ value: worktree_path.as_str().into(),
+ })
})
}
- /// Set commit generation command and save.
+ /// Set `[commit.generation] command` in the config file.
///
- /// Sets `[commit.generation] command = ...` in the user config.
- /// Acquires lock, reloads from disk, sets the command, and saves.
+ /// Under the lock, writes the command unless the file already has it.
pub fn set_commit_generation_command(
&mut self,
command: String,
@@ -163,10 +178,14 @@ impl UserConfig {
.get_or_insert_with(CommitGenerationConfig::default);
if gen_config.command.as_ref() == Some(&command) {
- return false;
+ return None;
}
- gen_config.command = Some(command);
- true
+ gen_config.command = Some(command.clone());
+ Some(ConfigEdit {
+ tables: vec!["commit", "generation"],
+ key: "command",
+ value: command.as_str().into(),
+ })
})
}
}
diff --git a/src/config/user/persistence.rs b/src/config/user/persistence.rs
index 879e6c5e8..eb7e003c7 100644
--- a/src/config/user/persistence.rs
+++ b/src/config/user/persistence.rs
@@ -1,335 +1,179 @@
-//! Config persistence - loading and saving to disk.
+//! Writing a config mutation into the file.
//!
-//! Handles TOML serialization with formatting (multiline arrays, implicit tables)
-//! and preserves comments when updating existing files via diff-based merge.
+//! A mutation writes the one value it changed, at its key path, into the file
+//! parsed as a `toml_edit` document ([`ConfigEdit`]). The rest of the file keeps
+//! its comments, formatting, key order, values written at their defaults, keys
+//! wt doesn't know, and deprecated spellings the load path migrates in memory.
+//! `cargo add`, uv, and poetry edit user-owned TOML the same way; no library
+//! merges a serialized struct into a document while keeping all of that.
//!
-//! 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.
+//! The exception is an edit the load path wouldn't read as written. A load-time
+//! migration that moves config onto the edit's path — a deprecated
+//! `[commit-generation]` onto `[commit.generation]` — declines once the
+//! canonical table exists, so the edit goes into the migrated file instead,
+//! which writes those migrations too ([`ConfigFile::edited`]).
-use std::borrow::Cow;
+use toml_edit::{DocumentMut, Item, Table, TableLike, Value};
use crate::config::ConfigError;
+use crate::config::Deprecations;
+use crate::config::deprecation::migrate_doc;
+use crate::path::format_path_for_display;
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
- /// (e.g., `commit = { generation = { command = "..." } }`). This converts them to standard
- /// multi-line tables for better human readability.
- fn expand_inline_tables(table: &mut toml_edit::Table) {
- let keys: Vec<_> = table.iter().map(|(k, _)| k.to_string()).collect();
- for key in keys {
- let item = table.get_mut(&key).unwrap();
- if let Some(inline) = item.as_inline_table() {
- let mut new_table = inline.clone().into_table();
- Self::expand_inline_tables(&mut new_table);
- *item = toml_edit::Item::Table(new_table);
- }
- }
- }
+/// One value a config mutation writes: the tables it sits in, its key, and the
+/// value.
+pub(super) struct ConfigEdit<'a> {
+ pub(super) tables: Vec<&'a str>,
+ pub(super) key: &'a str,
+ pub(super) value: Value,
+}
- /// Recursively merge desired state into existing document.
+impl ConfigEdit<'_> {
+ /// Set the value in `doc`, leaving everything else as it is.
///
- /// `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 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 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`), 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,
- base: Option<&toml_edit::Table>,
- ) {
- let stale_keys: Vec<_> = existing
- .iter()
- .map(|(k, _)| k.to_string())
- .filter(|k| !desired.contains_key(k) && base.is_some_and(|b| b.contains_key(k)))
- .collect();
- for key in &stale_keys {
- existing.remove(key);
- }
-
- 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. 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();
- 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);
- }
- continue;
- }
-
- match existing.get_mut(key) {
- // Both standard tables: recurse
- Some(existing_item) if existing_item.is_table() && desired_item.is_table() => {
- Self::merge_tables(
- existing_item.as_table_mut().unwrap(),
- desired_item.as_table().unwrap(),
- nested_base,
- );
- }
- // Both `[[…]]` blocks, as many of each: merge block by block, so
- // each block keeps its comments and formatting
- Some(toml_edit::Item::ArrayOfTables(blocks))
- if desired_item
- .as_array_of_tables()
- .is_some_and(|desired_blocks| desired_blocks.len() == blocks.len()) =>
- {
- let desired_blocks = desired_item.as_array_of_tables().unwrap();
- 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) => {
- if !Self::items_equal(existing_item, desired_item) {
- Self::replace_keeping_decor(existing_item, desired_item);
- }
+ /// An existing value is replaced in place and keeps its decor — the spacing
+ /// after `=` and a trailing comment. A missing table is created implicit, so
+ /// it writes no header of its own (`[commit.generation]`, not `[commit]`
+ /// above it), or inline inside an inline table, which can't hold a standard
+ /// one. An existing table is edited in whatever form the file writes it:
+ /// standard, inline, or dotted keys.
+ pub(super) fn apply(&self, doc: &mut DocumentMut) -> Result<(), ConfigError> {
+ let mut table: &mut dyn TableLike = doc.as_table_mut();
+ let mut inline = false;
+ for &name in &self.tables {
+ let item = table.entry(name).or_insert_with(|| {
+ if inline {
+ Item::Value(Value::InlineTable(Default::default()))
+ } else {
+ let mut implicit = Table::new();
+ implicit.set_implicit(true);
+ Item::Table(implicit)
}
- None => {
- existing[key] = desired_item.clone();
- }
- }
+ });
+ inline = item.is_inline_table();
+ table = item.as_table_like_mut().ok_or_else(|| {
+ ConfigError(format!(
+ "Failed to write config file: `{name}` is not a table"
+ ))
+ })?;
}
- }
- /// Re-spell a desired hook pipeline the way the file already writes it.
- ///
- /// A pipeline serializes in one spelling whatever the file used: one step as
- /// its lone table, more as an inline array of tables. The file may write
- /// either as `[[post-start]]` blocks — the documented form — or as an inline
- /// array. Compared as serialized, an untouched pipeline reads as changed on
- /// every save, and the rewrite moves it to the serialized spelling and drops
- /// the comments on its blocks. So desired steps become blocks where the file
- /// has blocks, and a lone step becomes a one-element array where the file has
- /// an inline array; anything else stays as serialized. Only a pipeline meets
- /// its serialized form in these shapes, so the match keys on shape alone.
- fn in_existing_spelling<'a>(
- existing: Option<&toml_edit::Item>,
- desired: &'a toml_edit::Item,
- ) -> Cow<'a, toml_edit::Item> {
- use toml_edit::{Array, ArrayOfTables, Item, Value};
- match (existing, desired) {
- (Some(Item::ArrayOfTables(_)), Item::Table(step)) => {
- let mut blocks = ArrayOfTables::new();
- blocks.push(step.clone());
- Cow::Owned(Item::ArrayOfTables(blocks))
- }
- (Some(Item::ArrayOfTables(_)), Item::Value(Value::Array(steps)))
- if steps.iter().all(Value::is_inline_table) =>
- {
- let mut blocks = ArrayOfTables::new();
- for step in steps.iter().filter_map(Value::as_inline_table) {
- blocks.push(step.clone().into_table());
- }
- Cow::Owned(Item::ArrayOfTables(blocks))
+ let mut value = self.value.clone();
+ match table.get_mut(self.key) {
+ Some(Item::Value(existing)) => {
+ *value.decor_mut() = existing.decor().clone();
+ *existing = value;
}
- (Some(Item::Value(Value::Array(_))), Item::Table(step)) => {
- let mut steps = Array::new();
- steps.push(step.clone().into_inline_table());
- Cow::Owned(Item::Value(Value::Array(steps)))
+ _ => {
+ table.insert(self.key, Item::Value(value));
}
- _ => Cow::Borrowed(desired),
- }
- }
-
- /// Overwrite an item, keeping the value's own decor — the spacing after `=`
- /// and the trailing comment after the value.
- ///
- /// Comments and blank lines *above* the line sit on the key's leaf decor,
- /// which a value replacement never touches. The trailing comment sits on the
- /// value, so replacing the item wholesale drops it: whenever a save changes
- /// a value, and — since template-variable migration became `Structural` —
- /// on a line the command never touched, because every load rewrites retired
- /// names and the next unrelated mutation (declining the commit-generation
- /// offer, say) finds that line changed. An inline table turning into a
- /// standard one takes the other path, `replace_inline_with_table`, which
- /// moves decor onto the header.
- fn replace_keeping_decor(existing_item: &mut toml_edit::Item, desired_item: &toml_edit::Item) {
- let decor = existing_item.as_value().map(|v| v.decor().clone());
- *existing_item = desired_item.clone();
- if let Some(decor) = decor
- && let Some(value) = existing_item.as_value_mut()
- {
- *value.decor_mut() = decor;
}
+ Ok(())
}
+}
- /// Compare two Items for value equality, ignoring formatting and comments.
- fn items_equal(a: &toml_edit::Item, b: &toml_edit::Item) -> bool {
- match (a, b) {
- (toml_edit::Item::Value(va), toml_edit::Item::Value(vb)) => Self::values_equal(va, vb),
- (toml_edit::Item::Table(ta), toml_edit::Item::Table(tb)) => Self::tables_equal(ta, tb),
- _ => false,
- }
- }
+/// The user config file as a mutation reads it: the document to edit and the
+/// config it loads as.
+pub(super) struct ConfigFile {
+ doc: DocumentMut,
+ pub(super) config: 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))
- }
- // Two different variants. Exhaustive on purpose — see above.
- (
- Value::String(_)
- | Value::Integer(_)
- | Value::Float(_)
- | Value::Boolean(_)
- | Value::Datetime(_)
- | Value::Array(_)
- | Value::InlineTable(_),
- _,
- ) => false,
+impl ConfigFile {
+ /// Read and parse the file; a missing file is an empty document holding the
+ /// default config.
+ pub(super) fn read(path: &std::path::Path) -> Result<Self, ConfigError> {
+ if !path.exists() {
+ return Ok(Self {
+ doc: DocumentMut::new(),
+ config: UserConfig::default(),
+ });
}
- }
- fn tables_equal(a: &toml_edit::Table, b: &toml_edit::Table) -> bool {
- a.len() == b.len()
- && a.iter()
- .all(|(k, v)| b.get(k).is_some_and(|bv| Self::items_equal(v, bv)))
+ let content = std::fs::read_to_string(path).map_err(|e| {
+ ConfigError(format!(
+ "Failed to read config file {}: {}",
+ format_path_for_display(path),
+ e
+ ))
+ })?;
+ let parse_error = |e: String| {
+ ConfigError(format!(
+ "Failed to parse config file {}: {}",
+ format_path_for_display(path),
+ e
+ ))
+ };
+ let doc: DocumentMut = content
+ .parse()
+ .map_err(|e: toml_edit::TomlError| parse_error(e.to_string()))?;
+ let config = load(&doc).map_err(|e| parse_error(e.to_string()))?;
+ Ok(Self { doc, config })
}
- /// Save the current configuration to a specific file path.
+ /// The file's content with `edit` applied, such that it loads as `expected`.
///
- /// Preserves comments and formatting in the existing file by diffing the
- /// serialized in-memory state against the parsed file and merging only
- /// 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)
- .map_err(|e| ConfigError(format!("Failed to create config directory: {}", e)))?;
+ /// The edit goes into the file as written when that loads as `expected`.
+ /// Otherwise a load-time migration touches the edit's path — a deprecated
+ /// `[commit-generation]` migrates to `[commit.generation]` only while that
+ /// table is absent — and the edit goes into the migrated file, which loads
+ /// as `expected` by construction: the migrations are idempotent and the
+ /// edit lands after them. That file carries *every* load-path migration,
+ /// not just the one on the edit's path, so it can also move an unrelated
+ /// deprecated section and drop the keys its destination has no field for.
+ /// A mutation is otherwise not what materializes migrations —
+ /// `wt config update` is — so [`Edited::Migrated`] says so, and its caller
+ /// tells the user.
+ pub(super) fn edited(
+ &self,
+ edit: &ConfigEdit,
+ expected: &UserConfig,
+ ) -> Result<Edited, ConfigError> {
+ let mut doc = self.doc.clone();
+ edit.apply(&mut doc)?;
+ if load(&doc).is_ok_and(|config| &config == expected) {
+ return Ok(Edited::AsWritten(doc.to_string()));
}
- let toml_string = if config_path.exists() {
- let existing_content = std::fs::read_to_string(config_path)
- .map_err(|e| ConfigError(format!("Failed to read config file: {}", e)))?;
-
- 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 desired_doc = self.to_expanded_document()?;
-
- // 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(),
- Some(base_doc.as_table()),
- );
-
- existing_doc.to_string()
- } else {
- self.to_expanded_document()?.to_string()
- };
+ let mut doc = self.doc.clone();
+ let changes = migrate_doc(&mut doc);
+ edit.apply(&mut doc)?;
+ Ok(Edited::Migrated {
+ content: doc.to_string(),
+ changes,
+ })
+ }
+}
- crate::config::ensure_config_parses(&toml_string)?;
- crate::utils::write_atomically(config_path, &toml_string)
- .map_err(|e| ConfigError(format!("Failed to write config file: {}", e)))?;
+/// A config file with an edit applied, and whether writing it took the load-path
+/// migrations with it.
+pub(super) enum Edited {
+ AsWritten(String),
+ /// The migrations came too, `changes` reporting each one — the sections
+ /// they moved and the keys they removed.
+ Migrated {
+ content: String,
+ changes: Deprecations,
+ },
+}
- Ok(())
+impl Edited {
+ pub(super) fn content(&self) -> &str {
+ match self {
+ Self::AsWritten(content) | Self::Migrated { content, .. } => content,
+ }
}
}
+/// The config a document loads as, after the load-time migrations.
+fn load(doc: &DocumentMut) -> Result<UserConfig, toml::de::Error> {
+ let mut migrated = doc.clone();
+ migrate_doc(&mut migrated);
+ toml::from_str(&migrated.to_string())
+}
+
// =========================================================================
// Validation
// =========================================================================
diff --git a/src/config/user/tests.rs b/src/config/user/tests.rs
index 0e78d47f8..3837ad8ff 100644
--- a/src/config/user/tests.rs
+++ b/src/config/user/tests.rs
@@ -1670,197 +1670,6 @@ worktree-path = "/worktrees/{{ branch | sanitize }}"
);
}
-// =========================================================================
-// save_to() tests
-// =========================================================================
-
-#[test]
-fn test_save_to_new_file_with_commit_generation() {
- // Test that save_to() creates a new file with commit.generation section
- // This exercises the "create from scratch" branch when no existing file exists
- let dir = tempfile::tempdir().unwrap();
- let config_path = dir.path().join("config.toml");
-
- let config = UserConfig {
- commit: CommitConfig {
- stage: None,
- generation: Some(CommitGenerationConfig {
- command: Some("llm -m haiku".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("[commit.generation]"),
- "Should use new format: {saved}"
- );
- assert!(
- saved.contains("command = \"llm -m haiku\""),
- "Should contain command: {saved}"
- );
- // When only generation is set (no stage), [commit] header should be implicit
- assert!(
- !saved.contains("[commit]\n"),
- "Should not have standalone [commit] header when only generation is set: {saved}"
- );
-}
-
-#[test]
-fn test_save_to_new_file_commit_with_stage_and_generation() {
- // Test that when both stage and generation are set, [commit] header is explicit
- let dir = tempfile::tempdir().unwrap();
- let config_path = dir.path().join("config.toml");
-
- let config = UserConfig {
- commit: CommitConfig {
- stage: Some(StageMode::Tracked),
- generation: Some(CommitGenerationConfig {
- command: Some("llm -m haiku".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("[commit]\n"),
- "Should have [commit] header when stage is set: {saved}"
- );
- assert!(
- saved.contains("stage = \"tracked\""),
- "Should contain stage: {saved}"
- );
- assert!(
- saved.contains("[commit.generation]"),
- "Should have generation section: {saved}"
- );
-}
-
-#[test]
-fn test_save_to_new_file_with_skip_shell_integration() {
- // Test skip-shell-integration-prompt is only written when true
- let dir = tempfile::tempdir().unwrap();
- let config_path = dir.path().join("config.toml");
-
- let config = UserConfig {
- skip_shell_integration_prompt: true,
- ..Default::default()
- };
-
- config.save_to(&config_path).unwrap();
-
- let saved = std::fs::read_to_string(&config_path).unwrap();
- assert!(
- saved.contains("skip-shell-integration-prompt = true"),
- "Should contain flag: {saved}"
- );
-}
-
-#[test]
-fn test_save_to_new_file_with_worktree_path() {
- // Test worktree-path is written when set
- let dir = tempfile::tempdir().unwrap();
- let config_path = dir.path().join("config.toml");
-
- let config = UserConfig {
- worktree_path: Some("../{{ repo }}.{{ branch }}".to_string()),
- ..Default::default()
- };
-
- config.save_to(&config_path).unwrap();
-
- let saved = std::fs::read_to_string(&config_path).unwrap();
- assert!(
- saved.contains("worktree-path = \"../{{ repo }}.{{ branch }}\""),
- "Should contain worktree-path: {saved}"
- );
-}
-
-#[test]
-fn test_save_to_preserves_project_section_configs() {
- // Exercises sync_serialized_section through the surgical-update save path
- let dir = tempfile::tempdir().unwrap();
- let config_path = dir.path().join("config.toml");
-
- // Create initial file with a project
- let initial = r#"
-[projects."github.com/user/repo"]
-worktree-path = ".wt/{{ branch | sanitize }}"
-"#;
- std::fs::write(&config_path, initial).unwrap();
-
- // Build config with project section overrides
- let mut config = UserConfig::default();
- config.projects.insert(
- "github.com/user/repo".to_string(),
- UserProjectOverrides {
- worktree_path: Some(".wt/{{ branch | sanitize }}".to_string()),
- merge: MergeConfig {
- squash: Some(false),
- ..Default::default()
- },
- list: ListConfig {
- full: Some(true),
- ..Default::default()
- },
- ..Default::default()
- },
- );
-
- config.save_to(&config_path).unwrap();
-
- let saved = std::fs::read_to_string(&config_path).unwrap();
- assert!(
- saved.contains("squash = false"),
- "Should serialize merge config: {saved}"
- );
- assert!(
- saved.contains("full = true"),
- "Should serialize list config: {saved}"
- );
-
- // Default sections should not appear
- assert!(
- !saved.contains("[projects.\"github.com/user/repo\".commit]"),
- "Default commit section should not appear: {saved}"
- );
- assert!(
- !saved.contains("[projects.\"github.com/user/repo\".switch]"),
- "Default switch section should not appear: {saved}"
- );
-}
-
-#[test]
-fn test_save_to_removes_default_project_section() {
- // Exercises the is_default → remove branch in sync_serialized_section
- let dir = tempfile::tempdir().unwrap();
- let config_path = dir.path().join("config.toml");
- std::fs::write(
- &config_path,
- "[projects.\"github.com/u/r\".list]\nfull = true\n",
- )
- .unwrap();
-
- let mut config =
- UserConfig::load_from_str(&std::fs::read_to_string(&config_path).unwrap()).unwrap();
- config.projects.get_mut("github.com/u/r").unwrap().list = ListConfig::default();
- config.save_to(&config_path).unwrap();
-
- let saved = std::fs::read_to_string(&config_path).unwrap();
- assert!(
- !saved.contains("[projects.\"github.com/u/r\".list]"),
- "Default section should be removed: {saved}"
- );
-}
-
// =========================================================================
// Per-project hooks tests (append semantics)
// =========================================================================
@@ -2130,13 +1939,13 @@ test = "npm test"
}
// =========================================================================
-// reload_from error path tests
+// Mutation error path tests
// =========================================================================
-/// Test that reload_from returns a parse error with formatted path
-/// when the config file contains invalid TOML.
+/// A mutation returns a parse error with the formatted path when the config
+/// file contains invalid TOML.
#[test]
-fn test_reload_from_invalid_toml() {
+fn test_mutation_invalid_toml() {
let dir = tempfile::tempdir().unwrap();
let config_path = dir.path().join("config.toml");
@@ -2146,7 +1955,7 @@ fn test_reload_from_invalid_toml() {
// Now corrupt it with invalid TOML
std::fs::write(&config_path, "this is not valid toml [[[").unwrap();
- // Try to reload via a mutation — should fail with parse error
+ // A mutation reads the file first — it should fail with a parse error
let mut config = UserConfig::default();
let result = config.set_skip_shell_integration_prompt(&config_path);
@@ -2328,11 +2137,11 @@ project-only = "only-project"
);
}
-/// Test that reload_from handles permission errors
-/// when the config file exists but cannot be read.
+/// A mutation surfaces a permission error when the config file exists but
+/// cannot be read.
#[cfg(unix)]
#[test]
-fn test_reload_from_permission_error() {
+fn test_mutation_permission_error() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
@@ -2361,7 +2170,7 @@ fn test_reload_from_permission_error() {
return;
}
- // Try to reload via a mutation — should fail with read error
+ // A mutation reads the file first — it should fail with a read error
let mut config = UserConfig::default();
let result = config.set_skip_shell_integration_prompt(&config_path);
@@ -2885,242 +2694,187 @@ fn test_finalize_with_undeserializable_table() {
}
// =========================================================================
-// save_to() tests — existing-file branch
+// ConfigEdit — writing one value into the file
// =========================================================================
#[test]
-fn test_save_to_existing_file_writes_project_sections() {
- // An existing file is updated with a project that has list, commit,
- // merge, and switch sections populated via diff-based merge.
- let dir = tempfile::tempdir().unwrap();
- let config_path = dir.path().join("config.toml");
-
- // Start with a minimal file so save_to takes the "existing file" path
- std::fs::write(&config_path, "# user config\n").unwrap();
-
- let mut config = UserConfig::default();
- config.projects.insert(
- "github.com/user/repo".to_string(),
- UserProjectOverrides {
- worktree_path: Some("../{{ branch | sanitize }}".to_string()),
- list: ListConfig {
- full: Some(true),
- ..Default::default()
- },
- commit: CommitConfig {
- stage: Some(StageMode::Tracked),
- generation: None,
- },
- merge: MergeConfig {
- squash: Some(false),
- ..Default::default()
- },
- switch: SwitchConfig {
- cd: Some(false),
- picker: None,
- },
- ..Default::default()
- },
- );
-
- config.save_to(&config_path).unwrap();
-
- let saved = std::fs::read_to_string(&config_path).unwrap();
- // Comment should be preserved
- assert!(saved.contains("# user config"), "comment lost: {saved}");
- // All four per-project sections should be present
- assert!(
- saved.contains("[projects.\"github.com/user/repo\".list]"),
- "missing list section: {saved}"
- );
- assert!(saved.contains("full = true"), "missing list.full: {saved}");
- assert!(
- saved.contains("[projects.\"github.com/user/repo\".commit]"),
- "missing commit section: {saved}"
- );
- assert!(
- saved.contains("stage = \"tracked\""),
- "missing commit.stage: {saved}"
- );
- assert!(
- saved.contains("[projects.\"github.com/user/repo\".merge]"),
- "missing merge section: {saved}"
- );
- assert!(
- saved.contains("squash = false"),
- "missing merge.squash: {saved}"
- );
- assert!(
- saved.contains("[projects.\"github.com/user/repo\".switch]"),
- "missing switch section: {saved}"
- );
- assert!(saved.contains("cd = false"), "missing switch.cd: {saved}");
-
- // Round-trip: file parses back into an equivalent config
- let reparsed = UserConfig::load_from_str(&saved).unwrap();
- let reloaded = reparsed.projects.get("github.com/user/repo").unwrap();
- assert_eq!(
- reloaded.worktree_path.as_deref(),
- Some("../{{ branch | sanitize }}")
- );
- assert_eq!(reloaded.list.full, Some(true));
- assert_eq!(reloaded.commit.stage, Some(StageMode::Tracked));
- assert_eq!(reloaded.merge.squash, Some(false));
- assert_eq!(reloaded.switch.cd, Some(false));
-}
-
-#[test]
-fn test_save_to_existing_file_removes_stale_projects_and_sections() {
- // The diff-based merge removes projects not in the in-memory config
- // and removes sections whose in-memory value is now None.
- let dir = tempfile::tempdir().unwrap();
- let config_path = dir.path().join("config.toml");
+fn test_config_edit_changes_only_its_value() {
+ // Each case writes one value and leaves the rest of the file as the user
+ // wrote it: comments, values at their defaults, and tables written inline
+ // or as dotted keys. An existing value keeps its trailing comment. A table
+ // the edit creates is implicit, or inline inside an inline table.
+ let cases: &[(&str, &[&str], &str)] = &[
+ (
+ r#"skip-shell-integration-prompt = false # keep asking
- // Existing file has two projects and a list section on the one we keep.
- std::fs::write(
- &config_path,
- r#"# keep me
-[projects."keep"]
-worktree-path = "keep-path"
+[list]
+columns = [] # pick later
-[projects."keep".list]
-full = true
+# fill in later
+[commit]
-[projects."drop"]
-worktree-path = "drop-path"
+[commit.generation]
+command = "old" # fast model
"#,
- )
- .unwrap();
+ &["commit", "generation"],
+ "command",
+ ),
+ ("", &["commit", "generation"], "command"),
+ (
+ "# why we generate\ncommit = { generation = { command = \"old\" } } # trailing\n",
+ &["commit", "generation"],
+ "command",
+ ),
+ (
+ "projects = { \"a\" = { worktree-path = \"x\" } }\n",
+ &["projects", "github.com/u/r"],
+ "worktree-path",
+ ),
+ (
+ "commit.generation.command = \"old\"\n",
+ &["commit", "generation"],
+ "command",
+ ),
+ (
+ "commit.stage = \"all\"\n",
+ &["commit", "generation"],
+ "command",
+ ),
+ ];
- let mut config = UserConfig::default();
- config.projects.insert(
- "keep".to_string(),
- UserProjectOverrides {
- worktree_path: Some("keep-path".to_string()),
- list: ListConfig::default(), // was non-default on disk, now default — should be removed
- ..Default::default()
- },
- );
+ let mut rendered = String::new();
+ for (input, tables, key) in cases {
+ let mut doc: toml_edit::DocumentMut = input.parse().unwrap();
+ super::persistence::ConfigEdit {
+ tables: tables.to_vec(),
+ key,
+ value: "new".into(),
+ }
+ .apply(&mut doc)
+ .unwrap();
+ rendered.push_str(&format!("----- {}.{key}\n{doc}", tables.join(".")));
+ }
+ insta::assert_snapshot!(rendered, @r#"
+ ----- commit.generation.command
+ skip-shell-integration-prompt = false # keep asking
- config.save_to(&config_path).unwrap();
+ [list]
+ columns = [] # pick later
- let saved = std::fs::read_to_string(&config_path).unwrap();
- assert!(saved.contains("# keep me"), "comment lost: {saved}");
- assert!(
- saved.contains("[projects.\"keep\"]") || saved.contains("\"keep\""),
- "keep project lost: {saved}"
- );
- assert!(
- !saved.contains("\"drop\""),
- "stale project not removed: {saved}"
- );
- assert!(
- !saved.contains("[projects.\"keep\".list]"),
- "stale list section not removed: {saved}"
- );
+ # fill in later
+ [commit]
+
+ [commit.generation]
+ command = "new" # fast model
+ ----- commit.generation.command
+ [commit.generation]
+ command = "new"
+ ----- commit.generation.command
+ # why we generate
+ commit = { generation = { command = "new" } } # trailing
+ ----- projects.github.com/u/r.worktree-path
+ projects = { "a" = { worktree-path = "x" } , "github.com/u/r" = { worktree-path = "new" } }
+ ----- commit.generation.command
+ commit.generation.command = "new"
+ ----- commit.generation.command
+ commit.stage = "all"
+
+ [commit.generation]
+ command = "new"
+ "#);
}
#[test]
-fn test_save_to_existing_file_updates_commit_generation_command() {
- // The file already has a [commit.generation] table — the diff-based merge
- // updates the changed command in place while preserving unchanged keys.
- let dir = tempfile::tempdir().unwrap();
- let config_path = dir.path().join("config.toml");
- std::fs::write(
- &config_path,
- r#"# keep this comment
-[commit.generation]
-command = "old-llm"
-template = "stays: {{ diff }}"
-"#,
- )
- .unwrap();
-
- let config = UserConfig {
- commit: CommitConfig {
- stage: None,
- generation: Some(CommitGenerationConfig {
- command: Some("new-llm".to_string()),
- template: Some("stays: {{ diff }}".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("# keep this comment"),
- "comment lost: {saved}"
- );
- assert!(
- saved.contains("command = \"new-llm\""),
- "command not updated: {saved}"
- );
- assert!(
- !saved.contains("old-llm"),
- "old command not removed: {saved}"
- );
- assert!(
- saved.contains("template = \"stays: {{ diff }}\""),
- "template not preserved: {saved}"
- );
+fn test_config_edit_fails_when_a_parent_is_not_a_table() {
+ let mut doc: toml_edit::DocumentMut = "commit = \"oops\"\n".parse().unwrap();
+ let err = super::persistence::ConfigEdit {
+ tables: vec!["commit", "generation"],
+ key: "command",
+ value: "llm".into(),
+ }
+ .apply(&mut doc)
+ .unwrap_err();
+ insta::assert_snapshot!(err.to_string(), @"Failed to write config file: `commit` is not a table");
}
#[test]
-fn test_save_to_existing_file_adds_commit_generation_to_plain_commit_table() {
- // Existing file has a [commit] table (e.g., with `stage`) but no
- // [commit.generation] subtable yet. The diff-based merge inserts the
- // new subtable while preserving existing keys.
+fn test_edit_takes_the_migrations_when_one_lands_on_its_path() {
+ // A deprecated `[commit-generation]` migrates to `[commit.generation]` only
+ // while that table is absent, so the command can't be written there as the
+ // file stands: the edit takes the load-time migrations with it, and says so.
let dir = tempfile::tempdir().unwrap();
let config_path = dir.path().join("config.toml");
std::fs::write(
&config_path,
- r#"[commit]
-stage = "all"
-"#,
+ "[commit-generation]\ntemplate = \"MINE\"\n\n[select]\npager = \"delta\"\nheight = 5\n",
)
.unwrap();
- let config = UserConfig {
- commit: CommitConfig {
- stage: Some(StageMode::All),
- generation: Some(CommitGenerationConfig {
- command: Some("llm".to_string()),
- ..Default::default()
- }),
- },
- ..Default::default()
- };
-
- config.save_to(&config_path).unwrap();
+ let file = super::persistence::ConfigFile::read(&config_path).unwrap();
+ let mut changed = file.config.clone();
+ changed
+ .commit
+ .generation
+ .get_or_insert_with(Default::default)
+ .command = Some("llm".to_string());
+ let edit = super::persistence::ConfigEdit {
+ tables: vec!["commit", "generation"],
+ key: "command",
+ value: "llm".into(),
+ };
+
+ let super::persistence::Edited::Migrated { content, changes } =
+ file.edited(&edit, &changed).unwrap()
+ else {
+ panic!("the edit should have taken the migrations with it");
+ };
+ // `[switch.picker]` has no `height`, so the migration drops it. Every
+ // change is reported, which is what the caller's warning prints.
+ insta::assert_snapshot!(
+ ansi_str::AnsiStr::ansi_strip(&crate::config::deprecation::format_applied_lines(&changes)),
+ @r"
+ ▲ Moved [commit-generation] to [commit.generation]
+ ▲ Moved [select] to [switch.picker]
+ ▲ Removed [select] height, which its replacement has no field for
+ "
+ );
+ // The migrated file carries every load-path migration, so the unrelated
+ // `[select]` moves too — what the caller's warning tells the user about.
+ insta::assert_snapshot!(content, @r#"
+ [commit.generation]
+ template = "MINE"
+ command = "llm"
+
+ [switch.picker]
+ pager = "delta"
+ "#);
- let saved = std::fs::read_to_string(&config_path).unwrap();
- assert!(
- saved.contains("[commit.generation]"),
- "generation subtable missing: {saved}"
- );
- assert!(
- saved.contains("command = \"llm\""),
- "command missing: {saved}"
- );
- assert!(saved.contains("stage = \"all\""), "stage lost: {saved}");
+ // An edit no migration lands on leaves the file's own spelling alone.
+ let mut only_flag = file.config.clone();
+ only_flag.skip_shell_integration_prompt = true;
+ let flag_edit = super::persistence::ConfigEdit {
+ tables: vec![],
+ key: "skip-shell-integration-prompt",
+ value: true.into(),
+ };
+ assert!(matches!(
+ file.edited(&flag_edit, &only_flag).unwrap(),
+ super::persistence::Edited::AsWritten(_)
+ ));
}
#[test]
-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.
+fn test_mutation_fails_on_a_file_that_is_not_a_valid_config_and_leaves_it() {
+ // Valid TOML that doesn't deserialize as a config (a hand edit like
+ // `commit = "oops"`) fails the reload, before anything is written.
let dir = tempfile::tempdir().unwrap();
let config_path = dir.path().join("config.toml");
let content = "commit = \"oops\"\n";
std::fs::write(&config_path, content).unwrap();
- let err = UserConfig::default().save_to(&config_path).unwrap_err();
+ let err = UserConfig::default()
+ .set_commit_generation_command("llm".to_string(), &config_path)
+ .unwrap_err();
assert!(
err.to_string().contains("Failed to parse config file"),
"expected parse error, got: {err}"
@@ -3128,661 +2882,19 @@ fn test_save_to_existing_file_with_type_mismatch_fails_and_leaves_it() {
assert_eq!(std::fs::read_to_string(&config_path).unwrap(), content);
}
+// =========================================================================
+// mutation.rs — additional coverage
+// =========================================================================
+
#[test]
-fn test_save_to_existing_file_with_invalid_toml_returns_parse_error() {
- // Covers the `parse().map_err(...)` closure in save_to's existing-file
- // branch: the file exists (so we take the "surgical update" path) but
- // its contents don't parse as TOML.
- let dir = tempfile::tempdir().unwrap();
- let config_path = dir.path().join("config.toml");
- std::fs::write(&config_path, "this is not [[[ valid toml").unwrap();
-
- let config = UserConfig::default();
- let err = config.save_to(&config_path).unwrap_err();
- let msg = err.to_string();
- assert!(
- msg.contains("Failed to parse config file"),
- "expected parse error, got: {msg}"
- );
-}
-
-#[cfg(unix)]
-#[test]
-fn test_save_to_existing_file_with_unreadable_file_returns_read_error() {
- // Covers the `read_to_string.map_err(...)` closure in save_to: the file
- // exists but we can't read it. Matches the pattern of the mutation-side
- // test_reload_from_permission_error.
- use std::os::unix::fs::PermissionsExt;
-
- let dir = tempfile::tempdir().unwrap();
- let config_path = dir.path().join("config.toml");
- std::fs::write(&config_path, "# valid\n").unwrap();
-
- let mut perms = std::fs::metadata(&config_path).unwrap().permissions();
- perms.set_mode(0o000);
- std::fs::set_permissions(&config_path, perms).unwrap();
-
- struct RestorePerms<'a>(&'a std::path::Path);
- impl Drop for RestorePerms<'_> {
- fn drop(&mut self) {
- let mut perms = std::fs::metadata(self.0).unwrap().permissions();
- perms.set_mode(0o644);
- let _ = std::fs::set_permissions(self.0, perms);
- }
- }
- let _guard = RestorePerms(&config_path);
-
- if !permissions_restrict_reads(dir.path()) {
- return;
- }
-
- let config = UserConfig::default();
- let err = config.save_to(&config_path).unwrap_err();
- let msg = err.to_string();
- assert!(
- msg.contains("Failed to read config file"),
- "expected read error, got: {msg}"
- );
-}
-
-#[test]
-fn test_save_to_root_path_skips_parent_creation() {
- // Covers the else branch of `if let Some(parent) = config_path.parent()`
- // in save_to: when the config path is the filesystem root (`/`), parent()
- // returns None and we skip create_dir_all. The downstream write will
- // fail because `/` is a directory, but we should reach that point
- // without panicking — proving the None branch executes cleanly.
- let config = UserConfig::default();
- let err = config.save_to(std::path::Path::new("/")).unwrap_err();
- let msg = err.to_string();
- // We expect to fail at the read/write step, not at create_dir_all.
- // The specific error depends on the platform (read error since "/"
- // exists, or write error). We just verify it wasn't the create_dir
- // path (which would mean line 216's else branch wasn't taken).
- assert!(
- !msg.contains("Failed to create config directory"),
- "should skip create_dir when parent is None, got: {msg}"
- );
-}
-
-#[test]
-fn test_save_to_fails_when_parent_is_a_file() {
- // Covers the create_dir_all error branch: if config_path's parent
- // already exists as a regular file, create_dir_all fails and save_to
- // returns a "Failed to create config directory" error.
- let dir = tempfile::tempdir().unwrap();
- let blocker = dir.path().join("blocker");
- std::fs::write(&blocker, "i am a file").unwrap();
-
- // config_path's parent is "blocker", which is a file
- let config_path = blocker.join("config.toml");
-
- let config = UserConfig::default();
- let err = config.save_to(&config_path).unwrap_err();
- let msg = err.to_string();
- assert!(
- msg.contains("Failed to create config directory"),
- "expected create_dir error, got: {msg}"
- );
-}
-
-#[test]
-fn test_save_to_new_file_expands_nested_project_inline_tables() {
- // Covers expand_inline_tables recursion: a per-project config with nested
- // sections forces to_document to emit inline tables that must be expanded
- // into standard [projects."id".list] etc. subtables for readability.
+fn test_set_project_worktree_path_noop_when_unchanged() {
+ // Covers the `None` early exit in set_project_worktree_path's
+ // mutator: when the path already matches, nothing is written. We verify
+ // this by checking that the file content is byte-identical across a
+ // redundant call.
let dir = tempfile::tempdir().unwrap();
let config_path = dir.path().join("config.toml");
-
- let mut config = UserConfig::default();
- config.projects.insert(
- "repo".to_string(),
- UserProjectOverrides {
- list: ListConfig {
- full: Some(true),
- branches: Some(true),
- ..Default::default()
- },
- switch: SwitchConfig {
- cd: Some(false),
- picker: None,
- },
- ..Default::default()
- },
- );
-
- config.save_to(&config_path).unwrap();
-
- let saved = std::fs::read_to_string(&config_path).unwrap();
- // Should be expanded into standard subtables, not inline tables
- assert!(
- saved.contains("[projects.repo.list]"),
- "list should be expanded to standard subtable: {saved}"
- );
- assert!(
- saved.contains("[projects.repo.switch]"),
- "switch should be expanded to standard subtable: {saved}"
- );
- // Inline syntax should not appear for these sections
- assert!(
- !saved.contains("list = {"),
- "list should not be inline: {saved}"
- );
- assert!(
- !saved.contains("switch = {"),
- "switch should not be inline: {saved}"
- );
- // And it should round-trip cleanly
- let reparsed = UserConfig::load_from_str(&saved).unwrap();
- assert_eq!(
- reparsed.projects.get("repo").unwrap().list.branches,
- Some(true)
- );
-}
-
-#[test]
-fn test_save_to_existing_file_preserves_integer_and_array_values() {
- // Exercises values_equal for Integer (timeout-ms) and Array
- // (approved-commands) — types beyond String and Boolean.
- let dir = tempfile::tempdir().unwrap();
- let config_path = dir.path().join("config.toml");
- std::fs::write(
- &config_path,
- r#"# keep comment
-[list]
-timeout-ms = 5000
-full = true
-
-[projects."repo"]
-approved-commands = ["cargo test", "cargo build"]
-"#,
- )
- .unwrap();
-
- let config =
- UserConfig::load_from_str(&std::fs::read_to_string(&config_path).unwrap()).unwrap();
- config.save_to(&config_path).unwrap();
-
- let saved = std::fs::read_to_string(&config_path).unwrap();
- assert!(saved.contains("# keep comment"), "comment lost: {saved}");
- assert!(
- saved.contains("timeout-ms = 5000"),
- "integer value should be preserved: {saved}"
- );
- assert!(
- saved.contains("full = true"),
- "boolean value should be preserved: {saved}"
- );
- assert!(
- saved.contains("cargo test") && saved.contains("cargo build"),
- "array values should be preserved: {saved}"
- );
-}
-
-#[test]
-fn test_save_to_existing_file_replaces_changed_inline_table() {
- // When an inline table's contents actually changed, the diff-based merge
- // replaces it (even though this changes formatting from inline to standard).
- let dir = tempfile::tempdir().unwrap();
- let config_path = dir.path().join("config.toml");
- std::fs::write(&config_path, "post-start = { build = \"cargo build\" }\n").unwrap();
-
- // Load, modify the hook, then save
- let mut config =
- UserConfig::load_from_str(&std::fs::read_to_string(&config_path).unwrap()).unwrap();
- config.hooks = toml::from_str("post-start = { build = \"cargo test\" }").unwrap();
- config.save_to(&config_path).unwrap();
-
- let saved = std::fs::read_to_string(&config_path).unwrap();
- assert!(
- saved.contains("cargo test"),
- "changed value should be written: {saved}"
- );
- assert!(
- !saved.contains("cargo build"),
- "old value should be gone: {saved}"
- );
-}
-
-#[test]
-fn test_save_to_existing_file_preserves_unknown_keys() {
- // Unknown top-level keys (typos, future fields) must survive a save.
- // The diff-based merge skips unknown keys in its stale-key sweep.
- let dir = tempfile::tempdir().unwrap();
- let config_path = dir.path().join("config.toml");
- std::fs::write(
- &config_path,
- r#"# A user comment
-unknown-key = "keep me"
-skip-shell-integration-prompt = true
-"#,
- )
- .unwrap();
-
- let config = UserConfig {
- skip_shell_integration_prompt: true,
- ..Default::default()
- };
-
- config.save_to(&config_path).unwrap();
-
- let saved = std::fs::read_to_string(&config_path).unwrap();
- assert!(
- saved.contains("unknown-key = \"keep me\""),
- "unknown key should be preserved: {saved}"
- );
- assert!(
- saved.contains("# A user comment"),
- "comment should be preserved: {saved}"
- );
- assert!(
- saved.contains("skip-shell-integration-prompt = true"),
- "known key should be preserved: {saved}"
- );
-}
-
-#[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 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(
- &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_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_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
- // 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 = { ... }`),
- // the diff-based merge must not rewrite it to a standard table if the value
- // is semantically unchanged.
- let dir = tempfile::tempdir().unwrap();
- let config_path = dir.path().join("config.toml");
- let original = "post-start = { build = \"cargo build\" }\n";
- std::fs::write(&config_path, original).unwrap();
-
- // Load the config (which parses hooks via flatten), then save it back
- let config = UserConfig::load_from_str(original).unwrap();
- config.save_to(&config_path).unwrap();
-
- let saved = std::fs::read_to_string(&config_path).unwrap();
- // The inline table syntax should be preserved (not expanded to [post-start])
- assert!(
- saved.contains("post-start = { build = \"cargo build\" }"),
- "inline table should be preserved: {saved}"
- );
- assert!(
- !saved.contains("[post-start]"),
- "should not be expanded to standard table: {saved}"
- );
-}
-
-// =========================================================================
-// mutation.rs — additional coverage
-// =========================================================================
-
-#[test]
-fn test_set_project_worktree_path_noop_when_unchanged() {
- // Covers the `return false` early-exit in set_project_worktree_path's
- // mutator: when the path already matches, no save happens. We verify
- // this by checking that the file content is byte-identical across a
- // redundant call.
- let dir = tempfile::tempdir().unwrap();
- let config_path = dir.path().join("config.toml");
- std::fs::write(&config_path, "# keep\n").unwrap();
+ std::fs::write(&config_path, "# keep\n").unwrap();
let mut config = UserConfig::default();
config
@@ -3793,9 +2905,9 @@ fn test_set_project_worktree_path_noop_when_unchanged() {
// Sanity: first call actually wrote the value
assert!(after_first.contains("../custom"), "{after_first}");
- // Second call with identical value should be a no-op — reload_from
- // refreshes self from disk, the mutator compares equal and returns
- // false, so save is skipped.
+ // Second call with identical value should be a no-op — the mutator runs
+ // on the file's config, compares equal and returns `None`, so nothing is
+ // written.
let mut config2 = UserConfig::default();
config2
.set_project_worktree_path("user/repo", "../custom".to_string(), &config_path)
@@ -3810,8 +2922,8 @@ fn test_set_project_worktree_path_noop_when_unchanged() {
#[test]
fn test_set_commit_generation_command_noop_when_unchanged() {
- // Covers the `return false` early-exit in set_commit_generation_command's
- // mutator: when the command already matches, no save happens. We verify
+ // Covers the `None` early exit in set_commit_generation_command's
+ // mutator: when the command already matches, nothing is written. We verify
// this by checking that the file content is byte-identical across a
// redundant call.
let dir = tempfile::tempdir().unwrap();
@@ -3827,9 +2939,9 @@ fn test_set_commit_generation_command_noop_when_unchanged() {
// Sanity: first call actually wrote the value
assert!(after_first.contains("llm -m haiku"), "{after_first}");
- // Second call with identical value should be a no-op — reload_from
- // refreshes self from disk, the mutator compares equal and returns
- // false, so save is skipped.
+ // Second call with identical value should be a no-op — the mutator runs
+ // on the file's config, compares equal and returns `None`, so nothing is
+ // written.
let mut config2 = UserConfig::default();
config2
.set_commit_generation_command("llm -m haiku".to_string(), &config_path)
@@ -3844,10 +2956,10 @@ fn test_set_commit_generation_command_noop_when_unchanged() {
#[test]
fn test_set_skip_shell_integration_prompt_noop_on_second_call() {
- // Covers the `return false` early-exit in set_skip_shell_integration_prompt's
- // mutator. reload_from refreshes all fields from disk — after the first
- // save, the flag is true on disk, so a second call sees it already true
- // and skips the save.
+ // Covers the `None` early exit in set_skip_shell_integration_prompt's
+ // mutator. The mutator runs on the file's config — after the first
+ // write, the flag is true on disk, so a second call sees it already true
+ // and writes nothing.
let dir = tempfile::tempdir().unwrap();
let config_path = dir.path().join("config.toml");
std::fs::write(&config_path, "# empty\n").unwrap();
@@ -3860,7 +2972,7 @@ fn test_set_skip_shell_integration_prompt_noop_on_second_call() {
assert!(after_first.contains("skip-shell-integration-prompt = true"));
// Second call with the flag already true in-memory — mutator returns
- // false, save is skipped, file is byte-identical.
+ // `None`, nothing is written, file is byte-identical.
config
.set_skip_shell_integration_prompt(&config_path)
.unwrap();
@@ -3868,6 +2980,35 @@ fn test_set_skip_shell_integration_prompt_noop_on_second_call() {
assert_eq!(after_first, after_second);
}
+#[test]
+fn test_mutation_keeps_in_memory_config_the_file_lacks() {
+ // The in-memory config also carries system config, environment variables,
+ // and `--config-set`. A mutation applies its change to it without
+ // replacing it with the file's config, so the rest of the command still
+ // reads those values.
+ let dir = tempfile::tempdir().unwrap();
+ let config_path = dir.path().join("config.toml");
+ std::fs::write(&config_path, "[list]\nfull = true\n").unwrap();
+
+ let mut config = UserConfig {
+ commit: CommitConfig {
+ stage: Some(StageMode::None),
+ generation: None,
+ },
+ ..Default::default()
+ };
+ config
+ .set_skip_commit_generation_prompt(&config_path)
+ .unwrap();
+
+ assert_eq!(config.commit.stage, Some(StageMode::None));
+ assert!(config.skip_commit_generation_prompt);
+ assert_eq!(
+ std::fs::read_to_string(&config_path).unwrap(),
+ "skip-commit-generation-prompt = true\n[list]\nfull = true\n"
+ );
+}
+
#[test]
fn test_acquire_config_lock_handles_root_path() {
// Covers the else branch of `if let Some(parent) = lock_path.parent()`
@@ -3915,53 +3056,49 @@ fn test_acquire_config_lock_fails_when_parent_is_file() {
#[cfg(unix)]
#[test]
-fn test_with_locked_mutation_propagates_save_error() {
- // Covers the `save_to(&path)?` error branch in with_locked_mutation:
- // after a successful lock + reload, the mutator closure chmods the
- // config file to 000. The subsequent save_to tries to read the
- // existing file and fails with a permission
- // error, which with_locked_mutation propagates back to the caller.
+fn test_with_locked_mutation_propagates_write_error() {
+ // After lock and reload, the mutator makes the config directory read-only,
+ // so writing the edited file — a temp file beside it, renamed over it —
+ // fails, and with_locked_mutation returns that error to the caller.
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
- let config_path = dir.path().join("config.toml");
+ let config_dir = dir.path().join("config");
+ std::fs::create_dir(&config_dir).unwrap();
+ let config_path = config_dir.join("config.toml");
std::fs::write(&config_path, "# valid\n").unwrap();
struct RestorePerms<'a>(&'a std::path::Path);
impl Drop for RestorePerms<'_> {
fn drop(&mut self) {
- if let Ok(meta) = std::fs::metadata(self.0) {
- let mut perms = meta.permissions();
- perms.set_mode(0o644);
- let _ = std::fs::set_permissions(self.0, perms);
- }
+ let _ = std::fs::set_permissions(self.0, std::fs::Permissions::from_mode(0o755));
}
}
- let _guard = RestorePerms(&config_path);
+ let _guard = RestorePerms(&config_dir);
if !permissions_restrict_reads(dir.path()) {
return;
}
- let cfg_path_for_closure = config_path.clone();
+ let dir_for_closure = config_dir.clone();
let mut config = UserConfig::default();
let err = config
.with_locked_mutation(&config_path, move |_config| {
- // Mid-mutation: strip read permissions from the config file.
- // reload_from already ran; save_to will try to read again and fail.
- let mut perms = std::fs::metadata(&cfg_path_for_closure)
- .unwrap()
- .permissions();
- perms.set_mode(0o000);
- std::fs::set_permissions(&cfg_path_for_closure, perms).unwrap();
- true
+ std::fs::set_permissions(&dir_for_closure, std::fs::Permissions::from_mode(0o555))
+ .unwrap();
+ Some(super::persistence::ConfigEdit {
+ tables: vec![],
+ key: "skip-shell-integration-prompt",
+ value: true.into(),
+ })
})
.unwrap_err();
let msg = err.to_string();
assert!(
- msg.contains("Failed to read config file"),
- "expected save-side read error, got: {msg}"
+ msg.contains("Failed to write config file"),
+ "expected write error, got: {msg}"
);
+ assert_eq!(std::fs::read_to_string(&config_path).unwrap(), "# valid\n");
}
#[test]
diff --git a/tests/integration_tests/approval_save.rs b/tests/integration_tests/approval_save.rs
index c632571ac..070330860 100644
--- a/tests/integration_tests/approval_save.rs
+++ b/tests/integration_tests/approval_save.rs
@@ -180,28 +180,6 @@ fn test_isolated_config_safety() {
assert!(isolated_content.contains("THIS SHOULD NOT APPEAR IN USER APPROVALS"));
}
-///
-/// The --yes flag should allow commands to run once without saving them
-/// to the config file. This ensures --yes is a one-time bypass, not a
-/// permanent approval.
-#[test]
-fn test_yes_flag_does_not_save_approval() {
- let temp_dir = TempDir::new().unwrap();
- let config_path = temp_dir.path().join("config.toml");
-
- // Start with empty config
- let initial_config = UserConfig::default();
- initial_config.save_to(&config_path).unwrap();
-
- // When using --yes, the approval is NOT saved to config
- // This is the correct behavior - yes is a one-time bypass
- // So we just verify the initial config is unchanged
-
- // Load the config and verify it's still empty (no approvals added)
- let saved_config = fs::read_to_string(&config_path).unwrap();
- assert_snapshot!(saved_config, @"");
-}
-
#[test]
fn test_approval_saves_to_new_approvals_file() {
let temp_dir = TempDir::new().unwrap();
@@ -235,72 +213,126 @@ fn test_approval_saves_to_new_approvals_file() {
"#);
}
-///
-/// When a user has a config file with comments and we save a non-approval
-/// mutation, all their comments should be preserved.
+/// A deprecated `[commit-generation]` section loads as `[commit.generation]`,
+/// but its migration declines once the canonical table exists. Writing the
+/// command there directly would leave the section's template unread, so the
+/// edit goes into the migrated file and the saved config keeps both — taking
+/// the rest of the load-path migrations with it, including a `[select]` key
+/// `[switch.picker]` has no field for.
#[test]
-fn test_saving_config_mutation_preserves_toml_comments() {
+fn test_saving_command_beside_deprecated_commit_generation_keeps_its_template() {
+ let temp_dir = TempDir::new().unwrap();
+ let config_path = temp_dir.path().join("config.toml");
+ fs::write(
+ &config_path,
+ "[commit-generation]\ntemplate = \"MY TEMPLATE {{ git_diff }}\"\n\n[select]\npager = \"delta\"\nheight = 5\n",
+ )
+ .unwrap();
+
+ UserConfig::default()
+ .set_commit_generation_command("llm".to_string(), &config_path)
+ .unwrap();
+
+ let saved = fs::read_to_string(&config_path).unwrap();
+ let loaded: UserConfig = toml::from_str(&worktrunk::config::migrate_content(&saved)).unwrap();
+ let generation = loaded.commit.generation.unwrap();
+ assert_eq!(generation.command.as_deref(), Some("llm"));
+ assert_eq!(
+ generation.template.as_deref(),
+ Some("MY TEMPLATE {{ git_diff }}")
+ );
+ assert_snapshot!(saved, @r#"
+ [commit.generation]
+ template = "MY TEMPLATE {{ git_diff }}"
+ command = "llm"
+
+ [switch.picker]
+ pager = "delta"
+ "#);
+}
+
+/// A config mutation writes only the value it changes. Everything else stays as
+/// the user wrote it, including what the load path rewrites in memory: a retired
+/// template variable, a hook under its `pre-create` alias, and a deprecated
+/// `[select]` section, none of which a save may write in its canonical form
+/// beside the original.
+#[test]
+fn test_saving_config_mutation_changes_only_its_value() {
let temp_dir = TempDir::new().unwrap();
let config_path = temp_dir.path().join("config.toml");
- // `main_worktree` is retired, so loading migrates this line to `{{ repo }}`
- // and the save below rewrites it — the case where decor is easiest to drop.
- // The `command` line carries one too, since that is the line the mutation
- // itself changes.
let initial_content = r#"# User preferences for worktrunk
-# These comments should be preserved after saving
-worktree-path = "../{{ main_worktree }}.{{ branch }}" # inline comment should also be preserved
+worktree-path = "../{{ main_worktree }}.{{ branch }}" # retired name
+skip-shell-integration-prompt = false # keep asking
+pre-create = "npm install" # alias for pre-start
+post-start = [{ server = "npm run dev" }] # port 3000
+
+[list]
+columns = [] # pick later
+
+# picker look
+[select]
+pager = "delta"
# LLM commit generation settings
+[commit]
+
[commit.generation]
-command = "llm -m claude-haiku-4.5" # comment on the mutated line
+command = "llm -m claude-haiku-4.5" # fast model
+
+[projects]
+"example.com/org/inline" = { worktree-path = "../x" } # entry note
-# Per-project settings below
+# announce the switch
+[[post-switch]]
+notify = "echo switched"
"#;
fs::write(&config_path, initial_content).unwrap();
- // Load the config manually by deserializing from TOML
- let toml_str = fs::read_to_string(&config_path).unwrap();
- let mut config: UserConfig = toml::from_str(&toml_str).unwrap();
-
- // Change a non-approval setting and save back to the same file
+ let mut config = UserConfig::default();
config
.set_commit_generation_command("llm -m claude-sonnet-4".to_string(), &config_path)
.unwrap();
+ config
+ .set_project_worktree_path(
+ "github.com/user/repo",
+ "../{{ branch }}".to_string(),
+ &config_path,
+ )
+ .unwrap();
- // Read back the saved config
- let saved_content = fs::read_to_string(&config_path).unwrap();
+ assert_snapshot!(fs::read_to_string(&config_path).unwrap(), @r#"
+ # User preferences for worktrunk
- // Verify comments are preserved
- assert!(
- saved_content.contains("# User preferences for worktrunk"),
- "Top-level comment was lost. Saved content:\n{saved_content}"
- );
- assert!(
- saved_content.contains("# LLM commit generation settings"),
- "Section comment was lost. Saved content:\n{saved_content}"
- );
- assert!(
- saved_content.contains("# inline comment should also be preserved"),
- "Inline comment was lost. Saved content:\n{saved_content}"
- );
- assert!(
- saved_content.contains("# comment on the mutated line"),
- "Inline comment on the mutated line was lost. Saved content:\n{saved_content}"
- );
+ worktree-path = "../{{ main_worktree }}.{{ branch }}" # retired name
+ skip-shell-integration-prompt = false # keep asking
+ pre-create = "npm install" # alias for pre-start
+ post-start = [{ server = "npm run dev" }] # port 3000
- // Verify the command was updated
- assert!(
- saved_content.contains("llm -m claude-sonnet-4"),
- "Command was not updated. Saved content:\n{saved_content}"
- );
+ [list]
+ columns = [] # pick later
- // The retired name still migrates — keeping the comment must not cost the rewrite
- assert!(
- saved_content.contains(r#"worktree-path = "../{{ repo }}.{{ branch }}""#),
- "Retired variable was not migrated. Saved content:\n{saved_content}"
- );
+ # picker look
+ [select]
+ pager = "delta"
+
+ # LLM commit generation settings
+ [commit]
+
+ [commit.generation]
+ command = "llm -m claude-sonnet-4" # fast model
+
+ [projects]
+ "example.com/org/inline" = { worktree-path = "../x" } # entry note
+
+ [projects."github.com/user/repo"]
+ worktree-path = "../{{ branch }}"
+
+ # announce the switch
+ [[post-switch]]
+ notify = "echo switched"
+ "#);
}
///
@@ -812,254 +844,3 @@ worktree-path = "../{{ main_worktree }}.{{ branch }}"
"Content should be identical whether read through symlink or target"
);
}
-
-/// Test that set_commit_generation_command persists to an existing config file
-/// while preserving other content.
-///
-/// This is a regression test for a bug where the "file exists" branch in save_to()
-/// didn't know about the commit.generation section, so setting the command would
-/// succeed in memory but not persist to disk.
-#[test]
-fn test_set_commit_generation_command_preserves_existing_content() {
- let temp_dir = TempDir::new().unwrap();
- let config_path = temp_dir.path().join("config.toml");
-
- // Create existing config with other sections
- let initial_content = r#"# My settings
-worktree-path = "../{{ repo }}.{{ branch }}"
-
-[projects."github.com/user/repo"]
-approved-commands = [
- "npm install",
-]
-"#;
- fs::write(&config_path, initial_content).unwrap();
-
- // Load the config and set the commit generation command
- 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 haiku".to_string(), &config_path)
- .unwrap();
-
- // Read back what was saved
- let saved = fs::read_to_string(&config_path).unwrap();
-
- // Original content should be preserved
- assert!(
- saved.contains("worktree-path = \"../{{ repo }}.{{ branch }}\""),
- "worktree-path should be preserved. Saved content:\n{saved}"
- );
- assert!(
- saved.contains("npm install"),
- "approved-commands should be preserved. Saved content:\n{saved}"
- );
- assert!(
- saved.contains("# My settings"),
- "Comments should be preserved. Saved content:\n{saved}"
- );
-
- // New section should be added
- assert!(
- saved.contains("[commit.generation]"),
- "[commit.generation] section should be added. Saved content:\n{saved}"
- );
- assert!(
- saved.contains("llm -m haiku"),
- "command should be saved. Saved content:\n{saved}"
- );
- // When only generation is set (no stage), [commit] header should be implicit
- assert!(
- !saved.contains("[commit]\n"),
- "Should not have standalone [commit] header when only generation is set:\n{saved}"
- );
-}
-
-/// 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
-/// save replaces it with a standard table — a different shape from the scalar
-/// case above, and the one where the comment is easiest to drop. The retired
-/// `main_worktree` inside it is what makes the entry differ from the file at
-/// all, since template migration runs on every load.
-#[test]
-fn test_saving_config_mutation_preserves_an_inline_entry_comment() {
- let temp_dir = TempDir::new().unwrap();
- let config_path = temp_dir.path().join("config.toml");
-
- let initial_content = r#"[projects]
-"example.com/org/repo" = { worktree-path = "../{{ main_worktree }}.{{ branch }}" } # entry note
-
-[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();
-
- // The comment lands after the header's `]`, and the rewrite still parses.
- let saved_content = fs::read_to_string(&config_path).unwrap();
- toml::from_str::<toml::Table>(&saved_content).unwrap();
- assert_snapshot!(saved_content, @r#"
- [projects]
-
- [projects."example.com/org/repo"] # entry note
- worktree-path = "../{{ repo }}.{{ branch }}"
-
- [commit.generation]
- command = "llm -m claude-sonnet-4"
- "#);
-}
-
-/// A hook pipeline serializes in one spelling — one step as its lone table, more
-/// as an inline array — while the file may write `[[post-start]]` blocks (the
-/// documented form) or an inline array. An unrelated save must keep each
-/// pipeline in the file's spelling with its comments, changing only the steps
-/// the load rewrote (template migration renaming `repo_root`).
-#[test]
-fn test_saving_config_mutation_keeps_each_pipeline_spelling_and_its_comments() {
- let temp_dir = TempDir::new().unwrap();
- let config_path = temp_dir.path().join("config.toml");
-
- let initial_content = r#"worktree-path = "../x"
-
-# start the dev server
-post-start = [{ server = "cd {{ repo_root }} && npm run dev" }] # port 3000
-
-# announce the switch
-[[post-switch]]
-notify = "echo switched"
-
-# share the build cache, then install
-[[pre-start]]
-copy = "wt step copy-ignored"
-
-[[pre-start]]
-install = "cd {{ repo_root }} && pnpm install" # after the copy
-"#;
- 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::<toml::Table>(&saved_content).unwrap();
- assert_snapshot!(saved_content, @r#"
- worktree-path = "../x"
-
- # start the dev server
- post-start = [{ server = "cd {{ repo_path }} && npm run dev" }] # port 3000
-
- # announce the switch
- [[post-switch]]
- notify = "echo switched"
-
- # share the build cache, then install
- [[pre-start]]
- copy = "wt step copy-ignored"
-
- [[pre-start]]
- install = "cd {{ repo_path }} && pnpm install" # after the copy
-
- [commit.generation]
- command = "llm -m claude-sonnet-4"
- "#);
-}
diff --git a/tests/integration_tests/shell_integration_prompt.rs b/tests/integration_tests/shell_integration_prompt.rs
index 6f69a4f24..1dcbdf05a 100644
--- a/tests/integration_tests/shell_integration_prompt.rs
+++ b/tests/integration_tests/shell_integration_prompt.rs
@@ -10,7 +10,6 @@
use crate::common::{TestRepo, repo};
use rstest::rstest;
use std::fs;
-use worktrunk::config::UserConfig;
///
/// When WORKTRUNK_DIRECTIVE_CD_FILE is set (shell integration active), we should:
@@ -63,12 +62,11 @@ fn test_switch_with_active_shell_integration_no_prompt(repo: TestRepo) {
#[rstest]
fn test_switch_with_skip_prompt_flag(repo: TestRepo) {
// Set the skip flag in config
- let config_path = repo.test_config_path();
- let config = UserConfig {
- skip_shell_integration_prompt: true,
- ..Default::default()
- };
- config.save_to(config_path).unwrap();
+ std::fs::write(
+ repo.test_config_path(),
+ "skip-shell-integration-prompt = true\n",
+ )
+ .unwrap();
let output = repo
.wt_command()