Skip to content

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

feat(dev): add 'run-hook' command to test project hooks

Maximilian Roos0ce14f0d166c
diff --git a/src/commands/dev.rs b/src/commands/dev.rs
new file mode 100644
index 000000000..8d310fa1a
--- /dev/null
+++ b/src/commands/dev.rs
@@ -0,0 +1,101 @@
+use worktrunk::config::{ProjectConfig, WorktrunkConfig};
+use worktrunk::git::{GitError, GitResultExt, Repository};
+use worktrunk::styling::{AnstyleStyle, HINT, HINT_EMOJI};
+
+use super::merge::{execute_post_merge_commands, run_pre_merge_commands};
+use super::worktree::{execute_post_create_commands, execute_post_start_commands_sequential};
+
+/// Handle `wt dev run-hook` command
+pub fn handle_dev_run_hook(hook_type: &str, force: bool) -> Result<(), GitError> {
+ // Derive context from current environment
+ let repo = Repository::current();
+ let worktree_path = std::env::current_dir()
+ .map_err(|e| GitError::CommandFailed(format!("Failed to get current directory: {}", e)))?;
+ let branch = repo
+ .current_branch()
+ .git_context("Failed to get current branch")?
+ .ok_or_else(|| GitError::CommandFailed("Not on a branch (detached HEAD)".to_string()))?;
+ let config = WorktrunkConfig::load().git_context("Failed to load config")?;
+
+ // Load project config (show helpful error if missing)
+ let project_config = load_project_config(&repo)?;
+
+ // TODO: Add support for custom variable overrides (e.g., --var key=value)
+ // This would allow testing hooks with different contexts without being in that context
+
+ // Execute the hook based on type
+ match hook_type {
+ "post-create" => {
+ check_hook_configured(&project_config.post_create_command, "post-create")?;
+ execute_post_create_commands(&worktree_path, &repo, &config, &branch, force)
+ }
+ "post-start" => {
+ check_hook_configured(&project_config.post_start_command, "post-start")?;
+ execute_post_start_commands_sequential(&worktree_path, &repo, &config, &branch, force)
+ }
+ "pre-merge" => {
+ check_hook_configured(&project_config.pre_merge_command, "pre-merge")?;
+ let target_branch = repo.default_branch().unwrap_or_else(|_| "main".to_string());
+ run_pre_merge_commands(
+ &project_config,
+ &branch,
+ &target_branch,
+ &worktree_path,
+ &repo,
+ &config,
+ force,
+ )
+ }
+ "post-merge" => {
+ check_hook_configured(&project_config.post_merge_command, "post-merge")?;
+ let target_branch = repo.default_branch().unwrap_or_else(|_| "main".to_string());
+ execute_post_merge_commands(
+ &worktree_path,
+ &repo,
+ &config,
+ &branch,
+ &target_branch,
+ force,
+ )
+ }
+ _ => Err(GitError::CommandFailed(format!(
+ "Unknown hook type: {}",
+ hook_type
+ ))),
+ }
+}
+
+fn load_project_config(repo: &Repository) -> Result<ProjectConfig, GitError> {
+ let repo_root = repo.worktree_root()?;
+ let config_path = repo_root.join(".config").join("wt.toml");
+
+ match ProjectConfig::load(&repo_root).git_context("Failed to load project config")? {
+ Some(cfg) => Ok(cfg),
+ None => {
+ // No project config found - show helpful error
+ let bold = AnstyleStyle::new().bold();
+ use worktrunk::styling::ERROR;
+ use worktrunk::styling::ERROR_EMOJI;
+ eprintln!("{ERROR_EMOJI} {ERROR}No project configuration found{ERROR:#}",);
+ eprintln!(
+ "{HINT_EMOJI} {HINT}Create a config file at: {bold}{}{bold:#}{HINT:#}",
+ config_path.display()
+ );
+ Err(GitError::CommandFailed(
+ "No project configuration found".to_string(),
+ ))
+ }
+ }
+}
+
+fn check_hook_configured<T>(hook: &Option<T>, hook_name: &str) -> Result<(), GitError> {
+ if hook.is_none() {
+ eprintln!(
+ "{HINT_EMOJI} {HINT}No {hook_name} commands configured in project config{HINT:#}"
+ );
+ return Err(GitError::CommandFailed(format!(
+ "No {hook_name} commands configured"
+ )));
+ }
+ Ok(())
+}
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index defb5d745..3a791e612 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -324,7 +324,7 @@ fn handle_squash(
}
/// Run pre-merge commands sequentially (blocking, fail-fast)
-fn run_pre_merge_commands(
+pub fn run_pre_merge_commands(
project_config: &ProjectConfig,
current_branch: &str,
target_branch: &str,
@@ -381,7 +381,7 @@ fn run_pre_merge_commands(
}
/// Execute post-merge commands sequentially in the main worktree (blocking)
-fn execute_post_merge_commands(
+pub fn execute_post_merge_commands(
main_worktree_path: &std::path::Path,
repo: &Repository,
config: &WorktrunkConfig,
diff --git a/src/commands/mod.rs b/src/commands/mod.rs
index 9e6cd4cfb..888368287 100644
--- a/src/commands/mod.rs
+++ b/src/commands/mod.rs
@@ -3,6 +3,7 @@ mod command_executor;
pub mod completion;
pub mod config;
pub mod configure_shell;
+pub mod dev;
pub mod init;
pub mod list;
pub mod merge;
@@ -12,6 +13,7 @@ pub mod worktree;
pub use completion::{handle_complete, handle_completion};
pub use config::{handle_config_init, handle_config_list};
pub use configure_shell::{ConfigAction, handle_configure_shell};
+pub use dev::handle_dev_run_hook;
pub use init::handle_init;
pub use list::handle_list;
pub use merge::handle_merge;
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rs
index 009069993..c18ddfb67 100644
--- a/src/commands/worktree.rs
+++ b/src/commands/worktree.rs
@@ -394,7 +394,7 @@ fn load_project_config(repo: &Repository) -> Result<Option<ProjectConfig>, GitEr
}
/// Execute post-create commands sequentially (blocking)
-fn execute_post_create_commands(
+pub fn execute_post_create_commands(
worktree_path: &std::path::Path,
repo: &Repository,
config: &WorktrunkConfig,
@@ -516,6 +516,62 @@ fn spawn_post_start_commands(
Ok(())
}
+/// Execute post-start commands sequentially (blocking) - for testing
+pub fn execute_post_start_commands_sequential(
+ worktree_path: &std::path::Path,
+ repo: &Repository,
+ config: &WorktrunkConfig,
+ branch: &str,
+ force: bool,
+) -> Result<(), GitError> {
+ let project_config = match load_project_config(repo)? {
+ Some(cfg) => cfg,
+ None => return Ok(()),
+ };
+
+ let Some(post_start_config) = &project_config.post_start_command else {
+ return Ok(());
+ };
+
+ let repo_root = repo.main_worktree_root()?;
+ let ctx = CommandContext::new(repo, config, branch, worktree_path, &repo_root, force);
+ let commands = prepare_project_commands(
+ post_start_config,
+ &ctx,
+ false,
+ &[],
+ "Post-start commands",
+ |_name, command| {
+ let dim = AnstyleStyle::new().dimmed();
+ crate::output::progress(format!("{dim}Skipping command: {command}{dim:#}")).ok();
+ },
+ )?;
+
+ if commands.is_empty() {
+ return Ok(());
+ }
+
+ // Execute sequentially for testing
+ for prepared in commands {
+ crate::output::progress(format!("🔄 {CYAN}Executing (post-start):{CYAN:#}"))?;
+ crate::output::progress(format_with_gutter(&prepared.expanded, "", None))?;
+
+ if let Err(e) = execute_command_in_worktree(worktree_path, &prepared.expanded) {
+ let message = match &prepared.name {
+ Some(name) => {
+ format!("{WARNING_EMOJI} {WARNING}Failed to execute '{name}': {e}{WARNING:#}")
+ }
+ None => format!("{WARNING_EMOJI} {WARNING}Command failed: {e}{WARNING:#}"),
+ };
+ crate::output::progress(message)?;
+ }
+ }
+
+ crate::output::flush()?;
+
+ Ok(())
+}
+
pub fn handle_push(
target: Option<&str>,
allow_merge_commits: bool,
diff --git a/src/main.rs b/src/main.rs
index 478d3fb47..526cd1354 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -12,8 +12,8 @@ mod output;
use commands::{
ConfigAction, Shell, handle_complete, handle_completion, handle_config_init,
- handle_config_list, handle_configure_shell, handle_init, handle_list, handle_merge,
- handle_push, handle_remove, handle_switch,
+ handle_config_list, handle_configure_shell, handle_dev_run_hook, handle_init, handle_list,
+ handle_merge, handle_push, handle_remove, handle_switch,
};
use output::{handle_remove_output, handle_switch_output};
@@ -51,6 +51,20 @@ enum ConfigCommand {
List,
}
+#[derive(Subcommand)]
+enum DevCommand {
+ /// Run a project hook for testing
+ RunHook {
+ /// Hook type to run
+ #[arg(value_parser = ["post-create", "post-start", "pre-merge", "post-merge"])]
+ hook_type: String,
+
+ /// Skip command approval prompts
+ #[arg(short, long)]
+ force: bool,
+ },
+}
+
#[derive(Subcommand)]
enum Commands {
/// Generate shell integration code
@@ -84,6 +98,13 @@ enum Commands {
action: ConfigCommand,
},
+ /// Development and testing utilities
+ #[command(hide = true)]
+ Dev {
+ #[command(subcommand)]
+ action: DevCommand,
+ },
+
/// List all worktrees
List {
/// Output format
@@ -348,6 +369,9 @@ fn main() {
ConfigCommand::Init => handle_config_init(),
ConfigCommand::List => handle_config_list(),
},
+ Commands::Dev { action } => match action {
+ DevCommand::RunHook { hook_type, force } => handle_dev_run_hook(&hook_type, force),
+ },
Commands::List { format, branches } => handle_list(format, branches),
Commands::Switch {
branch,
diff --git a/tests/snapshots/integration__integration_tests__init__init_bash.snap b/tests/snapshots/integration__integration_tests__init__init_bash.snap
index fec8f46e4..6e5f02774 100644
--- a/tests/snapshots/integration__integration_tests__init__init_bash.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_bash.snap
@@ -16,7 +16,7 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpq7zyU8/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpYBjef2/test-config.toml
---
success: true
exit_code: 0
@@ -169,6 +169,9 @@ _wt() {
wt,configure-shell)
cmd="wt__configure__shell"
;;
+ wt,dev)
+ cmd="wt__dev"
+ ;;
wt,init)
cmd="wt__init"
;;
@@ -193,6 +196,9 @@ _wt() {
wt__config,list)
cmd="wt__config__list"
;;
+ wt__dev,run-hook)
+ cmd="wt__dev__run__hook"
+ ;;
*)
;;
esac
@@ -200,7 +206,7 @@ _wt() {
case "${cmd}" in
wt)
- opts="-v -h -V --verbose --help --version init configure-shell config list switch remove push merge completion complete"
+ opts="-v -h -V --verbose --help --version init configure-shell config dev list switch remove push merge completion complete"
if [[ ${cur} == -* || ${COMP_CWORD} -eq 1 ]] ; then
COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
return 0
@@ -305,6 +311,34 @@ _wt() {
COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
return 0
;;
+ wt__dev)
+ opts="-v -h --verbose --help run-hook"
+ if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; then
+ COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
+ return 0
+ fi
+ case "${prev}" in
+ *)
+ COMPREPLY=()
+ ;;
+ esac
+ COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
+ return 0
+ ;;
+ wt__dev__run__hook)
+ opts="-f -v -h --force --verbose --help post-create post-start pre-merge post-merge"
+ if [[ ${cur} == -* || ${COMP_CWORD} -eq 3 ]] ; then
+ COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
+ return 0
+ fi
+ case "${prev}" in
+ *)
+ COMPREPLY=()
+ ;;
+ esac
+ COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
+ return 0
+ ;;
wt__init)
opts="-v -h --cmd --verbose --help <SHELL>"
if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; then
diff --git a/tests/snapshots/integration__integration_tests__init__init_bash_custom_prefix.snap b/tests/snapshots/integration__integration_tests__init__init_bash_custom_prefix.snap
index e2e279dba..09510696e 100644
--- a/tests/snapshots/integration__integration_tests__init__init_bash_custom_prefix.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_bash_custom_prefix.snap
@@ -18,7 +18,7 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpkxrxG1/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpCXsTxF/test-config.toml
---
success: true
exit_code: 0
@@ -171,6 +171,9 @@ _wt() {
wt,configure-shell)
cmd="wt__configure__shell"
;;
+ wt,dev)
+ cmd="wt__dev"
+ ;;
wt,init)
cmd="wt__init"
;;
@@ -195,6 +198,9 @@ _wt() {
wt__config,list)
cmd="wt__config__list"
;;
+ wt__dev,run-hook)
+ cmd="wt__dev__run__hook"
+ ;;
*)
;;
esac
@@ -202,7 +208,7 @@ _wt() {
case "${cmd}" in
wt)
- opts="-v -h -V --verbose --help --version init configure-shell config list switch remove push merge completion complete"
+ opts="-v -h -V --verbose --help --version init configure-shell config dev list switch remove push merge completion complete"
if [[ ${cur} == -* || ${COMP_CWORD} -eq 1 ]] ; then
COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
return 0
@@ -307,6 +313,34 @@ _wt() {
COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
return 0
;;
+ wt__dev)
+ opts="-v -h --verbose --help run-hook"
+ if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; then
+ COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
+ return 0
+ fi
+ case "${prev}" in
+ *)
+ COMPREPLY=()
+ ;;
+ esac
+ COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
+ return 0
+ ;;
+ wt__dev__run__hook)
+ opts="-f -v -h --force --verbose --help post-create post-start pre-merge post-merge"
+ if [[ ${cur} == -* || ${COMP_CWORD} -eq 3 ]] ; then
+ COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
+ return 0
+ fi
+ case "${prev}" in
+ *)
+ COMPREPLY=()
+ ;;
+ esac
+ COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
+ return 0
+ ;;
wt__init)
opts="-v -h --cmd --verbose --help <SHELL>"
if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; then
diff --git a/tests/snapshots/integration__integration_tests__init__init_fish.snap b/tests/snapshots/integration__integration_tests__init__init_fish.snap
index 137bbf0b8..dcea75cfb 100644
--- a/tests/snapshots/integration__integration_tests__init__init_fish.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_fish.snap
@@ -16,7 +16,7 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpAwdf0S/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpNVNuYN/test-config.toml
---
success: true
exit_code: 0
@@ -207,6 +207,7 @@ complete -c wt -n "__fish_wt_needs_command" -s V -l version -d 'Print version'
complete -c wt -n "__fish_wt_needs_command" -f -a "init" -d 'Generate shell integration code'
complete -c wt -n "__fish_wt_needs_command" -f -a "configure-shell" -d 'Configure shell by writing to config files'
complete -c wt -n "__fish_wt_needs_command" -f -a "config" -d 'Manage configuration'
+complete -c wt -n "__fish_wt_needs_command" -f -a "dev" -d 'Development and testing utilities'
complete -c wt -n "__fish_wt_needs_command" -f -a "list" -d 'List all worktrees'
complete -c wt -n "__fish_wt_needs_command" -f -a "switch" -d 'Switch to a worktree'
complete -c wt -n "__fish_wt_needs_command" -f -a "remove" -d 'Finish current worktree, returning to primary if current'
@@ -235,6 +236,12 @@ complete -c wt -n "__fish_wt_using_subcommand config; and __fish_seen_subcommand
complete -c wt -n "__fish_wt_using_subcommand config; and __fish_seen_subcommand_from init" -s h -l help -d 'Print help'
complete -c wt -n "__fish_wt_using_subcommand config; and __fish_seen_subcommand_from list" -s v -l verbose -d 'Enable verbose output (show git commands and debug info)'
complete -c wt -n "__fish_wt_using_subcommand config; and __fish_seen_subcommand_from list" -s h -l help -d 'Print help'
+complete -c wt -n "__fish_wt_using_subcommand dev; and not __fish_seen_subcommand_from run-hook" -s v -l verbose -d 'Enable verbose output (show git commands and debug info)'
+complete -c wt -n "__fish_wt_using_subcommand dev; and not __fish_seen_subcommand_from run-hook" -s h -l help -d 'Print help'
+complete -c wt -n "__fish_wt_using_subcommand dev; and not __fish_seen_subcommand_from run-hook" -f -a "run-hook" -d 'Run a project hook for testing'
+complete -c wt -n "__fish_wt_using_subcommand dev; and __fish_seen_subcommand_from run-hook" -s f -l force -d 'Skip command approval prompts'
+complete -c wt -n "__fish_wt_using_subcommand dev; and __fish_seen_subcommand_from run-hook" -s v -l verbose -d 'Enable verbose output (show git commands and debug info)'
+complete -c wt -n "__fish_wt_using_subcommand dev; and __fish_seen_subcommand_from run-hook" -s h -l help -d 'Print help'
complete -c wt -n "__fish_wt_using_subcommand list" -l format -d 'Output format' -r -f -a "table\t'Human-readable table format'
json\t'JSON format'"
complete -c wt -n "__fish_wt_using_subcommand list" -l branches -d 'Also display branches that don\'t have worktrees'
diff --git a/tests/snapshots/integration__integration_tests__init__init_zsh.snap b/tests/snapshots/integration__integration_tests__init__init_zsh.snap
index 3f363f8fe..f4eaf4aae 100644
--- a/tests/snapshots/integration__integration_tests__init__init_zsh.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_zsh.snap
@@ -210,6 +210,37 @@ _arguments "${_arguments_options[@]}" : \
;;
esac
;;
+(dev)
+_arguments "${_arguments_options[@]}" : \
+'-v[Enable verbose output (show git commands and debug info)]' \
+'--verbose[Enable verbose output (show git commands and debug info)]' \
+'-h[Print help]' \
+'--help[Print help]' \
+":: :_wt__dev_commands" \
+"*::: :->dev" \
+&& ret=0
+
+ case $state in
+ (dev)
+ words=($line[1] "${words[@]}")
+ (( CURRENT += 1 ))
+ curcontext="${curcontext%:*:*}:wt-dev-command-$line[1]:"
+ case $line[1] in
+ (run-hook)
+_arguments "${_arguments_options[@]}" : \
+'-f[Skip command approval prompts]' \
+'--force[Skip command approval prompts]' \
+'-v[Enable verbose output (show git commands and debug info)]' \
+'--verbose[Enable verbose output (show git commands and debug info)]' \
+'-h[Print help]' \
+'--help[Print help]' \
+':hook_type -- Hook type to run:(post-create post-start pre-merge post-merge)' \
+&& ret=0
+;;
+ esac
+ ;;
+esac
+;;
(list)
_arguments "${_arguments_options[@]}" : \
'--format=[Output format]:FORMAT:((table\:"Human-readable table format"
@@ -303,6 +334,7 @@ _wt_commands() {
'init:Generate shell integration code' \
'configure-shell:Configure shell by writing to config files' \
'config:Manage configuration' \
+'dev:Development and testing utilities' \
'list:List all worktrees' \
'switch:Switch to a worktree' \
'remove:Finish current worktree, returning to primary if current' \
@@ -346,6 +378,18 @@ _wt__configure-shell_commands() {
local commands; commands=()
_describe -t commands 'wt configure-shell commands' commands "$@"
}
+(( $+functions[_wt__dev_commands] )) ||
+_wt__dev_commands() {
+ local commands; commands=(
+'run-hook:Run a project hook for testing' \
+ )
+ _describe -t commands 'wt dev commands' commands "$@"
+}
+(( $+functions[_wt__dev__run-hook_commands] )) ||
+_wt__dev__run-hook_commands() {
+ local commands; commands=()
+ _describe -t commands 'wt dev run-hook commands' commands "$@"
+}
(( $+functions[_wt__init_commands] )) ||
_wt__init_commands() {
local commands; commands=()