Skip to content

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

config: parse typed env-var overrides and surface load failures (#2062)

Maximilian Roos2000d46f7715
diff --git a/src/config/user/mod.rs b/src/config/user/mod.rs
index 7e7faf02f..9bc7880e1 100644
--- a/src/config/user/mod.rs
+++ b/src/config/user/mod.rs
@@ -179,12 +179,20 @@ impl UserConfig {
// - prefix_separator("_"): strip prefix with single underscore (WORKTRUNK_ → key)
// - separator("__"): double underscore for nested fields (COMMIT__GENERATION__COMMAND → commit.generation.command)
// - convert_case(Kebab): converts snake_case to kebab-case to match serde field names
+ // - try_parsing(true): coerce env-var strings into bool/i64/f64 so any
+ // non-String typed field (e.g. `list.timeout-ms: Option<u64>`) accepts
+ // overrides like `WORKTRUNK__LIST__TIMEOUT_MS=30`. String fields still
+ // round-trip through `into_string()` in the config deserializer, so
+ // `WORKTRUNK_WORKTREE_PATH=42` stringifies back to "42" as expected.
+ // Without this, a single typed override fails the whole config deserialize
+ // and silently falls back to defaults.
// Example: WORKTRUNK_WORKTREE_PATH → worktree-path
builder = builder.add_source(
config::Environment::with_prefix("WORKTRUNK")
.prefix_separator("_")
.separator("__")
- .convert_case(Case::Kebab),
+ .convert_case(Case::Kebab)
+ .try_parsing(true),
);
// The config crate's `preserve_order` feature ensures TOML insertion order
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index 6aea33c45..947fcd3f1 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -383,10 +383,34 @@ impl Repository {
/// Prefer [`config()`](Self::config) for behavior settings. This is only needed
/// for operations that require the full `UserConfig` (e.g., path template formatting,
/// approval state, hook resolution).
+ ///
+ /// Falls back to defaults on load errors so a single bad field does not break
+ /// unrelated commands, but surfaces the error on stderr — a silent `log::warn!`
+ /// would hide it from anyone not running with `RUST_LOG=warn`.
pub fn user_config(&self) -> &UserConfig {
self.cache.user_config.get_or_init(|| {
UserConfig::load()
- .inspect_err(|err| log::warn!("Failed to load user config, using defaults: {err}"))
+ .inspect_err(|err| {
+ // Include the config file path so users know where to look.
+ // Serde's flatten/Option wrapping loses the offending field
+ // name inside the config crate's error, so the file path is
+ // the most reliable pointer we can give.
+ let path_hint = crate::config::config_path()
+ .map(|p| format!(" at {}", crate::path::format_path_for_display(&p)))
+ .unwrap_or_default();
+ crate::styling::eprintln!(
+ "{}",
+ crate::styling::warning_message(format!(
+ "Failed to load user config{path_hint}, using defaults: {err}"
+ ))
+ );
+ crate::styling::eprintln!(
+ "{}",
+ crate::styling::hint_message(
+ "If the value came from a WORKTRUNK_* env var, check those too.",
+ )
+ );
+ })
.unwrap_or_default()
})
}
diff --git a/tests/integration_tests/list_config.rs b/tests/integration_tests/list_config.rs
index 14130a2c4..6f6bc040c 100644
--- a/tests/integration_tests/list_config.rs
+++ b/tests/integration_tests/list_config.rs
@@ -1,7 +1,8 @@
//! Tests for `wt list` command with user config
use crate::common::{
- TestRepo, repo, set_temp_home_env, setup_snapshot_settings_with_home, temp_home, wt_command,
+ TestRepo, repo, set_temp_home_env, setup_snapshot_settings, setup_snapshot_settings_with_home,
+ temp_home, wt_command,
};
use insta_cmd::assert_cmd_snapshot;
use rstest::rstest;
@@ -441,6 +442,83 @@ task-timeout-ms = 0
);
}
+/// Regression: setting a typed env-var override (e.g. `WORKTRUNK__LIST__TIMEOUT_MS`)
+/// must not wipe unrelated fields in the same section.
+///
+/// Previously, the `config` crate's Environment source emitted values as strings,
+/// so `timeout-ms: Option<u64>` failed to deserialize and the whole `UserConfig`
+/// silently fell back to defaults — dropping `list.branches = true` and hiding
+/// the `feature` branch from `wt list` output.
+///
+/// The snapshot captures both stdout (feature branch present with the
+/// "1 branches" summary line) and the empty stderr (no silent fallback
+/// warning) — if the fix regresses, the diff shows the missing branch.
+#[rstest]
+fn test_list_config_env_override_preserves_file_fields(repo: TestRepo) {
+ // Create a branch without a worktree
+ repo.run_git(&["branch", "feature"]);
+
+ // Write to the test config path (the one `configure_wt_cmd` points
+ // WORKTRUNK_CONFIG_PATH at); an XDG config under a temp HOME would be
+ // ignored because WORKTRUNK_CONFIG_PATH takes precedence.
+ fs::write(
+ repo.test_config_path(),
+ r#"[list]
+branches = true
+"#,
+ )
+ .unwrap();
+
+ let settings = setup_snapshot_settings(&repo);
+ settings.bind(|| {
+ let mut cmd = wt_command();
+ repo.configure_wt_cmd(&mut cmd);
+ // Typed env-var override that must coerce a string → u64. The bug was
+ // at deserialize time, so any value reproduces it; 0 (disabled) is
+ // chosen so the timeout doesn't affect output.
+ cmd.env("WORKTRUNK__LIST__TIMEOUT_MS", "0");
+ cmd.arg("list").current_dir(repo.root_path());
+
+ assert_cmd_snapshot!(cmd);
+ });
+}
+
+/// When `UserConfig::load()` fails (e.g. user config has a wrong field type),
+/// `Repository::user_config()` falls back to defaults but must surface the
+/// error on stderr — a silent `log::warn!` would hide it from anyone not
+/// running with `RUST_LOG=warn`.
+///
+/// The snapshot pins both the warning prefix (`▲`) and the exact wording so
+/// an accidental downgrade back to `log::warn!` or a rewording is caught.
+#[rstest]
+fn test_list_config_malformed_config_warns_on_stderr(repo: TestRepo) {
+ // `list.branches` is typed `Option<bool>`; a string here fails serde
+ // deserialization and triggers the fallback path.
+ fs::write(
+ repo.test_config_path(),
+ r#"[list]
+branches = "not-a-bool"
+"#,
+ )
+ .unwrap();
+
+ let mut settings = setup_snapshot_settings(&repo);
+ // `format_path_for_display` produces different strings depending on
+ // whether HOME contains the tempdir — macOS tempdir lives under
+ // /var/folders (absolute), Linux CI tempdir lives under HOME (tilde).
+ // The default `~/…` → `_PARENT_/…` filter only fires in the tilde case,
+ // so normalize the Linux form back to `[TEST_CONFIG]` for a stable
+ // snapshot across platforms.
+ settings.add_filter(r"_PARENT_/[^\s,]*test-config\.toml", "[TEST_CONFIG]");
+ settings.bind(|| {
+ let mut cmd = wt_command();
+ repo.configure_wt_cmd(&mut cmd);
+ cmd.arg("list").current_dir(repo.root_path());
+
+ assert_cmd_snapshot!(cmd);
+ });
+}
+
/// Test that --full disables the task timeout.
#[rstest]
fn test_list_config_timeout_disabled_with_full(repo: TestRepo, temp_home: TempDir) {
diff --git a/tests/snapshots/integration__integration_tests__list_config__list_config_env_override_preserves_file_fields.snap b/tests/snapshots/integration__integration_tests__list_config__list_config_env_override_preserves_file_fields.snap
new file mode 100644
index 000000000..49f4ba995
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__list_config__list_config_env_override_preserves_file_fields.snap
@@ -0,0 +1,54 @@
+---
+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_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ NO_COLOR: ""
+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
+ PATH: "[PATH]"
+ PSModulePath: ""
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WORKTRUNK__LIST__TIMEOUT_MS: "0"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+ Branch Status HEAD± main↕ Remote⇅ Path Commit Age Message
+@ main ^| | . 05a4a45d 16h Initial commit
++ feature-a ↑ ↑1 ../repo.feature-a 1b87d473 16h Add feature-a file
++ feature-b ↑ ↑1 ../repo.feature-b f62940fc 16h Add feature-b file
++ feature-c ↑ ↑1 ../repo.feature-c 345c7c93 16h Add feature-c file
+ feature /_ 05a4a45d 16h Initial commit
+
+○ Showing 4 worktrees, 1 branches, 3 ahead
+
+----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__list_config__list_config_malformed_config_warns_on_stderr.snap b/tests/snapshots/integration__integration_tests__list_config__list_config_malformed_config_warns_on_stderr.snap
new file mode 100644
index 000000000..2906c9dfe
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__list_config__list_config_malformed_config_warns_on_stderr.snap
@@ -0,0 +1,54 @@
+---
+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_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ NO_COLOR: ""
+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
+ PATH: "[PATH]"
+ PSModulePath: ""
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+ Branch Status HEAD± main↕ Remote⇅ Path Commit Age Message
+@ main ^| | . 05a4a45d 16h Initial commit
++ feature-a ↑ ↑1 ../repo.feature-a 1b87d473 16h Add feature-a file
++ feature-b ↑ ↑1 ../repo.feature-b f62940fc 16h Add feature-b file
++ feature-c ↑ ↑1 ../repo.feature-c 345c7c93 16h Add feature-c file
+
+○ Showing 4 worktrees, 3 ahead
+
+----- stderr -----
+▲ Failed to load user config at [TEST_CONFIG], using defaults: invalid type: string "not-a-bool", expected a boolean
+↳ If the value came from a WORKTRUNK_* env var, check those too.