Skip to content

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

feat: Add context to uncommitted changes errors

Maximilian Roos8e8f4946a0ab
diff --git a/src/commands/config.rs b/src/commands/config.rs
index 94bf0c387..651ddbaeb 100644
--- a/src/commands/config.rs
+++ b/src/commands/config.rs
@@ -1,7 +1,7 @@
use anyhow::Context;
use etcetera::base_strategy::{BaseStrategy, choose_base_strategy};
use std::path::PathBuf;
-use worktrunk::git::{Repository, detached_head};
+use worktrunk::git::Repository;
use worktrunk::path::format_path_for_display;
use worktrunk::shell::Shell;
use worktrunk::styling::{AnstyleStyle, CYAN, GREEN, GREEN_BOLD, format_toml};
@@ -352,9 +352,7 @@ pub fn handle_config_status_set(value: String, branch: Option<String>) -> anyhow
let branch_name = match branch {
Some(b) => b,
- None => repo
- .current_branch()?
- .ok_or_else(|| anyhow::anyhow!("{}", detached_head()))?,
+ None => repo.require_current_branch("set status for current branch")?,
};
let config_key = format!("worktrunk.status.{}", branch_name);
@@ -397,8 +395,7 @@ pub fn handle_config_status_unset(target: String) -> anyhow::Result<()> {
} else {
// Clear specific branch status
let branch_name = if target.is_empty() {
- repo.current_branch()?
- .ok_or_else(|| anyhow::anyhow!("{}", detached_head()))?
+ repo.require_current_branch("clear status for current branch")?
} else {
target
};
diff --git a/src/commands/context.rs b/src/commands/context.rs
index f00a368d9..debde966b 100644
--- a/src/commands/context.rs
+++ b/src/commands/context.rs
@@ -1,7 +1,7 @@
use anyhow::Context;
use std::path::PathBuf;
use worktrunk::config::WorktrunkConfig;
-use worktrunk::git::{Repository, detached_head};
+use worktrunk::git::Repository;
use super::command_executor::CommandContext;
@@ -24,15 +24,15 @@ pub struct CommandEnv {
}
impl CommandEnv {
- /// Load the command environment from the current process context.
- pub fn current() -> anyhow::Result<Self> {
+ /// Load the command environment for a specific action.
+ ///
+ /// `action` describes what command is running (e.g., "merge", "squash").
+ /// Used in error messages when the environment can't be loaded.
+ pub fn for_action(action: &str) -> anyhow::Result<Self> {
let repo = Repository::current();
let worktree_path = std::env::current_dir()
.map_err(|e| anyhow::anyhow!("Failed to get current directory: {}", e))?;
- let branch = repo
- .current_branch()
- .context("Failed to get current branch")?
- .ok_or_else(|| anyhow::anyhow!("{}", detached_head()))?;
+ let branch = repo.require_current_branch(action)?;
let config = WorktrunkConfig::load().context("Failed to load config")?;
let repo_root = repo.worktree_base()?;
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index 53e193e74..6174d4906 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -68,14 +68,17 @@ pub fn handle_merge(
force: bool,
stage_mode: super::commit::StageMode,
) -> anyhow::Result<()> {
- let env = CommandEnv::current()?;
+ let env = CommandEnv::for_action("merge")?;
let repo = &env.repo;
let config = &env.config;
let current_branch = env.branch.clone();
// Validate --no-commit: requires clean working tree
if !commit && repo.is_dirty()? {
- return Err(anyhow::anyhow!("{}", worktrunk::git::uncommitted_changes()));
+ return Err(anyhow::anyhow!(
+ "{}",
+ worktrunk::git::uncommitted_changes(Some("merge with --no-commit"))
+ ));
}
// Validate --no-commit flag compatibility
@@ -181,7 +184,7 @@ pub fn handle_merge(
if remove_effective {
// STEP 1: Check for uncommitted changes before attempting cleanup
// This prevents showing "Cleaning up worktree..." before failing
- repo.ensure_clean_working_tree()?;
+ repo.ensure_clean_working_tree(Some("remove worktree after merge"))?;
// STEP 2: Remove worktree via shared remove output handler so final message matches wt remove
let worktree_root = repo.worktree_root()?;
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rs
index ff2199914..363a6d1dc 100644
--- a/src/commands/repository_ext.rs
+++ b/src/commands/repository_ext.rs
@@ -89,7 +89,7 @@ impl RepositoryCliExt for Repository {
}
let target_repo = Repository::at(&worktree_path);
- target_repo.ensure_clean_working_tree()?;
+ target_repo.ensure_clean_working_tree(Some("remove worktree"))?;
let current_worktree = self.worktree_root()?;
let removing_current = current_worktree == worktree_path;
diff --git a/src/commands/standalone.rs b/src/commands/standalone.rs
index 46703b4e5..82fd708c5 100644
--- a/src/commands/standalone.rs
+++ b/src/commands/standalone.rs
@@ -13,7 +13,7 @@ use super::repository_ext::RepositoryCliExt;
/// Handle `wt step hook` command
pub fn handle_standalone_run_hook(hook_type: HookType, force: bool) -> anyhow::Result<()> {
// Derive context from current environment
- let env = CommandEnv::current()?;
+ let env = CommandEnv::for_action(&format!("run {hook_type} hook"))?;
let repo = &env.repo;
let ctx = env.context(force);
@@ -65,7 +65,7 @@ pub fn handle_standalone_commit(
no_verify: bool,
stage_mode: super::commit::StageMode,
) -> anyhow::Result<()> {
- let env = CommandEnv::current()?;
+ let env = CommandEnv::for_action("commit")?;
let ctx = env.context(force);
let mut options = CommitOptions::new(&ctx);
options.no_verify = no_verify;
@@ -94,7 +94,7 @@ pub fn handle_squash(
) -> anyhow::Result<bool> {
use super::commit::StageMode;
- let env = CommandEnv::current()?;
+ let env = CommandEnv::for_action("squash")?;
let repo = &env.repo;
let current_branch = env.branch.clone();
let ctx = env.context(force);
diff --git a/src/git/error.rs b/src/git/error.rs
index 615bcf6d9..c24a9ca3e 100644
--- a/src/git/error.rs
+++ b/src/git/error.rs
@@ -101,16 +101,28 @@ pub fn parse_error(msg: impl std::fmt::Display) -> anyhow::Error {
}
/// Detached HEAD error
-pub fn detached_head() -> anyhow::Error {
+///
+/// `action` describes what was blocked (e.g., "merge")
+pub fn detached_head(action: Option<&str>) -> anyhow::Error {
+ let message = match action {
+ Some(action) => format!("Cannot {action}: not on a branch (detached HEAD)"),
+ None => "Not on a branch (detached HEAD)".to_string(),
+ };
anyhow::anyhow!(
- "{ERROR_EMOJI} {ERROR}Not on a branch (detached HEAD){ERROR:#}\n\n{HINT_EMOJI} {HINT}You are in detached HEAD state{HINT:#}"
+ "{ERROR_EMOJI} {ERROR}{message}{ERROR:#}\n\n{HINT_EMOJI} {HINT}Switch to a branch first with 'git switch <branch>'{HINT:#}"
)
}
/// Uncommitted changes error
-pub fn uncommitted_changes() -> anyhow::Error {
+///
+/// `action` describes what was blocked (e.g., "remove worktree")
+pub fn uncommitted_changes(action: Option<&str>) -> anyhow::Error {
+ let message = match action {
+ Some(action) => format!("Cannot {action}: working tree has uncommitted changes"),
+ None => "Working tree has uncommitted changes".to_string(),
+ };
anyhow::anyhow!(
- "{ERROR_EMOJI} {ERROR}Working tree has uncommitted changes{ERROR:#}\n\n{HINT_EMOJI} {HINT}Commit or stash them first{HINT:#}"
+ "{ERROR_EMOJI} {ERROR}{message}{ERROR:#}\n\n{HINT_EMOJI} {HINT}Commit or stash them first{HINT:#}"
)
}
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index 326b3714d..605bd247f 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -178,6 +178,14 @@ impl Repository {
}
}
+ /// Get the current branch name, or error if in detached HEAD state.
+ ///
+ /// `action` describes what requires being on a branch (e.g., "merge").
+ pub fn require_current_branch(&self, action: &str) -> anyhow::Result<String> {
+ self.current_branch()?
+ .ok_or_else(|| detached_head(Some(action)))
+ }
+
/// Read a user-defined status from `worktrunk.status.<branch>` in git config.
pub fn branch_keyed_status(&self, branch: &str) -> Option<String> {
let config_key = format!("worktrunk.status.{}", branch);
@@ -249,9 +257,9 @@ impl Repository {
/// - `Err` if "-" but no previous branch in history
pub fn resolve_worktree_name(&self, name: &str) -> anyhow::Result<String> {
match name {
- "@" => self
- .current_branch()?
- .ok_or_else(|| anyhow::anyhow!("{}", detached_head())),
+ "@" => self.current_branch()?.ok_or_else(|| {
+ anyhow::anyhow!("{}", detached_head(Some("resolve '@' to current branch")))
+ }),
"-" => {
// Read from worktrunk.history (recorded by wt switch operations)
// History stores (current, previous), we want previous
@@ -417,9 +425,10 @@ 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) -> anyhow::Result<()> {
+ /// `action` describes what was blocked (e.g., "remove worktree").
+ pub fn ensure_clean_working_tree(&self, action: Option<&str>) -> anyhow::Result<()> {
if self.is_dirty()? {
- return Err(uncommitted_changes());
+ return Err(uncommitted_changes(action));
}
Ok(())
}
diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rs
index 8581e468d..95bd41496 100644
--- a/tests/integration_tests/merge.rs
+++ b/tests/integration_tests/merge.rs
@@ -2277,7 +2277,7 @@ fn test_merge_no_commit_with_dirty_tree() {
success: false
exit_code: 1
----- stdout -----
- ❌ Working tree has uncommitted changes
+ ❌ Cannot merge with --no-commit: working tree has uncommitted changes
πŸ’‘ Commit or stash them first
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 392582820..0d32fca47 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
@@ -21,8 +21,8 @@ info:
success: false
exit_code: 1
----- stdout -----
-❌ Not on a branch (detached HEAD)
+❌ Cannot merge: not on a branch (detached HEAD)
-πŸ’‘ You are in detached HEAD state
+πŸ’‘ Switch to a branch first with 'git switch <branch>'
----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__remove__remove_by_name_dirty_target.snap b/tests/snapshots/integration__integration_tests__remove__remove_by_name_dirty_target.snap
index 26610c532..6215d97f8 100644
--- a/tests/snapshots/integration__integration_tests__remove__remove_by_name_dirty_target.snap
+++ b/tests/snapshots/integration__integration_tests__remove__remove_by_name_dirty_target.snap
@@ -21,7 +21,7 @@ info:
success: false
exit_code: 1
----- stdout -----
-❌ Working tree has uncommitted changes
+❌ Cannot remove worktree: working tree has uncommitted changes
πŸ’‘ Commit or stash them first
diff --git a/tests/snapshots/integration__integration_tests__remove__remove_dirty_working_tree.snap b/tests/snapshots/integration__integration_tests__remove__remove_dirty_working_tree.snap
index 7d92ecf43..6dbfa7bda 100644
--- a/tests/snapshots/integration__integration_tests__remove__remove_dirty_working_tree.snap
+++ b/tests/snapshots/integration__integration_tests__remove__remove_dirty_working_tree.snap
@@ -20,7 +20,7 @@ info:
success: false
exit_code: 1
----- stdout -----
-❌ Working tree has uncommitted changes
+❌ Cannot remove worktree: working tree has uncommitted changes
πŸ’‘ Commit or stash them first