Skip to content

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

refactor: Improve error output and message consistency

Maximilian Roos76c847e33bde
diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rs
index 2414a6066..e6d83481e 100644
--- a/src/commands/command_executor.rs
+++ b/src/commands/command_executor.rs
@@ -88,7 +88,7 @@ where
for (name, command) in &commands {
on_skip(name, command);
}
- return Err(GitError::CommandFailed(String::new()));
+ return Err(GitError::CommandNotApproved);
}
for (name, command) in commands {
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index aa03ef4ce..d488bbcd5 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -1,8 +1,8 @@
use worktrunk::config::{ProjectConfig, WorktrunkConfig};
use worktrunk::git::{GitError, Repository};
use worktrunk::styling::{
- AnstyleStyle, CYAN, CYAN_BOLD, ERROR, ERROR_EMOJI, GREEN, HINT, HINT_EMOJI, SUCCESS_EMOJI,
- eprint, eprintln, format_with_gutter, println,
+ AnstyleStyle, CYAN, CYAN_BOLD, GREEN, SUCCESS_EMOJI, eprint, eprintln, format_with_gutter,
+ println,
};
use super::command_executor::{CommandContext, prepare_project_commands};
@@ -21,12 +21,7 @@ pub fn handle_merge(
let repo = Repository::current();
// Get current branch
- let current_branch = repo.current_branch()?.ok_or_else(|| {
- eprintln!("{ERROR_EMOJI} {ERROR}Not on a branch (detached HEAD){ERROR:#}");
- eprintln!();
- eprintln!("{HINT_EMOJI} {HINT}You are in detached HEAD state{HINT:#}");
- GitError::CommandFailed(String::new())
- })?;
+ let current_branch = repo.current_branch()?.ok_or(GitError::DetachedHead)?;
// Get target branch (default to default branch if not provided)
let target_branch = target.map_or_else(|| repo.default_branch(), |b| Ok(b.to_string()))?;
@@ -226,10 +221,7 @@ fn handle_commit_changes(
// Check if there are staged changes after staging
if !repo.has_staged_changes()? {
// No staged changes means only untracked files exist
- eprintln!("{ERROR_EMOJI} {ERROR}Working tree has untracked files{ERROR:#}");
- eprintln!();
- eprintln!("{HINT_EMOJI} {HINT}Add them with 'git add' and try again{HINT:#}");
- return Err(GitError::CommandFailed(String::new()));
+ return Err(GitError::UntrackedFiles);
}
// Generate commit message
@@ -278,10 +270,7 @@ fn handle_squash(target_branch: &str) -> Result<Option<usize>, GitError> {
if commit_count == 0 && has_staged {
// Just staged changes, no commits - would need to commit but this shouldn't happen in merge flow
- eprintln!("{ERROR_EMOJI} {ERROR}Staged changes without commits{ERROR:#}");
- eprintln!();
- eprintln!("{HINT_EMOJI} {HINT}Please commit them first{HINT:#}");
- return Err(GitError::CommandFailed(String::new()));
+ return Err(GitError::StagedChangesWithoutCommits);
}
if commit_count == 1 && !has_staged {
@@ -374,17 +363,10 @@ fn run_pre_merge_checks(
let _ = std::io::stderr().flush();
if let Err(e) = execute_command_in_worktree(worktree_path, &prepared.expanded) {
- eprintln!();
- let error_bold = ERROR.bold();
- eprintln!(
- "{ERROR_EMOJI} {ERROR}Pre-merge check failed: {error_bold}{name}{error_bold:#}{ERROR:#}",
- name = prepared.name,
- );
- eprintln!();
- eprintln!("{e}");
- eprintln!();
- eprintln!("{HINT_EMOJI} {HINT}Use --no-verify to skip pre-merge checks{HINT:#}");
- return Err(GitError::CommandFailed(String::new()));
+ return Err(GitError::PreMergeCheckFailed {
+ check_name: prepared.name.clone(),
+ error: e.to_string(),
+ });
}
}
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rs
index 4b9b6fe3f..aa8acf76a 100644
--- a/src/commands/worktree.rs
+++ b/src/commands/worktree.rs
@@ -104,8 +104,8 @@ use std::path::PathBuf;
use worktrunk::config::{ProjectConfig, WorktrunkConfig};
use worktrunk::git::{GitError, Repository};
use worktrunk::styling::{
- ADDITION, AnstyleStyle, CYAN, CYAN_BOLD, DELETION, ERROR, ERROR_EMOJI, GREEN, GREEN_BOLD, HINT,
- HINT_EMOJI, SUCCESS_EMOJI, WARNING, WARNING_EMOJI, eprint, eprintln, format_with_gutter,
+ ADDITION, AnstyleStyle, CYAN, CYAN_BOLD, DELETION, GREEN, GREEN_BOLD, SUCCESS_EMOJI, WARNING,
+ WARNING_EMOJI, eprint, eprintln, format_with_gutter,
};
use super::command_executor::{CommandContext, prepare_project_commands};
@@ -154,13 +154,9 @@ pub fn handle_switch(
// Check for conflicting conditions
if create && repo.branch_exists(branch)? {
- let error_bold = ERROR.bold();
- eprintln!(
- "{ERROR_EMOJI} {ERROR}Branch {error_bold}{branch}{error_bold:#} already exists{ERROR:#}"
- );
- eprintln!();
- eprintln!("{HINT_EMOJI} {HINT}Remove --create flag to switch to it{HINT:#}");
- return Err(GitError::CommandFailed(String::new()));
+ return Err(GitError::BranchAlreadyExists {
+ branch: branch.to_string(),
+ });
}
// Check if base flag was provided without create flag
@@ -178,13 +174,9 @@ pub fn handle_switch(
return Ok(SwitchResult::ExistingWorktree(canonical_existing_path));
}
Some(_) => {
- let error_bold = ERROR.bold();
- eprintln!(
- "{ERROR_EMOJI} {ERROR}Worktree directory missing for {error_bold}{branch}{error_bold:#}{ERROR:#}"
- );
- eprintln!();
- eprintln!("{HINT_EMOJI} {HINT}Run 'git worktree prune' to clean up{HINT:#}");
- return Err(GitError::CommandFailed(String::new()));
+ return Err(GitError::WorktreeMissing {
+ branch: branch.to_string(),
+ });
}
None => {}
}
@@ -298,23 +290,17 @@ fn remove_worktree_by_name(repo: &Repository, branch_name: &str) -> Result<Remov
let worktree_path = match worktree_path {
Some(path) => path,
None => {
- let error_bold = ERROR.bold();
- eprintln!(
- "{ERROR_EMOJI} {ERROR}No worktree found for branch {error_bold}{branch_name}{error_bold:#}{ERROR:#}"
- );
- return Err(GitError::CommandFailed(String::new()));
+ return Err(GitError::NoWorktreeFound {
+ branch: branch_name.to_string(),
+ });
}
};
// Check if the target worktree exists on disk
if !worktree_path.exists() {
- let error_bold = ERROR.bold();
- eprintln!(
- "{ERROR_EMOJI} {ERROR}Worktree directory missing for {error_bold}{branch_name}{error_bold:#}{ERROR:#}"
- );
- eprintln!();
- eprintln!("{HINT_EMOJI} {HINT}Run 'git worktree prune' to clean up{HINT:#}");
- return Err(GitError::CommandFailed(String::new()));
+ return Err(GitError::WorktreeMissing {
+ branch: branch_name.to_string(),
+ });
}
// Check if the target worktree is clean (no uncommitted changes)
@@ -390,18 +376,10 @@ fn check_worktree_conflicts(
.collect();
if !overlapping.is_empty() {
- eprintln!("{ERROR_EMOJI} {ERROR}Cannot push: conflicting uncommitted changes in:{ERROR:#}");
- eprintln!();
- let dim = AnstyleStyle::new().dimmed();
- for file in &overlapping {
- eprintln!("{dim}•{dim:#} {}", file);
- }
- eprintln!();
- eprintln!(
- "{HINT_EMOJI} {HINT}Commit or stash these changes in {} first{HINT:#}",
- wt_path.display()
- );
- return Err(GitError::CommandFailed(String::new()));
+ return Err(GitError::ConflictingChanges {
+ files: overlapping,
+ worktree_path: wt_path.to_path_buf(),
+ });
}
Ok(())
@@ -544,26 +522,14 @@ pub fn handle_push(target: Option<&str>, allow_merge_commits: bool) -> Result<()
// Check if it's a fast-forward
if !repo.is_ancestor(&target_branch, "HEAD")? {
- let error_bold = ERROR.bold();
- eprintln!(
- "{ERROR_EMOJI} {ERROR}Not a fast-forward from {error_bold}{target_branch}{error_bold:#} to HEAD{ERROR:#}"
- );
- eprintln!();
- eprintln!(
- "{HINT_EMOJI} {HINT}The target branch has commits not in your current branch{HINT:#}"
- );
- eprintln!("{HINT_EMOJI} {HINT}Consider: git pull or git rebase{HINT:#}");
- return Err(GitError::CommandFailed(String::new()));
+ return Err(GitError::NotFastForward {
+ target_branch: target_branch.to_string(),
+ });
}
// Check for merge commits unless allowed
if !allow_merge_commits && repo.has_merge_commits(&target_branch, "HEAD")? {
- eprintln!("{ERROR_EMOJI} {ERROR}Found merge commits in push range{ERROR:#}");
- eprintln!();
- eprintln!(
- "{HINT_EMOJI} {HINT}Use --allow-merge-commits to push non-linear history{HINT:#}"
- );
- return Err(GitError::CommandFailed(String::new()));
+ return Err(GitError::MergeCommitsFound);
}
// Configure receive.denyCurrentBranch if needed
@@ -633,8 +599,8 @@ pub fn handle_push(target: Option<&str>, allow_merge_commits: bool) -> Result<()
// Perform the push
let push_target = format!("HEAD:{}", target_branch);
repo.run_command(&["push", git_common_dir.to_str().unwrap(), &push_target])
- .map_err(|e| {
- GitError::CommandFailed(format!("{ERROR_EMOJI} {ERROR}Push failed: {e}{ERROR:#}"))
+ .map_err(|e| GitError::PushFailed {
+ error: e.to_string(),
})?;
// Build success message with statistics
diff --git a/src/git.rs b/src/git.rs
index 33c6c0b83..661e488a9 100644
--- a/src/git.rs
+++ b/src/git.rs
@@ -14,20 +14,170 @@ pub struct Worktree {
#[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,
+ /// Working tree has staged changes but no commits
+ StagedChangesWithoutCommits,
+ /// Pre-merge check failed
+ PreMergeCheckFailed { check_name: String, error: String },
+ /// 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 },
+ /// Cannot push due to conflicting uncommitted changes
+ ConflictingChanges {
+ files: Vec<String>,
+ worktree_path: PathBuf,
+ },
+ /// Push is not a fast-forward
+ NotFastForward { target_branch: String },
+ /// Found merge commits in push range
+ MergeCommitsFound,
+ /// Command was not approved by user
+ CommandNotApproved,
+ /// Push operation failed
+ PushFailed { error: String },
}
impl std::fmt::Display for GitError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ use crate::styling::{ERROR, ERROR_EMOJI, HINT, HINT_EMOJI};
+
match self {
- // CommandFailed messages are already formatted with emoji and colors
+ // Plain message that will be displayed by main.rs
GitError::CommandFailed(msg) => write!(f, "{}", msg),
+
// ParseError messages need formatting
GitError::ParseError(msg) => {
- use crate::styling::{ERROR, ERROR_EMOJI};
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:#}"
+ )
+ }
+
+ // Staged changes without commits
+ GitError::StagedChangesWithoutCommits => {
+ write!(
+ f,
+ "{ERROR_EMOJI} {ERROR}Staged changes without commits{ERROR:#}\n\n{HINT_EMOJI} {HINT}Please commit them first{HINT:#}"
+ )
+ }
+
+ // Pre-merge check failed
+ GitError::PreMergeCheckFailed { check_name, error } => {
+ let error_bold = ERROR.bold();
+ write!(
+ f,
+ "{ERROR_EMOJI} {ERROR}Pre-merge check failed: {error_bold}{check_name}{error_bold:#}{ERROR:#}\n\n{error}\n\n{HINT_EMOJI} {HINT}Use --no-verify to skip pre-merge checks{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 } => {
+ let error_bold = ERROR.bold();
+ write!(
+ f,
+ "{ERROR_EMOJI} {ERROR}Branch {error_bold}{branch}{error_bold:#} already exists{ERROR:#}\n\n{HINT_EMOJI} {HINT}Remove --create flag to switch to it{HINT:#}"
+ )
+ }
+
+ // Worktree missing
+ GitError::WorktreeMissing { branch } => {
+ let error_bold = ERROR.bold();
+ 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:#}"
+ )
+ }
+
+ // No worktree found
+ GitError::NoWorktreeFound { branch } => {
+ let error_bold = ERROR.bold();
+ write!(
+ f,
+ "{ERROR_EMOJI} {ERROR}No worktree found for branch {error_bold}{branch}{error_bold:#}{ERROR:#}"
+ )
+ }
+
+ // Conflicting changes
+ GitError::ConflictingChanges {
+ files,
+ worktree_path,
+ } => {
+ use crate::styling::AnstyleStyle;
+ let dim = AnstyleStyle::new().dimmed();
+
+ write!(
+ f,
+ "{ERROR_EMOJI} {ERROR}Cannot push: conflicting uncommitted changes in:{ERROR:#}\n\n"
+ )?;
+ for file in files {
+ writeln!(f, "{dim}•{dim:#} {file}")?;
+ }
+ write!(
+ f,
+ "\n{HINT_EMOJI} {HINT}Commit or stash these changes in {} first{HINT:#}",
+ worktree_path.display()
+ )
+ }
+
+ // Not fast-forward
+ GitError::NotFastForward { target_branch } => {
+ let error_bold = ERROR.bold();
+ write!(
+ f,
+ "{ERROR_EMOJI} {ERROR}Not a fast-forward from {error_bold}{target_branch}{error_bold:#} to HEAD{ERROR:#}\n\n{HINT_EMOJI} {HINT}The target branch has commits not in your current branch{HINT:#}\n{HINT_EMOJI} {HINT}Consider: git pull or git rebase{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:#}"
+ )
+ }
+
+ // Command not approved
+ GitError::CommandNotApproved => {
+ Ok(()) // on_skip callback handles the printing
+ }
+
+ // Push failed
+ GitError::PushFailed { error } => {
+ write!(f, "{ERROR_EMOJI} {ERROR}Push failed: {error}{ERROR:#}")
+ }
}
}
}
@@ -184,11 +334,7 @@ impl Repository {
/// Returns an error if there are uncommitted changes.
pub fn ensure_clean_working_tree(&self) -> Result<(), GitError> {
if self.is_dirty()? {
- use crate::styling::{ERROR, ERROR_EMOJI, HINT, HINT_EMOJI, eprintln};
- eprintln!("{ERROR_EMOJI} {ERROR}Working tree has uncommitted changes{ERROR:#}");
- eprintln!();
- eprintln!("{HINT_EMOJI} {HINT}Commit or stash them first{HINT:#}");
- return Err(GitError::CommandFailed(String::new()));
+ return Err(GitError::UncommittedChanges);
}
Ok(())
}
diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rs
index bf86b775b..5cacb41d2 100644
--- a/tests/integration_tests/merge.rs
+++ b/tests/integration_tests/merge.rs
@@ -141,6 +141,46 @@ fn test_merge_dirty_working_tree() {
);
}
+#[test]
+fn test_merge_dirty_working_tree_error_message() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+ repo.setup_remote("main");
+
+ // Create a feature worktree with uncommitted changes (untracked file)
+ let feature_wt = repo.add_worktree("feature", "feature");
+ std::fs::write(feature_wt.join("untracked.txt"), "uncommitted content")
+ .expect("Failed to write file");
+
+ // Run merge command and capture output
+ let mut cmd = make_snapshot_cmd(&repo, "merge", &["main"], Some(&feature_wt));
+ let output = cmd.output().expect("Failed to run command");
+
+ // Should fail with exit code 1
+ assert!(!output.status.success(), "Command should fail");
+
+ // Convert stderr to string
+ let stderr = String::from_utf8_lossy(&output.stderr);
+
+ // CRITICAL: Error message must appear (styled with emoji/color)
+ // Before the fix, this would fail silently with no error message
+ // After the fix, structured errors are formatted in ONE canonical location (GitError::Display)
+ // and printed by main.rs (the only place that prints errors)
+ assert!(
+ stderr.contains("Working tree has untracked files"),
+ "Error output must contain the error message. Got stderr:\n{}",
+ stderr
+ );
+
+ // Verify we see the error exactly once (not duplicated)
+ let error_count = stderr.matches("Working tree has untracked files").count();
+ assert_eq!(
+ error_count, 1,
+ "Should see error message exactly once from main.rs via GitError::Display. Got {} occurrences",
+ error_count
+ );
+}
+
#[test]
fn test_merge_not_fast_forward() {
let mut repo = TestRepo::new();
diff --git a/tests/snapshots/integration__integration_tests__merge__merge_dirty_working_tree.snap b/tests/snapshots/integration__integration_tests__merge__merge_dirty_working_tree.snap
index 9279f6a70..bf72b98b5 100644
--- a/tests/snapshots/integration__integration_tests__merge__merge_dirty_working_tree.snap
+++ b/tests/snapshots/integration__integration_tests__merge__merge_dirty_working_tree.snap
@@ -14,7 +14,8 @@ info:
GIT_EDITOR: ""
LANG: C
LC_ALL: C
- SOURCE_DATE_EPOCH: "1704067200"
+ SOURCE_DATE_EPOCH: "1761609600"
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpDd1Xdj/test-config.toml
---
success: false
exit_code: 1
diff --git a/tests/snapshots/integration__integration_tests__merge__merge_error_detached_head.snap b/tests/snapshots/integration__integration_tests__merge__merge_error_detached_head.snap
index 636a6ab54..d8a066956 100644
--- a/tests/snapshots/integration__integration_tests__merge__merge_error_detached_head.snap
+++ b/tests/snapshots/integration__integration_tests__merge__merge_error_detached_head.snap
@@ -14,7 +14,8 @@ info:
GIT_EDITOR: ""
LANG: C
LC_ALL: C
- SOURCE_DATE_EPOCH: "1704067200"
+ SOURCE_DATE_EPOCH: "1761609600"
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpk3qSF0/test-config.toml
---
success: false
exit_code: 1
diff --git a/tests/snapshots/integration__integration_tests__merge__merge_pre_merge_check_failure.snap b/tests/snapshots/integration__integration_tests__merge__merge_pre_merge_check_failure.snap
index 309d6e35e..eddfd4cb0 100644
--- a/tests/snapshots/integration__integration_tests__merge__merge_pre_merge_check_failure.snap
+++ b/tests/snapshots/integration__integration_tests__merge__merge_pre_merge_check_failure.snap
@@ -16,7 +16,7 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpTsXvBu/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpMDyE2F/test-config.toml
---
success: false
exit_code: 1
@@ -25,7 +25,6 @@ exit_code: 1
----- stderr -----
🔄 Running pre-merge check 'cmd':
  exit 1
-
❌ Pre-merge check failed: cmd
Command failed with exit code: exit status: 1