Skip to content

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

fix(config): report an unparsable user config instead of panicking (#4002)

Worktrunk Botbc2ec124d6be
diff --git a/src/commands/config/show.rs b/src/commands/config/show.rs
index 7abf0a2b0..b11a328ed 100644
--- a/src/commands/config/show.rs
+++ b/src/commands/config/show.rs
@@ -102,7 +102,8 @@ fn handle_config_show_json() -> anyhow::Result<()> {
let user_path = require_config_path()?;
let user_exists = user_path.exists();
let user_config = if user_exists {
- Some(serde_json::to_value(&UserConfig::load()?)?)
+ let config = UserConfig::load().context("Failed to load config")?;
+ Some(serde_json::to_value(&config)?)
} else {
None
};
@@ -519,7 +520,7 @@ fn render_diagnostics(out: &mut String) -> anyhow::Result<()> {
render_version_check(out)?;
// Test commit generation - use effective config for current project
- let config = UserConfig::load()?;
+ let config = UserConfig::load().context("Failed to load config")?;
let project_id = repo.project_identifier().ok();
let commit_config = config.commit_generation(project_id.as_deref());
diff --git a/src/commands/eval.rs b/src/commands/eval.rs
index 8df9003e2..7c8634963 100644
--- a/src/commands/eval.rs
+++ b/src/commands/eval.rs
@@ -3,6 +3,7 @@
//! Evaluates a template expression in the current worktree context and prints
//! the result to stdout.
+use anyhow::Context;
use color_print::cformat;
use worktrunk::config::{UserConfig, VarScope, format_base_variables};
use worktrunk::git::Repository;
@@ -29,7 +30,7 @@ const EVAL_NAME: &str = "eval";
/// composes with either output format.
pub fn step_eval(template: &str, format: SwitchFormat) -> anyhow::Result<()> {
let repo = Repository::current()?;
- let config = UserConfig::load()?;
+ let config = UserConfig::load().context("Failed to load config")?;
let wt = repo.current_worktree();
let branch = wt.branch()?;
diff --git a/src/commands/for_each.rs b/src/commands/for_each.rs
index 96fc9f9d6..0aac03496 100644
--- a/src/commands/for_each.rs
+++ b/src/commands/for_each.rs
@@ -27,6 +27,7 @@
use std::io::Write as _;
use std::process::Stdio;
+use anyhow::Context;
use color_print::cformat;
use worktrunk::config::{UserConfig, VarScope};
use worktrunk::git::{ErrorExt, Repository, WorktreeInfo, WorktrunkError};
@@ -56,7 +57,7 @@ pub fn step_for_each(args: Vec<String>, format: crate::cli::SwitchFormat) -> any
.iter()
.filter(|wt| !wt.is_prunable())
.collect();
- let config = UserConfig::load()?;
+ let config = UserConfig::load().context("Failed to load config")?;
let mut failed: Vec<String> = Vec::new();
let mut json_results: Vec<serde_json::Value> = Vec::new();
diff --git a/src/commands/step/prune.rs b/src/commands/step/prune.rs
index c0b5fc233..88439e1c5 100644
--- a/src/commands/step/prune.rs
+++ b/src/commands/step/prune.rs
@@ -870,7 +870,7 @@ pub fn step_prune(
humantime::parse_duration(min_age).context("Invalid --min-age duration")?;
let repo = Repository::current()?;
- let config = UserConfig::load()?;
+ let config = UserConfig::load().context("Failed to load config")?;
// Capture once at command entry. Reused for every per-branch
// `integration_reason` probe later in this function.
diff --git a/src/commands/step/relocate.rs b/src/commands/step/relocate.rs
index 132c81eb7..75489115e 100644
--- a/src/commands/step/relocate.rs
+++ b/src/commands/step/relocate.rs
@@ -2,6 +2,8 @@
//!
//! See `src/commands/relocate.rs` for the implementation details and algorithm.
+use anyhow::Context;
+
use std::path::PathBuf;
use worktrunk::config::UserConfig;
@@ -36,7 +38,7 @@ pub fn step_relocate(
let json_mode = format == crate::cli::SwitchFormat::Json;
let repo = Repository::current()?;
- let config = UserConfig::load()?;
+ let config = UserConfig::load().context("Failed to load config")?;
let default_branch = repo.default_branch().unwrap_or_default();
// Validate default branch early - needed for main worktree relocation
diff --git a/tests/integration_tests/config_show.rs b/tests/integration_tests/config_show.rs
index 4968ebd94..f3e49bffd 100644
--- a/tests/integration_tests/config_show.rs
+++ b/tests/integration_tests/config_show.rs
@@ -545,6 +545,75 @@ fn test_config_show_empty_system_config(mut repo: TestRepo, temp_home: TempDir)
});
}
+/// A user config that doesn't parse must fail these commands *legibly*.
+///
+/// `UserConfig::load()`'s error is `LoadError::File`'s multi-line Display —
+/// the header plus the TOML parser's caret diagram — flattened into a
+/// `ConfigError` string. Propagated bare with `?`, it reaches anyhow with no
+/// context and no cause chain, which is the one shape `main.rs`'s renderer
+/// has no arm for: it trips that function's `debug_assert!`, so a debug build
+/// panics with exit 101 instead of erroring. A release build still prints the
+/// parse detail in the gutter — what it loses is the header, which becomes a
+/// bare `✗ Command failed` naming neither the config nor the file.
+/// `.context("Failed to load config")` — what 7 of the 22 `UserConfig::load()`
+/// call sites already did, and what all 13 propagating ones do after this —
+/// gives the renderer that header back.
+///
+/// One case per fixed call site, because the `debug_assert!` only fires on a
+/// path something exercises: an uncovered site is one where a future bare `?`
+/// regresses silently. `config show --format json` is the sharpest of them —
+/// the text form of that same command renders a full diagnosis of this exact
+/// file.
+#[rstest]
+#[case::config_show_json(&["config", "show", "--format=json"])]
+#[case::step_prune(&["step", "prune", "--dry-run"])]
+#[case::step_relocate(&["step", "relocate", "--dry-run"])]
+#[case::step_eval(&["step", "eval", "{{ branch }}"])]
+#[case::step_for_each(&["step", "for-each", "--", "true"])]
+#[case::config_show_full(&["config", "show", "--full"])]
+fn test_unparsable_user_config_errors_legibly(
+ repo: TestRepo,
+ temp_home: TempDir,
+ #[case] args: &[&str],
+) {
+ let global_config_dir = temp_home.path().join(".config").join("worktrunk");
+ fs::create_dir_all(&global_config_dir).unwrap();
+ fs::write(global_config_dir.join("config.toml"), "invalid = [toml\n").unwrap();
+
+ let mut cmd = repo.wt_command();
+ cmd.args(args).current_dir(repo.root_path());
+ set_temp_home_env(&mut cmd, temp_home.path());
+ set_xdg_config_path(&mut cmd, temp_home.path());
+ // `config show --full` reaches its `UserConfig::load()` after the version
+ // check, so inject the version the way the other `--full` tests do rather
+ // than letting the case call GitHub. The other cases ignore it.
+ cmd.env("WORKTRUNK_TEST_LATEST_VERSION", env!("CARGO_PKG_VERSION"));
+
+ let output = cmd.output().unwrap();
+ let stderr = String::from_utf8_lossy(&output.stderr);
+
+ // 101 is the debug_assert panic; 1 is the error this should be.
+ assert_eq!(
+ output.status.code(),
+ Some(1),
+ "{args:?} should fail cleanly, not panic; stderr:\n{stderr}"
+ );
+ assert!(
+ !stderr.contains("panicked"),
+ "{args:?} panicked; stderr:\n{stderr}"
+ );
+ // The header the renderer needs, and the parse detail it would otherwise
+ // have replaced with "Command failed".
+ assert!(
+ stderr.contains("Failed to load config"),
+ "{args:?} should name what failed; stderr:\n{stderr}"
+ );
+ assert!(
+ stderr.contains("unclosed array"),
+ "{args:?} should carry the parser's own diagnosis; stderr:\n{stderr}"
+ );
+}
+
/// Test that `config show` displays invalid system config with error details
#[rstest]
fn test_config_show_invalid_system_config(mut repo: TestRepo, temp_home: TempDir) {