Skip to content

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

refactor: Add GitResultExt trait to simplify error propagation

Maximilian Roos9af9d4bd8cb0
diff --git a/src/commands/command_approval.rs b/src/commands/command_approval.rs
index 289c6b9b2..fcad205f9 100644
--- a/src/commands/command_approval.rs
+++ b/src/commands/command_approval.rs
@@ -3,7 +3,7 @@
//! Shared helpers for approving commands declared in project configuration.
use worktrunk::config::{ApprovedCommand, CommandConfig, WorktrunkConfig};
-use worktrunk::git::GitError;
+use worktrunk::git::{GitError, GitResultExt};
use worktrunk::styling::{
AnstyleStyle, HINT_EMOJI, WARNING, WARNING_EMOJI, eprintln, format_with_gutter,
};
@@ -56,8 +56,7 @@ pub fn approve_command_batch(
let approved = if force {
true
} else {
- prompt_for_batch_approval(&needs_approval, project_id)
- .map_err(|e| GitError::CommandFailed(e.to_string()))?
+ prompt_for_batch_approval(&needs_approval, project_id)?
};
if !approved {
@@ -66,8 +65,7 @@ pub fn approve_command_batch(
return Ok(false);
}
- let mut fresh_config = WorktrunkConfig::load()
- .map_err(|e| GitError::CommandFailed(format!("Failed to reload config: {}", e)))?;
+ let mut fresh_config = WorktrunkConfig::load().git_context("Failed to reload config")?;
let mut updated = false;
for (_, command) in needs_approval {
diff --git a/src/commands/config.rs b/src/commands/config.rs
index 2f1ec8f0b..56ad50920 100644
--- a/src/commands/config.rs
+++ b/src/commands/config.rs
@@ -1,6 +1,6 @@
use etcetera::base_strategy::{BaseStrategy, choose_base_strategy};
use std::path::PathBuf;
-use worktrunk::git::{GitError, Repository};
+use worktrunk::git::{GitError, GitResultExt, Repository};
use worktrunk::styling::{
AnstyleStyle, GREEN, HINT, HINT_EMOJI, SUCCESS_EMOJI, format_toml, print, println,
};
@@ -34,8 +34,7 @@ pub fn handle_config_init() -> Result<(), GitError> {
}
// Write the example config
- std::fs::write(&config_path, CONFIG_EXAMPLE)
- .map_err(|e| GitError::CommandFailed(format!("Failed to write config file: {}", e)))?;
+ std::fs::write(&config_path, CONFIG_EXAMPLE).git_context("Failed to write config file")?;
// Success message
let bold = AnstyleStyle::new().bold();
@@ -83,8 +82,8 @@ fn display_global_config() -> Result<(), GitError> {
}
// Read and display the file contents
- let contents = std::fs::read_to_string(&config_path)
- .map_err(|e| GitError::CommandFailed(format!("Failed to read config file: {}", e)))?;
+ let contents =
+ std::fs::read_to_string(&config_path).git_context("Failed to read config file")?;
if contents.trim().is_empty() {
println!("{HINT_EMOJI} {HINT}Empty file (using defaults){HINT:#}");
@@ -121,8 +120,8 @@ fn display_project_config() -> Result<(), GitError> {
}
// Read and display the file contents
- let contents = std::fs::read_to_string(&config_path)
- .map_err(|e| GitError::CommandFailed(format!("Failed to read config file: {}", e)))?;
+ let contents =
+ std::fs::read_to_string(&config_path).git_context("Failed to read config file")?;
if contents.trim().is_empty() {
println!("{HINT_EMOJI} {HINT}Empty file{HINT:#}");
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index 8a72096e6..286c2739d 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -1,5 +1,5 @@
use worktrunk::config::{ProjectConfig, WorktrunkConfig};
-use worktrunk::git::{GitError, Repository};
+use worktrunk::git::{GitError, GitResultExt, Repository};
use worktrunk::styling::{AnstyleStyle, CYAN, CYAN_BOLD, format_with_gutter};
use super::command_executor::{CommandContext, prepare_project_commands};
@@ -18,8 +18,7 @@ pub fn handle_merge(
let repo = Repository::current();
// Show progress for initial validation
- crate::output::progress(format!("πŸ”„ {CYAN}Validating merge...{CYAN:#}"))
- .map_err(|e| GitError::CommandFailed(e.to_string()))?;
+ crate::output::progress(format!("πŸ”„ {CYAN}Validating merge...{CYAN:#}"))?;
// Get current branch
let current_branch = repo.current_branch()?.ok_or(GitError::DetachedHead)?;
@@ -32,21 +31,18 @@ pub fn handle_merge(
let bold = AnstyleStyle::new().bold();
crate::output::success(format!(
"Already on {bold}{target_branch}{bold:#}, nothing to merge"
- ))
- .map_err(|e| GitError::CommandFailed(e.to_string()))?;
+ ))?;
return Ok(());
}
// Load config for LLM integration
- let config = WorktrunkConfig::load()
- .map_err(|e| GitError::CommandFailed(format!("Failed to load config: {}", e)))?;
+ let config = WorktrunkConfig::load().git_context("Failed to load config")?;
// Run pre-merge checks unless --no-hooks was specified
// Do this BEFORE committing so we fail fast if checks won't pass
if !no_hooks && let Ok(Some(project_config)) = ProjectConfig::load(&repo.worktree_root()?) {
- 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().git_context("Failed to get current directory")?;
run_pre_merge_commands(
&project_config,
&current_branch,
@@ -72,8 +68,7 @@ pub fn handle_merge(
// Rebase onto target
crate::output::progress(format!(
"πŸ”„ {CYAN}Rebasing onto {CYAN_BOLD}{target_branch}{CYAN_BOLD:#}...{CYAN:#}"
- ))
- .map_err(|e| GitError::CommandFailed(e.to_string()))?;
+ ))?;
let rebase_result = repo.run_command(&["rebase", &target_branch]);
@@ -118,8 +113,7 @@ pub fn handle_merge(
// Finish worktree unless --keep was specified
if !keep {
- crate::output::progress(format!("πŸ”„ {CYAN}Cleaning up worktree...{CYAN:#}"))
- .map_err(|e| GitError::CommandFailed(e.to_string()))?;
+ crate::output::progress(format!("πŸ”„ {CYAN}Cleaning up worktree...{CYAN:#}"))?;
// Get primary worktree path before finishing (while we can still run git commands)
let primary_worktree_dir = repo.main_worktree_root()?;
@@ -128,8 +122,7 @@ pub fn handle_merge(
// Set directory for shell integration (but don't print separate success message)
if let super::worktree::RemoveResult::RemovedWorktree { primary_path } = &result {
- crate::output::change_directory(primary_path)
- .map_err(|e| GitError::CommandFailed(e.to_string()))?;
+ crate::output::change_directory(primary_path)?;
}
// Check if we need to switch to target branch
@@ -138,26 +131,18 @@ pub fn handle_merge(
if new_branch.as_deref() != Some(&target_branch) {
crate::output::progress(format!(
"πŸ”„ {CYAN}Switching to {CYAN_BOLD}{target_branch}{CYAN_BOLD:#}...{CYAN:#}"
- ))
- .map_err(|e| GitError::CommandFailed(e.to_string()))?;
+ ))?;
primary_repo
.run_command(&["switch", &target_branch])
- .map_err(|e| {
- GitError::CommandFailed(format!(
- "Failed to switch to '{}': {}",
- target_branch, e
- ))
- })?;
+ .git_context(&format!("Failed to switch to '{}'", target_branch))?;
}
// Print comprehensive summary
- crate::output::progress("")
- .map_err(|e| GitError::CommandFailed(format!("Output error: {}", e)))?;
+ crate::output::progress("")?;
handle_merge_summary_output(Some(&primary_worktree_dir))?;
} else {
// Print comprehensive summary (worktree preserved)
- crate::output::progress("")
- .map_err(|e| GitError::CommandFailed(format!("Output error: {}", e)))?;
+ crate::output::progress("")?;
handle_merge_summary_output(None)?;
}
@@ -179,10 +164,10 @@ fn handle_merge_summary_output(primary_path: Option<&std::path::Path>) -> Result
let message = format_merge_summary(primary_path);
// Show success message (formatting added by OutputContext)
- crate::output::success(message).map_err(|e| GitError::CommandFailed(e.to_string()))?;
+ crate::output::success(message)?;
// Flush output
- crate::output::flush().map_err(|e| GitError::CommandFailed(e.to_string()))?;
+ crate::output::flush()?;
Ok(())
}
@@ -219,31 +204,27 @@ fn handle_commit_changes(
crate::output::progress(format!(
"πŸ”„ {CYAN}Committing uncommitted changes...{CYAN:#}"
- ))
- .map_err(|e| GitError::CommandFailed(e.to_string()))?;
+ ))?;
// Stage all changes including untracked files
repo.run_command(&["add", "-A"])
- .map_err(|e| GitError::CommandFailed(format!("Failed to stage changes: {}", e)))?;
+ .git_context("Failed to stage changes")?;
// Generate commit message
- crate::output::progress(format!("πŸ”„ {CYAN}Generating commit message...{CYAN:#}"))
- .map_err(|e| GitError::CommandFailed(e.to_string()))?;
+ crate::output::progress(format!("πŸ”„ {CYAN}Generating commit message...{CYAN:#}"))?;
let commit_message =
crate::llm::generate_commit_message(custom_instruction, commit_generation_config)?;
// Display the generated commit message
let formatted_message = format_commit_message_for_display(&commit_message);
- crate::output::progress(format_with_gutter(&formatted_message, "", None))
- .map_err(|e| GitError::CommandFailed(e.to_string()))?;
+ crate::output::progress(format_with_gutter(&formatted_message, "", None))?;
// Commit
repo.run_command(&["commit", "-m", &commit_message])
- .map_err(|e| GitError::CommandFailed(format!("Failed to commit: {}", e)))?;
+ .git_context("Failed to commit")?;
- crate::output::success("Committed changes")
- .map_err(|e| GitError::CommandFailed(e.to_string()))?;
+ crate::output::success("Committed changes")?;
Ok(())
}
@@ -266,8 +247,7 @@ fn handle_squash(target_branch: &str) -> Result<Option<usize>, GitError> {
let dim = AnstyleStyle::new().dimmed();
crate::output::progress(format!(
"{dim}No commits to squash - already at merge base{dim:#}"
- ))
- .map_err(|e| GitError::CommandFailed(e.to_string()))?;
+ ))?;
return Ok(None);
}
@@ -281,16 +261,14 @@ fn handle_squash(target_branch: &str) -> Result<Option<usize>, GitError> {
let dim = AnstyleStyle::new().dimmed();
crate::output::progress(format!(
"{dim}Only 1 commit since {CYAN_BOLD}{target_branch}{CYAN_BOLD:#} - no squashing needed{dim:#}"
- ))
- .map_err(|e| GitError::CommandFailed(e.to_string()))?;
+ ))?;
return Ok(None);
}
// One or more commits (possibly with staged changes) - squash them
crate::output::progress(format!(
"πŸ”„ {CYAN}Squashing {commit_count} commits into one...{CYAN:#}"
- ))
- .map_err(|e| GitError::CommandFailed(e.to_string()))?;
+ ))?;
// Get commit subjects for the squash message
let range = format!("{}..HEAD", merge_base);
@@ -299,33 +277,27 @@ fn handle_squash(target_branch: &str) -> Result<Option<usize>, GitError> {
// Load config and generate commit message
crate::output::progress(format!(
"πŸ”„ {CYAN}Generating squash commit message...{CYAN:#}"
- ))
- .map_err(|e| GitError::CommandFailed(e.to_string()))?;
+ ))?;
- let config = WorktrunkConfig::load()
- .map_err(|e| GitError::CommandFailed(format!("Failed to load config: {}", e)))?;
+ let config = WorktrunkConfig::load().git_context("Failed to load config")?;
let commit_message =
crate::llm::generate_squash_message(target_branch, &subjects, &config.commit_generation)
- .map_err(|e| {
- GitError::CommandFailed(format!("Failed to generate commit message: {}", e))
- })?;
+ .git_context("Failed to generate commit message")?;
// Display the generated commit message
let formatted_message = format_commit_message_for_display(&commit_message);
- crate::output::progress(format_with_gutter(&formatted_message, "", None))
- .map_err(|e| GitError::CommandFailed(e.to_string()))?;
+ crate::output::progress(format_with_gutter(&formatted_message, "", None))?;
// Reset to merge base (soft reset stages all changes)
repo.run_command(&["reset", "--soft", &merge_base])
- .map_err(|e| GitError::CommandFailed(format!("Failed to reset to merge base: {}", e)))?;
+ .git_context("Failed to reset to merge base")?;
// Commit with the generated message
repo.run_command(&["commit", "-m", &commit_message])
- .map_err(|e| GitError::CommandFailed(format!("Failed to create squash commit: {}", e)))?;
+ .git_context("Failed to create squash commit")?;
// Show success immediately after completing the squash
- crate::output::success(format!("Squashed {commit_count} commits into one"))
- .map_err(|e| GitError::CommandFailed(e.to_string()))?;
+ crate::output::success(format!("Squashed {commit_count} commits into one"))?;
Ok(Some(commit_count))
}
@@ -362,10 +334,8 @@ fn run_pre_merge_commands(
crate::output::progress(format!(
"πŸ”„ {CYAN}Running pre-merge command {CYAN_BOLD}{name}{CYAN_BOLD:#}:{CYAN:#}",
name = prepared.name
- ))
- .map_err(|e| GitError::CommandFailed(format!("Output error: {}", e)))?;
- crate::output::progress(format_with_gutter(&prepared.expanded, "", None))
- .map_err(|e| GitError::CommandFailed(format!("Output error: {}", e)))?;
+ ))?;
+ crate::output::progress(format_with_gutter(&prepared.expanded, "", None))?;
if let Err(e) = execute_command_in_worktree(worktree_path, &prepared.expanded) {
return Err(GitError::PreMergeCommandFailed {
@@ -383,8 +353,7 @@ fn run_pre_merge_commands(
/// Load project configuration with proper error conversion
fn load_project_config(repo: &Repository) -> Result<Option<ProjectConfig>, GitError> {
let repo_root = repo.worktree_root()?;
- ProjectConfig::load(&repo_root)
- .map_err(|e| GitError::CommandFailed(format!("Failed to load project config: {}", e)))
+ ProjectConfig::load(&repo_root).git_context("Failed to load project config")
}
/// Execute post-merge commands sequentially in the main worktree (blocking)
@@ -430,10 +399,8 @@ fn execute_post_merge_commands(
crate::output::progress(format!(
"πŸ”„ {CYAN}Running post-merge command {CYAN_BOLD}{name}{CYAN_BOLD:#}:{CYAN:#}",
name = prepared.name
- ))
- .map_err(|e| GitError::CommandFailed(format!("Output error: {}", e)))?;
- crate::output::progress(format_with_gutter(&prepared.expanded, "", None))
- .map_err(|e| GitError::CommandFailed(format!("Output error: {}", e)))?;
+ ))?;
+ crate::output::progress(format_with_gutter(&prepared.expanded, "", None))?;
if let Err(e) = execute_command_in_worktree(main_worktree_path, &prepared.expanded) {
use worktrunk::styling::WARNING_EMOJI;
@@ -441,13 +408,12 @@ fn execute_post_merge_commands(
crate::output::progress(format!(
"{WARNING_EMOJI} {WARNING}Command {warning_bold}{name}{warning_bold:#} failed: {e}{WARNING:#}",
name = prepared.name,
- ))
- .map_err(|e| GitError::CommandFailed(format!("Output error: {}", e)))?;
+ ))?;
// Continue with other commands even if one fails
}
}
- crate::output::flush().map_err(|e| GitError::CommandFailed(format!("Output error: {}", e)))?;
+ crate::output::flush()?;
Ok(())
}
diff --git a/src/commands/process.rs b/src/commands/process.rs
index 2ec0423fb..6eac10bcb 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;
+use worktrunk::git::{GitError, GitResultExt};
/// Spawn a detached background process with output redirected to a log file
///
@@ -26,8 +26,7 @@ pub fn spawn_detached(
let git_path = worktree_path.join(".git");
let git_dir = if git_path.is_file() {
// Read the gitdir path from the file
- let content = fs::read_to_string(&git_path)
- .map_err(|e| GitError::CommandFailed(format!("Failed to read .git file: {}", e)))?;
+ let content = fs::read_to_string(&git_path).git_context("Failed to read .git file")?;
// Format is "gitdir: /path/to/git/dir"
let gitdir_path = content
.trim()
@@ -40,15 +39,13 @@ pub fn spawn_detached(
// Create log directory in the git directory
let log_dir = git_dir.join("wt-logs");
- fs::create_dir_all(&log_dir)
- .map_err(|e| GitError::CommandFailed(format!("Failed to create log directory: {}", e)))?;
+ fs::create_dir_all(&log_dir).git_context("Failed to create log directory")?;
// Generate log filename (no timestamp - overwrites on each run)
let log_path = log_dir.join(format!("post-start-{}.log", name));
// Create log file
- let log_file = fs::File::create(&log_path)
- .map_err(|e| GitError::CommandFailed(format!("Failed to create log file: {}", e)))?;
+ let log_file = fs::File::create(&log_path).git_context("Failed to create log file")?;
#[cfg(unix)]
{
@@ -88,7 +85,7 @@ fn spawn_detached_unix(
})?))
.stderr(Stdio::from(log_file))
.spawn()
- .map_err(|e| GitError::CommandFailed(format!("Failed to spawn detached process: {}", e)))?;
+ .git_context("Failed to spawn detached process")?;
Ok(())
}
@@ -116,7 +113,7 @@ fn spawn_detached_windows(
.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: {}", e)))?;
+ .git_context("Failed to spawn detached process")?;
Ok(())
}
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rs
index c3122b33f..ca96038a8 100644
--- a/src/commands/worktree.rs
+++ b/src/commands/worktree.rs
@@ -102,7 +102,7 @@
use std::path::PathBuf;
use worktrunk::config::{ProjectConfig, WorktrunkConfig};
-use worktrunk::git::{GitError, Repository};
+use worktrunk::git::{GitError, GitResultExt, Repository};
use worktrunk::styling::{
ADDITION, AnstyleStyle, CYAN, CYAN_BOLD, DELETION, GREEN, GREEN_BOLD, SUCCESS_EMOJI, WARNING,
WARNING_EMOJI, format_with_gutter,
@@ -163,8 +163,7 @@ pub fn handle_switch(
if base.is_some() && !create {
crate::output::progress(format!(
"{WARNING_EMOJI} {WARNING}--base flag is only used with --create, ignoring{WARNING:#}"
- ))
- .map_err(|e| GitError::CommandFailed(format!("Output error: {}", e)))?;
+ ))?;
}
// Check if worktree already exists for this branch
@@ -207,12 +206,12 @@ pub fn handle_switch(
}
repo.run_command(&args)
- .map_err(|e| GitError::CommandFailed(format!("Failed to create worktree: {}", e)))?;
+ .git_context("Failed to create worktree")?;
// Canonicalize the path to resolve any .. components
- let worktree_path = worktree_path.canonicalize().map_err(|e| {
- GitError::CommandFailed(format!("Failed to canonicalize worktree path: {}", e))
- })?;
+ let worktree_path = worktree_path
+ .canonicalize()
+ .git_context("Failed to canonicalize worktree path")?;
// Execute post-create commands (sequential, blocking)
if !no_hooks {
@@ -264,13 +263,11 @@ fn remove_current_worktree(repo: &Repository) -> Result<RemoveResult, GitError>
if let Err(e) = repo.remove_worktree(&worktree_root) {
crate::output::progress(format!(
"{WARNING_EMOJI} {WARNING}Failed to remove worktree: {e}{WARNING:#}"
- ))
- .map_err(|e| GitError::CommandFailed(format!("Output error: {}", e)))?;
+ ))?;
crate::output::progress(format!(
"You may need to run 'git worktree remove {}' manually",
worktree_root.display()
- ))
- .map_err(|e| GitError::CommandFailed(format!("Output error: {}", e)))?;
+ ))?;
}
Ok(RemoveResult::RemovedWorktree {
@@ -279,9 +276,7 @@ fn remove_current_worktree(repo: &Repository) -> Result<RemoveResult, GitError>
} else {
// In main repo but not on default branch: switch to default
repo.run_command(&["switch", &default_branch])
- .map_err(|e| {
- GitError::CommandFailed(format!("Failed to switch to '{}': {}", default_branch, e))
- })?;
+ .git_context(&format!("Failed to switch to '{}'", default_branch))?;
Ok(RemoveResult::SwitchedToDefault(default_branch))
}
@@ -327,13 +322,11 @@ fn remove_worktree_by_name(repo: &Repository, branch_name: &str) -> Result<Remov
if let Err(e) = repo.remove_worktree(&worktree_path) {
crate::output::progress(format!(
"{WARNING_EMOJI} {WARNING}Failed to remove worktree: {e}{WARNING:#}"
- ))
- .map_err(|e| GitError::CommandFailed(format!("Output error: {}", e)))?;
+ ))?;
crate::output::progress(format!(
"You may need to run 'git worktree remove {}' manually",
worktree_path.display()
- ))
- .map_err(|e| GitError::CommandFailed(format!("Output error: {}", e)))?;
+ ))?;
}
// If we removed the current worktree, return to primary
@@ -397,8 +390,7 @@ fn check_worktree_conflicts(
/// Helper to load project config with error handling
fn load_project_config(repo: &Repository) -> Result<Option<ProjectConfig>, GitError> {
let repo_root = repo.worktree_root()?;
- ProjectConfig::load(&repo_root)
- .map_err(|e| GitError::CommandFailed(format!("Failed to load project config: {}", e)))
+ ProjectConfig::load(&repo_root).git_context("Failed to load project config")
}
/// Execute post-create commands sequentially (blocking)
@@ -438,23 +430,20 @@ fn execute_post_create_commands(
// Execute each command sequentially
for prepared in commands {
- crate::output::progress(format!("πŸ”„ {CYAN}Executing (post-create):{CYAN:#}"))
- .map_err(|e| GitError::CommandFailed(format!("Output error: {}", e)))?;
- crate::output::progress(format_with_gutter(&prepared.expanded, "", None))
- .map_err(|e| GitError::CommandFailed(format!("Output error: {}", e)))?;
+ crate::output::progress(format!("πŸ”„ {CYAN}Executing (post-create):{CYAN:#}"))?;
+ crate::output::progress(format_with_gutter(&prepared.expanded, "", None))?;
if let Err(e) = execute_command_in_worktree(worktree_path, &prepared.expanded) {
let warning_bold = WARNING.bold();
crate::output::progress(format!(
"{WARNING_EMOJI} {WARNING}Command {warning_bold}{name}{warning_bold:#} failed: {e}{WARNING:#}",
name = prepared.name,
- ))
- .map_err(|e| GitError::CommandFailed(format!("Output error: {}", e)))?;
+ ))?;
// Continue with other commands even if one fails
}
}
- crate::output::flush().map_err(|e| GitError::CommandFailed(format!("Output error: {}", e)))?;
+ crate::output::flush()?;
Ok(())
}
@@ -496,10 +485,8 @@ fn spawn_post_start_commands(
// Spawn each command as a detached background process
for prepared in commands {
- crate::output::progress(format!("πŸ”„ {CYAN}Starting (background):{CYAN:#}"))
- .map_err(|e| GitError::CommandFailed(format!("Output error: {}", e)))?;
- crate::output::progress(format_with_gutter(&prepared.expanded, "", None))
- .map_err(|e| GitError::CommandFailed(format!("Output error: {}", e)))?;
+ crate::output::progress(format!("πŸ”„ {CYAN}Starting (background):{CYAN:#}"))?;
+ crate::output::progress(format_with_gutter(&prepared.expanded, "", None))?;
match spawn_detached(worktree_path, &prepared.expanded, &prepared.name) {
Ok(_log_path) => {
@@ -510,13 +497,12 @@ fn spawn_post_start_commands(
crate::output::progress(format!(
"{WARNING_EMOJI} {WARNING}Failed to spawn '{name}': {e}{WARNING:#}",
name = prepared.name,
- ))
- .map_err(|e| GitError::CommandFailed(format!("Output error: {}", e)))?;
+ ))?;
}
}
}
- crate::output::flush().map_err(|e| GitError::CommandFailed(format!("Output error: {}", e)))?;
+ crate::output::flush()?;
Ok(())
}
@@ -570,8 +556,7 @@ pub fn handle_push(target: Option<&str>, allow_merge_commits: bool) -> Result<()
crate::output::progress(format!(
"πŸ”„ {CYAN}Pushing {commit_count} {commit_text} to {CYAN_BOLD}{target_branch}{CYAN_BOLD:#} @ {head_sha}{CYAN:#}\n"
- ))
- .map_err(|e| GitError::CommandFailed(e.to_string()))?;
+ ))?;
// Show the commit graph with color
let log_output = repo.run_command(&[
@@ -582,8 +567,7 @@ pub fn handle_push(target: Option<&str>, allow_merge_commits: bool) -> Result<()
"--decorate",
&format!("{}..HEAD", target_branch),
])?;
- crate::output::progress(format!("{}\n", log_output.trim()))
- .map_err(|e| GitError::CommandFailed(e.to_string()))?;
+ crate::output::progress(format!("{}\n", log_output.trim()))?;
// Show diff statistics with color
let diff_stat = repo.run_command(&[
@@ -595,8 +579,7 @@ pub fn handle_push(target: Option<&str>, allow_merge_commits: bool) -> Result<()
let diff_stat = diff_stat.trim_end();
if !diff_stat.is_empty() {
- crate::output::progress(format!("{}\n", diff_stat))
- .map_err(|e| GitError::CommandFailed(e.to_string()))?;
+ crate::output::progress(format!("{}\n", diff_stat))?;
}
}
@@ -639,13 +622,11 @@ pub fn handle_push(target: Option<&str>, allow_merge_commits: bool) -> Result<()
crate::output::progress(format!(
"{SUCCESS_EMOJI} {GREEN}Pushed to {GREEN_BOLD}{target_branch}{GREEN_BOLD:#} ({}) {GREEN:#}",
summary_parts.join(", ")
- ))
- .map_err(|e| GitError::CommandFailed(e.to_string()))?;
+ ))?;
} else {
crate::output::progress(format!(
"{SUCCESS_EMOJI} {GREEN}Pushed to {GREEN_BOLD}{target_branch}{GREEN_BOLD:#}{GREEN:#}"
- ))
- .map_err(|e| GitError::CommandFailed(e.to_string()))?;
+ ))?;
}
Ok(())
diff --git a/src/git.rs b/src/git.rs
index 6ea44e30c..113c9f49b 100644
--- a/src/git.rs
+++ b/src/git.rs
@@ -204,6 +204,52 @@ impl std::fmt::Display for GitError {
impl std::error::Error for GitError {}
+// Automatic conversion from io::Error to GitError
+// This eliminates the need for manual .map_err() on output functions
+impl From<std::io::Error> for GitError {
+ fn from(e: std::io::Error) -> Self {
+ GitError::CommandFailed(e.to_string())
+ }
+}
+
+/// 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> {
+ self.map_err(|e| GitError::CommandFailed(format!("{}: {}", context, e)))
+ }
+
+ fn git_err(self) -> Result<T, GitError> {
+ self.map_err(|e| GitError::CommandFailed(e.to_string()))
+ }
+}
+
/// Repository context for git operations.
///
/// Provides a more ergonomic API than the `*_in(path, ...)` functions by
diff --git a/src/main.rs b/src/main.rs
index b7f15e3d6..438c29ea3 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -2,7 +2,7 @@ use anstyle::Style;
use clap::{CommandFactory, Parser, Subcommand};
use std::process;
use worktrunk::config::WorktrunkConfig;
-use worktrunk::git::{GitError, Repository};
+use worktrunk::git::{GitError, GitResultExt, Repository};
use worktrunk::styling::{SUCCESS_EMOJI, println};
mod commands;
@@ -297,7 +297,7 @@ fn main() {
let result = match cli.command {
Commands::Init { shell, cmd } => {
let mut cli_cmd = Cli::command();
- handle_init(&shell, &cmd, &mut cli_cmd).map_err(GitError::CommandFailed)
+ handle_init(&shell, &cmd, &mut cli_cmd).git_err()
}
Commands::ConfigureShell { shell, cmd, yes } => {
handle_configure_shell(shell, &cmd, yes)
@@ -346,7 +346,7 @@ fn main() {
"{HINT_EMOJI} {HINT}Restart your shell or run: source <config-file>{HINT:#}"
);
})
- .map_err(GitError::CommandFailed)
+ .git_err()
}
Commands::Config { action } => match action {
ConfigCommand::Init => handle_config_init(),
@@ -361,7 +361,7 @@ fn main() {
force,
no_hooks,
} => WorktrunkConfig::load()
- .map_err(|e| GitError::CommandFailed(format!("Failed to load config: {}", e)))
+ .git_context("Failed to load config")
.and_then(|config| {
handle_switch(&branch, create, base.as_deref(), force, no_hooks, &config)
.and_then(|result| handle_switch_output(&result, &branch, execute.as_deref()))
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index f8e89236a..ea0d46d50 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -1,7 +1,7 @@
//! Output handlers for worktree operations using the global output context
use crate::commands::worktree::{RemoveResult, SwitchResult};
-use worktrunk::git::GitError;
+use worktrunk::git::{GitError, GitResultExt};
use worktrunk::styling::AnstyleStyle;
/// Format plain message for switch operation (no emoji - added by OutputContext)
@@ -69,23 +69,21 @@ pub fn handle_switch_output(
execute: Option<&str>,
) -> Result<(), GitError> {
// Set target directory for command execution
- super::change_directory(result.path()).map_err(|e| GitError::CommandFailed(e.to_string()))?;
+ super::change_directory(result.path())?;
// Show success message (plain text - formatting added by OutputContext)
- super::success(format_switch_message_plain(result, branch))
- .map_err(|e| GitError::CommandFailed(e.to_string()))?;
+ super::success(format_switch_message_plain(result, branch))?;
// Execute command if provided
if let Some(cmd) = execute {
- super::execute(cmd).map_err(|e| GitError::CommandFailed(e.to_string()))?;
+ super::execute(cmd)?;
} else {
// No execute command: show shell integration hint (only in interactive mode)
- super::progress(format!("\n{}", shell_integration_hint()))
- .map_err(|e| GitError::CommandFailed(e.to_string()))?;
+ super::progress(format!("\n{}", shell_integration_hint()))?;
}
// Flush output (important for directive mode)
- super::flush().map_err(|e| GitError::CommandFailed(e.to_string()))?;
+ super::flush()?;
Ok(())
}
@@ -94,16 +92,14 @@ pub fn handle_switch_output(
pub fn handle_remove_output(result: &RemoveResult) -> Result<(), GitError> {
// For removed worktree, set target directory for shell to cd to
if let RemoveResult::RemovedWorktree { primary_path } = result {
- super::change_directory(primary_path)
- .map_err(|e| GitError::CommandFailed(e.to_string()))?;
+ super::change_directory(primary_path)?;
}
// Show success message
- super::success(format_remove_message_plain(result))
- .map_err(|e| GitError::CommandFailed(e.to_string()))?;
+ super::success(format_remove_message_plain(result))?;
// Flush output
- super::flush().map_err(|e| GitError::CommandFailed(e.to_string()))?;
+ super::flush()?;
Ok(())
}
@@ -139,7 +135,7 @@ pub fn execute_command_in_worktree(
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.status()
- .map_err(|e| GitError::CommandFailed(format!("Failed to execute command: {}", e)))?;
+ .git_context("Failed to execute command")?;
if !status.success() {
return Err(GitError::CommandFailed(format!(
@@ -149,7 +145,7 @@ pub fn execute_command_in_worktree(
}
// Terminate output (adds NUL in directive mode, no-op in interactive)
- super::terminate_output().map_err(|e| GitError::CommandFailed(e.to_string()))?;
+ super::terminate_output()?;
Ok(())
}
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_execute_failure.snap b/tests/snapshots/integration__integration_tests__switch__switch_execute_failure.snap
index 5eb701cba..cfbc31953 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_execute_failure.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_execute_failure.snap
@@ -14,10 +14,11 @@ info:
GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
GIT_CONFIG_GLOBAL: /dev/null
GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpIb8Xmw/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpfbWMfI/test-config.toml
---
success: false
exit_code: 1