Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor: improve module organization and separation of concerns (#386)
Maximilian Roos1cea35a2b51f
diff --git a/src/commands/branch_deletion.rs b/src/commands/branch_deletion.rsnew file mode 100644index 000000000..f9d588e00--- /dev/null+++ b/src/commands/branch_deletion.rs@@ -0,0 +1,131 @@+//! Branch deletion logic for worktree operations.+//!+//! This module handles the decision-making around whether a branch can be safely+//! deleted after its worktree is removed. It checks if the branch's content has+//! been integrated into the target branch.++use worktrunk::git::{IntegrationReason, Repository};++/// Result of an integration check, including which target was used.+pub struct IntegrationResult {+ pub reason: Option<IntegrationReason>,+ /// The target that was actually checked against (may be upstream if ahead of local)+ pub effective_target: String,+}++/// Outcome of a branch deletion attempt.+pub enum BranchDeletionOutcome {+ /// Branch was not deleted (not integrated and not forced)+ NotDeleted,+ /// Branch was force-deleted without integration check+ ForceDeleted,+ /// Branch was deleted because it was integrated+ Integrated(IntegrationReason),+}++/// Result of a branch deletion attempt.+pub struct BranchDeletionResult {+ pub outcome: BranchDeletionOutcome,+ /// The target that was actually checked against (may be upstream if ahead of local)+ pub effective_target: String,+}++/// Check if a branch's content has been integrated into the target.+///+/// Returns the reason if the branch is safe to delete (ordered by check cost):+/// - `SameCommit`: Branch HEAD is literally the same commit as target+/// - `NoAddedChanges`: Branch has no file changes beyond merge-base (empty three-dot diff)+/// - `TreesMatch`: The branch's tree SHA matches the target's tree SHA (squash merge/rebase)+/// - `MergeAddsNothing`: Merge simulation shows branch would add nothing (squash + target advanced)+///+/// Also returns the effective target used (may be upstream if it's ahead of local).+///+/// Returns None reason if no condition is met, or if an error occurs (e.g., invalid refs).+/// This fail-safe default prevents accidental branch deletion when integration cannot+/// be determined.+pub fn get_integration_reason(+ repo: &Repository,+ branch_name: &str,+ target: &str,+) -> IntegrationResult {+ let effective_target = repo.effective_integration_target(target);++ let reason = check_integration_against(repo, branch_name, &effective_target);++ IntegrationResult {+ reason,+ effective_target,+ }+}++/// Check integration against a specific target ref.+fn check_integration_against(+ repo: &Repository,+ branch_name: &str,+ target: &str,+) -> Option<IntegrationReason> {+ // Use lazy provider for short-circuit evaluation.+ // Expensive checks (would_merge_add) are skipped if cheaper ones succeed.+ let mut provider = worktrunk::git::LazyGitIntegration::new(repo, branch_name, target);+ worktrunk::git::check_integration(&mut provider)+}++/// Attempt to delete a branch if it's integrated or force_delete is set.+///+/// Returns `BranchDeletionResult` with:+/// - `outcome`: Whether/why deletion occurred+/// - `effective_target`: The ref checked against (may be upstream if ahead of local)+pub fn delete_branch_if_safe(+ repo: &Repository,+ branch_name: &str,+ target: &str,+ force_delete: bool,+) -> anyhow::Result<BranchDeletionResult> {+ let IntegrationResult {+ reason,+ effective_target,+ } = get_integration_reason(repo, branch_name, target);++ // Determine outcome based on integration and force flag+ let outcome = match (reason, force_delete) {+ (Some(r), _) => {+ repo.run_command(&["branch", "-D", branch_name])?;+ BranchDeletionOutcome::Integrated(r)+ }+ (None, true) => {+ repo.run_command(&["branch", "-D", branch_name])?;+ BranchDeletionOutcome::ForceDeleted+ }+ (None, false) => BranchDeletionOutcome::NotDeleted,+ };++ Ok(BranchDeletionResult {+ outcome,+ effective_target,+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_branch_deletion_outcome_matching() {+ // Ensure the match patterns work correctly+ let outcomes = [+ (BranchDeletionOutcome::NotDeleted, false),+ (BranchDeletionOutcome::ForceDeleted, true),+ (+ BranchDeletionOutcome::Integrated(IntegrationReason::SameCommit),+ true,+ ),+ ];+ for (outcome, expected_deleted) in outcomes {+ let deleted = matches!(+ outcome,+ BranchDeletionOutcome::ForceDeleted | BranchDeletionOutcome::Integrated(_)+ );+ assert_eq!(deleted, expected_deleted);+ }+ }+}diff --git a/src/commands/standalone.rs b/src/commands/hook_commands.rssimilarity index 55%rename from src/commands/standalone.rsrename to src/commands/hook_commands.rsindex 3f44c2fd5..0dc26d676 100644--- a/src/commands/standalone.rs+++ b/src/commands/hook_commands.rs@@ -1,3 +1,11 @@+//! Hook commands for `wt hook` subcommand.+//!+//! This module contains:+//! - `run_hook` - Execute a specific hook type+//! - `add_approvals` - Approve all project commands+//! - `clear_approvals` - Clear approved commands+//! - `handle_hook_show` - Display configured hooks+use anyhow::Context;use color_print::cformat;use std::fmt::Write as _;@@ -6,12 +14,11 @@ use worktrunk::config::{CommandConfig, ProjectConfig, WorktrunkConfig};use worktrunk::git::{GitError, Repository};use worktrunk::path::format_path_for_display;use worktrunk::styling::{- INFO_SYMBOL, PROMPT_SYMBOL, format_bash_with_gutter, format_heading, format_with_gutter,- hint_message, info_message, progress_message, success_message,+ INFO_SYMBOL, PROMPT_SYMBOL, format_bash_with_gutter, format_heading, hint_message,+ info_message, success_message,};use super::command_executor::CommandContext;-use super::commit::{CommitGenerator, CommitOptions};use super::context::CommandEnv;use super::hooks::{HookFailureStrategy, check_name_filter_matched, prepare_hook_commands, run_hook_with_filter,@@ -171,390 +178,6 @@ pub fn run_hook(hook_type: HookType, yes: bool, name_filter: Option<&str>) -> an}}-/// Handle `wt step commit` command-pub fn step_commit(- yes: bool,- no_verify: bool,- stage_mode: super::commit::StageMode,- show_prompt: bool,-) -> anyhow::Result<()> {- use super::command_approval::approve_hooks;-- // Handle --show-prompt early: just build and output the prompt- if show_prompt {- let config = WorktrunkConfig::load().context("Failed to load config")?;- let prompt = crate::llm::build_commit_prompt(&config.commit_generation)?;- crate::output::stdout(prompt)?;- return Ok(());- }-- let env = CommandEnv::for_action("commit")?;- let ctx = env.context(yes);-- // "Approve at the Gate": approve pre-commit hooks upfront (unless --no-verify)- // Shadow no_verify: if user declines approval, skip hooks but continue commit- let no_verify = if !no_verify {- let approved = approve_hooks(&ctx, &[HookType::PreCommit])?;- if !approved {- crate::output::print(worktrunk::styling::info_message(- "Commands declined, committing without hooks",- ))?;- true // Skip hooks- } else {- false // Run hooks- }- } else {- true // --no-verify was passed- };-- let mut options = CommitOptions::new(&ctx);- options.no_verify = no_verify;- options.stage_mode = stage_mode;- options.show_no_squash_note = false;- // Only warn about untracked if we're staging all- options.warn_about_untracked = stage_mode == super::commit::StageMode::All;-- options.commit()-}--/// Result of a squash operation-#[derive(Debug, Clone)]-pub enum SquashResult {- /// Squash or commit occurred- Squashed,- /// Nothing to squash: no commits ahead of target branch- NoCommitsAhead(String),- /// Nothing to squash: already a single commit- AlreadySingleCommit,- /// Squash attempted but resulted in no net changes (commits canceled out)- NoNetChanges,-}--/// Handle shared squash workflow (used by `wt step squash` and `wt merge`)-///-/// # Arguments-/// * `skip_pre_commit` - If true, skip all pre-commit hooks (both user and project)-/// * `stage_mode` - What to stage before committing (All or Tracked; None not supported for squash)-pub fn handle_squash(- target: Option<&str>,- yes: bool,- skip_pre_commit: bool,- stage_mode: super::commit::StageMode,-) -> anyhow::Result<SquashResult> {- use super::commit::StageMode;-- let env = CommandEnv::for_action("squash")?;- let repo = &env.repo;- // Squash requires being on a branch (can't squash in detached HEAD)- let current_branch = env.require_branch("squash")?.to_string();- let ctx = env.context(yes);- let generator = CommitGenerator::new(&env.config.commit_generation);-- // Get target branch (default to default branch if not provided)- let target_branch = repo.resolve_target_branch(target)?;-- // Auto-stage changes before running pre-commit hooks so both beta and merge paths behave identically- match stage_mode {- StageMode::All => {- repo.warn_if_auto_staging_untracked()?;- repo.run_command(&["add", "-A"])- .context("Failed to stage changes")?;- }- StageMode::Tracked => {- repo.run_command(&["add", "-u"])- .context("Failed to stage tracked changes")?;- }- StageMode::None => {- // Stage nothing - use what's already staged- }- }-- // Run pre-commit hooks unless explicitly skipped- let project_config = repo.load_project_config()?;- let has_project_pre_commit = project_config- .as_ref()- .map(|c| c.hooks.pre_commit.is_some())- .unwrap_or(false);- let has_user_pre_commit = ctx.config.hooks.pre_commit.is_some();- let has_any_pre_commit = has_project_pre_commit || has_user_pre_commit;-- if skip_pre_commit && has_any_pre_commit {- crate::output::print(info_message(cformat!(- "Skipping pre-commit hooks (<bright-black>--no-verify</>)"- )))?;- }-- // Run pre-commit hooks (user first, then project)- if !skip_pre_commit {- let extra_vars = [("target", target_branch.as_str())];- run_hook_with_filter(- &ctx,- ctx.config.hooks.pre_commit.as_ref(),- project_config- .as_ref()- .and_then(|c| c.hooks.pre_commit.as_ref()),- HookType::PreCommit,- &extra_vars,- HookFailureStrategy::FailFast,- None,- None,- )- .map_err(worktrunk::git::add_hook_skip_hint)?;- }-- // Get merge base with target branch- let merge_base = repo.merge_base("HEAD", &target_branch)?;-- // Count commits since merge base- let commit_count = repo.count_commits(&merge_base, "HEAD")?;-- // Check if there are staged changes in addition to commits- let has_staged = repo.has_staged_changes()?;-- // Handle different scenarios- if commit_count == 0 && !has_staged {- // No commits and no staged changes - nothing to squash- return Ok(SquashResult::NoCommitsAhead(target_branch));- }-- if commit_count == 0 && has_staged {- // Just staged changes, no commits - commit them directly (no squashing needed)- generator.commit_staged_changes(true, stage_mode)?;- return Ok(SquashResult::Squashed);- }-- if commit_count == 1 && !has_staged {- // Single commit, no staged changes - already squashed- return Ok(SquashResult::AlreadySingleCommit);- }-- // Either multiple commits OR single commit with staged changes - squash them- // Get diff stats early for display in progress message- let range = format!("{}..HEAD", merge_base);-- let commit_text = if commit_count == 1 {- "commit"- } else {- "commits"- };-- // Get total stats (commits + any working tree changes)- let total_stats = if has_staged {- repo.diff_stats_summary(&["diff", "--shortstat", &merge_base, "--cached"])- } else {- repo.diff_stats_summary(&["diff", "--shortstat", &range])- };-- let with_changes = if has_staged {- match stage_mode {- super::commit::StageMode::Tracked => " & tracked changes",- _ => " & working tree changes",- }- } else {- ""- };-- // Build parenthesized content: stats only (stage mode is in message text)- let parts = total_stats;-- let squash_progress = if parts.is_empty() {- format!("Squashing {commit_count} {commit_text}{with_changes} into a single commit...")- } else {- // Gray parenthetical with separate cformat for closing paren (avoids optimizer)- let parts_str = parts.join(", ");- let paren_close = cformat!("<bright-black>)</>");- cformat!(- "Squashing {commit_count} {commit_text}{with_changes} into a single commit <bright-black>({parts_str}</>{paren_close}..."- )- };- crate::output::print(progress_message(squash_progress))?;-- // Create safety backup before potentially destructive reset if there are working tree changes- if has_staged {- let backup_message = format!("{} → {} (squash)", current_branch, target_branch);- let sha = repo.create_safety_backup(&backup_message)?;- crate::output::print(hint_message(format!("Backup created @ {sha}")))?;- }-- // Get commit subjects for the squash message- let subjects = repo.commit_subjects(&range)?;-- // Generate squash commit message- crate::output::print(progress_message("Generating squash commit message..."))?;-- generator.emit_hint_if_needed()?;-- // Get current branch and repo name for template variables- let repo_root = repo.worktree_root()?;- let repo_name = repo_root- .file_name()- .and_then(|n| n.to_str())- .unwrap_or("repo");-- let commit_message = crate::llm::generate_squash_message(- &target_branch,- &merge_base,- &subjects,- ¤t_branch,- repo_name,- &env.config.commit_generation,- )?;-- // Display the generated commit message- let formatted_message = generator.format_message_for_display(&commit_message);- crate::output::print(format_with_gutter(&formatted_message, None))?;-- // Reset to merge base (soft reset stages all changes, including any already-staged uncommitted changes)- repo.run_command(&["reset", "--soft", &merge_base])- .context("Failed to reset to merge base")?;-- // Check if there are actually any changes to commit- if !repo.has_staged_changes()? {- crate::output::print(info_message(format!(- "No changes after squashing {commit_count} {commit_text}"- )))?;- return Ok(SquashResult::NoNetChanges);- }-- // Commit with the generated message- repo.run_command(&["commit", "-m", &commit_message])- .context("Failed to create squash commit")?;-- // Get commit hash for display- let commit_hash = repo- .run_command(&["rev-parse", "--short", "HEAD"])?- .trim()- .to_string();-- // Show success immediately after completing the squash- crate::output::print(success_message(cformat!(- "Squashed @ <dim>{commit_hash}</>"- )))?;-- Ok(SquashResult::Squashed)-}--/// Handle `wt step squash --show-prompt`-///-/// Builds and outputs the squash prompt without running the LLM or squashing.-pub fn step_show_squash_prompt(- target: Option<&str>,- config: &worktrunk::config::CommitGenerationConfig,-) -> anyhow::Result<()> {- let repo = Repository::current();-- // Get target branch (default to default branch if not provided)- let target_branch = repo.resolve_target_branch(target)?;-- // Get current branch- let current_branch = repo.current_branch()?.unwrap_or("HEAD");-- // Get merge base with target branch- let merge_base = repo.merge_base("HEAD", &target_branch)?;-- // Get commit subjects for the squash message- let range = format!("{}..HEAD", merge_base);- let subjects = repo.commit_subjects(&range)?;-- // Get repo name from directory- let repo_root = repo.worktree_root()?;- let repo_name = repo_root- .file_name()- .and_then(|n| n.to_str())- .unwrap_or("repo");-- let prompt = crate::llm::build_squash_prompt(- &target_branch,- &merge_base,- &subjects,- current_branch,- repo_name,- config,- )?;- crate::output::stdout(prompt)?;- Ok(())-}--/// Result of a rebase operation-pub enum RebaseResult {- /// Rebase occurred (either true rebase or fast-forward)- Rebased,- /// Already up-to-date with target branch- UpToDate(String),-}--/// Handle shared rebase workflow (used by `wt step rebase` and `wt merge`)-pub fn handle_rebase(target: Option<&str>) -> anyhow::Result<RebaseResult> {- use super::repository_ext::RepositoryCliExt;-- let repo = Repository::current();-- // Get target branch (default to default branch if not provided)- let target_branch = repo.resolve_target_branch(target)?;-- // Check if already up-to-date (linear extension of target, no merge commits)- if repo.is_rebased_onto(&target_branch)? {- return Ok(RebaseResult::UpToDate(target_branch));- }-- // Check if this is a fast-forward or true rebase- let merge_base = repo.merge_base("HEAD", &target_branch)?;- let head_sha = repo.run_command(&["rev-parse", "HEAD"])?.trim().to_string();- let is_fast_forward = merge_base == head_sha;-- // Only show progress for true rebases (fast-forwards are instant)- if !is_fast_forward {- crate::output::print(progress_message(cformat!(- "Rebasing onto <bold>{target_branch}</>..."- )))?;- }-- let rebase_result = repo.run_command(&["rebase", &target_branch]);-- // If rebase failed, check if it's due to conflicts- if let Err(e) = rebase_result {- if let Some(state) = repo.worktree_state()?- && state.starts_with("REBASING")- {- // Extract git's stderr output from the error- let git_output = e.to_string();- return Err(worktrunk::git::GitError::RebaseConflict {- target_branch: target_branch.clone(),- git_output,- }- .into());- }- // Not a rebase conflict, return original error- return Err(worktrunk::git::GitError::Other {- message: format!("Failed to rebase onto '{}': {}", target_branch, e),- }- .into());- }-- // Verify rebase completed successfully (safety check for edge cases)- if let Some(state) = repo.worktree_state()? {- let _ = state; // used for diagnostics- return Err(worktrunk::git::GitError::RebaseConflict {- target_branch: target_branch.clone(),- git_output: String::new(),- }- .into());- }-- // Success- if is_fast_forward {- crate::output::print(success_message(cformat!(- "Fast-forwarded to <bold>{target_branch}</>"- )))?;- } else {- crate::output::print(success_message(cformat!(- "Rebased onto <bold>{target_branch}</>"- )))?;- }-- Ok(RebaseResult::Rebased)-}-/// Handle `wt hook approvals add` command - approve all commands in the projectpub fn add_approvals(show_all: bool) -> anyhow::Result<()> {use super::command_approval::approve_command_batch;@@ -927,56 +550,3 @@ fn expand_command_template(template: &str, ctx: &CommandContext, hook_type: Hookworktrunk::config::expand_template(template, &vars, true).unwrap_or_else(|_| template.to_string())}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn test_squash_result_variants() {- // Test Debug implementation- let result = SquashResult::Squashed;- let debug = format!("{:?}", result);- assert!(debug.contains("Squashed"));-- let result = SquashResult::NoCommitsAhead("main".to_string());- let debug = format!("{:?}", result);- assert!(debug.contains("NoCommitsAhead"));- assert!(debug.contains("main"));-- let result = SquashResult::AlreadySingleCommit;- let debug = format!("{:?}", result);- assert!(debug.contains("AlreadySingleCommit"));-- let result = SquashResult::NoNetChanges;- let debug = format!("{:?}", result);- assert!(debug.contains("NoNetChanges"));- }-- #[test]- fn test_squash_result_clone() {- let original = SquashResult::NoCommitsAhead("develop".to_string());- let cloned = original.clone();- assert!(matches!(cloned, SquashResult::NoCommitsAhead(ref s) if s == "develop"));- }-- #[test]- fn test_rebase_result_variants() {- // RebaseResult doesn't derive Debug/Clone by default, just test matching- let result = RebaseResult::Rebased;- assert!(matches!(result, RebaseResult::Rebased));-- let result = RebaseResult::UpToDate("main".to_string());- assert!(matches!(result, RebaseResult::UpToDate(ref s) if s == "main"));- }-- #[test]- fn test_rebase_result_up_to_date_branch_extraction() {- let result = RebaseResult::UpToDate("feature-branch".to_string());- if let RebaseResult::UpToDate(branch) = result {- assert_eq!(branch, "feature-branch");- } else {- panic!("Expected UpToDate variant");- }- }-}diff --git a/src/commands/merge.rs b/src/commands/merge.rsindex adb13598d..5d4452b66 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -172,13 +172,13 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {// Squash commits if enabled - track whether squashing occurredlet squashed = if squash_enabled {matches!(- super::standalone::handle_squash(+ super::step_commands::handle_squash(Some(&target_branch),yes,!verify, // skip_pre_commit when !verifystage_mode)?,- super::standalone::SquashResult::Squashed+ super::step_commands::SquashResult::Squashed)} else {false@@ -188,8 +188,8 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {let rebased = if rebase {// Auto-rebase onto targetmatches!(- super::standalone::handle_rebase(Some(&target_branch))?,- super::standalone::RebaseResult::Rebased+ super::step_commands::handle_rebase(Some(&target_branch))?,+ super::step_commands::RebaseResult::Rebased)} else {// --no-rebase: verify already rebased, fail if notdiff --git a/src/commands/mod.rs b/src/commands/mod.rsindex 7039a3f57..4eabce64f 100644--- a/src/commands/mod.rs+++ b/src/commands/mod.rs@@ -1,3 +1,4 @@+pub mod branch_deletion;pub mod command_approval;pub mod command_executor;pub mod commit;@@ -5,6 +6,7 @@ pub mod config;pub mod configure_shell;pub mod context;mod for_each;+mod hook_commands;mod hooks;pub mod init;pub mod list;@@ -14,8 +16,8 @@ pub mod project_config;pub mod repository_ext;#[cfg(unix)]pub mod select;-pub mod standalone;pub mod statusline;+pub mod step_commands;pub mod worktree;pub use command_approval::approve_hooks;@@ -25,14 +27,14 @@ pub use config::{};pub use configure_shell::{handle_configure_shell, handle_show_theme, handle_unconfigure_shell};pub use for_each::step_for_each;+pub use hook_commands::{add_approvals, clear_approvals, handle_hook_show, run_hook};pub use init::handle_init;pub use list::handle_list;pub use merge::{MergeOptions, execute_pre_remove_commands, handle_merge};#[cfg(unix)]pub use select::handle_select;-pub use standalone::{- RebaseResult, SquashResult, add_approvals, clear_approvals, handle_hook_show, handle_rebase,- handle_squash, run_hook, step_commit, step_show_squash_prompt,+pub use step_commands::{+ RebaseResult, SquashResult, handle_rebase, handle_squash, step_commit, step_show_squash_prompt,};pub use worktree::{ResolutionContext, compute_worktree_path, handle_remove, handle_remove_by_path,diff --git a/src/commands/process.rs b/src/commands/process.rsindex ec9580717..5af25ccf3 100644--- a/src/commands/process.rs+++ b/src/commands/process.rs@@ -246,6 +246,60 @@ fn spawn_detached_windows(Ok(())}+/// Build shell command for background worktree removal+///+/// `branch_to_delete` is the branch to delete after removing the worktree.+/// Pass `None` for detached HEAD or when branch should be retained.+/// This decision is computed upfront (checking if branch is merged) before spawning the background process.+///+/// `force_worktree` adds `--force` to `git worktree remove`, allowing removal+/// even when the worktree contains untracked files (like build artifacts).+pub fn build_remove_command(+ worktree_path: &std::path::Path,+ branch_to_delete: Option<&str>,+ force_worktree: bool,+) -> String {+ use shell_escape::escape;++ let worktree_path_str = worktree_path.to_string_lossy();+ let worktree_escaped = escape(worktree_path_str.as_ref().into());++ // TODO: This delay is a timing-based workaround, not a principled fix.+ // The race: after wt exits, the shell wrapper reads the directive file and+ // runs `cd`. But fish (and other shells) may call getcwd() before the cd+ // completes (e.g., for prompt updates), and if the background removal has+ // already deleted the directory, we get "shell-init: error retrieving current+ // directory". A 1s delay is very conservative (shell cd takes ~1-5ms), but+ // deterministic solutions (shell-spawned background, marker file sync) add+ // significant complexity for marginal benefit.+ let delay = "sleep 1";++ // Stop fsmonitor daemon first (best effort - ignore errors)+ // This prevents zombie daemons from accumulating when using builtin fsmonitor+ let stop_fsmonitor = format!(+ "git -C {} fsmonitor--daemon stop 2>/dev/null || true",+ worktree_escaped+ );++ let force_flag = if force_worktree { " --force" } else { "" };++ match branch_to_delete {+ Some(branch_name) => {+ let branch_escaped = escape(branch_name.into());+ format!(+ "{} && {} && git worktree remove{} {} && git branch -D {}",+ delay, stop_fsmonitor, force_flag, worktree_escaped, branch_escaped+ )+ }+ None => {+ format!(+ "{} && {} && git worktree remove{} {}",+ delay, stop_fsmonitor, force_flag, worktree_escaped+ )+ }+ }+}+#[cfg(test)]mod tests {use super::*;@@ -317,4 +371,39 @@ mod tests {// Commands with internal semicolons but not trailingassert_eq!(posix_command_separator("echo; hello"), ";");}++ #[test]+ fn test_build_remove_command() {+ use std::path::PathBuf;++ let path = PathBuf::from("/tmp/test-worktree");++ // Without branch deletion, without force+ let cmd = build_remove_command(&path, None, false);+ assert!(cmd.contains("git worktree remove"));+ assert!(cmd.contains("/tmp/test-worktree"));+ assert!(!cmd.contains("branch -D"));+ assert!(!cmd.contains("--force"));++ // With branch deletion, without force+ let cmd = build_remove_command(&path, Some("feature-branch"), false);+ assert!(cmd.contains("git worktree remove"));+ assert!(cmd.contains("git branch -D"));+ assert!(cmd.contains("feature-branch"));+ assert!(!cmd.contains("--force"));++ // With force flag+ let cmd = build_remove_command(&path, None, true);+ assert!(cmd.contains("git worktree remove --force"));++ // With branch deletion and force+ let cmd = build_remove_command(&path, Some("feature-branch"), true);+ assert!(cmd.contains("git worktree remove --force"));+ assert!(cmd.contains("git branch -D"));++ // Shell escaping for special characters+ let special_path = PathBuf::from("/tmp/test worktree");+ let cmd = build_remove_command(&special_path, Some("feature/branch"), false);+ assert!(cmd.contains("worktree remove"));+ }}diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rsnew file mode 100644index 000000000..5e580edd8--- /dev/null+++ b/src/commands/step_commands.rs@@ -0,0 +1,458 @@+//! Step commands for the merge workflow.+//!+//! This module contains the individual steps that make up `wt merge`:+//! - `step_commit` - Commit working tree changes+//! - `handle_squash` - Squash commits into one+//! - `step_show_squash_prompt` - Show squash prompt without executing+//! - `handle_rebase` - Rebase onto target branch++use anyhow::Context;+use color_print::cformat;+use worktrunk::HookType;+use worktrunk::config::WorktrunkConfig;+use worktrunk::git::Repository;+use worktrunk::styling::{+ format_with_gutter, hint_message, info_message, progress_message, success_message,+};++use super::commit::{CommitGenerator, CommitOptions};+use super::context::CommandEnv;+use super::hooks::{HookFailureStrategy, run_hook_with_filter};+use super::repository_ext::RepositoryCliExt;++/// Handle `wt step commit` command+pub fn step_commit(+ yes: bool,+ no_verify: bool,+ stage_mode: super::commit::StageMode,+ show_prompt: bool,+) -> anyhow::Result<()> {+ use super::command_approval::approve_hooks;++ // Handle --show-prompt early: just build and output the prompt+ if show_prompt {+ let config = WorktrunkConfig::load().context("Failed to load config")?;+ let prompt = crate::llm::build_commit_prompt(&config.commit_generation)?;+ crate::output::stdout(prompt)?;+ return Ok(());+ }++ let env = CommandEnv::for_action("commit")?;+ let ctx = env.context(yes);++ // "Approve at the Gate": approve pre-commit hooks upfront (unless --no-verify)+ // Shadow no_verify: if user declines approval, skip hooks but continue commit+ let no_verify = if !no_verify {+ let approved = approve_hooks(&ctx, &[HookType::PreCommit])?;+ if !approved {+ crate::output::print(worktrunk::styling::info_message(+ "Commands declined, committing without hooks",+ ))?;+ true // Skip hooks+ } else {+ false // Run hooks+ }+ } else {+ true // --no-verify was passed+ };++ let mut options = CommitOptions::new(&ctx);+ options.no_verify = no_verify;+ options.stage_mode = stage_mode;+ options.show_no_squash_note = false;+ // Only warn about untracked if we're staging all+ options.warn_about_untracked = stage_mode == super::commit::StageMode::All;++ options.commit()+}++/// Result of a squash operation+#[derive(Debug, Clone)]+pub enum SquashResult {+ /// Squash or commit occurred+ Squashed,+ /// Nothing to squash: no commits ahead of target branch+ NoCommitsAhead(String),+ /// Nothing to squash: already a single commit+ AlreadySingleCommit,+ /// Squash attempted but resulted in no net changes (commits canceled out)+ NoNetChanges,+}++/// Handle shared squash workflow (used by `wt step squash` and `wt merge`)+///+/// # Arguments+/// * `skip_pre_commit` - If true, skip all pre-commit hooks (both user and project)+/// * `stage_mode` - What to stage before committing (All or Tracked; None not supported for squash)+pub fn handle_squash(+ target: Option<&str>,+ yes: bool,+ skip_pre_commit: bool,+ stage_mode: super::commit::StageMode,+) -> anyhow::Result<SquashResult> {+ use super::commit::StageMode;++ let env = CommandEnv::for_action("squash")?;+ let repo = &env.repo;+ // Squash requires being on a branch (can't squash in detached HEAD)+ let current_branch = env.require_branch("squash")?.to_string();+ let ctx = env.context(yes);+ let generator = CommitGenerator::new(&env.config.commit_generation);++ // Get target branch (default to default branch if not provided)+ let target_branch = repo.resolve_target_branch(target)?;++ // Auto-stage changes before running pre-commit hooks so both beta and merge paths behave identically+ match stage_mode {+ StageMode::All => {+ repo.warn_if_auto_staging_untracked()?;+ repo.run_command(&["add", "-A"])+ .context("Failed to stage changes")?;+ }+ StageMode::Tracked => {+ repo.run_command(&["add", "-u"])+ .context("Failed to stage tracked changes")?;+ }+ StageMode::None => {+ // Stage nothing - use what's already staged+ }+ }++ // Run pre-commit hooks unless explicitly skipped+ let project_config = repo.load_project_config()?;+ let has_project_pre_commit = project_config+ .as_ref()+ .map(|c| c.hooks.pre_commit.is_some())+ .unwrap_or(false);+ let has_user_pre_commit = ctx.config.hooks.pre_commit.is_some();+ let has_any_pre_commit = has_project_pre_commit || has_user_pre_commit;++ if skip_pre_commit && has_any_pre_commit {+ crate::output::print(info_message(cformat!(+ "Skipping pre-commit hooks (<bright-black>--no-verify</>)"+ )))?;+ }++ // Run pre-commit hooks (user first, then project)+ if !skip_pre_commit {+ let extra_vars = [("target", target_branch.as_str())];+ run_hook_with_filter(+ &ctx,+ ctx.config.hooks.pre_commit.as_ref(),+ project_config+ .as_ref()+ .and_then(|c| c.hooks.pre_commit.as_ref()),+ HookType::PreCommit,+ &extra_vars,+ HookFailureStrategy::FailFast,+ None,+ None,+ )+ .map_err(worktrunk::git::add_hook_skip_hint)?;+ }++ // Get merge base with target branch+ let merge_base = repo.merge_base("HEAD", &target_branch)?;++ // Count commits since merge base+ let commit_count = repo.count_commits(&merge_base, "HEAD")?;++ // Check if there are staged changes in addition to commits+ let has_staged = repo.has_staged_changes()?;++ // Handle different scenarios+ if commit_count == 0 && !has_staged {+ // No commits and no staged changes - nothing to squash+ return Ok(SquashResult::NoCommitsAhead(target_branch));+ }++ if commit_count == 0 && has_staged {+ // Just staged changes, no commits - commit them directly (no squashing needed)+ generator.commit_staged_changes(true, stage_mode)?;+ return Ok(SquashResult::Squashed);+ }++ if commit_count == 1 && !has_staged {+ // Single commit, no staged changes - already squashed+ return Ok(SquashResult::AlreadySingleCommit);+ }++ // Either multiple commits OR single commit with staged changes - squash them+ // Get diff stats early for display in progress message+ let range = format!("{}..HEAD", merge_base);++ let commit_text = if commit_count == 1 {+ "commit"+ } else {+ "commits"+ };++ // Get total stats (commits + any working tree changes)+ let total_stats = if has_staged {+ repo.diff_stats_summary(&["diff", "--shortstat", &merge_base, "--cached"])+ } else {+ repo.diff_stats_summary(&["diff", "--shortstat", &range])+ };++ let with_changes = if has_staged {+ match stage_mode {+ super::commit::StageMode::Tracked => " & tracked changes",+ _ => " & working tree changes",+ }+ } else {+ ""+ };++ // Build parenthesized content: stats only (stage mode is in message text)+ let parts = total_stats;++ let squash_progress = if parts.is_empty() {+ format!("Squashing {commit_count} {commit_text}{with_changes} into a single commit...")+ } else {+ // Gray parenthetical with separate cformat for closing paren (avoids optimizer)+ let parts_str = parts.join(", ");+ let paren_close = cformat!("<bright-black>)</>");+ cformat!(+ "Squashing {commit_count} {commit_text}{with_changes} into a single commit <bright-black>({parts_str}</>{paren_close}..."+ )+ };+ crate::output::print(progress_message(squash_progress))?;++ // Create safety backup before potentially destructive reset if there are working tree changes+ if has_staged {+ let backup_message = format!("{} → {} (squash)", current_branch, target_branch);+ let sha = repo.create_safety_backup(&backup_message)?;+ crate::output::print(hint_message(format!("Backup created @ {sha}")))?;+ }++ // Get commit subjects for the squash message+ let subjects = repo.commit_subjects(&range)?;++ // Generate squash commit message+ crate::output::print(progress_message("Generating squash commit message..."))?;++ generator.emit_hint_if_needed()?;++ // Get current branch and repo name for template variables+ let repo_root = repo.worktree_root()?;+ let repo_name = repo_root+ .file_name()+ .and_then(|n| n.to_str())+ .unwrap_or("repo");++ let commit_message = crate::llm::generate_squash_message(+ &target_branch,+ &merge_base,+ &subjects,+ ¤t_branch,+ repo_name,+ &env.config.commit_generation,+ )?;++ // Display the generated commit message+ let formatted_message = generator.format_message_for_display(&commit_message);+ crate::output::print(format_with_gutter(&formatted_message, None))?;++ // Reset to merge base (soft reset stages all changes, including any already-staged uncommitted changes)+ repo.run_command(&["reset", "--soft", &merge_base])+ .context("Failed to reset to merge base")?;++ // Check if there are actually any changes to commit+ if !repo.has_staged_changes()? {+ crate::output::print(info_message(format!(+ "No changes after squashing {commit_count} {commit_text}"+ )))?;+ return Ok(SquashResult::NoNetChanges);+ }++ // Commit with the generated message+ repo.run_command(&["commit", "-m", &commit_message])+ .context("Failed to create squash commit")?;++ // Get commit hash for display+ let commit_hash = repo+ .run_command(&["rev-parse", "--short", "HEAD"])?+ .trim()+ .to_string();++ // Show success immediately after completing the squash+ crate::output::print(success_message(cformat!(+ "Squashed @ <dim>{commit_hash}</>"+ )))?;++ Ok(SquashResult::Squashed)+}++/// Handle `wt step squash --show-prompt`+///+/// Builds and outputs the squash prompt without running the LLM or squashing.+pub fn step_show_squash_prompt(+ target: Option<&str>,+ config: &worktrunk::config::CommitGenerationConfig,+) -> anyhow::Result<()> {+ let repo = Repository::current();++ // Get target branch (default to default branch if not provided)+ let target_branch = repo.resolve_target_branch(target)?;++ // Get current branch+ let current_branch = repo.current_branch()?.unwrap_or("HEAD");++ // Get merge base with target branch+ let merge_base = repo.merge_base("HEAD", &target_branch)?;++ // Get commit subjects for the squash message+ let range = format!("{}..HEAD", merge_base);+ let subjects = repo.commit_subjects(&range)?;++ // Get repo name from directory+ let repo_root = repo.worktree_root()?;+ let repo_name = repo_root+ .file_name()+ .and_then(|n| n.to_str())+ .unwrap_or("repo");++ let prompt = crate::llm::build_squash_prompt(+ &target_branch,+ &merge_base,+ &subjects,+ current_branch,+ repo_name,+ config,+ )?;+ crate::output::stdout(prompt)?;+ Ok(())+}++/// Result of a rebase operation+pub enum RebaseResult {+ /// Rebase occurred (either true rebase or fast-forward)+ Rebased,+ /// Already up-to-date with target branch+ UpToDate(String),+}++/// Handle shared rebase workflow (used by `wt step rebase` and `wt merge`)+pub fn handle_rebase(target: Option<&str>) -> anyhow::Result<RebaseResult> {+ use super::repository_ext::RepositoryCliExt;++ let repo = Repository::current();++ // Get target branch (default to default branch if not provided)+ let target_branch = repo.resolve_target_branch(target)?;++ // Check if already up-to-date (linear extension of target, no merge commits)+ if repo.is_rebased_onto(&target_branch)? {+ return Ok(RebaseResult::UpToDate(target_branch));+ }++ // Check if this is a fast-forward or true rebase+ let merge_base = repo.merge_base("HEAD", &target_branch)?;+ let head_sha = repo.run_command(&["rev-parse", "HEAD"])?.trim().to_string();+ let is_fast_forward = merge_base == head_sha;++ // Only show progress for true rebases (fast-forwards are instant)+ if !is_fast_forward {+ crate::output::print(progress_message(cformat!(+ "Rebasing onto <bold>{target_branch}</>..."+ )))?;+ }++ let rebase_result = repo.run_command(&["rebase", &target_branch]);++ // If rebase failed, check if it's due to conflicts+ if let Err(e) = rebase_result {+ if let Some(state) = repo.worktree_state()?+ && state.starts_with("REBASING")+ {+ // Extract git's stderr output from the error+ let git_output = e.to_string();+ return Err(worktrunk::git::GitError::RebaseConflict {+ target_branch: target_branch.clone(),+ git_output,+ }+ .into());+ }+ // Not a rebase conflict, return original error+ return Err(worktrunk::git::GitError::Other {+ message: format!("Failed to rebase onto '{}': {}", target_branch, e),+ }+ .into());+ }++ // Verify rebase completed successfully (safety check for edge cases)+ if let Some(state) = repo.worktree_state()? {+ let _ = state; // used for diagnostics+ return Err(worktrunk::git::GitError::RebaseConflict {+ target_branch: target_branch.clone(),+ git_output: String::new(),+ }+ .into());+ }++ // Success+ if is_fast_forward {+ crate::output::print(success_message(cformat!(+ "Fast-forwarded to <bold>{target_branch}</>"+ )))?;+ } else {+ crate::output::print(success_message(cformat!(+ "Rebased onto <bold>{target_branch}</>"+ )))?;+ }++ Ok(RebaseResult::Rebased)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_squash_result_variants() {+ // Test Debug implementation+ let result = SquashResult::Squashed;+ let debug = format!("{:?}", result);+ assert!(debug.contains("Squashed"));++ let result = SquashResult::NoCommitsAhead("main".to_string());+ let debug = format!("{:?}", result);+ assert!(debug.contains("NoCommitsAhead"));+ assert!(debug.contains("main"));++ let result = SquashResult::AlreadySingleCommit;+ let debug = format!("{:?}", result);+ assert!(debug.contains("AlreadySingleCommit"));++ let result = SquashResult::NoNetChanges;+ let debug = format!("{:?}", result);+ assert!(debug.contains("NoNetChanges"));+ }++ #[test]+ fn test_squash_result_clone() {+ let original = SquashResult::NoCommitsAhead("develop".to_string());+ let cloned = original.clone();+ assert!(matches!(cloned, SquashResult::NoCommitsAhead(ref s) if s == "develop"));+ }++ #[test]+ fn test_rebase_result_variants() {+ // RebaseResult doesn't derive Debug/Clone by default, just test matching+ let result = RebaseResult::Rebased;+ assert!(matches!(result, RebaseResult::Rebased));++ let result = RebaseResult::UpToDate("main".to_string());+ assert!(matches!(result, RebaseResult::UpToDate(ref s) if s == "main"));+ }++ #[test]+ fn test_rebase_result_up_to_date_branch_extraction() {+ let result = RebaseResult::UpToDate("feature-branch".to_string());+ if let RebaseResult::UpToDate(branch) = result {+ assert_eq!(branch, "feature-branch");+ } else {+ panic!("Expected UpToDate variant");+ }+ }+}diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex f52245c94..23f9a57ab 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -3,9 +3,12 @@use color_print::cformat;use std::path::Path;+use crate::commands::branch_deletion::{+ BranchDeletionOutcome, BranchDeletionResult, delete_branch_if_safe,+};use crate::commands::command_executor::CommandContext;use crate::commands::execute_pre_remove_commands;-use crate::commands::process::spawn_detached;+use crate::commands::process::{build_remove_command, spawn_detached};use crate::commands::worktree::{BranchDeletionMode, RemoveResult, SwitchBranchInfo, SwitchResult};use worktrunk::config::WorktrunkConfig;use worktrunk::git::GitError;@@ -56,101 +59,6 @@ fn format_switch_message(}}-/// Result of an integration check, including which target was used.-struct IntegrationResult {- reason: Option<IntegrationReason>,- /// The target that was actually checked against (may be upstream if ahead of local)- effective_target: String,-}--/// Check if a branch's content has been integrated into the target.-///-/// Returns the reason if the branch is safe to delete (ordered by check cost):-/// - `SameCommit`: Branch HEAD is literally the same commit as target-/// - `NoAddedChanges`: Branch has no file changes beyond merge-base (empty three-dot diff)-/// - `TreesMatch`: The branch's tree SHA matches the target's tree SHA (squash merge/rebase)-/// - `MergeAddsNothing`: Merge simulation shows branch would add nothing (squash + target advanced)-///-/// Also returns the effective target used (may be upstream if it's ahead of local).-///-/// Returns None reason if no condition is met, or if an error occurs (e.g., invalid refs).-/// This fail-safe default prevents accidental branch deletion when integration cannot-/// be determined.-fn get_integration_reason(repo: &Repository, branch_name: &str, target: &str) -> IntegrationResult {- let effective_target = repo.effective_integration_target(target);-- let reason = check_integration_against(repo, branch_name, &effective_target);-- IntegrationResult {- reason,- effective_target,- }-}--/// Check integration against a specific target ref.-fn check_integration_against(- repo: &Repository,- branch_name: &str,- target: &str,-) -> Option<IntegrationReason> {- // Use lazy provider for short-circuit evaluation.- // Expensive checks (would_merge_add) are skipped if cheaper ones succeed.- let mut provider = worktrunk::git::LazyGitIntegration::new(repo, branch_name, target);- worktrunk::git::check_integration(&mut provider)-}--/// Outcome of a branch deletion attempt.-enum BranchDeletionOutcome {- /// Branch was not deleted (not integrated and not forced)- NotDeleted,- /// Branch was force-deleted without integration check- ForceDeleted,- /// Branch was deleted because it was integrated- Integrated(IntegrationReason),-}--/// Result of a branch deletion attempt.-struct BranchDeletionResult {- outcome: BranchDeletionOutcome,- /// The target that was actually checked against (may be upstream if ahead of local)- effective_target: String,-}--/// Attempt to delete a branch if it's integrated or force_delete is set.-///-/// Returns `BranchDeletionResult` with:-/// - `outcome`: Whether/why deletion occurred-/// - `effective_target`: The ref checked against (may be upstream if ahead of local)-fn delete_branch_if_safe(- repo: &Repository,- branch_name: &str,- target: &str,- force_delete: bool,-) -> anyhow::Result<BranchDeletionResult> {- let IntegrationResult {- reason,- effective_target,- } = get_integration_reason(repo, branch_name, target);-- // Determine outcome based on integration and force flag- let outcome = match (reason, force_delete) {- (Some(r), _) => {- repo.run_command(&["branch", "-D", branch_name])?;- BranchDeletionOutcome::Integrated(r)- }- (None, true) => {- repo.run_command(&["branch", "-D", branch_name])?;- BranchDeletionOutcome::ForceDeleted- }- (None, false) => BranchDeletionOutcome::NotDeleted,- };-- Ok(BranchDeletionResult {- outcome,- effective_target,- })-}-/// Handle the result of a branch deletion attempt.////// Shows appropriate messages for non-deleted branches:@@ -751,60 +659,6 @@ pub fn execute_user_command(command: &str) -> anyhow::Result<()> {Ok(())}-/// Build shell command for background worktree removal-///-/// `branch_to_delete` is the branch to delete after removing the worktree.-/// Pass `None` for detached HEAD or when branch should be retained.-/// This decision is computed upfront (checking if branch is merged) before spawning the background process.-///-/// `force_worktree` adds `--force` to `git worktree remove`, allowing removal-/// even when the worktree contains untracked files (like build artifacts).-fn build_remove_command(- worktree_path: &std::path::Path,- branch_to_delete: Option<&str>,- force_worktree: bool,-) -> String {- use shell_escape::escape;-- let worktree_path_str = worktree_path.to_string_lossy();- let worktree_escaped = escape(worktree_path_str.as_ref().into());-- // TODO: This delay is a timing-based workaround, not a principled fix.- // The race: after wt exits, the shell wrapper reads the directive file and- // runs `cd`. But fish (and other shells) may call getcwd() before the cd- // completes (e.g., for prompt updates), and if the background removal has- // already deleted the directory, we get "shell-init: error retrieving current- // directory". A 1s delay is very conservative (shell cd takes ~1-5ms), but- // deterministic solutions (shell-spawned background, marker file sync) add- // significant complexity for marginal benefit.- let delay = "sleep 1";-- // Stop fsmonitor daemon first (best effort - ignore errors)- // This prevents zombie daemons from accumulating when using builtin fsmonitor- let stop_fsmonitor = format!(- "git -C {} fsmonitor--daemon stop 2>/dev/null || true",- worktree_escaped- );-- let force_flag = if force_worktree { " --force" } else { "" };-- match branch_to_delete {- Some(branch_name) => {- let branch_escaped = escape(branch_name.into());- format!(- "{} && {} && git worktree remove{} {} && git branch -D {}",- delay, stop_fsmonitor, force_flag, worktree_escaped, branch_escaped- )- }- None => {- format!(- "{} && {} && git worktree remove{} {}",- delay, stop_fsmonitor, force_flag, worktree_escaped- )- }- }-}-/// Handle output for a remove operation////// Approval is handled at the gate (command entry point), not here.@@ -1338,57 +1192,4 @@ mod tests {let hint = shell_integration_hint();assert!(hint.contains("wt config shell install"));}-- #[test]- fn test_build_remove_command() {- let path = PathBuf::from("/tmp/test-worktree");-- // Without branch deletion, without force- let cmd = build_remove_command(&path, None, false);- assert!(cmd.contains("git worktree remove"));- assert!(cmd.contains("/tmp/test-worktree"));- assert!(!cmd.contains("branch -D"));- assert!(!cmd.contains("--force"));-- // With branch deletion, without force- let cmd = build_remove_command(&path, Some("feature-branch"), false);- assert!(cmd.contains("git worktree remove"));- assert!(cmd.contains("git branch -D"));- assert!(cmd.contains("feature-branch"));- assert!(!cmd.contains("--force"));-- // With force flag- let cmd = build_remove_command(&path, None, true);- assert!(cmd.contains("git worktree remove --force"));-- // With branch deletion and force- let cmd = build_remove_command(&path, Some("feature-branch"), true);- assert!(cmd.contains("git worktree remove --force"));- assert!(cmd.contains("git branch -D"));-- // Shell escaping for special characters- let special_path = PathBuf::from("/tmp/test worktree");- let cmd = build_remove_command(&special_path, Some("feature/branch"), false);- assert!(cmd.contains("worktree remove"));- }-- #[test]- fn test_branch_deletion_outcome_matching() {- // Ensure the match patterns work correctly- let outcomes = [- (BranchDeletionOutcome::NotDeleted, false),- (BranchDeletionOutcome::ForceDeleted, true),- (- BranchDeletionOutcome::Integrated(IntegrationReason::SameCommit),- true,- ),- ];- for (outcome, expected_deleted) in outcomes {- let deleted = matches!(- outcome,- BranchDeletionOutcome::ForceDeleted | BranchDeletionOutcome::Integrated(_)- );- assert_eq!(deleted, expected_deleted);- }- }}