Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat(hook): add --dry-run flag to wt hook (#1361)
Maximilian Roos5978e0004ee5
diff --git a/src/cli/hook.rs b/src/cli/hook.rsindex 864ce7faa..48e3beffb 100644--- a/src/cli/hook.rs+++ b/src/cli/hook.rs@@ -33,6 +33,10 @@ pub enum HookCommand {#[arg(short, long)]yes: bool,+ /// Show what would run without executing+ #[arg(long)]+ dry_run: bool,+/// Override built-in template variable (KEY=VALUE)#[arg(long = "var", value_name = "KEY=VALUE", value_parser = super::parse_key_val, action = clap::ArgAction::Append)]vars: Vec<(String, String)>,@@ -53,6 +57,10 @@ pub enum HookCommand {#[arg(short, long)]yes: bool,+ /// Show what would run without executing+ #[arg(long)]+ dry_run: bool,+/// Override built-in template variable (KEY=VALUE)#[arg(long = "var", value_name = "KEY=VALUE", value_parser = super::parse_key_val, action = clap::ArgAction::Append)]vars: Vec<(String, String)>,@@ -73,6 +81,10 @@ pub enum HookCommand {#[arg(short, long)]yes: bool,+ /// Show what would run without executing+ #[arg(long)]+ dry_run: bool,+/// Run in foreground (block until complete)#[arg(long)]foreground: bool,@@ -101,6 +113,10 @@ pub enum HookCommand {#[arg(short, long)]yes: bool,+ /// Show what would run without executing+ #[arg(long)]+ dry_run: bool,+/// Run in foreground (block until complete)#[arg(long)]foreground: bool,@@ -127,6 +143,10 @@ pub enum HookCommand {#[arg(short, long)]yes: bool,+ /// Show what would run without executing+ #[arg(long)]+ dry_run: bool,+/// Override built-in template variable (KEY=VALUE)#[arg(long = "var", value_name = "KEY=VALUE", value_parser = super::parse_key_val, action = clap::ArgAction::Append)]vars: Vec<(String, String)>,@@ -145,6 +165,10 @@ pub enum HookCommand {#[arg(short, long)]yes: bool,+ /// Show what would run without executing+ #[arg(long)]+ dry_run: bool,+/// Override built-in template variable (KEY=VALUE)#[arg(long = "var", value_name = "KEY=VALUE", value_parser = super::parse_key_val, action = clap::ArgAction::Append)]vars: Vec<(String, String)>,@@ -163,6 +187,10 @@ pub enum HookCommand {#[arg(short, long)]yes: bool,+ /// Show what would run without executing+ #[arg(long)]+ dry_run: bool,+/// Override built-in template variable (KEY=VALUE)#[arg(long = "var", value_name = "KEY=VALUE", value_parser = super::parse_key_val, action = clap::ArgAction::Append)]vars: Vec<(String, String)>,@@ -181,6 +209,10 @@ pub enum HookCommand {#[arg(short, long)]yes: bool,+ /// Show what would run without executing+ #[arg(long)]+ dry_run: bool,+/// Override built-in template variable (KEY=VALUE)#[arg(long = "var", value_name = "KEY=VALUE", value_parser = super::parse_key_val, action = clap::ArgAction::Append)]vars: Vec<(String, String)>,@@ -201,6 +233,10 @@ pub enum HookCommand {#[arg(short, long)]yes: bool,+ /// Show what would run without executing+ #[arg(long)]+ dry_run: bool,+/// Run in foreground (block until complete)#[arg(long)]foreground: bool,diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rsindex 3af67a54f..95ff4822a 100644--- a/src/commands/hook_commands.rs+++ b/src/commands/hook_commands.rs@@ -120,6 +120,7 @@ pub fn run_hook(hook_type: HookType,yes: bool,foreground: Option<bool>,+ dry_run: bool,name_filter: Option<&str>,custom_vars: &[(String, String)],) -> anyhow::Result<()> {@@ -131,13 +132,15 @@ pub fn run_hook(// Load project config (optional - user hooks can run without project config)let project_config = repo.load_project_config()?;- // "Approve at the Gate": approve project hooks upfront- // Pass name_filter to only approve the targeted hook, not all hooks of this type- let approved = approve_hooks_filtered(&ctx, &[hook_type], name_filter)?;- // If declined, return early - the whole point of `wt hook` is to run hooks- if !approved {- eprintln!("{}", worktrunk::styling::info_message("Commands declined"));- return Ok(());+ if !dry_run {+ // "Approve at the Gate": approve project hooks upfront+ // Pass name_filter to only approve the targeted hook, not all hooks of this type+ let approved = approve_hooks_filtered(&ctx, &[hook_type], name_filter)?;+ // If declined, return early - the whole point of `wt hook` is to run hooks+ if !approved {+ eprintln!("{}", worktrunk::styling::info_message("Commands declined"));+ return Ok(());+ }}// Build extra vars from command-line --var flags@@ -163,90 +166,88 @@ pub fn run_hook(// Get effective user hooks (global + per-project merged)let user_hooks = ctx.config.hooks(ctx.project_id().as_deref());- let hook_configs = |hook: HookType| {- (- user_hooks.get(hook),- project_config.as_ref().and_then(|c| c.hooks.get(hook)),- )+ let (user_config, proj_config) = (+ user_hooks.get(hook_type),+ project_config.as_ref().and_then(|c| c.hooks.get(hook_type)),+ );+ require_hooks(user_config, proj_config, hook_type)?;++ // Build extra vars per hook type (shared by dry-run and execution paths)+ let default_branch = repo.default_branch();+ let extra_vars: Vec<(&str, &str)> = match hook_type {+ HookType::PreCommit => build_target_vars(default_branch.as_deref(), &custom_vars_refs),+ HookType::PreMerge | HookType::PostMerge => {+ build_target_vars(Some(ctx.branch_or_head()), &custom_vars_refs)+ }+ _ => custom_vars_refs.to_vec(),};- // Execute the hook based on type- match hook_type {- HookType::PreSwitch | HookType::PostCreate | HookType::PreRemove => {- let (user_config, project_config) = hook_configs(hook_type);- require_hooks(user_config, project_config, hook_type)?;- // Manual wt hook: user stays at cwd (no cd happens)- run_filtered_hook(- &ctx,- user_config,- project_config,- hook_type,- &custom_vars_refs,- name_filter,- HookFailureStrategy::FailFast,- )- }- HookType::PostStart | HookType::PostSwitch | HookType::PostRemove => {- let (user_config, project_config) = hook_configs(hook_type);- require_hooks(user_config, project_config, hook_type)?;- run_post_hook(- &ctx,- foreground,- user_config,- project_config,- hook_type,- &custom_vars_refs,- name_filter,- )- }- HookType::PreCommit => {- let (user_config, project_config) = hook_configs(hook_type);- require_hooks(user_config, project_config, hook_type)?;- // Pre-commit hook can optionally use target branch context- // Custom vars take precedence (added last)- let target_branch = repo.default_branch();- let extra_vars = build_target_vars(target_branch.as_deref(), &custom_vars_refs);- // Manual wt hook: user stays at cwd (no cd happens)- run_filtered_hook(- &ctx,- user_config,- project_config,- hook_type,- &extra_vars,- name_filter,- HookFailureStrategy::FailFast,- )- }- HookType::PreMerge => {- let (user_config, project_config) = hook_configs(hook_type);- require_hooks(user_config, project_config, hook_type)?;- // Use current branch as target (matches approval prompt for wt hook)- let vars = build_target_vars(Some(ctx.branch_or_head()), &custom_vars_refs);- run_filtered_hook(- &ctx,- user_config,- project_config,- hook_type,- &vars,- name_filter,- HookFailureStrategy::FailFast,- )- }- HookType::PostMerge => {- let (user_config, project_config) = hook_configs(hook_type);- require_hooks(user_config, project_config, hook_type)?;- // Manual wt hook: user stays at cwd (no cd happens)- let vars = build_target_vars(Some(ctx.branch_or_head()), &custom_vars_refs);- run_filtered_hook(- &ctx,+ if dry_run {+ let commands = prepare_hook_commands(+ &ctx,+ HookCommandSpec {user_config,- project_config,+ project_config: proj_config,hook_type,- &vars,+ extra_vars: &extra_vars,name_filter,- HookFailureStrategy::Warn,- )+ display_path: None,+ },+ )?;+ check_name_filter_matched(name_filter, commands.len(), user_config, proj_config)?;++ for cmd in &commands {+ let label = match &cmd.prepared.name {+ Some(n) => {+ let display_name = format!("{}:{}", cmd.source, n);+ cformat!("{hook_type} <bold>{display_name}</> would run:")+ }+ None => cformat!("{hook_type} {} hook would run:", cmd.source),+ };+ eprintln!(+ "{}",+ info_message(cformat!(+ "{label}\n{}",+ format_bash_with_gutter(&cmd.prepared.expanded)+ ))+ );}+ return Ok(());+ }++ // Execute the hook based on type+ match hook_type {+ HookType::PreSwitch+ | HookType::PostCreate+ | HookType::PreRemove+ | HookType::PreCommit+ | HookType::PreMerge => run_filtered_hook(+ &ctx,+ user_config,+ proj_config,+ hook_type,+ &extra_vars,+ name_filter,+ HookFailureStrategy::FailFast,+ ),+ HookType::PostStart | HookType::PostSwitch | HookType::PostRemove => run_post_hook(+ &ctx,+ foreground,+ user_config,+ proj_config,+ hook_type,+ &extra_vars,+ name_filter,+ ),+ HookType::PostMerge => run_filtered_hook(+ &ctx,+ user_config,+ proj_config,+ hook_type,+ &extra_vars,+ name_filter,+ HookFailureStrategy::Warn,+ ),}}diff --git a/src/main.rs b/src/main.rsindex 370669adb..a2706d9d6 100644--- a/src/main.rs+++ b/src/main.rs@@ -129,22 +129,24 @@ fn flag_pair(positive: bool, negative: bool) -> Option<bool> {fn run_non_toggle_hook(hook_type: HookType,yes: bool,+ dry_run: bool,name: Option<&str>,vars: &[(String, String)],) -> anyhow::Result<()> {- run_hook(hook_type, yes, None, name, vars)+ run_hook(hook_type, yes, None, dry_run, name, vars)}fn run_toggleable_hook(hook_type: HookType,yes: bool,+ dry_run: bool,foreground: bool,no_background: bool,name: Option<&str>,vars: &[(String, String)],) -> anyhow::Result<()> {let foreground = is_foreground_mode(foreground, no_background);- run_hook(hook_type, yes, Some(foreground), name, vars)+ run_hook(hook_type, yes, Some(foreground), dry_run, name, vars)}fn warn_select_deprecated() {@@ -160,21 +162,29 @@ fn handle_hook_command(action: HookCommand) -> anyhow::Result<()> {hook_type,expanded,} => handle_hook_show(hook_type.as_deref(), expanded),- HookCommand::PreSwitch { name, yes, vars } => {- run_non_toggle_hook(HookType::PreSwitch, yes, name.as_deref(), &vars)- }- HookCommand::PostCreate { name, yes, vars } => {- run_non_toggle_hook(HookType::PostCreate, yes, name.as_deref(), &vars)- }+ HookCommand::PreSwitch {+ name,+ yes,+ dry_run,+ vars,+ } => run_non_toggle_hook(HookType::PreSwitch, yes, dry_run, name.as_deref(), &vars),+ HookCommand::PostCreate {+ name,+ yes,+ dry_run,+ vars,+ } => run_non_toggle_hook(HookType::PostCreate, yes, dry_run, name.as_deref(), &vars),HookCommand::PostStart {name,yes,+ dry_run,foreground,no_background,vars,} => run_toggleable_hook(HookType::PostStart,yes,+ dry_run,foreground,no_background,name.as_deref(),@@ -183,38 +193,54 @@ fn handle_hook_command(action: HookCommand) -> anyhow::Result<()> {HookCommand::PostSwitch {name,yes,+ dry_run,foreground,no_background,vars,} => run_toggleable_hook(HookType::PostSwitch,yes,+ dry_run,foreground,no_background,name.as_deref(),&vars,),- HookCommand::PreCommit { name, yes, vars } => {- run_non_toggle_hook(HookType::PreCommit, yes, name.as_deref(), &vars)- }- HookCommand::PreMerge { name, yes, vars } => {- run_non_toggle_hook(HookType::PreMerge, yes, name.as_deref(), &vars)- }- HookCommand::PostMerge { name, yes, vars } => {- run_non_toggle_hook(HookType::PostMerge, yes, name.as_deref(), &vars)- }- HookCommand::PreRemove { name, yes, vars } => {- run_non_toggle_hook(HookType::PreRemove, yes, name.as_deref(), &vars)- }+ HookCommand::PreCommit {+ name,+ yes,+ dry_run,+ vars,+ } => run_non_toggle_hook(HookType::PreCommit, yes, dry_run, name.as_deref(), &vars),+ HookCommand::PreMerge {+ name,+ yes,+ dry_run,+ vars,+ } => run_non_toggle_hook(HookType::PreMerge, yes, dry_run, name.as_deref(), &vars),+ HookCommand::PostMerge {+ name,+ yes,+ dry_run,+ vars,+ } => run_non_toggle_hook(HookType::PostMerge, yes, dry_run, name.as_deref(), &vars),+ HookCommand::PreRemove {+ name,+ yes,+ dry_run,+ vars,+ } => run_non_toggle_hook(HookType::PreRemove, yes, dry_run, name.as_deref(), &vars),HookCommand::PostRemove {name,yes,+ dry_run,foreground,vars,} => run_hook(HookType::PostRemove,yes,Some(foreground),+ dry_run,name.as_deref(),&vars,),diff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rsindex c39f02b9d..ee2d1c96c 100644--- a/tests/integration_tests/user_hooks.rs+++ b/tests/integration_tests/user_hooks.rs@@ -1347,6 +1347,69 @@ fn test_standalone_hook_no_hooks_configured(repo: TestRepo) {);}+// ============================================================================+// Dry-Run Tests+// ============================================================================++/// --dry-run shows expanded commands without executing them+#[rstest]+fn test_hook_dry_run_shows_expanded_command(repo: TestRepo) {+ repo.write_project_config(r#"pre-merge = "echo branch={{ branch }}""#);++ let settings = setup_snapshot_settings(&repo);+ let _guard = settings.bind_to_scope();++ // No --yes needed: --dry-run skips approval+ assert_cmd_snapshot!(make_snapshot_cmd(+ &repo,+ "hook",+ &["pre-merge", "--dry-run"],+ Some(repo.root_path()),+ ));+}++/// --dry-run does not execute the hook command+#[rstest]+fn test_hook_dry_run_does_not_execute(repo: TestRepo) {+ repo.write_project_config(r#"post-create = "echo 'SHOULD_NOT_RUN' > hook_ran.txt""#);++ let mut cmd = crate::common::wt_command();+ cmd.current_dir(repo.root_path());+ cmd.env("WORKTRUNK_CONFIG_PATH", repo.test_config_path());+ cmd.args(["hook", "post-create", "--dry-run"]);++ let output = cmd.output().unwrap();+ assert!(output.status.success(), "dry-run should succeed");++ // Hook should NOT have run+ let marker = repo.root_path().join("hook_ran.txt");+ assert!(+ !marker.exists(),+ "dry-run should not execute the hook command"+ );+}++/// --dry-run shows named hooks with source:name labels+#[rstest]+fn test_hook_dry_run_named_hooks(repo: TestRepo) {+ repo.write_project_config(+ r#"[pre-merge]+lint = "pre-commit run --all-files"+test = "cargo test"+"#,+ );++ let settings = setup_snapshot_settings(&repo);+ let _guard = settings.bind_to_scope();++ assert_cmd_snapshot!(make_snapshot_cmd(+ &repo,+ "hook",+ &["pre-merge", "--dry-run"],+ Some(repo.root_path()),+ ));+}+// ============================================================================// Background Hook Execution Tests (post-start, post-switch)// ============================================================================diff --git a/tests/snapshots/integration__integration_tests__user_hooks__hook_dry_run_named_hooks.snap b/tests/snapshots/integration__integration_tests__user_hooks__hook_dry_run_named_hooks.snapnew file mode 100644index 000000000..30ff240b3--- /dev/null+++ b/tests/snapshots/integration__integration_tests__user_hooks__hook_dry_run_named_hooks.snap@@ -0,0 +1,49 @@+---+source: tests/integration_tests/user_hooks.rs+info:+ program: wt+ args:+ - hook+ - pre-merge+ - "--dry-run"+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ NO_COLOR: ""+ PATH: "[PATH]"+ PSModulePath: ""+ RUST_LOG: warn+ SHELL: ""+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+[2m○[22m pre-merge [1mproject:lint[22m would run:+[107m [0m [2m[0m[2m[34mpre-commit[0m[2m run [0m[2m[36m--all-files[0m[2m+[2m○[22m pre-merge [1mproject:test[22m would run:+[107m [0m [2m[0m[2m[34mcargo[0m[2m testdiff --git a/tests/snapshots/integration__integration_tests__user_hooks__hook_dry_run_shows_expanded_command.snap b/tests/snapshots/integration__integration_tests__user_hooks__hook_dry_run_shows_expanded_command.snapnew file mode 100644index 000000000..b8429cd0e--- /dev/null+++ b/tests/snapshots/integration__integration_tests__user_hooks__hook_dry_run_shows_expanded_command.snap@@ -0,0 +1,47 @@+---+source: tests/integration_tests/user_hooks.rs+info:+ program: wt+ args:+ - hook+ - pre-merge+ - "--dry-run"+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ NO_COLOR: ""+ PATH: "[PATH]"+ PSModulePath: ""+ RUST_LOG: warn+ SHELL: ""+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+[2m○[22m pre-merge project hook would run:+[107m [0m [2m[0m[2m[34mecho[0m[2m branch=main