Skip to content

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

refactor: Simplify error helpers to return anyhow::Error directly

Maximilian Roos09997a5be3e7
diff --git a/src/commands/command_approval.rs b/src/commands/command_approval.rs
index 5f5d5ac89..216323b0c 100644
--- a/src/commands/command_approval.rs
+++ b/src/commands/command_approval.rs
@@ -107,7 +107,7 @@ fn prompt_for_batch_approval(commands: &[&Command], project_id: &str) -> anyhow:
// This happens AFTER showing the commands so they appear in CI/CD logs
// even when the prompt cannot be displayed (fail-fast principle)
if !io::stdin().is_terminal() {
- anyhow::bail!("{}", not_interactive());
+ return Err(not_interactive());
}
// Flush stderr before showing prompt to ensure all output is visible
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rs
index dda0f894c..3bdc5b02b 100644
--- a/src/commands/repository_ext.rs
+++ b/src/commands/repository_ext.rs
@@ -3,7 +3,7 @@ use std::process;
use std::time::{SystemTime, UNIX_EPOCH};
use super::worktree::RemoveResult;
-use anyhow::{Context, bail};
+use anyhow::Context;
use worktrunk::config::ProjectConfig;
use worktrunk::git::{Repository, conflicting_changes, no_worktree_found, worktree_missing};
use worktrunk::path::format_path_for_display;
@@ -80,12 +80,12 @@ impl RepositoryCliExt for Repository {
let worktree_path = match self.worktree_for_branch(branch_name)? {
Some(path) => path,
None => {
- bail!("{}", no_worktree_found(branch_name));
+ return Err(no_worktree_found(branch_name));
}
};
if !worktree_path.exists() {
- bail!("{}", worktree_missing(branch_name));
+ return Err(worktree_missing(branch_name));
}
let target_repo = Repository::at(&worktree_path);
@@ -144,7 +144,7 @@ impl RepositoryCliExt for Repository {
.collect();
if !overlapping.is_empty() {
- bail!("{}", conflicting_changes(&overlapping, wt_path));
+ return Err(conflicting_changes(&overlapping, wt_path));
}
let nanos = SystemTime::now()
diff --git a/src/commands/standalone.rs b/src/commands/standalone.rs
index 94c2f10e2..1d60c7e26 100644
--- a/src/commands/standalone.rs
+++ b/src/commands/standalone.rs
@@ -282,7 +282,7 @@ pub fn handle_rebase(target: Option<&str>) -> anyhow::Result<bool> {
// Verify rebase completed successfully (safety check for edge cases)
if let Some(state) = repo.worktree_state()? {
let _ = state; // used for diagnostics
- bail!("{}", worktrunk::git::rebase_conflict(&target_branch, ""));
+ return Err(worktrunk::git::rebase_conflict(&target_branch, ""));
}
// Success
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rs
index 231f3415c..7ffc0e19a 100644
--- a/src/commands/worktree.rs
+++ b/src/commands/worktree.rs
@@ -204,7 +204,7 @@ pub fn handle_switch(
// Check for conflicting conditions
if create && repo.local_branch_exists(&resolved_branch)? {
- bail!("{}", branch_already_exists(&resolved_branch));
+ return Err(branch_already_exists(&resolved_branch));
}
// Check if base flag was provided without create flag
@@ -243,7 +243,7 @@ pub fn handle_switch(
));
}
Some(_) => {
- bail!("{}", worktree_missing(&resolved_branch));
+ return Err(worktree_missing(&resolved_branch));
}
None => {}
}
@@ -319,7 +319,7 @@ pub fn handle_switch(
let path = std::path::PathBuf::from(path_str);
// Canonicalize if possible, otherwise use as-is
let normalized_path = path.canonicalize().unwrap_or(path);
- bail!("{}", worktree_path_exists(&normalized_path));
+ return Err(worktree_path_exists(&normalized_path));
}
}
// Fall back to generic error with context
@@ -523,7 +523,7 @@ pub fn handle_push(
// Check for merge commits unless allowed
let has_merge_commits = repo.has_merge_commits(&target_branch, "HEAD")?;
if !allow_merge_commits && has_merge_commits {
- bail!("{}", merge_commits_found());
+ return Err(merge_commits_found());
}
// Configure receive.denyCurrentBranch if needed
@@ -635,7 +635,7 @@ pub fn handle_push(
stash.restore()?;
}
// CommandFailed contains raw git output, wrap in PushFailed for proper formatting
- bail!("{}", push_failed(&e.to_string()));
+ return Err(push_failed(&e.to_string()));
}
if let Some(stash) = target_worktree_stash.take() {
diff --git a/src/git/error.rs b/src/git/error.rs
index 275fe88da..29da071f7 100644
--- a/src/git/error.rs
+++ b/src/git/error.rs
@@ -89,63 +89,56 @@ fn format_error_block(header: String, error: &str) -> String {
}
/// Generic formatted error message
-pub fn error_message(msg: impl std::fmt::Display) -> String {
- format!("{ERROR_EMOJI} {ERROR}{msg}{ERROR:#}")
+pub fn error_message(msg: impl std::fmt::Display) -> anyhow::Error {
+ anyhow::anyhow!("{ERROR_EMOJI} {ERROR}{msg}{ERROR:#}")
}
/// Parse error
-pub fn parse_error(msg: impl std::fmt::Display) -> String {
- format!("{ERROR_EMOJI} {ERROR}{msg}{ERROR:#}")
+pub fn parse_error(msg: impl std::fmt::Display) -> anyhow::Error {
+ anyhow::anyhow!("{ERROR_EMOJI} {ERROR}{msg}{ERROR:#}")
}
/// Detached HEAD error
-pub fn detached_head() -> String {
- format!(
+pub fn detached_head() -> anyhow::Error {
+ anyhow::anyhow!(
"{ERROR_EMOJI} {ERROR}Not on a branch (detached HEAD){ERROR:#}\n\n{HINT_EMOJI} {HINT}You are in detached HEAD state{HINT:#}"
)
}
-/// Untracked files error
-pub fn untracked_files() -> String {
- format!(
- "{ERROR_EMOJI} {ERROR}Working tree has untracked files{ERROR:#}\n\n{HINT_EMOJI} {HINT}Add them with 'git add' and try again{HINT:#}"
- )
-}
-
/// Uncommitted changes error
-pub fn uncommitted_changes() -> String {
- format!(
+pub fn uncommitted_changes() -> anyhow::Error {
+ anyhow::anyhow!(
"{ERROR_EMOJI} {ERROR}Working tree has uncommitted changes{ERROR:#}\n\n{HINT_EMOJI} {HINT}Commit or stash them first{HINT:#}"
)
}
/// Branch already exists error
-pub fn branch_already_exists(branch: &str) -> String {
- format!(
+pub fn branch_already_exists(branch: &str) -> anyhow::Error {
+ anyhow::anyhow!(
"{ERROR_EMOJI} {ERROR}Branch {ERROR_BOLD}{branch}{ERROR_BOLD:#}{ERROR} already exists{ERROR:#}\n\n{HINT_EMOJI} {HINT}Remove --create flag to switch to it{HINT:#}"
)
}
/// Worktree missing error
-pub fn worktree_missing(branch: &str) -> String {
- format!(
+pub fn worktree_missing(branch: &str) -> anyhow::Error {
+ anyhow::anyhow!(
"{ERROR_EMOJI} {ERROR}Worktree directory missing for {ERROR_BOLD}{branch}{ERROR_BOLD:#}{ERROR:#}\n\n{HINT_EMOJI} {HINT}Run 'git worktree prune' to clean up{HINT:#}"
)
}
/// No worktree found error
-pub fn no_worktree_found(branch: &str) -> String {
- format!(
+pub fn no_worktree_found(branch: &str) -> anyhow::Error {
+ anyhow::anyhow!(
"{ERROR_EMOJI} {ERROR}No worktree found for branch {ERROR_BOLD}{branch}{ERROR_BOLD:#}{ERROR:#}"
)
}
/// Worktree path occupied error
-pub fn worktree_path_occupied(branch: &str, path: &Path, occupant: Option<&str>) -> String {
+pub fn worktree_path_occupied(branch: &str, path: &Path, occupant: Option<&str>) -> anyhow::Error {
let occupant_note = occupant
.map(|b| format!(" (currently on {ERROR_BOLD}{b}{ERROR_BOLD:#})"))
.unwrap_or_default();
- format!(
+ anyhow::anyhow!(
"{ERROR_EMOJI} {ERROR}Cannot create worktree for {ERROR_BOLD}{branch}{ERROR_BOLD:#}{ERROR}: target path already exists{ERROR:#}\n\n{HINT_EMOJI} {HINT}Reuse the existing worktree at {}{} or remove it before retrying{HINT:#}",
format_path_for_display(path),
occupant_note
@@ -153,7 +146,7 @@ pub fn worktree_path_occupied(branch: &str, path: &Path, occupant: Option<&str>)
}
/// Conflicting changes error
-pub fn conflicting_changes(files: &[String], worktree_path: &Path) -> String {
+pub fn conflicting_changes(files: &[String], worktree_path: &Path) -> anyhow::Error {
let mut msg = format!(
"{ERROR_EMOJI} {ERROR}Cannot push: conflicting uncommitted changes in:{ERROR:#}\n\n"
);
@@ -165,7 +158,7 @@ pub fn conflicting_changes(files: &[String], worktree_path: &Path) -> String {
"\n{HINT_EMOJI} {HINT}Commit or stash these changes in {} first{HINT:#}",
format_path_for_display(worktree_path)
));
- msg
+ anyhow::anyhow!("{}", msg)
}
/// Not fast-forward error
@@ -173,7 +166,7 @@ pub fn not_fast_forward(
target_branch: &str,
commits_formatted: &str,
files_formatted: &str,
-) -> String {
+) -> anyhow::Error {
let mut msg = format!(
"{ERROR_EMOJI} {ERROR}Can't push to local {ERROR_BOLD}{target_branch}{ERROR_BOLD:#} branch: it has newer commits{ERROR:#}\n"
);
@@ -191,31 +184,31 @@ pub fn not_fast_forward(
msg.push_str(&format!(
"\n{HINT_EMOJI} {HINT}Use 'wt merge' to rebase your changes onto {target_branch}{HINT:#}"
));
- msg
+ anyhow::anyhow!("{}", msg)
}
/// Merge commits found error
-pub fn merge_commits_found() -> String {
- format!(
+pub fn merge_commits_found() -> anyhow::Error {
+ anyhow::anyhow!(
"{ERROR_EMOJI} {ERROR}Found merge commits in push range{ERROR:#}\n\n{HINT_EMOJI} {HINT}Use --allow-merge-commits to push non-linear history{HINT:#}"
)
}
/// Not interactive error
-pub fn not_interactive() -> String {
- format!(
+pub fn not_interactive() -> anyhow::Error {
+ anyhow::anyhow!(
"{ERROR_EMOJI} {ERROR}Cannot prompt for approval in non-interactive environment{ERROR:#}\n\n{HINT_EMOJI} {HINT}In CI/CD, use --force to skip prompts. To pre-approve commands, use 'wt beta ask-approvals'{HINT:#}"
)
}
/// Push failed error
-pub fn push_failed(error: &str) -> String {
+pub fn push_failed(error: &str) -> anyhow::Error {
let header = format!("{ERROR_EMOJI} {ERROR}Push failed{ERROR:#}");
- format_error_block(header, error)
+ anyhow::anyhow!("{}", format_error_block(header, error))
}
/// Rebase conflict error
-pub fn rebase_conflict(target_branch: &str, git_output: &str) -> String {
+pub fn rebase_conflict(target_branch: &str, git_output: &str) -> anyhow::Error {
let mut msg = format!(
"{ERROR_EMOJI} {ERROR}Rebase onto {ERROR_BOLD}{target_branch}{ERROR_BOLD:#}{ERROR} incomplete{ERROR:#}"
);
@@ -229,19 +222,23 @@ pub fn rebase_conflict(target_branch: &str, git_output: &str) -> String {
));
}
- msg
+ anyhow::anyhow!("{}", msg)
}
/// Worktree path exists error
-pub fn worktree_path_exists(path: &Path) -> String {
- format!(
+pub fn worktree_path_exists(path: &Path) -> anyhow::Error {
+ anyhow::anyhow!(
"{ERROR_EMOJI} {ERROR}Directory already exists: {ERROR_BOLD}{}{ERROR_BOLD:#}{ERROR:#}\n\n{HINT_EMOJI} {HINT}Remove the directory or use a different branch name{HINT:#}",
format_path_for_display(path)
)
}
/// Worktree creation failed error
-pub fn worktree_creation_failed(branch: &str, base_branch: Option<&str>, error: &str) -> String {
+pub fn worktree_creation_failed(
+ branch: &str,
+ base_branch: Option<&str>,
+ error: &str,
+) -> anyhow::Error {
let base_suffix = base_branch
.map(|base| format!("{ERROR} from base {ERROR_BOLD}{base}{ERROR_BOLD:#}"))
.unwrap_or_default();
@@ -249,59 +246,22 @@ pub fn worktree_creation_failed(branch: &str, base_branch: Option<&str>, error:
let header = format!(
"{ERROR_EMOJI} {ERROR}Failed to create worktree for {ERROR_BOLD}{branch}{ERROR_BOLD:#}{base_suffix}{ERROR:#}"
);
- format_error_block(header, error)
-}
-
-/// Switch failed error
-pub fn switch_failed(branch: &str, error: &str) -> String {
- let header = format!(
- "{ERROR_EMOJI} {ERROR}Failed to switch to {ERROR_BOLD}{branch}{ERROR_BOLD:#}{ERROR:#}"
- );
- format_error_block(header, error)
+ anyhow::anyhow!("{}", format_error_block(header, error))
}
/// Worktree removal failed error
-pub fn worktree_removal_failed(branch: &str, path: &Path, error: &str) -> String {
+pub fn worktree_removal_failed(branch: &str, path: &Path, error: &str) -> anyhow::Error {
let header = format!(
"{ERROR_EMOJI} {ERROR}Failed to remove worktree for {ERROR_BOLD}{branch}{ERROR_BOLD:#}{ERROR} at {ERROR_BOLD}{}{ERROR_BOLD:#}{ERROR:#}",
format_path_for_display(path)
);
- format_error_block(header, error)
+ anyhow::anyhow!("{}", format_error_block(header, error))
}
/// Branch deletion failed error
-pub fn branch_deletion_failed(branch: &str, error: &str) -> String {
+pub fn branch_deletion_failed(branch: &str, error: &str) -> anyhow::Error {
let header = format!(
"{ERROR_EMOJI} {ERROR}Failed to delete branch {ERROR_BOLD}{branch}{ERROR_BOLD:#}{ERROR:#}"
);
- format_error_block(header, error)
-}
-
-/// Cannot remove main worktree error
-pub fn cannot_remove_main_worktree() -> String {
- format!(
- "{ERROR_EMOJI} {ERROR}Cannot remove main worktree{ERROR:#}\n\n{HINT_EMOJI} {HINT}Use 'wt remove' from a secondary worktree, or 'wt switch' to change branches{HINT:#}"
- )
-}
-
-// =============================================================================
-// Conversions
-// =============================================================================
-
-/// Convert io::Error to anyhow::Error, parsing exit codes from error messages
-///
-/// Protocol: execute_streaming() embeds exit codes in error messages as:
-/// "CHILD_EXIT_CODE:{code} {original_message}"
-/// This allows passing exit codes through io::Error while preserving context.
-pub fn from_io_error(e: std::io::Error) -> anyhow::Error {
- let msg = e.to_string();
- // Parse exit code from error message (format: "CHILD_EXIT_CODE:130 Command failed...")
- if let Some(rest) = msg.strip_prefix("CHILD_EXIT_CODE:")
- && let Some(space_idx) = rest.find(' ')
- && let Ok(code) = rest[..space_idx].parse::<i32>()
- {
- let message = rest[space_idx + 1..].to_string();
- return WorktrunkError::ChildProcessExited { code, message }.into();
- }
- anyhow::Error::from(e)
+ anyhow::anyhow!("{}", format_error_block(header, error))
}
diff --git a/src/git/mod.rs b/src/git/mod.rs
index b1bbd83da..0689e8d36 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -31,12 +31,11 @@ static HEAVY_OPS_SEMAPHORE: LazyLock<semaphore::Semaphore> =
// Re-exports from submodules
pub use diff::{DiffStats, LineDiff};
pub use error::{
- WorktrunkError, branch_already_exists, branch_deletion_failed, cannot_remove_main_worktree,
- conflicting_changes, detached_head, error_message, exit_code, from_io_error,
- is_command_not_approved, merge_commits_found, no_worktree_found, not_fast_forward,
- not_interactive, parse_error, push_failed, rebase_conflict, switch_failed, uncommitted_changes,
- untracked_files, worktree_creation_failed, worktree_missing, worktree_path_exists,
- worktree_path_occupied, worktree_removal_failed,
+ WorktrunkError, branch_already_exists, branch_deletion_failed, conflicting_changes,
+ detached_head, error_message, exit_code, is_command_not_approved, merge_commits_found,
+ no_worktree_found, not_fast_forward, not_interactive, parse_error, push_failed,
+ rebase_conflict, uncommitted_changes, worktree_creation_failed, worktree_missing,
+ worktree_path_exists, worktree_path_occupied, worktree_removal_failed,
};
pub use repository::{Repository, set_base_path};
@@ -95,7 +94,7 @@ impl WorktreeList {
let worktrees: Vec<_> = raw_worktrees.into_iter().filter(|wt| !wt.bare).collect();
if worktrees.is_empty() {
- anyhow::bail!("{}", error_message("No worktrees found"));
+ return Err(error_message("No worktrees found"));
}
Ok(Self { worktrees })
diff --git a/src/git/parse.rs b/src/git/parse.rs
index 9d2b192f9..a68add38e 100644
--- a/src/git/parse.rs
+++ b/src/git/parse.rs
@@ -27,7 +27,7 @@ impl Worktree {
match key {
"worktree" => {
let Some(path) = value else {
- bail!("{}", parse_error("worktree line missing path"));
+ return Err(parse_error("worktree line missing path"));
};
current = Some(Worktree {
path: PathBuf::from(path),
@@ -42,14 +42,14 @@ impl Worktree {
key => match (key, current.as_mut()) {
("HEAD", Some(wt)) => {
let Some(sha) = value else {
- bail!("{}", parse_error("HEAD line missing SHA"));
+ return Err(parse_error("HEAD line missing SHA"));
};
wt.head = sha.to_string();
}
("branch", Some(wt)) => {
// Strip refs/heads/ prefix if present
let Some(branch_ref) = value else {
- bail!("{}", parse_error("branch line missing ref"));
+ return Err(parse_error("branch line missing ref"));
};
let branch = branch_ref
.strip_prefix("refs/heads/")
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index ef8b690cc..4b5c26c0d 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -419,7 +419,7 @@ impl Repository {
/// Returns an error if there are uncommitted changes.
pub fn ensure_clean_working_tree(&self) -> anyhow::Result<()> {
if self.is_dirty()? {
- bail!("{}", uncommitted_changes());
+ return Err(uncommitted_changes());
}
Ok(())
}
diff --git a/src/output/directive.rs b/src/output/directive.rs
index a231e7ca9..525a65239 100644
--- a/src/output/directive.rs
+++ b/src/output/directive.rs
@@ -131,9 +131,10 @@ impl DirectiveOutput {
io::stdout().flush()
}
- pub fn execute(&mut self, command: String) -> io::Result<()> {
+ pub fn execute(&mut self, command: String) -> anyhow::Result<()> {
write!(io::stdout(), "__WORKTRUNK_EXEC__{}\0", command)?;
- io::stdout().flush()
+ io::stdout().flush()?;
+ Ok(())
}
pub fn flush(&mut self) -> io::Result<()> {
diff --git a/src/output/global.rs b/src/output/global.rs
index dc7c54254..b74aa7c9f 100644
--- a/src/output/global.rs
+++ b/src/output/global.rs
@@ -234,7 +234,7 @@ pub fn change_directory(path: impl AsRef<Path>) -> io::Result<()> {
}
/// Request command execution
-pub fn execute(command: impl Into<String>) -> io::Result<()> {
+pub fn execute(command: impl Into<String>) -> anyhow::Result<()> {
OUTPUT_CONTEXT.with(|ctx| {
let cmd = command.into();
match &mut *ctx.borrow_mut() {
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 5a8a20374..323456726 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -138,14 +138,13 @@ pub fn handle_switch_output(
/// Execute the --execute command after hooks have run
pub fn execute_user_command(command: &str) -> anyhow::Result<()> {
- use worktrunk::git::from_io_error;
use worktrunk::styling::{CYAN, format_bash_with_gutter};
// Show what command is being executed (section header + gutter content)
super::progress(format!("{CYAN}Executing (--execute):{CYAN:#}"))?;
super::gutter(format_bash_with_gutter(command, ""))?;
- super::execute(command).map_err(from_io_error)?;
+ super::execute(command)?;
Ok(())
}
@@ -329,9 +328,9 @@ pub(crate) fn execute_streaming(
command: &str,
working_dir: &std::path::Path,
redirect_stdout_to_stderr: bool,
-) -> std::io::Result<()> {
- use std::io;
+) -> anyhow::Result<()> {
use std::process::Command;
+ use worktrunk::git::WorktrunkError;
let command_to_run = if redirect_stdout_to_stderr {
// Use newline instead of semicolon before closing brace to support
@@ -349,20 +348,21 @@ pub(crate) fn execute_streaming(
.stdout(std::process::Stdio::inherit()) // Preserve TTY for output
.stderr(std::process::Stdio::inherit()) // Preserve TTY for errors
.spawn()
- .map_err(|e| io::Error::other(format!("Failed to execute command: {}", e)))?;
+ .map_err(|e| anyhow::anyhow!("Failed to execute command: {}", e))?;
// Wait for command to complete
let status = child
.wait()
- .map_err(|e| io::Error::other(format!("Failed to wait for command: {}", e)))?;
+ .map_err(|e| anyhow::anyhow!("Failed to wait for command: {}", e))?;
if !status.success() {
// Get the exit code if available (None means terminated by signal on some platforms)
let code = status.code().unwrap_or(1);
- return Err(io::Error::other(format!(
- "CHILD_EXIT_CODE:{} exit status: {}",
- code, code
- )));
+ return Err(WorktrunkError::ChildProcessExited {
+ code,
+ message: format!("exit status: {}", code),
+ }
+ .into());
}
Ok(())
@@ -408,8 +408,7 @@ pub fn execute_command_in_worktree(
stderr().flush().ok(); // Ignore flush errors - reset is best-effort, command execution should proceed
// Execute with stdout→stderr redirect for deterministic ordering
- // io::Error is converted via from_io_error to parse embedded exit codes
- execute_streaming(command, worktree_path, true).map_err(worktrunk::git::from_io_error)?;
+ execute_streaming(command, worktree_path, true)?;
// Flush to ensure all output appears before we continue
super::flush()?;
diff --git a/src/output/interactive.rs b/src/output/interactive.rs
index 7edf557b2..585af98ad 100644
--- a/src/output/interactive.rs
+++ b/src/output/interactive.rs
@@ -116,7 +116,7 @@ impl InteractiveOutput {
Ok(())
}
- pub fn execute(&mut self, command: String) -> io::Result<()> {
+ pub fn execute(&mut self, command: String) -> anyhow::Result<()> {
// Execute command in the target directory with streaming output
let exec_dir = self.target_dir.as_deref().unwrap_or_else(|| Path::new("."));