Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(config): migrate deprecated keys in env vars and inline tables (#3158)
Maximilian Roos333d630ef4ed
diff --git a/src/config/deprecation.rs b/src/config/deprecation.rsindex 41d61a243..d659c8626 100644--- a/src/config/deprecation.rs+++ b/src/config/deprecation.rs@@ -498,10 +498,11 @@ enum DeprecationRule {/// `[switch.picker]`.////// Most rows rewrite disjoint keys, but one ordering is load-bearing:-/// - `[select]` → `[switch.picker]` precedes the rules that edit keys under-/// `[switch]`: it moves a `timeout-ms` written under `[select]` to where-/// the strip rule looks, and converts an inline `switch` table to a-/// standard one, which the `no-cd` rule's `as_table()` match requires.+/// - `[select]` → `[switch.picker]` precedes the `timeout-ms` strip rule so a+/// `timeout-ms` written under `[select]` is first moved to `switch.picker`,+/// where the strip rule then removes it. The `no-cd` and `timeout-ms` rules+/// both match an inline `switch` directly, so the move is the only ordering+/// dependency — no inline-to-standard conversion is relied on.////// The `[ci]` → `[forge]` rule is order-independent: `[forge]` takes over/// `[ci]`'s explicit document position (see [`migrate_ci_doc`]), so its@@ -936,8 +937,28 @@ fn migrate_negated_bool(table: &mut toml_edit::Table, old_key: &str, new_key: &strue}+/// The inline-table counterpart of [`migrate_negated_bool`], for a section+/// written inline as `merge = { no-ff = true }`. `toml_edit` surfaces a regular+/// `[merge]` section and an inline `merge = { … }` as different node types, so+/// both forms need their own walk (mirroring [`remove_switch_picker_timeout_in`]).+fn migrate_negated_bool_inline(+ table: &mut toml_edit::InlineTable,+ old_key: &str,+ new_key: &str,+) -> bool {+ let Some(old_val) = table.get(old_key).and_then(|v| v.as_bool()) else {+ return false;+ };+ table.remove(old_key);+ if !table.contains_key(new_key) {+ table.insert(new_key, toml_edit::Value::from(!old_val));+ }+ true+}+/// Migrate a negated boolean field in a section and its project-level-/// counterparts, reporting `kind` when any scope changed.+/// counterparts, reporting `kind` when any scope changed. Handles a section+/// written as a standard table (`[merge]`) or inline (`merge = { … }`).fn migrate_negated_bool_doc(doc: &mut toml_edit::DocumentMut,section: &str,@@ -945,11 +966,12 @@ fn migrate_negated_bool_doc(new_key: &str,kind: DeprecationKind,) -> Deprecations {- if 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))+ if for_each_config_table_mut(doc, |_, scope| match scope.get_mut(section) {+ Some(toml_edit::Item::Table(table)) => migrate_negated_bool(table, old_key, new_key),+ Some(toml_edit::Item::Value(toml_edit::Value::InlineTable(table))) => {+ migrate_negated_bool_inline(table, old_key, new_key)+ }+ _ => false,}) {vec![kind]} else {@@ -999,26 +1021,29 @@ fn rename_hook_key(doc: &mut toml_edit::DocumentMut, old_key: &str, new_key: &stmodified}-/// Remove `timeout-ms` from `[switch.picker]` in a table (top-level or project).-/// An emptied `[switch.picker]` section is left in place — it round-trips-/// harmlessly.+/// Remove `timeout-ms` from `switch.picker` in a table (top-level or project).+/// An emptied `picker` is left in place — it round-trips harmlessly.///-/// `[switch.picker]` can be written either as a section (regular table) or-/// inline (`picker = { ... }`); `toml_edit` surfaces these as different node-/// types, so both branches are needed.+/// Both `switch` and its `picker` can be written as a section table or inline+/// (`switch = { picker = { ... } }`); `toml_edit` surfaces these as different+/// node types, so every shape gets its own branch — matching the inline-aware+/// `no-cd`/`no-ff` rules. A `picker` nested inside an inline `switch` is itself+/// always inline.fn remove_switch_picker_timeout_in(table: &mut toml_edit::Table) -> bool {- let Some(picker) = table- .get_mut("switch")- .and_then(|s| s.as_table_mut())- .and_then(|t| t.get_mut("picker"))- else {- return false;- };- match picker {- toml_edit::Item::Table(t) => t.remove("timeout-ms").is_some(),- toml_edit::Item::Value(toml_edit::Value::InlineTable(it)) => {- it.remove("timeout-ms").is_some()- }+ match table.get_mut("switch") {+ // `[switch]` section: `picker` may be a section or inline table.+ Some(toml_edit::Item::Table(switch)) => match switch.get_mut("picker") {+ Some(toml_edit::Item::Table(t)) => t.remove("timeout-ms").is_some(),+ Some(toml_edit::Item::Value(toml_edit::Value::InlineTable(it))) => {+ it.remove("timeout-ms").is_some()+ }+ _ => false,+ },+ // Inline `switch = { picker = { ... } }`: `picker` is itself inline.+ Some(toml_edit::Item::Value(toml_edit::Value::InlineTable(switch))) => switch+ .get_mut("picker")+ .and_then(|p| p.as_inline_table_mut())+ .is_some_and(|it| it.remove("timeout-ms").is_some()),_ => false,}}@@ -2937,9 +2962,10 @@ platform = "github""switch = \"x\"\n\n[select]\npreview = \"p\"\n","commit = \"x\"\n\n[commit-generation]\ncommand = \"llm\"\n",// non-bool negated key is left for the unknown-field warning,- // whether or not the new key is present+ // whether or not the new key is present (section or inline form)"[merge]\nno-ff = \"yes\"\n","[merge]\nff = true\nno-ff = \"yes\"\n",+ "merge = { no-ff = \"yes\" }\n",// empty approved-commands is not deprecated"[projects.\"github.com/u/r\"]\napproved-commands = []\n",];@@ -2958,6 +2984,12 @@ platform = "github"let rewritten = ["[ci]\nplatform = \"github\"\n","[merge]\nff = true\nno-ff = true\n",+ // negated bool written inline (`merge = { no-ff = true }`) migrates+ // like the section form+ "merge = { no-ff = true }\n",+ "switch = { no-cd = true }\n",+ // timeout-ms under an inline `switch` is stripped like the section form+ "switch = { picker = { timeout-ms = 500 } }\n","[select]\ntimeout-ms = 500\n","worktree-path = \"../{{ repo_root }}.{{ branch }}\"\n","[projects.\"github.com/u/r\"]\napproved-commands = [\"npm test\"]\n",@@ -3965,6 +3997,14 @@ no-ff = trueassert!(!result.contains("no-cd"), "Should remove no-cd: {result}");}+ #[test]+ fn test_migrate_negated_bool_inline_table() {+ // A section written inline (`merge = { no-ff = true }`) migrates like the+ // standard `[merge]` form, preserving the inline shape.+ insta::assert_snapshot!(migrate_content("merge = { no-ff = true }\n"), @"merge = { ff = false }");+ insta::assert_snapshot!(migrate_content("switch = { no-cd = true }\n"), @"switch = { cd = false }");+ }+#[test]fn test_migrate_no_ff_project_level() {let content = r#"diff --git a/src/config/user/mod.rs b/src/config/user/mod.rsindex 3d704e2c7..9fe1e17b1 100644--- a/src/config/user/mod.rs+++ b/src/config/user/mod.rs@@ -204,6 +204,36 @@ fn resolve_env_overlay(file_table: &toml::Table, vars: &[EnvVar]) -> toml::Tableoverlay}+/// Canonicalize a built env-var overlay through the same deprecation migration+/// as config files and `--config-set`, so a deprecated env var such as+/// `WORKTRUNK__MERGE__NO_FF` (which resolves to the deprecated key+/// `merge.no-ff`) takes effect as `merge.ff` instead of falling through as an+/// unknown field. Migrating before the deep-merge keeps env winning over a+/// lower layer's canonical key — the same fragment-before-merge ordering+/// [`UserConfig::apply_cli_overrides`] uses.+///+/// The rewrite is silent, matching the other ephemeral layer: an env overlay+/// has no file for `wt config update` to materialize.+///+/// Round-trips through [`super::deprecation::migrate_content`]'s string form.+/// The overlay's leaves are the scalars [`try_parse_value`] produces (bool,+/// int, float, string) plus nested tables, so it always serializes, and+/// `migrate_content` always returns valid TOML — mirroring the same+/// post-migration reparse `expect` in [`load_config_file`].+///+/// Canonicalization can surface a type mismatch the deprecated name hid: an+/// unknown key like `commit-generation.command = 42` deserializes (unknown+/// fields are ignored) but the migrated `commit.generation.command = 42` does+/// not, so it joins the whole-env-layer `LoadError::Env` drop at the call site+/// instead of being silently ignored — the same outcome a type-mismatched value+/// in a *canonical* env var already produces.+fn migrate_env_overlay(overlay: toml::Table) -> toml::Table {+ let serialized = toml::to_string(&overlay).expect("env overlay serializes to TOML");+ super::deprecation::migrate_content(&serialized)+ .parse::<toml::Table>()+ .expect("migrate_content returns valid TOML")+}+/// Try to coerce a string into a typed TOML value (bool → i64 → f64 → string).fn try_parse_value(s: &str) -> toml::Value {if s.eq_ignore_ascii_case("true") {@@ -495,7 +525,7 @@ impl UserConfig {// field. This handles mixed cases (e.g., WORKTRUNK__LIST__TIMEOUT_MS=100// needs Integer for u64, WORKTRUNK_WORKTREE_PATH=42 needs String).let file_table = merged_table.clone();- let env_overlay = resolve_env_overlay(&file_table, &env_vars);+ let env_overlay = migrate_env_overlay(resolve_env_overlay(&file_table, &env_vars));deep_merge_table(&mut merged_table, env_overlay);// Env overlay broke deserialization — fall back to file-only config.diff --git a/src/config/user/tests.rs b/src/config/user/tests.rsindex 64d8cadda..ab99c4565 100644--- a/src/config/user/tests.rs+++ b/src/config/user/tests.rs@@ -2614,6 +2614,24 @@ fn test_try_parse_value() {);}+#[test]+fn test_env_overlay_migrates_deprecated_key() {+ use super::{EnvVar, migrate_env_overlay, resolve_env_overlay, try_parse_value};+ // `WORKTRUNK__MERGE__NO_FF=true` resolves to the deprecated key+ // `merge.no-ff`. The env overlay runs through the same deprecation migration+ // as config files and `--config-set`, so it takes effect as `merge.ff =+ // false` instead of falling through as an unknown field.+ let var = EnvVar {+ name: "WORKTRUNK__MERGE__NO_FF".to_string(),+ segments: vec!["merge".to_string(), "no-ff".to_string()],+ typed_value: try_parse_value("true"),+ raw_value: "true".to_string(),+ };+ let overlay = migrate_env_overlay(resolve_env_overlay(&toml::Table::new(), &[var]));+ let config: UserConfig = toml::Value::Table(overlay).try_into().unwrap();+ assert_eq!(config.merge.ff, Some(false));+}+// =========================================================================// finalize() — defensive fallback// =========================================================================diff --git a/tests/integration_tests/list_config.rs b/tests/integration_tests/list_config.rsindex 87d30d623..56748fec3 100644--- a/tests/integration_tests/list_config.rs+++ b/tests/integration_tests/list_config.rs@@ -427,6 +427,28 @@ fn test_list_config_env_override_bad_value_warns_on_stderr(repo: TestRepo) {});}+/// A *deprecated* env var is canonicalized before it is applied, so a+/// type-mismatched value the deprecated name hid now surfaces.+/// `WORKTRUNK__COMMIT_GENERATION__COMMAND=42` migrates to+/// `commit.generation.command = 42`, which fails to deserialize (the field is a+/// String), so the whole env layer is dropped with a `LoadError::Env` warning+/// naming the var — the same contract as a bad value in a canonical env var.+/// File config survives. (Pre-migration the unknown key was silently ignored.)+#[rstest]+fn test_list_config_env_deprecated_type_mismatch_drops_layer(repo: TestRepo) {+ fs::write(repo.test_config_path(), "[list]\nbranches = true\n").unwrap();++ let settings = setup_snapshot_settings(&repo);+ settings.bind(|| {+ let mut cmd = wt_command();+ repo.configure_wt_cmd(&mut cmd);+ cmd.env("WORKTRUNK__COMMIT_GENERATION__COMMAND", "42");+ cmd.arg("list").current_dir(repo.root_path());++ assert_cmd_snapshot!(cmd);+ });+}+/// Numeric-looking env var values for String fields must not break config/// loading. WORKTRUNK_WORKTREE_PATH=42 should be treated as the string "42",/// not the integer 42 (which would fail to deserialize into Option<String>).diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rsindex 8d9c4481f..9648103f5 100644--- a/tests/integration_tests/switch.rs+++ b/tests/integration_tests/switch.rs@@ -6438,6 +6438,24 @@ fn test_switch_config_set_migrates_deprecated_no_cd(repo: TestRepo) {);}+/// The `WORKTRUNK_*` env layer migrates deprecated keys the same way:+/// `WORKTRUNK__SWITCH__NO_CD=true` resolves to the deprecated `switch.no-cd`,+/// which is canonicalized to `switch.cd = false` and suppresses the cd+/// directive — the output omits the "Cannot change directory" line. Without+/// migration the env var would fall through as an unknown field and the line+/// would appear.+#[rstest]+fn test_switch_env_var_migrates_deprecated_no_cd(repo: TestRepo) {+ repo.run_git(&["branch", "env-no-cd"]);++ let settings = setup_snapshot_settings(&repo);+ settings.bind(|| {+ let mut cmd = make_snapshot_cmd(&repo, "switch", &["env-no-cd"], None);+ cmd.env("WORKTRUNK__SWITCH__NO_CD", "true");+ assert_cmd_snapshot!("switch_env_var_migrates_deprecated_no_cd", cmd);+ });+}+/// Test that worktrunk works correctly when `worktree.useRelativePaths` is enabled.////// Git 2.48+ supports `worktree.useRelativePaths`, which stores relative paths in thediff --git a/tests/snapshots/integration__integration_tests__list_config__list_config_env_deprecated_type_mismatch_drops_layer.snap b/tests/snapshots/integration__integration_tests__list_config__list_config_env_deprecated_type_mismatch_drops_layer.snapnew file mode 100644index 000000000..45d81ff5d--- /dev/null+++ b/tests/snapshots/integration__integration_tests__list_config__list_config_env_deprecated_type_mismatch_drops_layer.snap@@ -0,0 +1,58 @@+---+source: tests/integration_tests/list_config.rs+info:+ program: wt+ args:+ - list+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"+ PATH: "[PATH]"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_BASH_INSTALLED: "0"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_FISH_INSTALLED: "0"+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"+ WORKTRUNK__COMMIT_GENERATION__COMMAND: "42"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----+ [1mBranch[0m [1mStatus[0m [1mHEAD±[0m [1mmain↕[0m [1mRemote⇅[0m [1mPath[0m [1mCommit[0m [1mAge[0m [1mMessage[0m+@ main [2m^[22m[2m|[22m [2m|[0m . [2m05a4a45d[0m [2m16h[0m [2mInitial commit[0m++ feature-a [2m↑[22m [32m↑1[0m ../repo.feature-a [2m1b87d473[0m [2m16h[0m [2mAdd feature-a file[0m++ feature-b [2m↑[22m [32m↑1[0m ../repo.feature-b [2mf62940fc[0m [2m16h[0m [2mAdd feature-b file[0m++ feature-c [2m↑[22m [32m↑1[0m ../repo.feature-c [2m345c7c93[0m [2m16h[0m [2mAdd feature-c file[0m++[2m○[22m [2mShowing 4 worktrees, 3 ahead[0m++----- stderr -----+[33m▲[39m [33mIgnoring env var overrides: WORKTRUNK__COMMIT_GENERATION__COMMAND=42[39m+[107m [0m invalid type: integer `42`, expected a string+[107m [0m in `commit.generation.command`diff --git a/tests/snapshots/integration__integration_tests__switch__switch_env_var_migrates_deprecated_no_cd.snap b/tests/snapshots/integration__integration_tests__switch__switch_env_var_migrates_deprecated_no_cd.snapnew file mode 100644index 000000000..73d31cd8f--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_env_var_migrates_deprecated_no_cd.snap@@ -0,0 +1,50 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - switch+ - env-no-cd+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"+ PATH: "[PATH]"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_BASH_INSTALLED: "0"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_FISH_INSTALLED: "0"+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"+ WORKTRUNK__SWITCH__NO_CD: "true"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+[32m✓[39m [32mCreated worktree for [1menv-no-cd[22m @ [1m_REPO_.env-no-cd[22m[39m