Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor: remove config crate, inline OverridableConfig (#2087)
Maximilian Roos81182a687a8d
diff --git a/Cargo.lock b/Cargo.lockindex 40965dd11..1a9e9875d 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -205,9 +205,6 @@ name = "bitflags"version = "2.10.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3"-dependencies = [- "serde_core",-][[package]]name = "block-buffer"@@ -406,22 +403,6 @@ version = "1.0.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75"-[[package]]-name = "config"-version = "0.15.22"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8e68cfe19cd7d23ffde002c24ffa5cda73931913ef394d5eaaa32037dc940c0c"-dependencies = [- "convert_case 0.6.0",- "indexmap",- "pathdiff",- "ron",- "serde_core",- "serde_json",- "toml",- "winnow 1.0.0",-]-[[package]]name = "console"version = "0.16.3"@@ -439,15 +420,6 @@ version = "0.10.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"-[[package]]-name = "convert_case"-version = "0.6.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ec182b0ca2f35d8fc196cf3404988fd8b8c739a4d270ff118a398feb0cbec1ca"-dependencies = [- "unicode-segmentation",-]-[[package]]name = "convert_case"version = "0.10.0"@@ -773,7 +745,7 @@ version = "2.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb"dependencies = [- "convert_case 0.10.0",+ "convert_case","proc-macro2","quote","rustc_version",@@ -1911,21 +1883,6 @@ version = "1.9.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ba39f3699c378cd8970968dcbff9c43159ea4cfbd88d43c00b22f2ef10a435d2"-[[package]]-name = "ron"-version = "0.12.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "fd490c5b18261893f14449cbd28cb9c0b637aebf161cd77900bfdedaff21ec32"-dependencies = [- "bitflags 2.10.0",- "indexmap",- "once_cell",- "serde",- "serde_derive",- "typeid",- "unicode-ident",-]-[[package]]name = "rstest"version = "0.26.1"@@ -2667,12 +2624,6 @@ version = "0.1.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4ae62f7eae5eb549c71b76658648b72cc6111f2d87d24a1e31fa907f4943e3ce"-[[package]]-name = "typeid"-version = "1.0.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c"-[[package]]name = "typenum"version = "1.19.0"@@ -3189,7 +3140,6 @@ dependencies = ["clap","clap_complete","color-print",- "config","criterion","crossbeam-channel","crossterm",diff --git a/Cargo.toml b/Cargo.tomlindex 1cd9358aa..30d85b12a 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -71,8 +71,6 @@ askama = { version = "0.15", default-features = false, features = ["derive", "stchrono = "0.4"clap = { version = "4.6", features = ["derive", "unstable-ext", "wrap_help"] }clap_complete = { version = "4.6", features = ["unstable-dynamic"] }-# Only enable TOML format - saves ~250KB by excluding yaml, ron, json5, ini parsers-config = { version = "0.15", default-features = false, features = ["toml", "convert-case", "preserve_order"] }crossbeam-channel = "0.5"crossterm = "0.29"env_logger = "0.11"diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rsindex 2c6dbe50d..15cb47e12 100644--- a/src/commands/hook_commands.rs+++ b/src/commands/hook_commands.rs@@ -508,7 +508,7 @@ fn render_user_hooks(// Collect all user hooks (global hooks from the user config file)// Note: uses overrides.hooks for display, not the merged hooks() accessor.// get() handles the post-create → pre-start deprecation merge.- let user_hooks = &config.configs.hooks;+ let user_hooks = &config.hooks;let hooks: Vec<_> = HookType::iter().filter_map(|ht| user_hooks.get(ht).map(|cfg| (ht, cfg))).collect();diff --git a/src/completion.rs b/src/completion.rsindex f7642b24f..93bb08149 100644--- a/src/completion.rs+++ b/src/completion.rs@@ -257,7 +257,7 @@ impl ValueCompleter for HookCommandCompleter {// Load user config and add user hook namesif let Ok(user_config) = UserConfig::load()- && let Some(config) = user_config.configs.hooks.get(hook_type)+ && let Some(config) = user_config.hooks.get(hook_type){add_named_commands(&mut candidates, config);}diff --git a/src/config/approvals.rs b/src/config/approvals.rsindex 94f0c0552..33656d1e7 100644--- a/src/config/approvals.rs+++ b/src/config/approvals.rs@@ -22,9 +22,10 @@use std::collections::BTreeMap;use std::path::{Path, PathBuf};-use config::ConfigError;use serde::{Deserialize, Serialize};+use super::ConfigError;+use crate::config::deprecation::normalize_template_vars;use crate::path::format_path_for_display;@@ -99,14 +100,14 @@ impl Approvals {/// Load approvals from a specific file path.fn load_from_file(path: &Path) -> Result<Self, ConfigError> {let content = std::fs::read_to_string(path).map_err(|e| {- ConfigError::Message(format!(+ ConfigError(format!("Failed to read approvals file {}: {}",format_path_for_display(path),e))})?;let approvals: Self = toml::from_str(&content).map_err(|e| {- ConfigError::Message(format!(+ ConfigError(format!("Failed to parse approvals file {}: {}",format_path_for_display(path),e@@ -155,9 +156,8 @@ impl Approvals {/// Save approvals to a specific file path.pub fn save_to(&self, path: &Path) -> Result<(), ConfigError> {if let Some(parent) = path.parent() {- std::fs::create_dir_all(parent).map_err(|e| {- ConfigError::Message(format!("Failed to create approvals directory: {e}"))- })?;+ std::fs::create_dir_all(parent)+ .map_err(|e| ConfigError(format!("Failed to create approvals directory: {e}")))?;}let mut doc = toml_edit::DocumentMut::new();@@ -188,7 +188,7 @@ impl Approvals {};std::fs::write(path, output)- .map_err(|e| ConfigError::Message(format!("Failed to write approvals file: {e}")))?;+ .map_err(|e| ConfigError(format!("Failed to write approvals file: {e}")))?;Ok(())}@@ -242,7 +242,7 @@ impl Approvals {let path = match approvals_path {Some(p) => p.to_path_buf(),None => self::approvals_path().ok_or_else(|| {- ConfigError::Message(+ ConfigError("Cannot determine approvals path. Set $HOME or $XDG_CONFIG_HOME".to_string(),)})?,@@ -266,7 +266,7 @@ impl Approvals {/// Extract approved-commands from a specific config file.pub(crate) fn load_from_config_file(config_path: &Path) -> Result<Self, ConfigError> {let content = std::fs::read_to_string(config_path).map_err(|e| {- ConfigError::Message(format!(+ ConfigError(format!("Failed to read config file {}: {}",format_path_for_display(config_path),e@@ -274,7 +274,7 @@ impl Approvals {})?;let config: super::UserConfig = toml::from_str(&content).map_err(|e| {- ConfigError::Message(format!(+ ConfigError(format!("Failed to parse config file {}: {}",format_path_for_display(config_path),ediff --git a/src/config/mod.rs b/src/config/mod.rsindex c1a1dac06..329301faf 100644--- a/src/config/mod.rs+++ b/src/config/mod.rs@@ -70,6 +70,21 @@ impl WorktrunkConfig for ProjectConfig {}}+/// Configuration error type.+///+/// Replaces the `config` crate's `ConfigError` with a simple string wrapper.+/// Every usage was `ConfigError::Message(String)` — no other variants were used.+#[derive(Debug)]+pub struct ConfigError(pub String);++impl std::fmt::Display for ConfigError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.write_str(&self.0)+ }+}++impl std::error::Error for ConfigError {}+// Re-export public typespub use approvals::{Approvals, approvals_path};pub use commands::{Command, CommandConfig, HookStep, append_aliases};@@ -126,10 +141,7 @@ mod tests {// With worktree-path setlet config = UserConfig {- configs: OverridableConfig {- worktree_path: Some("custom/{{ branch }}".to_string()),- ..Default::default()- },+ worktree_path: Some("custom/{{ branch }}".to_string()),..Default::default()};assert_snapshot!(toml::to_string(&config).unwrap(), @r#"@@ -143,7 +155,7 @@ mod tests {fn test_default_config() {let config = UserConfig::default();// worktree_path is None by default, but the getter returns the default- assert!(config.configs.worktree_path.is_none());+ assert!(config.worktree_path.is_none());assert_eq!(config.worktree_path(),"{{ repo_path }}/../{{ repo }}.{{ branch | sanitize }}"@@ -155,10 +167,7 @@ mod tests {fn test_format_worktree_path() {let test = test_repo();let config = UserConfig {- configs: OverridableConfig {- worktree_path: Some("{{ main_worktree }}.{{ branch }}".to_string()),- ..Default::default()- },+ worktree_path: Some("{{ main_worktree }}.{{ branch }}".to_string()),..Default::default()};assert_eq!(@@ -173,10 +182,7 @@ mod tests {fn test_format_worktree_path_custom_template() {let test = test_repo();let config = UserConfig {- configs: OverridableConfig {- worktree_path: Some("{{ main_worktree }}-{{ branch }}".to_string()),- ..Default::default()- },+ worktree_path: Some("{{ main_worktree }}-{{ branch }}".to_string()),..Default::default()};assert_eq!(@@ -191,10 +197,7 @@ mod tests {fn test_format_worktree_path_only_branch() {let test = test_repo();let config = UserConfig {- configs: OverridableConfig {- worktree_path: Some(".worktrees/{{ main_worktree }}/{{ branch }}".to_string()),- ..Default::default()- },+ worktree_path: Some(".worktrees/{{ main_worktree }}/{{ branch }}".to_string()),..Default::default()};assert_eq!(@@ -210,10 +213,7 @@ mod tests {let test = test_repo();// Use {{ branch | sanitize }} to replace slashes with dasheslet config = UserConfig {- configs: OverridableConfig {- worktree_path: Some("{{ main_worktree }}.{{ branch | sanitize }}".to_string()),- ..Default::default()- },+ worktree_path: Some("{{ main_worktree }}.{{ branch | sanitize }}".to_string()),..Default::default()};assert_eq!(@@ -228,12 +228,9 @@ mod tests {fn test_format_worktree_path_with_multiple_slashes() {let test = test_repo();let config = UserConfig {- configs: OverridableConfig {- worktree_path: Some(- ".worktrees/{{ main_worktree }}/{{ branch | sanitize }}".to_string(),- ),- ..Default::default()- },+ worktree_path: Some(+ ".worktrees/{{ main_worktree }}/{{ branch | sanitize }}".to_string(),+ ),..Default::default()};assert_eq!(@@ -249,12 +246,9 @@ mod tests {let test = test_repo();// Windows-style path separators should also be sanitizedlet config = UserConfig {- configs: OverridableConfig {- worktree_path: Some(- ".worktrees/{{ main_worktree }}/{{ branch | sanitize }}".to_string(),- ),- ..Default::default()- },+ worktree_path: Some(+ ".worktrees/{{ main_worktree }}/{{ branch | sanitize }}".to_string(),+ ),..Default::default()};assert_eq!(@@ -270,10 +264,7 @@ mod tests {let test = test_repo();// {{ branch }} without filter gives raw branch namelet config = UserConfig {- configs: OverridableConfig {- worktree_path: Some("{{ main_worktree }}.{{ branch }}".to_string()),- ..Default::default()- },+ worktree_path: Some("{{ main_worktree }}.{{ branch }}".to_string()),..Default::default()};assert_eq!(@@ -545,11 +536,7 @@ template-file = "~/file.txt"// The deserialization should succeed, but validation in load() would fail// Since we can't easily test load() without env vars, we verify the fields deserializeif let Ok(config) = config_result {- let generation = config- .configs- .commit- .as_ref()- .and_then(|c| c.generation.as_ref());+ let generation = config.commit.as_ref().and_then(|c| c.generation.as_ref());// Verify validation logic: both fields should not be Somelet has_both = generation.map(|g| g.template.is_some() && g.template_file.is_some())@@ -579,11 +566,7 @@ squash-template-file = "~/file.txt"// The deserialization should succeed, but validation in load() would fail// Since we can't easily test load() without env vars, we verify the fields deserializeif let Ok(config) = config_result {- let generation = config- .configs- .commit- .as_ref()- .and_then(|c| c.generation.as_ref());+ let generation = config.commit.as_ref().and_then(|c| c.generation.as_ref());// Verify validation logic: both fields should not be Somelet has_both = generation.map(|g| g.squash_template.is_some() && g.squash_template_file.is_some())@@ -676,7 +659,6 @@ lint = "cargo clippy"// Check post-createlet post_create = config- .configs.hooks.post_create.expect("post-create should be present");@@ -685,11 +667,7 @@ lint = "cargo clippy"assert_eq!(commands[0].name.as_deref(), Some("log"));// Check pre-merge (multiple commands preserve order)- let pre_merge = config- .configs- .hooks- .pre_merge- .expect("pre-merge should be present");+ let pre_merge = config.hooks.pre_merge.expect("pre-merge should be present");let commands: Vec<_> = pre_merge.commands().collect();assert_eq!(commands.len(), 2);assert_eq!(commands[0].name.as_deref(), Some("test"));@@ -705,7 +683,6 @@ post-create = "npm install"let config: UserConfig = toml::from_str(toml_str).unwrap();let post_create = config- .configs.hooks.post_create.expect("post-create should be present");diff --git a/src/config/project.rs b/src/config/project.rsindex ac5c81e85..85e704fe4 100644--- a/src/config/project.rs+++ b/src/config/project.rs@@ -4,10 +4,10 @@use std::collections::BTreeMap;-use config::ConfigError;use schemars::JsonSchema;use serde::{Deserialize, Serialize};+use super::ConfigError;use super::commands::CommandConfig;use super::{CopyIgnoredConfig, HooksConfig, StepConfig};@@ -200,7 +200,7 @@ impl ProjectConfig {) -> Result<Option<Self>, ConfigError> {let config_path = match repo.project_config_path()- .map_err(|e| ConfigError::Message(format!("Failed to get config path: {}", e)))?+ .map_err(|e| ConfigError(format!("Failed to get config path: {}", e)))?{Some(path) if path.exists() => path,_ => return Ok(None),@@ -208,7 +208,7 @@ impl ProjectConfig {// Load directly with toml crate to preserve insertion order (with preserve_order feature)let contents = std::fs::read_to_string(&config_path)- .map_err(|e| ConfigError::Message(format!("Failed to read config file: {}", e)))?;+ .map_err(|e| ConfigError(format!("Failed to read config file: {}", e)))?;// Check for deprecated template variables and create migration file if needed// Only write migration file in main worktree, not linked worktrees@@ -234,7 +234,7 @@ impl ProjectConfig {}let config: ProjectConfig = toml::from_str(&contents).map_err(|e| {- ConfigError::Message(format!(+ ConfigError(format!("Project config at {} failed to parse:\n{e}",crate::path::format_path_for_display(&config_path),))diff --git a/src/config/user/accessors.rs b/src/config/user/accessors.rsindex be3b0fb85..6b566f16c 100644--- a/src/config/user/accessors.rs+++ b/src/config/user/accessors.rs@@ -43,22 +43,21 @@ impl UserConfig {/// Returns the worktree path template, falling back to the default if not set.pub fn worktree_path(&self) -> String {- self.configs- .worktree_path+ self.worktree_path.clone().unwrap_or_else(default_worktree_path)}/// Returns true if the user has explicitly set a custom global worktree-path.pub fn has_custom_worktree_path(&self) -> bool {- self.configs.worktree_path.is_some()+ self.worktree_path.is_some()}/// Returns true if the given project has an explicit worktree-path override.pub fn has_project_worktree_path(&self, project: &str) -> bool {self.projects.get(project)- .and_then(|p| p.overrides.worktree_path.as_ref())+ .and_then(|p| p.worktree_path.as_ref()).is_some()}@@ -69,7 +68,7 @@ impl UserConfig {pub fn worktree_path_for_project(&self, project: &str) -> String {self.projects.get(project)- .and_then(|p| p.overrides.worktree_path.clone())+ .and_then(|p| p.worktree_path.clone()).unwrap_or_else(|| self.worktree_path())}@@ -82,13 +81,11 @@ impl UserConfig {pub fn commit_generation(&self, project: Option<&str>) -> CommitGenerationConfig {self.merged_project_config(project,- self.configs- .commit+ self.commit.as_ref().and_then(|commit| commit.generation.as_ref()),|config| {config- .overrides.commit.as_ref().and_then(|commit| commit.generation.as_ref())@@ -102,9 +99,7 @@ impl UserConfig {/// Merges project-specific settings with global settings, where project/// settings take precedence for fields that are set.pub fn list(&self, project: Option<&str>) -> Option<ListConfig> {- self.merged_project_config(project, self.configs.list.as_ref(), |config| {- config.overrides.list.as_ref()- })+ self.merged_project_config(project, self.list.as_ref(), |config| config.list.as_ref())}/// Returns the commit config for a specific project.@@ -112,8 +107,8 @@ impl UserConfig {/// Merges project-specific settings with global settings, where project/// settings take precedence for fields that are set.pub fn commit(&self, project: Option<&str>) -> Option<CommitConfig> {- self.merged_project_config(project, self.configs.commit.as_ref(), |config| {- config.overrides.commit.as_ref()+ self.merged_project_config(project, self.commit.as_ref(), |config| {+ config.commit.as_ref()})}@@ -122,9 +117,7 @@ impl UserConfig {/// Merges project-specific settings with global settings, where project/// settings take precedence for fields that are set.pub fn merge(&self, project: Option<&str>) -> Option<MergeConfig> {- self.merged_project_config(project, self.configs.merge.as_ref(), |config| {- config.overrides.merge.as_ref()- })+ self.merged_project_config(project, self.merge.as_ref(), |config| config.merge.as_ref())}/// Returns the switch config for a specific project.@@ -132,16 +125,14 @@ impl UserConfig {/// Merges project-specific settings with global settings, where project/// settings take precedence for fields that are set.pub fn switch(&self, project: Option<&str>) -> Option<SwitchConfig> {- self.merged_project_config(project, self.configs.switch.as_ref(), |config| {- config.overrides.switch.as_ref()+ self.merged_project_config(project, self.switch.as_ref(), |config| {+ config.switch.as_ref()})}/// Returns the `wt step` config for a specific project.pub fn step(&self, project: Option<&str>) -> Option<StepConfig> {- self.merged_project_config(project, self.configs.step.as_ref(), |config| {- config.overrides.step.as_ref()- })+ self.merged_project_config(project, self.step.as_ref(), |config| config.step.as_ref())}/// Returns the `wt step copy-ignored` config for a specific project.@@ -158,7 +149,6 @@ impl UserConfig {/// sections are normalized into `[switch.picker]` during config loading.pub fn switch_picker(&self, project: Option<&str>) -> SwitchPickerConfig {let global = self- .configs.switch.as_ref().and_then(|switch| switch.picker.as_ref())@@ -168,7 +158,6 @@ impl UserConfig {self.project_overrides(project).and_then(|config| {config- .overrides.switch.as_ref().and_then(|switch| switch.picker.as_ref())@@ -183,10 +172,8 @@ impl UserConfig {/// Merges global hooks with per-project hooks using append semantics./// Both global and per-project hooks run (global first, then per-project).pub fn hooks(&self, project: Option<&str>) -> HooksConfig {- let global = &self.configs.hooks;- let project_hooks = self- .project_overrides(project)- .map(|config| &config.overrides.hooks);+ let global = &self.hooks;+ let project_hooks = self.project_overrides(project).map(|config| &config.hooks);match project_hooks {Some(ph) => global.merge_with(ph),@@ -199,10 +186,10 @@ impl UserConfig {/// Merges global user aliases with per-project user aliases using append/// semantics: both run on name collision (global first, then per-project).pub fn aliases(&self, project: Option<&str>) -> BTreeMap<String, CommandConfig> {- let mut result = self.configs.aliases.clone().unwrap_or_default();+ let mut result = self.aliases.clone().unwrap_or_default();if let Some(proj_aliases) = project.and_then(|p| self.projects.get(p))- .and_then(|proj| proj.overrides.aliases.as_ref())+ .and_then(|proj| proj.aliases.as_ref()){crate::config::commands::append_aliases(&mut result, proj_aliases);}diff --git a/src/config/user/mod.rs b/src/config/user/mod.rsindex 812151508..b9dfeeec0 100644--- a/src/config/user/mod.rs+++ b/src/config/user/mod.rs@@ -13,9 +13,9 @@ mod sections;#[cfg(test)]mod tests;-use std::path::PathBuf;+use std::path::{Path, PathBuf};-use config::{Case, Config, ConfigError, File};+use super::ConfigError;use schemars::JsonSchema;use serde::{Deserialize, Serialize};@@ -45,13 +45,10 @@ pub enum LoadError {err: Box<toml::de::Error>,},/// Config files parsed cleanly; applying env-var overrides failed.- /// `override_vars` lists `WORKTRUNK_*` env vars that could be the cause.- Env {- err: ConfigError,- override_vars: Vec<String>,- },- /// Other errors (validation, config-crate internals).- Other(ConfigError),+ /// `vars` lists the exact `WORKTRUNK_*` env vars that were parsed.+ Env { err: String, vars: Vec<String> },+ /// Validation errors (e.g. empty worktree-path).+ Validation(String),}impl std::fmt::Display for LoadError {@@ -65,38 +62,153 @@ impl std::fmt::Display for LoadError {)}LoadError::Env { err, .. } => write!(f, "{err}"),- LoadError::Other(err) => write!(f, "{err}"),+ LoadError::Validation(err) => write!(f, "{err}"),}}}impl std::error::Error for LoadError {}-/// Returns names of `WORKTRUNK_*` env vars that could be value overrides,-/// excluding infrastructure paths and the `WORKTRUNK_TEST_` namespace.-// TODO: This hardcoded exclusion list is a smell — ideally the config loading-// layer would track which source each value came from, making attribution-// automatic rather than heuristic. Consider integrating this into the config-// crate's source-tracking or building our own env-var overlay.-fn collect_worktrunk_override_vars() -> Vec<String> {+// ---- Env-var overlay ----++/// Parsed WORKTRUNK_* env-var overrides ready to merge into a TOML table.+///+/// Stores both typed and string versions because we can't know the target type+/// at parse time. Typed values work for `Option<u64>`/`Option<bool>` fields;+/// string values work for `Option<String>` fields with numeric-looking values+/// (e.g., `WORKTRUNK_WORKTREE_PATH=42`). The load flow tries typed first, then+/// falls back to strings. A mixed case (one var needing typed, another needing+/// string) would fail both passes — unlikely in practice since String fields+/// hold paths/commands, not numeric values.+struct EnvOverrides {+ typed_table: toml::Table,+ string_table: toml::Table,+ var_names: Vec<String>,+}++/// Read `WORKTRUNK_*` env vars and build a nested TOML table.+///+/// Env-var convention (matches the config crate's prior behavior):+/// - `WORKTRUNK_WORKTREE_PATH=foo` → `worktree-path = "foo"`+/// - `WORKTRUNK__LIST__TIMEOUT_MS=30` → `[list]\ntimeout-ms = 30`+/// - `WORKTRUNK_COMMIT__GENERATION__COMMAND=cmd` → `[commit.generation]\ncommand = "cmd"`+///+/// Infrastructure vars (`_CONFIG_PATH`, `_SYSTEM_CONFIG_PATH`,+/// `_APPROVALS_PATH`) and test vars (`_TEST_*`) are excluded.+fn parse_worktrunk_env_vars() -> EnvOverrides {const INFRA_VARS: &[&str] = &["WORKTRUNK_CONFIG_PATH","WORKTRUNK_SYSTEM_CONFIG_PATH","WORKTRUNK_APPROVALS_PATH",];- let mut vars: Vec<String> = std::env::vars()- .filter_map(|(k, _)| {- if !k.starts_with("WORKTRUNK_") {- return None;++ let mut typed_table = toml::Table::new();+ let mut string_table = toml::Table::new();+ let mut var_names = Vec::new();++ let mut env_vars: Vec<_> = std::env::vars()+ .filter(|(k, _)| k.starts_with("WORKTRUNK_"))+ .filter(|(k, _)| !INFRA_VARS.contains(&k.as_str()))+ .filter(|(k, _)| !k.starts_with("WORKTRUNK_TEST_"))+ .collect();+ env_vars.sort_by(|a, b| a.0.cmp(&b.0));++ for (key, value) in env_vars {+ var_names.push(key.clone());+ // Strip WORKTRUNK_ prefix, split by __ for nesting, convert to kebab-case+ let stripped = &key["WORKTRUNK_".len()..];+ let segments: Vec<String> = stripped+ .split("__")+ .map(|s| {+ s.to_lowercase()+ .replace('_', "-")+ .trim_start_matches('-')+ .to_string()+ })+ .filter(|s| !s.is_empty())+ .collect();++ if segments.is_empty() {+ continue;+ }++ set_nested_value(&mut typed_table, &segments, try_parse_value(&value));+ set_nested_value(&mut string_table, &segments, toml::Value::String(value));+ }++ EnvOverrides {+ typed_table,+ string_table,+ var_names,+ }+}++/// 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") {+ return toml::Value::Boolean(true);+ }+ if s.eq_ignore_ascii_case("false") {+ return toml::Value::Boolean(false);+ }+ if let Ok(n) = s.parse::<i64>() {+ return toml::Value::Integer(n);+ }+ if let Ok(n) = s.parse::<f64>() {+ return toml::Value::Float(n);+ }+ toml::Value::String(s.to_string())+}++/// Set a value at a nested path in a TOML table, creating intermediate tables.+fn set_nested_value(table: &mut toml::Table, path: &[String], value: toml::Value) {+ if path.len() == 1 {+ table.insert(path[0].clone(), value);+ return;+ }+ let entry = table+ .entry(&path[0])+ .or_insert_with(|| toml::Value::Table(toml::Table::new()));+ if let toml::Value::Table(inner) = entry {+ set_nested_value(inner, &path[1..], value);+ }+}++/// Recursively merge `overlay` into `base`. Overlay values win for scalars;+/// nested tables merge recursively.+fn deep_merge_table(base: &mut toml::Table, overlay: toml::Table) {+ for (key, value) in overlay {+ match (base.get_mut(&key), &value) {+ (Some(toml::Value::Table(base_t)), toml::Value::Table(overlay_t)) => {+ deep_merge_table(base_t, overlay_t.clone());}- if INFRA_VARS.contains(&k.as_str()) || k.starts_with("WORKTRUNK_TEST_") {- return None;+ _ => {+ base.insert(key, value);}- Some(k)- })- .collect();- vars.sort();- vars+ }+ }+}++/// Load and validate a single config file. Returns the parsed table for+/// merging and validates via `toml::from_str::<UserConfig>` for rich errors.+fn load_config_file(+ path: &Path,+ migrated: &str,+ label: &'static str,+) -> Result<toml::Table, LoadError> {+ // Validate by deserializing — gives rich line/col errors.+ if let Err(err) = toml::from_str::<UserConfig>(migrated) {+ return Err(LoadError::File {+ path: path.to_path_buf(),+ label,+ err: Box::new(err),+ });+ }+ // Parse as table for merging. Infallible after from_str::<UserConfig>+ // succeeds — valid UserConfig TOML is always valid TOML.+ Ok(migrated+ .parse::<toml::Table>()+ .expect("valid TOML after UserConfig parse"))}/// User-level configuration for worktree path formatting and LLM integration.@@ -145,9 +257,41 @@ pub struct UserConfig {#[serde(default)]pub projects: std::collections::BTreeMap<String, UserProjectOverrides>,- /// Settings that can be overridden per-project (worktree-path, list, commit, merge, switch, step, hooks)+ /// Hooks configuration (top-level keys like pre-merge, post-switch, etc.)#[serde(flatten, default)]- pub configs: OverridableConfig,+ pub hooks: crate::config::HooksConfig,++ /// Worktree path template+ #[serde(+ rename = "worktree-path",+ default,+ skip_serializing_if = "Option::is_none"+ )]+ pub worktree_path: Option<String>,++ /// Configuration for the `wt list` command+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub list: Option<sections::ListConfig>,++ /// Configuration for the `wt step commit` command (also used by merge)+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub commit: Option<sections::CommitConfig>,++ /// Configuration for the `wt merge` command+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub merge: Option<sections::MergeConfig>,++ /// Configuration for the `wt switch` command+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub switch: Option<sections::SwitchConfig>,++ /// Configuration for `wt step` subcommands+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub step: Option<sections::StepConfig>,++ /// Command aliases for `wt step <name>`+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub aliases: Option<std::collections::BTreeMap<String, crate::config::commands::CommandConfig>>,/// Skip the first-run shell integration prompt#[serde(@@ -175,7 +319,7 @@ impl UserConfig {/// 3. User config file (personal preferences)/// 4. Environment variables (WORKTRUNK_*)pub fn load() -> Result<Self, ConfigError> {- Self::load_with_cause().map_err(|e| ConfigError::Message(e.to_string()))+ Self::load_with_cause().map_err(|e| ConfigError(e.to_string()))}/// Like [`load()`](Self::load), but returns a [`LoadError`] that@@ -183,58 +327,27 @@ impl UserConfig {/// env-var override failures. Used by `Repository::user_config()`/// to emit targeted diagnostics.pub(crate) fn load_with_cause() -> Result<Self, LoadError> {- // Note: worktree-path has no default set here - it's handled by the getter- // which returns the default when None. This allows us to distinguish- // "user explicitly set this" from "using default".- let mut builder = Config::builder();+ let mut merged_table = toml::Table::new();- // Add system config if it exists (lowest priority file source)+ // 1. System config (lowest priority)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 configsuper::deprecation::warn_unknown_fields::<UserConfig>(&system_path,&find_unknown_keys(&content),"System config",);-- // Feed migrated content to serde so deprecated patterns parse correctlylet migrated = super::deprecation::migrate_content(&content);-- // Pre-validate with the toml crate for rich line/col errors.- // Try OverridableConfig first — it has section fields (list,- // commit, merge, ...) as direct fields, so toml tracks their- // location correctly. UserConfig's flatten loses field paths.- // Then try UserConfig to catch non-section fields (projects,- // skip-*-prompt) that OverridableConfig silently ignores.- if let Err(err) = toml::from_str::<OverridableConfig>(&migrated) {- return Err(LoadError::File {- path: system_path,- label: "System config",- err: Box::new(err),- });- }- if let Err(err) = toml::from_str::<Self>(&migrated) {- return Err(LoadError::File {- path: system_path,- label: "System config",- err: Box::new(err),- });- }-- builder = builder.add_source(File::from_str(&migrated, config::FileFormat::Toml));+ let table = load_config_file(&system_path, &migrated, "System config")?;+ deep_merge_table(&mut merged_table, table);}- // Add user config file if it exists (overrides system config)+ // 2. User config (overrides system)let config_path = config_path();if let Some(config_path) = config_path.as_ref()&& config_path.exists(){- // Check for deprecated template variables and create migration file if needed- // User config always gets migration file (it's global, not worktree-specific)- // 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 migrated = super::deprecation::check_and_migrate(config_path,@@ -242,45 +355,23 @@ impl UserConfig {true,"User config",None,- true, // show_brief_warning+ true,).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- // config.unknown includes env vars which shouldn't trigger warnings)super::deprecation::warn_unknown_fields::<UserConfig>(config_path,&find_unknown_keys(&content),"User config",);- // Pre-validate with the toml crate for rich line/col errors- // (see system config comment above for the two-pass rationale).- if let Err(err) = toml::from_str::<OverridableConfig>(&migrated) {- return Err(LoadError::File {- path: config_path.clone(),- label: "User config",- err: Box::new(err),- });- }- if let Err(err) = toml::from_str::<Self>(&migrated) {- return Err(LoadError::File {- path: config_path.clone(),- label: "User config",- err: Box::new(err),- });- }-- // 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));+ let table = load_config_file(config_path, &migrated, "User config")?;+ deep_merge_table(&mut merged_table, table);}} else if let Some(config_path) = config_path.as_ref()&& path::is_config_path_explicit(){- // Warn if user explicitly specified a config path that doesn't existcrate::styling::eprintln!("{}",crate::styling::warning_message(format!(@@ -290,43 +381,37 @@ impl UserConfig {);}- // Add environment variables with WORKTRUNK prefix- // - 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)- .try_parsing(true),- );-- // 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 config: Self = builder- .build()- .map_err(LoadError::Other)?- .try_deserialize()- .map_err(|err| {- // Files were pre-validated above, so a deserialize failure here- // is caused by env-var overrides.- LoadError::Env {- err,- override_vars: collect_worktrunk_override_vars(),- }- })?;-- config.validate().map_err(LoadError::Other)?;+ // 3. Env-var overrides (highest priority)+ let env = parse_worktrunk_env_vars();+ let has_env_vars = !env.var_names.is_empty();+ let file_table = merged_table.clone();++ if !env.typed_table.is_empty() {+ deep_merge_table(&mut merged_table, env.typed_table);+ }++ // 4. Deserialize the merged table.+ //+ // Try typed env values first (handles Option<u64>, Option<bool>).+ // If that fails and env vars are present, retry with string values+ // (handles Option<String> fields with numeric-looking values like+ // WORKTRUNK_WORKTREE_PATH=42).+ let config: Self = match toml::Value::Table(merged_table).try_into() {+ Ok(config) => config,+ Err(typed_err) if has_env_vars => {+ let mut string_merged = file_table;+ deep_merge_table(&mut string_merged, env.string_table);+ toml::Value::Table(string_merged)+ .try_into()+ .map_err(|_: toml::de::Error| LoadError::Env {+ err: typed_err.to_string(),+ vars: env.var_names,+ })?+ }+ Err(err) => return Err(LoadError::Validation(err.to_string())),+ };++ config.validate().map_err(|e| LoadError::Validation(e.0))?;Ok(config)}@@ -335,8 +420,7 @@ impl UserConfig {#[cfg(test)]pub(crate) fn load_from_str(content: &str) -> Result<Self, ConfigError> {let migrated = crate::config::deprecation::migrate_content(content);- let config: Self =- toml::from_str(&migrated).map_err(|e| ConfigError::Message(e.to_string()))?;+ let config: Self = toml::from_str(&migrated).map_err(|e| ConfigError(e.to_string()))?;config.validate()?;Ok(config)}diff --git a/src/config/user/mutation.rs b/src/config/user/mutation.rsindex 509ee71cd..a8fd69715 100644--- a/src/config/user/mutation.rs+++ b/src/config/user/mutation.rs@@ -3,9 +3,10 @@//! These methods modify the UserConfig and persist changes to disk,//! using file locking to prevent race conditions between concurrent processes.-use config::ConfigError;use fs2::FileExt;+use crate::config::ConfigError;+use crate::path::format_path_for_display;use super::UserConfig;@@ -24,7 +25,7 @@ pub(crate) fn acquire_config_lock(// Create parent directory if neededif let Some(parent) = lock_path.parent() {std::fs::create_dir_all(parent)- .map_err(|e| ConfigError::Message(format!("Failed to create config directory: {e}")))?;+ .map_err(|e| ConfigError(format!("Failed to create config directory: {e}")))?;}let file = std::fs::OpenOptions::new()@@ -33,10 +34,10 @@ pub(crate) fn acquire_config_lock(.create(true).truncate(false).open(&lock_path)- .map_err(|e| ConfigError::Message(format!("Failed to open lock file: {e}")))?;+ .map_err(|e| ConfigError(format!("Failed to open lock file: {e}")))?;file.lock_exclusive()- .map_err(|e| ConfigError::Message(format!("Failed to acquire config lock: {e}")))?;+ .map_err(|e| ConfigError(format!("Failed to acquire config lock: {e}")))?;Ok(file)}@@ -56,7 +57,7 @@ impl UserConfig {let path = match config_path {Some(p) => p.to_path_buf(),None => path::config_path().ok_or_else(|| {- ConfigError::Message(+ ConfigError("Cannot determine config directory. Set $HOME or $XDG_CONFIG_HOME".to_string(),)})?,@@ -93,7 +94,7 @@ impl UserConfig {}let content = std::fs::read_to_string(&path).map_err(|e| {- ConfigError::Message(format!(+ ConfigError(format!("Failed to read config file {}: {}",format_path_for_display(&path),e@@ -102,7 +103,7 @@ impl UserConfig {let migrated = crate::config::deprecation::migrate_content(&content);let disk_config: UserConfig = toml::from_str(&migrated).map_err(|e| {- ConfigError::Message(format!(+ ConfigError(format!("Failed to parse config file {}: {}",format_path_for_display(&path),e@@ -161,10 +162,10 @@ impl UserConfig {) -> Result<(), ConfigError> {self.with_locked_mutation(config_path, |config| {let entry = config.projects.entry(project.to_string()).or_default();- if entry.overrides.worktree_path.as_ref() == Some(&worktree_path) {+ if entry.worktree_path.as_ref() == Some(&worktree_path) {return false;}- entry.overrides.worktree_path = Some(worktree_path);+ entry.worktree_path = Some(worktree_path);true})}@@ -181,10 +182,7 @@ impl UserConfig {) -> Result<(), ConfigError> {self.with_locked_mutation(config_path, |config| {// Ensure commit config exists- let commit_config = config- .configs- .commit- .get_or_insert_with(CommitConfig::default);+ let commit_config = config.commit.get_or_insert_with(CommitConfig::default);let gen_config = commit_config.generation.get_or_insert_with(CommitGenerationConfig::default);diff --git a/src/config/user/persistence.rs b/src/config/user/persistence.rsindex 6c26c20d6..7df6864c9 100644--- a/src/config/user/persistence.rs+++ b/src/config/user/persistence.rs@@ -3,9 +3,10 @@//! Handles TOML serialization with formatting (multiline arrays, implicit tables)//! and preserves comments when updating existing files.-use config::ConfigError;use serde::Serialize;+use crate::config::ConfigError;+use super::UserConfig;use super::path;use super::sections::CommitGenerationConfig;@@ -73,7 +74,7 @@ impl UserConfig {Some(path) => self.save_to(path),None => {let path = path::config_path().ok_or_else(|| {- ConfigError::Message(+ ConfigError("Cannot determine config directory. Set $HOME or $XDG_CONFIG_HOME environment variable".to_string(),)})?;@@ -84,7 +85,7 @@ impl UserConfig {/// Update the [commit.generation] section in the document.fn update_commit_generation_section(&self, doc: &mut toml_edit::DocumentMut) {- if let Some(ref commit_cfg) = self.configs.commit+ if let Some(ref commit_cfg) = self.commit&& let Some(ref gen_cfg) = commit_cfg.generation{// Ensure [commit] table exists@@ -145,28 +146,24 @@ impl UserConfig {Self::sync_string_field(project_table,"worktree-path",- project_config.overrides.worktree_path.as_ref(),+ project_config.worktree_path.as_ref(),);- Self::sync_serialized_section(- project_table,- "list",- project_config.overrides.list.as_ref(),- );+ Self::sync_serialized_section(project_table, "list", project_config.list.as_ref());Self::sync_serialized_section(project_table,"commit",- project_config.overrides.commit.as_ref(),+ project_config.commit.as_ref(),);Self::sync_serialized_section(project_table,"merge",- project_config.overrides.merge.as_ref(),+ project_config.merge.as_ref(),);Self::sync_serialized_section(project_table,"switch",- project_config.overrides.switch.as_ref(),+ project_config.switch.as_ref(),);}}@@ -214,19 +211,18 @@ impl UserConfig {pub fn save_to(&self, config_path: &std::path::Path) -> Result<(), ConfigError> {// Create parent directory if it doesn't existif let Some(parent) = config_path.parent() {- std::fs::create_dir_all(parent).map_err(|e| {- ConfigError::Message(format!("Failed to create config directory: {}", e))- })?;+ std::fs::create_dir_all(parent)+ .map_err(|e| ConfigError(format!("Failed to create config directory: {}", e)))?;}let toml_string = if config_path.exists() {// Surgically update sections to preserve commentslet existing_content = std::fs::read_to_string(config_path)- .map_err(|e| ConfigError::Message(format!("Failed to read config file: {}", e)))?;+ .map_err(|e| ConfigError(format!("Failed to read config file: {}", e)))?;let mut doc: toml_edit::DocumentMut = existing_content.parse()- .map_err(|e| ConfigError::Message(format!("Failed to parse config file: {}", e)))?;+ .map_err(|e| ConfigError(format!("Failed to parse config file: {}", e)))?;// Update all programmatically-modifiable sections// NOTE: If you add a new setter that modifies config, add the update here too!@@ -249,7 +245,7 @@ impl UserConfig {} else {// No existing file: serialize struct directly, then post-process formattinglet mut doc = toml_edit::ser::to_document(&self)- .map_err(|e| ConfigError::Message(format!("Serialization error: {e}")))?;+ .map_err(|e| ConfigError(format!("Serialization error: {e}")))?;// Convert inline tables to standard tables for readabilitySelf::expand_inline_tables(doc.as_table_mut());@@ -264,7 +260,7 @@ impl UserConfig {};std::fs::write(config_path, toml_string)- .map_err(|e| ConfigError::Message(format!("Failed to write config file: {}", e)))?;+ .map_err(|e| ConfigError(format!("Failed to write config file: {}", e)))?;Ok(())}@@ -278,41 +274,41 @@ impl UserConfig {/// Validate configuration values.pub(super) fn validate(&self) -> Result<(), ConfigError> {// Validate worktree path (only if explicitly set - default is always valid)- if let Some(ref path) = self.configs.worktree_path+ if let Some(ref path) = self.worktree_path&& path.trim().is_empty(){- return Err(ConfigError::Message("worktree-path cannot be empty".into()));+ return Err(ConfigError("worktree-path cannot be empty".into()));}// Validate per-project configsfor (project, project_config) in &self.projects {// Validate worktree path- if let Some(ref path) = project_config.overrides.worktree_path+ if let Some(ref path) = project_config.worktree_path&& path.trim().is_empty(){- return Err(ConfigError::Message(format!(+ return Err(ConfigError(format!("projects.{project}.worktree-path cannot be empty")));}- if let Some(ref commit) = project_config.overrides.commit+ if let Some(ref commit) = project_config.commit&& let Some(ref cg) = commit.generation{Self::validate_commit_generation(cg, &format!("projects.{project}"))?;}}- if let Some(ref commit) = self.configs.commit+ if let Some(ref commit) = self.commit&& let Some(ref cg) = commit.generation{if cg.template.is_some() && cg.template_file.is_some() {- return Err(ConfigError::Message(+ return Err(ConfigError("commit.generation.template and commit.generation.template-file are mutually exclusive".into(),));}if cg.squash_template.is_some() && cg.squash_template_file.is_some() {- return Err(ConfigError::Message(+ return Err(ConfigError("commit.generation.squash-template and commit.generation.squash-template-file are mutually exclusive".into(),));}@@ -326,12 +322,12 @@ impl UserConfig {prefix: &str,) -> Result<(), ConfigError> {if cg.template.is_some() && cg.template_file.is_some() {- return Err(ConfigError::Message(format!(+ return Err(ConfigError(format!("{prefix}.commit-generation.template and template-file are mutually exclusive")));}if cg.squash_template.is_some() && cg.squash_template_file.is_some() {- return Err(ConfigError::Message(format!(+ return Err(ConfigError(format!("{prefix}.commit-generation.squash-template and squash-template-file are mutually exclusive")));}diff --git a/src/config/user/sections.rs b/src/config/user/sections.rsindex 8abe07630..0d09c5182 100644--- a/src/config/user/sections.rs+++ b/src/config/user/sections.rs@@ -462,69 +462,19 @@ impl Merge for StepConfig {/// Settings that can be set globally or per-project.///-/// This struct is flattened into both `UserConfig` (global) and `UserProjectOverrides`-/// (per-project), ensuring new settings are automatically available in both-/// contexts without manual synchronization.-///-/// Note: Hooks use append semantics when merging global with per-project:-/// - Global hooks (top-level in TOML) are in `UserConfig.configs.hooks`-/// - Per-project hooks are in `UserProjectOverrides.overrides.hooks`-/// - The `UserConfig::hooks()` method merges both with global running first-#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default, JsonSchema)]+/// This is a merge-only type — not a serde target. Fields are inlined directly+/// into `UserConfig` and `UserProjectOverrides` for deserialization (avoiding+/// `#[serde(flatten)]` which causes toml to lose error locations). Use+/// `UserProjectOverrides::overridable_config()` to construct this for merging.+#[derive(Debug, Clone, PartialEq, Default)]pub struct OverridableConfig {- /// Hooks configuration.- ///- /// At top level: global hooks that run for all projects.- /// In `[projects."..."]`: per-project hooks that append to global hooks.- #[serde(flatten, default)]pub hooks: HooksConfig,-- /// Worktree path template- #[serde(- rename = "worktree-path",- default,- skip_serializing_if = "Option::is_none"- )]pub worktree_path: Option<String>,-- /// Configuration for the `wt list` command- #[serde(default, skip_serializing_if = "Option::is_none")]pub list: Option<ListConfig>,-- /// Configuration for the `wt step commit` command (also used by merge)- #[serde(default, skip_serializing_if = "Option::is_none")]pub commit: Option<CommitConfig>,-- /// Configuration for the `wt merge` command- #[serde(default, skip_serializing_if = "Option::is_none")]pub merge: Option<MergeConfig>,-- /// Configuration for the `wt switch` command- #[serde(default, skip_serializing_if = "Option::is_none")]pub switch: Option<SwitchConfig>,-- /// Configuration for `wt step` subcommands.- #[serde(default, skip_serializing_if = "Option::is_none")]pub step: Option<StepConfig>,-- /// \[experimental\] Command aliases for `wt step <name>`.- ///- /// Each alias maps a name to one or more command templates. All hook- /// template variables are available (e.g., `{{ branch }}`, `{{ worktree_path }}`).- ///- /// Per-project aliases append to global aliases on name collision (global- /// first, then per-project), matching hook merge semantics.- ///- /// Uses `CommandConfig` for consistency with hooks. This means the- /// named-table format (`[aliases.deploy] build = "..." run = "..."`)- /// technically works, but the single-string format is the expected usage.- ///- /// ```toml- /// [aliases]- /// deploy = "cd {{ worktree_path }} && make deploy"- /// lint = "npm run lint"- /// ```- #[serde(default, skip_serializing_if = "Option::is_none")]pub aliases: Option<BTreeMap<String, CommandConfig>>,}@@ -615,9 +565,35 @@ pub struct UserProjectOverrides {)]pub approved_commands: Vec<String>,- /// Per-project overrides (worktree-path, list, commit, merge, switch, step)+ /// Per-project hooks (append to global hooks)#[serde(flatten, default)]- pub overrides: OverridableConfig,+ pub hooks: HooksConfig,++ /// Per-project worktree path template override+ #[serde(+ rename = "worktree-path",+ default,+ skip_serializing_if = "Option::is_none"+ )]+ pub worktree_path: Option<String>,++ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub list: Option<ListConfig>,++ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub commit: Option<CommitConfig>,++ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub merge: Option<MergeConfig>,++ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub switch: Option<SwitchConfig>,++ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub step: Option<StepConfig>,++ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub aliases: Option<BTreeMap<String, CommandConfig>>,}impl UserProjectOverrides {@@ -626,7 +602,21 @@ 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.overrides.is_empty()+ self.overridable_config().is_empty()+ }++ /// Construct an `OverridableConfig` from this project's inlined fields.+ pub fn overridable_config(&self) -> OverridableConfig {+ OverridableConfig {+ hooks: self.hooks.clone(),+ worktree_path: self.worktree_path.clone(),+ list: self.list.clone(),+ commit: self.commit.clone(),+ merge: self.merge.clone(),+ switch: self.switch.clone(),+ step: self.step.clone(),+ aliases: self.aliases.clone(),+ }}}diff --git a/src/config/user/tests.rs b/src/config/user/tests.rsindex 550f8c812..7656baf20 100644--- a/src/config/user/tests.rs+++ b/src/config/user/tests.rs@@ -158,18 +158,16 @@ fn test_stage_mode_serde() {#[test]fn test_user_project_config_default() {let config = UserProjectOverrides::default();- assert!(config.overrides.worktree_path.is_none());+ assert!(config.worktree_path.is_none());assert!(config.approved_commands.is_empty());}#[test]fn test_user_project_config_with_worktree_path_serde() {let config = UserProjectOverrides {- overrides: OverridableConfig {- worktree_path: Some(".worktrees/{{ branch | sanitize }}".to_string()),- ..Default::default()- },+ worktree_path: Some(".worktrees/{{ branch | sanitize }}".to_string()),approved_commands: vec!["npm install".to_string()],+ ..Default::default()};let toml = toml::to_string(&config).unwrap();insta::assert_snapshot!(toml, @r#"@@ -179,7 +177,7 @@ fn test_user_project_config_with_worktree_path_serde() {let parsed: UserProjectOverrides = toml::from_str(&toml).unwrap();assert_eq!(- parsed.overrides.worktree_path,+ parsed.worktree_path,Some(".worktrees/{{ branch | sanitize }}".to_string()));assert_eq!(parsed.approved_commands, vec!["npm install".to_string()]);@@ -191,11 +189,8 @@ fn test_worktree_path_for_project_uses_project_specific() {config.projects.insert("github.com/user/repo".to_string(),UserProjectOverrides {- overrides: OverridableConfig {- worktree_path: Some(".worktrees/{{ branch | sanitize }}".to_string()),- ..Default::default()- },- approved_commands: vec![],+ worktree_path: Some(".worktrees/{{ branch | sanitize }}".to_string()),+ ..Default::default()},);@@ -209,20 +204,15 @@ fn test_worktree_path_for_project_uses_project_specific() {#[test]fn test_worktree_path_for_project_falls_back_to_global() {let mut config = UserConfig {- configs: OverridableConfig {- worktree_path: Some("../{{ repo }}-{{ branch | sanitize }}".to_string()),- ..Default::default()- },+ worktree_path: Some("../{{ repo }}-{{ branch | sanitize }}".to_string()),..Default::default()};config.projects.insert("github.com/user/repo".to_string(),UserProjectOverrides {- overrides: OverridableConfig {- worktree_path: None, // No project-specific path- ..Default::default()- },+ worktree_path: None, // No project-specific pathapproved_commands: vec!["npm install".to_string()],+ ..Default::default()},);@@ -248,20 +238,14 @@ fn test_worktree_path_for_project_falls_back_to_default() {fn test_format_path_with_project_override() {let test = test_repo();let mut config = UserConfig {- configs: OverridableConfig {- worktree_path: Some("../{{ repo }}.{{ branch | sanitize }}".to_string()),- ..Default::default()- },+ worktree_path: Some("../{{ repo }}.{{ branch | sanitize }}".to_string()),..Default::default()};config.projects.insert("github.com/user/repo".to_string(),UserProjectOverrides {- overrides: OverridableConfig {- worktree_path: Some(".worktrees/{{ branch | sanitize }}".to_string()),- ..Default::default()- },- approved_commands: vec![],+ worktree_path: Some(".worktrees/{{ branch | sanitize }}".to_string()),+ ..Default::default()},);@@ -313,15 +297,15 @@ fn test_commit_config_default() {fn test_worktrunk_config_default() {let config = UserConfig::default();// worktree_path is None by default, but the getter returns the default- assert!(config.configs.worktree_path.is_none());+ assert!(config.worktree_path.is_none());assert_eq!(config.worktree_path(),"{{ repo_path }}/../{{ repo }}.{{ branch | sanitize }}");assert!(config.projects.is_empty());- assert!(config.configs.list.is_none());- assert!(config.configs.commit.is_none());- assert!(config.configs.merge.is_none());+ assert!(config.list.is_none());+ assert!(config.commit.is_none());+ assert!(config.merge.is_none());assert!(!config.skip_shell_integration_prompt);}@@ -356,10 +340,7 @@ fn test_worktrunk_config_format_path() {fn test_worktrunk_config_format_path_custom_template() {let test = test_repo();let config = UserConfig {- configs: OverridableConfig {- worktree_path: Some(".worktrees/{{ branch }}".to_string()),- ..Default::default()- },+ worktree_path: Some(".worktrees/{{ branch }}".to_string()),..Default::default()};let path = config@@ -372,11 +353,8 @@ fn test_worktrunk_config_format_path_custom_template() {fn test_worktrunk_config_format_path_repo_path_variable() {let test = test_repo();let config = UserConfig {- configs: OverridableConfig {- // Use forward slashes in template (works on all platforms)- worktree_path: Some("{{ repo_path }}/worktrees/{{ branch | sanitize }}".to_string()),- ..Default::default()- },+ // Use forward slashes in template (works on all platforms)+ worktree_path: Some("{{ repo_path }}/worktrees/{{ branch | sanitize }}".to_string()),..Default::default()};let path = config@@ -404,10 +382,7 @@ fn test_worktrunk_config_format_path_repo_path_variable() {fn test_worktrunk_config_format_path_tilde_expansion() {let test = test_repo();let config = UserConfig {- configs: OverridableConfig {- worktree_path: Some("~/worktrees/{{ repo }}/{{ branch | sanitize }}".to_string()),- ..Default::default()- },+ worktree_path: Some("~/worktrees/{{ repo }}/{{ branch | sanitize }}".to_string()),..Default::default()};let path = config@@ -442,10 +417,7 @@ fn test_worktrunk_config_format_path_owner_variable() {]);let config = UserConfig {- configs: OverridableConfig {- worktree_path: Some("{{ owner }}/{{ repo }}/{{ branch }}".to_string()),- ..Default::default()- },+ worktree_path: Some("{{ owner }}/{{ repo }}/{{ branch }}".to_string()),..Default::default()};@@ -468,10 +440,7 @@ fn test_worktrunk_config_format_path_owner_uses_full_namespace() {]);let config = UserConfig {- configs: OverridableConfig {- worktree_path: Some("{{ owner }}/{{ repo }}/{{ branch }}".to_string()),- ..Default::default()- },+ worktree_path: Some("{{ owner }}/{{ repo }}/{{ branch }}".to_string()),..Default::default()};@@ -827,16 +796,13 @@ fn test_commit_generation_merge_squash_template_mutual_exclusivity() {#[test]fn test_effective_commit_generation_no_project() {let config = UserConfig {- configs: OverridableConfig {- commit: Some(CommitConfig {- stage: None,- generation: Some(CommitGenerationConfig {- command: Some("global-llm".to_string()),- ..Default::default()- }),+ commit: Some(CommitConfig {+ stage: None,+ generation: Some(CommitGenerationConfig {+ command: Some("global-llm".to_string()),+ ..Default::default()}),- ..Default::default()- },+ }),..Default::default()};@@ -847,32 +813,26 @@ fn test_effective_commit_generation_no_project() {#[test]fn test_effective_commit_generation_with_project_override() {let mut config = UserConfig {- configs: OverridableConfig {- commit: Some(CommitConfig {- stage: None,- generation: Some(CommitGenerationConfig {- command: Some("global-llm".to_string()),- ..Default::default()- }),+ commit: Some(CommitConfig {+ stage: None,+ generation: Some(CommitGenerationConfig {+ command: Some("global-llm".to_string()),+ ..Default::default()}),- ..Default::default()- },+ }),..Default::default()};config.projects.insert("github.com/user/repo".to_string(),UserProjectOverrides {- overrides: OverridableConfig {- commit: Some(CommitConfig {- stage: None,- generation: Some(CommitGenerationConfig {- command: Some("project-llm".to_string()),- ..Default::default()- }),+ commit: Some(CommitConfig {+ stage: None,+ generation: Some(CommitGenerationConfig {+ command: Some("project-llm".to_string()),+ ..Default::default()}),- ..Default::default()- },+ }),..Default::default()},);@@ -892,34 +852,28 @@ fn test_effective_commit_generation_with_project_override() {#[test]fn test_effective_merge_with_partial_override() {let mut config = UserConfig {- configs: OverridableConfig {- merge: Some(MergeConfig {- squash: Some(true),- commit: Some(true),- rebase: Some(true),- remove: Some(true),- verify: Some(true),- ff: Some(true),- }),- ..Default::default()- },+ merge: Some(MergeConfig {+ squash: Some(true),+ commit: Some(true),+ rebase: Some(true),+ remove: Some(true),+ verify: Some(true),+ ff: Some(true),+ }),..Default::default()};config.projects.insert("github.com/user/repo".to_string(),UserProjectOverrides {- overrides: OverridableConfig {- merge: Some(MergeConfig {- squash: Some(false), // Only override squash- commit: None,- rebase: None,- remove: None,- verify: None,- ff: None,- }),- ..Default::default()- },+ merge: Some(MergeConfig {+ squash: Some(false), // Only override squash+ commit: None,+ rebase: None,+ remove: None,+ verify: None,+ ff: None,+ }),..Default::default()},);@@ -934,18 +888,15 @@ fn test_effective_merge_with_partial_override() {fn test_effective_list_project_only() {// No global list config, only project configlet mut config = UserConfig::default();- assert!(config.configs.list.is_none());+ assert!(config.list.is_none());config.projects.insert("github.com/user/repo".to_string(),UserProjectOverrides {- overrides: OverridableConfig {- list: Some(ListConfig {- full: Some(true),- ..Default::default()- }),+ list: Some(ListConfig {+ full: Some(true),..Default::default()- },+ }),..Default::default()},);@@ -962,13 +913,10 @@ fn test_effective_list_project_only() {fn test_effective_commit_global_only() {// Only global config, no project configlet config = UserConfig {- configs: OverridableConfig {- commit: Some(CommitConfig {- stage: Some(StageMode::Tracked),- generation: None,- }),- ..Default::default()- },+ commit: Some(CommitConfig {+ stage: Some(StageMode::Tracked),+ generation: None,+ }),..Default::default()};@@ -1047,14 +995,14 @@ fn test_merge_config_accessor_methods_with_values() {#[test]fn test_deprecated_no_ff_migrated_to_ff() {let config = UserConfig::load_from_str("[merge]\nno-ff = true\n").unwrap();- assert!(!config.configs.merge.unwrap().ff());+ assert!(!config.merge.unwrap().ff());}#[test]fn test_deprecated_no_ff_does_not_override_explicit_ff() {// If both `ff` and `no-ff` are set, `ff` wins (no-ff is ignored)let config = UserConfig::load_from_str("[merge]\nff = true\nno-ff = true\n").unwrap();- assert!(config.configs.merge.unwrap().ff());+ assert!(config.merge.unwrap().ff());}#[test]@@ -1126,14 +1074,7 @@ pager = "delta --paging=never"timeout-ms = 300"#;let config: UserConfig = toml::from_str(content).unwrap();- let picker = config- .configs- .switch- .as_ref()- .unwrap()- .picker- .as_ref()- .unwrap();+ let picker = config.switch.as_ref().unwrap().picker.as_ref().unwrap();assert_eq!(picker.pager.as_deref(), Some("delta --paging=never"));assert_eq!(picker.timeout_ms, Some(300));}@@ -1272,13 +1213,13 @@ cd = false#[test]fn test_deprecated_no_cd_migrated_to_cd() {let config = UserConfig::load_from_str("[switch]\nno-cd = true\n").unwrap();- assert!(!config.configs.switch.unwrap().cd());+ assert!(!config.switch.unwrap().cd());}#[test]fn test_deprecated_no_cd_does_not_override_explicit_cd() {let config = UserConfig::load_from_str("[switch]\ncd = true\nno-cd = true\n").unwrap();- assert!(config.configs.switch.unwrap().cd());+ assert!(config.switch.unwrap().cd());}#[test]@@ -1296,7 +1237,6 @@ pager = "bat"// [select] is migrated to [switch.picker] at the TOML level before parsingassert_eq!(config- .configs.switch.as_ref().and_then(|switch| switch.picker.as_ref())@@ -1335,32 +1275,26 @@ fn test_switch_picker_project_override() {use crate::config::user::{SwitchConfig, SwitchPickerConfig};let mut config = UserConfig {- configs: OverridableConfig {- switch: Some(SwitchConfig {- picker: Some(SwitchPickerConfig {- pager: Some("delta".to_string()),- timeout_ms: Some(200),- }),- ..Default::default()+ switch: Some(SwitchConfig {+ picker: Some(SwitchPickerConfig {+ pager: Some("delta".to_string()),+ timeout_ms: Some(200),}),..Default::default()- },+ }),..Default::default()};config.projects.insert("github.com/user/repo".to_string(),UserProjectOverrides {- overrides: OverridableConfig {- switch: Some(SwitchConfig {- picker: Some(SwitchPickerConfig {- pager: Some("bat".to_string()),- timeout_ms: None, // Fall back to global- }),- ..Default::default()+ switch: Some(SwitchConfig {+ picker: Some(SwitchPickerConfig {+ pager: Some("bat".to_string()),+ timeout_ms: None, // Fall back to global}),..Default::default()- },+ }),..Default::default()},);@@ -1394,7 +1328,6 @@ pager = "bat".projects.get("github.com/user/repo").unwrap()- .overrides.switch.as_ref().and_then(|s| s.picker.as_ref())@@ -1409,28 +1342,25 @@ fn test_resolved_config_for_project() {use crate::config::user::SwitchPickerConfig;let config = UserConfig {- configs: OverridableConfig {- list: Some(ListConfig {- full: Some(true),- ..Default::default()- }),- merge: Some(MergeConfig {- squash: Some(false),- ..Default::default()- }),- commit: Some(CommitConfig {- stage: Some(StageMode::None),- ..Default::default()- }),- switch: Some(SwitchConfig {- picker: Some(SwitchPickerConfig {- pager: Some("less".to_string()),- timeout_ms: Some(300),- }),- ..Default::default()+ list: Some(ListConfig {+ full: Some(true),+ ..Default::default()+ }),+ merge: Some(MergeConfig {+ squash: Some(false),+ ..Default::default()+ }),+ commit: Some(CommitConfig {+ stage: Some(StageMode::None),+ ..Default::default()+ }),+ switch: Some(SwitchConfig {+ picker: Some(SwitchPickerConfig {+ pager: Some("less".to_string()),+ timeout_ms: Some(300),}),..Default::default()- },+ }),..Default::default()};@@ -1455,37 +1385,34 @@ 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()],- overrides: OverridableConfig {- worktree_path: Some(".worktrees/{{ branch }}".to_string()),- list: Some(ListConfig {- full: Some(true),- ..Default::default()- }),- commit: Some(CommitConfig {- stage: Some(StageMode::Tracked),- generation: Some(CommitGenerationConfig {- command: Some("llm -m gpt-4".to_string()),- ..Default::default()- }),- }),- merge: Some(MergeConfig {- squash: Some(false),+ worktree_path: Some(".worktrees/{{ branch }}".to_string()),+ list: Some(ListConfig {+ full: Some(true),+ ..Default::default()+ }),+ commit: Some(CommitConfig {+ stage: Some(StageMode::Tracked),+ generation: Some(CommitGenerationConfig {+ command: Some("llm -m gpt-4".to_string()),..Default::default()}),+ }),+ merge: Some(MergeConfig {+ squash: Some(false),..Default::default()- },+ }),+ ..Default::default()};let toml = toml::to_string(&config).unwrap();let parsed: UserProjectOverrides = toml::from_str(&toml).unwrap();assert_eq!(- parsed.overrides.worktree_path,+ parsed.worktree_path,Some(".worktrees/{{ branch }}".to_string()));assert_eq!(parsed- .overrides.commit.as_ref().unwrap()@@ -1495,12 +1422,12 @@ fn test_user_project_config_with_nested_configs_serde() {.command,Some("llm -m gpt-4".to_string()));- assert_eq!(parsed.overrides.list.as_ref().unwrap().full, Some(true));+ assert_eq!(parsed.list.as_ref().unwrap().full, Some(true));assert_eq!(- parsed.overrides.commit.as_ref().unwrap().stage,+ parsed.commit.as_ref().unwrap().stage,Some(StageMode::Tracked));- assert_eq!(parsed.overrides.merge.as_ref().unwrap().squash, Some(false));+ assert_eq!(parsed.merge.as_ref().unwrap().squash, Some(false));}#[test]@@ -1530,12 +1457,11 @@ squash = false// Global configassert_eq!(- config.configs.worktree_path,+ config.worktree_path,Some("../{{ repo }}.{{ branch | sanitize }}".to_string()));assert_eq!(config- .configs.commit.as_ref().unwrap()@@ -1549,12 +1475,11 @@ squash = false// Project configlet project = config.projects.get("github.com/user/repo").unwrap();assert_eq!(- project.overrides.worktree_path,+ project.worktree_path,Some(".worktrees/{{ branch | sanitize }}".to_string()));assert_eq!(project- .overrides.commit.as_ref().unwrap()@@ -1564,11 +1489,8 @@ squash = false.command,Some("claude -p --model opus".to_string()));- assert_eq!(project.overrides.list.as_ref().unwrap().full, Some(true));- assert_eq!(- project.overrides.merge.as_ref().unwrap().squash,- Some(false)- );+ assert_eq!(project.list.as_ref().unwrap().full, Some(true));+ assert_eq!(project.merge.as_ref().unwrap().squash, Some(false));// Effective config for projectlet effective_cg = config.commit_generation(Some("github.com/user/repo"));@@ -1633,7 +1555,6 @@ command = "claude -p --model opus"assert_eq!(config- .configs.commit.as_ref().and_then(|commit| commit.generation.as_ref())@@ -1644,7 +1565,6 @@ command = "claude -p --model opus"let project = config.projects.get("github.com/user/repo").unwrap();assert_eq!(project- .overrides.commit.as_ref().and_then(|commit| commit.generation.as_ref())@@ -1672,7 +1592,6 @@ args = ["-m", "claude-haiku-4.5"]// Migration merges args into command and renames sectionassert_eq!(config- .configs.commit.as_ref().and_then(|c| c.generation.as_ref())@@ -1773,16 +1692,13 @@ fn test_save_to_new_file_with_commit_generation() {let config_path = dir.path().join("config.toml");let config = UserConfig {- configs: OverridableConfig {- commit: Some(CommitConfig {- stage: None,- generation: Some(CommitGenerationConfig {- command: Some("llm -m haiku".to_string()),- ..Default::default()- }),+ commit: Some(CommitConfig {+ stage: None,+ generation: Some(CommitGenerationConfig {+ command: Some("llm -m haiku".to_string()),+ ..Default::default()}),- ..Default::default()- },+ }),..Default::default()};@@ -1811,16 +1727,13 @@ fn test_save_to_new_file_commit_with_stage_and_generation() {let config_path = dir.path().join("config.toml");let config = UserConfig {- configs: OverridableConfig {- commit: Some(CommitConfig {- stage: Some(StageMode::Tracked),- generation: Some(CommitGenerationConfig {- command: Some("llm -m haiku".to_string()),- ..Default::default()- }),+ commit: Some(CommitConfig {+ stage: Some(StageMode::Tracked),+ generation: Some(CommitGenerationConfig {+ command: Some("llm -m haiku".to_string()),+ ..Default::default()}),- ..Default::default()- },+ }),..Default::default()};@@ -1868,10 +1781,7 @@ fn test_save_to_new_file_with_worktree_path() {let config_path = dir.path().join("config.toml");let config = UserConfig {- configs: OverridableConfig {- worktree_path: Some("../{{ repo }}.{{ branch }}".to_string()),- ..Default::default()- },+ worktree_path: Some("../{{ repo }}.{{ branch }}".to_string()),..Default::default()};@@ -1898,20 +1808,14 @@ fn test_hooks_merge_append_semantics() {// Global has post-start, per-project has post-start// Both should run (global first, then per-project)let mut config = UserConfig {- configs: OverridableConfig {- hooks: parse_hooks("post-start = \"echo global\""),- ..Default::default()- },+ hooks: parse_hooks("post-start = \"echo global\""),..Default::default()};config.projects.insert("github.com/user/repo".to_string(),UserProjectOverrides {- overrides: OverridableConfig {- hooks: parse_hooks("post-start = \"echo project\""),- ..Default::default()- },+ hooks: parse_hooks("post-start = \"echo project\""),..Default::default()},);@@ -1928,10 +1832,7 @@ fn test_hooks_merge_append_semantics() {fn test_hooks_no_project_override_uses_global() {// Global has hooks, project doesn't - global hooks usedlet config = UserConfig {- configs: OverridableConfig {- hooks: parse_hooks("post-start = \"echo global\""),- ..Default::default()- },+ hooks: parse_hooks("post-start = \"echo global\""),..Default::default()};@@ -1950,10 +1851,7 @@ fn test_hooks_project_only_no_global() {config.projects.insert("github.com/user/repo".to_string(),UserProjectOverrides {- overrides: OverridableConfig {- hooks: parse_hooks("post-start = \"echo project\""),- ..Default::default()- },+ hooks: parse_hooks("post-start = \"echo project\""),..Default::default()},);@@ -1970,20 +1868,14 @@ fn test_hooks_different_hook_types_not_merged() {// Global has post-start, per-project has pre-commit// These should remain separate (different hook types)let mut config = UserConfig {- configs: OverridableConfig {- hooks: parse_hooks("post-start = \"echo global-start\""),- ..Default::default()- },+ hooks: parse_hooks("post-start = \"echo global-start\""),..Default::default()};config.projects.insert("github.com/user/repo".to_string(),UserProjectOverrides {- overrides: OverridableConfig {- hooks: parse_hooks("pre-commit = \"echo project-commit\""),- ..Default::default()- },+ hooks: parse_hooks("pre-commit = \"echo project-commit\""),..Default::default()},);@@ -2007,10 +1899,7 @@ fn test_hooks_different_hook_types_not_merged() {fn test_hooks_none_project_uses_global() {// When no project is provided, only global hooks are usedlet config = UserConfig {- configs: OverridableConfig {- hooks: parse_hooks("post-start = \"echo global\""),- ..Default::default()- },+ hooks: parse_hooks("post-start = \"echo global\""),..Default::default()};@@ -2125,20 +2014,14 @@ setup = "echo setup");let mut config = UserConfig {- configs: OverridableConfig {- hooks: global_hooks,- ..Default::default()- },+ hooks: global_hooks,..Default::default()};config.projects.insert("github.com/user/repo".to_string(),UserProjectOverrides {- overrides: OverridableConfig {- hooks: project_hooks,- ..Default::default()- },+ hooks: project_hooks,..Default::default()},);@@ -2170,20 +2053,14 @@ test = "npm test");let mut config = UserConfig {- configs: OverridableConfig {- hooks: global_hooks,- ..Default::default()- },+ hooks: global_hooks,..Default::default()};config.projects.insert("github.com/user/repo".to_string(),UserProjectOverrides {- overrides: OverridableConfig {- hooks: project_hooks,- ..Default::default()- },+ hooks: project_hooks,..Default::default()},);@@ -2257,32 +2134,20 @@ squash = truelet user_config = UserConfig::load_from_str(user_toml).unwrap();// Verify system config values- assert_eq!(- system_config.configs.merge.as_ref().unwrap().squash,- Some(false)- );- assert_eq!(- system_config.configs.merge.as_ref().unwrap().rebase,- Some(false)- );- assert_eq!(- system_config.configs.list.as_ref().unwrap().full,- Some(true)- );+ assert_eq!(system_config.merge.as_ref().unwrap().squash, Some(false));+ assert_eq!(system_config.merge.as_ref().unwrap().rebase, Some(false));+ assert_eq!(system_config.list.as_ref().unwrap().full, Some(true));// Verify user config values- assert_eq!(- user_config.configs.merge.as_ref().unwrap().squash,- Some(true)- );+ assert_eq!(user_config.merge.as_ref().unwrap().squash, Some(true));// Simulate the merge that happens via the config crate's builder:// When both system and user configs define [merge], the config crate// performs a deep merge where user values override system values.// This is tested end-to-end via integration tests; here we verify// the Merge trait works correctly for the layering.- let system_merge = system_config.configs.merge.as_ref().unwrap();- let user_merge = user_config.configs.merge.as_ref().unwrap();+ let system_merge = system_config.merge.as_ref().unwrap();+ let user_merge = user_config.merge.as_ref().unwrap();let merged = system_merge.merge_with(user_merge);assert_eq!(merged.squash, Some(true)); // User overrides@@ -2501,7 +2366,7 @@ fn test_reload_projects_from_permission_error() {#[test]fn test_load_error_display_file() {- let toml_err = toml::from_str::<OverridableConfig>("[list]\nbranches = \"bad\"\n").unwrap_err();+ let toml_err = toml::from_str::<UserConfig>("[list]\nbranches = \"bad\"\n").unwrap_err();let err = LoadError::File {path: std::path::PathBuf::from("/tmp/config.toml"),label: "User config",@@ -2516,14 +2381,30 @@ fn test_load_error_display_file() {#[test]fn test_load_error_display_env() {let err = LoadError::Env {- err: config::ConfigError::Message("invalid type".into()),- override_vars: vec!["WORKTRUNK__LIST__BRANCHES".into()],+ err: "invalid type".into(),+ vars: vec!["WORKTRUNK__LIST__BRANCHES".into()],};assert_eq!(err.to_string(), "invalid type");}#[test]-fn test_load_error_display_other() {- let err = LoadError::Other(config::ConfigError::Message("bad".into()));+fn test_load_error_display_validation() {+ let err = LoadError::Validation("bad".into());assert_eq!(err.to_string(), "bad");}++#[test]+fn test_try_parse_value() {+ use super::try_parse_value;++ assert_eq!(try_parse_value("true"), toml::Value::Boolean(true));+ assert_eq!(try_parse_value("TRUE"), toml::Value::Boolean(true));+ assert_eq!(try_parse_value("false"), toml::Value::Boolean(false));+ assert_eq!(try_parse_value("42"), toml::Value::Integer(42));+ assert_eq!(try_parse_value("0"), toml::Value::Integer(0));+ assert_eq!(try_parse_value("1.5"), toml::Value::Float(1.5));+ assert_eq!(+ try_parse_value("hello"),+ toml::Value::String("hello".into())+ );+}diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 5f5e97f4e..7ad0f140e 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -410,31 +410,25 @@ impl Repository {crate::styling::format_with_gutter(&err.to_string(), None));}- LoadError::Env {- err,- override_vars,- } => {+ LoadError::Env { err, vars } => {crate::styling::eprintln!("{}",crate::styling::warning_message(format!(- "Failed to apply WORKTRUNK_* env var override, using defaults: {err}"+ "Failed to apply WORKTRUNK_* env var override, using defaults: {}",+ err.trim())));- // TODO: With source-tracking in the config layer- // (see collect_worktrunk_override_vars TODO) we could- // pinpoint the exact var and show its value, rather- // than dumping all override vars.- if !override_vars.is_empty() {+ if !vars.is_empty() {crate::styling::eprintln!("{}",crate::styling::hint_message(format!("Currently set: {}",- override_vars.join(", ")+ vars.join(", "))));}}- LoadError::Other(err) => {+ LoadError::Validation(err) => {crate::styling::eprintln!("{}",crate::styling::warning_message(format!(diff --git a/tests/integration_tests/list_config.rs b/tests/integration_tests/list_config.rsindex 2efca8a20..1e40249e8 100644--- a/tests/integration_tests/list_config.rs+++ b/tests/integration_tests/list_config.rs@@ -434,6 +434,29 @@ fn test_list_config_env_override_bad_value_warns_on_stderr(repo: TestRepo) {});}+/// 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>).+#[rstest]+fn test_list_config_env_override_numeric_string_field(repo: TestRepo) {+ let settings = setup_snapshot_settings(&repo);+ settings.bind(|| {+ let mut cmd = wt_command();+ repo.configure_wt_cmd(&mut cmd);+ // worktree-path is Option<String>; "42" must round-trip as a string+ cmd.env("WORKTRUNK_WORKTREE_PATH", "42");+ cmd.arg("list").current_dir(repo.root_path());++ let output = cmd.output().unwrap();+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ !stderr.contains("Failed"),+ "numeric string should not fail: {stderr}"+ );+ assert!(output.status.success());+ });+}+/// Bad values in non-section fields (projects, skip-*-prompt) must still be/// attributed to the file, not to env vars. These fields are NOT caught by/// the OverridableConfig pre-validation (which only covers section fields) —diff --git a/tests/integration_tests/select_config.rs b/tests/integration_tests/select_config.rsindex 4b7d476cc..4fae22986 100644--- a/tests/integration_tests/select_config.rs+++ b/tests/integration_tests/select_config.rs@@ -22,5 +22,5 @@ fn test_select_config_optional() {full = true"#;let config: UserConfig = toml::from_str(content).unwrap();- assert!(config.configs.switch.is_none());+ assert!(config.switch.is_none());}diff --git a/tests/snapshots/integration__integration_tests__list_config__list_config_env_override_bad_value_warns_on_stderr.snap b/tests/snapshots/integration__integration_tests__list_config__list_config_env_override_bad_value_warns_on_stderr.snapindex 6c25b7b81..30e1f0114 100644--- a/tests/snapshots/integration__integration_tests__list_config__list_config_env_override_bad_value_warns_on_stderr.snap+++ b/tests/snapshots/integration__integration_tests__list_config__list_config_env_override_bad_value_warns_on_stderr.snap@@ -51,5 +51,6 @@ exit_code: 0[2m○[22m [2mShowing 4 worktrees, 3 ahead----- stderr ------[33m▲[39m [33mFailed to apply WORKTRUNK_* env var override, using defaults: invalid type: string "not-a-bool", expected a boolean[39m+[33m▲[39m [33mFailed to apply WORKTRUNK_* env var override, using defaults: invalid type: string "not-a-bool", expected a boolean+in `list.branches`[39m[2m↳[22m [2mCurrently set: WORKTRUNK__LIST__BRANCHES[22m