Skip to content

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

refactor(cli): extract reusable hook pipeline and refine CLI argument parsing

Maximilian Roos09d977b1ec65
diff --git a/src/cli.rs b/src/cli.rs
new file mode 100644
index 000000000..551ecaa88
--- /dev/null
+++ b/src/cli.rs
@@ -0,0 +1,450 @@
+use clap::{ArgAction, Parser, Subcommand};
+use std::sync::OnceLock;
+use worktrunk::HookType;
+
+use crate::commands::Shell;
+
+fn version_str() -> &'static str {
+ static VERSION: OnceLock<String> = OnceLock::new();
+ VERSION.get_or_init(|| {
+ let git_version = env!("VERGEN_GIT_DESCRIBE");
+ let cargo_version = env!("CARGO_PKG_VERSION");
+
+ if git_version.contains("IDEMPOTENT") {
+ cargo_version.to_string()
+ } else {
+ git_version.to_string()
+ }
+ })
+}
+
+#[derive(Debug, Clone, Copy, clap::ValueEnum)]
+pub enum OutputFormat {
+ /// Human-readable table format
+ Table,
+ /// Machine-readable JSON with display fields (includes styled unicode for rendering)
+ Json,
+}
+
+#[derive(Parser)]
+#[command(name = "wt")]
+#[command(about = "Git worktree management", long_about = None)]
+#[command(version = version_str())]
+#[command(disable_help_subcommand = true)]
+pub struct Cli {
+ /// Enable verbose output (show git commands and debug info)
+ #[arg(long, short = 'v', global = true)]
+ pub verbose: bool,
+
+ /// Use internal mode (outputs directives for shell wrapper)
+ #[arg(long, global = true, hide = true)]
+ pub internal: bool,
+
+ #[command(subcommand)]
+ pub command: Commands,
+}
+
+#[derive(Subcommand)]
+pub enum ConfigCommand {
+ /// Initialize global configuration file with examples
+ Init,
+ /// List all configuration files and their locations
+ List,
+ /// Show setup guide for AI-generated commit messages
+ Help,
+ /// Refresh the cached default branch by querying the remote
+ RefreshCache,
+ /// Configure shell by writing to config files
+ Shell {
+ /// Specific shell to configure (default: all shells with existing config files)
+ #[arg(long, value_enum)]
+ shell: Option<Shell>,
+
+ /// Skip confirmation prompt
+ #[arg(short, long)]
+ force: bool,
+ },
+}
+
+#[derive(Subcommand)]
+pub enum BetaCommand {
+ /// Run a project hook for testing
+ RunHook {
+ /// Hook type to run
+ hook_type: HookType,
+
+ /// Skip command approval prompts
+ #[arg(short, long)]
+ force: bool,
+ },
+
+ /// Commit changes with LLM-generated message
+ Commit {
+ /// Skip command approval prompts
+ #[arg(short, long)]
+ force: bool,
+
+ /// Skip all project hooks (pre-commit-command)
+ #[arg(long)]
+ no_verify: bool,
+ },
+
+ /// Squash commits with LLM-generated message
+ Squash {
+ /// Target branch to squash against (defaults to default branch)
+ target: Option<String>,
+
+ /// Skip command approval prompts
+ #[arg(short, long)]
+ force: bool,
+
+ /// Skip all project hooks (pre-commit-command, pre-merge-command)
+ #[arg(long)]
+ no_verify: bool,
+ },
+
+ /// Push changes to target branch
+ Push {
+ /// Target branch (defaults to default branch)
+ target: Option<String>,
+
+ /// Allow pushing merge commits (non-linear history)
+ #[arg(long)]
+ allow_merge_commits: bool,
+ },
+
+ /// Rebase current branch onto target branch
+ Rebase {
+ /// Target branch to rebase onto (defaults to default branch)
+ target: Option<String>,
+ },
+
+ /// Approve commands in the project config (shows unapproved by default)
+ AskApprovals {
+ /// Skip command approval prompts
+ #[arg(short, long)]
+ force: bool,
+
+ /// Show all commands including already-approved ones
+ #[arg(long)]
+ all: bool,
+ },
+
+ /// Interactive worktree selector
+ ///
+ /// Preview modes (toggle with 1/2/3):
+ /// - Mode 1: Working tree changes
+ /// - Mode 2: History (commits not on main shown bright, commits on main dimmed)
+ /// - Mode 3: Branch diff (line changes ahead of main)
+ ///
+ /// Note: When viewing main itself, all commits shown without dimming
+ #[cfg(unix)]
+ Select,
+}
+
+#[derive(Subcommand)]
+pub enum Commands {
+ /// Generate shell integration code
+ Init {
+ /// Shell to generate code for
+ shell: Shell,
+ },
+
+ /// Manage configuration
+ Config {
+ #[command(subcommand)]
+ action: ConfigCommand,
+ },
+
+ /// Development and testing utilities
+ #[command(hide = true)]
+ Beta {
+ #[command(subcommand)]
+ action: BetaCommand,
+ },
+
+ /// List worktrees and optionally branches
+ #[command(after_help = r#"COLUMNS:
+ Branch: Branch name
+ Status: Quick status symbols (see STATUS SYMBOLS below)
+ HEAD±: Uncommitted changes vs HEAD (+added -deleted lines, staged + unstaged)
+ main↕: Commit count ahead↑/behind↓ relative to main (commits in HEAD vs main)
+ main…± (--full): Line diffs in commits ahead of main (+added -deleted)
+ Path: Worktree directory location
+ Remote↕: Commits ahead↑/behind↓ relative to tracking branch (e.g. origin/branch)
+ CI (--full): CI pipeline status (tries PR/MR checks first, falls back to branch workflows)
+ ● passed (green) - All checks passed
+ ● running (blue) - Checks in progress
+ ● failed (red) - Checks failed
+ ● conflicts (yellow) - Merge conflicts with base
+ ● no-ci (gray) - PR/MR or workflow found but no checks configured
+ (blank) - No PR/MR or workflow found, or gh/glab CLI unavailable
+ (dimmed) - Stale: unpushed local changes differ from PR/MR head
+ Commit: Short commit hash (8 chars)
+ Age: Time since last commit (relative)
+ Message: Last commit message (truncated)
+
+STATUS SYMBOLS (order: = ≡∅ ↻⋈ ◇⊠⚠ ↑↓ ⇡⇣ ?!+»✘):
+ · Branch without worktree (no working directory to check)
+ = Merge conflicts (unmerged paths in working tree)
+ ≡ Working tree matches main (identical contents, regardless of commit history)
+ ∅ No commits (no commits ahead AND no uncommitted changes)
+ ↻ Rebase in progress
+ ⋈ Merge in progress
+ ◇ Bare worktree (no working directory)
+ ⊠ Locked worktree
+ ⚠ Prunable worktree
+ ↑ Ahead of main branch
+ ↓ Behind main branch
+ ⇡ Ahead of remote tracking branch
+ ⇣ Behind remote tracking branch
+ ? Untracked files present
+ ! Modified files (unstaged changes)
+ + Staged files (ready to commit)
+ » Renamed files
+ ✘ Deleted files
+
+Rows are dimmed when no unique work (≡ matches main OR ∅ no commits)."#)]
+ List {
+ /// Output format
+ #[arg(long, value_enum, default_value = "table")]
+ format: OutputFormat,
+
+ /// Include branches without worktrees
+ #[arg(long)]
+ branches: bool,
+
+ /// Show CI status, conflict detection, and complete diff statistics
+ ///
+ /// Adds columns: CI (pipeline status), main…± (line diffs).
+ /// Enables conflict detection (shows "=" symbol in Status column).
+ /// Requires network requests and git merge-tree operations.
+ #[arg(long, verbatim_doc_comment)]
+ full: bool,
+ },
+
+ /// Switch to a worktree
+ #[command(after_help = r#"BEHAVIOR:
+
+Switching to Existing Worktree:
+ - If worktree exists for branch, changes directory to it
+ - No hooks run
+ - No branch creation
+
+Creating New Worktree (--create):
+ 1. Creates new branch (defaults to current default branch as base)
+ 2. Creates worktree in parallel directory (../<branch>)
+ 3. Runs post-create hooks sequentially (blocking)
+ 4. Shows success message
+ 5. Spawns post-start hooks in background (non-blocking)
+ 6. Changes directory to new worktree
+
+HOOKS:
+
+post-create (sequential, blocking):
+ - Run after worktree creation, before success message
+ - Typically: npm install, cargo build, setup tasks
+ - Failures block the operation
+ - Skip with --no-verify
+
+post-start (parallel, background):
+ - Spawned after success message shown
+ - Typically: dev servers, file watchers, editors
+ - Run in background, failures logged but don't block
+ - Skip with --no-verify
+
+EXAMPLES:
+
+Switch to existing worktree:
+ wt switch feature-branch
+
+Create new worktree from main:
+ wt switch --create new-feature
+
+Switch to previous worktree:
+ wt switch -
+
+Create from specific base:
+ wt switch --create hotfix --base production
+
+Create and run command:
+ wt switch --create docs --execute "code ."
+
+Skip hooks during creation:
+ wt switch --create temp --no-verify"#)]
+ Switch {
+ /// Branch name, worktree path, '@' for current HEAD, or '-' for previous branch
+ branch: String,
+
+ /// Create a new branch
+ #[arg(short = 'c', long)]
+ create: bool,
+
+ /// Base branch to create from (only with --create). Use '@' for current HEAD
+ #[arg(short = 'b', long)]
+ base: Option<String>,
+
+ /// Execute command after switching
+ #[arg(short = 'x', long)]
+ execute: Option<String>,
+
+ /// Skip confirmation prompt
+ #[arg(short = 'f', long)]
+ force: bool,
+
+ /// Skip all project hooks (post-create, post-start)
+ #[arg(long)]
+ no_verify: bool,
+ },
+
+ /// Finish current worktree, returning to primary if current
+ #[command(after_help = r#"BEHAVIOR:
+
+Remove Current Worktree (no arguments):
+ - Requires clean working tree (no uncommitted changes)
+ - If in worktree: removes it and switches to primary worktree
+ - If in primary worktree: switches to default branch (e.g., main)
+ - If already on default branch in primary: does nothing
+
+Remove Specific Worktree (by name):
+ - Requires target worktree has clean working tree
+ - Removes specified worktree(s) and associated branches
+ - If removing current worktree, switches to primary first
+ - Can remove multiple worktrees in one command
+
+Remove Multiple Worktrees:
+ - When removing multiple, current worktree is removed last
+ - Prevents deleting directory you're currently in
+ - Each worktree must have clean working tree
+
+CLEANUP:
+
+When removing a worktree (by default):
+ 1. Validates worktree has no uncommitted changes
+ 2. Changes directory (if removing current worktree)
+ 3. Deletes worktree directory
+ 4. Removes git worktree metadata
+ 5. Deletes associated branch (uses git branch -d, safe delete)
+ - If branch has unmerged commits, shows warning but continues
+ - Use --no-delete-branch to skip branch deletion
+
+EXAMPLES:
+
+Remove current worktree and branch:
+ wt remove
+
+Remove specific worktree and branch:
+ wt remove feature-branch
+
+Remove worktree but keep branch:
+ wt remove --no-delete-branch feature-branch
+
+Remove multiple worktrees:
+ wt remove old-feature another-branch
+
+Switch to default in primary:
+ wt remove # (when already in primary worktree)"#)]
+ Remove {
+ /// Worktree names or branches to remove (use '@' for current, defaults to current if none specified)
+ worktrees: Vec<String>,
+
+ /// Don't delete the branch after removing the worktree (by default, branches are deleted)
+ #[arg(long = "no-delete-branch")]
+ no_delete_branch: bool,
+ },
+
+ /// Merge worktree into target branch
+ #[command(long_about = r#"Merge worktree into target branch
+
+LIFECYCLE
+
+The merge operation follows a strict order designed for fail-fast execution:
+
+1. Validate branches
+ Verifies current branch exists (not detached HEAD) and determines target branch
+ (defaults to repository's default branch).
+
+2. Auto-commit uncommitted changes
+ If working tree has uncommitted changes, stages all changes (git add -A) and commits
+ with LLM-generated message.
+
+3. Squash commits (default)
+ By default, counts commits since merge base with target branch. When multiple
+ commits exist, squashes them into one with LLM-generated message. Skip squashing
+ with --no-squash.
+
+4. Rebase onto target
+ Rebases current branch onto target branch. Detects conflicts and aborts if found.
+ This fails fast before running expensive checks.
+
+5. Run pre-merge commands
+ Runs commands from project config's [pre-merge-command] after rebase completes.
+ These receive {target} placeholder for the target branch. Commands run sequentially
+ and any failure aborts the merge immediately. Skip with --no-verify.
+
+6. Push to target
+ Fast-forward pushes to target branch. Rejects non-fast-forward pushes (ensures
+ linear history).
+
+7. Clean up worktree and branch
+ Removes current worktree, deletes the branch, and switches primary worktree to target
+ branch if needed. Skip removal with --no-remove.
+
+EXAMPLES
+
+Basic merge to main:
+ wt merge
+
+Merge without squashing:
+ wt merge --no-squash
+
+Keep worktree after merging:
+ wt merge --no-remove
+
+Skip pre-merge commands:
+ wt merge --no-verify"#)]
+ Merge {
+ /// Target branch to merge into (defaults to default branch)
+ target: Option<String>,
+
+ /// Disable squashing commits (by default, commits are squashed into one before merging)
+ #[arg(long = "no-squash", action = ArgAction::SetFalse, default_value_t = true)]
+ squash_enabled: bool,
+
+ /// Push commits as-is without transformations (requires clean tree; implies --no-squash, --no-remove, and skips rebase)
+ #[arg(long)]
+ no_commit: bool,
+
+ /// Keep worktree after merging (don't remove)
+ #[arg(long = "no-remove")]
+ no_remove: bool,
+
+ /// Skip all project hooks (pre-merge-command)
+ #[arg(long)]
+ no_verify: bool,
+
+ /// Skip approval prompts for commands
+ #[arg(short, long)]
+ force: bool,
+
+ /// Only stage tracked files (git add -u) instead of all files (git add -A)
+ #[arg(long)]
+ tracked_only: bool,
+ },
+
+ /// Generate shell completion script (deprecated - use init instead)
+ #[command(hide = true)]
+ Completion {
+ /// Shell to generate completions for
+ #[arg(value_enum)]
+ shell: Shell,
+ },
+
+ /// Internal completion helper (hidden)
+ #[command(hide = true)]
+ Complete {
+ /// Arguments to complete
+ #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
+ args: Vec<String>,
+ },
+}
diff --git a/src/commands/hooks.rs b/src/commands/hooks.rs
new file mode 100644
index 000000000..6cc4d72cb
--- /dev/null
+++ b/src/commands/hooks.rs
@@ -0,0 +1,138 @@
+use worktrunk::HookType;
+use worktrunk::config::{CommandConfig, CommandPhase, WorktrunkConfig};
+use worktrunk::git::{GitError, Repository};
+use worktrunk::styling::{CYAN, WARNING, WARNING_BOLD, format_bash_with_gutter};
+
+use super::command_executor::{CommandContext, PreparedCommand, prepare_project_commands};
+use crate::commands::process::spawn_detached;
+use crate::output::execute_command_in_worktree;
+
+/// Controls how hook execution should respond to failures.
+pub enum HookFailureStrategy {
+ /// Stop on first failure and surface a `HookCommandFailed` error with the provided hook type.
+ FailFast { hook_type: HookType },
+ /// Log warnings and continue executing remaining commands.
+ Warn,
+}
+
+/// Helper for preparing and executing project hook commands.
+pub struct HookPipeline<'a> {
+ ctx: CommandContext<'a>,
+}
+
+impl<'a> HookPipeline<'a> {
+ pub fn new(
+ repo: &'a Repository,
+ config: &'a WorktrunkConfig,
+ branch: &'a str,
+ worktree_path: &'a std::path::Path,
+ repo_root: &'a std::path::Path,
+ force: bool,
+ ) -> Self {
+ Self {
+ ctx: CommandContext::new(repo, config, branch, worktree_path, repo_root, force),
+ }
+ }
+
+ fn prepare_commands(
+ &self,
+ command_config: &CommandConfig,
+ phase: CommandPhase,
+ auto_trust: bool,
+ extra_vars: &[(&str, &str)],
+ ) -> Result<Vec<PreparedCommand>, GitError> {
+ prepare_project_commands(command_config, &self.ctx, auto_trust, extra_vars, phase)
+ }
+
+ /// Run hook commands sequentially, using the provided failure strategy.
+ pub fn run_sequential(
+ &self,
+ command_config: &CommandConfig,
+ phase: CommandPhase,
+ auto_trust: bool,
+ extra_vars: &[(&str, &str)],
+ label_prefix: &str,
+ failure_strategy: HookFailureStrategy,
+ ) -> Result<(), GitError> {
+ let commands = self.prepare_commands(command_config, phase, auto_trust, extra_vars)?;
+ if commands.is_empty() {
+ return Ok(());
+ }
+
+ for prepared in commands {
+ let label =
+ crate::commands::format_command_label(label_prefix, prepared.name.as_deref());
+ crate::output::progress(format!("{CYAN}{label}:{CYAN:#}"))?;
+ crate::output::gutter(format_bash_with_gutter(&prepared.expanded, ""))?;
+
+ if let Err(err) =
+ execute_command_in_worktree(self.ctx.worktree_path, &prepared.expanded)
+ {
+ let err_msg = err.to_string();
+ match &failure_strategy {
+ HookFailureStrategy::FailFast { hook_type } => {
+ let exit_code = match &err {
+ GitError::ChildProcessExited { code, .. } => Some(*code),
+ _ => None,
+ };
+ return Err(GitError::HookCommandFailed {
+ hook_type: *hook_type,
+ command_name: prepared.name.clone(),
+ error: err_msg,
+ exit_code,
+ });
+ }
+ HookFailureStrategy::Warn => {
+ let message = match &prepared.name {
+ Some(name) => format!(
+ "{WARNING}Command {WARNING_BOLD}{name}{WARNING_BOLD:#} failed: {err_msg}{WARNING:#}"
+ ),
+ None => format!("{WARNING}Command failed: {err_msg}{WARNING:#}"),
+ };
+ crate::output::warning(message)?;
+ }
+ }
+ }
+ }
+
+ crate::output::flush()?;
+ Ok(())
+ }
+
+ /// Spawn hook commands in the background (used for post-start hooks).
+ pub fn spawn_detached(
+ &self,
+ command_config: &CommandConfig,
+ phase: CommandPhase,
+ auto_trust: bool,
+ extra_vars: &[(&str, &str)],
+ label_prefix: &str,
+ ) -> Result<(), GitError> {
+ let commands = self.prepare_commands(command_config, phase, auto_trust, extra_vars)?;
+ if commands.is_empty() {
+ return Ok(());
+ }
+
+ for prepared in commands {
+ let label =
+ crate::commands::format_command_label(label_prefix, prepared.name.as_deref());
+ crate::output::progress(format!("{CYAN}{label}:{CYAN:#}"))?;
+ crate::output::gutter(format_bash_with_gutter(&prepared.expanded, ""))?;
+
+ let name = prepared.name.as_deref().unwrap_or("cmd");
+ if let Err(err) = spawn_detached(self.ctx.worktree_path, &prepared.expanded, name) {
+ let err_msg = err.to_string();
+ let message = match &prepared.name {
+ Some(name) => {
+ format!("{WARNING}Failed to spawn '{name}': {err_msg}{WARNING:#}")
+ }
+ None => format!("{WARNING}Failed to spawn command: {err_msg}{WARNING:#}"),
+ };
+ crate::output::warning(message)?;
+ }
+ }
+
+ crate::output::flush()?;
+ Ok(())
+ }
+}
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index 0b45aa450..579778156 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -4,15 +4,14 @@ use worktrunk::config::{Command, CommandPhase, ProjectConfig, WorktrunkConfig};
use worktrunk::git::{GitError, GitResultExt, Repository};
use worktrunk::styling::{
AnstyleStyle, CYAN, CYAN_BOLD, ERROR, ERROR_EMOJI, GREEN_BOLD, HINT, HINT_EMOJI, WARNING,
- WARNING_BOLD, format_bash_with_gutter, format_with_gutter,
+ format_with_gutter,
};
use super::command_approval::approve_command_batch;
-use super::command_executor::{CommandContext, prepare_project_commands};
use super::context::CommandEnv;
+use super::hooks::{HookFailureStrategy, HookPipeline};
use super::project_config::load_project_config;
use super::worktree::handle_push;
-use crate::output::execute_command_in_worktree;
/// Context for collecting merge commands
struct MergeCommandCollector<'a> {
@@ -475,7 +474,7 @@ pub fn run_pre_merge_commands(
};
let repo_root = repo.worktree_base()?;
- let ctx = CommandContext::new(
+ let pipeline = HookPipeline::new(
repo,
config,
current_branch,
@@ -483,36 +482,17 @@ pub fn run_pre_merge_commands(
&repo_root,
force,
);
- let commands = prepare_project_commands(
+
+ pipeline.run_sequential(
pre_merge_config,
- &ctx,
+ CommandPhase::PreMerge,
true, // auto_trust: commands already approved in batch
&[("target", target_branch)],
- CommandPhase::PreMerge,
- )?;
- for prepared in commands {
- let label = crate::commands::format_command_label("pre-merge", prepared.name.as_deref());
- crate::output::progress(format!("{CYAN}{label}:{CYAN:#}"))?;
- crate::output::gutter(format_bash_with_gutter(&prepared.expanded, ""))?;
-
- if let Err(e) = execute_command_in_worktree(worktree_path, &prepared.expanded) {
- // Extract exit code from ChildProcessExited to preserve signal information
- let exit_code = match &e {
- GitError::ChildProcessExited { code, .. } => Some(*code),
- _ => None,
- };
- return Err(GitError::HookCommandFailed {
- hook_type: HookType::PreMerge,
- command_name: prepared.name.clone(),
- error: e.to_string(),
- exit_code,
- });
- }
-
- // No need to flush here - the redirect in execute_command_in_worktree ensures ordering
- }
-
- Ok(())
+ "pre-merge",
+ HookFailureStrategy::FailFast {
+ hook_type: HookType::PreMerge,
+ },
+ )
}
/// Execute post-merge commands sequentially in the main worktree (blocking)
@@ -524,8 +504,6 @@ pub fn execute_post_merge_commands(
target_branch: &str,
force: bool,
) -> Result<(), GitError> {
- use worktrunk::styling::WARNING;
-
// Load project config from the main worktree path directly
let project_config = match load_project_config(repo)? {
Some(cfg) => cfg,
@@ -536,7 +514,7 @@ pub fn execute_post_merge_commands(
return Ok(());
};
- let ctx = CommandContext::new(
+ let pipeline = HookPipeline::new(
repo,
config,
branch,
@@ -544,39 +522,15 @@ pub fn execute_post_merge_commands(
main_worktree_path,
force,
);
- let commands = prepare_project_commands(
+
+ pipeline.run_sequential(
post_merge_config,
- &ctx,
+ CommandPhase::PostMerge,
true, // auto_trust: commands already approved in batch
&[("target", target_branch)],
- CommandPhase::PostMerge,
- )?;
-
- if commands.is_empty() {
- return Ok(());
- }
-
- // Execute each command sequentially in the main worktree
- for prepared in commands {
- let label = crate::commands::format_command_label("post-merge", prepared.name.as_deref());
- crate::output::progress(format!("{CYAN}{label}:{CYAN:#}"))?;
- crate::output::gutter(format_bash_with_gutter(&prepared.expanded, ""))?;
-
- if let Err(e) = execute_command_in_worktree(main_worktree_path, &prepared.expanded) {
- let message = match &prepared.name {
- Some(name) => format!(
- "{WARNING}Command {WARNING_BOLD}{name}{WARNING_BOLD:#} failed: {e}{WARNING:#}"
- ),
- None => format!("{WARNING}Command failed: {e}{WARNING:#}"),
- };
- crate::output::warning(message)?;
- // Continue with other commands even if one fails
- }
- }
-
- crate::output::flush()?;
-
- Ok(())
+ "post-merge",
+ HookFailureStrategy::Warn,
+ )
}
/// Run pre-commit commands sequentially (blocking, fail-fast)
@@ -596,7 +550,7 @@ pub fn run_pre_commit_commands(
};
let repo_root = repo.worktree_base()?;
- let ctx = CommandContext::new(
+ let pipeline = HookPipeline::new(
repo,
config,
current_branch,
@@ -605,47 +559,19 @@ pub fn run_pre_commit_commands(
force,
);
- // Build extra variables - include target if provided
- let extra_vars: Vec<(&str, &str)> = if let Some(target) = target_branch {
- vec![("target", target)]
- } else {
- vec![]
- };
+ let extra_vars: Vec<(&str, &str)> = target_branch
+ .into_iter()
+ .map(|target| ("target", target))
+ .collect();
- let commands = prepare_project_commands(
+ pipeline.run_sequential(
pre_commit_config,
- &ctx,
+ CommandPhase::PreCommit,
auto_trust,
&extra_vars,
- CommandPhase::PreCommit,
- )?;
-
- if commands.is_empty() {
- return Ok(());
- }
-
- // Execute each command sequentially
- for prepared in commands {
- let label = crate::commands::format_command_label("pre-commit", prepared.name.as_deref());
- crate::output::progress(format!("{CYAN}{label}:{CYAN:#}"))?;
- crate::output::gutter(format_bash_with_gutter(&prepared.expanded, ""))?;
-
- if let Err(e) = execute_command_in_worktree(worktree_path, &prepared.expanded) {
- // Extract exit code from ChildProcessExited to preserve signal information
- let exit_code = match &e {
- GitError::ChildProcessExited { code, .. } => Some(*code),
- _ => None,
- };
- return Err(GitError::HookCommandFailed {
- hook_type: HookType::PreCommit,
- command_name: prepared.name.clone(),
- error: e.to_string(),
- exit_code,
- });
- }
- }
-
- crate::output::flush()?;
-
- Ok(())
+ "pre-commit",
+ HookFailureStrategy::FailFast {
+ hook_type: HookType::PreCommit,
+ },
+ )
}
diff --git a/src/commands/mod.rs b/src/commands/mod.rs
index e5f6ae2e9..b1ee2a24d 100644
--- a/src/commands/mod.rs
+++ b/src/commands/mod.rs
@@ -5,6 +5,7 @@ pub mod completion;
pub mod config;
pub mod configure_shell;
pub mod context;
+mod hooks;
pub mod init;
pub mod list;
pub mod merge;
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rs
index f48610b89..d734034ad 100644
--- a/src/commands/worktree.rs
+++ b/src/commands/worktree.rs
@@ -101,15 +101,10 @@
use std::path::PathBuf;
use worktrunk::config::{CommandPhase, WorktrunkConfig};
use worktrunk::git::{GitError, GitResultExt, Repository};
-use worktrunk::styling::{
- CYAN, CYAN_BOLD, GREEN, GREEN_BOLD, WARNING, WARNING_BOLD, format_bash_with_gutter,
- format_with_gutter,
-};
+use worktrunk::styling::{CYAN, CYAN_BOLD, GREEN, GREEN_BOLD, WARNING, format_with_gutter};
-use super::command_executor::{CommandContext, prepare_project_commands};
+use super::hooks::{HookFailureStrategy, HookPipeline};
use super::project_config::load_project_config;
-use crate::commands::process::spawn_detached;
-use crate::output::execute_command_in_worktree;
/// Result of a worktree switch operation
pub enum SwitchResult {
@@ -488,40 +483,15 @@ pub fn execute_post_create_commands(
};
let repo_root = repo.worktree_base()?;
- let ctx = CommandContext::new(repo, config, branch, worktree_path, &repo_root, force);
- let commands = prepare_project_commands(
+ let pipeline = HookPipeline::new(repo, config, branch, worktree_path, &repo_root, force);
+ pipeline.run_sequential(
post_create_config,
- &ctx,
+ CommandPhase::PostCreate,
false,
&[],
- CommandPhase::PostCreate,
- )?;
-
- if commands.is_empty() {
- return Ok(());
- }
-
- // Execute each command sequentially
- for prepared in commands {
- let label = crate::commands::format_command_label("post-create", prepared.name.as_deref());
- crate::output::progress(format!("{CYAN}{label}:{CYAN:#}"))?;
- crate::output::gutter(format_bash_with_gutter(&prepared.expanded, ""))?;
-
- if let Err(e) = execute_command_in_worktree(worktree_path, &prepared.expanded) {
- let message = match &prepared.name {
- Some(name) => format!(
- "{WARNING}Command {WARNING_BOLD}{name}{WARNING_BOLD:#} failed: {e}{WARNING:#}"
- ),
- None => format!("{WARNING}Command failed: {e}{WARNING:#}"),
- };
- crate::output::warning(message)?;
- // Continue with other commands even if one fails
- }
- }
-
- crate::output::flush()?;
-
- Ok(())
+ "post-create",
+ HookFailureStrategy::Warn,
+ )
}
/// Spawn post-start commands in parallel as background processes (non-blocking)
@@ -542,43 +512,14 @@ pub fn spawn_post_start_commands(
};
let repo_root = repo.worktree_base()?;
- let ctx = CommandContext::new(repo, config, branch, worktree_path, &repo_root, force);
- let commands =
- prepare_project_commands(post_start_config, &ctx, false, &[], CommandPhase::PostStart)?;
-
- if commands.is_empty() {
- return Ok(());
- }
-
- // Spawn each command as a detached background process
- for prepared in commands {
- let label = crate::commands::format_command_label("post-start", prepared.name.as_deref());
- crate::output::progress(format!("{CYAN}{label}:{CYAN:#}"))?;
- crate::output::gutter(format_bash_with_gutter(&prepared.expanded, ""))?;
-
- let name = prepared.name.as_deref().unwrap_or("cmd");
- match spawn_detached(worktree_path, &prepared.expanded, name) {
- Ok(_log_path) => {
- // Background command spawned successfully
- // Log file path not shown - only needed for debugging failures
- }
- Err(e) => {
- let message = match &prepared.name {
- Some(name) => {
- format!("{WARNING}Failed to spawn '{name}': {e}{WARNING:#}")
- }
- None => {
- format!("{WARNING}Failed to spawn command: {e}{WARNING:#}")
- }
- };
- crate::output::warning(message)?;
- }
- }
- }
-
- crate::output::flush()?;
-
- Ok(())
+ let pipeline = HookPipeline::new(repo, config, branch, worktree_path, &repo_root, force);
+ pipeline.spawn_detached(
+ post_start_config,
+ CommandPhase::PostStart,
+ false,
+ &[],
+ "post-start",
+ )
}
/// Execute post-start commands sequentially (blocking) - for testing
@@ -599,34 +540,15 @@ pub fn execute_post_start_commands_sequential(
};
let repo_root = repo.worktree_base()?;
- let ctx = CommandContext::new(repo, config, branch, worktree_path, &repo_root, force);
- let commands =
- prepare_project_commands(post_start_config, &ctx, false, &[], CommandPhase::PostStart)?;
-
- if commands.is_empty() {
- return Ok(());
- }
-
- // Execute sequentially for testing
- for prepared in commands {
- let label = crate::commands::format_command_label("post-start", prepared.name.as_deref());
- crate::output::progress(format!("{CYAN}{label}:{CYAN:#}"))?;
- crate::output::gutter(format_bash_with_gutter(&prepared.expanded, ""))?;
-
- if let Err(e) = execute_command_in_worktree(worktree_path, &prepared.expanded) {
- let message = match &prepared.name {
- Some(name) => {
- format!("{WARNING}Failed to execute '{name}': {e}{WARNING:#}")
- }
- None => format!("{WARNING}Command failed: {e}{WARNING:#}"),
- };
- crate::output::warning(message)?;
- }
- }
-
- crate::output::flush()?;
-
- Ok(())
+ let pipeline = HookPipeline::new(repo, config, branch, worktree_path, &repo_root, force);
+ pipeline.run_sequential(
+ post_start_config,
+ CommandPhase::PostStart,
+ false,
+ &[],
+ "post-start",
+ HookFailureStrategy::Warn,
+ )
}
/// Push changes to target branch
diff --git a/src/main.rs b/src/main.rs
index 5bf50b456..82946370a 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,38 +1,23 @@
use anstyle::Style;
-use clap::{ArgAction, CommandFactory, Parser, Subcommand};
+use clap::{CommandFactory, Parser};
use std::process;
-use std::sync::OnceLock;
-use worktrunk::HookType;
use worktrunk::config::WorktrunkConfig;
use worktrunk::git::{GitError, GitResultExt, Repository};
use worktrunk::styling::{SUCCESS_EMOJI, println};
-/// Get the version string, trying git describe first, falling back to Cargo version
-fn version_str() -> &'static str {
- static VERSION: OnceLock<String> = OnceLock::new();
- VERSION.get_or_init(|| {
- let git_version = env!("VERGEN_GIT_DESCRIBE");
- let cargo_version = env!("CARGO_PKG_VERSION");
-
- // Try to use git describe, fall back to Cargo version if it's the idempotent placeholder
- if git_version.contains("IDEMPOTENT") {
- cargo_version.to_string()
- } else {
- git_version.to_string()
- }
- })
-}
-
+mod cli;
mod commands;
mod display;
mod llm;
mod output;
+pub use crate::cli::OutputFormat;
+
#[cfg(unix)]
use commands::handle_select;
use commands::worktree::SwitchResult;
use commands::{
- ConfigAction, Shell, handle_beta_ask_approvals, handle_beta_commit, handle_beta_push,
+ ConfigAction, handle_beta_ask_approvals, handle_beta_commit, handle_beta_push,
handle_beta_rebase, handle_beta_run_hook, handle_beta_squash, handle_complete,
handle_completion, handle_config_help, handle_config_init, handle_config_list,
handle_config_refresh_cache, handle_configure_shell, handle_init, handle_list, handle_merge,
@@ -40,439 +25,7 @@ use commands::{
};
use output::{execute_user_command, handle_remove_output, handle_switch_output};
-#[derive(Debug, Clone, Copy, clap::ValueEnum)]
-pub enum OutputFormat {
- /// Human-readable table format
- Table,
- /// Machine-readable JSON with display fields (includes styled unicode for rendering)
- Json,
-}
-
-#[derive(Parser)]
-#[command(name = "wt")]
-#[command(about = "Git worktree management", long_about = None)]
-#[command(version = version_str())]
-#[command(disable_help_subcommand = true)]
-struct Cli {
- /// Enable verbose output (show git commands and debug info)
- #[arg(long, short = 'v', global = true)]
- verbose: bool,
-
- /// Use internal mode (outputs directives for shell wrapper)
- #[arg(long, global = true, hide = true)]
- internal: bool,
-
- #[command(subcommand)]
- command: Commands,
-}
-
-#[derive(Subcommand)]
-enum ConfigCommand {
- /// Initialize global configuration file with examples
- Init,
- /// List all configuration files and their locations
- List,
- /// Show setup guide for AI-generated commit messages
- Help,
- /// Refresh the cached default branch by querying the remote
- RefreshCache,
- /// Configure shell by writing to config files
- Shell {
- /// Specific shell to configure (default: all shells with existing config files)
- #[arg(long, value_enum)]
- shell: Option<Shell>,
-
- /// Skip confirmation prompt
- #[arg(short, long)]
- force: bool,
- },
-}
-
-#[derive(Subcommand)]
-enum BetaCommand {
- /// Run a project hook for testing
- RunHook {
- /// Hook type to run
- hook_type: HookType,
-
- /// Skip command approval prompts
- #[arg(short, long)]
- force: bool,
- },
-
- /// Commit changes with LLM-generated message
- Commit {
- /// Skip command approval prompts
- #[arg(short, long)]
- force: bool,
-
- /// Skip all project hooks (pre-commit-command)
- #[arg(long)]
- no_verify: bool,
- },
-
- /// Squash commits with LLM-generated message
- Squash {
- /// Target branch to squash against (defaults to default branch)
- target: Option<String>,
-
- /// Skip command approval prompts
- #[arg(short, long)]
- force: bool,
-
- /// Skip all project hooks (pre-commit-command, pre-merge-command)
- #[arg(long)]
- no_verify: bool,
- },
-
- /// Push changes to target branch
- Push {
- /// Target branch (defaults to default branch)
- target: Option<String>,
-
- /// Allow pushing merge commits (non-linear history)
- #[arg(long)]
- allow_merge_commits: bool,
- },
-
- /// Rebase current branch onto target branch
- Rebase {
- /// Target branch to rebase onto (defaults to default branch)
- target: Option<String>,
- },
-
- /// Approve commands in the project config (shows unapproved by default)
- AskApprovals {
- /// Skip command approval prompts
- #[arg(short, long)]
- force: bool,
-
- /// Show all commands including already-approved ones
- #[arg(long)]
- all: bool,
- },
-
- /// Interactive worktree selector
- ///
- /// Preview modes (toggle with 1/2/3):
- /// - Mode 1: Working tree changes
- /// - Mode 2: History (commits not on main shown bright, commits on main dimmed)
- /// - Mode 3: Branch diff (line changes ahead of main)
- ///
- /// Note: When viewing main itself, all commits shown without dimming
- #[cfg(unix)]
- Select,
-}
-
-#[derive(Subcommand)]
-enum Commands {
- /// Generate shell integration code
- Init {
- /// Shell to generate code for
- shell: Shell,
- },
-
- /// Manage configuration
- Config {
- #[command(subcommand)]
- action: ConfigCommand,
- },
-
- /// Development and testing utilities
- #[command(hide = true)]
- Beta {
- #[command(subcommand)]
- action: BetaCommand,
- },
-
- /// List worktrees and optionally branches
- #[command(after_help = "\
-COLUMNS:
- Branch: Branch name
- Status: Quick status symbols (see STATUS SYMBOLS below)
- HEAD±: Uncommitted changes vs HEAD (+added -deleted lines, staged + unstaged)
- main↕: Commit count ahead↑/behind↓ relative to main (commits in HEAD vs main)
- main…± (--full): Line diffs in commits ahead of main (+added -deleted)
- Path: Worktree directory location
- Remote↕: Commits ahead↑/behind↓ relative to tracking branch (e.g. origin/branch)
- CI (--full): CI pipeline status (tries PR/MR checks first, falls back to branch workflows)
- ● passed (green) - All checks passed
- ● running (blue) - Checks in progress
- ● failed (red) - Checks failed
- ● conflicts (yellow) - Merge conflicts with base
- ● no-ci (gray) - PR/MR or workflow found but no checks configured
- (blank) - No PR/MR or workflow found, or gh/glab CLI unavailable
- (dimmed) - Stale: unpushed local changes differ from PR/MR head
- Commit: Short commit hash (8 chars)
- Age: Time since last commit (relative)
- Message: Last commit message (truncated)
-
-STATUS SYMBOLS (order: = ≡∅ ↻⋈ ◇⊠⚠ ↑↓ ⇡⇣ ?!+»✘):
- · Branch without worktree (no working directory to check)
- = Merge conflicts (unmerged paths in working tree)
- ≡ Working tree matches main (identical contents, regardless of commit history)
- ∅ No commits (no commits ahead AND no uncommitted changes)
- ↻ Rebase in progress
- ⋈ Merge in progress
- ◇ Bare worktree (no working directory)
- ⊠ Locked worktree
- ⚠ Prunable worktree
- ↑ Ahead of main branch
- ↓ Behind main branch
- ⇡ Ahead of remote tracking branch
- ⇣ Behind remote tracking branch
- ? Untracked files present
- ! Modified files (unstaged changes)
- + Staged files (ready to commit)
- » Renamed files
- ✘ Deleted files
-
-Rows are dimmed when no unique work (≡ matches main OR ∅ no commits).")]
- List {
- /// Output format
- #[arg(long, value_enum, default_value = "table")]
- format: OutputFormat,
-
- /// Include branches without worktrees
- #[arg(long)]
- branches: bool,
-
- /// Show CI status, conflict detection, and complete diff statistics
- ///
- /// Adds columns: CI (pipeline status), main…± (line diffs).
- /// Enables conflict detection (shows "=" symbol in Status column).
- /// Requires network requests and git merge-tree operations.
- #[arg(long, verbatim_doc_comment)]
- full: bool,
- },
-
- /// Switch to a worktree
- #[command(after_help = "\
-BEHAVIOR:
-
-Switching to Existing Worktree:
- - If worktree exists for branch, changes directory to it
- - No hooks run
- - No branch creation
-
-Creating New Worktree (--create):
- 1. Creates new branch (defaults to current default branch as base)
- 2. Creates worktree in parallel directory (../<branch>)
- 3. Runs post-create hooks sequentially (blocking)
- 4. Shows success message
- 5. Spawns post-start hooks in background (non-blocking)
- 6. Changes directory to new worktree
-
-HOOKS:
-
-post-create (sequential, blocking):
- - Run after worktree creation, before success message
- - Typically: npm install, cargo build, setup tasks
- - Failures block the operation
- - Skip with --no-verify
-
-post-start (parallel, background):
- - Spawned after success message shown
- - Typically: dev servers, file watchers, editors
- - Run in background, failures logged but don't block
- - Skip with --no-verify
-
-EXAMPLES:
-
-Switch to existing worktree:
- wt switch feature-branch
-
-Create new worktree from main:
- wt switch --create new-feature
-
-Switch to previous worktree:
- wt switch -
-
-Create from specific base:
- wt switch --create hotfix --base production
-
-Create and run command:
- wt switch --create docs --execute \"code .\"
-
-Skip hooks during creation:
- wt switch --create temp --no-verify")]
- Switch {
- /// Branch name, worktree path, '@' for current HEAD, or '-' for previous branch
- branch: String,
-
- /// Create a new branch
- #[arg(short = 'c', long)]
- create: bool,
-
- /// Base branch to create from (only with --create). Use '@' for current HEAD
- #[arg(short = 'b', long)]
- base: Option<String>,
-
- /// Execute command after switching
- #[arg(short = 'x', long)]
- execute: Option<String>,
-
- /// Skip confirmation prompt
- #[arg(short = 'f', long)]
- force: bool,
-
- /// Skip all project hooks (post-create, post-start)
- #[arg(long)]
- no_verify: bool,
- },
-
- /// Finish current worktree, returning to primary if current
- #[command(after_help = "\
-BEHAVIOR:
-
-Remove Current Worktree (no arguments):
- - Requires clean working tree (no uncommitted changes)
- - If in worktree: removes it and switches to primary worktree
- - If in primary worktree: switches to default branch (e.g., main)
- - If already on default branch in primary: does nothing
-
-Remove Specific Worktree (by name):
- - Requires target worktree has clean working tree
- - Removes specified worktree(s) and associated branches
- - If removing current worktree, switches to primary first
- - Can remove multiple worktrees in one command
-
-Remove Multiple Worktrees:
- - When removing multiple, current worktree is removed last
- - Prevents deleting directory you're currently in
- - Each worktree must have clean working tree
-
-CLEANUP:
-
-When removing a worktree (by default):
- 1. Validates worktree has no uncommitted changes
- 2. Changes directory (if removing current worktree)
- 3. Deletes worktree directory
- 4. Removes git worktree metadata
- 5. Deletes associated branch (uses git branch -d, safe delete)
- - If branch has unmerged commits, shows warning but continues
- - Use --no-delete-branch to skip branch deletion
-
-EXAMPLES:
-
-Remove current worktree and branch:
- wt remove
-
-Remove specific worktree and branch:
- wt remove feature-branch
-
-Remove worktree but keep branch:
- wt remove --no-delete-branch feature-branch
-
-Remove multiple worktrees:
- wt remove old-feature another-branch
-
-Switch to default in primary:
- wt remove # (when already in primary worktree)")]
- Remove {
- /// Worktree names or branches to remove (use '@' for current, defaults to current if none specified)
- worktrees: Vec<String>,
-
- /// Don't delete the branch after removing the worktree (by default, branches are deleted)
- #[arg(long = "no-delete-branch")]
- no_delete_branch: bool,
- },
-
- /// Merge worktree into target branch
- #[command(long_about = "Merge worktree into target branch
-
-LIFECYCLE
-
-The merge operation follows a strict order designed for fail-fast execution:
-
-1. Validate branches
- Verifies current branch exists (not detached HEAD) and determines target branch
- (defaults to repository's default branch).
-
-2. Auto-commit uncommitted changes
- If working tree has uncommitted changes, stages all changes (git add -A) and commits
- with LLM-generated message.
-
-3. Squash commits (default)
- By default, counts commits since merge base with target branch. When multiple
- commits exist, squashes them into one with LLM-generated message. Skip squashing
- with --no-squash.
-
-4. Rebase onto target
- Rebases current branch onto target branch. Detects conflicts and aborts if found.
- This fails fast before running expensive checks.
-
-5. Run pre-merge commands
- Runs commands from project config's [pre-merge-command] after rebase completes.
- These receive {target} placeholder for the target branch. Commands run sequentially
- and any failure aborts the merge immediately. Skip with --no-verify.
-
-6. Push to target
- Fast-forward pushes to target branch. Rejects non-fast-forward pushes (ensures
- linear history).
-
-7. Clean up worktree and branch
- Removes current worktree, deletes the branch, and switches primary worktree to target
- branch if needed. Skip removal with --no-remove.
-
-EXAMPLES
-
-Basic merge to main:
- wt merge
-
-Merge without squashing:
- wt merge --no-squash
-
-Keep worktree after merging:
- wt merge --no-remove
-
-Skip pre-merge commands:
- wt merge --no-verify")]
- Merge {
- /// Target branch to merge into (defaults to default branch)
- target: Option<String>,
-
- /// Disable squashing commits (by default, commits are squashed into one before merging)
- #[arg(long = "no-squash", action = ArgAction::SetFalse, default_value_t = true)]
- squash_enabled: bool,
-
- /// Push commits as-is without transformations (requires clean tree; implies --no-squash, --no-remove, and skips rebase)
- #[arg(long)]
- no_commit: bool,
-
- /// Keep worktree after merging (don't remove)
- #[arg(long = "no-remove")]
- no_remove: bool,
-
- /// Skip all project hooks (pre-merge-command)
- #[arg(long)]
- no_verify: bool,
-
- /// Skip approval prompts for commands
- #[arg(short, long)]
- force: bool,
-
- /// Only stage tracked files (git add -u) instead of all files (git add -A)
- #[arg(long)]
- tracked_only: bool,
- },
-
- /// Generate shell completion script (deprecated - use init instead)
- #[command(hide = true)]
- Completion {
- /// Shell to generate completions for
- #[arg(value_enum)]
- shell: Shell,
- },
-
- /// Internal completion helper (hidden)
- #[command(hide = true)]
- Complete {
- /// Arguments to complete
- #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
- args: Vec<String>,
- },
-}
+use cli::{BetaCommand, Cli, Commands, ConfigCommand};
fn main() {
let cli = Cli::parse();