Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(hook): inject `target` symmetrically on switch/create/start (#2295)
Maximilian Roos1fd6eaba2092
diff --git a/docs/content/hook.md b/docs/content/hook.mdindex fc5c1f004..1ac0a18ce 100644--- a/docs/content/hook.md+++ b/docs/content/hook.md@@ -143,12 +143,13 @@ Bare variables (`branch`, `worktree_path`, `commit`) refer to the branch the ope| Operation | Bare vars | `base` | `target` ||-----------|-----------|--------|----------|| switch/create | destination | where you came from | = bare vars |+| commit (during merge/squash) | worktree being squashed | = bare vars | integration target || merge | feature being merged | = bare vars | merge target || remove | branch being removed | = bare vars | where you end up |Pre and post hooks share the same perspective — `{{ branch | hash_port }}` produces the same port in `post-start` and `post-remove`. `cwd` is the worktree root where the hook command runs. It differs from `worktree_path` in three cases: pre-switch, where the hook runs in the source but `worktree_path` is the destination; post-remove, where the active worktree is gone so the hook runs in primary; and post-merge with removal, same — the active worktree is gone, so the hook runs in target.-Some variables are conditional: `upstream` requires remote tracking; `base`/`target` are only in two-worktree hooks; `vars` keys may not exist. Undefined variables error — use conditionals or defaults for optional behavior:+Some variables are conditional: `upstream` requires remote tracking; `base` only appears in switch/create hooks; `target_worktree_path` requires the target to have a worktree; `vars` keys may not exist. Undefined variables error — use conditionals or defaults for optional behavior:```toml[pre-start]diff --git a/skills/worktrunk/reference/hook.md b/skills/worktrunk/reference/hook.mdindex 677168989..fb92e6087 100644--- a/skills/worktrunk/reference/hook.md+++ b/skills/worktrunk/reference/hook.md@@ -134,12 +134,13 @@ Bare variables (`branch`, `worktree_path`, `commit`) refer to the branch the ope| Operation | Bare vars | `base` | `target` ||-----------|-----------|--------|----------|| switch/create | destination | where you came from | = bare vars |+| commit (during merge/squash) | worktree being squashed | = bare vars | integration target || merge | feature being merged | = bare vars | merge target || remove | branch being removed | = bare vars | where you end up |Pre and post hooks share the same perspective — `{{ branch | hash_port }}` produces the same port in `post-start` and `post-remove`. `cwd` is the worktree root where the hook command runs. It differs from `worktree_path` in three cases: pre-switch, where the hook runs in the source but `worktree_path` is the destination; post-remove, where the active worktree is gone so the hook runs in primary; and post-merge with removal, same — the active worktree is gone, so the hook runs in target.-Some variables are conditional: `upstream` requires remote tracking; `base`/`target` are only in two-worktree hooks; `vars` keys may not exist. Undefined variables error — use conditionals or defaults for optional behavior:+Some variables are conditional: `upstream` requires remote tracking; `base` only appears in switch/create hooks; `target_worktree_path` requires the target to have a worktree; `vars` keys may not exist. Undefined variables error — use conditionals or defaults for optional behavior:```toml[pre-start]diff --git a/src/cli/mod.rs b/src/cli/mod.rsindex 00c93cb10..6202bfd8c 100644--- a/src/cli/mod.rs+++ b/src/cli/mod.rs@@ -1280,12 +1280,13 @@ Bare variables (`branch`, `worktree_path`, `commit`) refer to the branch the ope| Operation | Bare vars | `base` | `target` ||-----------|-----------|--------|----------|| switch/create | destination | where you came from | = bare vars |+| commit (during merge/squash) | worktree being squashed | = bare vars | integration target || merge | feature being merged | = bare vars | merge target || remove | branch being removed | = bare vars | where you end up |Pre and post hooks share the same perspective — `{{ branch | hash_port }}` produces the same port in `post-start` and `post-remove`. `cwd` is the worktree root where the hook command runs. It differs from `worktree_path` in three cases: pre-switch, where the hook runs in the source but `worktree_path` is the destination; post-remove, where the active worktree is gone so the hook runs in primary; and post-merge with removal, same — the active worktree is gone, so the hook runs in target.-Some variables are conditional: `upstream` requires remote tracking; `base`/`target` are only in two-worktree hooks; `vars` keys may not exist. Undefined variables error — use conditionals or defaults for optional behavior:+Some variables are conditional: `upstream` requires remote tracking; `base` only appears in switch/create hooks; `target_worktree_path` requires the target to have a worktree; `vars` keys may not exist. Undefined variables error — use conditionals or defaults for optional behavior:```toml[pre-start]diff --git a/src/commands/handle_switch.rs b/src/commands/handle_switch.rsindex ed37f6645..1f4718be4 100644--- a/src/commands/handle_switch.rs+++ b/src/commands/handle_switch.rs@@ -414,7 +414,15 @@ pub fn handle_switch(// Build extra vars for base/target context (used by both hooks and --execute).// "base" is the source worktree the user switched from (all switches),// or the branch they branched from (creates).+ // "target" matches the bare vars (the destination) — documented as+ // "target = bare vars" for switch/create and kept symmetric with pre-switch.+ let target_path_str = worktrunk::path::to_posix_path(&result.path().to_string_lossy());+let mut extra_vars = switch_extra_vars(&result);+ if let Some(target_branch) = branch_info.branch.as_deref() {+ extra_vars.push(("target", target_branch));+ }+ extra_vars.push(("target_worktree_path", &target_path_str));// For existing switches, add source worktree as baseif matches!(result,diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rsindex 8f3cef168..8306dedaa 100644--- a/src/commands/worktree/switch.rs+++ b/src/commands/worktree/switch.rs@@ -908,6 +908,8 @@ pub fn execute_switch(// Execute post-create commandsif run_hooks {let ctx = CommandContext::new(repo, config, Some(&branch), &worktree_path, force);+ let target_wt_posix =+ worktrunk::path::to_posix_path(&worktree_path.to_string_lossy());match &method {CreationMethod::Regular { base_branch, .. } => {@@ -916,6 +918,8 @@ pub fn execute_switch(base_worktree_path.as_ref().map(|p| ("base_worktree_path", p.as_str())),+ Some(("target", branch.as_str())),+ Some(("target_worktree_path", target_wt_posix.as_str())),].into_iter().flatten()@@ -933,8 +937,12 @@ pub fn execute_switch(RefType::Pr => ("pr_number", "pr_url"),RefType::Mr => ("mr_number", "mr_url"),};- let extra_vars: Vec<(&str, &str)> =- vec![(num_key, &num_str), (url_key, ref_url)];+ let extra_vars: Vec<(&str, &str)> = vec![+ (num_key, &num_str),+ (url_key, ref_url),+ ("target", &branch),+ ("target_worktree_path", &target_wt_posix),+ ];ctx.execute_pre_start_commands(&extra_vars)?;}}diff --git a/src/config/expansion.rs b/src/config/expansion.rsindex 93c0d1f1d..cf4548a7d 100644--- a/src/config/expansion.rs+++ b/src/config/expansion.rs@@ -96,16 +96,21 @@ fn hook_extras(hook_type: HookType) -> &'static [&'static str] {use HookType::*;match hook_type {// Switch: source branch (`base`) and destination (`target`).- // Post-switch has already switched, so only `base` is set — but we- // accept both here so user templates stay portable between pre/post.PreSwitch | PostSwitch => &["base","base_worktree_path","target","target_worktree_path",],- // Create/start: source worktree the new branch was created from.- PreStart | PostStart => &["base", "base_worktree_path"],+ // Create/start: source worktree (`base`) and newly-created destination+ // (`target`). On create, the destination branch equals the bare `branch`+ // var — `target` is accepted for template portability with switch hooks.+ PreStart | PostStart => &[+ "base",+ "base_worktree_path",+ "target",+ "target_worktree_path",+ ],// Commit: integration target for the pre-commit squash.PreCommit | PostCommit => &["target"],// Merge: where the feature is being merged into.@@ -1677,10 +1682,10 @@ mod tests {err.message);- // `target` is unavailable in pre-start — catch the typo at validation time.+ // `base` is unavailable in pre-merge — catch the typo at validation time.let err = validate_template(- "{{ target }}",- ValidationScope::Hook(HookType::PreStart),+ "{{ base }}",+ ValidationScope::Hook(HookType::PreMerge),&test.repo,"test",)diff --git a/tests/integration_tests/post_start_commands.rs b/tests/integration_tests/post_start_commands.rsindex 53dee587f..870535992 100644--- a/tests/integration_tests/post_start_commands.rs+++ b/tests/integration_tests/post_start_commands.rs@@ -1312,6 +1312,75 @@ approved-commands = [);}+#[rstest]+fn test_post_start_target_variable_expands_to_branch(repo: TestRepo) {+ // `{{ target }}` in post-start should equal the bare `{{ branch }}` —+ // symmetric with `pre-switch`, which already injects `target`.+ repo.write_project_config(r#"post-start = "echo '{{ target }}' > target_marker.txt""#);+ repo.commit("Add post-start with target var");++ repo.write_test_approvals(+ r#"[projects."../origin"]+approved-commands = ["echo '{{ target }}' > target_marker.txt"]+"#,+ );++ snapshot_switch(+ "post_start_target_variable",+ &repo,+ &["--create", "feature"],+ );++ let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");+ let marker = worktree_path.join("target_marker.txt");+ wait_for_file_content(&marker);++ let content = fs::read_to_string(&marker).unwrap();+ assert_eq!(+ content.trim(),+ "feature",+ "target should resolve to the newly created branch, got: {content}"+ );+}++#[rstest]+fn test_post_switch_target_variable_on_existing_switch(repo: TestRepo) {+ // `{{ target }}` in post-switch must equal the destination branch for+ // switches to an existing worktree — not just creates.+ repo.write_project_config(r#"post-switch = "echo '{{ target }}' > target_marker.txt""#);+ repo.commit("Add post-switch with target var");++ repo.write_test_approvals(+ r#"[projects."../origin"]+approved-commands = ["echo '{{ target }}' > target_marker.txt"]+"#,+ );++ // Create the destination worktree first, then switch back to main so the+ // next invocation exercises the existing-worktree switch path (not create).+ repo.wt_command()+ .args(["switch", "--create", "feature", "--no-hooks", "--yes"])+ .output()+ .expect("failed to pre-create feature worktree");+ repo.wt_command()+ .args(["switch", "main", "--no-hooks", "--yes"])+ .output()+ .expect("failed to switch back to main");++ snapshot_switch("post_switch_target_variable_existing", &repo, &["feature"]);++ let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");+ let marker = worktree_path.join("target_marker.txt");+ wait_for_file_content(&marker);++ let content = fs::read_to_string(&marker).unwrap();+ assert_eq!(+ content.trim(),+ "feature",+ "target should resolve to the switched-to branch, got: {content}"+ );+}+#[rstest]fn test_post_start_mixed_user_pipeline_project_flat(repo: TestRepo) {// User has a pipeline, project has flat concurrent commands.diff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_create_upstream_template.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_upstream_template.snapindex a5a70a064..f95506d2a 100644--- a/tests/snapshots/integration__integration_tests__post_start_commands__post_create_upstream_template.snap+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_upstream_template.snap@@ -50,4 +50,4 @@ exit_code: 1[2m↳[22m [2mTo see details, run [4mwt config show[24m; to apply updates, run [4mwt config update[24m[22m[31m✗[39m [31mFailed to expand project pre-start hook: undefined value @ line 1[39m[107m [0m echo 'Upstream: {{ upstream }}' > upstream.txt-[2m↳[22m [2mAvailable variables: [4mbase[24m, [4mbase_worktree_path[24m, [4mbranch[24m, [4mcommit[24m, [4mcwd[24m, [4mdefault_branch[24m, [4mhook_type[24m, [4mmain_worktree[24m, [4mmain_worktree_path[24m, [4mprimary_worktree_path[24m, [4mremote[24m, [4mremote_url[24m, [4mrepo[24m, [4mrepo_path[24m, [4mrepo_root[24m, [4mshort_commit[24m, [4mworktree[24m, [4mworktree_name[24m, [4mworktree_path[24m[22m+[2m↳[22m [2mAvailable variables: [4mbase[24m, [4mbase_worktree_path[24m, [4mbranch[24m, [4mcommit[24m, [4mcwd[24m, [4mdefault_branch[24m, [4mhook_type[24m, [4mmain_worktree[24m, [4mmain_worktree_path[24m, [4mprimary_worktree_path[24m, [4mremote[24m, [4mremote_url[24m, [4mrepo[24m, [4mrepo_path[24m, [4mrepo_root[24m, [4mshort_commit[24m, [4mtarget[24m, [4mtarget_worktree_path[24m, [4mworktree[24m, [4mworktree_name[24m, [4mworktree_path[24m[22mdiff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_target_variable.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_target_variable.snapnew file mode 100644index 000000000..e6a730670--- /dev/null+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_target_variable.snap@@ -0,0 +1,52 @@+---+source: tests/integration_tests/post_start_commands.rs+info:+ program: wt+ args:+ - switch+ - "--create"+ - feature+ 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: ""+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"+ 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_OPENCODE_INSTALLED: "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 -----+[32m✓[39m [32mCreated branch [1mfeature[22m from [1mmain[22m and worktree @ [1m_REPO_.feature[22m[39m+[2m↳[22m [2mTo customize worktree locations, run [4mwt config create[24m[22m+[33m▲[39m [33mCannot change directory — shell integration not installed[39m+[2m↳[22m [2mTo enable automatic cd, run [4mwt config shell install[24m[22m+[36m◎[39m [36mRunning post-start: [1mproject[22m @ [1m_REPO_.feature[22m[39mdiff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_switch_target_variable_existing.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_switch_target_variable_existing.snapnew file mode 100644index 000000000..deb73b32d--- /dev/null+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_switch_target_variable_existing.snap@@ -0,0 +1,49 @@+---+source: tests/integration_tests/post_start_commands.rs+info:+ program: wt+ args:+ - switch+ - feature+ 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: ""+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"+ 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_OPENCODE_INSTALLED: "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 -----+[33m▲[39m [33mWorktree for [1mfeature[22m @ [1m_REPO_.feature[22m, but cannot change directory — shell integration not installed[39m+[2m↳[22m [2mTo enable automatic cd, run [4mwt config shell install[24m[22m+[36m◎[39m [36mRunning post-switch: [1mproject[22m @ [1m_REPO_.feature[22m[39m