Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor: Use `anyhow::Context` for error messages
Maximilian Roos7d0c7692c53e
diff --git a/src/commands/config.rs b/src/commands/config.rsindex 36b36847c..8992f1ff0 100644--- a/src/commands/config.rs+++ b/src/commands/config.rs@@ -62,8 +62,7 @@ pub fn handle_config_create() -> anyhow::Result<()> {// Create parent directory if it doesn't existif let Some(parent) = config_path.parent() {- std::fs::create_dir_all(parent)- .map_err(|e| anyhow::anyhow!("Failed to create config directory: {}", e))?;+ std::fs::create_dir_all(parent).context("Failed to create config directory")?;}// Write the example config with all values commented outdiff --git a/src/commands/context.rs b/src/commands/context.rsindex debde966b..331eb077f 100644--- a/src/commands/context.rs+++ b/src/commands/context.rs@@ -30,8 +30,7 @@ impl CommandEnv {/// Used in error messages when the environment can't be loaded.pub fn for_action(action: &str) -> anyhow::Result<Self> {let repo = Repository::current();- let worktree_path = std::env::current_dir()- .map_err(|e| anyhow::anyhow!("Failed to get current directory: {}", e))?;+ let worktree_path = std::env::current_dir().context("Failed to get current directory")?;let branch = repo.require_current_branch(action)?;let config = WorktrunkConfig::load().context("Failed to load config")?;let repo_root = repo.worktree_base()?;diff --git a/src/commands/list/mod.rs b/src/commands/list/mod.rsindex 6b2b9b330..80c56716a 100644--- a/src/commands/list/mod.rs+++ b/src/commands/list/mod.rs@@ -130,6 +130,7 @@ pub(crate) mod render;mod spacing_test;// Layout is calculated in collect.rs+use anyhow::Context;use model::{ListData, ListItem};use progressive::RenderMode;use worktrunk::git::Repository;@@ -178,8 +179,8 @@ pub fn handle_list(match format {crate::OutputFormat::Json => {// Display fields are already computed in collect()- let json = serde_json::to_string_pretty(&items)- .map_err(|e| anyhow::anyhow!("Failed to serialize to JSON: {}", e))?;+ let json =+ serde_json::to_string_pretty(&items).context("Failed to serialize to JSON")?;crate::output::data(json)?;}crate::OutputFormat::Table => {diff --git a/src/commands/worktree.rs b/src/commands/worktree.rsindex d5193ca2b..2ddf5eede 100644--- a/src/commands/worktree.rs+++ b/src/commands/worktree.rs@@ -220,7 +220,7 @@ fn compute_worktree_path(let relative_path = config.format_path(repo_name, branch)- .map_err(|e| anyhow::anyhow!("Failed to format worktree path: {}", e))?;+ .map_err(|e| anyhow::anyhow!("Failed to format worktree path: {e}"))?;Ok(repo_root.join(relative_path))}diff --git a/src/config/mod.rs b/src/config/mod.rsindex a27206f2d..bd7dc0307 100644--- a/src/config/mod.rs+++ b/src/config/mod.rs@@ -77,11 +77,7 @@ mod tests {fn test_format_worktree_path() {let config = WorktrunkConfig {worktree_path: "{{ main_worktree }}.{{ branch }}".to_string(),- commit_generation: CommitGenerationConfig::default(),- projects: std::collections::BTreeMap::new(),- list: None,- commit: None,- merge: None,+ ..Default::default()};assert_eq!(config.format_path("myproject", "feature-x").unwrap(),@@ -93,11 +89,7 @@ mod tests {fn test_format_worktree_path_custom_template() {let config = WorktrunkConfig {worktree_path: "{{ main_worktree }}-{{ branch }}".to_string(),- commit_generation: CommitGenerationConfig::default(),- projects: std::collections::BTreeMap::new(),- list: None,- commit: None,- merge: None,+ ..Default::default()};assert_eq!(config.format_path("myproject", "feature-x").unwrap(),@@ -109,11 +101,7 @@ mod tests {fn test_format_worktree_path_only_branch() {let config = WorktrunkConfig {worktree_path: ".worktrees/{{ main_worktree }}/{{ branch }}".to_string(),- commit_generation: CommitGenerationConfig::default(),- projects: std::collections::BTreeMap::new(),- list: None,- commit: None,- merge: None,+ ..Default::default()};assert_eq!(config.format_path("myproject", "feature-x").unwrap(),@@ -126,11 +114,7 @@ mod tests {// Slashes should be replaced with dashes to prevent directory traversallet config = WorktrunkConfig {worktree_path: "{{ main_worktree }}.{{ branch }}".to_string(),- commit_generation: CommitGenerationConfig::default(),- projects: std::collections::BTreeMap::new(),- list: None,- commit: None,- merge: None,+ ..Default::default()};assert_eq!(config.format_path("myproject", "feature/foo").unwrap(),@@ -142,11 +126,7 @@ mod tests {fn test_format_worktree_path_with_multiple_slashes() {let config = WorktrunkConfig {worktree_path: ".worktrees/{{ main_worktree }}/{{ branch }}".to_string(),- commit_generation: CommitGenerationConfig::default(),- projects: std::collections::BTreeMap::new(),- list: None,- commit: None,- merge: None,+ ..Default::default()};assert_eq!(config.format_path("myproject", "feature/sub/task").unwrap(),@@ -159,11 +139,7 @@ mod tests {// Windows-style path separators should also be sanitizedlet config = WorktrunkConfig {worktree_path: ".worktrees/{{ main_worktree }}/{{ branch }}".to_string(),- commit_generation: CommitGenerationConfig::default(),- projects: std::collections::BTreeMap::new(),- list: None,- commit: None,- merge: None,+ ..Default::default()};assert_eq!(config.format_path("myproject", "feature\\foo").unwrap(),diff --git a/src/config/project.rs b/src/config/project.rsindex ea4bd480c..35f663178 100644--- a/src/config/project.rs+++ b/src/config/project.rs@@ -7,17 +7,6 @@ use serde::{Deserialize, Serialize};use super::commands::CommandConfig;-/// Valid top-level keys for project config-// TODO: Replace with #[serde(flatten)] HashMap<String, toml::Value> on the struct-// to capture unknown fields automatically during deserialization-const VALID_PROJECT_KEYS: &[&str] = &[- "post-create",- "post-start",- "pre-commit",- "pre-merge",- "post-merge",-];-/// Project-specific configuration with hooks.////// This config is stored at `<repo>/.config/wt.toml` within the repository and@@ -74,6 +63,10 @@ pub struct ProjectConfig {/// Available template variables: `{{ repo }}`, `{{ branch }}`, `{{ worktree }}`, `{{ repo_root }}`, `{{ target }}`#[serde(default, rename = "post-merge")]pub post_merge: Option<CommandConfig>,++ /// Captures unknown fields for validation warnings+ #[serde(flatten, default, skip_serializing)]+ unknown: std::collections::HashMap<String, toml::Value>,}impl ProjectConfig {@@ -99,14 +92,12 @@ impl ProjectConfig {/// Find unknown keys in project config TOML content////// Returns a list of unrecognized top-level keys that will be silently ignored.+/// Uses serde deserialization with flatten to automatically detect unknown fields.pub fn find_unknown_keys(contents: &str) -> Vec<String> {- let Ok(table) = contents.parse::<toml::Table>() else {+ // Deserialize into ProjectConfig - unknown fields are captured in the `unknown` map+ let Ok(config) = toml::from_str::<ProjectConfig>(contents) else {return vec![];};- table- .keys()- .filter(|key| !VALID_PROJECT_KEYS.contains(&key.as_str()))- .cloned()- .collect()+ config.unknown.into_keys().collect()}diff --git a/src/config/user.rs b/src/config/user.rsindex e38876af9..c07a1dc00 100644--- a/src/config/user.rs+++ b/src/config/user.rs@@ -10,18 +10,6 @@ use std::sync::OnceLock;#[cfg(not(test))]use etcetera::base_strategy::{BaseStrategy, choose_base_strategy};-/// Valid top-level keys for user config-// TODO: Replace with #[serde(flatten)] HashMap<String, toml::Value> on the struct-// to capture unknown fields automatically during deserialization-const VALID_USER_KEYS: &[&str] = &[- "worktree-path",- "commit-generation",- "projects",- "list",- "commit",- "merge",-];-/// Global override for config path, set via --config CLI flagstatic CONFIG_PATH: OnceLock<PathBuf> = OnceLock::new();@@ -96,7 +84,7 @@ pub enum StageMode {/// `__` separator for nested fields (e.g., `WORKTRUNK_COMMIT_GENERATION__COMMAND`).#[derive(Debug, Serialize, Deserialize)]pub struct WorktrunkConfig {- #[serde(rename = "worktree-path")]+ #[serde(rename = "worktree-path", default = "default_worktree_path")]pub worktree_path: String,#[serde(default, rename = "commit-generation")]@@ -118,6 +106,10 @@ pub struct WorktrunkConfig {/// Configuration for the `wt merge` command#[serde(default, skip_serializing_if = "Option::is_none")]pub merge: Option<MergeConfig>,++ /// Captures unknown fields for validation warnings+ #[serde(flatten, default, skip_serializing)]+ pub(crate) unknown: std::collections::HashMap<String, toml::Value>,}/// Configuration for commit message generation@@ -238,15 +230,21 @@ pub struct MergeConfig {pub verify: Option<bool>,}+/// Default worktree path template (used by serde)+fn default_worktree_path() -> String {+ "../{{ main_worktree }}.{{ branch }}".to_string()+}+impl Default for WorktrunkConfig {fn default() -> Self {Self {- worktree_path: "../{{ main_worktree }}.{{ branch }}".to_string(),+ worktree_path: default_worktree_path(),commit_generation: CommitGenerationConfig::default(),projects: std::collections::BTreeMap::new(),list: None,commit: None,merge: None,+ unknown: std::collections::HashMap::new(),}}}@@ -569,14 +567,12 @@ pub fn get_config_path() -> Option<PathBuf> {/// Find unknown keys in user config TOML content////// Returns a list of unrecognized top-level keys that will be silently ignored.+/// Uses serde deserialization with flatten to automatically detect unknown fields.pub fn find_unknown_keys(contents: &str) -> Vec<String> {- let Ok(table) = contents.parse::<toml::Table>() else {+ // Deserialize into WorktrunkConfig - unknown fields are captured in the `unknown` map+ let Ok(config) = toml::from_str::<WorktrunkConfig>(contents) else {return vec![];};- table- .keys()- .filter(|key| !VALID_USER_KEYS.contains(&key.as_str()))- .cloned()- .collect()+ config.unknown.into_keys().collect()}diff --git a/src/llm.rs b/src/llm.rsindex d5a535d0d..e04a73346 100644--- a/src/llm.rs+++ b/src/llm.rs@@ -1,3 +1,4 @@+use anyhow::Context;use std::io::Write;use std::path::{Path, PathBuf};use std::process::{self, Stdio};@@ -100,15 +101,19 @@ fn execute_llm_command(command: &str, args: &[String], prompt: &str) -> anyhow::log::debug!(" {}", line);}- let mut child = cmd.spawn()?;+ let mut child = cmd.spawn().context("Failed to spawn LLM command")?;// Write prompt to stdinif let Some(mut stdin) = child.stdin.take() {- stdin.write_all(prompt.as_bytes())?;+ stdin+ .write_all(prompt.as_bytes())+ .context("Failed to write prompt to LLM stdin")?;// stdin is dropped here, closing the pipe}- let output = child.wait_with_output()?;+ let output = child+ .wait_with_output()+ .context("Failed to wait for LLM output")?;if !output.status.success() {let stderr = String::from_utf8_lossy(&output.stderr);diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex 4d46494d0..5e7545c85 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -307,18 +307,14 @@ pub fn execute_user_command(command: &str) -> anyhow::Result<()> {/// Build shell command for background worktree removal///-/// `should_delete_branch` indicates whether to delete the branch after removing the worktree.+/// `branch_to_delete` is the branch to delete after removing the worktree.+/// Pass `None` for detached HEAD or when branch should be retained./// This decision is computed upfront (checking if branch is merged) before spawning the background process.-fn build_remove_command(- worktree_path: &std::path::Path,- branch_name: &str,- should_delete_branch: bool,-) -> String {+fn build_remove_command(worktree_path: &std::path::Path, branch_to_delete: Option<&str>) -> String {use shell_escape::escape;let worktree_path_str = worktree_path.to_string_lossy();let worktree_escaped = escape(worktree_path_str.as_ref().into());- let branch_escaped = escape(branch_name.into());// Stop fsmonitor daemon first (best effort - ignore errors)// This prevents zombie daemons from accumulating when using builtin fsmonitor@@ -327,40 +323,23 @@ fn build_remove_command(worktree_escaped);- if should_delete_branch {- // Stop fsmonitor, remove worktree, and delete branch- format!(- "{} && git worktree remove {} && git branch -D {}",- stop_fsmonitor, worktree_escaped, branch_escaped- )- } else {- // Stop fsmonitor and remove the worktree- format!(- "{} && git worktree remove {}",- stop_fsmonitor, worktree_escaped- )+ match branch_to_delete {+ Some(branch_name) => {+ let branch_escaped = escape(branch_name.into());+ format!(+ "{} && git worktree remove {} && git branch -D {}",+ stop_fsmonitor, worktree_escaped, branch_escaped+ )+ }+ None => {+ format!(+ "{} && git worktree remove {}",+ stop_fsmonitor, worktree_escaped+ )+ }}}-/// Build the shell command for background worktree removal (no branch)-fn build_remove_command_no_branch(worktree_path: &std::path::Path) -> String {- use shell_escape::escape;-- let worktree_path_str = worktree_path.to_string_lossy();- let worktree_escaped = escape(worktree_path_str.as_ref().into());-- // Stop fsmonitor daemon first (best effort - ignore errors)- let stop_fsmonitor = format!(- "git -C {} fsmonitor--daemon stop 2>/dev/null || true",- worktree_escaped- );-- format!(- "{} && git worktree remove {}",- stop_fsmonitor, worktree_escaped- )-}-/// Handle output for a remove operationpub fn handle_remove_output(result: &RemoveResult,@@ -460,7 +439,7 @@ fn handle_removed_worktree_output(super::progress("Removing worktree in background (detached HEAD, no branch to delete)",)?;- let remove_command = build_remove_command_no_branch(worktree_path);+ let remove_command = build_remove_command(worktree_path, None);spawn_detached(&repo, main_path, &remove_command, "detached", "remove")?;} else {let target_repo = worktrunk::git::Repository::at(worktree_path);@@ -531,7 +510,8 @@ fn handle_removed_worktree_output(super::progress(action)?;// Build command with the decision we already made- let remove_command = build_remove_command(worktree_path, branch_name, should_delete_branch);+ let remove_command =+ build_remove_command(worktree_path, should_delete_branch.then_some(branch_name));// Spawn the removal in background - runs from main_path (where we cd'd to)spawn_detached(&repo, main_path, &remove_command, branch_name, "remove")?;