Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Add ResolutionContext for worktree removal path checks
Maximilian Roos47f9da221113
diff --git a/src/commands/mod.rs b/src/commands/mod.rsindex 9e8e8a1d1..055d3a7df 100644--- a/src/commands/mod.rs+++ b/src/commands/mod.rs@@ -37,8 +37,9 @@ pub use standalone::{handle_squash, run_hook, step_commit, step_show_squash_prompt,};pub use worktree::{- compute_worktree_path, handle_remove, handle_remove_by_path, handle_remove_current,- handle_switch, is_worktree_at_expected_path, resolve_worktree_arg, worktree_display_name,+ ResolutionContext, compute_worktree_path, handle_remove, handle_remove_by_path,+ handle_remove_current, handle_switch, is_worktree_at_expected_path, resolve_worktree_arg,+ worktree_display_name,};// Re-export Shell from the canonical locationdiff --git a/src/commands/worktree.rs b/src/commands/worktree.rsindex 91b94515b..41b0a1979 100644--- a/src/commands/worktree.rs+++ b/src/commands/worktree.rs@@ -126,6 +126,17 @@ use super::command_executor::CommandContext;use super::hooks::{HookFailureStrategy, HookPipeline, HookSource};use super::repository_ext::RepositoryCliExt;+/// Context for worktree resolution - determines which checks are performed.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum ResolutionContext {+ /// Creating or switching to a worktree - path occupation is an error+ /// because we need to create a worktree at the expected path.+ CreateOrSwitch,+ /// Removing a worktree - we only care if the branch has a worktree,+ /// path occupation is irrelevant since we're not creating anything.+ Remove,+}+/// Resolve a worktree argument using branch-first lookup.////// Resolution order:@@ -134,12 +145,16 @@ use super::repository_ext::RepositoryCliExt;/// 3. If branch has a worktree, return it/// 4. Otherwise, return branch-only (no worktree)///-/// If the branch has no worktree but expected path is occupied by another-/// branch's worktree, an error is raised.+/// For `CreateOrSwitch` context: If the branch has no worktree but expected+/// path is occupied by another branch's worktree, an error is raised.+///+/// For `Remove` context: Path occupation is ignored since we're not creating+/// a worktree - we just return `BranchOnly` if no worktree exists.pub fn resolve_worktree_arg(repo: &Repository,name: &str,config: &WorktrunkConfig,+ context: ResolutionContext,) -> anyhow::Result<ResolvedWorktree> {// Special symbolsmatch name {@@ -172,19 +187,21 @@ pub fn resolve_worktree_arg(});}- // No worktree for branch - check if expected path is occupied- let expected_path = compute_worktree_path(repo, name, config)?;- if let Some((_, occupant_branch)) = repo.worktree_at_path(&expected_path)? {- // Path is occupied by a different branch's worktree- return Err(GitError::WorktreePathOccupied {- branch,- path: expected_path,- occupant: occupant_branch,+ // No worktree for branch - check if expected path is occupied (only for create/switch)+ if context == ResolutionContext::CreateOrSwitch {+ let expected_path = compute_worktree_path(repo, name, config)?;+ if let Some((_, occupant_branch)) = repo.worktree_at_path(&expected_path)? {+ // Path is occupied by a different branch's worktree+ return Err(GitError::WorktreePathOccupied {+ branch,+ path: expected_path,+ occupant: occupant_branch,+ }+ .into());}- .into());}- // No worktree for branch or at expected path+ // No worktree for branch (and path not occupied, or we don't care about path)Ok(ResolvedWorktree::BranchOnly { branch })}diff --git a/src/git/error.rs b/src/git/error.rsindex 0c82a8812..941c5a15c 100644--- a/src/git/error.rs+++ b/src/git/error.rs@@ -629,7 +629,8 @@ impl std::error::Error for HookErrorWithHint {}/// Format an error with header and gutter content-fn format_error_block(header: String, error: &str) -> String {+fn format_error_block(header: impl Into<String>, error: &str) -> String {+ let header = header.into();let trimmed = error.trim();if trimmed.is_empty() {headerdiff --git a/src/main.rs b/src/main.rsindex 7412ecd47..cfcc34ab9 100644--- a/src/main.rs+++ b/src/main.rs@@ -27,13 +27,13 @@ use commands::command_executor::CommandContext;use commands::handle_select;use commands::worktree::{SwitchResult, handle_push};use commands::{- ConfigAction, MergeOptions, RebaseResult, SquashResult, add_approvals, approve_hooks,- clear_approvals, compute_worktree_path, handle_config_create, handle_config_show,- handle_configure_shell, handle_hook_show, handle_init, handle_list, handle_merge,- handle_rebase, handle_remove, handle_remove_by_path, handle_remove_current, handle_show_theme,- handle_squash, handle_state_clear, handle_state_clear_all, handle_state_get, handle_state_set,- handle_state_show, handle_switch, handle_unconfigure_shell, resolve_worktree_arg, run_hook,- step_commit, step_for_each,+ ConfigAction, MergeOptions, RebaseResult, ResolutionContext, SquashResult, add_approvals,+ approve_hooks, clear_approvals, compute_worktree_path, handle_config_create,+ handle_config_show, handle_configure_shell, handle_hook_show, handle_init, handle_list,+ handle_merge, handle_rebase, handle_remove, handle_remove_by_path, handle_remove_current,+ handle_show_theme, handle_squash, handle_state_clear, handle_state_clear_all, handle_state_get,+ handle_state_set, handle_state_show, handle_switch, handle_unconfigure_shell,+ resolve_worktree_arg, run_hook, step_commit, step_for_each,};use output::{execute_user_command, handle_remove_output, handle_switch_output};@@ -1330,7 +1330,12 @@ fn main() {let mut errors: Vec<anyhow::Error> = Vec::new();for worktree_name in &worktrees {- match resolve_worktree_arg(&repo, worktree_name, &config) {+ match resolve_worktree_arg(+ &repo,+ worktree_name,+ &config,+ ResolutionContext::Remove,+ ) {Ok(ResolvedWorktree::Worktree { path, branch }) => {if Some(&path) == current_worktree.as_ref() {current = Some((path, branch));@@ -1351,7 +1356,8 @@ fn main() {// (resolution errors are fatal - we can't proceed with unknown names)if !errors.is_empty() {for e in &errors {- output::print(error_message(e.to_string()))?;+ // GitError variants already include emoji via error_message() in Display+ output::print(e.to_string())?;}anyhow::bail!("Failed to resolve {} of {} specified names",diff --git a/src/styling/constants.rs b/src/styling/constants.rsindex 7623a23b2..1fc7452cd 100644--- a/src/styling/constants.rs+++ b/src/styling/constants.rs@@ -79,6 +79,75 @@ pub const INFO_EMOJI: &str = "⚪";/// `eprint!("{PROMPT_EMOJI} Proceed? [y/N] ")`pub const PROMPT_EMOJI: &str = "❓";+// ============================================================================+// Formatted Message Type+// ============================================================================++use std::fmt;++/// A message that has already been formatted with emoji and styling.+///+/// This type provides compile-time prevention of double-formatting. Message+/// functions like `error_message()` take `impl AsRef<str>` and return+/// `FormattedMessage`. Since `FormattedMessage` does NOT implement `AsRef<str>`,+/// passing it to a message function is a compile error.+///+/// # Type Safety+///+/// ```compile_fail+/// use worktrunk::styling::{error_message, FormattedMessage};+///+/// let msg = error_message("first error");+/// // This won't compile - FormattedMessage doesn't implement AsRef<str>+/// let double = error_message(msg);+/// ```+///+/// # Usage+///+/// ```+/// use worktrunk::styling::error_message;+///+/// let msg = error_message("Something went wrong");+/// println!("{}", msg); // Uses Display+/// ```+#[derive(Debug, Clone)]+pub struct FormattedMessage(String);++impl FormattedMessage {+ /// Create a formatted message from a pre-formatted string.+ ///+ /// Use this when implementing `Into<FormattedMessage>` for error types+ /// that format themselves (like `GitError`).+ pub fn new(content: String) -> Self {+ Self(content)+ }++ /// Get the inner string for output.+ pub fn into_inner(self) -> String {+ self.0+ }++ /// Borrow the inner string for inspection (e.g., in tests).+ ///+ /// Note: This does NOT implement `AsRef<str>` to prevent accidentally+ /// passing a `FormattedMessage` to message functions like `error_message()`.+ pub fn as_str(&self) -> &str {+ &self.0+ }+}++impl fmt::Display for FormattedMessage {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ write!(f, "{}", self.0)+ }+}++impl From<FormattedMessage> for String {+ fn from(msg: FormattedMessage) -> String {+ msg.0+ }+}+// ============================================================================// Message Formatting Functions// ============================================================================@@ -86,6 +155,9 @@ pub const PROMPT_EMOJI: &str = "❓";// These functions provide the canonical formatting for each message type.// Used by both the output system (output::error, etc.) and Display impls// (GitError, WorktrunkError) to ensure consistent styling.+//+// All functions take `impl AsRef<str>` (which FormattedMessage does NOT+// implement) and return `FormattedMessage`, preventing double-formatting.use color_print::cformat;@@ -99,33 +171,33 @@ use color_print::cformat;/// let name = "feature";/// println!("{}", error_message(cformat!("Branch <bold>{name}</> not found")));/// ```-pub fn error_message(content: impl AsRef<str>) -> String {- cformat!("{ERROR_EMOJI} <red>{}</>", content.as_ref())+pub fn error_message(content: impl AsRef<str>) -> FormattedMessage {+ FormattedMessage(cformat!("{ERROR_EMOJI} <red>{}</>", content.as_ref()))}/// Format a hint message with emoji and dim styling-pub fn hint_message(content: impl AsRef<str>) -> String {- cformat!("{HINT_EMOJI} <dim>{}</>", content.as_ref())+pub fn hint_message(content: impl AsRef<str>) -> FormattedMessage {+ FormattedMessage(cformat!("{HINT_EMOJI} <dim>{}</>", content.as_ref()))}/// Format a warning message with emoji and yellow styling-pub fn warning_message(content: impl AsRef<str>) -> String {- cformat!("{WARNING_EMOJI} <yellow>{}</>", content.as_ref())+pub fn warning_message(content: impl AsRef<str>) -> FormattedMessage {+ FormattedMessage(cformat!("{WARNING_EMOJI} <yellow>{}</>", content.as_ref()))}/// Format a success message with emoji and green styling-pub fn success_message(content: impl AsRef<str>) -> String {- cformat!("{SUCCESS_EMOJI} <green>{}</>", content.as_ref())+pub fn success_message(content: impl AsRef<str>) -> FormattedMessage {+ FormattedMessage(cformat!("{SUCCESS_EMOJI} <green>{}</>", content.as_ref()))}/// Format a progress message with emoji and cyan styling-pub fn progress_message(content: impl AsRef<str>) -> String {- cformat!("{PROGRESS_EMOJI} <cyan>{}</>", content.as_ref())+pub fn progress_message(content: impl AsRef<str>) -> FormattedMessage {+ FormattedMessage(cformat!("{PROGRESS_EMOJI} <cyan>{}</>", content.as_ref()))}/// Format an info message with emoji (no color - neutral status)-pub fn info_message(content: impl AsRef<str>) -> String {- cformat!("{INFO_EMOJI} {}", content.as_ref())+pub fn info_message(content: impl AsRef<str>) -> FormattedMessage {+ FormattedMessage(cformat!("{INFO_EMOJI} {}", content.as_ref()))}/// Format a section heading (cyan uppercase text, no emoji)@@ -205,52 +277,52 @@ mod tests {#[test]fn test_error_message() {let msg = error_message("Something went wrong");- assert!(msg.contains("❌"));- assert!(msg.contains("Something went wrong"));+ assert!(msg.as_str().contains("❌"));+ assert!(msg.as_str().contains("Something went wrong"));}#[test]fn test_error_message_with_inner_styling() {let name = "feature";let msg = error_message(cformat!("Branch <bold>{name}</> not found"));- assert!(msg.contains("❌"));- assert!(msg.contains("Branch"));- assert!(msg.contains("feature"));+ assert!(msg.as_str().contains("❌"));+ assert!(msg.as_str().contains("Branch"));+ assert!(msg.as_str().contains("feature"));}#[test]fn test_hint_message() {let msg = hint_message("Try running --help");- assert!(msg.contains("💡"));- assert!(msg.contains("Try running --help"));+ assert!(msg.as_str().contains("💡"));+ assert!(msg.as_str().contains("Try running --help"));}#[test]fn test_warning_message() {let msg = warning_message("Deprecated option");- assert!(msg.contains("🟡"));- assert!(msg.contains("Deprecated option"));+ assert!(msg.as_str().contains("🟡"));+ assert!(msg.as_str().contains("Deprecated option"));}#[test]fn test_success_message() {let msg = success_message("Operation completed");- assert!(msg.contains("✅"));- assert!(msg.contains("Operation completed"));+ assert!(msg.as_str().contains("✅"));+ assert!(msg.as_str().contains("Operation completed"));}#[test]fn test_progress_message() {let msg = progress_message("Loading data...");- assert!(msg.contains("🔄"));- assert!(msg.contains("Loading data..."));+ assert!(msg.as_str().contains("🔄"));+ assert!(msg.as_str().contains("Loading data..."));}#[test]fn test_info_message() {let msg = info_message("5 items found");- assert!(msg.contains("⚪"));- assert!(msg.contains("5 items found"));+ assert!(msg.as_str().contains("⚪"));+ assert!(msg.as_str().contains("5 items found"));}// ============================================================================diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rsindex 4fdeb0ea6..1f87294f6 100644--- a/tests/integration_tests/remove.rs+++ b/tests/integration_tests/remove.rs@@ -120,6 +120,69 @@ fn test_remove_nonexistent_worktree(repo: TestRepo) {snapshot_remove("remove_nonexistent_worktree", &repo, &["nonexistent"], None);}+/// Test removing a branch that exists but has no worktree, when expected path is occupied.+///+/// Regression test for bug where `wt remove npm` would show "Cannot create worktree for npm"+/// when the expected path was occupied. The fix uses `ResolutionContext::Remove` which skips+/// the path occupation check entirely, correctly treating this as a branch-only removal.+///+/// Setup:+/// - Branch `npm` exists but has no worktree+/// - The expected path for `npm` (repo.npm) is occupied by a different branch's worktree+///+/// Expected behavior:+/// - Warning: "No worktree found for branch npm"+/// - Success: Branch deleted (same commit as main)+#[rstest]+fn test_remove_branch_no_worktree_path_occupied(mut repo: TestRepo) {+ // Create branch `npm` without a worktree+ repo.git_command(&["branch", "npm"]).output().unwrap();++ // Create a worktree for a different branch at the path where `npm` worktree would be+ // (the path template puts worktrees at ../repo.branch, so ../repo.npm would be npm's path)+ let _other_worktree = repo.add_worktree("other");++ // Manually move the worktree to occupy npm's expected path+ // First, get the expected path for npm+ let npm_expected_path = repo.root_path().parent().unwrap().join(format!(+ "{}.npm",+ repo.root_path().file_name().unwrap().to_str().unwrap()+ ));+ let other_path = repo.root_path().parent().unwrap().join(format!(+ "{}.other",+ repo.root_path().file_name().unwrap().to_str().unwrap()+ ));++ // Remove the worktree metadata and move the directory+ repo.git_command(&[+ "worktree",+ "remove",+ "--force",+ other_path.to_str().unwrap(),+ ])+ .output()+ .unwrap();++ // Create worktree at npm's expected path but for the "other" branch+ repo.git_command(&[+ "worktree",+ "add",+ npm_expected_path.to_str().unwrap(),+ "other",+ ])+ .output()+ .unwrap();++ // Now: branch `npm` exists, no worktree for it, but npm's expected path has `other` branch+ // Running `wt remove npm` should show "No worktree found" NOT "Cannot create worktree"+ snapshot_remove(+ "remove_branch_no_worktree_path_occupied",+ &repo,+ &["npm"],+ None,+ );+}+#[rstest]fn test_remove_multiple_nonexistent_force(repo: TestRepo) {// Try to force-remove multiple branches that don't existdiff --git a/tests/snapshots/integration__integration_tests__remove__remove_branch_no_worktree_path_occupied.snap b/tests/snapshots/integration__integration_tests__remove__remove_branch_no_worktree_path_occupied.snapnew file mode 100644index 000000000..dad25383b--- /dev/null+++ b/tests/snapshots/integration__integration_tests__remove__remove_branch_no_worktree_path_occupied.snap@@ -0,0 +1,33 @@+---+source: tests/integration_tests/remove.rs+info:+ program: wt+ args:+ - remove+ - npm+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "150"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ PATH: "[PATH]"+ SOURCE_DATE_EPOCH: "1735776000"+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+🟡 [33mNo worktree found for branch [1mnpm[22m[39m+✅ [32mRemoved branch [1mnpm[22m (same commit as main)[39m