Skip to content

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

feat: Migrate error handling to anyhow and update docs

Maximilian Roos7596c340c278
diff --git a/Cargo.lock b/Cargo.lock
index 770c4094b..eabeae904 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3032,6 +3032,7 @@ dependencies = [
"ansi-str",
"anstream",
"anstyle",
+ "anyhow",
"askama",
"chrono",
"clap",
diff --git a/Cargo.toml b/Cargo.toml
index 9ea5eb079..e018daedc 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -33,6 +33,7 @@ name = "wt"
path = "src/main.rs"
[dependencies]
+anyhow = "1.0"
anstream = "0.6"
anstyle = "1.0"
ansi-str = "0.9"
diff --git a/src/commands/command_approval.rs b/src/commands/command_approval.rs
index 8c97ae56e..5f5d5ac89 100644
--- a/src/commands/command_approval.rs
+++ b/src/commands/command_approval.rs
@@ -2,8 +2,9 @@
//!
//! Shared helpers for approving commands declared in project configuration.
+use anyhow::Context;
use worktrunk::config::{Command, WorktrunkConfig};
-use worktrunk::git::{GitError, GitResultExt};
+use worktrunk::git::not_interactive;
use worktrunk::styling::{
AnstyleStyle, HINT, HINT_EMOJI, PROGRESS_EMOJI, WARNING, WARNING_BOLD, WARNING_EMOJI, eprint,
eprintln, format_bash_with_gutter, println, stderr,
@@ -23,7 +24,7 @@ pub fn approve_command_batch(
config: &WorktrunkConfig,
force: bool,
commands_already_filtered: bool,
-) -> Result<bool, GitError> {
+) -> anyhow::Result<bool> {
let needs_approval: Vec<&Command> = commands
.iter()
.filter(|cmd| {
@@ -47,7 +48,7 @@ pub fn approve_command_batch(
// Only save approvals when interactively approved, not when using --force
if !force {
- let mut fresh_config = WorktrunkConfig::load().git_context("Failed to reload config")?;
+ let mut fresh_config = WorktrunkConfig::load().context("Failed to reload config")?;
let project_entry = fresh_config
.projects
@@ -71,7 +72,7 @@ pub fn approve_command_batch(
Ok(true)
}
-fn prompt_for_batch_approval(commands: &[&Command], project_id: &str) -> Result<bool, GitError> {
+fn prompt_for_batch_approval(commands: &[&Command], project_id: &str) -> anyhow::Result<bool> {
use std::io::{self, IsTerminal, Write};
let project_name = project_id.split('/').next_back().unwrap_or(project_id);
@@ -106,7 +107,7 @@ fn prompt_for_batch_approval(commands: &[&Command], project_id: &str) -> Result<
// 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() {
- return Err(GitError::NotInteractive);
+ anyhow::bail!("{}", not_interactive());
}
// Flush stderr before showing prompt to ensure all output is visible
diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rs
index 0e639573a..7a0c21dbf 100644
--- a/src/commands/command_executor.rs
+++ b/src/commands/command_executor.rs
@@ -1,7 +1,7 @@
use std::collections::HashMap;
use std::path::Path;
use worktrunk::config::{Command, CommandConfig, CommandPhase, WorktrunkConfig, expand_template};
-use worktrunk::git::{GitError, Repository};
+use worktrunk::git::{Repository, WorktrunkError};
use super::command_approval::approve_command_batch;
@@ -49,7 +49,7 @@ fn expand_commands(
commands: &[Command],
ctx: &CommandContext<'_>,
extra_vars: &[(&str, &str)],
-) -> Result<Vec<Command>, GitError> {
+) -> anyhow::Result<Vec<Command>> {
if commands.is_empty() {
return Ok(Vec::new());
}
@@ -83,10 +83,11 @@ fn expand_commands(
for cmd in commands {
let expanded_str = expand_template(&cmd.template, repo_name, ctx.branch, &extras_ref)
.map_err(|e| {
- GitError::message(format!(
+ anyhow::anyhow!(
"Failed to expand command template '{}': {}",
- cmd.template, e
- ))
+ cmd.template,
+ e
+ )
})?;
expanded_commands.push(Command::with_expansion(
cmd.name.clone(),
@@ -106,14 +107,14 @@ fn expand_commands(
/// 2. Requests user approval for unapproved commands (unless auto_trust or force)
/// 3. Returns prepared commands ready for execution
///
-/// Returns `Err(GitError::CommandNotApproved)` if the user declines approval.
+/// Returns `Err(WorktrunkError::CommandNotApproved)` if the user declines approval.
pub fn prepare_project_commands(
command_config: &CommandConfig,
ctx: &CommandContext<'_>,
auto_trust: bool,
extra_vars: &[(&str, &str)],
phase: CommandPhase,
-) -> Result<Vec<PreparedCommand>, GitError> {
+) -> anyhow::Result<Vec<PreparedCommand>> {
let commands = command_config.commands_with_phase(phase);
if commands.is_empty() {
return Ok(Vec::new());
@@ -138,7 +139,7 @@ pub fn prepare_project_commands(
false,
)?
{
- return Err(GitError::CommandNotApproved);
+ return Err(WorktrunkError::CommandNotApproved.into());
}
Ok(expanded_commands
diff --git a/src/commands/commit.rs b/src/commands/commit.rs
index 67f682c4e..123bcf2ad 100644
--- a/src/commands/commit.rs
+++ b/src/commands/commit.rs
@@ -1,5 +1,6 @@
+use anyhow::Context;
use worktrunk::config::CommitGenerationConfig;
-use worktrunk::git::{GitError, GitResultExt, Repository};
+use worktrunk::git::Repository;
use worktrunk::styling::{AnstyleStyle, CYAN, GREEN, HINT, format_with_gutter};
use super::command_executor::CommandContext;
@@ -61,7 +62,7 @@ impl<'a> CommitGenerator<'a> {
result
}
- pub fn emit_hint_if_needed(&self) -> Result<(), GitError> {
+ pub fn emit_hint_if_needed(&self) -> anyhow::Result<()> {
if !self.config.is_configured() {
crate::output::hint(format!(
"{HINT}Using fallback commit message. Run 'wt config --help' for LLM setup guide{HINT:#}"
@@ -70,7 +71,7 @@ impl<'a> CommitGenerator<'a> {
Ok(())
}
- pub fn commit_staged_changes(&self, show_no_squash_note: bool) -> Result<(), GitError> {
+ pub fn commit_staged_changes(&self, show_no_squash_note: bool) -> anyhow::Result<()> {
let repo = Repository::current();
let stats_parts = repo.diff_stats_summary(&["diff", "--staged", "--shortstat"]);
@@ -104,7 +105,7 @@ impl<'a> CommitGenerator<'a> {
crate::output::gutter(format_with_gutter(&formatted_message, "", None))?;
repo.run_command(&["commit", "-m", &commit_message])
- .git_context("Failed to commit")?;
+ .context("Failed to commit")?;
let commit_hash = repo
.run_command(&["rev-parse", "--short", "HEAD"])?
@@ -122,7 +123,7 @@ impl<'a> CommitGenerator<'a> {
/// Commit uncommitted changes with the shared commit pipeline.
impl CommitOptions<'_> {
- pub fn commit(self) -> Result<(), GitError> {
+ pub fn commit(self) -> anyhow::Result<()> {
if !self.no_verify
&& let Some(project_config) = self.ctx.repo.load_project_config()?
{
@@ -138,12 +139,12 @@ impl CommitOptions<'_> {
self.ctx
.repo
.run_command(&["add", "-u"])
- .git_context("Failed to stage tracked changes")?;
+ .context("Failed to stage tracked changes")?;
} else {
self.ctx
.repo
.run_command(&["add", "-A"])
- .git_context("Failed to stage changes")?;
+ .context("Failed to stage changes")?;
}
CommitGenerator::new(&self.ctx.config.commit_generation)
diff --git a/src/commands/config.rs b/src/commands/config.rs
index 695aa1e81..68ec0b6e3 100644
--- a/src/commands/config.rs
+++ b/src/commands/config.rs
@@ -1,6 +1,7 @@
+use anyhow::Context;
use etcetera::base_strategy::{BaseStrategy, choose_base_strategy};
use std::path::PathBuf;
-use worktrunk::git::{GitError, GitResultExt, Repository};
+use worktrunk::git::{Repository, detached_head};
use worktrunk::path::format_path_for_display;
use worktrunk::styling::{
AnstyleStyle, CYAN, GREEN, GREEN_BOLD, HINT, HINT_EMOJI, INFO_EMOJI, SUCCESS_EMOJI,
@@ -11,10 +12,9 @@ use worktrunk::styling::{
const CONFIG_EXAMPLE: &str = include_str!("../../config.example.toml");
/// Handle the config init command
-pub fn handle_config_init() -> Result<(), GitError> {
- let config_path = get_global_config_path().ok_or_else(|| {
- GitError::CommandFailed("Could not determine global config path".to_string())
- })?;
+pub fn handle_config_init() -> anyhow::Result<()> {
+ let config_path = get_global_config_path()
+ .ok_or_else(|| anyhow::anyhow!("Could not determine global config path"))?;
// Check if file already exists
if config_path.exists() {
@@ -30,13 +30,12 @@ pub fn handle_config_init() -> Result<(), GitError> {
// Create parent directory if it doesn't exist
if let Some(parent) = config_path.parent() {
- std::fs::create_dir_all(parent).map_err(|e| {
- GitError::CommandFailed(format!("Failed to create config directory: {}", e))
- })?;
+ std::fs::create_dir_all(parent)
+ .map_err(|e| anyhow::anyhow!("Failed to create config directory: {}", e))?;
}
// Write the example config
- std::fs::write(&config_path, CONFIG_EXAMPLE).git_context("Failed to write config file")?;
+ std::fs::write(&config_path, CONFIG_EXAMPLE).context("Failed to write config file")?;
// Success message
let green_bold = GREEN.bold();
@@ -53,7 +52,7 @@ pub fn handle_config_init() -> Result<(), GitError> {
}
/// Handle the config list command
-pub fn handle_config_list() -> Result<(), GitError> {
+pub fn handle_config_list() -> anyhow::Result<()> {
// Display global config
display_global_config()?;
println!();
@@ -64,13 +63,12 @@ pub fn handle_config_list() -> Result<(), GitError> {
Ok(())
}
-fn display_global_config() -> Result<(), GitError> {
+fn display_global_config() -> anyhow::Result<()> {
let bold = AnstyleStyle::new().bold();
// Get config path
- let config_path = get_global_config_path().ok_or_else(|| {
- GitError::CommandFailed("Could not determine global config path".to_string())
- })?;
+ let config_path = get_global_config_path()
+ .ok_or_else(|| anyhow::anyhow!("Could not determine global config path"))?;
println!(
"{INFO_EMOJI} Global Config: {bold}{}{bold:#}",
@@ -89,8 +87,7 @@ fn display_global_config() -> Result<(), GitError> {
}
// Read and display the file contents
- let contents =
- std::fs::read_to_string(&config_path).git_context("Failed to read config file")?;
+ let contents = std::fs::read_to_string(&config_path).context("Failed to read config file")?;
if contents.trim().is_empty() {
println!("{HINT_EMOJI} {HINT}Empty file (using defaults){HINT:#}");
@@ -103,7 +100,7 @@ fn display_global_config() -> Result<(), GitError> {
Ok(())
}
-fn display_project_config() -> Result<(), GitError> {
+fn display_project_config() -> anyhow::Result<()> {
let bold = AnstyleStyle::new().bold();
let dim = AnstyleStyle::new().dimmed();
@@ -130,8 +127,7 @@ fn display_project_config() -> Result<(), GitError> {
}
// Read and display the file contents
- let contents =
- std::fs::read_to_string(&config_path).git_context("Failed to read config file")?;
+ let contents = std::fs::read_to_string(&config_path).context("Failed to read config file")?;
if contents.trim().is_empty() {
println!("{HINT_EMOJI} {HINT}Empty file{HINT:#}");
@@ -167,7 +163,7 @@ fn get_global_config_path() -> Option<PathBuf> {
}
/// Handle the config refresh-cache command
-pub fn handle_config_refresh_cache() -> Result<(), GitError> {
+pub fn handle_config_refresh_cache() -> anyhow::Result<()> {
let repo = Repository::current();
// Display progress message
@@ -187,7 +183,7 @@ pub fn handle_config_refresh_cache() -> Result<(), GitError> {
}
/// Handle the config status set command
-pub fn handle_config_status_set(value: String, branch: Option<String>) -> Result<(), GitError> {
+pub fn handle_config_status_set(value: String, branch: Option<String>) -> anyhow::Result<()> {
let repo = Repository::current();
// TODO: Worktree-specific status (worktrunk.status with --worktree flag) would allow
@@ -197,9 +193,9 @@ pub fn handle_config_status_set(value: String, branch: Option<String>) -> Result
let branch_name = match branch {
Some(b) => b,
- None => repo.current_branch()?.ok_or_else(|| {
- GitError::CommandFailed("Not on a branch (detached HEAD)".to_string())
- })?,
+ None => repo
+ .current_branch()?
+ .ok_or_else(|| anyhow::anyhow!("{}", detached_head()))?,
};
let config_key = format!("worktrunk.status.{}", branch_name);
@@ -214,7 +210,7 @@ pub fn handle_config_status_set(value: String, branch: Option<String>) -> Result
}
/// Handle the config status unset command
-pub fn handle_config_status_unset(target: String) -> Result<(), GitError> {
+pub fn handle_config_status_unset(target: String) -> anyhow::Result<()> {
let repo = Repository::current();
if target == "*" {
@@ -242,16 +238,15 @@ pub fn handle_config_status_unset(target: String) -> Result<(), GitError> {
} else {
// Clear specific branch status
let branch_name = if target.is_empty() {
- repo.current_branch()?.ok_or_else(|| {
- GitError::CommandFailed("Not on a branch (detached HEAD)".to_string())
- })?
+ repo.current_branch()?
+ .ok_or_else(|| anyhow::anyhow!("{}", detached_head()))?
} else {
target
};
let config_key = format!("worktrunk.status.{}", branch_name);
repo.run_command(&["config", "--unset", &config_key])
- .git_context("Failed to unset status (may not be set)")?;
+ .context("Failed to unset status (may not be set)")?;
let branch_bold = GREEN.bold();
crate::output::success(format!(
diff --git a/src/commands/context.rs b/src/commands/context.rs
index f0d4f4275..f00a368d9 100644
--- a/src/commands/context.rs
+++ b/src/commands/context.rs
@@ -1,15 +1,16 @@
+use anyhow::Context;
use std::path::PathBuf;
use worktrunk::config::WorktrunkConfig;
-use worktrunk::git::{GitError, GitResultExt, Repository};
+use worktrunk::git::{Repository, detached_head};
use super::command_executor::CommandContext;
/// Shared execution context for command handlers that operate on the current worktree.
///
-/// Centralizes the common “repo + branch + config + cwd” setup so individual handlers
+/// Centralizes the common "repo + branch + config + cwd" setup so individual handlers
/// can focus on their core logic while sharing consistent error messaging.
///
-/// This helper is used for commands that explicitly act on “where the user is standing”
+/// This helper is used for commands that explicitly act on "where the user is standing"
/// (e.g., `beta` and `merge`) and therefore need all of these pieces together. Commands that
/// inspect multiple worktrees or run without a config/branch requirement (`list`, `select`,
/// some `worktree` helpers) still call `Repository::current()` directly so they can operate in
@@ -24,16 +25,15 @@ pub struct CommandEnv {
impl CommandEnv {
/// Load the command environment from the current process context.
- pub fn current() -> Result<Self, GitError> {
+ pub fn current() -> anyhow::Result<Self> {
let repo = Repository::current();
- let worktree_path = std::env::current_dir().map_err(|e| {
- GitError::CommandFailed(format!("Failed to get current directory: {}", e))
- })?;
+ let worktree_path = std::env::current_dir()
+ .map_err(|e| anyhow::anyhow!("Failed to get current directory: {}", e))?;
let branch = repo
.current_branch()
- .git_context("Failed to get current branch")?
- .ok_or(GitError::DetachedHead)?;
- let config = WorktrunkConfig::load().git_context("Failed to load config")?;
+ .context("Failed to get current branch")?
+ .ok_or_else(|| anyhow::anyhow!("{}", detached_head()))?;
+ let config = WorktrunkConfig::load().context("Failed to load config")?;
let repo_root = repo.worktree_base()?;
Ok(Self {
diff --git a/src/commands/hooks.rs b/src/commands/hooks.rs
index b230fec42..dec35c21d 100644
--- a/src/commands/hooks.rs
+++ b/src/commands/hooks.rs
@@ -1,6 +1,6 @@
use worktrunk::HookType;
use worktrunk::config::{CommandConfig, CommandPhase, ProjectConfig};
-use worktrunk::git::GitError;
+use worktrunk::git::WorktrunkError;
use worktrunk::styling::{CYAN, WARNING, WARNING_BOLD, format_bash_with_gutter};
use super::command_executor::{CommandContext, PreparedCommand, prepare_project_commands};
@@ -32,7 +32,7 @@ impl<'a> HookPipeline<'a> {
phase: CommandPhase,
auto_trust: bool,
extra_vars: &[(&str, &str)],
- ) -> Result<Vec<PreparedCommand>, GitError> {
+ ) -> anyhow::Result<Vec<PreparedCommand>> {
prepare_project_commands(command_config, &self.ctx, auto_trust, extra_vars, phase)
}
@@ -47,7 +47,7 @@ impl<'a> HookPipeline<'a> {
label_prefix: &str,
hook_type: HookType,
failure_strategy: HookFailureStrategy,
- ) -> Result<(), GitError> {
+ ) -> anyhow::Result<()> {
let commands = self.prepare_commands(command_config, phase, auto_trust, extra_vars)?;
if commands.is_empty() {
return Ok(());
@@ -65,24 +65,28 @@ impl<'a> HookPipeline<'a> {
if let Err(err) =
execute_command_in_worktree(self.ctx.worktree_path, &prepared.expanded)
{
- // Extract raw message for embedding (without formatting from Display impl)
- let err_msg = match &err {
- GitError::ChildProcessExited { message, .. } => message.clone(),
- other => other.to_string(),
- };
- let exit_code = match &err {
- GitError::ChildProcessExited { code, .. } => Some(*code),
- _ => None,
- };
+ // Extract raw message and exit code from error
+ let (err_msg, exit_code) =
+ if let Some(wt_err) = err.downcast_ref::<WorktrunkError>() {
+ match wt_err {
+ WorktrunkError::ChildProcessExited { message, code } => {
+ (message.clone(), Some(*code))
+ }
+ _ => (err.to_string(), None),
+ }
+ } else {
+ (err.to_string(), None)
+ };
match &failure_strategy {
HookFailureStrategy::FailFast => {
- return Err(GitError::HookCommandFailed {
+ return Err(WorktrunkError::HookCommandFailed {
hook_type,
command_name: prepared.name.clone(),
error: err_msg,
exit_code,
- });
+ }
+ .into());
}
HookFailureStrategy::Warn => {
let message = match &prepared.name {
@@ -108,12 +112,13 @@ impl<'a> HookPipeline<'a> {
// For Warn strategy with PostMerge: if any command failed, propagate the exit code
// This matches git's behavior: post-hooks can't stop the operation but affect exit status
if let Some((error, command_name, exit_code)) = first_failure {
- return Err(GitError::HookCommandFailed {
+ return Err(WorktrunkError::HookCommandFailed {
hook_type,
command_name,
error,
exit_code: Some(exit_code),
- });
+ }
+ .into());
}
Ok(())
@@ -127,7 +132,7 @@ impl<'a> HookPipeline<'a> {
auto_trust: bool,
extra_vars: &[(&str, &str)],
label_prefix: &str,
- ) -> Result<(), GitError> {
+ ) -> anyhow::Result<()> {
let commands = self.prepare_commands(command_config, phase, auto_trust, extra_vars)?;
if commands.is_empty() {
return Ok(());
@@ -168,7 +173,7 @@ impl<'a> HookPipeline<'a> {
project_config: &ProjectConfig,
target_branch: Option<&str>,
auto_trust: bool,
- ) -> Result<(), GitError> {
+ ) -> anyhow::Result<()> {
let Some(pre_commit_config) = &project_config.pre_commit_command else {
return Ok(());
};
diff --git a/src/commands/list/collect.rs b/src/commands/list/collect.rs
index 24affa89d..358a423c5 100644
--- a/src/commands/list/collect.rs
+++ b/src/commands/list/collect.rs
@@ -21,7 +21,7 @@
//! This ensures fast operations don't wait for slow ones (e.g., CI doesn't block ahead/behind counts)
use crossbeam_channel as chan;
use rayon::prelude::*;
-use worktrunk::git::{GitError, LineDiff, Repository, Worktree};
+use worktrunk::git::{LineDiff, Repository, Worktree};
use worktrunk::styling::INFO_EMOJI;
use super::ci_status::PrStatus;
@@ -408,7 +408,7 @@ fn drain_cell_updates(
fn get_branches_without_worktrees(
repo: &Repository,
worktrees: &[Worktree],
-) -> Result<Vec<(String, String)>, GitError> {
+) -> anyhow::Result<Vec<(String, String)>> {
// Get all local branches
let all_branches = repo.list_local_branches()?;
@@ -441,7 +441,7 @@ pub fn collect(
check_merge_tree_conflicts: bool,
show_progress: bool,
render_table: bool,
-) -> Result<Option<super::model::ListData>, GitError> {
+) -> anyhow::Result<Option<super::model::ListData>> {
use indicatif::{MultiProgress, ProgressBar, ProgressStyle};
use std::time::Duration;
diff --git a/src/commands/list/mod.rs b/src/commands/list/mod.rs
index 74d908921..c3524df75 100644
--- a/src/commands/list/mod.rs
+++ b/src/commands/list/mod.rs
@@ -89,14 +89,14 @@ mod spacing_test;
// Layout is calculated in collect.rs
use model::{ListData, ListItem};
use progressive::RenderMode;
-use worktrunk::git::{GitError, Repository};
+use worktrunk::git::Repository;
pub fn handle_list(
format: crate::OutputFormat,
show_branches: bool,
show_full: bool,
render_mode: RenderMode,
-) -> Result<(), GitError> {
+) -> anyhow::Result<()> {
let repo = Repository::current();
let fetch_ci = show_full; // Only fetch CI with --full (expensive)
@@ -128,9 +128,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| {
- GitError::CommandFailed(format!("Failed to serialize to JSON: {}", e))
- })?;
+ let json = serde_json::to_string_pretty(&items)
+ .map_err(|e| anyhow::anyhow!("Failed to serialize to JSON: {}", e))?;
crate::output::raw(json)?;
}
crate::OutputFormat::Table => {
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index cc56fe3d3..5871db4b8 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -1,6 +1,6 @@
use worktrunk::HookType;
use worktrunk::config::{Command, CommandPhase, ProjectConfig};
-use worktrunk::git::{GitError, Repository};
+use worktrunk::git::Repository;
use worktrunk::path::format_path_for_display;
use worktrunk::styling::{CYAN, ERROR, ERROR_EMOJI, GREEN_BOLD, HINT, HINT_EMOJI};
@@ -29,7 +29,7 @@ impl<'a> MergeCommandCollector<'a> {
/// Collect all commands that will be executed during merge
///
/// Returns original (unexpanded) commands for approval matching
- fn collect(self) -> Result<CollectedCommands, GitError> {
+ fn collect(self) -> anyhow::Result<CollectedCommands> {
let mut all_commands = Vec::new();
let project_config = match self.repo.load_project_config()? {
Some(cfg) => cfg,
@@ -67,7 +67,7 @@ pub fn handle_merge(
no_verify: bool,
force: bool,
tracked_only: bool,
-) -> Result<(), GitError> {
+) -> anyhow::Result<()> {
let env = CommandEnv::current()?;
let repo = &env.repo;
let config = &env.config;
@@ -75,12 +75,12 @@ pub fn handle_merge(
// Validate --no-commit: requires clean working tree
if no_commit && repo.is_dirty()? {
- return Err(GitError::UncommittedChanges);
+ return Err(anyhow::anyhow!("{}", worktrunk::git::uncommitted_changes()));
}
// Validate --no-commit flag compatibility
if no_commit && !no_remove {
- return Err(GitError::CommandFailed(format!(
+ return Err(anyhow::anyhow!(format!(
"{ERROR_EMOJI} {ERROR}--no-commit requires --no-remove{ERROR:#}\n\n{HINT_EMOJI} {HINT}Cannot remove active worktree when skipping commit/rebase{HINT:#}"
)));
}
@@ -241,7 +241,7 @@ fn format_merge_summary(main_path: Option<&std::path::Path>) -> String {
}
/// Handle output for merge summary using global output context
-fn handle_merge_summary_output(main_path: Option<&std::path::Path>) -> Result<(), GitError> {
+fn handle_merge_summary_output(main_path: Option<&std::path::Path>) -> anyhow::Result<()> {
let message = format_merge_summary(main_path);
// Show success message (formatting added by OutputContext)
@@ -262,7 +262,7 @@ pub fn run_pre_merge_commands(
ctx: &CommandContext,
target_branch: &str,
auto_trust: bool,
-) -> Result<(), GitError> {
+) -> anyhow::Result<()> {
let Some(pre_merge_config) = &project_config.pre_merge_command else {
return Ok(());
};
@@ -289,7 +289,7 @@ pub fn execute_post_merge_commands(
ctx: &CommandContext,
target_branch: &str,
auto_trust: bool,
-) -> Result<(), GitError> {
+) -> anyhow::Result<()> {
// Load project config from the main worktree path directly
let project_config = match ctx.repo.load_project_config()? {
Some(cfg) => cfg,
diff --git a/src/commands/process.rs b/src/commands/process.rs
index 6c4a76ee0..8c0fd2635 100644
--- a/src/commands/process.rs
+++ b/src/commands/process.rs
@@ -1,7 +1,7 @@
use std::fs;
use std::path::Path;
use std::process::{Command, Stdio};
-use worktrunk::git::{GitError, Repository};
+use worktrunk::git::Repository;
/// Spawn a detached background process with output redirected to a log file
///
@@ -26,14 +26,14 @@ pub fn spawn_detached(
command: &str,
branch: &str,
name: &str,
-) -> Result<std::path::PathBuf, GitError> {
+) -> anyhow::Result<std::path::PathBuf> {
// Get the git common directory (shared across all worktrees)
let git_common_dir = repo.git_common_dir()?;
// Create log directory in the common git directory
let log_dir = git_common_dir.join("wt-logs");
fs::create_dir_all(&log_dir)
- .map_err(|e| GitError::CommandFailed(format!("Failed to create log directory\n {e}")))?;
+ .map_err(|e| anyhow::anyhow!("Failed to create log directory\n {e}"))?;
// Generate log filename (no timestamp - overwrites on each run)
// Format: {branch}-{name}.log (e.g., "feature-post-start-npm.log", "bugfix-remove.log")
@@ -44,7 +44,7 @@ pub fn spawn_detached(
// Create log file
let log_file = fs::File::create(&log_path)
- .map_err(|e| GitError::CommandFailed(format!("Failed to create log file\n {e}")))?;
+ .map_err(|e| anyhow::anyhow!("Failed to create log file\n {e}"))?;
#[cfg(unix)]
{
@@ -64,7 +64,7 @@ fn spawn_detached_unix(
worktree_path: &Path,
command: &str,
log_file: fs::File,
-) -> Result<(), GitError> {
+) -> anyhow::Result<()> {
// Detachment using nohup and background execution (&):
// - nohup makes the process immune to SIGHUP (continues after parent exits)
// - sh -c allows complex shell commands with pipes, redirects, etc.
@@ -81,18 +81,16 @@ fn spawn_detached_unix(
.current_dir(worktree_path)
.stdin(Stdio::null())
.stdout(Stdio::from(log_file.try_clone().map_err(|e| {
- GitError::CommandFailed(format!("Failed to clone log file handle: {}", e))
+ anyhow::anyhow!(format!("Failed to clone log file handle: {}", e))
})?))
.stderr(Stdio::from(log_file))
.spawn()
- .map_err(|e| {
- GitError::CommandFailed(format!("Failed to spawn detached process\n {e}"))
- })?;
+ .map_err(|e| anyhow::anyhow!(format!("Failed to spawn detached process\n {e}")))?;
// Wait for the outer shell to exit (immediate, doesn't block on background command)
- child.wait().map_err(|e| {
- GitError::CommandFailed(format!("Failed to wait for detachment shell\n {e}"))
- })?;
+ child
+ .wait()
+ .map_err(|e| anyhow::anyhow!(format!("Failed to wait for detachment shell\n {e}")))?;
Ok(())
}
@@ -102,7 +100,7 @@ fn spawn_detached_windows(
worktree_path: &Path,
command: &str,
log_file: fs::File,
-) -> Result<(), GitError> {
+) -> anyhow::Result<()> {
use std::os::windows::process::CommandExt;
// CREATE_NEW_PROCESS_GROUP: Creates new process group (0x00000200)
@@ -115,14 +113,12 @@ fn spawn_detached_windows(
.current_dir(worktree_path)
.stdin(Stdio::null())
.stdout(Stdio::from(log_file.try_clone().map_err(|e| {
- GitError::CommandFailed(format!("Failed to clone log file handle: {}", e))
+ anyhow::anyhow!(format!("Failed to clone log file handle: {}", e))
})?))
.stderr(Stdio::from(log_file))
.creation_flags(CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS)
.spawn()
- .map_err(|e| {
- GitError::CommandFailed(format!("Failed to spawn detached process\n {e}"))
- })?;
+ .map_err(|e| anyhow::anyhow!(format!("Failed to spawn detached process\n {e}")))?;
Ok(())
}
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rs
index b584c71ef..dda0f894c 100644
--- a/src/commands/repository_ext.rs
+++ b/src/commands/repository_ext.rs
@@ -3,8 +3,9 @@ use std::process;
use std::time::{SystemTime, UNIX_EPOCH};
use super::worktree::RemoveResult;
+use anyhow::{Context, bail};
use worktrunk::config::ProjectConfig;
-use worktrunk::git::{GitError, GitResultExt, Repository};
+use worktrunk::git::{Repository, conflicting_changes, no_worktree_found, worktree_missing};
use worktrunk::path::format_path_for_display;
use worktrunk::styling::{
CYAN, CYAN_BOLD, ERROR, ERROR_EMOJI, HINT, HINT_BOLD, HINT_EMOJI, WARNING, WARNING_BOLD,
@@ -15,13 +16,13 @@ use worktrunk::styling::{
/// implementations inside the binary crate.
pub trait RepositoryCliExt {
/// Load the project configuration if it exists.
- fn load_project_config(&self) -> Result<Option<ProjectConfig>, GitError>;
+ fn load_project_config(&self) -> anyhow::Result<Option<ProjectConfig>>;
/// Load the project configuration, emitting a helpful hint if missing.
- fn require_project_config(&self) -> Result<ProjectConfig, GitError>;
+ fn require_project_config(&self) -> anyhow::Result<ProjectConfig>;
/// Warn about untracked files being auto-staged.
- fn warn_if_auto_staging_untracked(&self) -> Result<(), GitError>;
+ fn warn_if_auto_staging_untracked(&self) -> anyhow::Result<()>;
/// Remove a worktree identified by branch name.
fn remove_worktree_by_name(
@@ -29,23 +30,23 @@ pub trait RepositoryCliExt {
branch_name: &str,
no_delete_branch: bool,
force_delete: bool,
- ) -> Result<RemoveResult, GitError>;
+ ) -> anyhow::Result<RemoveResult>;
/// Prepare the target worktree for push by auto-stashing non-overlapping changes when safe.
fn prepare_target_worktree(
&self,
target_worktree: Option<&PathBuf>,
target_branch: &str,
- ) -> Result<Option<TargetWorktreeStash>, GitError>;
+ ) -> anyhow::Result<Option<TargetWorktreeStash>>;
}
impl RepositoryCliExt for Repository {
- fn load_project_config(&self) -> Result<Option<ProjectConfig>, GitError> {
+ fn load_project_config(&self) -> anyhow::Result<Option<ProjectConfig>> {
let repo_root = self.worktree_root()?;
load_project_config_at(&repo_root)
}
- fn require_project_config(&self) -> Result<ProjectConfig, GitError> {
+ fn require_project_config(&self) -> anyhow::Result<ProjectConfig> {
let repo_root = self.worktree_root()?;
let config_path = repo_root.join(".config").join("wt.toml");
@@ -58,17 +59,15 @@ impl RepositoryCliExt for Repository {
"{HINT_EMOJI} {HINT}Create a config file at: {HINT_BOLD}{}{HINT_BOLD:#}{HINT:#}",
format_path_for_display(&config_path)
);
- Err(GitError::CommandFailed(
- "No project configuration found".to_string(),
- ))
+ Err(anyhow::anyhow!("No project configuration found"))
}
}
}
- fn warn_if_auto_staging_untracked(&self) -> Result<(), GitError> {
+ fn warn_if_auto_staging_untracked(&self) -> anyhow::Result<()> {
let status = self
.run_command(&["status", "--porcelain"])
- .git_context("Failed to get status")?;
+ .context("Failed to get status")?;
AutoStageWarning::from_status(&status).emit()
}
@@ -77,20 +76,16 @@ impl RepositoryCliExt for Repository {
branch_name: &str,
no_delete_branch: bool,
force_delete: bool,
- ) -> Result<RemoveResult, GitError> {
+ ) -> anyhow::Result<RemoveResult> {
let worktree_path = match self.worktree_for_branch(branch_name)? {
Some(path) => path,
None => {
- return Err(GitError::NoWorktreeFound {
- branch: branch_name.to_string(),
- });
+ bail!("{}", no_worktree_found(branch_name));
}
};
if !worktree_path.exists() {
- return Err(GitError::WorktreeMissing {
- branch: branch_name.to_string(),
- });
+ bail!("{}", worktree_missing(branch_name));
}
let target_repo = Repository::at(&worktree_path);
@@ -121,7 +116,7 @@ impl RepositoryCliExt for Repository {
&self,
target_worktree: Option<&PathBuf>,
target_branch: &str,
- ) -> Result<Option<TargetWorktreeStash>, GitError> {
+ ) -> anyhow::Result<Option<TargetWorktreeStash>> {
let Some(wt_path) = target_worktree else {
return Ok(None);
};
@@ -149,10 +144,7 @@ impl RepositoryCliExt for Repository {
.collect();
if !overlapping.is_empty() {
- return Err(GitError::ConflictingChanges {
- files: overlapping,
- worktree_path: wt_path.clone(),
- });
+ bail!("{}", conflicting_changes(&overlapping, wt_path));
}
let nanos = SystemTime::now()
@@ -194,7 +186,7 @@ impl RepositoryCliExt for Repository {
}
let Some(stash_ref) = stash_ref else {
- return Err(GitError::CommandFailed(format!(
+ return Err(anyhow::anyhow!(format!(
"Failed to locate autostash entry '{}'",
stash_name
)));
@@ -204,8 +196,8 @@ impl RepositoryCliExt for Repository {
}
}
-fn load_project_config_at(repo_root: &Path) -> Result<Option<ProjectConfig>, GitError> {
- ProjectConfig::load(repo_root).git_context("Failed to load project config")
+fn load_project_config_at(repo_root: &Path) -> anyhow::Result<Option<ProjectConfig>> {
+ ProjectConfig::load(repo_root).context("Failed to load project config")
}
struct AutoStageWarning {
@@ -223,7 +215,7 @@ impl AutoStageWarning {
Self { files }
}
- fn emit(&self) -> Result<(), GitError> {
+ fn emit(&self) -> anyhow::Result<()> {
if self.files.is_empty() {
return Ok(());
}
@@ -256,7 +248,7 @@ impl TargetWorktreeStash {
}
}
- pub(crate) fn restore(self) -> Result<(), GitError> {
+ pub(crate) fn restore(self) -> anyhow::Result<()> {
crate::output::progress(format!(
"{CYAN}Restoring stashed changes in {CYAN_BOLD}{}{CYAN_BOLD:#}{CYAN}...{CYAN:#}",
format_path_for_display(&self.path)
diff --git a/src/commands/select.rs b/src/commands/select.rs
index 0e9edded7..7d9fc7b1d 100644
--- a/src/commands/select.rs
+++ b/src/commands/select.rs
@@ -1,10 +1,11 @@
+use anyhow::Context;
use skim::prelude::*;
use std::borrow::Cow;
use std::fs;
use std::path::PathBuf;
use std::sync::{Arc, OnceLock};
use worktrunk::config::WorktrunkConfig;
-use worktrunk::git::{GitError, GitResultExt, Repository};
+use worktrunk::git::Repository;
use super::list::collect;
use super::list::model::ListItem;
@@ -242,7 +243,7 @@ impl WorktreeSkimItem {
}
}
-pub fn handle_select() -> Result<(), GitError> {
+pub fn handle_select() -> anyhow::Result<()> {
let repo = Repository::current();
// Initialize preview mode state file (auto-cleanup on drop)
@@ -338,13 +339,13 @@ pub fn handle_select() -> Result<(), GitError> {
"1: working | 2: history | 3: diff | ctrl-u/d: scroll | ctrl-/: toggle".to_string(),
))
.build()
- .map_err(|e| GitError::CommandFailed(format!("Failed to build skim options: {}", e)))?;
+ .map_err(|e| anyhow::anyhow!(format!("Failed to build skim options: {}", e)))?;
// Create item receiver
let (tx, rx): (SkimItemSender, SkimItemReceiver) = unbounded();
for item in items {
tx.send(item)
- .map_err(|e| GitError::CommandFailed(format!("Failed to send item to skim: {}", e)))?;
+ .map_err(|e| anyhow::anyhow!(format!("Failed to send item to skim: {}", e)))?;
}
drop(tx);
@@ -361,7 +362,7 @@ pub fn handle_select() -> Result<(), GitError> {
let identifier = selected.output().to_string();
// Load config
- let config = WorktrunkConfig::load().git_context("Failed to load config")?;
+ let config = WorktrunkConfig::load().context("Failed to load config")?;
// Switch to the selected worktree
// handle_switch can handle both branch names and worktree paths
diff --git a/src/commands/standalone.rs b/src/commands/standalone.rs
index 2681949b8..94c2f10e2 100644
--- a/src/commands/standalone.rs
+++ b/src/commands/standalone.rs
@@ -1,5 +1,6 @@
+use anyhow::{Context, bail};
use worktrunk::HookType;
-use worktrunk::git::{GitError, GitResultExt, Repository};
+use worktrunk::git::Repository;
use worktrunk::styling::{AnstyleStyle, CYAN, CYAN_BOLD, GREEN_BOLD, format_with_gutter};
use super::commit::{CommitGenerator, CommitOptions};
@@ -10,7 +11,7 @@ use super::project_config::collect_commands_for_hooks;
use super::repository_ext::RepositoryCliExt;
/// Handle `wt beta run-hook` command
-pub fn handle_standalone_run_hook(hook_type: HookType, force: bool) -> Result<(), GitError> {
+pub fn handle_standalone_run_hook(hook_type: HookType, force: bool) -> anyhow::Result<()> {
// Derive context from current environment
let env = CommandEnv::current()?;
let repo = &env.repo;
@@ -51,15 +52,15 @@ pub fn handle_standalone_run_hook(hook_type: HookType, force: bool) -> Result<()
}
}
-fn check_hook_configured<T>(hook: &Option<T>, hook_type: HookType) -> Result<(), GitError> {
+fn check_hook_configured<T>(hook: &Option<T>, hook_type: HookType) -> anyhow::Result<()> {
if hook.is_none() {
- return Err(GitError::message(format!("No {hook_type} hook configured")));
+ return Err(anyhow::anyhow!(format!("No {hook_type} hook configured")));
}
Ok(())
}
/// Handle `wt beta commit` command
-pub fn handle_standalone_commit(force: bool, no_verify: bool) -> Result<(), GitError> {
+pub fn handle_standalone_commit(force: bool, no_verify: bool) -> anyhow::Result<()> {
let env = CommandEnv::current()?;
let ctx = env.context(force);
let mut options = CommitOptions::new(&ctx);
@@ -85,7 +86,7 @@ pub fn handle_squash(
auto_trust: bool,
tracked_only: bool,
warn_about_untracked: bool,
-) -> Result<bool, GitError> {
+) -> anyhow::Result<bool> {
let env = CommandEnv::current()?;
let repo = &env.repo;
let current_branch = env.branch.clone();
@@ -102,10 +103,10 @@ pub fn handle_squash(
if tracked_only {
repo.run_command(&["add", "-u"])
- .git_context("Failed to stage tracked changes")?;
+ .context("Failed to stage tracked changes")?;
} else {
repo.run_command(&["add", "-A"])
- .git_context("Failed to stage changes")?;
+ .context("Failed to stage changes")?;
}
// Run pre-commit hook unless explicitly skipped
@@ -187,7 +188,7 @@ pub fn handle_squash(
repo_name,
&env.config.commit_generation,
)
- .git_context("Failed to generate commit message")?;
+ .context("Failed to generate commit message")?;
// Display the generated commit message
let formatted_message = generator.format_message_for_display(&commit_message);
@@ -204,7 +205,7 @@ pub fn handle_squash(
// Reset to merge base (soft reset stages all changes, including any already-staged uncommitted changes)
repo.run_command(&["reset", "--soft", &merge_base])
- .git_context("Failed to reset to merge base")?;
+ .context("Failed to reset to merge base")?;
// Check if there are actually any changes to commit
if !repo.has_staged_changes()? {
@@ -217,7 +218,7 @@ pub fn handle_squash(
// Commit with the generated message
repo.run_command(&["commit", "-m", &commit_message])
- .git_context("Failed to create squash commit")?;
+ .context("Failed to create squash commit")?;
// Get commit hash for display
let commit_hash = repo
@@ -237,7 +238,7 @@ pub fn handle_squash(
/// Handle shared rebase workflow (used by `wt beta rebase` and `wt merge`)
/// Returns true if rebasing occurred, false if already up-to-date
-pub fn handle_rebase(target: Option<&str>) -> Result<bool, GitError> {
+pub fn handle_rebase(target: Option<&str>) -> anyhow::Result<bool> {
let repo = Repository::current();
// Get target branch (default to default branch if not provided)
@@ -268,30 +269,20 @@ pub fn handle_rebase(target: Option<&str>) -> Result<bool, GitError> {
&& state.starts_with("REBASING")
{
// Extract git's stderr output from the error
- let git_output = match &e {
- GitError::CommandFailed(msg) => msg.clone(),
- _ => e.to_string(),
- };
- return Err(GitError::RebaseConflict {
- state,
- target_branch: target_branch.to_string(),
- git_output,
- });
+ let git_output = e.to_string();
+ bail!(
+ "{}",
+ worktrunk::git::rebase_conflict(&target_branch, &git_output)
+ );
}
// Not a rebase conflict, return original error
- return Err(GitError::CommandFailed(format!(
- "Failed to rebase onto '{}': {}",
- target_branch, e
- )));
+ bail!("Failed to rebase onto '{}': {}", target_branch, e);
}
// Verify rebase completed successfully (safety check for edge cases)
if let Some(state) = repo.worktree_state()? {
- return Err(GitError::RebaseConflict {
- state,
- target_branch: target_branch.to_string(),
- git_output: String::new(), // No error output in this edge case
- });
+ let _ = state; // used for diagnostics
+ bail!("{}", worktrunk::git::rebase_conflict(&target_branch, ""));
}
// Success
@@ -304,13 +295,13 @@ pub fn handle_rebase(target: Option<&str>) -> Result<bool, GitError> {
}
/// Handle `wt beta ask-approvals` command - approve all commands in the project
-pub fn handle_standalone_ask_approvals(force: bool, show_all: bool) -> Result<(), GitError> {
+pub fn handle_standalone_ask_approvals(force: bool, show_all: bool) -> anyhow::Result<()> {
use super::command_approval::approve_command_batch;
use worktrunk::config::WorktrunkConfig;
let repo = Repository::current();
let project_id = repo.project_identifier()?;
- let config = WorktrunkConfig::load().git_context("Failed to load config")?;
+ let config = WorktrunkConfig::load().context("Failed to load config")?;
// Load project config (show helpful error if missing)
let project_config = repo.require_project_config()?;
@@ -376,10 +367,10 @@ pub fn handle_standalone_ask_approvals(force: bool, show_all: bool) -> Result<()
}
/// Handle `wt beta clear-approvals` command - clear approved commands
-pub fn handle_standalone_clear_approvals(global: bool) -> Result<(), GitError> {
+pub fn handle_standalone_clear_approvals(global: bool) -> anyhow::Result<()> {
use worktrunk::config::WorktrunkConfig;
- let mut config = WorktrunkConfig::load().git_context("Failed to load config")?;
+ let mut config = WorktrunkConfig::load().context("Failed to load config")?;
if global {
// Clear all approvals for all projects
@@ -392,7 +383,7 @@ pub fn handle_standalone_clear_approvals(global: bool) -> Result<(), GitError> {
}
config.projects.clear();
- config.save().git_context("Failed to save config")?;
+ config.save().context("Failed to save config")?;
use worktrunk::styling::GREEN;
crate::output::success(format!(
@@ -424,7 +415,7 @@ pub fn handle_standalone_clear_approvals(global: bool) -> Result<(), GitError> {
config
.revoke_project(&project_id)
- .git_context("Failed to clear project approvals")?;
+ .context("Failed to clear project approvals")?;
use worktrunk::styling::GREEN;
crate::output::success(format!(
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rs
index 9914488b5..231f3415c 100644
--- a/src/commands/worktree.rs
+++ b/src/commands/worktree.rs
@@ -98,10 +98,15 @@
//!
//! The shell wrapper is generated by `wt init <shell>` from templates in `templates/`.
+use anyhow::{Context, bail};
use std::path::PathBuf;
use worktrunk::HookType;
use worktrunk::config::{CommandPhase, WorktrunkConfig};
-use worktrunk::git::{GitError, GitResultExt, Repository};
+use worktrunk::git::{
+ Repository, branch_already_exists, is_command_not_approved, merge_commits_found,
+ not_fast_forward, push_failed, worktree_creation_failed, worktree_missing,
+ worktree_path_exists, worktree_path_occupied,
+};
use worktrunk::styling::{CYAN, CYAN_BOLD, GREEN, GREEN_BOLD, WARNING, format_with_gutter};
use super::command_executor::CommandContext;
@@ -162,7 +167,7 @@ pub fn handle_switch(
force: bool,
no_verify: bool,
config: &WorktrunkConfig,
-) -> Result<(SwitchResult, String), GitError> {
+) -> anyhow::Result<(SwitchResult, String)> {
let repo = Repository::current();
// Get current history (current, previous) before resolving
@@ -199,9 +204,7 @@ pub fn handle_switch(
// Check for conflicting conditions
if create && repo.local_branch_exists(&resolved_branch)? {
- return Err(GitError::BranchAlreadyExists {
- branch: resolved_branch.clone(),
- });
+ bail!("{}", branch_already_exists(&resolved_branch));
}
// Check if base flag was provided without create flag
@@ -240,9 +243,7 @@ pub fn handle_switch(
));
}
Some(_) => {
- return Err(GitError::WorktreeMissing {
- branch: resolved_branch.clone(),
- });
+ bail!("{}", worktree_missing(&resolved_branch));
}
None => {}
}
@@ -252,14 +253,14 @@ pub fn handle_switch(
let repo_name = repo_root
.file_name()
- .ok_or_else(|| GitError::message("Invalid repository path"))?
+ .ok_or_else(|| anyhow::anyhow!("{}", "Invalid repository path"))?
.to_str()
- .ok_or_else(|| GitError::message("Invalid UTF-8 in path"))?;
+ .ok_or_else(|| anyhow::anyhow!("{}", "Invalid UTF-8 in path"))?;
let worktree_path = repo_root.join(
config
.format_path(repo_name, &resolved_branch)
- .map_err(|e| GitError::message(format!("Failed to format worktree path: {}", e)))?,
+ .map_err(|e| anyhow::anyhow!(format!("Failed to format worktree path: {}", e)))?,
);
// If the target path already exists but no worktree is registered for this branch,
@@ -269,11 +270,10 @@ pub fn handle_switch(
.current_branch()
.ok()
.flatten();
- return Err(GitError::WorktreePathOccupied {
- branch: resolved_branch.clone(),
- path: worktree_path.clone(),
- occupant,
- });
+ bail!(
+ "{}",
+ worktree_path_occupied(&resolved_branch, &worktree_path, occupant.as_deref())
+ );
}
// Create the worktree
@@ -303,10 +303,9 @@ pub fn handle_switch(
// Create worktree and parse specific error cases
if let Err(e) = repo.run_command(&args) {
+ let msg = e.to_string();
// Check if error is about directory already existing
- if let GitError::CommandFailed(ref msg) = e
- && msg.contains("already exists")
- {
+ if msg.contains("already exists") {
// Parse the path from git's error message
// Format: "fatal: '/path/to/dir' already exists"
if let Some(path_str) = msg
@@ -320,26 +319,20 @@ 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);
- return Err(GitError::WorktreePathExists {
- path: normalized_path,
- });
+ bail!("{}", worktree_path_exists(&normalized_path));
}
}
// Fall back to generic error with context
- return Err(match e {
- GitError::CommandFailed(msg) => GitError::WorktreeCreationFailed {
- branch: resolved_branch.clone(),
- base_branch: base_for_creation.clone(),
- error: msg,
- },
- other => other,
- });
+ bail!(
+ "{}",
+ worktree_creation_failed(&resolved_branch, base_for_creation.as_deref(), &msg)
+ );
}
// Canonicalize the path to resolve any .. components
let worktree_path = worktree_path
.canonicalize()
- .git_context("Failed to canonicalize worktree path")?;
+ .context("Failed to canonicalize worktree path")?;
// Execute post-create commands (sequential, blocking)
// Note: If user declines, continue anyway - worktree already created
@@ -356,7 +349,7 @@ pub fn handle_switch(
if let Err(e) = ctx.execute_post_create_commands() {
// Only treat CommandNotApproved as non-fatal (user declined)
// Other errors should still fail
- if matches!(e, GitError::CommandNotApproved) {
+ if is_command_not_approved(&e) {
crate::output::info("Commands declined, continuing worktree creation")?;
} else {
return Err(e);
@@ -385,7 +378,7 @@ pub fn handle_remove(
no_delete_branch: bool,
force_delete: bool,
background: bool,
-) -> Result<RemoveResult, GitError> {
+) -> anyhow::Result<RemoveResult> {
let repo = Repository::current();
// Show progress (unless running in background - output handler will show command)
@@ -401,7 +394,7 @@ pub fn handle_remove(
impl<'a> CommandContext<'a> {
/// Execute post-create commands sequentially (blocking)
- pub fn execute_post_create_commands(&self) -> Result<(), GitError> {
+ pub fn execute_post_create_commands(&self) -> anyhow::Result<()> {
let project_config = match self.repo.load_project_config()? {
Some(cfg) => cfg,
None => return Ok(()),
@@ -424,7 +417,7 @@ impl<'a> CommandContext<'a> {
}
/// Spawn post-start commands in parallel as background processes (non-blocking)
- pub fn spawn_post_start_commands(&self) -> Result<(), GitError> {
+ pub fn spawn_post_start_commands(&self) -> anyhow::Result<()> {
let project_config = match self.repo.load_project_config()? {
Some(cfg) => cfg,
None => return Ok(()),
@@ -445,7 +438,7 @@ impl<'a> CommandContext<'a> {
}
/// Execute post-start commands sequentially (blocking) - for testing
- pub fn execute_post_start_commands_sequential(&self) -> Result<(), GitError> {
+ pub fn execute_post_start_commands_sequential(&self) -> anyhow::Result<()> {
let project_config = match self.repo.load_project_config()? {
Some(cfg) => cfg,
None => return Ok(()),
@@ -482,7 +475,7 @@ pub fn handle_push(
allow_merge_commits: bool,
verb: &str,
operations: Option<MergeOperations>,
-) -> Result<(), GitError> {
+) -> anyhow::Result<()> {
let repo = Repository::current();
// Get target branch (default to default branch if not provided)
@@ -521,17 +514,16 @@ pub fn handle_push(
.trim_end()
.to_string();
- return Err(GitError::NotFastForward {
- target_branch: target_branch.to_string(),
- commits_formatted,
- files_formatted,
- });
+ bail!(
+ "{}",
+ not_fast_forward(&target_branch, &commits_formatted, &files_formatted)
+ );
}
// Check for merge commits unless allowed
let has_merge_commits = repo.has_merge_commits(&target_branch, "HEAD")?;
if !allow_merge_commits && has_merge_commits {
- return Err(GitError::MergeCommitsFound);
+ bail!("{}", merge_commits_found());
}
// Configure receive.denyCurrentBranch if needed
@@ -643,9 +635,7 @@ pub fn handle_push(
stash.restore()?;
}
// CommandFailed contains raw git output, wrap in PushFailed for proper formatting
- return Err(GitError::PushFailed {
- error: e.to_string(),
- });
+ bail!("{}", push_failed(&e.to_string()));
}
if let Some(stash) = target_worktree_stash.take() {
diff --git a/src/git/diff.rs b/src/git/diff.rs
index 2362a3f14..5f9d49a4d 100644
--- a/src/git/diff.rs
+++ b/src/git/diff.rs
@@ -1,6 +1,5 @@
//! Git diff utilities for parsing and formatting diff statistics.
-use super::GitError;
use crate::styling::{ADDITION, DELETION};
/// Line-level diff totals (added/deleted counts) used across git operations.
@@ -12,7 +11,7 @@ pub struct LineDiff {
impl LineDiff {
/// Parse `git diff --numstat` output into aggregated line totals.
- pub fn from_numstat(output: &str) -> Result<Self, GitError> {
+ pub fn from_numstat(output: &str) -> anyhow::Result<Self> {
let mut totals = LineDiff::default();
for line in output.lines() {
diff --git a/src/git/error.rs b/src/git/error.rs
index 65df10910..275fe88da 100644
--- a/src/git/error.rs
+++ b/src/git/error.rs
@@ -1,20 +1,22 @@
-//! Git error types and formatting
+//! Worktrunk error types and formatting helpers
+//!
+//! Uses anyhow for error propagation. WorktrunkError is a minimal enum for
+//! semantic errors that need special handling (exit codes, silent errors).
-use std::path::PathBuf;
+use std::path::Path;
use super::HookType;
use crate::path::format_path_for_display;
+use crate::styling::{ERROR, ERROR_BOLD, ERROR_EMOJI, HINT, HINT_EMOJI, format_with_gutter};
+/// Semantic errors that require special handling in main.rs
+///
+/// Most errors use anyhow::bail! with formatted messages. This enum is only
+/// for cases that need exit code extraction or special handling.
#[derive(Debug)]
-pub enum GitError {
- /// Generic error with a message
- CommandFailed(String),
- /// Error for parsing failures
- ParseError(String),
- /// Repository is in detached HEAD state
- DetachedHead,
- /// Working tree has untracked files
- UntrackedFiles,
+pub enum WorktrunkError {
+ /// Child process exited with non-zero code (preserves exit code for signals)
+ ChildProcessExited { code: i32, message: String },
/// Hook command failed
HookCommandFailed {
hook_type: HookType,
@@ -22,119 +24,22 @@ pub enum GitError {
error: String,
exit_code: Option<i32>,
},
- /// Working tree has uncommitted changes
- UncommittedChanges,
- /// Branch already exists (when trying to create)
- BranchAlreadyExists { branch: String },
- /// Worktree directory is missing
- WorktreeMissing { branch: String },
- /// No worktree found for branch
- NoWorktreeFound { branch: String },
- /// Expected branch has no worktree and its target path is already used by another branch
- WorktreePathOccupied {
- branch: String,
- path: PathBuf,
- occupant: Option<String>,
- },
- /// Cannot push due to conflicting uncommitted changes
- ConflictingChanges {
- files: Vec<String>,
- worktree_path: PathBuf,
- },
- /// Push is not a fast-forward
- NotFastForward {
- target_branch: String,
- commits_formatted: String,
- files_formatted: String,
- },
- /// Found merge commits in push range
- MergeCommitsFound,
- /// Command was not approved by user
+ /// Command was not approved by user (silent error)
CommandNotApproved,
- /// Cannot prompt for approval in non-interactive environment
- NotInteractive,
- /// Child process exited with non-zero code (preserves exit code for signals)
- ChildProcessExited { code: i32, message: String },
- /// Push operation failed
- PushFailed { error: String },
- /// Rebase resulted in a conflict or incomplete state
- RebaseConflict {
- state: String,
- target_branch: String,
- git_output: String,
- },
- /// Worktree path already exists on filesystem
- WorktreePathExists { path: PathBuf },
- /// Creating a worktree failed
- WorktreeCreationFailed {
- branch: String,
- base_branch: Option<String>,
- error: String,
- },
- /// Switching branches failed
- SwitchFailed { branch: String, error: String },
- /// Removing a worktree directory failed
- WorktreeRemovalFailed {
- branch: String,
- path: PathBuf,
- error: String,
- },
- /// Deleting a branch failed
- BranchDeletionFailed { branch: String, error: String },
- /// Cannot remove main worktree
- CannotRemoveMainWorktree,
-}
-
-impl GitError {
- /// Create a formatted user-facing error message with emoji and styling.
- ///
- /// Use this for application errors (not raw git output).
- /// For raw git stderr, use `CommandFailed` directly.
- pub fn message(msg: impl Into<String>) -> Self {
- use crate::styling::{ERROR, ERROR_EMOJI};
- let msg = msg.into();
- GitError::CommandFailed(format!("{ERROR_EMOJI} {ERROR}{msg}{ERROR:#}"))
- }
}
-impl std::fmt::Display for GitError {
+impl std::fmt::Display for WorktrunkError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- use crate::styling::{ERROR, ERROR_BOLD, ERROR_EMOJI, HINT, HINT_EMOJI};
-
match self {
- // Generic error - raw passthrough, no formatting
- // Specific error variants should be used for git command failures that need formatting
- GitError::CommandFailed(msg) => write!(f, "{}", msg),
-
- // ParseError messages need formatting
- GitError::ParseError(msg) => {
- write!(f, "{ERROR_EMOJI} {ERROR}{msg}{ERROR:#}")
- }
-
- // Detached HEAD error
- GitError::DetachedHead => {
- write!(
- f,
- "{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
- GitError::UntrackedFiles => {
- write!(
- f,
- "{ERROR_EMOJI} {ERROR}Working tree has untracked files{ERROR:#}\n\n{HINT_EMOJI} {HINT}Add them with 'git add' and try again{HINT:#}"
- )
+ WorktrunkError::ChildProcessExited { message, .. } => {
+ write!(f, "{ERROR_EMOJI} {ERROR}{message}{ERROR:#}")
}
-
- // Hook command failed
- GitError::HookCommandFailed {
+ WorktrunkError::HookCommandFailed {
hook_type,
command_name,
error,
- exit_code: _,
+ ..
} => {
- // Build optional command name suffix
let name_suffix = command_name
.as_ref()
.map(|n| format!(": {ERROR_BOLD}{n}{ERROR_BOLD:#}"))
@@ -145,260 +50,258 @@ impl std::fmt::Display for GitError {
"{ERROR_EMOJI} {ERROR}{hook_type} command failed{name_suffix}: {error}{ERROR:#}\n\n{HINT_EMOJI} {HINT}Use --no-verify to skip {hook_type} commands{HINT:#}"
)
}
-
- // Uncommitted changes
- GitError::UncommittedChanges => {
- write!(
- f,
- "{ERROR_EMOJI} {ERROR}Working tree has uncommitted changes{ERROR:#}\n\n{HINT_EMOJI} {HINT}Commit or stash them first{HINT:#}"
- )
- }
-
- // Branch already exists
- GitError::BranchAlreadyExists { branch } => {
- write!(
- f,
- "{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:#}"
- )
+ WorktrunkError::CommandNotApproved => {
+ Ok(()) // on_skip callback handles the printing
}
+ }
+ }
+}
- // Worktree missing
- GitError::WorktreeMissing { branch } => {
- write!(
- f,
- "{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:#}"
- )
- }
+impl std::error::Error for WorktrunkError {}
- // No worktree found
- GitError::NoWorktreeFound { branch } => {
- write!(
- f,
- "{ERROR_EMOJI} {ERROR}No worktree found for branch {ERROR_BOLD}{branch}{ERROR_BOLD:#}{ERROR:#}"
- )
- }
+/// Extract exit code from WorktrunkError, if applicable
+pub fn exit_code(err: &anyhow::Error) -> Option<i32> {
+ err.downcast_ref::<WorktrunkError>().and_then(|e| match e {
+ WorktrunkError::ChildProcessExited { code, .. } => Some(*code),
+ WorktrunkError::HookCommandFailed { exit_code, .. } => *exit_code,
+ WorktrunkError::CommandNotApproved => None,
+ })
+}
- GitError::WorktreePathOccupied {
- branch,
- path,
- occupant,
- } => {
- let occupant_note = occupant
- .as_ref()
- .map(|b| format!(" (currently on {ERROR_BOLD}{b}{ERROR_BOLD:#})"))
- .unwrap_or_default();
- write!(
- f,
- "{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
- )
- }
+/// Check if error is CommandNotApproved (silent error)
+pub fn is_command_not_approved(err: &anyhow::Error) -> bool {
+ err.downcast_ref::<WorktrunkError>()
+ .is_some_and(|e| matches!(e, WorktrunkError::CommandNotApproved))
+}
- // Conflicting changes
- GitError::ConflictingChanges {
- files,
- worktree_path,
- } => {
- use crate::styling::format_with_gutter;
+// =============================================================================
+// Error formatting helpers
+// =============================================================================
- write!(
- f,
- "{ERROR_EMOJI} {ERROR}Cannot push: conflicting uncommitted changes in:{ERROR:#}\n\n"
- )?;
- if !files.is_empty() {
- let joined_files = files.join("\n");
- write!(f, "{}", format_with_gutter(&joined_files, "", None))?;
- }
- write!(
- f,
- "\n{HINT_EMOJI} {HINT}Commit or stash these changes in {} first{HINT:#}",
- format_path_for_display(worktree_path)
- )
- }
+/// Format an error with header and gutter content
+fn format_error_block(header: String, error: &str) -> String {
+ let trimmed = error.trim();
+ if trimmed.is_empty() {
+ header
+ } else {
+ format!("{header}\n{}", format_with_gutter(trimmed, "", None))
+ }
+}
- // Not fast-forward
- GitError::NotFastForward {
- target_branch,
- commits_formatted,
- files_formatted,
- } => {
- writeln!(
- f,
- "{ERROR_EMOJI} {ERROR}Can't push to local {ERROR_BOLD}{target_branch}{ERROR_BOLD:#} branch: it has newer commits{ERROR:#}"
- )?;
+/// Generic formatted error message
+pub fn error_message(msg: impl std::fmt::Display) -> String {
+ format!("{ERROR_EMOJI} {ERROR}{msg}{ERROR:#}")
+}
- // Show the formatted commit log
- if !commits_formatted.is_empty() {
- writeln!(f)?;
- write!(f, "{}", commits_formatted)?;
- }
+/// Parse error
+pub fn parse_error(msg: impl std::fmt::Display) -> String {
+ format!("{ERROR_EMOJI} {ERROR}{msg}{ERROR:#}")
+}
- // Show the formatted diff stat
- if !files_formatted.is_empty() {
- writeln!(f)?;
- write!(f, "{}", files_formatted)?;
- }
+/// Detached HEAD error
+pub fn detached_head() -> String {
+ format!(
+ "{ERROR_EMOJI} {ERROR}Not on a branch (detached HEAD){ERROR:#}\n\n{HINT_EMOJI} {HINT}You are in detached HEAD state{HINT:#}"
+ )
+}
- write!(
- f,
- "\n{HINT_EMOJI} {HINT}Use 'wt merge' to rebase your changes onto {target_branch}{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:#}"
+ )
+}
- // Merge commits found
- GitError::MergeCommitsFound => {
- write!(
- f,
- "{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:#}"
- )
- }
+/// Uncommitted changes error
+pub fn uncommitted_changes() -> String {
+ format!(
+ "{ERROR_EMOJI} {ERROR}Working tree has uncommitted changes{ERROR:#}\n\n{HINT_EMOJI} {HINT}Commit or stash them first{HINT:#}"
+ )
+}
- // Command not approved
- GitError::CommandNotApproved => {
- Ok(()) // on_skip callback handles the printing
- }
+/// Branch already exists error
+pub fn branch_already_exists(branch: &str) -> String {
+ format!(
+ "{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:#}"
+ )
+}
- // Not interactive (cannot prompt)
- GitError::NotInteractive => {
- write!(
- f,
- "{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:#}"
- )
- }
+/// Worktree missing error
+pub fn worktree_missing(branch: &str) -> String {
+ format!(
+ "{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:#}"
+ )
+}
- // Child process exited with non-zero code
- // Display with error emoji - main.rs will use the exit code
- GitError::ChildProcessExited { code: _, message } => {
- write!(f, "{ERROR_EMOJI} {ERROR}{message}{ERROR:#}")
- }
+/// No worktree found error
+pub fn no_worktree_found(branch: &str) -> String {
+ format!(
+ "{ERROR_EMOJI} {ERROR}No worktree found for branch {ERROR_BOLD}{branch}{ERROR_BOLD:#}{ERROR:#}"
+ )
+}
- // Push failed
- GitError::PushFailed { error } => {
- let header = format!("{ERROR_EMOJI} {ERROR}Push failed{ERROR:#}");
- write!(f, "{}", format_error_block(header, error))
- }
+/// Worktree path occupied error
+pub fn worktree_path_occupied(branch: &str, path: &Path, occupant: Option<&str>) -> String {
+ let occupant_note = occupant
+ .map(|b| format!(" (currently on {ERROR_BOLD}{b}{ERROR_BOLD:#})"))
+ .unwrap_or_default();
+ format!(
+ "{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
+ )
+}
- // Rebase conflict
- GitError::RebaseConflict {
- state: _,
- target_branch,
- git_output,
- } => {
- use crate::styling::format_with_gutter;
+/// Conflicting changes error
+pub fn conflicting_changes(files: &[String], worktree_path: &Path) -> String {
+ let mut msg = format!(
+ "{ERROR_EMOJI} {ERROR}Cannot push: conflicting uncommitted changes in:{ERROR:#}\n\n"
+ );
+ if !files.is_empty() {
+ let joined_files = files.join("\n");
+ msg.push_str(&format_with_gutter(&joined_files, "", None));
+ }
+ msg.push_str(&format!(
+ "\n{HINT_EMOJI} {HINT}Commit or stash these changes in {} first{HINT:#}",
+ format_path_for_display(worktree_path)
+ ));
+ msg
+}
- write!(
- f,
- "{ERROR_EMOJI} {ERROR}Rebase onto {ERROR_BOLD}{target_branch}{ERROR_BOLD:#}{ERROR} incomplete{ERROR:#}"
- )?;
-
- if !git_output.is_empty() {
- writeln!(f)?;
- write!(f, "{}", format_with_gutter(git_output, "", None))?;
- } else {
- // Fallback hints if no git output (edge case)
- write!(
- f,
- "\n\n{HINT_EMOJI} {HINT}Resolve conflicts and run 'git rebase --continue'{HINT:#}\n{HINT_EMOJI} {HINT}Or abort with 'git rebase --abort'{HINT:#}"
- )?;
- }
-
- Ok(())
- }
+/// Not fast-forward error
+pub fn not_fast_forward(
+ target_branch: &str,
+ commits_formatted: &str,
+ files_formatted: &str,
+) -> String {
+ 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"
+ );
+
+ if !commits_formatted.is_empty() {
+ msg.push('\n');
+ msg.push_str(commits_formatted);
+ }
- // Worktree path already exists
- GitError::WorktreePathExists { path } => {
- write!(
- f,
- "{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)
- )
- }
+ if !files_formatted.is_empty() {
+ msg.push('\n');
+ msg.push_str(files_formatted);
+ }
- GitError::WorktreeCreationFailed {
- branch,
- base_branch,
- error,
- } => {
- // Build optional base branch suffix (includes re-establishing ERROR color)
- let base_suffix = base_branch
- .as_ref()
- .map(|base| format!("{ERROR} from base {ERROR_BOLD}{base}{ERROR_BOLD:#}"))
- .unwrap_or_default();
+ msg.push_str(&format!(
+ "\n{HINT_EMOJI} {HINT}Use 'wt merge' to rebase your changes onto {target_branch}{HINT:#}"
+ ));
+ msg
+}
- let header = format!(
- "{ERROR_EMOJI} {ERROR}Failed to create worktree for {ERROR_BOLD}{branch}{ERROR_BOLD:#}{base_suffix}{ERROR:#}"
- );
- write!(f, "{}", format_error_block(header, error))
- }
+/// Merge commits found error
+pub fn merge_commits_found() -> String {
+ format!(
+ "{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:#}"
+ )
+}
- GitError::SwitchFailed { branch, error } => {
- let header = format!(
- "{ERROR_EMOJI} {ERROR}Failed to switch to {ERROR_BOLD}{branch}{ERROR_BOLD:#}{ERROR:#}"
- );
- write!(f, "{}", format_error_block(header, error))
- }
+/// Not interactive error
+pub fn not_interactive() -> String {
+ format!(
+ "{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:#}"
+ )
+}
- GitError::WorktreeRemovalFailed {
- branch,
- path,
- 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)
- );
- write!(f, "{}", format_error_block(header, error))
- }
+/// Push failed error
+pub fn push_failed(error: &str) -> String {
+ let header = format!("{ERROR_EMOJI} {ERROR}Push failed{ERROR:#}");
+ format_error_block(header, error)
+}
- GitError::BranchDeletionFailed { branch, error } => {
- let header = format!(
- "{ERROR_EMOJI} {ERROR}Failed to delete branch {ERROR_BOLD}{branch}{ERROR_BOLD:#}{ERROR:#}"
- );
- write!(f, "{}", format_error_block(header, error))
- }
+/// Rebase conflict error
+pub fn rebase_conflict(target_branch: &str, git_output: &str) -> String {
+ let mut msg = format!(
+ "{ERROR_EMOJI} {ERROR}Rebase onto {ERROR_BOLD}{target_branch}{ERROR_BOLD:#}{ERROR} incomplete{ERROR:#}"
+ );
- GitError::CannotRemoveMainWorktree => {
- write!(
- f,
- "{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:#}"
- )
- }
- }
+ if !git_output.is_empty() {
+ msg.push('\n');
+ msg.push_str(&format_with_gutter(git_output, "", None));
+ } else {
+ msg.push_str(&format!(
+ "\n\n{HINT_EMOJI} {HINT}Resolve conflicts and run 'git rebase --continue'{HINT:#}\n{HINT_EMOJI} {HINT}Or abort with 'git rebase --abort'{HINT:#}"
+ ));
}
+
+ msg
}
-fn format_error_block(header: String, error: &str) -> String {
- use crate::styling::format_with_gutter;
- let trimmed = error.trim();
- if trimmed.is_empty() {
- header
- } else {
- format!("{header}\n{}", format_with_gutter(trimmed, "", None))
- }
+/// Worktree path exists error
+pub fn worktree_path_exists(path: &Path) -> String {
+ format!(
+ "{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)
+ )
}
-impl std::error::Error for GitError {}
-
-// Automatic conversion from io::Error to GitError
-// This eliminates the need for manual .map_err() on output functions
-// Parses exit codes from error messages to preserve signal information
-//
-// Protocol: execute_streaming() embeds exit codes in error messages as:
-// "CHILD_EXIT_CODE:{code} {original_message}"
-// This allows passing exit codes through io::Error (which doesn't carry codes)
-// while preserving the full error context.
-impl From<std::io::Error> for GitError {
- fn from(e: std::io::Error) -> Self {
- 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 GitError::ChildProcessExited { code, message };
- }
- GitError::CommandFailed(msg)
+/// Worktree creation failed error
+pub fn worktree_creation_failed(branch: &str, base_branch: Option<&str>, error: &str) -> String {
+ let base_suffix = base_branch
+ .map(|base| format!("{ERROR} from base {ERROR_BOLD}{base}{ERROR_BOLD:#}"))
+ .unwrap_or_default();
+
+ 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)
+}
+
+/// Worktree removal failed error
+pub fn worktree_removal_failed(branch: &str, path: &Path, error: &str) -> String {
+ 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)
+}
+
+/// Branch deletion failed error
+pub fn branch_deletion_failed(branch: &str, error: &str) -> String {
+ 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)
}
diff --git a/src/git/mod.rs b/src/git/mod.rs
index b851c89f1..b1bbd83da 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -30,8 +30,15 @@ static HEAVY_OPS_SEMAPHORE: LazyLock<semaphore::Semaphore> =
// Re-exports from submodules
pub use diff::{DiffStats, LineDiff};
-pub use error::GitError;
-pub use repository::{GitResultExt, Repository, set_base_path};
+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,
+};
+pub use repository::{Repository, set_base_path};
// Re-export parsing helpers for internal use
pub(crate) use parse::DefaultBranchName;
@@ -84,11 +91,11 @@ pub struct WorktreeList {
impl WorktreeList {
/// Create from raw worktrees, filtering bare entries and identifying primary.
- pub(crate) fn from_raw(raw_worktrees: Vec<Worktree>) -> Result<Self, GitError> {
+ pub(crate) fn from_raw(raw_worktrees: Vec<Worktree>) -> anyhow::Result<Self> {
let worktrees: Vec<_> = raw_worktrees.into_iter().filter(|wt| !wt.bare).collect();
if worktrees.is_empty() {
- return Err(GitError::message("No worktrees found"));
+ anyhow::bail!("{}", error_message("No worktrees found"));
}
Ok(Self { worktrees })
diff --git a/src/git/parse.rs b/src/git/parse.rs
index bee14dfe3..9d2b192f9 100644
--- a/src/git/parse.rs
+++ b/src/git/parse.rs
@@ -2,10 +2,12 @@
use std::path::PathBuf;
-use super::{GitError, Worktree, finalize_worktree};
+use anyhow::bail;
+
+use super::{Worktree, finalize_worktree, parse_error};
impl Worktree {
- pub(crate) fn parse_porcelain_list(output: &str) -> Result<Vec<Self>, GitError> {
+ pub(crate) fn parse_porcelain_list(output: &str) -> anyhow::Result<Vec<Self>> {
let mut worktrees = Vec::new();
let mut current: Option<Worktree> = None;
@@ -24,9 +26,9 @@ impl Worktree {
match key {
"worktree" => {
- let path = value.ok_or_else(|| {
- GitError::ParseError("worktree line missing path".to_string())
- })?;
+ let Some(path) = value else {
+ bail!("{}", parse_error("worktree line missing path"));
+ };
current = Some(Worktree {
path: PathBuf::from(path),
head: String::new(),
@@ -39,17 +41,16 @@ impl Worktree {
}
key => match (key, current.as_mut()) {
("HEAD", Some(wt)) => {
- wt.head = value
- .ok_or_else(|| {
- GitError::ParseError("HEAD line missing SHA".to_string())
- })?
- .to_string();
+ let Some(sha) = value else {
+ bail!("{}", parse_error("HEAD line missing SHA"));
+ };
+ wt.head = sha.to_string();
}
("branch", Some(wt)) => {
// Strip refs/heads/ prefix if present
- let branch_ref = value.ok_or_else(|| {
- GitError::ParseError("branch line missing ref".to_string())
- })?;
+ let Some(branch_ref) = value else {
+ bail!("{}", parse_error("branch line missing ref"));
+ };
let branch = branch_ref
.strip_prefix("refs/heads/")
.unwrap_or(branch_ref)
@@ -88,7 +89,7 @@ impl Worktree {
pub(crate) struct DefaultBranchName(String);
impl DefaultBranchName {
- pub(crate) fn from_local(remote: &str, output: &str) -> Result<Self, GitError> {
+ pub(crate) fn from_local(remote: &str, output: &str) -> anyhow::Result<Self> {
let trimmed = output.trim();
// Strip "remote/" prefix if present
@@ -96,16 +97,16 @@ impl DefaultBranchName {
let branch = trimmed.strip_prefix(&prefix).unwrap_or(trimmed);
if branch.is_empty() {
- return Err(GitError::ParseError(format!(
- "Empty branch name from {}/HEAD",
- remote
- )));
+ bail!(
+ "{}",
+ parse_error(format!("Empty branch name from {}/HEAD", remote))
+ );
}
Ok(Self(branch.to_string()))
}
- pub(crate) fn from_remote(output: &str) -> Result<Self, GitError> {
+ pub(crate) fn from_remote(output: &str) -> anyhow::Result<Self> {
output
.lines()
.find_map(|line| {
@@ -117,7 +118,10 @@ impl DefaultBranchName {
})
.map(Self)
.ok_or_else(|| {
- GitError::ParseError("Could not find symbolic ref in ls-remote output".to_string())
+ anyhow::anyhow!(
+ "{}",
+ parse_error("Could not find symbolic ref in ls-remote output")
+ )
})
}
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index 39101d5ce..ef8b690cc 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -3,9 +3,12 @@ use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::sync::OnceLock;
+use anyhow::{Context, bail};
+
// Import types and functions from parent module (mod.rs)
use super::{
- DefaultBranchName, DiffStats, GitError, LineDiff, SwitchHistory, Worktree, WorktreeList,
+ DefaultBranchName, DiffStats, LineDiff, SwitchHistory, Worktree, WorktreeList, detached_head,
+ error_message, parse_error, uncommitted_changes,
};
/// Global base path for repository operations, set by -C flag
@@ -27,52 +30,6 @@ fn base_path() -> &'static PathBuf {
.unwrap_or_else(|| DEFAULT.get_or_init(|| PathBuf::from(".")))
}
-/// Extension trait for Result types to simplify GitError conversions
-///
-/// This trait provides ergonomic methods to convert any Result into Result<T, GitError>.
-///
-/// # Examples
-///
-/// ```no_run
-/// use worktrunk::git::{GitError, GitResultExt};
-///
-/// fn load_config() -> Result<String, std::io::Error> {
-/// std::fs::read_to_string("config.toml")
-/// }
-///
-/// // Without context:
-/// let config = load_config().git_err()?;
-///
-/// // With context:
-/// let config = load_config().git_context("Failed to load config")?;
-/// # Ok::<(), GitError>(())
-/// ```
-pub trait GitResultExt<T> {
- /// Convert the error to GitError with additional context
- fn git_context(self, context: &str) -> Result<T, GitError>;
-
- /// Convert the error to GitError using its Display implementation
- fn git_err(self) -> Result<T, GitError>;
-}
-
-impl<T, E: std::fmt::Display> GitResultExt<T> for Result<T, E> {
- fn git_context(self, context: &str) -> Result<T, GitError> {
- use crate::styling::{ERROR, ERROR_EMOJI, format_with_gutter};
- self.map_err(|e| {
- let error_str = e.to_string();
- let header = format!("{ERROR_EMOJI} {ERROR}{context}{ERROR:#}");
- // External errors always use gutter formatting (canonical path)
- let formatted = format!("{}\n{}", header, format_with_gutter(&error_str, "", None));
- GitError::CommandFailed(formatted)
- })
- }
-
- fn git_err(self) -> Result<T, GitError> {
- use crate::styling::{ERROR, ERROR_EMOJI};
- self.map_err(|e| GitError::CommandFailed(format!("{ERROR_EMOJI} {ERROR}{e}{ERROR:#}")))
- }
-}
-
/// Internal layout information for a repository.
///
/// Cached to avoid repeated git queries.
@@ -95,7 +52,7 @@ struct RepositoryLayout {
/// let repo = Repository::current();
/// let branch = repo.current_branch()?;
/// let is_dirty = repo.is_dirty()?;
-/// # Ok::<(), worktrunk::git::GitError>(())
+/// # Ok::<(), anyhow::Error>(())
/// ```
#[derive(Debug)]
pub struct Repository {
@@ -126,7 +83,7 @@ impl Repository {
}
/// Get the repository layout, initializing it if needed.
- fn layout(&self) -> Result<&RepositoryLayout, GitError> {
+ fn layout(&self) -> anyhow::Result<&RepositoryLayout> {
if let Some(layout) = self.layout.get() {
return Ok(layout);
}
@@ -134,7 +91,7 @@ impl Repository {
let git_common_dir = self
.git_common_dir()?
.canonicalize()
- .map_err(|e| GitError::CommandFailed(format!("Failed to canonicalize path: {}", e)))?;
+ .context("Failed to canonicalize path")?;
let is_bare = self.is_bare_repo()?;
@@ -143,7 +100,7 @@ impl Repository {
} else {
git_common_dir
.parent()
- .ok_or_else(|| GitError::message("Invalid git directory"))?
+ .ok_or_else(|| anyhow::anyhow!("{}", error_message("Invalid git directory")))?
.to_path_buf()
};
@@ -157,7 +114,7 @@ impl Repository {
}
/// Check if this is a bare repository (no working tree).
- fn is_bare_repo(&self) -> Result<bool, GitError> {
+ fn is_bare_repo(&self) -> anyhow::Result<bool> {
let output = self.run_command(&["config", "--bool", "core.bare"])?;
Ok(output.trim() == "true")
}
@@ -169,7 +126,7 @@ impl Repository {
/// (Note: Detached HEAD falls through to step 2)
/// 2. Otherwise, get the first remote from `git remote`
/// 3. Fall back to "origin" if no remotes exist
- pub fn primary_remote(&self) -> Result<String, GitError> {
+ pub fn primary_remote(&self) -> anyhow::Result<String> {
// Try to get the remote from the current branch's upstream
if let Ok(Some(branch)) = self.current_branch()
&& let Ok(Some(upstream)) = self.upstream_branch(&branch)
@@ -186,14 +143,14 @@ impl Repository {
}
/// Check if a local git branch exists.
- pub fn local_branch_exists(&self, branch: &str) -> Result<bool, GitError> {
+ pub fn local_branch_exists(&self, branch: &str) -> anyhow::Result<bool> {
Ok(self
.run_command(&["rev-parse", "--verify", &format!("refs/heads/{}", branch)])
.is_ok())
}
/// Check if a git branch exists (local or remote).
- pub fn branch_exists(&self, branch: &str) -> Result<bool, GitError> {
+ pub fn branch_exists(&self, branch: &str) -> anyhow::Result<bool> {
// Try local branch first
if self.local_branch_exists(branch)? {
return Ok(true);
@@ -211,7 +168,7 @@ impl Repository {
}
/// Get the current branch name, or None if in detached HEAD state.
- pub fn current_branch(&self) -> Result<Option<String>, GitError> {
+ pub fn current_branch(&self) -> anyhow::Result<Option<String>> {
let stdout = self.run_command(&["branch", "--show-current"])?;
let branch = stdout.trim();
@@ -245,7 +202,7 @@ impl Repository {
&self,
current: &str,
previous: Option<&str>,
- ) -> Result<(), GitError> {
+ ) -> anyhow::Result<()> {
let value = if let Some(prev) = previous {
format!("{},{}", current, prev)
} else {
@@ -291,18 +248,20 @@ impl Repository {
/// - `Ok(default_branch)` if "^"
/// - `Err(DetachedHead)` if "@" and in detached HEAD state
/// - `Err` if "-" but no previous branch in history
- pub fn resolve_worktree_name(&self, name: &str) -> Result<String, GitError> {
+ pub fn resolve_worktree_name(&self, name: &str) -> anyhow::Result<String> {
match name {
- "@" => self.current_branch()?.ok_or(GitError::DetachedHead),
+ "@" => self
+ .current_branch()?
+ .ok_or_else(|| anyhow::anyhow!("{}", detached_head())),
"-" => {
// Read from worktrunk.history (recorded by wt switch operations)
// History stores (current, previous), we want previous
self.get_switch_history()
.and_then(|h| h.previous)
.ok_or_else(|| {
- GitError::message(
+ anyhow::anyhow!("{}", error_message(
"No previous branch found in history. Use 'wt list' to see available worktrees.",
- )
+ ))
})
}
"^" => self.default_branch(),
@@ -324,7 +283,7 @@ impl Repository {
/// 2. If not cached, query remote (`git ls-remote`) - may take 100ms-2s depending on network
/// 3. Cache the result (`git remote set-head`) for future invocations
/// 4. If no remote available, infer from local branches (no caching, shows hint)
- pub fn default_branch(&self) -> Result<String, GitError> {
+ pub fn default_branch(&self) -> anyhow::Result<String> {
// Try to get default branch from remote
if let Ok(remote) = self.primary_remote() {
// Try local cache first (fast path)
@@ -354,7 +313,7 @@ impl Repository {
///
/// If target is Some, returns it as a String. Otherwise, queries the default branch.
/// This is a common pattern used throughout commands that accept an optional --target flag.
- pub fn resolve_target_branch(&self, target: Option<&str>) -> Result<String, GitError> {
+ pub fn resolve_target_branch(&self, target: Option<&str>) -> anyhow::Result<String> {
target.map_or_else(|| self.default_branch(), |b| Ok(b.to_string()))
}
@@ -366,7 +325,7 @@ impl Repository {
/// 3. Check user's git config init.defaultBranch
/// 4. Look for common branch names (main, master, develop)
/// 5. Fail if none of the above work
- fn infer_default_branch_locally(&self) -> Result<String, GitError> {
+ fn infer_default_branch_locally(&self) -> anyhow::Result<String> {
// 1. If there's only one local branch, use it
let branches = self.local_branches()?;
if branches.len() == 1 {
@@ -389,13 +348,16 @@ impl Repository {
}
// 4. Give up - can't infer
- Err(GitError::CommandFailed(
- "Could not infer default branch. Please specify target branch explicitly or set up a remote.".to_string()
- ))
+ bail!(
+ "{}",
+ error_message(
+ "Could not infer default branch. Please specify target branch explicitly or set up a remote."
+ )
+ )
}
/// List all local branches.
- fn local_branches(&self) -> Result<Vec<String>, GitError> {
+ fn local_branches(&self) -> anyhow::Result<Vec<String>> {
let stdout = self.run_command(&["branch", "--format=%(refname:short)"])?;
Ok(stdout.lines().map(|s| s.trim().to_string()).collect())
}
@@ -403,15 +365,16 @@ impl Repository {
/// Get the git common directory (the actual .git directory for the repository).
///
/// Always returns an absolute path, resolving any relative paths returned by git.
- pub fn git_common_dir(&self) -> Result<PathBuf, GitError> {
+ pub fn git_common_dir(&self) -> anyhow::Result<PathBuf> {
let stdout = self.run_command(&["rev-parse", "--git-common-dir"])?;
let path = PathBuf::from(stdout.trim());
// Resolve relative paths against the repo's directory
if path.is_relative() {
- self.path.join(&path).canonicalize().map_err(|e| {
- GitError::CommandFailed(format!("Failed to resolve git common directory\n {e}"))
- })
+ self.path
+ .join(&path)
+ .canonicalize()
+ .context("Failed to resolve git common directory")
} else {
Ok(path)
}
@@ -420,15 +383,16 @@ impl Repository {
/// Get the git directory (may be different from common-dir in worktrees).
///
/// Always returns an absolute path, resolving any relative paths returned by git.
- pub fn git_dir(&self) -> Result<PathBuf, GitError> {
+ pub fn git_dir(&self) -> anyhow::Result<PathBuf> {
let stdout = self.run_command(&["rev-parse", "--git-dir"])?;
let path = PathBuf::from(stdout.trim());
// Resolve relative paths against the repo's directory
if path.is_relative() {
- self.path.join(&path).canonicalize().map_err(|e| {
- GitError::CommandFailed(format!("Failed to resolve git directory\n {e}"))
- })
+ self.path
+ .join(&path)
+ .canonicalize()
+ .context("Failed to resolve git directory")
} else {
Ok(path)
}
@@ -440,12 +404,12 @@ impl Repository {
/// For bare repositories: the bare repository directory itself.
///
/// This is the path that should be used when constructing worktree paths.
- pub fn worktree_base(&self) -> Result<PathBuf, GitError> {
+ pub fn worktree_base(&self) -> anyhow::Result<PathBuf> {
Ok(self.layout()?.worktree_base.clone())
}
/// Check if the working tree has uncommitted changes.
- pub fn is_dirty(&self) -> Result<bool, GitError> {
+ pub fn is_dirty(&self) -> anyhow::Result<bool> {
let stdout = self.run_command(&["status", "--porcelain"])?;
Ok(!stdout.trim().is_empty())
}
@@ -453,9 +417,9 @@ impl Repository {
/// Ensure the working tree is clean (no uncommitted changes).
///
/// Returns an error if there are uncommitted changes.
- pub fn ensure_clean_working_tree(&self) -> Result<(), GitError> {
+ pub fn ensure_clean_working_tree(&self) -> anyhow::Result<()> {
if self.is_dirty()? {
- return Err(GitError::UncommittedChanges);
+ bail!("{}", uncommitted_changes());
}
Ok(())
}
@@ -464,71 +428,74 @@ impl Repository {
///
/// Returns the canonicalized absolute path to the top-level directory of the
/// current working tree. This could be the main worktree or a linked worktree.
- pub fn worktree_root(&self) -> Result<PathBuf, GitError> {
+ pub fn worktree_root(&self) -> anyhow::Result<PathBuf> {
let stdout = self.run_command(&["rev-parse", "--show-toplevel"])?;
let path = PathBuf::from(stdout.trim());
- path.canonicalize().map_err(|e| {
- GitError::CommandFailed(format!("Failed to canonicalize worktree root: {}", e))
- })
+ path.canonicalize()
+ .context("Failed to canonicalize worktree root")
}
/// Check if the path is in a worktree (vs the main repository).
- pub fn is_in_worktree(&self) -> Result<bool, GitError> {
+ pub fn is_in_worktree(&self) -> anyhow::Result<bool> {
let git_dir = self.git_dir()?;
let common_dir = self.git_common_dir()?;
Ok(git_dir != common_dir)
}
/// Check if base is an ancestor of head (i.e., would be a fast-forward).
- pub fn is_ancestor(&self, base: &str, head: &str) -> Result<bool, GitError> {
+ pub fn is_ancestor(&self, base: &str, head: &str) -> anyhow::Result<bool> {
self.run_command_check(&["merge-base", "--is-ancestor", base, head])
}
/// Count commits between base and head.
- pub fn count_commits(&self, base: &str, head: &str) -> Result<usize, GitError> {
+ pub fn count_commits(&self, base: &str, head: &str) -> anyhow::Result<usize> {
// Limit concurrent rev-list operations to reduce mmap thrash on commit-graph
let _guard = super::HEAVY_OPS_SEMAPHORE.acquire();
let range = format!("{}..{}", base, head);
let stdout = self.run_command(&["rev-list", "--count", &range])?;
- stdout
- .trim()
- .parse()
- .map_err(|e| GitError::ParseError(format!("Failed to parse commit count: {}", e)))
+ stdout.trim().parse().map_err(|e| {
+ anyhow::anyhow!(
+ "{}",
+ parse_error(format!("Failed to parse commit count: {}", e))
+ )
+ })
}
/// Check if there are merge commits in the range base..head.
- pub fn has_merge_commits(&self, base: &str, head: &str) -> Result<bool, GitError> {
+ pub fn has_merge_commits(&self, base: &str, head: &str) -> anyhow::Result<bool> {
let range = format!("{}..{}", base, head);
let stdout = self.run_command(&["rev-list", "--merges", &range])?;
Ok(!stdout.trim().is_empty())
}
/// Get files changed between base and head.
- pub fn changed_files(&self, base: &str, head: &str) -> Result<Vec<String>, GitError> {
+ pub fn changed_files(&self, base: &str, head: &str) -> anyhow::Result<Vec<String>> {
let range = format!("{}..{}", base, head);
let stdout = self.run_command(&["diff", "--name-only", &range])?;
Ok(stdout.lines().map(String::from).collect())
}
/// Get commit timestamp in seconds since epoch.
- pub fn commit_timestamp(&self, commit: &str) -> Result<i64, GitError> {
+ pub fn commit_timestamp(&self, commit: &str) -> anyhow::Result<i64> {
let stdout = self.run_command(&["show", "-s", "--format=%ct", commit])?;
- stdout
- .trim()
- .parse()
- .map_err(|e| GitError::ParseError(format!("Failed to parse timestamp: {}", e)))
+ stdout.trim().parse().map_err(|e| {
+ anyhow::anyhow!(
+ "{}",
+ parse_error(format!("Failed to parse timestamp: {}", e))
+ )
+ })
}
/// Get commit message (subject line) for a commit.
- pub fn commit_message(&self, commit: &str) -> Result<String, GitError> {
+ pub fn commit_message(&self, commit: &str) -> anyhow::Result<String> {
let stdout = self.run_command(&["show", "-s", "--format=%s", commit])?;
Ok(stdout.trim().to_owned())
}
/// Get the upstream tracking branch for the given branch.
- pub fn upstream_branch(&self, branch: &str) -> Result<Option<String>, GitError> {
+ pub fn upstream_branch(&self, branch: &str) -> anyhow::Result<Option<String>> {
let result = self.run_command(&["rev-parse", "--abbrev-ref", &format!("{}@{{u}}", branch)]);
match result {
@@ -541,7 +508,7 @@ impl Repository {
}
/// Get merge/rebase status for the worktree.
- pub fn worktree_state(&self) -> Result<Option<String>, GitError> {
+ pub fn worktree_state(&self) -> anyhow::Result<Option<String>> {
let git_dir = self.git_dir()?;
// Check for merge
@@ -591,7 +558,7 @@ impl Repository {
///
/// Returns (ahead, behind) where ahead is commits in head not in base,
/// and behind is commits in base not in head.
- pub fn ahead_behind(&self, base: &str, head: &str) -> Result<(usize, usize), GitError> {
+ pub fn ahead_behind(&self, base: &str, head: &str) -> anyhow::Result<(usize, usize)> {
// Use single git call with --left-right --count for better performance
let range = format!("{}...{}", base, head);
let output = self.run_command(&["rev-list", "--left-right", "--count", &range])?;
@@ -601,25 +568,18 @@ impl Repository {
// git rev-list --left-right outputs left (base) first, then right (head)
let parts: Vec<&str> = output.trim().split('\t').collect();
if parts.len() != 2 {
- return Err(GitError::CommandFailed(format!(
- "Unexpected rev-list output format: {}",
- output
- )));
+ bail!("Unexpected rev-list output format: {}", output);
}
- let behind: usize = parts[0]
- .parse()
- .map_err(|e| GitError::CommandFailed(format!("Failed to parse behind count: {}", e)))?;
- let ahead: usize = parts[1]
- .parse()
- .map_err(|e| GitError::CommandFailed(format!("Failed to parse ahead count: {}", e)))?;
+ let behind: usize = parts[0].parse().context("Failed to parse behind count")?;
+ let ahead: usize = parts[1].parse().context("Failed to parse ahead count")?;
Ok((ahead, behind))
}
/// List all local branches with their HEAD commit SHA.
/// Returns a vector of (branch_name, commit_sha) tuples.
- pub fn list_local_branches(&self) -> Result<Vec<(String, String)>, GitError> {
+ pub fn list_local_branches(&self) -> anyhow::Result<Vec<(String, String)>> {
let output = self.run_command(&[
"for-each-ref",
"--format=%(refname:short) %(objectname)",
@@ -642,7 +602,7 @@ impl Repository {
}
/// Get line diff statistics for working tree changes (unstaged + staged).
- pub fn working_tree_diff_stats(&self) -> Result<LineDiff, GitError> {
+ pub fn working_tree_diff_stats(&self) -> anyhow::Result<LineDiff> {
// Limit concurrent diff operations to reduce mmap thrash on pack files
let _guard = super::HEAVY_OPS_SEMAPHORE.acquire();
@@ -655,7 +615,7 @@ impl Repository {
/// This compares the current working tree contents (including uncommitted changes)
/// against the specified ref, regardless of what HEAD points to.
///
- pub fn working_tree_diff_vs_ref(&self, ref_name: &str) -> Result<LineDiff, GitError> {
+ pub fn working_tree_diff_vs_ref(&self, ref_name: &str) -> anyhow::Result<LineDiff> {
// Limit concurrent diff operations to reduce mmap thrash on pack files
let _guard = super::HEAVY_OPS_SEMAPHORE.acquire();
@@ -673,7 +633,7 @@ impl Repository {
&self,
base_branch: Option<&str>,
working_tree_dirty: bool,
- ) -> Result<Option<LineDiff>, GitError> {
+ ) -> anyhow::Result<Option<LineDiff>> {
let Some(branch) = base_branch else {
return Ok(Some(LineDiff::default()));
};
@@ -691,7 +651,7 @@ impl Repository {
/// Get line diff statistics between two refs (using three-dot diff for merge base).
///
- pub fn branch_diff_stats(&self, base: &str, head: &str) -> Result<LineDiff, GitError> {
+ pub fn branch_diff_stats(&self, base: &str, head: &str) -> anyhow::Result<LineDiff> {
// Limit concurrent diff operations to reduce mmap thrash on pack files
let _guard = super::HEAVY_OPS_SEMAPHORE.acquire();
@@ -716,7 +676,7 @@ impl Repository {
/// Determine whether there are staged changes in the index.
///
/// Returns `Ok(true)` when staged changes are present, `Ok(false)` otherwise.
- pub fn has_staged_changes(&self) -> Result<bool, GitError> {
+ pub fn has_staged_changes(&self) -> anyhow::Result<bool> {
Ok(!self.run_command_check(&["diff", "--cached", "--quiet", "--exit-code"])?)
}
@@ -737,9 +697,9 @@ impl Repository {
/// let repo = Repository::current();
/// let (sha, restore_cmd) = repo.create_safety_backup("feature → main (squash)")?;
/// println!("Backup created: {} - Restore with: {}", sha, restore_cmd);
- /// # Ok::<(), worktrunk::git::GitError>(())
+ /// # Ok::<(), anyhow::Error>(())
/// ```
- pub fn create_safety_backup(&self, message: &str) -> Result<(String, String), GitError> {
+ pub fn create_safety_backup(&self, message: &str) -> anyhow::Result<(String, String)> {
// Create a backup commit using git stash create (without storing it in the stash list)
let backup_sha = self
.run_command(&["stash", "create", "--include-untracked"])?
@@ -748,9 +708,7 @@ impl Repository {
// Validate that we got a SHA back
if backup_sha.is_empty() {
- return Err(GitError::CommandFailed(
- "git stash create returned empty SHA - no changes to backup".into(),
- ));
+ bail!("git stash create returned empty SHA - no changes to backup");
}
// Get current branch name to use in the ref name
@@ -774,7 +732,7 @@ impl Repository {
&ref_name,
&backup_sha,
])
- .git_context("Failed to create backup ref")?;
+ .context("Failed to create backup ref")?;
// Return short SHA and restore command
// Use git stash apply because the backup is a merge commit (created by git stash create)
@@ -785,7 +743,7 @@ impl Repository {
}
/// Get all branch names (local branches only).
- pub fn all_branches(&self) -> Result<Vec<String>, GitError> {
+ pub fn all_branches(&self) -> anyhow::Result<Vec<String>> {
let stdout = self.run_command(&[
"branch",
"--sort=-committerdate",
@@ -800,7 +758,7 @@ impl Repository {
}
/// Get the merge base between two commits.
- pub fn merge_base(&self, commit1: &str, commit2: &str) -> Result<String, GitError> {
+ pub fn merge_base(&self, commit1: &str, commit2: &str) -> anyhow::Result<String> {
let output = self.run_command(&["merge-base", commit1, commit2])?;
Ok(output.trim().to_owned())
}
@@ -816,9 +774,9 @@ impl Repository {
///
/// let repo = Repository::current();
/// let has_conflicts = repo.has_merge_conflicts("main", "feature-branch")?;
- /// # Ok::<(), worktrunk::git::GitError>(())
+ /// # Ok::<(), anyhow::Error>(())
/// ```
- pub fn has_merge_conflicts(&self, base: &str, head: &str) -> Result<bool, GitError> {
+ pub fn has_merge_conflicts(&self, base: &str, head: &str) -> anyhow::Result<bool> {
// Use modern merge-tree --write-tree mode which exits with 1 when conflicts exist
// (the old 3-argument deprecated mode always exits with 0)
// run_command_check returns true for exit 0, false otherwise
@@ -827,7 +785,7 @@ impl Repository {
}
/// Get commit subjects (first line of commit message) from a range.
- pub fn commit_subjects(&self, range: &str) -> Result<Vec<String>, GitError> {
+ pub fn commit_subjects(&self, range: &str) -> anyhow::Result<Vec<String>> {
let output = self.run_command(&["log", "--format=%s", range])?;
Ok(output.lines().map(String::from).collect())
}
@@ -836,14 +794,14 @@ impl Repository {
///
/// Returns a WorktreeList that automatically filters out bare repositories
/// and provides access to the main worktree.
- pub fn list_worktrees(&self) -> Result<WorktreeList, GitError> {
+ pub fn list_worktrees(&self) -> anyhow::Result<WorktreeList> {
let stdout = self.run_command(&["worktree", "list", "--porcelain"])?;
let raw_worktrees = Worktree::parse_porcelain_list(&stdout)?;
WorktreeList::from_raw(raw_worktrees)
}
/// Find the worktree path for a given branch, if one exists.
- pub fn worktree_for_branch(&self, branch: &str) -> Result<Option<PathBuf>, GitError> {
+ pub fn worktree_for_branch(&self, branch: &str) -> anyhow::Result<Option<PathBuf>> {
let worktrees = self.list_worktrees()?;
Ok(worktrees
@@ -854,7 +812,7 @@ impl Repository {
}
/// Get branches that don't have worktrees (available for switch).
- pub fn available_branches(&self) -> Result<Vec<String>, GitError> {
+ pub fn available_branches(&self) -> anyhow::Result<Vec<String>> {
let all_branches = self.all_branches()?;
let worktrees = self.list_worktrees()?;
@@ -873,7 +831,7 @@ impl Repository {
}
/// Get a git config value. Returns None if the key doesn't exist.
- pub fn get_config(&self, key: &str) -> Result<Option<String>, GitError> {
+ pub fn get_config(&self, key: &str) -> anyhow::Result<Option<String>> {
match self.run_command(&["config", key]) {
Ok(value) => Ok(Some(value.trim().to_string())),
Err(_) => Ok(None), // Config key doesn't exist
@@ -881,16 +839,16 @@ impl Repository {
}
/// Set a git config value.
- pub fn set_config(&self, key: &str, value: &str) -> Result<(), GitError> {
+ pub fn set_config(&self, key: &str, value: &str) -> anyhow::Result<()> {
self.run_command(&["config", key, value])?;
Ok(())
}
/// Remove a worktree at the specified path.
- pub fn remove_worktree(&self, path: &std::path::Path) -> Result<(), GitError> {
- let path_str = path
- .to_str()
- .ok_or_else(|| GitError::message("Invalid UTF-8 in worktree path"))?;
+ pub fn remove_worktree(&self, path: &std::path::Path) -> anyhow::Result<()> {
+ let path_str = path.to_str().ok_or_else(|| {
+ anyhow::anyhow!("{}", error_message("Invalid UTF-8 in worktree path"))
+ })?;
self.run_command(&["worktree", "remove", path_str])?;
Ok(())
}
@@ -903,38 +861,38 @@ impl Repository {
/// default branch has been changed on the remote).
///
/// Returns the refreshed default branch name.
- pub fn refresh_default_branch(&self) -> Result<String, GitError> {
+ pub fn refresh_default_branch(&self) -> anyhow::Result<String> {
let remote = self.primary_remote()?;
let branch = self.query_remote_default_branch(&remote)?;
self.cache_default_branch(&remote, &branch)?;
Ok(branch)
}
- fn branch_tree_matches_head(&self, branch: &str) -> Result<bool, GitError> {
+ fn branch_tree_matches_head(&self, branch: &str) -> anyhow::Result<bool> {
let head_tree = self.rev_parse_tree("HEAD^{tree}")?;
let branch_tree = self.rev_parse_tree(&format!("{branch}^{{tree}}"))?;
Ok(head_tree == branch_tree)
}
- fn rev_parse_tree(&self, spec: &str) -> Result<String, GitError> {
+ fn rev_parse_tree(&self, spec: &str) -> anyhow::Result<String> {
self.run_command(&["rev-parse", spec])
.map(|output| output.trim().to_string())
}
// Private helper methods for default_branch()
- fn get_local_default_branch(&self, remote: &str) -> Result<String, GitError> {
+ fn get_local_default_branch(&self, remote: &str) -> anyhow::Result<String> {
let stdout =
self.run_command(&["rev-parse", "--abbrev-ref", &format!("{}/HEAD", remote)])?;
DefaultBranchName::from_local(remote, &stdout).map(DefaultBranchName::into_string)
}
- fn query_remote_default_branch(&self, remote: &str) -> Result<String, GitError> {
+ fn query_remote_default_branch(&self, remote: &str) -> anyhow::Result<String> {
let stdout = self.run_command(&["ls-remote", "--symref", remote, "HEAD"])?;
DefaultBranchName::from_remote(&stdout).map(DefaultBranchName::into_string)
}
- fn cache_default_branch(&self, remote: &str, branch: &str) -> Result<(), GitError> {
+ fn cache_default_branch(&self, remote: &str, branch: &str) -> anyhow::Result<()> {
self.run_command(&["remote", "set-head", remote, branch])?;
Ok(())
}
@@ -946,7 +904,7 @@ impl Repository {
///
/// This identifier is used to track which commands have been approved
/// for execution in this project.
- pub fn project_identifier(&self) -> Result<String, GitError> {
+ pub fn project_identifier(&self) -> anyhow::Result<String> {
// Try to get the remote URL first
let remote = self.primary_remote()?;
@@ -997,7 +955,9 @@ impl Repository {
let repo_name = repo_root
.file_name()
.and_then(|name| name.to_str())
- .ok_or_else(|| GitError::message("Could not determine repository name"))?;
+ .ok_or_else(|| {
+ anyhow::anyhow!("{}", error_message("Could not determine repository name"))
+ })?;
Ok(repo_name.to_string())
}
@@ -1013,9 +973,9 @@ impl Repository {
///
/// let repo = Repository::current();
/// let status = repo.run_command(&["status", "--porcelain"])?;
- /// # Ok::<(), worktrunk::git::GitError>(())
+ /// # Ok::<(), anyhow::Error>(())
/// ```
- pub fn run_command(&self, args: &[&str]) -> Result<String, GitError> {
+ pub fn run_command(&self, args: &[&str]) -> anyhow::Result<String> {
use std::time::Instant;
let mut cmd = Command::new("git");
@@ -1038,9 +998,7 @@ impl Repository {
};
let t0 = Instant::now();
- let output = cmd
- .output()
- .map_err(|e| GitError::CommandFailed(e.to_string()))?;
+ let output = cmd.output().context("Failed to execute git command")?;
let duration = t0.elapsed();
// Performance tracing at debug level (enable with RUST_LOG=debug)
@@ -1060,7 +1018,7 @@ impl Repository {
for line in stderr.trim().lines() {
log::debug!(" ! {}", line);
}
- return Err(GitError::CommandFailed(stderr));
+ bail!("{}", stderr);
}
let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
@@ -1084,9 +1042,9 @@ impl Repository {
///
/// let repo = Repository::current();
/// let is_clean = repo.run_command_check(&["diff", "--quiet", "--exit-code"])?;
- /// # Ok::<(), worktrunk::git::GitError>(())
+ /// # Ok::<(), anyhow::Error>(())
/// ```
- pub fn run_command_check(&self, args: &[&str]) -> Result<bool, GitError> {
+ pub fn run_command_check(&self, args: &[&str]) -> anyhow::Result<bool> {
let mut cmd = Command::new("git");
cmd.args(args);
cmd.current_dir(&self.path);
@@ -1103,9 +1061,7 @@ impl Repository {
log::debug!("$ git {} [{}]", args.join(" "), worktree);
}
- let output = cmd
- .output()
- .map_err(|e| GitError::CommandFailed(e.to_string()))?;
+ let output = cmd.output().context("Failed to execute git command")?;
let success = output.status.success();
if !success {
@@ -1118,7 +1074,7 @@ impl Repository {
///
/// The pager is spawned in a detached session (via setsid on Unix) to prevent it from
/// accessing /dev/tty, which would cause hangs when called from within TUI contexts like skim.
- pub fn run_diff_with_pager(&self, args: &[&str]) -> Result<String, GitError> {
+ pub fn run_diff_with_pager(&self, args: &[&str]) -> anyhow::Result<String> {
let mut git_args = args.to_vec();
git_args.push("--color=always");
let git_output = self.run_command(&git_args)?;
diff --git a/src/git/repository/tests.rs b/src/git/repository/tests.rs
index 31f04421a..964303144 100644
--- a/src/git/repository/tests.rs
+++ b/src/git/repository/tests.rs
@@ -1,7 +1,6 @@
use std::path::PathBuf;
use super::super::{DefaultBranchName, Worktree, finalize_worktree};
-use super::*;
#[test]
fn test_parse_worktree_list() {
@@ -177,7 +176,6 @@ fn test_parse_local_default_branch_empty() {
let result =
DefaultBranchName::from_local("origin", output).map(DefaultBranchName::into_string);
assert!(result.is_err());
- assert!(matches!(result.unwrap_err(), GitError::ParseError(_)));
}
#[test]
@@ -235,7 +233,6 @@ fn test_parse_remote_default_branch_missing_symref() {
let output = "85a1ce7c7182540f9c02453441cb3e8bf0ced214\tHEAD\n";
let result = DefaultBranchName::from_remote(output).map(DefaultBranchName::into_string);
assert!(result.is_err());
- assert!(matches!(result.unwrap_err(), GitError::ParseError(_)));
}
#[test]
diff --git a/src/git/test.rs b/src/git/test.rs
index 98a8446b6..6cb05ef74 100644
--- a/src/git/test.rs
+++ b/src/git/test.rs
@@ -3,7 +3,7 @@
//! These tests target edge cases and error conditions in git output parsing
//! that are likely to reveal bugs in real-world usage.
-use super::{DefaultBranchName, GitError, LineDiff, Worktree};
+use super::{DefaultBranchName, LineDiff, Worktree};
#[test]
fn test_parse_worktree_list_empty_output() {
@@ -210,15 +210,12 @@ fn test_parse_worktree_list_worktree_missing_path() {
// Current code: value.ok_or_else(|| GitError::ParseError("worktree line missing path"))
assert!(result.is_err(), "Worktree without path should error");
- match result {
- Err(GitError::ParseError(msg)) => {
- assert!(
- msg.contains("missing path"),
- "Error should mention missing path"
- );
- }
- _ => panic!("Expected ParseError about missing path"),
- }
+ let err = result.unwrap_err();
+ let msg = err.to_string();
+ assert!(
+ msg.contains("missing path"),
+ "Error should mention missing path, got: {msg}"
+ );
}
#[test]
@@ -229,15 +226,12 @@ fn test_parse_worktree_list_head_missing_sha() {
// Current code: value.ok_or_else(|| GitError::ParseError("HEAD line missing SHA"))
assert!(result.is_err(), "HEAD without SHA should error");
- match result {
- Err(GitError::ParseError(msg)) => {
- assert!(
- msg.contains("missing SHA"),
- "Error should mention missing SHA"
- );
- }
- _ => panic!("Expected ParseError about missing SHA"),
- }
+ let err = result.unwrap_err();
+ let msg = err.to_string();
+ assert!(
+ msg.contains("missing SHA"),
+ "Error should mention missing SHA, got: {msg}"
+ );
}
#[test]
@@ -248,15 +242,12 @@ fn test_parse_worktree_list_branch_missing_ref() {
// Current code: value.ok_or_else(|| GitError::ParseError("branch line missing ref"))
assert!(result.is_err(), "Branch without ref should error");
- match result {
- Err(GitError::ParseError(msg)) => {
- assert!(
- msg.contains("missing ref"),
- "Error should mention missing ref"
- );
- }
- _ => panic!("Expected ParseError about missing ref"),
- }
+ let err = result.unwrap_err();
+ let msg = err.to_string();
+ assert!(
+ msg.contains("missing ref"),
+ "Error should mention missing ref, got: {msg}"
+ );
}
// Tests for parse_remote_default_branch
@@ -288,15 +279,12 @@ fn test_parse_remote_default_branch_empty_output() {
let result = DefaultBranchName::from_remote(output).map(DefaultBranchName::into_string);
assert!(result.is_err(), "Empty output should return an error");
- match result {
- Err(GitError::ParseError(msg)) => {
- assert!(
- msg.contains("symbolic ref"),
- "Error should mention symbolic ref"
- );
- }
- _ => panic!("Expected ParseError"),
- }
+ let err = result.unwrap_err();
+ let msg = err.to_string();
+ assert!(
+ msg.contains("symbolic ref"),
+ "Error should mention symbolic ref, got: {msg}"
+ );
}
#[test]
@@ -382,15 +370,12 @@ fn test_parse_local_default_branch_empty_output() {
let result = DefaultBranchName::from_local("origin", "").map(DefaultBranchName::into_string);
assert!(result.is_err(), "Empty output should error");
- match result {
- Err(GitError::ParseError(msg)) => {
- assert!(
- msg.contains("Empty branch"),
- "Error should mention empty branch"
- );
- }
- _ => panic!("Expected ParseError about empty branch"),
- }
+ let err = result.unwrap_err();
+ let msg = err.to_string();
+ assert!(
+ msg.contains("Empty branch"),
+ "Error should mention empty branch, got: {msg}"
+ );
}
#[test]
diff --git a/src/llm.rs b/src/llm.rs
index 3c704b008..af8a1f63e 100644
--- a/src/llm.rs
+++ b/src/llm.rs
@@ -2,7 +2,7 @@ use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{self, Stdio};
use worktrunk::config::CommitGenerationConfig;
-use worktrunk::git::{GitError, Repository};
+use worktrunk::git::Repository;
use worktrunk::path::format_path_for_display;
use minijinja::Environment;
@@ -71,11 +71,7 @@ Commits being combined:
///
/// This is the canonical way to execute LLM commands in this codebase.
/// All LLM execution should go through this function to maintain consistency.
-fn execute_llm_command(
- command: &str,
- args: &[String],
- prompt: &str,
-) -> Result<String, Box<dyn std::error::Error>> {
+fn execute_llm_command(command: &str, args: &[String], prompt: &str) -> anyhow::Result<String> {
// Build command args
let mut cmd = process::Command::new(command);
cmd.args(args);
@@ -103,13 +99,13 @@ fn execute_llm_command(
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
- return Err(format!("LLM command failed: {}", stderr).into());
+ anyhow::bail!("LLM command failed: {}", stderr);
}
let message = String::from_utf8_lossy(&output.stdout).trim().to_owned();
if message.is_empty() {
- return Err("LLM returned empty message".into());
+ anyhow::bail!("LLM returned empty message");
}
Ok(message)
@@ -121,14 +117,14 @@ fn build_commit_prompt(
diff: &str,
recent_commits: Option<&Vec<String>>,
context: &PromptContext<'_>,
-) -> Result<String, Box<dyn std::error::Error>> {
+) -> anyhow::Result<String> {
// Get template source
let template = match (&config.template, &config.template_file) {
(Some(inline), None) => inline.clone(),
(None, Some(path)) => {
let expanded_path = PathBuf::from(shellexpand::tilde(path).as_ref());
std::fs::read_to_string(&expanded_path).map_err(|e| {
- format!(
+ anyhow::anyhow!(
"Failed to read template-file '{}': {}",
format_path_for_display(&expanded_path),
e
@@ -143,7 +139,7 @@ fn build_commit_prompt(
// Validate non-empty
if template.trim().is_empty() {
- return Err("Template is empty".into());
+ anyhow::bail!("Template is empty");
}
// Render template with minijinja
@@ -166,14 +162,14 @@ fn build_squash_prompt(
target_branch: &str,
commits: &[String],
context: &PromptContext<'_>,
-) -> Result<String, Box<dyn std::error::Error>> {
+) -> anyhow::Result<String> {
// Get template source
let template = match (&config.squash_template, &config.squash_template_file) {
(Some(inline), None) => inline.clone(),
(None, Some(path)) => {
let expanded_path = PathBuf::from(shellexpand::tilde(path).as_ref());
std::fs::read_to_string(&expanded_path).map_err(|e| {
- format!(
+ anyhow::anyhow!(
"Failed to read squash-template-file '{}': {}",
format_path_for_display(&expanded_path),
e
@@ -190,7 +186,7 @@ fn build_squash_prompt(
// Validate non-empty
if template.trim().is_empty() {
- return Err("Squash template is empty".into());
+ anyhow::bail!("Squash template is empty");
}
// Render template with minijinja
@@ -212,7 +208,7 @@ fn build_squash_prompt(
pub fn generate_commit_message(
commit_generation_config: &CommitGenerationConfig,
-) -> Result<String, GitError> {
+) -> anyhow::Result<String> {
// Check if commit generation is configured (non-empty command)
if commit_generation_config.is_configured() {
let command = commit_generation_config.command.as_ref().unwrap();
@@ -223,7 +219,7 @@ pub fn generate_commit_message(
commit_generation_config,
)
.map_err(|e| {
- GitError::CommandFailed(format!(
+ anyhow::anyhow!(format!(
"Commit generation command '{}' failed: {}",
command, e
))
@@ -263,7 +259,7 @@ fn try_generate_commit_message(
command: &str,
args: &[String],
config: &CommitGenerationConfig,
-) -> Result<String, Box<dyn std::error::Error>> {
+) -> anyhow::Result<String> {
let repo = Repository::current();
// Get staged diff
@@ -307,7 +303,7 @@ pub fn generate_squash_message(
current_branch: &str,
repo_name: &str,
commit_generation_config: &CommitGenerationConfig,
-) -> Result<String, Box<dyn std::error::Error>> {
+) -> anyhow::Result<String> {
// Check if commit generation is configured (non-empty command)
if commit_generation_config.is_configured() {
let command = commit_generation_config.command.as_ref().unwrap();
diff --git a/src/main.rs b/src/main.rs
index 4253990a5..2664ed690 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,8 +1,9 @@
use anstyle::Style;
+use anyhow::Context;
use clap::FromArgMatches;
use std::process;
use worktrunk::config::WorktrunkConfig;
-use worktrunk::git::{GitError, GitResultExt, Repository, set_base_path};
+use worktrunk::git::{Repository, exit_code, is_command_not_approved, set_base_path};
use worktrunk::path::format_path_for_display;
use worktrunk::styling::{SUCCESS_EMOJI, println};
@@ -173,7 +174,7 @@ fn main() {
command_name,
} => {
let mut cli_cmd = cli::build_command();
- handle_init(shell, command_name, &mut cli_cmd).git_err()
+ handle_init(shell, command_name, &mut cli_cmd).map_err(|e| anyhow::anyhow!("{}", e))
}
Commands::Config { action } => match action {
ConfigCommand::Init => handle_config_init(),
@@ -185,6 +186,7 @@ fn main() {
command_name,
} => {
handle_configure_shell(shell, force, command_name)
+ .map_err(|e| anyhow::anyhow!("{}", e))
.map(|results| {
use anstyle::{AnsiColor, Color};
@@ -232,13 +234,11 @@ fn main() {
"{HINT_EMOJI} {HINT}Restart your shell or run: source <config-file>{HINT:#}"
);
})
- .git_err()
}
ConfigCommand::Status { action } => match action {
StatusAction::Set { value, branch } => handle_config_status_set(value, branch),
StatusAction::Unset { target } => handle_config_status_unset(target),
- }
- .git_err(),
+ },
},
Commands::Standalone { action } => match action {
StandaloneCommand::RunHook { hook_type, force } => {
@@ -275,7 +275,7 @@ fn main() {
// Load config and merge with CLI flags (CLI flags take precedence)
WorktrunkConfig::load()
- .git_context("Failed to load config")
+ .context("Failed to load config")
.and_then(|config| {
let repo = Repository::current();
@@ -315,7 +315,7 @@ fn main() {
force,
verify,
} => WorktrunkConfig::load()
- .git_context("Failed to load config")
+ .context("Failed to load config")
.and_then(|config| {
// Execute switch operation (creates worktree, runs post-create hooks)
let (result, resolved_branch) =
@@ -341,7 +341,7 @@ fn main() {
if let Err(e) = ctx.spawn_post_start_commands() {
// Only treat CommandNotApproved as non-fatal (user declined)
// Other errors should still fail
- if !matches!(e, GitError::CommandNotApproved) {
+ if !is_command_not_approved(&e) {
return Err(e);
}
}
@@ -359,12 +359,10 @@ fn main() {
delete_branch,
force_delete,
background,
- } => (|| -> Result<(), GitError> {
+ } => (|| -> anyhow::Result<()> {
// Validate conflicting flags
if !delete_branch && force_delete {
- return Err(GitError::message(
- "Cannot use --force-delete with --no-delete-branch",
- ));
+ anyhow::bail!("Cannot use --force-delete with --no-delete-branch");
}
let repo = Repository::current();
@@ -445,11 +443,7 @@ fn main() {
let _ = output::error(e.to_string());
// Preserve exit code from child processes (especially for signals like SIGINT)
- let exit_code = match &e {
- GitError::ChildProcessExited { code, .. } => *code,
- GitError::HookCommandFailed { exit_code, .. } => exit_code.unwrap_or(1),
- _ => 1,
- };
- process::exit(exit_code);
+ let code = exit_code(&e).unwrap_or(1);
+ process::exit(code);
}
}
diff --git a/src/output/directive.rs b/src/output/directive.rs
index a72acad23..a231e7ca9 100644
--- a/src/output/directive.rs
+++ b/src/output/directive.rs
@@ -88,8 +88,13 @@ impl DirectiveOutput {
}
pub fn error(&mut self, message: String) -> io::Result<()> {
- // Error messages go to stderr (already formatted, include ❌ emoji from GitError::Display)
- writeln!(io::stderr(), "{message}")?;
+ use worktrunk::styling::{ERROR, ERROR_EMOJI};
+ // Error messages go to stderr; add emoji and styling if not already present
+ if message.starts_with(ERROR_EMOJI) {
+ writeln!(io::stderr(), "{message}")?;
+ } else {
+ writeln!(io::stderr(), "{ERROR_EMOJI} {ERROR}{message}{ERROR:#}")?;
+ }
io::stderr().flush()
}
diff --git a/src/output/global.rs b/src/output/global.rs
index 5367b9e17..dc7c54254 100644
--- a/src/output/global.rs
+++ b/src/output/global.rs
@@ -140,7 +140,7 @@ pub fn warning(message: impl Into<String>) -> io::Result<()> {
/// Emit an error message
///
/// Error messages are critical failures like "❌ Cannot remove main worktree"
-/// The message is already formatted (includes ERROR_EMOJI from GitError::Display).
+/// The message is already formatted (includes ERROR_EMOJI from WorktrunkError::Display).
///
/// In interactive mode: goes to stdout (with other worktrunk output)
/// In directive mode: goes to stderr (with other user-facing messages)
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 7ed7010c3..5a8a20374 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -3,7 +3,7 @@
use crate::commands::process::spawn_detached;
use crate::commands::worktree::{RemoveResult, SwitchResult};
use crate::output::global::format_switch_success;
-use worktrunk::git::GitError;
+use worktrunk::git::{branch_deletion_failed, worktree_removal_failed};
use worktrunk::path::format_path_for_display;
use worktrunk::styling::{
CYAN, CYAN_BOLD, GREEN, GREEN_BOLD, WARNING, WARNING_BOLD, format_with_gutter,
@@ -112,7 +112,7 @@ pub fn handle_switch_output(
result: &SwitchResult,
branch: &str,
has_execute_command: bool,
-) -> Result<(), GitError> {
+) -> anyhow::Result<()> {
// Set target directory for command execution
super::change_directory(result.path())?;
@@ -137,14 +137,15 @@ pub fn handle_switch_output(
}
/// Execute the --execute command after hooks have run
-pub fn execute_user_command(command: &str) -> Result<(), GitError> {
+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)?;
+ super::execute(command).map_err(from_io_error)?;
Ok(())
}
@@ -182,7 +183,7 @@ pub fn handle_remove_output(
branch: Option<&str>,
strict_branch_deletion: bool,
background: bool,
-) -> Result<(), GitError> {
+) -> anyhow::Result<()> {
let RemoveResult::RemovedWorktree {
main_path,
worktree_path,
@@ -253,14 +254,10 @@ pub fn handle_remove_output(
// Synchronous mode: remove immediately and report actual results
// Track whether branch was actually deleted (will be computed based on deletion attempt)
if let Err(err) = repo.remove_worktree(worktree_path) {
- return Err(match err {
- GitError::CommandFailed(msg) => GitError::WorktreeRemovalFailed {
- branch: branch_name.clone(),
- path: worktree_path.clone(),
- error: msg,
- },
- other => other,
- });
+ anyhow::bail!(
+ "{}",
+ worktree_removal_failed(branch_name, worktree_path, &err.to_string())
+ );
}
// Delete the branch (unless --no-delete-branch was specified)
@@ -282,10 +279,10 @@ pub fn handle_remove_output(
}
Ok(false) | Err(_) => {
// Branch is not fully merged to target
- Err(worktrunk::git::GitError::CommandFailed(format!(
+ Err(anyhow::anyhow!(
"error: the branch '{}' is not fully merged",
branch_name
- )))
+ ))
}
}
};
@@ -294,13 +291,7 @@ pub fn handle_remove_output(
Ok(_) => true,
Err(e) => {
if strict_branch_deletion {
- return Err(match e {
- GitError::CommandFailed(msg) => GitError::BranchDeletionFailed {
- branch: branch_name.clone(),
- error: msg,
- },
- other => other,
- });
+ anyhow::bail!("{}", branch_deletion_failed(branch_name, &e.to_string()));
}
// If branch deletion fails in non-strict mode, show a warning but don't error
@@ -309,11 +300,7 @@ pub fn handle_remove_output(
))?;
// Show the git error in a gutter-formatted block (raw output, no styling)
- let raw_error = match &e {
- GitError::CommandFailed(msg) => msg.as_str(),
- _ => &e.to_string(),
- };
- super::gutter(format_with_gutter(raw_error, "", None))?;
+ super::gutter(format_with_gutter(&e.to_string(), "", None))?;
false
}
}
@@ -406,7 +393,7 @@ pub(crate) fn execute_streaming(
pub fn execute_command_in_worktree(
worktree_path: &std::path::Path,
command: &str,
-) -> Result<(), GitError> {
+) -> anyhow::Result<()> {
use std::io::Write;
use worktrunk::styling::{eprint, stderr};
@@ -421,8 +408,8 @@ 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 automatically converted to GitError, parsing exit codes via From impl
- execute_streaming(command, worktree_path, true)?;
+ // 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)?;
// Flush to ensure all output appears before we continue
super::flush()?;
diff --git a/src/output/interactive.rs b/src/output/interactive.rs
index 79fb2c9e3..7edf557b2 100644
--- a/src/output/interactive.rs
+++ b/src/output/interactive.rs
@@ -65,8 +65,13 @@ impl InteractiveOutput {
}
pub fn error(&mut self, message: String) -> io::Result<()> {
- // Error messages are already formatted (include ❌ emoji from GitError::Display)
- println!("{message}");
+ use worktrunk::styling::{ERROR, ERROR_EMOJI};
+ // Add emoji and styling if not already present
+ if message.starts_with(ERROR_EMOJI) {
+ println!("{message}");
+ } else {
+ println!("{ERROR_EMOJI} {ERROR}{message}{ERROR:#}");
+ }
stdout().flush()?;
Ok(())
}
diff --git a/tests/git_error_display.rs b/tests/git_error_display.rs
index eea36200c..b5ecaae53 100644
--- a/tests/git_error_display.rs
+++ b/tests/git_error_display.rs
@@ -1,23 +1,22 @@
use insta::assert_snapshot;
-use worktrunk::git::GitError;
+use worktrunk::git::{push_failed, worktree_removal_failed};
#[test]
fn display_worktree_removal_failed() {
- let err = GitError::WorktreeRemovalFailed {
- branch: "feature-x".to_string(),
- path: std::path::PathBuf::from("/tmp/repo.feature-x"),
- error: "fatal: worktree is dirty\nerror: could not remove worktree".to_string(),
- };
+ let msg = worktree_removal_failed(
+ "feature-x",
+ std::path::Path::new("/tmp/repo.feature-x"),
+ "fatal: worktree is dirty\nerror: could not remove worktree",
+ );
- assert_snapshot!("worktree_removal_failed", err.to_string());
+ assert_snapshot!("worktree_removal_failed", msg);
}
#[test]
fn display_push_failed() {
- let err = GitError::PushFailed {
- error: "To /Users/user/workspace/repo/.git\n ! [remote rejected] HEAD -> main (Up-to-date check failed)\nerror: failed to push some refs to '/Users/user/workspace/repo/.git'"
- .to_string(),
- };
+ let msg = push_failed(
+ "To /Users/user/workspace/repo/.git\n ! [remote rejected] HEAD -> main (Up-to-date check failed)\nerror: failed to push some refs to '/Users/user/workspace/repo/.git'",
+ );
- assert_snapshot!("push_failed", err.to_string());
+ assert_snapshot!("push_failed", msg);
}
diff --git a/tests/snapshots/integration__integration_tests__approvals__ask_approvals_no_config.snap b/tests/snapshots/integration__integration_tests__approvals__ask_approvals_no_config.snap
index 28ef935ab..7d271f7a5 100644
--- a/tests/snapshots/integration__integration_tests__approvals__ask_approvals_no_config.snap
+++ b/tests/snapshots/integration__integration_tests__approvals__ask_approvals_no_config.snap
@@ -10,8 +10,12 @@ info:
COLUMNS: "150"
GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_COUNT: "1"
GIT_CONFIG_GLOBAL: /dev/null
+ GIT_CONFIG_KEY_0: advice.mergeConflict
GIT_CONFIG_SYSTEM: /dev/null
+ GIT_CONFIG_VALUE_0: "false"
+ GIT_EDITOR: ""
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
@@ -20,7 +24,7 @@ info:
success: false
exit_code: 1
----- stdout -----
-No project configuration found
+❌ No project configuration found
----- stderr -----
❌ No project configuration found
diff --git a/tests/snapshots/integration__integration_tests__post_start_commands__invalid_toml.snap b/tests/snapshots/integration__integration_tests__post_start_commands__invalid_toml.snap
index 2e8a1ea57..157107da8 100644
--- a/tests/snapshots/integration__integration_tests__post_start_commands__invalid_toml.snap
+++ b/tests/snapshots/integration__integration_tests__post_start_commands__invalid_toml.snap
@@ -11,8 +11,11 @@ info:
COLUMNS: "150"
GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_COUNT: "1"
GIT_CONFIG_GLOBAL: /dev/null
+ GIT_CONFIG_KEY_0: advice.mergeConflict
GIT_CONFIG_SYSTEM: /dev/null
+ GIT_CONFIG_VALUE_0: "false"
GIT_EDITOR: ""
LANG: C
LC_ALL: C
@@ -23,11 +26,5 @@ success: false
exit_code: 1
----- stdout -----
❌ Failed to load project config
-  Failed to parse TOML: TOML parse error at line 1, column 39
-  |
-  1 | post-create-command = [invalid syntax
-  | ^
-  unclosed array, expected `]`
-
----- stderr -----