Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat(hook): expose pr_number and pr_url to PR/MR worktree hooks (#2300)
Maximilian Roos68ee0a327beb
diff --git a/docs/content/hook.md b/docs/content/hook.mdindex 1ac0a18ce..cb1091e77 100644--- a/docs/content/hook.md+++ b/docs/content/hook.md@@ -134,6 +134,8 @@ Hooks can use template variables that expand at runtime:| `{{ default_branch }}` | Default branch name || `{{ remote }}` | Primary remote name || `{{ remote_url }}` | Remote URL |+| `{{ pr_number }}` | PR/MR number (when creating via `pr:N` / `mr:N`) |+| `{{ pr_url }}` | PR/MR web URL (when creating via `pr:N` / `mr:N`) || `{{ hook_type }}` | Hook type being run (e.g. `pre-start`, `pre-merge`) || `{{ hook_name }}` | Hook command name (if named) || `{{ vars.<key> }}` | Per-branch variables from [`wt config state vars`](@/config.md#wt-config-state-vars) |@@ -149,7 +151,7 @@ Bare variables (`branch`, `worktree_path`, `commit`) refer to the branch the opePre 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` 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:+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; `pr_number`/`pr_url` are populated for `post-switch`, `pre-start`, and `post-start` hooks when creating via `pr:N` or `mr:N`; `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 fb92e6087..efb190d03 100644--- a/skills/worktrunk/reference/hook.md+++ b/skills/worktrunk/reference/hook.md@@ -125,6 +125,8 @@ Hooks can use template variables that expand at runtime:| `{{ default_branch }}` | Default branch name || `{{ remote }}` | Primary remote name || `{{ remote_url }}` | Remote URL |+| `{{ pr_number }}` | PR/MR number (when creating via `pr:N` / `mr:N`) |+| `{{ pr_url }}` | PR/MR web URL (when creating via `pr:N` / `mr:N`) || `{{ hook_type }}` | Hook type being run (e.g. `pre-start`, `pre-merge`) || `{{ hook_name }}` | Hook command name (if named) || `{{ vars.<key> }}` | Per-branch variables from [`wt config state vars`](https://worktrunk.dev/config/#wt-config-state-vars) |@@ -140,7 +142,7 @@ Bare variables (`branch`, `worktree_path`, `commit`) refer to the branch the opePre 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` 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:+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; `pr_number`/`pr_url` are populated for `post-switch`, `pre-start`, and `post-start` hooks when creating via `pr:N` or `mr:N`; `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 ecd7938dd..9037b8e4a 100644--- a/src/cli/mod.rs+++ b/src/cli/mod.rs@@ -1272,6 +1272,8 @@ Hooks can use template variables that expand at runtime:| `{{ default_branch }}` | Default branch name || `{{ remote }}` | Primary remote name || `{{ remote_url }}` | Remote URL |+| `{{ pr_number }}` | PR/MR number (when creating via `pr:N` / `mr:N`) |+| `{{ pr_url }}` | PR/MR web URL (when creating via `pr:N` / `mr:N`) || `{{ hook_type }}` | Hook type being run (e.g. `pre-start`, `pre-merge`) || `{{ hook_name }}` | Hook command name (if named) || `{{ vars.<key> }}` | Per-branch variables from [`wt config state vars`](@/config.md#wt-config-state-vars) |@@ -1287,7 +1289,7 @@ Bare variables (`branch`, `worktree_path`, `commit`) refer to the branch the opePre 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` 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:+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; `pr_number`/`pr_url` are populated for `post-switch`, `pre-start`, and `post-start` hooks when creating via `pr:N` or `mr:N`; `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 1f4718be4..f2245c9ee 100644--- a/src/commands/handle_switch.rs+++ b/src/commands/handle_switch.rs@@ -208,22 +208,37 @@ pub(crate) fn approve_switch_hooks(/// Compute extra template variables from a switch result.///-/// Returns base branch context (`base`, `base_worktree_path`) for hooks and template expansion.-pub(crate) fn switch_extra_vars(result: &SwitchResult) -> Vec<(&str, &str)> {+/// Returns base branch context (`base`, `base_worktree_path`) and, for+/// `pr:N` / `mr:N` creations, `pr_number` and `pr_url` for hooks and template+/// expansion. The caller owns the `pr_number` string buffer because the+/// returned slice borrows from it.+pub(crate) fn switch_extra_vars<'a>(+ result: &'a SwitchResult,+ pr_number_buf: &'a mut String,+) -> Vec<(&'a str, &'a str)> {match result {SwitchResult::Created {base_branch,base_worktree_path,+ pr_number,+ pr_url,..- } => [- base_branch.as_deref().map(|b| ("base", b)),- base_worktree_path- .as_deref()- .map(|p| ("base_worktree_path", p)),- ]- .into_iter()- .flatten()- .collect(),+ } => {+ if let Some(n) = pr_number {+ *pr_number_buf = n.to_string();+ }+ [+ base_branch.as_deref().map(|b| ("base", b)),+ base_worktree_path+ .as_deref()+ .map(|p| ("base_worktree_path", p)),+ pr_number.map(|_| ("pr_number", pr_number_buf.as_str())),+ pr_url.as_deref().map(|u| ("pr_url", u)),+ ]+ .into_iter()+ .flatten()+ .collect()+ }SwitchResult::Existing { .. } | SwitchResult::AlreadyAt(_) => Vec::new(),}}@@ -418,7 +433,8 @@ pub fn handle_switch(// "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);+ let mut pr_number_buf = String::new();+ let mut extra_vars = switch_extra_vars(&result, &mut pr_number_buf);if let Some(target_branch) = branch_info.branch.as_deref() {extra_vars.push(("target", target_branch));}diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rsindex adf689737..2b76aa956 100644--- a/src/commands/picker/mod.rs+++ b/src/commands/picker/mod.rs@@ -747,7 +747,8 @@ pub fn handle_picker(// Spawn background hooks after success messageif hooks_approved {- let extra_vars = switch_extra_vars(&result);+ let mut pr_number_buf = String::new();+ let extra_vars = switch_extra_vars(&result, &mut pr_number_buf);spawn_switch_background_hooks(&repo,&config,diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rsindex 8306dedaa..f74cb6f22 100644--- a/src/commands/worktree/switch.rs+++ b/src/commands/worktree/switch.rs@@ -905,6 +905,16 @@ pub fn execute_switch(.and_then(|b| repo.worktree_for_branch(b).ok().flatten()).map(|p| worktrunk::path::to_posix_path(&p.to_string_lossy()));+ // PR/MR identity travels into both the pre-start hook below and the+ // SwitchResult — switch_extra_vars then forwards it to background+ // post-switch / post-start hooks.+ let (pr_number, pr_url) = match &method {+ CreationMethod::ForkRef {+ number, ref_url, ..+ } => (Some(*number), Some(ref_url.clone())),+ CreationMethod::Regular { .. } => (None, None),+ };+// Execute post-create commandsif run_hooks {let ctx = CommandContext::new(repo, config, Some(&branch), &worktree_path, force);@@ -927,19 +937,12 @@ pub fn execute_switch(ctx.execute_pre_start_commands(&extra_vars)?;}CreationMethod::ForkRef {- ref_type,- number,- ref_url,- ..+ number, ref_url, ..} => {let num_str = number.to_string();- let (num_key, url_key) = match ref_type {- 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),+ ("pr_number", &num_str),+ ("pr_url", ref_url),("target", &branch),("target_worktree_path", &target_wt_posix),];@@ -958,6 +961,8 @@ pub fn execute_switch(base_branch,base_worktree_path,from_remote,+ pr_number,+ pr_url,},SwitchBranchInfo {branch: Some(branch),diff --git a/src/commands/worktree/types.rs b/src/commands/worktree/types.rsindex edbd92f92..edcb0ac15 100644--- a/src/commands/worktree/types.rs+++ b/src/commands/worktree/types.rs@@ -31,6 +31,12 @@ pub enum SwitchResult {base_worktree_path: Option<String>,/// Remote tracking branch if auto-created from remote (e.g., "origin/feature")from_remote: Option<String>,+ /// PR/MR number when created via `pr:N` / `mr:N` (carried into post-* hook+ /// templates as `pr_number`).+ pr_number: Option<u32>,+ /// PR/MR web URL when created via `pr:N` / `mr:N` (carried into post-* hook+ /// templates as `pr_url`).+ pr_url: Option<String>,},}@@ -256,6 +262,8 @@ mod tests {base_branch: Some("main".to_string()),base_worktree_path: Some("/test/main".to_string()),from_remote: None,+ pr_number: None,+ pr_url: None,};assert_eq!(result.path(), &path);}@@ -269,6 +277,8 @@ mod tests {base_branch: None,base_worktree_path: None,from_remote: Some("origin/feature".to_string()),+ pr_number: None,+ pr_url: None,};assert_eq!(result.path(), &path);}diff --git a/src/config/expansion.rs b/src/config/expansion.rsindex 88936247c..f36a24c76 100644--- a/src/config/expansion.rs+++ b/src/config/expansion.rs@@ -97,20 +97,29 @@ fn hook_extras(hook_type: HookType) -> &'static [&'static str] {use HookType::*;match hook_type {// Switch: source branch (`base`) and destination (`target`).+ // `pr_number`/`pr_url` are populated for `post-switch` when creating+ // via `pr:N` / `mr:N`; pre-switch fires before the PR/MR API call,+ // so they're never set there but remain accepted for portability.PreSwitch | PostSwitch => &["base","base_worktree_path","target","target_worktree_path",+ "pr_number",+ "pr_url",],// 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.+ // `pr_number`/`pr_url` are populated when creating via `pr:N` / `mr:N`+ // (GitLab MRs reuse the same `pr_*` names).PreStart | PostStart => &["base","base_worktree_path","target","target_worktree_path",+ "pr_number",+ "pr_url",],// Commit: integration target for the pre-commit squash.PreCommit | PostCommit => &["target"],@@ -1720,6 +1729,35 @@ mod tests {.is_ok());+ // `pr_number`/`pr_url` are available in pre-start (populated when+ // creating via `pr:N` / `mr:N`).+ for var in ["pr_number", "pr_url"] {+ assert!(+ validate_template(+ &format!("{{{{ {var} }}}}"),+ ValidationScope::Hook(HookType::PreStart),+ &test.repo,+ "test"+ )+ .is_ok(),+ "{var} should validate in pre-start scope"+ );+ }++ // `pr_number` is not available in pre-merge (different hook type).+ let err = validate_template(+ "{{ pr_number }}",+ ValidationScope::Hook(HookType::PreMerge),+ &test.repo,+ "test",+ )+ .unwrap_err();+ assert!(+ err.message.contains("undefined value"),+ "got: {}",+ err.message+ );+// `args` is not available in SwitchExecute.let err = validate_template("{{ args }}",diff --git a/tests/integration_tests/shell_wrapper.rs b/tests/integration_tests/shell_wrapper.rsindex 14fd651e3..c518d03ef 100644--- a/tests/integration_tests/shell_wrapper.rs+++ b/tests/integration_tests/shell_wrapper.rs@@ -1549,9 +1549,6 @@ approved-commands = ["echo 'fish background task'"]// when using the --source flag (instead of being hidden with generic// wrapper error messages like "Error: cargo build failed").- // This test runs `cargo run` inside a PTY which can take longer than the- // default 60s timeout when cargo checks/compiles dependencies. Extended- // timeout configured in .config/nextest.toml.// Note: Nushell not included - this test builds custom scripts with bash syntax#[rstest]#[case("bash")]@@ -1559,6 +1556,30 @@ approved-commands = ["echo 'fish background task'"]#[case("fish")]fn test_source_flag_forwards_errors(#[case] shell: &str, repo: TestRepo) {use std::env;+ use std::os::unix::fs::PermissionsExt;++ // Stub `cargo` instead of invoking the real one. The wrapper's+ // `--source` branch shells out to `cargo run --bin wt --quiet --+ // <args>`. Real cargo unlinks and re-links `target/debug/wt` on every+ // invocation (~4% non-existence window measured locally), which+ // races concurrent tests that `spawn(target/debug/wt)` and produces+ // ENOENT flakes on Linux CI. The stub strips the cargo args and+ // execs the existing wt binary directly — same end-to-end coverage+ // of error pass-through through the `--source` branch, no race.+ let stub_dir = repo.root_path().join("stub-bin");+ fs::create_dir_all(&stub_dir).unwrap();+ let stub_cargo = stub_dir.join("cargo");+ fs::write(+ &stub_cargo,+ "#!/bin/sh\nshift 5\nexec \"$WORKTRUNK_BIN\" \"$@\"\n",+ )+ .unwrap();+ fs::set_permissions(&stub_cargo, fs::Permissions::from_mode(0o755)).unwrap();+ let stub_path = format!(+ "{}:{}",+ stub_dir.display(),+ env::var("PATH").unwrap_or_default()+ );// Get the worktrunk source directory (where this test is running from)// This is the directory that contains Cargo.toml with the workspace@@ -1568,9 +1589,9 @@ approved-commands = ["echo 'fish background task'"]let mut script = String::new();append_wrapper_setup(&mut script, shell, &repo);- // Try to run wt --source with an invalid subcommand- // The --source flag triggers cargo build (which succeeds)- // Then it tries to run 'wt foo' which should fail with "unrecognized subcommand"+ // Try to run wt --source with an invalid subcommand. The wrapper+ // routes this through the stub `cargo`, which execs the real wt;+ // wt then fails with clap's "unrecognized subcommand" error.script.push_str("wt --source foo\n");// Wrap in subshell to merge stderr@@ -1582,6 +1603,7 @@ approved-commands = ["echo 'fish background task'"]let config_path = repo.test_config_path().to_string_lossy().to_string();let approvals_path = repo.test_approvals_path().to_string_lossy().to_string();let env_vars: Vec<(&str, &str)> = vec![+ ("PATH", &stub_path),("CLICOLOR_FORCE", "1"),("WORKTRUNK_CONFIG_PATH", &config_path),("WORKTRUNK_APPROVALS_PATH", &approvals_path),diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rsindex 365c97c62..22b5f1eba 100644--- a/tests/integration_tests/switch.rs+++ b/tests/integration_tests/switch.rs@@ -1,7 +1,8 @@use crate::common::{TestRepo, configure_directive_files, directive_files, make_snapshot_cmd,make_snapshot_cmd_with_global_flags, repo, repo_with_remote, set_temp_home_env,- setup_home_snapshot_settings, setup_snapshot_settings, temp_home, wt_command,+ setup_home_snapshot_settings, setup_snapshot_settings, temp_home, wait_for_file_content,+ wt_command,};use ansi_str::AnsiStr;use insta_cmd::assert_cmd_snapshot;@@ -2011,6 +2012,106 @@ fn test_switch_pr_fork(#[from(repo_with_remote)] repo: TestRepo) {});}+/// `pre-start`, `post-start`, and `post-switch` hooks on PR/MR-created worktrees+/// see `pr_number` and `pr_url` in their template context. Both GitHub PRs and+/// GitLab MRs canonicalize to the same `pr_*` names — hook authors don't need+/// to branch on platform. Pre-switch fires before PR resolution and never sees+/// them.+#[rstest]+fn test_switch_pr_hooks_see_pr_vars(#[from(repo_with_remote)] repo: TestRepo) {+ // Set up the same fork-PR scenario as test_switch_pr_fork: a refs/pull/42/head on the+ // bare remote, origin redirected to GitHub-style URL, and `gh api` mocked.+ repo.run_git(&["checkout", "-b", "pr-source"]);+ fs::write(repo.root_path().join("pr-file.txt"), "PR content").unwrap();+ repo.run_git(&["add", "pr-file.txt"]);+ repo.run_git(&["commit", "-m", "PR commit"]);++ let commit_sha = repo+ .git_command()+ .args(["rev-parse", "HEAD"])+ .run()+ .unwrap();+ let sha = String::from_utf8_lossy(&commit_sha.stdout)+ .trim()+ .to_string();+ repo.run_git(&["push", "origin", &format!("{}:refs/pull/42/head", sha)]);+ repo.run_git(&["checkout", "main"]);++ let bare_url = String::from_utf8_lossy(+ &repo+ .git_command()+ .args(["config", "remote.origin.url"])+ .run()+ .unwrap()+ .stdout,+ )+ .trim()+ .to_string();+ repo.run_git(&[+ "remote",+ "set-url",+ "origin",+ "https://github.com/owner/test-repo.git",+ ]);+ repo.run_git(&[+ "config",+ &format!("url.{}.insteadOf", bare_url),+ "https://github.com/owner/test-repo.git",+ ]);++ let gh_response = r#"{+ "title": "Add feature fix for edge case",+ "user": {"login": "contributor"},+ "state": "open",+ "draft": false,+ "head": {+ "ref": "feature-fix",+ "repo": {"name": "test-repo", "owner": {"login": "contributor"}}+ },+ "base": {+ "ref": "main",+ "repo": {"name": "test-repo", "owner": {"login": "owner"}}+ },+ "html_url": "https://github.com/owner/test-repo/pull/42"+ }"#;+ let mock_bin = setup_mock_gh_for_pr(&repo, Some(gh_response));++ // Each hook writes its own marker in the primary worktree so we can verify+ // post-switch + post-start (background) populate pr_number/pr_url too.+ // {{ repo_path }} is always the main repo's working tree.+ repo.write_project_config(+ r#"pre-start = "echo 'pr_number={{ pr_number }} pr_url={{ pr_url }}' > {{ repo_path }}/pre_start.txt"+post-start = "echo 'pr_number={{ pr_number }} pr_url={{ pr_url }}' > {{ repo_path }}/post_start.txt"+post-switch = "echo 'pr_number={{ pr_number }} pr_url={{ pr_url }}' > {{ repo_path }}/post_switch.txt"+"#,+ );++ let mut cmd = repo.wt_command();+ cmd.args(["switch", "pr:42", "--yes"]);+ configure_mock_gh_env(&mut cmd, &mock_bin);+ let output = cmd.output().expect("wt switch pr:42 should run");+ assert!(+ output.status.success(),+ "wt switch pr:42 failed: stdout={}\nstderr={}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr),+ );++ let expected = "pr_number=42 pr_url=https://github.com/owner/test-repo/pull/42";+ for marker in ["pre_start.txt", "post_start.txt", "post_switch.txt"] {+ let path = repo.root_path().join(marker);+ // post-* hooks run in the background; poll until the file appears.+ wait_for_file_content(&path);+ let contents = fs::read_to_string(&path)+ .unwrap_or_else(|e| panic!("{marker} should have been written: {e}"));+ assert_eq!(+ contents.trim(),+ expected,+ "{marker} hook should see canonical pr_number and pr_url variables",+ );+ }+}+/// Test fork PR when origin points to fork (no remote for base repo)////// User scenario: