Skip to content

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

refactor(deprecation): Vec<DeprecationKind> + config-table combinators (#2946)

Maximilian Roos3549f21e4f82
diff --git a/CLAUDE.md b/CLAUDE.md
index d733186a3..7c1dcfe5f 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -165,7 +165,7 @@ Check `Cargo.toml` before hand-rolling a utility:
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, emits per-process-deduped warnings, and generates a `.new` migration file. **Never silently drop an old config key** — that's a silent behavior change for users; migrate it.
-Adding a deprecation: (1) a detection function plus extend `Deprecations` / `detect_deprecations()`; (2) an idempotent migration function; (3) call it from `migrate_content()`; (4) a warning in `format_deprecation_warnings()`; (5) update `Deprecations::is_empty()`; (6) 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. Renaming a field within a section follows the same shape via a TOML-level rename function (see `migrate_negated_bool_in_section`); the struct never needs the old field since migration precedes serde.
+Detection produces a `Vec<DeprecationKind>` (`Deprecations`): each variant carries its own display payload, so `format_deprecation_warnings()` is one match over the kinds and `is_empty` is just `Vec::is_empty()`. Adding a deprecation: (1) a detection function, plus a `DeprecationKind` variant that `detect_deprecations_from_doc()` pushes in warning-emission order; (2) an idempotent migration function; (3) call it from `migrate_content()`; (4) a match arm in `format_deprecation_warnings()`; (5) 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`) gets no variant — it emits no warning by construction. 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.
## Adding CLI Commands
diff --git a/src/commands/config/update.rs b/src/commands/config/update.rs
index 33146d55d..86bd51f78 100644
--- a/src/commands/config/update.rs
+++ b/src/commands/config/update.rs
@@ -10,7 +10,7 @@ use std::path::PathBuf;
use anyhow::Context;
use color_print::cformat;
use worktrunk::config::{
- DeprecationInfo, compute_migrated_content, config_path,
+ DeprecationInfo, DeprecationKind, compute_migrated_content, config_path,
copy_approved_commands_to_approvals_file, format_deprecation_warnings, format_migration_diff,
};
use worktrunk::git::Repository;
@@ -93,7 +93,11 @@ pub fn handle_config_update(yes: bool, print: bool) -> anyhow::Result<()> {
// drops them; approvals.toml becomes the authoritative source). Abort
// the whole update if the copy fails — rewriting config.toml first
// would silently lose the legacy approvals.
- if candidate.info.deprecations.approved_commands
+ if candidate
+ .info
+ .deprecations
+ .iter()
+ .any(|k| matches!(k, DeprecationKind::ApprovedCommands))
&& let Some(approvals_path) =
copy_approved_commands_to_approvals_file(&candidate.config_path)?
{
diff --git a/src/config/deprecation.rs b/src/config/deprecation.rs
index fb726adaa..ee0c9dfe5 100644
--- a/src/config/deprecation.rs
+++ b/src/config/deprecation.rs
@@ -461,78 +461,142 @@ impl CommitGenerationDeprecations {
}
}
-/// All deprecation information detected in a config file.
+/// One deprecated config pattern, carrying the payload its warning needs.
///
-/// This is a pure data struct with no path/label context. Used by both
-/// config loading (brief warnings) and `wt config show` (full details).
-#[derive(Debug, Default, Clone)]
-pub struct Deprecations {
- /// Deprecated template variables found: (old_name, new_name)
- pub vars: Vec<(&'static str, &'static str)>,
- /// Deprecated commit-generation sections found
- pub commit_gen: CommitGenerationDeprecations,
- /// Has `approved-commands` in any `[projects."..."]` section (moved to approvals.toml)
- pub approved_commands: bool,
- /// Has `[select]` section (moved to `[switch.picker]`)
- pub select: 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,
- /// Pre-* hooks using multi-entry table form (will become concurrent in a future version)
- pub pre_hook_table_form: Vec<String>,
- /// Has `timeout-ms` under `[switch.picker]` (removed — picker now renders progressively)
- pub switch_picker_timeout_ms: bool,
+/// Each variant maps to a single `format_deprecation_warnings` arm. Silently
+/// migrated patterns (the `-create` → `-start` hook rename) have NO variant —
+/// they produce no warning by construction.
+#[derive(Debug, Clone)]
+pub enum DeprecationKind {
+ /// Deprecated template variable `old` replaced by `new`.
+ TemplateVar {
+ old: &'static str,
+ new: &'static str,
+ },
+ /// `[commit-generation]` sections → `[commit.generation]`. Carries the
+ /// top-level flag plus per-project keys so each emits its own warning line.
+ CommitGeneration(CommitGenerationDeprecations),
+ /// `approved-commands` under `[projects."..."]` (moved to approvals.toml).
+ ApprovedCommands,
+ /// `[select]` section (moved to `[switch.picker]`).
+ Select,
+ /// `[ci]` section (moved to `[forge]`).
+ CiSection,
+ /// `no-ff` in `[merge]` (use `ff` instead).
+ NoFf,
+ /// `no-cd` in `[switch]` (use `cd` instead).
+ NoCd,
+ /// `timeout-ms` under `[switch.picker]` (removed — picker renders progressively).
+ SwitchPickerTimeout,
+ /// Pre-* hooks using multi-entry table form, by display path.
+ PreHookTableForm(Vec<String>),
}
-impl Deprecations {
- /// Returns true if any deprecations were found
- pub fn is_empty(&self) -> bool {
- self.vars.is_empty()
- && self.commit_gen.is_empty()
- && !self.approved_commands
- && !self.select
- && !self.ci_section
- && !self.no_ff
- && !self.no_cd
- && self.pre_hook_table_form.is_empty()
- && !self.switch_picker_timeout_ms
- }
-}
+/// All deprecation patterns detected in a config file, in the order their
+/// warnings are emitted.
+///
+/// Pure data with no path/label context. Used by both config loading (brief
+/// warnings) and `wt config show` (full details). Empty when nothing is
+/// deprecated.
+pub type Deprecations = Vec<DeprecationKind>;
/// Detect deprecations in config content. Pure function, no I/O.
///
/// Parses the TOML content once and checks all deprecation types against the
/// parsed document.
///
-/// Returns a `Deprecations` struct containing all detected deprecation issues.
-/// This is the recommended entry point for deprecation detection.
+/// Returns the detected deprecation patterns. This is the recommended entry
+/// point for deprecation detection.
pub fn detect_deprecations(content: &str) -> Deprecations {
let Ok(doc) = content.parse::<toml_edit::DocumentMut>() else {
- return Deprecations::default();
+ return Vec::new();
};
let template_strings = extract_template_strings_from_doc(&doc);
detect_deprecations_from_doc(&doc, &template_strings)
}
-/// Detect deprecations from an already-parsed document and pre-extracted template strings.
+/// Detect deprecations from an already-parsed document and pre-extracted
+/// template strings.
+///
+/// Pushes kinds in the order their warnings are emitted, so iterating the
+/// returned `Vec` reproduces the warning text byte-for-byte.
fn detect_deprecations_from_doc(
doc: &toml_edit::DocumentMut,
template_strings: &[String],
) -> Deprecations {
- Deprecations {
- vars: find_deprecated_vars_from_strings(template_strings),
- commit_gen: find_commit_generation_from_doc(doc),
- approved_commands: find_approved_commands_from_doc(doc),
- select: find_select_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"),
- pre_hook_table_form: find_pre_hook_table_form_from_doc(doc),
- switch_picker_timeout_ms: find_switch_picker_timeout_from_doc(doc),
+ let mut kinds = Vec::new();
+
+ for (old, new) in find_deprecated_vars_from_strings(template_strings) {
+ kinds.push(DeprecationKind::TemplateVar { old, new });
}
+ let commit_gen = find_commit_generation_from_doc(doc);
+ if !commit_gen.is_empty() {
+ kinds.push(DeprecationKind::CommitGeneration(commit_gen));
+ }
+ if find_approved_commands_from_doc(doc) {
+ kinds.push(DeprecationKind::ApprovedCommands);
+ }
+ if find_select_from_doc(doc) {
+ kinds.push(DeprecationKind::Select);
+ }
+ if find_ci_section_from_doc(doc) {
+ kinds.push(DeprecationKind::CiSection);
+ }
+ if find_negated_bool_from_doc(doc, "merge", "no-ff", "ff") {
+ kinds.push(DeprecationKind::NoFf);
+ }
+ if find_negated_bool_from_doc(doc, "switch", "no-cd", "cd") {
+ kinds.push(DeprecationKind::NoCd);
+ }
+ if find_switch_picker_timeout_from_doc(doc) {
+ kinds.push(DeprecationKind::SwitchPickerTimeout);
+ }
+ let pre_hook_table_form = find_pre_hook_table_form_from_doc(doc);
+ if !pre_hook_table_form.is_empty() {
+ kinds.push(DeprecationKind::PreHookTableForm(pre_hook_table_form));
+ }
+
+ kinds
+}
+
+/// Detect-side scope walk: apply `f` to the top-level table (scope `None`) and
+/// to each `[projects."key"]` table (scope `Some(key)`), short-circuiting on the
+/// first `true`. The scope key feeds callers that build display paths.
+fn any_config_table(
+ doc: &toml_edit::DocumentMut,
+ mut f: impl FnMut(Option<&str>, &toml_edit::Table) -> bool,
+) -> bool {
+ if f(None, doc.as_table()) {
+ return true;
+ }
+ if let Some(projects) = doc.get("projects").and_then(|p| p.as_table()) {
+ for (key, value) in projects.iter() {
+ if let Some(table) = value.as_table()
+ && f(Some(key), table)
+ {
+ return true;
+ }
+ }
+ }
+ false
+}
+
+/// Migrate-side scope walk: apply `f` mutably to the top-level table (scope
+/// `None`) and to each `[projects."key"]` table (scope `Some(key)`), returning
+/// whether any scope reported a change.
+fn for_each_config_table_mut(
+ doc: &mut toml_edit::DocumentMut,
+ mut f: impl FnMut(Option<&str>, &mut toml_edit::Table) -> bool,
+) -> bool {
+ let mut modified = f(None, doc.as_table_mut());
+ if let Some(projects) = doc.get_mut("projects").and_then(|p| p.as_table_mut()) {
+ for (key, value) in projects.iter_mut() {
+ if let Some(table) = value.as_table_mut() {
+ modified |= f(Some(key.get()), table);
+ }
+ }
+ }
+ modified
}
fn find_approved_commands_from_doc(doc: &toml_edit::DocumentMut) -> bool {
@@ -552,50 +616,32 @@ fn find_approved_commands_from_doc(doc: &toml_edit::DocumentMut) -> bool {
false
}
-fn find_commit_generation_from_doc(doc: &toml_edit::DocumentMut) -> CommitGenerationDeprecations {
- let mut result = CommitGenerationDeprecations::default();
-
- // Check if new [commit.generation] already exists as a valid table
- // (skip deprecation warning if so)
- let has_new_section = has_table_like_child(doc.get("commit"), "generation");
-
- // Check top-level [commit-generation] - only flag if non-empty and new section doesn't exist
- // Handle both regular tables and inline tables
- if !has_new_section && let Some(section) = doc.get("commit-generation") {
- if let Some(table) = section.as_table() {
- if !table.is_empty() {
- result.has_top_level = true;
- }
- } else if let Some(inline) = section.as_inline_table()
- && !inline.is_empty()
- {
- result.has_top_level = true;
- }
+/// Whether a scope has a non-empty deprecated `commit-generation` section and
+/// no canonical `[commit.generation]` to supersede it. Shared by detection and
+/// migration so both agree on which scopes need migrating.
+fn has_deprecated_commit_generation(table: &toml_edit::Table) -> bool {
+ if has_table_like_child(table.get("commit"), "generation") {
+ return false;
}
+ table.get("commit-generation").is_some_and(|section| {
+ section.as_table().is_some_and(|t| !t.is_empty())
+ || section.as_inline_table().is_some_and(|t| !t.is_empty())
+ })
+}
- // Check [projects."...".commit-generation]
- if let Some(projects) = doc.get("projects").and_then(|p| p.as_table()) {
- for (project_key, project_value) in projects.iter() {
- if let Some(project_table) = project_value.as_table() {
- // Check if this project has new section as a valid table
- let has_new_project_section =
- has_table_like_child(project_table.get("commit"), "generation");
-
- // Only flag if old section exists, is non-empty, and new doesn't exist
- // Handle both regular tables and inline tables
- if !has_new_project_section
- && let Some(old_section) = project_table.get("commit-generation")
- {
- let is_non_empty = old_section.as_table().is_some_and(|t| !t.is_empty())
- || old_section.as_inline_table().is_some_and(|t| !t.is_empty());
- if is_non_empty {
- result.project_keys.push(project_key.to_string());
- }
- }
+fn find_commit_generation_from_doc(doc: &toml_edit::DocumentMut) -> CommitGenerationDeprecations {
+ let mut result = CommitGenerationDeprecations::default();
+ // Top-level sets a bool; each project records its key — a per-scope fork, so
+ // the closure branches on the scope rather than returning a uniform bool.
+ any_config_table(doc, |scope, table| {
+ if has_deprecated_commit_generation(table) {
+ match scope {
+ None => result.has_top_level = true,
+ Some(key) => result.project_keys.push(key.to_string()),
}
}
- }
-
+ false
+ });
result
}
@@ -656,80 +702,39 @@ fn into_table(item: toml_edit::Item) -> Option<toml_edit::Table> {
}
}
-fn migrate_commit_generation_doc(doc: &mut toml_edit::DocumentMut) -> bool {
- let mut modified = false;
-
- // Check if new [commit.generation] already exists as a valid table - if so, skip migration
- // (new format takes precedence, don't overwrite it)
- let has_new_section = has_table_like_child(doc.get("commit"), "generation");
-
- // Migrate top-level [commit-generation] → [commit.generation]
- // Only if new section doesn't already exist
- // Handle both regular tables and inline tables. Peek before removing so a
- // malformed value (e.g., a bare string) is left in place rather than
- // silently dropped when a sibling migration also serializes the doc.
- // Also require `commit` be absent or a table — a scalar `commit = "x"`
- // blocks insertion of `[commit.generation]`; removing the source then
- // would silently drop the deprecated section.
- if !has_new_section
- && doc.get("commit-generation").is_some_and(is_table_like)
- && can_host_subtable(doc.get("commit"))
- && let Some(old_section) = doc.remove("commit-generation")
+/// Migrate one scope's `[commit-generation]` → `[commit.generation]`.
+///
+/// Skips when a canonical `[commit.generation]` already exists (new format takes
+/// precedence). Peeks before removing so a malformed value (e.g. a bare string)
+/// is left in place rather than silently dropped when a sibling migration also
+/// serializes the doc. Requires `commit` be absent or a table — a scalar
+/// `commit = "x"` blocks insertion of `[commit.generation]`, and removing the
+/// source then would silently drop the deprecated section.
+fn migrate_commit_generation_in(table: &mut toml_edit::Table) -> bool {
+ if has_table_like_child(table.get("commit"), "generation")
+ || !table.get("commit-generation").is_some_and(is_table_like)
+ || !can_host_subtable(table.get("commit"))
{
- let mut table = into_table(old_section).expect("checked is_table_like above");
-
- // Merge args into command if present
- merge_args_into_command(&mut table);
-
- // Ensure [commit] section exists.
- // Mark as implicit so it doesn't render a separate [commit] header
- // (only [commit.generation] will render)
- // Move to [commit.generation]
- if let Some(commit_table) = ensure_standard_table_parent(doc.as_table_mut(), "commit") {
- commit_table.insert("generation", toml_edit::Item::Table(table));
- }
-
- modified = true;
+ return false;
}
+ let Some(old_section) = table.remove("commit-generation") else {
+ return false;
+ };
+ let mut generation = into_table(old_section).expect("checked is_table_like above");
- // Migrate [projects."...".commit-generation] → [projects."...".commit.generation]
- if let Some(projects) = doc.get_mut("projects").and_then(|p| p.as_table_mut()) {
- for (_project_key, project_value) in projects.iter_mut() {
- if let Some(project_table) = project_value.as_table_mut() {
- // Check if new section already exists as a valid table for this project
- let has_new_project_section =
- has_table_like_child(project_table.get("commit"), "generation");
-
- // Peek before removing so a malformed value is preserved.
- // Same scalar-parent guard as the top-level case above.
- if !has_new_project_section
- && project_table
- .get("commit-generation")
- .is_some_and(is_table_like)
- && can_host_subtable(project_table.get("commit"))
- && let Some(old_section) = project_table.remove("commit-generation")
- {
- let mut table = into_table(old_section).expect("checked is_table_like above");
-
- // Merge args into command if present
- merge_args_into_command(&mut table);
-
- // Ensure [projects."...".commit] section exists.
- // Mark as implicit so it doesn't render a separate header
- // Move to [projects."...".commit.generation]
- if let Some(commit_table) =
- ensure_standard_table_parent(project_table, "commit")
- {
- commit_table.insert("generation", toml_edit::Item::Table(table));
- }
-
- modified = true;
- }
- }
- }
+ // Merge args into command if present.
+ merge_args_into_command(&mut generation);
+
+ // Ensure [commit] exists (implicit, so only [commit.generation] renders a
+ // header) and move the migrated section under it.
+ if let Some(commit_table) = ensure_standard_table_parent(table, "commit") {
+ commit_table.insert("generation", toml_edit::Item::Table(generation));
}
+ true
+}
- modified
+fn migrate_commit_generation_doc(doc: &mut toml_edit::DocumentMut) -> bool {
+ for_each_config_table_mut(doc, |_, table| migrate_commit_generation_in(table))
}
/// Remove `approved-commands` from all `\[projects."..."\]` sections.
@@ -785,22 +790,7 @@ fn remove_approved_commands_doc(doc: &mut toml_edit::DocumentMut) -> bool {
}
fn find_select_from_doc(doc: &toml_edit::DocumentMut) -> bool {
- 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
+ any_config_table(doc, |_, table| has_select_without_picker(table))
}
/// Check if a table has a non-empty `select` section without `switch.picker`.
@@ -828,43 +818,30 @@ fn has_select_without_picker(table: &toml_edit::Table) -> bool {
/// 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 {
- 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
+ for_each_config_table_mut(doc, |_, table| migrate_select_table(table))
}
-/// Migrate a `select` key to `switch.picker` within a table.
+/// Migrate a `select` key to `switch.picker` within a table. Returns whether a
+/// migration was performed.
///
/// Leaves a malformed `select` (e.g., a string) in place rather than removing
/// it — silently dropping it would lose user config when a sibling migration
/// also rewrites the document.
-fn migrate_select_table(table: &mut toml_edit::Table, modified: &mut bool) {
+fn migrate_select_table(table: &mut toml_edit::Table) -> bool {
let has_new_section = has_table_like_child(table.get("switch"), "picker");
if has_new_section {
- return;
+ return false;
}
if !table.get("select").is_some_and(is_table_like) {
- return;
+ return false;
}
// A scalar `switch = "x"` blocks insertion of `[switch.picker]`; removing
// `select` then would silently drop the user's picker config.
if !can_host_subtable(table.get("switch")) {
- return;
+ return false;
}
let select_table =
@@ -874,7 +851,7 @@ fn migrate_select_table(table: &mut toml_edit::Table, modified: &mut bool) {
switch_table.insert("picker", toml_edit::Item::Table(select_table));
}
- *modified = true;
+ true
}
/// The 5 canonical pre-* hook keys.
@@ -912,20 +889,11 @@ fn collect_pre_hook_table_form_keys(
/// hook found.
fn find_pre_hook_table_form_from_doc(doc: &toml_edit::DocumentMut) -> Vec<String> {
let mut found = Vec::new();
-
- // Top-level (user config or project config)
- collect_pre_hook_table_form_keys(doc.as_table(), "", &mut found);
-
- // Per-project overrides (user config)
- if let Some(projects) = doc.get("projects").and_then(|p| p.as_table()) {
- for (project_key, project_value) in projects.iter() {
- if let Some(project_table) = project_value.as_table() {
- let prefix = format!("projects.\"{project_key}\"");
- collect_pre_hook_table_form_keys(project_table, &prefix, &mut found);
- }
- }
- }
-
+ any_config_table(doc, |scope, table| {
+ let prefix = scope.map_or_else(String::new, |key| format!("projects.\"{key}\""));
+ collect_pre_hook_table_form_keys(table, &prefix, &mut found);
+ false
+ });
found
}
@@ -1005,30 +973,12 @@ fn find_negated_bool_from_doc(
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
+ any_config_table(doc, |_, scope| {
+ scope
+ .get(section)
+ .and_then(|s| s.as_table())
+ .is_some_and(|table| !table.contains_key(new_key) && table.contains_key(old_key))
+ })
}
/// Migrate a negated boolean field within a table (e.g., `no-ff = true` → `ff = false`).
@@ -1059,30 +1009,12 @@ fn migrate_negated_bool_doc(
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
+ for_each_config_table_mut(doc, |_, scope| {
+ scope
+ .get_mut(section)
+ .and_then(|s| s.as_table_mut())
+ .is_some_and(|table| migrate_negated_bool(table, old_key, new_key))
+ })
}
/// Convert a multi-entry pre-* table section into an array-of-tables pipeline.
@@ -1093,7 +1025,7 @@ fn migrate_negated_bool_doc(
/// Iterates pre-* keys in document order (not [`PRE_HOOK_KEYS`] order) so
/// migrated sections land in the same relative position they had in the
/// source file.
-fn migrate_pre_hook_table_in(table: &mut toml_edit::Table, modified: &mut bool) {
+fn migrate_pre_hook_table_in(table: &mut toml_edit::Table) -> bool {
let keys_to_migrate: Vec<String> = table
.iter()
.filter(|(k, v)| {
@@ -1103,6 +1035,7 @@ fn migrate_pre_hook_table_in(table: &mut toml_edit::Table, modified: &mut bool)
.map(|(k, _)| k.to_string())
.collect();
+ let mut modified = false;
for key in keys_to_migrate {
let item = table.get_mut(&key).unwrap();
let entries = pre_hook_pipeline_entries(item).unwrap();
@@ -1115,8 +1048,9 @@ fn migrate_pre_hook_table_in(table: &mut toml_edit::Table, modified: &mut bool)
}
*item = toml_edit::Item::ArrayOfTables(arr);
- *modified = true;
+ modified = true;
}
+ modified
}
fn pre_hook_pipeline_entries(item: &toml_edit::Item) -> Option<Vec<(String, String)>> {
@@ -1144,21 +1078,7 @@ fn pre_hook_pipeline_entries(item: &toml_edit::Item) -> Option<Vec<(String, Stri
/// Hooks are flattened into the top level of user config, project config, and
/// each `[projects."id"]` subtree.
fn migrate_pre_hook_table_form_doc(doc: &mut toml_edit::DocumentMut) -> bool {
- let mut modified = false;
-
- // Top-level (user config or project config)
- migrate_pre_hook_table_in(doc.as_table_mut(), &mut modified);
-
- // Per-project overrides (user config)
- 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_pre_hook_table_in(project_table, &mut modified);
- }
- }
- }
-
- modified
+ for_each_config_table_mut(doc, |_, table| migrate_pre_hook_table_in(table))
}
/// Apply all structural TOML migrations to a parsed document.
@@ -1248,19 +1168,7 @@ fn has_switch_picker_timeout(table: &toml_edit::Table) -> bool {
}
fn find_switch_picker_timeout_from_doc(doc: &toml_edit::DocumentMut) -> bool {
- if has_switch_picker_timeout(doc.as_table()) {
- return true;
- }
- 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_switch_picker_timeout(project_table)
- {
- return true;
- }
- }
- }
- false
+ any_config_table(doc, |_, table| has_switch_picker_timeout(table))
}
/// Remove `timeout-ms` from `[switch.picker]` in a table (top-level or project).
@@ -1286,15 +1194,7 @@ fn remove_switch_picker_timeout_in(table: &mut toml_edit::Table) -> bool {
/// Strips the key at both the top level and under `[projects."..."]`. Empty
/// `[switch.picker]` sections are left in place — they round-trip harmlessly.
fn migrate_switch_picker_timeout_doc(doc: &mut toml_edit::DocumentMut) -> bool {
- let mut modified = remove_switch_picker_timeout_in(doc.as_table_mut());
- 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() {
- modified |= remove_switch_picker_timeout_in(project_table);
- }
- }
- }
- modified
+ for_each_config_table_mut(doc, |_, table| remove_switch_picker_timeout_in(table))
}
fn migrate_content_from_doc(content: &str, mut doc: toml_edit::DocumentMut) -> String {
@@ -1513,7 +1413,7 @@ pub fn check_and_migrate(
let migrated_content = migrate_content_from_doc(content, doc);
(deprecations, migrated_content)
}
- Err(_) => (Deprecations::default(), content.to_string()),
+ Err(_) => (Vec::new(), content.to_string()),
};
if deprecations.is_empty() {
@@ -1609,7 +1509,10 @@ pub fn compute_migrated_content(content: &str) -> String {
// Replace deprecated template vars on the parsed tree (correct even when
// the source uses escapes — see `replace_deprecated_vars_in_doc`).
- let mut modified = if !deprecations.vars.is_empty() {
+ let has_template_vars = deprecations
+ .iter()
+ .any(|k| matches!(k, DeprecationKind::TemplateVar { .. }));
+ let mut modified = if has_template_vars {
replace_deprecated_vars_in_doc(&mut doc)
} else {
false
@@ -1619,7 +1522,10 @@ pub fn compute_migrated_content(content: &str) -> String {
modified |= migrate_content_doc(&mut doc);
// Additionally remove approved-commands (not part of migrate_content because
// approved-commands is still a valid serde field at runtime).
- if deprecations.approved_commands {
+ if deprecations
+ .iter()
+ .any(|k| matches!(k, DeprecationKind::ApprovedCommands))
+ {
modified |= remove_approved_commands_doc(&mut doc);
}
if modified {
@@ -1668,127 +1574,116 @@ pub fn format_migration_diff(original: &str, migrated: &str, label: &str) -> Opt
/// `wt config update` hint and diff) and `wt config update` (which applies directly).
pub fn format_deprecation_warnings(info: &DeprecationInfo) -> String {
use std::fmt::Write;
+ let label = &info.label;
let mut out = String::new();
- for (old, new) in &info.deprecations.vars {
- let _ = writeln!(
- out,
- "{}",
- warning_message(cformat!(
- "{label}: template variable <bold>{old}</> is deprecated in favor of <bold>{new}</>",
- label = info.label,
- ))
- );
- }
-
- if info.deprecations.commit_gen.has_top_level {
- let _ = writeln!(
- out,
- "{}",
- warning_message(cformat!(
- "{}: <bold>[commit-generation]</> is deprecated in favor of <bold>[commit.generation]</>",
- info.label
- ))
- );
- }
- for project_key in &info.deprecations.commit_gen.project_keys {
- let _ = writeln!(
- out,
- "{}",
- warning_message(cformat!(
- "{label}: <bold>[projects.\"{k}\".commit-generation]</> is deprecated in favor of <bold>[projects.\"{k}\".commit.generation]</>",
- label = info.label,
- k = project_key
- ))
- );
- }
-
- if info.deprecations.approved_commands {
- let _ = writeln!(
- out,
- "{}",
- warning_message(cformat!(
- "{}: <bold>approved-commands</> under <bold>[projects]</> is deprecated in favor of <bold>approvals.toml</>",
- info.label
- ))
- );
- }
-
- if info.deprecations.select {
- let _ = writeln!(
- out,
- "{}",
- warning_message(cformat!(
- "{}: <bold>[select]</> is deprecated in favor of <bold>[switch.picker]</>",
- info.label
- ))
- );
- }
-
- if info.deprecations.ci_section {
- let _ = writeln!(
- out,
- "{}",
- warning_message(cformat!(
- "{}: <bold>[ci]</> is deprecated in favor of <bold>[forge]</>",
- info.label
- ))
- );
- }
-
- if info.deprecations.no_ff {
- let _ = writeln!(
- out,
- "{}",
- warning_message(cformat!(
- "{}: <bold>merge.no-ff</> is deprecated in favor of <bold>merge.ff</> (inverted)",
- info.label
- ))
- );
- }
-
- if info.deprecations.no_cd {
- let _ = writeln!(
- out,
- "{}",
- warning_message(cformat!(
- "{}: <bold>switch.no-cd</> is deprecated in favor of <bold>switch.cd</> (inverted)",
- info.label
- ))
- );
- }
-
- if info.deprecations.switch_picker_timeout_ms {
- let _ = writeln!(
- out,
- "{}",
- warning_message(cformat!(
- "{}: <bold>switch.picker.timeout-ms</> is no longer used — the picker now renders progressively",
- info.label
- ))
- );
- }
-
- if !info.deprecations.pre_hook_table_form.is_empty() {
- let hook_list = info
- .deprecations
- .pre_hook_table_form
- .iter()
- .map(|h| cformat!("<bold>{h}</>"))
- .collect::<Vec<_>>()
- .join(", ");
- let _ = writeln!(
- out,
- "{}",
- warning_message(cformat!(
- "{}: table form for {} is deprecated in favor of the pipeline form. \
- We're unifying pre-hooks, post-hooks, and aliases so that list form always runs serially \
- and table form always runs in parallel — migrate now to keep the current serial behavior \
- once the table form is repurposed.",
- info.label,
- hook_list
- ))
- );
+ // One `warning_message` line per emitted message. The kinds are stored in
+ // emission order, so a single pass reproduces the original output verbatim.
+ // Each arm pushes its own newline so a multi-line kind (commit-generation)
+ // can emit several lines.
+ for kind in &info.deprecations {
+ match kind {
+ DeprecationKind::TemplateVar { old, new } => {
+ let _ = writeln!(
+ out,
+ "{}",
+ warning_message(cformat!(
+ "{label}: template variable <bold>{old}</> is deprecated in favor of <bold>{new}</>"
+ ))
+ );
+ }
+ DeprecationKind::CommitGeneration(commit_gen) => {
+ if commit_gen.has_top_level {
+ let _ = writeln!(
+ out,
+ "{}",
+ warning_message(cformat!(
+ "{label}: <bold>[commit-generation]</> is deprecated in favor of <bold>[commit.generation]</>"
+ ))
+ );
+ }
+ for k in &commit_gen.project_keys {
+ let _ = writeln!(
+ out,
+ "{}",
+ warning_message(cformat!(
+ "{label}: <bold>[projects.\"{k}\".commit-generation]</> is deprecated in favor of <bold>[projects.\"{k}\".commit.generation]</>"
+ ))
+ );
+ }
+ }
+ DeprecationKind::ApprovedCommands => {
+ let _ = writeln!(
+ out,
+ "{}",
+ warning_message(cformat!(
+ "{label}: <bold>approved-commands</> under <bold>[projects]</> is deprecated in favor of <bold>approvals.toml</>"
+ ))
+ );
+ }
+ DeprecationKind::Select => {
+ let _ = writeln!(
+ out,
+ "{}",
+ warning_message(cformat!(
+ "{label}: <bold>[select]</> is deprecated in favor of <bold>[switch.picker]</>"
+ ))
+ );
+ }
+ DeprecationKind::CiSection => {
+ let _ = writeln!(
+ out,
+ "{}",
+ warning_message(cformat!(
+ "{label}: <bold>[ci]</> is deprecated in favor of <bold>[forge]</>"
+ ))
+ );
+ }
+ DeprecationKind::NoFf => {
+ let _ = writeln!(
+ out,
+ "{}",
+ warning_message(cformat!(
+ "{label}: <bold>merge.no-ff</> is deprecated in favor of <bold>merge.ff</> (inverted)"
+ ))
+ );
+ }
+ DeprecationKind::NoCd => {
+ let _ = writeln!(
+ out,
+ "{}",
+ warning_message(cformat!(
+ "{label}: <bold>switch.no-cd</> is deprecated in favor of <bold>switch.cd</> (inverted)"
+ ))
+ );
+ }
+ DeprecationKind::SwitchPickerTimeout => {
+ let _ = writeln!(
+ out,
+ "{}",
+ warning_message(cformat!(
+ "{label}: <bold>switch.picker.timeout-ms</> is no longer used — the picker now renders progressively"
+ ))
+ );
+ }
+ DeprecationKind::PreHookTableForm(hooks) => {
+ let hook_list = hooks
+ .iter()
+ .map(|h| cformat!("<bold>{h}</>"))
+ .collect::<Vec<_>>()
+ .join(", ");
+ let _ = writeln!(
+ out,
+ "{}",
+ warning_message(cformat!(
+ "{label}: table form for {hook_list} is deprecated in favor of the pipeline form. \
+ We're unifying pre-hooks, post-hooks, and aliases so that list form always runs serially \
+ and table form always runs in parallel — migrate now to keep the current serial behavior \
+ once the table form is repurposed."
+ ))
+ );
+ }
+ }
}
out
@@ -2059,6 +1954,13 @@ mod tests {
find_deprecated_vars_from_strings(&strings)
}
+ /// True when `deprecations` carries a kind matching `pred`. Lets the
+ /// per-kind tests assert presence of a single deprecation against the
+ /// `Vec<DeprecationKind>`, the way they used to read a boolean field.
+ fn has_kind(deprecations: &Deprecations, pred: impl Fn(&DeprecationKind) -> bool) -> bool {
+ deprecations.iter().any(pred)
+ }
+
fn find_commit_generation_deprecations(content: &str) -> CommitGenerationDeprecations {
content
.parse::<toml_edit::DocumentMut>()
@@ -3421,7 +3323,10 @@ approved-commands = ["npm install"]
approved-commands = ["npm install"]
"#;
let deprecations = detect_deprecations(content);
- assert!(deprecations.approved_commands);
+ assert!(has_kind(&deprecations, |k| matches!(
+ k,
+ DeprecationKind::ApprovedCommands
+ )));
assert!(!deprecations.is_empty());
}
@@ -3440,17 +3345,7 @@ approved-commands = ["npm install"]
"#;
let info = DeprecationInfo {
config_path: std::path::PathBuf::from("/tmp/test-config.toml"),
- deprecations: Deprecations {
- vars: vec![],
- commit_gen: CommitGenerationDeprecations::default(),
- approved_commands: true,
- select: false,
- ci_section: false,
- no_ff: false,
- no_cd: false,
- pre_hook_table_form: vec![],
- switch_picker_timeout_ms: false,
- },
+ deprecations: vec![DeprecationKind::ApprovedCommands],
label: "User config".to_string(),
main_worktree_path: None,
};
@@ -3815,7 +3710,10 @@ full = true
pager = "delta"
"#;
let deprecations = detect_deprecations(content);
- assert!(deprecations.select);
+ assert!(has_kind(&deprecations, |k| matches!(
+ k,
+ DeprecationKind::Select
+ )));
assert!(!deprecations.is_empty());
}
@@ -3840,17 +3738,7 @@ pager = "delta --paging=never"
"#;
let info = DeprecationInfo {
config_path: std::path::PathBuf::from("/tmp/test-config.toml"),
- deprecations: Deprecations {
- vars: vec![],
- commit_gen: CommitGenerationDeprecations::default(),
- approved_commands: false,
- select: true,
- ci_section: false,
- no_ff: false,
- no_cd: false,
- pre_hook_table_form: vec![],
- switch_picker_timeout_ms: false,
- },
+ deprecations: vec![DeprecationKind::Select],
label: "User config".to_string(),
main_worktree_path: None,
};
@@ -3988,7 +3876,10 @@ pager = "delta"
timeout-ms = 500
"#;
let deprecations = detect_deprecations(content);
- assert!(deprecations.switch_picker_timeout_ms);
+ assert!(has_kind(&deprecations, |k| matches!(
+ k,
+ DeprecationKind::SwitchPickerTimeout
+ )));
assert!(!deprecations.is_empty());
}
@@ -3999,7 +3890,10 @@ timeout-ms = 500
timeout-ms = 300
"#;
let deprecations = detect_deprecations(content);
- assert!(deprecations.switch_picker_timeout_ms);
+ assert!(has_kind(&deprecations, |k| matches!(
+ k,
+ DeprecationKind::SwitchPickerTimeout
+ )));
}
#[test]
@@ -4009,7 +3903,10 @@ timeout-ms = 300
picker = { pager = "delta", timeout-ms = 500 }
"#;
let deprecations = detect_deprecations(content);
- assert!(deprecations.switch_picker_timeout_ms);
+ assert!(has_kind(&deprecations, |k| matches!(
+ k,
+ DeprecationKind::SwitchPickerTimeout
+ )));
}
#[test]
@@ -4030,7 +3927,10 @@ picker = { pager = "delta", timeout-ms = 500 }
pager = "delta"
"#;
let deprecations = detect_deprecations(content);
- assert!(!deprecations.switch_picker_timeout_ms);
+ assert!(!has_kind(&deprecations, |k| matches!(
+ k,
+ DeprecationKind::SwitchPickerTimeout
+ )));
}
#[test]
@@ -4084,10 +3984,7 @@ pager = "delta"
fn test_format_deprecation_warnings_switch_picker_timeout() {
let info = DeprecationInfo {
config_path: std::path::PathBuf::from("/tmp/test-config.toml"),
- deprecations: Deprecations {
- switch_picker_timeout_ms: true,
- ..Deprecations::default()
- },
+ deprecations: vec![DeprecationKind::SwitchPickerTimeout],
label: "User config".to_string(),
main_worktree_path: None,
};
@@ -4108,17 +4005,7 @@ pager = "delta"
fn test_format_deprecation_warnings_no_ff_and_no_cd() {
let info = DeprecationInfo {
config_path: std::path::PathBuf::from("/tmp/test-config.toml"),
- deprecations: Deprecations {
- vars: vec![],
- commit_gen: CommitGenerationDeprecations::default(),
- approved_commands: false,
- select: false,
- ci_section: false,
- no_ff: true,
- no_cd: true,
- pre_hook_table_form: vec![],
- switch_picker_timeout_ms: false,
- },
+ deprecations: vec![DeprecationKind::NoFf, DeprecationKind::NoCd],
label: "User config".to_string(),
main_worktree_path: None,
};
@@ -4130,19 +4017,28 @@ pager = "delta"
#[test]
fn test_detect_no_ff_deprecation() {
let deprecations = detect_deprecations("[merge]\nno-ff = true\n");
- assert!(deprecations.no_ff);
+ assert!(has_kind(&deprecations, |k| matches!(
+ k,
+ DeprecationKind::NoFf
+ )));
}
#[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);
+ assert!(!has_kind(&deprecations, |k| matches!(
+ k,
+ DeprecationKind::NoFf
+ )));
}
#[test]
fn test_detect_no_cd_deprecation() {
let deprecations = detect_deprecations("[switch]\nno-cd = true\n");
- assert!(deprecations.no_cd);
+ assert!(has_kind(&deprecations, |k| matches!(
+ k,
+ DeprecationKind::NoCd
+ )));
}
#[test]
@@ -4152,7 +4048,10 @@ pager = "delta"
no-ff = true
"#;
let deprecations = detect_deprecations(content);
- assert!(deprecations.no_ff);
+ assert!(has_kind(&deprecations, |k| matches!(
+ k,
+ DeprecationKind::NoFf
+ )));
}
#[test]
@@ -4213,7 +4112,10 @@ no-ff = true
pager = "bat"
"#;
let deprecations = detect_deprecations(content);
- assert!(deprecations.select);
+ assert!(has_kind(&deprecations, |k| matches!(
+ k,
+ DeprecationKind::Select
+ )));
}
#[test]
diff --git a/src/config/mod.rs b/src/config/mod.rs
index 648d6a6aa..c1c54c01c 100644
--- a/src/config/mod.rs
+++ b/src/config/mod.rs
@@ -128,7 +128,6 @@ pub use approvals::{Approvals, approvals_path, require_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;
pub use deprecation::compute_migrated_content;
pub use deprecation::copy_approved_commands_to_approvals_file;
@@ -143,6 +142,7 @@ pub use deprecation::{
DEPRECATED_SECTION_KEYS, DeprecatedSection, UnknownKeyKind, classify_unknown_key,
key_belongs_in, nested_key_belongs_in, warn_unknown_fields,
};
+pub use deprecation::{DeprecationKind, Deprecations};
pub use expansion::{
ACTIVE_VARS, ALIAS_ARGS_KEY, DEPRECATED_TEMPLATE_VARS, EXEC_BASE_VARS, REPO_VARS,
TemplateExpandError, ValidationScope, alias_context_filter, base_vars, expand_template,