Skip to content

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

refactor: consolidate config deprecation from two layers to one (#1879)

Maximilian Roosa569ddbfcee4
diff --git a/CLAUDE.md b/CLAUDE.md
index 46644c329..280a3b471 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -373,44 +373,34 @@ if worktree.is_dirty() {
## Config Deprecation
-Config deprecation has two layers, both required for a complete migration.
+All config deprecation is handled by a single layer: pre-deserialization TOML migration in `src/config/deprecation.rs`.
-### Layer 1: Pre-deserialization scanning (`src/config/deprecation.rs`)
+### How it works
-`check_and_migrate()` scans raw TOML text before serde parses it. It detects deprecated template variables, renamed sections, and removed fields, then generates a migration file (e.g., `config.deprecated.toml`) with upgrade instructions. Warnings are deduplicated per-process via `WARNED_DEPRECATED_PATHS`.
+`migrate_content()` is the structural TOML migration entry point before serde parses config, rewriting deprecated patterns into their canonical form. Load paths that only need migration call it directly; `check_and_migrate()` reuses the same migration path and returns the migrated TOML so callers don't reparse the file just to load it.
-To register a new deprecation at this layer:
+Separately, `check_and_migrate()` detects deprecated patterns, emits warnings, and generates a `.new` migration file (which additionally renames deprecated template variables and removes `approved-commands`). Warnings are deduplicated per-process via `WARNED_DEPRECATED_PATHS`.
-1. Add detection logic to `detect_deprecations()` and extend the `Deprecations` struct
-2. Add the migration instructions to `write_migration_file()`
-3. If it's a top-level section, add the key to `DEPRECATED_SECTION_KEYS` (this prevents `warn_unknown_fields` from also flagging it)
+### Adding a new deprecation
-### Layer 2: Post-deserialization normalization (`src/config/user/mod.rs`)
-
-After serde parses the config, `normalize_deprecated_sections()` moves deprecated values to their canonical locations. This runs on every load path (`load()`, `load_from_str()`, and `mutation.rs` reloads). Existing examples: `[commit-generation]` → `[commit.generation]`, `[select]` → `[switch.picker]`.
+1. Add a detection function and extend the `Deprecations` struct + `detect_deprecations()`
+2. Add a migration function (idempotent: no-op if pattern is absent or already migrated)
+3. Call the migration function from `migrate_content()`
+4. Add a warning message in `format_deprecation_warnings()`
+5. Update `Deprecations::is_empty()` to include the new field
+6. If it's a top-level section being removed from the struct, add the key to `DEPRECATED_SECTION_KEYS` (prevents `warn_unknown_fields` from also flagging it)
### Renaming a field within a section
-This is the most common case. Serde's `#[serde(deny_unknown_fields)]` is not used on config sections, so unrecognized fields inside a section like `[merge]` are silently ignored — they won't trigger `warn_unknown_fields`, which only checks top-level keys. The serde-level approach below is the only way to catch and migrate inner-section fields.
-
-Recipe for renaming `old-name` → `new-name` inside an existing section:
-
-1. **Keep the old field in the struct** so serde still deserializes it:
-
- ```rust
- /// **DEPRECATED**: Use `new-name` instead.
- #[serde(rename = "old-name", skip_serializing, default)]
- #[schemars(skip)]
- pub old_name: Option<bool>,
- ```
+Recipe for renaming `old-name` → `new-name` inside an existing section (e.g., `[merge]`):
- `skip_serializing` prevents writing the old name back. `schemars(skip)` hides it from the JSON schema.
+1. **Add a TOML-level migration function** (see `migrate_negated_bool_in_section` for the pattern). The function should rename the field in the TOML document, applying any transformation (e.g., boolean inversion).
-2. **Add a normalization method** on the section struct that transfers the old value to the new field, applying any inversion or transformation needed, and emits a deprecation warning via `warning_message()`.
+2. **Call it from `migrate_content()`** so all load paths get the fix.
-3. **Call it from `normalize_deprecated_sections()`** in `src/config/user/mod.rs`, alongside the existing normalizations.
+3. **Add detection** in `detect_deprecations()` and a warning in `format_deprecation_warnings()`.
-Do not silently drop old config keys — this causes silent behavior changes for users.
+The struct does not need the old field — migration happens before serde sees the TOML. Do not silently drop old config keys — this causes silent behavior changes for users.
## Adding CLI Commands
diff --git a/src/commands/config/mod.rs b/src/commands/config/mod.rs
index 7284839f7..50d5fb1ea 100644
--- a/src/commands/config/mod.rs
+++ b/src/commands/config/mod.rs
@@ -147,15 +147,13 @@ mod tests {
#[test]
fn test_warn_unknown_keys_suggests_other_config() {
- // commit-generation in project config should suggest user config
+ // skip-shell-integration-prompt in project config should suggest user config
let mut unknown = HashMap::new();
- let mut inner = toml::map::Map::new();
- inner.insert(
- "command".to_string(),
- toml::Value::String("claude".to_string()),
+ unknown.insert(
+ "skip-shell-integration-prompt".to_string(),
+ toml::Value::Boolean(true),
);
- unknown.insert("commit-generation".to_string(), toml::Value::Table(inner));
- assert_snapshot!(warn_unknown_keys::<ProjectConfig>(&unknown), @"▲ Key commit-generation belongs in user config (will be ignored)");
+ assert_snapshot!(warn_unknown_keys::<ProjectConfig>(&unknown), @"▲ Key skip-shell-integration-prompt belongs in user config (will be ignored)");
// ci in user config should suggest project config
let mut unknown = HashMap::new();
diff --git a/src/commands/config/show.rs b/src/commands/config/show.rs
index dc199da55..c594d3083 100644
--- a/src/commands/config/show.rs
+++ b/src/commands/config/show.rs
@@ -421,7 +421,7 @@ fn render_user_config(out: &mut String, has_system_config: bool) -> anyhow::Resu
// Check for deprecations with show_brief_warning=false (silent mode)
// User config is global, not tied to any repository
- let has_deprecations = if let Ok(Some(info)) = worktrunk::config::check_and_migrate(
+ let has_deprecations = if let Ok(result) = worktrunk::config::check_and_migrate(
&config_path,
&contents,
true,
@@ -429,9 +429,13 @@ fn render_user_config(out: &mut String, has_system_config: bool) -> anyhow::Resu
None,
false, // silent mode - we'll format the output ourselves
) {
- // Add deprecation details to the output buffer
- out.push_str(&worktrunk::config::format_deprecation_details(&info));
- true
+ if let Some(info) = result.info {
+ // Add deprecation details to the output buffer
+ out.push_str(&worktrunk::config::format_deprecation_details(&info));
+ true
+ } else {
+ false
+ }
} else {
false
};
@@ -563,7 +567,7 @@ fn render_project_config(out: &mut String) -> anyhow::Result<()> {
// Check for deprecations with show_brief_warning=false (silent mode)
// Only write migration file in main worktree, not linked worktrees
let is_main_worktree = !repo.current_worktree().is_linked().unwrap_or(true);
- let has_deprecations = if let Ok(Some(info)) = worktrunk::config::check_and_migrate(
+ let has_deprecations = if let Ok(result) = worktrunk::config::check_and_migrate(
&config_path,
&contents,
is_main_worktree,
@@ -571,9 +575,13 @@ fn render_project_config(out: &mut String) -> anyhow::Result<()> {
Some(&repo),
false, // silent mode - we'll format the output ourselves
) {
- // Add deprecation details to the output buffer
- out.push_str(&worktrunk::config::format_deprecation_details(&info));
- true
+ if let Some(info) = result.info {
+ // Add deprecation details to the output buffer
+ out.push_str(&worktrunk::config::format_deprecation_details(&info));
+ true
+ } else {
+ false
+ }
} else {
false
};
diff --git a/src/commands/config/update.rs b/src/commands/config/update.rs
index 595f37055..7ba82589f 100644
--- a/src/commands/config/update.rs
+++ b/src/commands/config/update.rs
@@ -122,7 +122,14 @@ fn check_user_config() -> anyhow::Result<Option<UpdateCandidate>> {
None, // no repo context for user config
false, // silent mode
)? {
- Some(info) if info.has_deprecations() => info,
+ result
+ if result
+ .info
+ .as_ref()
+ .is_some_and(DeprecationInfo::has_deprecations) =>
+ {
+ result.info.unwrap()
+ }
_ => return Ok(None),
};
@@ -165,7 +172,14 @@ fn check_project_config() -> anyhow::Result<Option<UpdateCandidate>> {
Some(&repo),
false, // silent mode
)? {
- Some(info) if info.has_deprecations() => info,
+ result
+ if result
+ .info
+ .as_ref()
+ .is_some_and(DeprecationInfo::has_deprecations) =>
+ {
+ result.info.unwrap()
+ }
_ => return Ok(None),
};
diff --git a/src/config/deprecation.rs b/src/config/deprecation.rs
index 27a8648aa..042941ed0 100644
--- a/src/config/deprecation.rs
+++ b/src/config/deprecation.rs
@@ -210,6 +210,10 @@ pub struct Deprecations {
pub post_create: bool,
/// Has `[ci]` section (moved to `[forge]`)
pub ci_section: bool,
+ /// Has `no-ff` in `[merge]` section (use `ff` instead)
+ pub no_ff: bool,
+ /// Has `no-cd` in `[switch]` section (use `cd` instead)
+ pub no_cd: bool,
}
impl Deprecations {
@@ -221,6 +225,8 @@ impl Deprecations {
&& !self.select
&& !self.post_create
&& !self.ci_section
+ && !self.no_ff
+ && !self.no_cd
}
}
@@ -251,6 +257,8 @@ fn detect_deprecations_from_doc(
select: find_select_from_doc(doc),
post_create: find_post_create_from_doc(doc),
ci_section: find_ci_section_from_doc(doc),
+ no_ff: find_negated_bool_from_doc(doc, "merge", "no-ff", "ff"),
+ no_cd: find_negated_bool_from_doc(doc, "switch", "no-cd", "cd"),
}
}
@@ -472,8 +480,27 @@ fn remove_approved_commands_doc(doc: &mut toml_edit::DocumentMut) -> bool {
}
fn find_select_from_doc(doc: &toml_edit::DocumentMut) -> bool {
- // Check if new [switch.picker] already exists
- let has_new_section = doc
+ if has_select_without_picker(doc) {
+ return true;
+ }
+
+ // Check project-level sections
+ if let Some(projects) = doc.get("projects").and_then(|p| p.as_table()) {
+ for (_key, project_value) in projects.iter() {
+ if let Some(project_table) = project_value.as_table()
+ && has_select_without_picker(project_table)
+ {
+ return true;
+ }
+ }
+ }
+
+ false
+}
+
+/// Check if a table has a non-empty `select` section without `switch.picker`.
+fn has_select_without_picker(table: &toml_edit::Table) -> bool {
+ let has_new_section = table
.get("switch")
.and_then(|s| s.as_table())
.and_then(|t| t.get("picker"))
@@ -483,13 +510,12 @@ fn find_select_from_doc(doc: &toml_edit::DocumentMut) -> bool {
return false;
}
- // Check if [select] exists and is non-empty
- if let Some(section) = doc.get("select") {
- if let Some(table) = section.as_table() {
- return !table.is_empty();
+ if let Some(section) = table.get("select") {
+ if let Some(t) = section.as_table() {
+ return !t.is_empty();
}
- if let Some(inline) = section.as_inline_table() {
- return !inline.is_empty();
+ if let Some(t) = section.as_inline_table() {
+ return !t.is_empty();
}
}
@@ -577,25 +603,42 @@ fn migrate_post_create_doc(doc: &mut toml_edit::DocumentMut) -> bool {
modified
}
-/// Migrate `[select]` section to `[switch.picker]`.
+/// Migrate `[select]` sections to `[switch.picker]`.
///
-/// Renames `[select]` to `[switch.picker]`, preserving all fields.
-/// Skips migration if `[switch.picker]` already exists.
+/// Handles both top-level and project-level `[projects."...".select]` sections.
+/// Skips each migration if `[switch.picker]` already exists at that level.
fn migrate_select_doc(doc: &mut toml_edit::DocumentMut) -> bool {
- // Check if [switch.picker] already exists
- let has_new_section = doc
+ let mut modified = false;
+
+ // Migrate top-level [select] → [switch.picker]
+ migrate_select_table(doc.as_table_mut(), &mut modified);
+
+ // Migrate project-level [projects."...".select] → [projects."...".switch.picker]
+ if let Some(projects) = doc.get_mut("projects").and_then(|p| p.as_table_mut()) {
+ for (_key, project_value) in projects.iter_mut() {
+ if let Some(project_table) = project_value.as_table_mut() {
+ migrate_select_table(project_table, &mut modified);
+ }
+ }
+ }
+
+ modified
+}
+
+/// Migrate a `select` key to `switch.picker` within a table.
+fn migrate_select_table(table: &mut toml_edit::Table, modified: &mut bool) {
+ let has_new_section = table
.get("switch")
.and_then(|s| s.as_table())
.and_then(|t| t.get("picker"))
.is_some_and(|p| p.is_table() || p.is_inline_table());
if has_new_section {
- return false;
+ return;
}
- // Remove [select] and migrate to [switch.picker]
- let Some(old_section) = doc.remove("select") else {
- return false;
+ let Some(old_section) = table.remove("select") else {
+ return;
};
let table_opt = match old_section {
@@ -604,23 +647,21 @@ fn migrate_select_doc(doc: &mut toml_edit::DocumentMut) -> bool {
_ => None,
};
- let Some(table) = table_opt else {
- return false;
+ let Some(select_table) = table_opt else {
+ return;
};
- // Ensure [switch] section exists (implicit so only [switch.picker] renders)
- if !doc.contains_key("switch") {
+ if !table.contains_key("switch") {
let mut switch_table = toml_edit::Table::new();
switch_table.set_implicit(true);
- doc.insert("switch", toml_edit::Item::Table(switch_table));
+ table.insert("switch", toml_edit::Item::Table(switch_table));
}
- // Move to [switch.picker]
- if let Some(switch_table) = doc["switch"].as_table_mut() {
- switch_table.insert("picker", toml_edit::Item::Table(table));
+ if let Some(switch_table) = table["switch"].as_table_mut() {
+ switch_table.insert("picker", toml_edit::Item::Table(select_table));
}
- true
+ *modified = true;
}
fn find_ci_section_from_doc(doc: &toml_edit::DocumentMut) -> bool {
@@ -676,6 +717,134 @@ fn migrate_ci_doc(doc: &mut toml_edit::DocumentMut) -> bool {
true
}
+/// Check if a section has a deprecated negated boolean field (e.g., `no-ff` without `ff`).
+///
+/// Checks both the top-level section and project-level sections.
+fn find_negated_bool_from_doc(
+ doc: &toml_edit::DocumentMut,
+ section: &str,
+ old_key: &str,
+ new_key: &str,
+) -> bool {
+ // Check top-level section
+ if let Some(table) = doc.get(section).and_then(|s| s.as_table())
+ && !table.contains_key(new_key)
+ && table.contains_key(old_key)
+ {
+ return true;
+ }
+
+ // Check project-level sections
+ if let Some(projects) = doc.get("projects").and_then(|p| p.as_table()) {
+ for (_key, project_value) in projects.iter() {
+ if let Some(table) = project_value
+ .as_table()
+ .and_then(|t| t.get(section))
+ .and_then(|s| s.as_table())
+ && !table.contains_key(new_key)
+ && table.contains_key(old_key)
+ {
+ return true;
+ }
+ }
+ }
+
+ false
+}
+
+/// Migrate a negated boolean field within a table (e.g., `no-ff = true` → `ff = false`).
+///
+/// Returns true if a migration was performed.
+fn migrate_negated_bool(table: &mut toml_edit::Table, old_key: &str, new_key: &str) -> bool {
+ if table.contains_key(new_key) {
+ // New key takes precedence; remove the old one if present
+ return table.remove(old_key).is_some();
+ }
+ let Some(old_item) = table.remove(old_key) else {
+ return false;
+ };
+ if let Some(bool_val) = old_item.as_value().and_then(|v| v.as_bool()) {
+ table.insert(new_key, toml_edit::value(!bool_val));
+ true
+ } else {
+ // Put it back if we can't parse it
+ table.insert(old_key, old_item);
+ false
+ }
+}
+
+/// Migrate a negated boolean field in a section and its project-level counterparts.
+fn migrate_negated_bool_doc(
+ doc: &mut toml_edit::DocumentMut,
+ section: &str,
+ old_key: &str,
+ new_key: &str,
+) -> bool {
+ let mut modified = false;
+
+ // Top-level section
+ if let Some(table) = doc.get_mut(section).and_then(|s| s.as_table_mut())
+ && migrate_negated_bool(table, old_key, new_key)
+ {
+ modified = true;
+ }
+
+ // Project-level sections
+ if let Some(projects) = doc.get_mut("projects").and_then(|p| p.as_table_mut()) {
+ for (_key, project_value) in projects.iter_mut() {
+ if let Some(table) = project_value
+ .as_table_mut()
+ .and_then(|t| t.get_mut(section))
+ .and_then(|s| s.as_table_mut())
+ && migrate_negated_bool(table, old_key, new_key)
+ {
+ modified = true;
+ }
+ }
+ }
+
+ modified
+}
+
+/// Apply all structural TOML migrations to a parsed document.
+///
+/// This is the single source of truth for config migration. Returns true if
+/// any modifications were made.
+///
+/// Note: `replace_deprecated_vars` and `remove_approved_commands` are NOT
+/// included here — template variable renaming is cosmetic (would break
+/// `--var` overrides), and approved-commands is still a valid serde field.
+fn migrate_content_doc(doc: &mut toml_edit::DocumentMut) -> bool {
+ let mut modified = false;
+ modified |= migrate_commit_generation_doc(doc);
+ modified |= migrate_select_doc(doc);
+ modified |= migrate_post_create_doc(doc);
+ modified |= migrate_ci_doc(doc);
+ modified |= migrate_negated_bool_doc(doc, "merge", "no-ff", "ff");
+ modified |= migrate_negated_bool_doc(doc, "switch", "no-cd", "cd");
+ modified
+}
+
+fn migrate_content_from_doc(content: &str, mut doc: toml_edit::DocumentMut) -> String {
+ if migrate_content_doc(&mut doc) {
+ doc.to_string()
+ } else {
+ content.to_string()
+ }
+}
+
+/// Apply all TOML-level migrations to config content.
+///
+/// Parses the TOML, applies all structural migrations, and returns the result.
+/// Called by load paths that only need structural migration. `check_and_migrate()`
+/// reuses the same migration path when it also needs warnings or `.new` files.
+pub fn migrate_content(content: &str) -> String {
+ let Ok(doc) = content.parse::<toml_edit::DocumentMut>() else {
+ return content.to_string();
+ };
+ migrate_content_from_doc(content, doc)
+}
+
/// Copy approved-commands from config.toml to approvals.toml.
///
/// Called during migration to ensure approved-commands are preserved before
@@ -775,6 +944,16 @@ impl DeprecationInfo {
}
}
+/// Result of checking config content for deprecations.
+///
+/// `migrated_content` is the structurally migrated TOML used for serde loading.
+/// `info` is present only when user-visible deprecations were detected.
+#[derive(Debug)]
+pub struct CheckAndMigrateResult {
+ pub info: Option<DeprecationInfo>,
+ pub migrated_content: String,
+}
+
fn migration_path(path: &Path) -> PathBuf {
// config.toml -> config.toml.new
// config -> config.new
@@ -810,7 +989,8 @@ fn migration_path(path: &Path) -> PathBuf {
///
/// Warnings are deduplicated per path per process.
///
-/// Returns `Ok(Some(info))` if deprecations were found, `Ok(None)` otherwise.
+/// Returns the structurally migrated content for serde loading, plus optional
+/// deprecation info when user-visible deprecations were found.
pub fn check_and_migrate(
path: &Path,
content: &str,
@@ -818,13 +998,18 @@ pub fn check_and_migrate(
label: &str,
repo: Option<&crate::git::Repository>,
show_brief_warning: bool,
-) -> anyhow::Result<Option<DeprecationInfo>> {
+) -> anyhow::Result<CheckAndMigrateResult> {
// Parse once — shared by detection and migration
- let Ok(doc) = content.parse::<toml_edit::DocumentMut>() else {
- return Ok(None);
- };
- let template_strings = extract_template_strings_from_doc(&doc);
- let deprecations = detect_deprecations_from_doc(&doc, &template_strings);
+ let (deprecations, migrated_content, template_strings) =
+ match content.parse::<toml_edit::DocumentMut>() {
+ Ok(doc) => {
+ let template_strings = extract_template_strings_from_doc(&doc);
+ let deprecations = detect_deprecations_from_doc(&doc, &template_strings);
+ let migrated_content = migrate_content_from_doc(content, doc);
+ (deprecations, migrated_content, template_strings)
+ }
+ Err(_) => (Deprecations::default(), content.to_string(), vec![]),
+ };
if deprecations.is_empty() {
// Config is clean - clear hint so future deprecations get full treatment.
@@ -835,7 +1020,10 @@ pub fn check_and_migrate(
if let Some(repo) = repo {
let _ = repo.clear_hint(HINT_DEPRECATED_CONFIG);
}
- return Ok(None);
+ return Ok(CheckAndMigrateResult {
+ info: None,
+ migrated_content,
+ });
}
let new_path = migration_path(path);
@@ -863,7 +1051,10 @@ pub fn check_and_migrate(
// Skip warning entirely if not in main worktree (for project config)
if !warn_and_migrate {
- return Ok(Some(info));
+ return Ok(CheckAndMigrateResult {
+ info: Some(info),
+ migrated_content,
+ });
}
// Deduplicate warnings per path per process
@@ -875,7 +1066,10 @@ pub fn check_and_migrate(
if new_path.exists() {
info.migration_path = Some(new_path);
}
- return Ok(Some(info));
+ return Ok(CheckAndMigrateResult {
+ info: Some(info),
+ migrated_content,
+ });
}
guard.insert(canonical_path.clone());
}
@@ -912,7 +1106,10 @@ pub fn check_and_migrate(
}
std::io::stderr().flush().ok();
- return Ok(Some(info));
+ return Ok(CheckAndMigrateResult {
+ info: Some(info),
+ migrated_content,
+ });
}
// Silent mode for `wt config show` - just write migration file and return info
@@ -922,7 +1119,10 @@ pub fn check_and_migrate(
write_migration_file(path, content, &info.deprecations, repo, &template_strings);
}
- Ok(Some(info))
+ Ok(CheckAndMigrateResult {
+ info: Some(info),
+ migrated_content,
+ })
}
/// Format brief warning for normal config loading.
@@ -959,7 +1159,7 @@ pub fn write_migration_file(
) -> Option<PathBuf> {
let new_path = migration_path(path);
- // Apply string-level var replacement first (operates on raw content)
+ // Apply string-level var replacement first (cosmetic, operates on raw content)
let new_content = if !deprecations.vars.is_empty() {
replace_deprecated_vars_from_strings(content, template_strings)
} else {
@@ -969,22 +1169,12 @@ pub fn write_migration_file(
// Parse once for all structural migrations
let new_content = match new_content.parse::<toml_edit::DocumentMut>() {
Ok(mut doc) => {
- let mut modified = false;
- if !deprecations.commit_gen.is_empty() {
- modified |= migrate_commit_generation_doc(&mut doc);
- }
+ let mut modified = migrate_content_doc(&mut doc);
+ // Additionally remove approved-commands for the .new file (not part of
+ // migrate_content because approved-commands is still a valid serde field)
if deprecations.approved_commands {
modified |= remove_approved_commands_doc(&mut doc);
}
- if deprecations.select {
- modified |= migrate_select_doc(&mut doc);
- }
- if deprecations.post_create {
- modified |= migrate_post_create_doc(&mut doc);
- }
- if deprecations.ci_section {
- modified |= migrate_ci_doc(&mut doc);
- }
if modified {
doc.to_string()
} else {
@@ -1134,6 +1324,28 @@ pub fn format_deprecation_warnings(info: &DeprecationInfo) -> String {
);
}
+ if info.deprecations.no_ff {
+ let _ = writeln!(
+ out,
+ "{}",
+ warning_message(format!(
+ "{} uses deprecated field: [merge] no-ff → ff (inverted)",
+ info.label
+ ))
+ );
+ }
+
+ if info.deprecations.no_cd {
+ let _ = writeln!(
+ out,
+ "{}",
+ warning_message(format!(
+ "{} uses deprecated field: [switch] no-cd → cd (inverted)",
+ info.label
+ ))
+ );
+ }
+
out
}
@@ -1171,8 +1383,8 @@ pub fn format_deprecation_details(info: &DeprecationInfo) -> String {
/// Generic over `C`, the config type where the key was found. If the key would
/// be valid in `C::Other`, returns that config's description.
///
-/// For example, `key_belongs_in::<ProjectConfig>("commit-generation")` returns
-/// `Some("user config")`.
+/// For example, `key_belongs_in::<ProjectConfig>("skip-shell-integration-prompt")`
+/// returns `Some("user config")`.
/// Returns `None` if the key is truly unknown (not valid in either config).
pub fn key_belongs_in<C: WorktrunkConfig>(key: &str) -> Option<&'static str> {
C::Other::is_valid_key(key).then(C::Other::description)
@@ -1626,7 +1838,7 @@ approved-commands = [
let result =
check_and_migrate(non_existent_path, content, true, "Test config", None, false);
assert!(result.is_ok());
- assert!(result.unwrap().is_some());
+ assert!(result.unwrap().info.is_some());
}
#[test]
@@ -1639,12 +1851,33 @@ approved-commands = [
// First call should process normally
let result1 = check_and_migrate(unique_path, content, true, "Test config", None, false);
assert!(result1.is_ok());
- assert!(result1.unwrap().is_some());
+ assert!(result1.unwrap().info.is_some());
// Second call with same path should early-return (hits the deduplication branch)
let result2 = check_and_migrate(unique_path, content, true, "Test config", None, false);
assert!(result2.is_ok());
- assert!(result2.unwrap().is_some());
+ assert!(result2.unwrap().info.is_some());
+ }
+
+ #[test]
+ fn test_check_and_migrate_returns_migrated_content() {
+ let content = r#"
+[select]
+pager = "delta"
+"#;
+
+ let result = check_and_migrate(
+ std::path::Path::new("/tmp/config.toml"),
+ content,
+ true,
+ "Test config",
+ None,
+ false,
+ )
+ .unwrap();
+
+ assert_eq!(result.migrated_content, migrate_content(content));
+ assert!(result.info.is_some());
}
#[test]
@@ -2278,6 +2511,8 @@ approved-commands = ["npm install"]
select: false,
post_create: false,
ci_section: false,
+ no_ff: false,
+ no_cd: false,
},
label: "User config".to_string(),
main_worktree_path: None,
@@ -2308,6 +2543,8 @@ approved-commands = ["npm install"]
select: false,
post_create: false,
ci_section: false,
+ no_ff: false,
+ no_cd: false,
},
label: "User config".to_string(),
main_worktree_path: None,
@@ -2339,6 +2576,8 @@ approved-commands = ["npm install"]
select: false,
post_create: false,
ci_section: false,
+ no_ff: false,
+ no_cd: false,
};
let result = write_migration_file(&config_path, content, &deprecations, None, &[]);
assert!(
@@ -2599,6 +2838,8 @@ branches = true
select: true,
post_create: false,
ci_section: false,
+ no_ff: false,
+ no_cd: false,
},
label: "User config".to_string(),
main_worktree_path: None,
@@ -2633,6 +2874,8 @@ pager = "delta --paging=never"
select: true,
post_create: false,
ci_section: false,
+ no_ff: false,
+ no_cd: false,
};
let result = write_migration_file(&config_path, content, &deprecations, None, &[]);
assert!(result.is_some(), "Should write migration file for select");
@@ -2881,6 +3124,8 @@ server = "npm run dev"
select: false,
post_create: true,
ci_section: false,
+ no_ff: false,
+ no_cd: false,
},
label: "Project config".to_string(),
main_worktree_path: None,
@@ -2915,6 +3160,8 @@ server = "npm run dev"
select: false,
post_create: true,
ci_section: false,
+ no_ff: false,
+ no_cd: false,
};
let result = write_migration_file(&config_path, content, &deprecations, None, &[]);
assert!(
@@ -2932,4 +3179,179 @@ server = "npm run dev"
"Migrated content should not have post-create: {migrated}"
);
}
+
+ // ==================== negated bool format + migration tests ====================
+
+ #[test]
+ fn test_format_deprecation_warnings_no_ff_and_no_cd() {
+ let info = DeprecationInfo {
+ config_path: std::path::PathBuf::from("/tmp/test-config.toml"),
+ migration_path: None,
+ deprecations: Deprecations {
+ vars: vec![],
+ commit_gen: CommitGenerationDeprecations::default(),
+ approved_commands: false,
+ select: false,
+ post_create: false,
+ ci_section: false,
+ no_ff: true,
+ no_cd: true,
+ },
+ label: "User config".to_string(),
+ main_worktree_path: None,
+ approvals_copied_to: None,
+ };
+ let output = format_deprecation_warnings(&info);
+ assert!(output.contains("no-ff"), "Should mention no-ff: {output}");
+ assert!(output.contains("no-cd"), "Should mention no-cd: {output}");
+ }
+
+ #[test]
+ fn test_detect_no_ff_deprecation() {
+ let deprecations = detect_deprecations("[merge]\nno-ff = true\n");
+ assert!(deprecations.no_ff);
+ }
+
+ #[test]
+ fn test_detect_no_ff_not_flagged_when_ff_exists() {
+ let deprecations = detect_deprecations("[merge]\nff = true\nno-ff = true\n");
+ assert!(!deprecations.no_ff);
+ }
+
+ #[test]
+ fn test_detect_no_cd_deprecation() {
+ let deprecations = detect_deprecations("[switch]\nno-cd = true\n");
+ assert!(deprecations.no_cd);
+ }
+
+ #[test]
+ fn test_detect_no_ff_project_level() {
+ let content = r#"
+[projects."github.com/user/repo".merge]
+no-ff = true
+"#;
+ let deprecations = detect_deprecations(content);
+ assert!(deprecations.no_ff);
+ }
+
+ #[test]
+ fn test_migrate_no_ff_to_ff() {
+ let content = "[merge]\nno-ff = true\n";
+ let result = migrate_content(content);
+ assert!(result.contains("ff = false"), "Should invert: {result}");
+ assert!(!result.contains("no-ff"), "Should remove no-ff: {result}");
+ }
+
+ #[test]
+ fn test_migrate_no_cd_to_cd() {
+ let content = "[switch]\nno-cd = false\n";
+ let result = migrate_content(content);
+ assert!(result.contains("cd = true"), "Should invert: {result}");
+ assert!(!result.contains("no-cd"), "Should remove no-cd: {result}");
+ }
+
+ #[test]
+ fn test_migrate_no_ff_project_level() {
+ let content = r#"
+[projects."github.com/user/repo".merge]
+no-ff = true
+"#;
+ let result = migrate_content(content);
+ assert!(result.contains("ff = false"), "Should migrate: {result}");
+ assert!(!result.contains("no-ff"), "Should remove no-ff: {result}");
+ }
+
+ #[test]
+ fn test_migrate_negated_bool_non_boolean_value_preserved() {
+ // Non-boolean `no-ff` value should be left alone
+ let content = "[merge]\nno-ff = \"not-a-bool\"\n";
+ let result = migrate_content(content);
+ assert!(
+ result.contains("no-ff"),
+ "Non-boolean value should be preserved: {result}"
+ );
+ }
+
+ #[test]
+ fn test_migrate_no_ff_skips_when_ff_exists() {
+ let content = "[merge]\nff = true\nno-ff = true\n";
+ let result = migrate_content(content);
+ assert!(result.contains("ff = true"), "ff should be kept: {result}");
+ assert!(
+ !result.contains("no-ff"),
+ "no-ff should be removed: {result}"
+ );
+ }
+
+ // ==================== project-level select migration tests ====================
+
+ #[test]
+ fn test_detect_select_project_level() {
+ let content = r#"
+[projects."github.com/user/repo".select]
+pager = "bat"
+"#;
+ let deprecations = detect_deprecations(content);
+ assert!(deprecations.select);
+ }
+
+ #[test]
+ fn test_migrate_select_project_level() {
+ let content = r#"
+[projects."github.com/user/repo".select]
+pager = "bat"
+"#;
+ let result = migrate_content(content);
+ assert!(
+ result.contains("[projects.\"github.com/user/repo\".switch.picker]"),
+ "Should migrate project select: {result}"
+ );
+ assert!(
+ !result.contains("[projects.\"github.com/user/repo\".select]"),
+ "Should remove project select: {result}"
+ );
+ }
+
+ // ==================== migrate_content tests ====================
+
+ #[test]
+ fn test_migrate_content_applies_all_structural_migrations() {
+ let content = r#"
+[commit-generation]
+command = "llm"
+
+[select]
+pager = "delta"
+
+[merge]
+no-ff = true
+
+[switch]
+no-cd = true
+"#;
+ let result = migrate_content(content);
+ assert!(
+ result.contains("[commit.generation]"),
+ "commit-generation: {result}"
+ );
+ assert!(
+ result.contains("[switch.picker]"),
+ "select to switch.picker: {result}"
+ );
+ assert!(result.contains("ff = false"), "no-ff to ff: {result}");
+ assert!(result.contains("cd = false"), "no-cd to cd: {result}");
+ }
+
+ #[test]
+ fn test_migrate_content_is_no_op_for_canonical_config() {
+ let content = r#"
+[commit.generation]
+command = "llm"
+
+[merge]
+ff = true
+"#;
+ let result = migrate_content(content);
+ assert_eq!(result, content);
+ }
}
diff --git a/src/config/mod.rs b/src/config/mod.rs
index 86809eec7..7d4d4b031 100644
--- a/src/config/mod.rs
+++ b/src/config/mod.rs
@@ -15,7 +15,7 @@
pub mod approvals;
mod commands;
-mod deprecation;
+pub(crate) mod deprecation;
mod expansion;
mod hooks;
mod project;
@@ -73,6 +73,7 @@ impl WorktrunkConfig for ProjectConfig {
// Re-export public types
pub use approvals::{Approvals, approvals_path};
pub use commands::{Command, CommandConfig, HookStep, append_aliases};
+pub use deprecation::CheckAndMigrateResult;
pub use deprecation::DeprecationInfo;
pub use deprecation::Deprecations;
pub use deprecation::check_and_migrate;
@@ -81,6 +82,7 @@ pub use deprecation::format_brief_warning;
pub use deprecation::format_deprecation_details;
pub use deprecation::format_deprecation_warnings;
pub use deprecation::format_migration_diff;
+pub use deprecation::migrate_content;
pub use deprecation::normalize_template_vars;
pub use deprecation::write_migration_file;
pub use deprecation::{DEPRECATED_SECTION_KEYS, key_belongs_in, warn_unknown_fields};
@@ -96,10 +98,10 @@ pub use project::{
};
pub use user::{
CommitConfig, CommitGenerationConfig, CopyIgnoredConfig, ListConfig, MergeConfig,
- OverridableConfig, ResolvedConfig, SelectConfig, StageMode, StepConfig, SwitchConfig,
- SwitchPickerConfig, UserConfig, UserProjectOverrides, config_path, default_config_path,
- default_system_config_path, find_unknown_keys as find_unknown_user_keys, set_config_path,
- system_config_path, valid_user_config_keys,
+ OverridableConfig, ResolvedConfig, StageMode, StepConfig, SwitchConfig, SwitchPickerConfig,
+ UserConfig, UserProjectOverrides, config_path, default_config_path, default_system_config_path,
+ find_unknown_keys as find_unknown_user_keys, set_config_path, system_config_path,
+ valid_user_config_keys,
};
#[cfg(test)]
@@ -162,8 +164,6 @@ mod tests {
config.worktree_path(),
"{{ repo_path }}/../{{ repo }}.{{ branch | sanitize }}"
);
- // commit_generation is None by default
- assert!(config.commit_generation.is_none());
assert!(config.projects.is_empty());
}
@@ -662,7 +662,7 @@ squash-template-file = "~/file.txt"
#[test]
fn test_find_unknown_user_keys_valid() {
- let toml_str = "worktree-path = \"../test\"\n\n[commit-generation]\ncommand = \"llm\"\n\n[list]\nfull = true";
+ let toml_str = "worktree-path = \"../test\"\n\n[commit.generation]\ncommand = \"llm\"\n\n[list]\nfull = true";
let unknown = find_unknown_user_keys(toml_str);
assert!(unknown.is_empty());
}
@@ -750,22 +750,19 @@ test = "cargo test"
#[test]
fn test_user_config_key_in_project_config_is_detected() {
- // commit-generation is a user-config-only key
- let toml_str = r#"
-[commit-generation]
-command = "claude"
-"#;
+ // skip-shell-integration-prompt is a user-config-only key
+ let toml_str = "skip-shell-integration-prompt = true\n";
let unknown = find_unknown_project_keys(toml_str);
assert!(
- unknown.contains_key("commit-generation"),
- "commit-generation should be unknown in project config"
+ unknown.contains_key("skip-shell-integration-prompt"),
+ "skip-shell-integration-prompt should be unknown in project config"
);
// Verify it's valid in user config
let unknown_in_user = find_unknown_user_keys(toml_str);
assert!(
unknown_in_user.is_empty(),
- "commit-generation should be valid in user config"
+ "skip-shell-integration-prompt should be valid in user config"
);
}
diff --git a/src/config/user/accessors.rs b/src/config/user/accessors.rs
index 127f34b91..a35899a86 100644
--- a/src/config/user/accessors.rs
+++ b/src/config/user/accessors.rs
@@ -12,8 +12,8 @@ use crate::config::expansion::expand_template;
use super::UserConfig;
use super::merge::{Merge, merge_optional};
use super::sections::{
- CommitConfig, CommitGenerationConfig, CopyIgnoredConfig, ListConfig, MergeConfig, SelectConfig,
- StepConfig, SwitchConfig, SwitchPickerConfig,
+ CommitConfig, CommitGenerationConfig, CopyIgnoredConfig, ListConfig, MergeConfig, StepConfig,
+ SwitchConfig, SwitchPickerConfig,
};
/// Default worktree path template
@@ -143,16 +143,6 @@ impl UserConfig {
.unwrap_or_default()
}
- /// Returns the select config for a specific project (deprecated path).
- ///
- /// Merges project-specific settings with global settings, where project
- /// settings take precedence for fields that are set.
- pub fn select(&self, project: Option<&str>) -> Option<SelectConfig> {
- self.merged_project_config(project, self.configs.select.as_ref(), |config| {
- config.overrides.select.as_ref()
- })
- }
-
/// Returns the switch picker config for a specific project.
///
/// Merges project-specific settings with global settings, where project
diff --git a/src/config/user/mod.rs b/src/config/user/mod.rs
index 638db4e90..540385c33 100644
--- a/src/config/user/mod.rs
+++ b/src/config/user/mod.rs
@@ -27,7 +27,7 @@ pub use resolved::ResolvedConfig;
pub use schema::{find_unknown_keys, valid_user_config_keys};
pub use sections::{
CommitConfig, CommitGenerationConfig, CopyIgnoredConfig, ListConfig, MergeConfig,
- OverridableConfig, SelectConfig, StageMode, StepConfig, SwitchConfig, SwitchPickerConfig,
+ OverridableConfig, StageMode, StepConfig, SwitchConfig, SwitchPickerConfig,
UserProjectOverrides,
};
@@ -72,23 +72,12 @@ pub use sections::{
/// `__` separator for nested fields (e.g., `WORKTRUNK_COMMIT__GENERATION__COMMAND`).
#[derive(Debug, Default, Serialize, Deserialize, JsonSchema)]
pub struct UserConfig {
- /// **DEPRECATED**: Use `[commit.generation]` instead.
- ///
- /// This field is kept for backward compatibility. When both are set,
- /// `commit.generation` takes precedence.
- #[serde(
- default,
- rename = "commit-generation",
- skip_serializing_if = "Option::is_none"
- )]
- pub commit_generation: Option<CommitGenerationConfig>,
-
/// Per-project configuration (approved commands, etc.)
/// Uses BTreeMap for deterministic serialization order and better diff readability
#[serde(default)]
pub projects: std::collections::BTreeMap<String, UserProjectOverrides>,
- /// Settings that can be overridden per-project (worktree-path, list, commit, merge, switch, step, select, hooks)
+ /// Settings that can be overridden per-project (worktree-path, list, commit, merge, switch, step, hooks)
#[serde(flatten, default)]
pub configs: OverridableConfig,
@@ -110,76 +99,6 @@ pub struct UserConfig {
}
impl UserConfig {
- fn normalize_deprecated_sections(&mut self) {
- Self::normalize_commit_generation_section(
- &mut self.commit_generation,
- &mut self.configs.commit,
- );
- Self::normalize_select_section(&mut self.configs.select, &mut self.configs.switch);
- if let Some(merge) = &mut self.configs.merge {
- merge.normalize_deprecated_fields();
- }
- if let Some(switch) = &mut self.configs.switch {
- switch.normalize_deprecated_fields();
- }
-
- for project in self.projects.values_mut() {
- Self::normalize_commit_generation_section(
- &mut project.commit_generation,
- &mut project.overrides.commit,
- );
- Self::normalize_select_section(
- &mut project.overrides.select,
- &mut project.overrides.switch,
- );
- if let Some(merge) = &mut project.overrides.merge {
- merge.normalize_deprecated_fields();
- }
- if let Some(switch) = &mut project.overrides.switch {
- switch.normalize_deprecated_fields();
- }
- }
- }
-
- fn normalize_commit_generation_section(
- deprecated: &mut Option<CommitGenerationConfig>,
- commit: &mut Option<CommitConfig>,
- ) {
- let Some(deprecated_config) = deprecated.take() else {
- return;
- };
-
- if deprecated_config == CommitGenerationConfig::default() {
- return;
- }
-
- let commit_config = commit.get_or_insert_with(CommitConfig::default);
- if commit_config.generation.is_none() {
- commit_config.generation = Some(deprecated_config);
- }
- }
-
- fn normalize_select_section(
- deprecated: &mut Option<SelectConfig>,
- switch: &mut Option<SwitchConfig>,
- ) {
- let Some(select_config) = deprecated.take() else {
- return;
- };
-
- if select_config == SelectConfig::default() {
- return;
- }
-
- let switch_config = switch.get_or_insert_with(SwitchConfig::default);
- if switch_config.picker.is_none() {
- switch_config.picker = Some(SwitchPickerConfig {
- pager: select_config.pager,
- timeout_ms: None,
- });
- }
- }
-
/// Load configuration from system config, user config, and environment variables.
///
/// Configuration is loaded in the following order (later sources override earlier ones):
@@ -194,22 +113,23 @@ impl UserConfig {
let mut builder = Config::builder();
// Add system config if it exists (lowest priority file source)
- if let Some(system_path) = path::system_config_path() {
- if let Ok(content) = std::fs::read_to_string(&system_path) {
- // Warn about unknown fields in system config
- let unknown_keys: std::collections::HashMap<_, _> = find_unknown_keys(&content)
- .into_iter()
- .filter(|(k, _)| {
- !super::deprecation::DEPRECATED_SECTION_KEYS.contains(&k.as_str())
- })
- .collect();
- super::deprecation::warn_unknown_fields::<UserConfig>(
- &system_path,
- &unknown_keys,
- "System config",
- );
- }
- builder = builder.add_source(File::from(system_path));
+ if let Some(system_path) = path::system_config_path()
+ && let Ok(content) = std::fs::read_to_string(&system_path)
+ {
+ // Warn about unknown fields in system config
+ let unknown_keys: std::collections::HashMap<_, _> = find_unknown_keys(&content)
+ .into_iter()
+ .filter(|(k, _)| !super::deprecation::DEPRECATED_SECTION_KEYS.contains(&k.as_str()))
+ .collect();
+ super::deprecation::warn_unknown_fields::<UserConfig>(
+ &system_path,
+ &unknown_keys,
+ "System config",
+ );
+
+ // Feed migrated content to serde so deprecated patterns parse correctly
+ let migrated = super::deprecation::migrate_content(&content);
+ builder = builder.add_source(File::from_str(&migrated, config::FileFormat::Toml));
}
// Add user config file if it exists (overrides system config)
@@ -222,14 +142,16 @@ impl UserConfig {
// Use show_brief_warning=true to emit a brief pointer to `wt config show`
// Warning is deduplicated per-process via WARNED_DEPRECATED_PATHS.
if let Ok(content) = std::fs::read_to_string(config_path) {
- let _ = super::deprecation::check_and_migrate(
+ let migrated = super::deprecation::check_and_migrate(
config_path,
&content,
true,
"User config",
None,
true, // show_brief_warning
- );
+ )
+ .map(|result| result.migrated_content)
+ .unwrap_or_else(|_| super::deprecation::migrate_content(&content));
// Warn about unknown fields in the config file
// (must check file content directly, not config.unknown, because
@@ -245,9 +167,11 @@ impl UserConfig {
&unknown_keys,
"User config",
);
- }
- builder = builder.add_source(File::from(config_path.clone()));
+ // Feed migrated content from check_and_migrate to serde so deprecated
+ // patterns parse correctly without reparsing the TOML here.
+ builder = builder.add_source(File::from_str(&migrated, config::FileFormat::Toml));
+ }
} else if let Some(config_path) = config_path.as_ref()
&& path::is_config_path_explicit()
{
@@ -276,8 +200,7 @@ impl UserConfig {
// The config crate's `preserve_order` feature ensures TOML insertion order
// is preserved (uses IndexMap instead of HashMap internally).
// See: https://github.com/max-sixty/worktrunk/issues/737
- let mut config: Self = builder.build()?.try_deserialize()?;
- config.normalize_deprecated_sections();
+ let config: Self = builder.build()?.try_deserialize()?;
config.validate()?;
Ok(config)
@@ -286,9 +209,9 @@ impl UserConfig {
/// Load configuration from a TOML string for testing.
#[cfg(test)]
pub(crate) fn load_from_str(content: &str) -> Result<Self, ConfigError> {
- let mut config: Self =
- toml::from_str(content).map_err(|e| ConfigError::Message(e.to_string()))?;
- config.normalize_deprecated_sections();
+ let migrated = crate::config::deprecation::migrate_content(content);
+ let config: Self =
+ toml::from_str(&migrated).map_err(|e| ConfigError::Message(e.to_string()))?;
config.validate()?;
Ok(config)
}
diff --git a/src/config/user/mutation.rs b/src/config/user/mutation.rs
index 5b8a5029e..509ee71cd 100644
--- a/src/config/user/mutation.rs
+++ b/src/config/user/mutation.rs
@@ -100,14 +100,14 @@ impl UserConfig {
))
})?;
- let mut disk_config: UserConfig = toml::from_str(&content).map_err(|e| {
+ let migrated = crate::config::deprecation::migrate_content(&content);
+ let disk_config: UserConfig = toml::from_str(&migrated).map_err(|e| {
ConfigError::Message(format!(
"Failed to parse config file {}: {}",
format_path_for_display(&path),
e
))
})?;
- disk_config.normalize_deprecated_sections();
// Replace in-memory projects with disk state (disk is authoritative)
self.projects = disk_config.projects;
diff --git a/src/config/user/persistence.rs b/src/config/user/persistence.rs
index 99c2703e7..6c26c20d6 100644
--- a/src/config/user/persistence.rs
+++ b/src/config/user/persistence.rs
@@ -148,11 +148,6 @@ impl UserConfig {
project_config.overrides.worktree_path.as_ref(),
);
- Self::sync_serialized_section(
- project_table,
- "commit-generation",
- project_config.commit_generation.as_ref(),
- );
Self::sync_serialized_section(
project_table,
"list",
@@ -173,11 +168,6 @@ impl UserConfig {
"switch",
project_config.overrides.switch.as_ref(),
);
- Self::sync_serialized_section(
- project_table,
- "select",
- project_config.overrides.select.as_ref(),
- );
}
}
}
diff --git a/src/config/user/sections.rs b/src/config/user/sections.rs
index 6cf205dc0..8abe07630 100644
--- a/src/config/user/sections.rs
+++ b/src/config/user/sections.rs
@@ -270,30 +270,9 @@ pub struct MergeConfig {
/// Fast-forward merge instead of creating a merge commit (default: true)
#[serde(skip_serializing_if = "Option::is_none")]
pub ff: Option<bool>,
-
- /// Deprecated: use `ff` instead. Kept for backward-compatible deserialization.
- #[serde(rename = "no-ff", skip_serializing, default)]
- #[schemars(skip)]
- pub(crate) no_ff_deprecated: Option<bool>,
}
impl MergeConfig {
- /// Migrate deprecated `no-ff` field to `ff` (inverted). Warns on use.
- pub fn normalize_deprecated_fields(&mut self) {
- if let Some(no_ff) = self.no_ff_deprecated.take()
- && self.ff.is_none()
- {
- self.ff = Some(!no_ff);
- eprintln!(
- "{}",
- crate::styling::warning_message(format!(
- "`no-ff` in [merge] is deprecated; use `ff = {}` instead",
- !no_ff
- ))
- );
- }
- }
-
/// Squash commits when merging (default: true)
pub fn squash(&self) -> bool {
self.squash.unwrap_or(true)
@@ -334,26 +313,6 @@ impl Merge for MergeConfig {
remove: other.remove.or(self.remove),
verify: other.verify.or(self.verify),
ff: other.ff.or(self.ff),
- no_ff_deprecated: None,
- }
- }
-}
-
-/// **DEPRECATED**: Use `[switch.picker]` instead.
-///
-/// Configuration for the `wt switch` interactive picker (old format).
-/// Kept for backward-compatible deserialization of `[select]` sections.
-#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default, JsonSchema)]
-pub struct SelectConfig {
- /// Pager command with flags for diff preview
- #[serde(skip_serializing_if = "Option::is_none")]
- pub pager: Option<String>,
-}
-
-impl Merge for SelectConfig {
- fn merge_with(&self, other: &Self) -> Self {
- Self {
- pager: other.pager.clone().or_else(|| self.pager.clone()),
}
}
}
@@ -422,33 +381,12 @@ pub struct SwitchConfig {
#[serde(skip_serializing_if = "Option::is_none")]
pub cd: Option<bool>,
- /// Deprecated: use `cd` instead. Kept for backward-compatible deserialization.
- #[serde(rename = "no-cd", skip_serializing, default)]
- #[schemars(skip)]
- pub(crate) no_cd_deprecated: Option<bool>,
-
/// Picker settings for the interactive selector
#[serde(default, skip_serializing_if = "Option::is_none")]
pub picker: Option<SwitchPickerConfig>,
}
impl SwitchConfig {
- /// Migrate deprecated `no-cd` field to `cd` (inverted). Warns on use.
- pub fn normalize_deprecated_fields(&mut self) {
- if let Some(no_cd) = self.no_cd_deprecated.take()
- && self.cd.is_none()
- {
- self.cd = Some(!no_cd);
- eprintln!(
- "{}",
- crate::styling::warning_message(format!(
- "`no-cd` in [switch] is deprecated; use `cd = {}` instead",
- !no_cd
- ))
- );
- }
- }
-
/// Change directory after switch (default: true)
pub fn cd(&self) -> bool {
self.cd.unwrap_or(true)
@@ -459,7 +397,6 @@ impl Merge for SwitchConfig {
fn merge_with(&self, other: &Self) -> Self {
Self {
cd: other.cd.or(self.cd),
- no_cd_deprecated: None,
picker: match (&self.picker, &other.picker) {
(None, None) => None,
(Some(s), None) => Some(s.clone()),
@@ -570,10 +507,6 @@ pub struct OverridableConfig {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub step: Option<StepConfig>,
- /// **DEPRECATED**: Use `[switch.picker]` instead.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub select: Option<SelectConfig>,
-
/// \[experimental\] Command aliases for `wt step <name>`.
///
/// Each alias maps a name to one or more command templates. All hook
@@ -607,7 +540,6 @@ impl OverridableConfig {
&& self.merge.is_none()
&& self.switch.is_none()
&& self.step.is_none()
- && self.select.is_none()
&& self.aliases.is_none()
}
}
@@ -627,7 +559,6 @@ impl Merge for OverridableConfig {
merge: merge_optional(self.merge.as_ref(), other.merge.as_ref()),
switch: merge_optional(self.switch.as_ref(), other.switch.as_ref()),
step: merge_optional(self.step.as_ref(), other.step.as_ref()),
- select: merge_optional(self.select.as_ref(), other.select.as_ref()),
aliases: merge_alias_maps(&self.aliases, &other.aliases), // Append semantics
}
}
@@ -684,17 +615,7 @@ pub struct UserProjectOverrides {
)]
pub approved_commands: Vec<String>,
- /// **DEPRECATED**: Use `commit.generation` instead.
- ///
- /// Per-project commit generation settings (overrides global `[commit.generation]`)
- #[serde(
- default,
- rename = "commit-generation",
- skip_serializing_if = "Option::is_none"
- )]
- pub commit_generation: Option<CommitGenerationConfig>,
-
- /// Per-project overrides (worktree-path, list, commit, merge, switch, step, select)
+ /// Per-project overrides (worktree-path, list, commit, merge, switch, step)
#[serde(flatten, default)]
pub overrides: OverridableConfig,
}
@@ -705,7 +626,7 @@ impl UserProjectOverrides {
/// Approvals are stored in `approvals.toml`, so `approved_commands` is only
/// kept here for backward-compatible parsing and migration — not checked.
pub fn is_empty(&self) -> bool {
- self.commit_generation.is_none() && self.overrides.is_empty()
+ self.overrides.is_empty()
}
}
diff --git a/src/config/user/tests.rs b/src/config/user/tests.rs
index 3da34f432..e14ed9d9d 100644
--- a/src/config/user/tests.rs
+++ b/src/config/user/tests.rs
@@ -85,15 +85,15 @@ fn test_find_unknown_keys_known_sections() {
let content = r#"
worktree-path = "../{{ main_worktree }}.{{ branch }}"
-[commit-generation]
-command = "llm"
-
[list]
full = true
[commit]
stage = "all"
+[commit.generation]
+command = "llm"
+
[merge]
squash = true
@@ -189,7 +189,6 @@ fn test_user_project_config_with_worktree_path_serde() {
..Default::default()
},
approved_commands: vec!["npm install".to_string()],
- ..Default::default()
};
let toml = toml::to_string(&config).unwrap();
insta::assert_snapshot!(toml, @r#"
@@ -216,7 +215,6 @@ fn test_worktree_path_for_project_uses_project_specific() {
..Default::default()
},
approved_commands: vec![],
- ..Default::default()
},
);
@@ -244,7 +242,6 @@ fn test_worktree_path_for_project_falls_back_to_global() {
..Default::default()
},
approved_commands: vec!["npm install".to_string()],
- ..Default::default()
},
);
@@ -284,7 +281,6 @@ fn test_format_path_with_project_override() {
..Default::default()
},
approved_commands: vec![],
- ..Default::default()
},
);
@@ -345,7 +341,6 @@ fn test_worktrunk_config_default() {
assert!(config.configs.list.is_none());
assert!(config.configs.commit.is_none());
assert!(config.configs.merge.is_none());
- assert!(config.commit_generation.is_none());
assert!(!config.skip_shell_integration_prompt);
}
@@ -463,7 +458,6 @@ fn test_merge_config_serde() {
remove: Some(true),
verify: Some(true),
ff: None,
- ..Default::default()
};
let json = serde_json::to_string(&config).unwrap();
let parsed: MergeConfig = serde_json::from_str(&json).unwrap();
@@ -672,7 +666,6 @@ fn test_merge_merge_config() {
remove: Some(true),
verify: Some(true),
ff: Some(true),
- ..Default::default()
};
let override_config = MergeConfig {
squash: Some(false), // Override
@@ -681,7 +674,6 @@ fn test_merge_merge_config() {
remove: Some(false), // Override
verify: None, // Fall back to base
ff: Some(false), // Override
- ..Default::default()
};
let merged = base.merge_with(&override_config);
@@ -875,7 +867,6 @@ fn test_effective_merge_with_partial_override() {
remove: Some(true),
verify: Some(true),
ff: Some(true),
- ..Default::default()
}),
..Default::default()
},
@@ -893,7 +884,6 @@ fn test_effective_merge_with_partial_override() {
remove: None,
verify: None,
ff: None,
- ..Default::default()
}),
..Default::default()
},
@@ -935,45 +925,6 @@ fn test_effective_list_project_only() {
assert!(config.list(Some("github.com/other/repo")).is_none());
}
-#[test]
-fn test_effective_select_with_project_override() {
- // Test that OverridableConfig merge works correctly for select
- let mut config = UserConfig {
- configs: OverridableConfig {
- select: Some(SelectConfig {
- pager: Some("delta".to_string()),
- }),
- ..Default::default()
- },
- ..Default::default()
- };
-
- config.projects.insert(
- "github.com/user/repo".to_string(),
- UserProjectOverrides {
- overrides: OverridableConfig {
- select: Some(SelectConfig {
- pager: Some("bat".to_string()),
- }),
- ..Default::default()
- },
- ..Default::default()
- },
- );
-
- // Project override takes precedence
- let effective = config.select(Some("github.com/user/repo")).unwrap();
- assert_eq!(effective.pager, Some("bat".to_string()));
-
- // No project override = use global
- let effective = config.select(Some("github.com/other/repo")).unwrap();
- assert_eq!(effective.pager, Some("delta".to_string()));
-
- // No project = use global
- let effective = config.select(None).unwrap();
- assert_eq!(effective.pager, Some("delta".to_string()));
-}
-
#[test]
fn test_effective_commit_global_only() {
// Only global config, no project config
@@ -1051,7 +1002,6 @@ fn test_merge_config_accessor_methods_with_values() {
remove: Some(false),
verify: Some(false),
ff: Some(false),
- ..Default::default()
};
assert!(!config.squash());
assert!(!config.commit());
@@ -1086,17 +1036,6 @@ fn test_commit_config_accessor_methods() {
assert_eq!(config.stage(), StageMode::Tracked);
}
-#[test]
-fn test_select_config_fields() {
- let config = SelectConfig::default();
- assert!(config.pager.is_none());
-
- let config = SelectConfig {
- pager: Some("delta --paging=never".to_string()),
- };
- assert_eq!(config.pager.as_deref(), Some("delta --paging=never"));
-}
-
// =========================================================================
// SwitchPickerConfig tests
// =========================================================================
@@ -1321,7 +1260,7 @@ pager = "bat"
let picker = config.switch_picker(None);
assert_eq!(picker.pager.as_deref(), Some("bat"));
- assert!(config.configs.select.is_none());
+ // [select] is migrated to [switch.picker] at the TOML level before parsing
assert_eq!(
config
.configs
@@ -1356,7 +1295,6 @@ pager = "bat"
let picker = config.switch_picker(None);
assert_eq!(picker.pager.as_deref(), Some("delta"));
assert_eq!(picker.timeout_ms, Some(100));
- assert!(config.configs.select.is_none());
}
#[test]
@@ -1416,14 +1354,19 @@ pager = "bat"
let picker = config.switch_picker(Some("github.com/user/repo"));
assert_eq!(picker.pager.as_deref(), Some("bat"));
assert_eq!(picker.timeout_ms, Some(300));
+ // [select] is migrated to [switch.picker] at the TOML level before parsing,
+ // so it ends up in the switch.picker field, not select
assert!(
config
.projects
.get("github.com/user/repo")
.unwrap()
.overrides
- .select
- .is_none()
+ .switch
+ .as_ref()
+ .and_then(|s| s.picker.as_ref())
+ .and_then(|p| p.pager.as_deref())
+ == Some("bat")
);
}
@@ -1479,7 +1422,6 @@ fn test_resolved_config_for_project() {
fn test_user_project_config_with_nested_configs_serde() {
let config = UserProjectOverrides {
approved_commands: vec!["npm install".to_string()],
- commit_generation: None, // Deprecated field, use commit.generation instead
overrides: OverridableConfig {
worktree_path: Some(".worktrees/{{ branch }}".to_string()),
list: Some(ListConfig {
@@ -1643,34 +1585,9 @@ exclude = [".repo-local/", ".entire/"]
}
#[test]
-fn test_deprecated_commit_generation_format_serde() {
- // Raw serde still accepts the old shape for backward compatibility.
- let content = r#"
-[commit-generation]
-command = "llm -m claude-haiku-4.5"
-
-[projects."github.com/user/repo".commit-generation]
-command = "claude -p --model opus"
-"#;
-
- let config: UserConfig = toml::from_str(content).unwrap();
-
- // Old format parsed into commit_generation field
- assert_eq!(
- config.commit_generation.as_ref().unwrap().command,
- Some("llm -m claude-haiku-4.5".to_string())
- );
-
- // Project override uses deprecated field
- let project = config.projects.get("github.com/user/repo").unwrap();
- assert_eq!(
- project.commit_generation.as_ref().unwrap().command,
- Some("claude -p --model opus".to_string())
- );
-}
-
-#[test]
-fn test_load_normalizes_deprecated_commit_generation_sections() {
+fn test_deprecated_commit_generation_migrated_on_load() {
+ // [commit-generation] is migrated to [commit.generation] at the TOML level
+ // before serde parsing, so it lands in configs.commit.generation
let content = r#"
[commit-generation]
command = "llm -m claude-haiku-4.5"
@@ -1681,7 +1598,6 @@ command = "claude -p --model opus"
let config = UserConfig::load_from_str(content).unwrap();
- assert!(config.commit_generation.is_none());
assert_eq!(
config
.configs
@@ -1693,7 +1609,6 @@ command = "claude -p --model opus"
);
let project = config.projects.get("github.com/user/repo").unwrap();
- assert!(project.commit_generation.is_none());
assert_eq!(
project
.overrides
@@ -1713,26 +1628,23 @@ command = "claude -p --model opus"
#[test]
fn test_deprecated_commit_generation_with_args_field() {
- // Test that old format with args field still parses (args is ignored)
- // This ensures backward compatibility for users who haven't migrated yet
+ // Test that old format with args field is migrated: args merged into command
let content = r#"
[commit-generation]
command = "llm"
args = ["-m", "claude-haiku-4.5"]
"#;
- let result: Result<UserConfig, _> = toml::from_str(content);
- assert!(
- result.is_ok(),
- "Old format with args field should parse (args is ignored): {:?}",
- result.err()
- );
-
- let config = result.unwrap();
- // Command is parsed, args is ignored (struct no longer has args field)
+ let config = UserConfig::load_from_str(content).unwrap();
+ // Migration merges args into command and renames section
assert_eq!(
- config.commit_generation.as_ref().unwrap().command,
- Some("llm".to_string())
+ config
+ .configs
+ .commit
+ .as_ref()
+ .and_then(|c| c.generation.as_ref())
+ .and_then(|g| g.command.as_deref()),
+ Some("llm -m claude-haiku-4.5")
);
}
@@ -1896,34 +1808,6 @@ fn test_save_to_new_file_commit_with_stage_and_generation() {
);
}
-#[test]
-fn test_save_to_new_file_with_deprecated_commit_generation() {
- // Test that save_to() serializes deprecated commit_generation field
- // (for backward compat when loading old configs and re-saving)
- let dir = tempfile::tempdir().unwrap();
- let config_path = dir.path().join("config.toml");
-
- let config = UserConfig {
- commit_generation: Some(CommitGenerationConfig {
- command: Some("old-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("[commit-generation]"),
- "Should use deprecated format: {saved}"
- );
- assert!(
- saved.contains("command = \"old-llm\""),
- "Should contain command: {saved}"
- );
-}
-
#[test]
fn test_save_to_new_file_with_skip_shell_integration() {
// Test skip-shell-integration-prompt is only written when true
diff --git a/tests/integration_tests/select_config.rs b/tests/integration_tests/select_config.rs
index 515fbc9d8..4b7d476cc 100644
--- a/tests/integration_tests/select_config.rs
+++ b/tests/integration_tests/select_config.rs
@@ -1,43 +1,26 @@
use worktrunk::config::UserConfig;
+use worktrunk::config::migrate_content;
#[test]
-fn test_select_pager_config_deserialization() {
- // Verify that SelectConfig with pager field deserializes correctly
- let config_content = r#"
+fn test_select_pager_config_migrated_to_switch_picker() {
+ // [select] is migrated to [switch.picker] at the TOML level before parsing
+ let content = r#"
[select]
pager = "test-pager --custom-flag"
"#;
-
- let config: UserConfig = toml::from_str(config_content).unwrap();
-
- assert!(config.configs.select.is_some());
- let select = config.configs.select.unwrap();
- assert_eq!(select.pager, Some("test-pager --custom-flag".to_string()));
-}
-
-#[test]
-fn test_select_pager_config_empty_string() {
- // Verify that empty string is valid TOML and deserializes
- let config_content = r#"
-[select]
-pager = ""
-"#;
-
- let config: UserConfig = toml::from_str(config_content).unwrap();
-
- assert!(config.configs.select.is_some());
- let select = config.configs.select.unwrap();
- assert_eq!(select.pager, Some("".to_string()));
+ let migrated = migrate_content(content);
+ let config: UserConfig = toml::from_str(&migrated).unwrap();
+ let picker = config.switch_picker(None);
+ assert_eq!(picker.pager.as_deref(), Some("test-pager --custom-flag"));
}
#[test]
fn test_select_config_optional() {
- // Verify that config without [select] section is still valid
- let config_content = r#"
+ // Config without [select] section is still valid
+ let content = r#"
[list]
full = true
"#;
-
- let config: UserConfig = toml::from_str(config_content).unwrap();
- assert!(config.configs.select.is_none());
+ let config: UserConfig = toml::from_str(content).unwrap();
+ assert!(config.configs.switch.is_none());
}
diff --git a/tests/snapshots/integration__integration_tests__config_show__config_show_suggests_user_config_for_commit_generation.snap b/tests/snapshots/integration__integration_tests__config_show__config_show_suggests_user_config_for_commit_generation.snap
index d5051e9f3..b2117610c 100644
--- a/tests/snapshots/integration__integration_tests__config_show__config_show_suggests_user_config_for_commit_generation.snap
+++ b/tests/snapshots/integration__integration_tests__config_show__config_show_suggests_user_config_for_commit_generation.snap
@@ -60,7 +60,7 @@ exit_code: 0
  / No newline at end of file
  +[commit.generation]
  +command = "claude"
-▲ Key commit-generation belongs in user config (will be ignored)
+▲ Unknown key commit-generation will be ignored
○ Current config:
  [commit-generation]
  command = "claude"