Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat(templates): add expected_worktree_path_of_branch() template function (#4502)
Worktrunk Bot4cb4267619ae
diff --git a/docs/src/content/docs/hook.md b/docs/src/content/docs/hook.mdindex cb317f55d..b6de07fef 100644--- a/docs/src/content/docs/hook.md+++ b/docs/src/content/docs/hook.md@@ -250,6 +250,7 @@ Templates also support functions for dynamic lookups:| Function | Example | Description ||----------|---------|-------------|| `worktree_path_of_branch(branch)` | `{{ worktree_path_of_branch("main") }}` | Look up the path of a branch's worktree |+| `expected_worktree_path_of_branch(branch)` | `{{ expected_worktree_path_of_branch("feature") }}` | Where `wt switch` expects the branch's worktree |The `worktree_path_of_branch` function returns the filesystem path of a worktree given a branch name, or an empty string if no worktree exists for that branch. This is useful for referencing files in other worktrees:@@ -260,6 +261,12 @@ The `worktree_path_of_branch` function returns the filesystem path of a worktreesetup = "cp {{ worktree_path_of_branch('main') }}/config.local {{ worktree_path }}"```+The `expected_worktree_path_of_branch` function returns the path `wt switch --create` would use for a branch, whether or not a worktree exists there. Unlike `worktree_path_of_branch`, it still returns that path after the worktree there has moved to another branch. For example, this switches to the worktree at `feature`'s path, whichever branch it now holds:++```bash+wt switch "$(wt step eval "{{ expected_worktree_path_of_branch('feature') }}")"+```+## Interactive hooksHooks can prompt when run serially in the foreground, as in this `pre-start` hook:diff --git a/plugins/worktrunk/skills/worktrunk/reference/hook.md b/plugins/worktrunk/skills/worktrunk/reference/hook.mdindex b0e4af4b0..337412e38 100644--- a/plugins/worktrunk/skills/worktrunk/reference/hook.md+++ b/plugins/worktrunk/skills/worktrunk/reference/hook.md@@ -244,6 +244,7 @@ Templates also support functions for dynamic lookups:| Function | Example | Description ||----------|---------|-------------|| `worktree_path_of_branch(branch)` | `{{ worktree_path_of_branch("main") }}` | Look up the path of a branch's worktree |+| `expected_worktree_path_of_branch(branch)` | `{{ expected_worktree_path_of_branch("feature") }}` | Where `wt switch` expects the branch's worktree |The `worktree_path_of_branch` function returns the filesystem path of a worktree given a branch name, or an empty string if no worktree exists for that branch. This is useful for referencing files in other worktrees:@@ -254,6 +255,12 @@ The `worktree_path_of_branch` function returns the filesystem path of a worktreesetup = "cp {{ worktree_path_of_branch('main') }}/config.local {{ worktree_path }}"```+The `expected_worktree_path_of_branch` function returns the path `wt switch --create` would use for a branch, whether or not a worktree exists there. Unlike `worktree_path_of_branch`, it still returns that path after the worktree there has moved to another branch. For example, this switches to the worktree at `feature`'s path, whichever branch it now holds:++```bash+wt switch "$(wt step eval "{{ expected_worktree_path_of_branch('feature') }}")"+```+## Interactive hooksHooks can prompt when run serially in the foreground, as in this `pre-start` hook:diff --git a/skills/worktrunk/reference/hook.md b/skills/worktrunk/reference/hook.mdindex b0e4af4b0..337412e38 100644--- a/skills/worktrunk/reference/hook.md+++ b/skills/worktrunk/reference/hook.md@@ -244,6 +244,7 @@ Templates also support functions for dynamic lookups:| Function | Example | Description ||----------|---------|-------------|| `worktree_path_of_branch(branch)` | `{{ worktree_path_of_branch("main") }}` | Look up the path of a branch's worktree |+| `expected_worktree_path_of_branch(branch)` | `{{ expected_worktree_path_of_branch("feature") }}` | Where `wt switch` expects the branch's worktree |The `worktree_path_of_branch` function returns the filesystem path of a worktree given a branch name, or an empty string if no worktree exists for that branch. This is useful for referencing files in other worktrees:@@ -254,6 +255,12 @@ The `worktree_path_of_branch` function returns the filesystem path of a worktreesetup = "cp {{ worktree_path_of_branch('main') }}/config.local {{ worktree_path }}"```+The `expected_worktree_path_of_branch` function returns the path `wt switch --create` would use for a branch, whether or not a worktree exists there. Unlike `worktree_path_of_branch`, it still returns that path after the worktree there has moved to another branch. For example, this switches to the worktree at `feature`'s path, whichever branch it now holds:++```bash+wt switch "$(wt step eval "{{ expected_worktree_path_of_branch('feature') }}")"+```+## Interactive hooksHooks can prompt when run serially in the foreground, as in this `pre-start` hook:diff --git a/src/cli/mod.rs b/src/cli/mod.rsindex 7936a06e1..2251e95e1 100644--- a/src/cli/mod.rs+++ b/src/cli/mod.rs@@ -1874,6 +1874,7 @@ Templates also support functions for dynamic lookups:| Function | Example | Description ||----------|---------|-------------|| `worktree_path_of_branch(branch)` | `{{ worktree_path_of_branch("main") }}` | Look up the path of a branch's worktree |+| `expected_worktree_path_of_branch(branch)` | `{{ expected_worktree_path_of_branch("feature") }}` | Where `wt switch` expects the branch's worktree |The `worktree_path_of_branch` function returns the filesystem path of a worktree given a branch name, or an empty string if no worktree exists for that branch. This is useful for referencing files in other worktrees:@@ -1884,6 +1885,12 @@ The `worktree_path_of_branch` function returns the filesystem path of a worktreesetup = "cp {{ worktree_path_of_branch('main') }}/config.local {{ worktree_path }}"```+The `expected_worktree_path_of_branch` function returns the path `wt switch --create` would use for a branch, whether or not a worktree exists there. Unlike `worktree_path_of_branch`, it still returns that path after the worktree there has moved to another branch. For example, this switches to the worktree at `feature`'s path, whichever branch it now holds:++```bash+wt switch "$(wt step eval "{{ expected_worktree_path_of_branch('feature') }}")"+```+## Interactive hooksHooks can prompt when run serially in the foreground, as in this `pre-start` hook:diff --git a/src/commands/worktree/resolve.rs b/src/commands/worktree/resolve.rsindex 312313cf9..17f4fe0d6 100644--- a/src/commands/worktree/resolve.rs+++ b/src/commands/worktree/resolve.rs@@ -9,7 +9,6 @@ use std::io::IsTerminal;use std::path::PathBuf;use color_print::cformat;-use normalize_path::NormalizePath;use path_slash::PathExt as _;use worktrunk::config::UserConfig;use worktrunk::git::Repository;@@ -31,36 +30,7 @@ pub fn compute_worktree_path(branch: &str,config: &UserConfig,) -> anyhow::Result<PathBuf> {- let repo_root = repo.repo_path()?;- let default_branch = repo.default_branch().unwrap_or_default();- let is_bare = repo.is_bare()?;-- // Default branch lives at repo root (main worktree), not a templated path.- // Exception: bare repos have no main worktree, so all branches use templated paths.- if !is_bare && branch == default_branch {- return Ok(repo_root.to_path_buf());- }-- let repo_name = repo_root- .file_name()- .ok_or_else(|| {- anyhow::anyhow!(- "Repository path has no filename: {}",- format_path_for_display(repo_root)- )- })?- .to_str()- .ok_or_else(|| {- anyhow::anyhow!(- "Repository path contains invalid UTF-8: {}",- format_path_for_display(repo_root)- )- })?;-- let project = repo.project_identifier().ok();- let expanded_path = config.format_path(repo_name, branch, repo, project.as_deref())?;-- Ok(repo_root.join(expanded_path).normalize())+ config.expected_worktree_path(repo, branch)}/// Check if a worktree is at its expected path based on config template.diff --git a/src/config/expansion.rs b/src/config/expansion.rsindex 0f24cf7d9..2123592cb 100644--- a/src/config/expansion.rs+++ b/src/config/expansion.rs@@ -956,6 +956,34 @@ pub fn template_environment(repo: &Repository) -> Environment<'static> {.unwrap_or_default()});+ // Register expected_worktree_path_of_branch: where `wt switch --create` would put a+ // branch's worktree, whether or not one exists there. Rendering the+ // `worktree-path` template re-enters this environment, so a template+ // that calls the function errors rather than recursing.+ let repo_clone = repo.clone();+ env.add_function(+ "expected_worktree_path_of_branch",+ move |branch: String| -> Result<String, minijinja::Error> {+ thread_local! {+ static IN_EXPECTED_WORKTREE_PATH_OF_BRANCH: std::cell::Cell<bool> =+ const { std::cell::Cell::new(false) };+ }+ if IN_EXPECTED_WORKTREE_PATH_OF_BRANCH.replace(true) {+ return Err(minijinja::Error::new(+ ErrorKind::InvalidOperation,+ "expected_worktree_path_of_branch cannot be used in the worktree-path template",+ ));+ }+ let result = repo_clone+ .user_config()+ .expected_worktree_path(&repo_clone, &branch);+ IN_EXPECTED_WORKTREE_PATH_OF_BRANCH.set(false);+ result+ .map(|p| to_posix_path(&p.to_string_lossy()))+ .map_err(|e| minijinja::Error::new(ErrorKind::InvalidOperation, format!("{e:#}")))+ },+ );+env}@@ -1133,6 +1161,8 @@ pub fn validate_template(/// # Functions/// - `worktree_path_of_branch(branch)` — Look up the filesystem path of a branch's worktree/// Returns empty string if branch has no worktree.+/// - `expected_worktree_path_of_branch(branch)` — Where `wt switch` expects the branch's worktree,+/// from the `worktree-path` template. Returns the path whether or not it exists.////// The `name` parameter appears in error messages to help identify which template failed.pub fn expand_template(diff --git a/src/config/user/accessors.rs b/src/config/user/accessors.rsindex a4b188570..cbe569ef6 100644--- a/src/config/user/accessors.rs+++ b/src/config/user/accessors.rs@@ -4,10 +4,14 @@//! project by merging global settings with project-specific overrides.use std::collections::{BTreeMap, HashMap};+use std::path::PathBuf;++use normalize_path::NormalizePath;use crate::config::HooksConfig;use crate::config::commands::CommandConfig;use crate::config::expansion::expand_template;+use crate::path::format_path_for_display;use crate::shell_exec::ShellEscapeMode;use super::UserConfig;@@ -271,4 +275,47 @@ impl UserConfig {).map(|p| shellexpand::tilde(&p).into_owned())?)}++ /// Compute the expected worktree path for a branch name.+ ///+ /// For the default branch, returns the repo root (main worktree location).+ /// For other branches, applies the `worktree-path` template from config.+ ///+ /// Uses cached values from Repository for `default_branch` and `is_bare`.+ pub fn expected_worktree_path(+ &self,+ repo: &crate::git::Repository,+ branch: &str,+ ) -> anyhow::Result<PathBuf> {+ let repo_root = repo.repo_path()?;+ let default_branch = repo.default_branch().unwrap_or_default();+ let is_bare = repo.is_bare()?;++ // Default branch lives at repo root (main worktree), not a templated path.+ // Exception: bare repos have no main worktree, so all branches use templated paths.+ if !is_bare && branch == default_branch {+ return Ok(repo_root.to_path_buf());+ }++ let repo_name = repo_root+ .file_name()+ .ok_or_else(|| {+ anyhow::anyhow!(+ "Repository path has no filename: {}",+ format_path_for_display(repo_root)+ )+ })?+ .to_str()+ .ok_or_else(|| {+ anyhow::anyhow!(+ "Repository path contains invalid UTF-8: {}",+ format_path_for_display(repo_root)+ )+ })?;++ let project = repo.project_identifier().ok();+ let expanded_path = self.format_path(repo_name, branch, repo, project.as_deref())?;++ Ok(repo_root.join(expanded_path).normalize())+ }}diff --git a/tests/integration_tests/eval.rs b/tests/integration_tests/eval.rsindex 7a0859878..c7988431c 100644--- a/tests/integration_tests/eval.rs+++ b/tests/integration_tests/eval.rs@@ -203,3 +203,66 @@ fn test_eval_commit_matches_head_sha(repo: TestRepo) {"eval commit should match HEAD SHA");}++/// `expected_worktree_path_of_branch` renders the `worktree-path` template for a branch+/// even when another branch occupies that path, which is where+/// `worktree_path_of_branch` comes back empty.+#[rstest]+fn test_eval_expected_worktree_path_of_branch(repo: TestRepo) {+ repo.write_test_config(+ "worktree-path = \"{{ repo_path }}/../{{ repo }}.wt.{{ branch | sanitize }}\"\n",+ );+ let repo_name = repo.root_path().file_name().unwrap().to_str().unwrap();+ let occupied = repo+ .root_path()+ .parent()+ .unwrap()+ .join(format!("{repo_name}.wt.feature-x"));+ repo.run_git(&["worktree", "add", "-b", "other", occupied.to_str().unwrap()]);++ let output = repo+ .wt_command()+ .args([+ "step",+ "eval",+ "{{ expected_worktree_path_of_branch('feature/x') }}|{{ worktree_path_of_branch('feature/x') }}|{{ expected_worktree_path_of_branch('main') }}",+ ])+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "stderr: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ let stdout = String::from_utf8_lossy(&output.stdout);+ let parts: Vec<&str> = stdout.trim().split('|').collect();+ let file_name = |p: &str| p.rsplit(['/', '\\']).next().unwrap().to_string();+ assert_eq!(file_name(parts[0]), format!("{repo_name}.wt.feature-x"));+ assert_eq!(parts[1], "");+ // The default branch lives at the repo root, not a templated path.+ assert_eq!(file_name(parts[2]), repo_name);+}++/// A `worktree-path` template that calls `expected_worktree_path_of_branch` errors+/// instead of recursing.+#[rstest]+fn test_eval_expected_worktree_path_of_branch_in_worktree_path_template(repo: TestRepo) {+ repo.write_test_config("worktree-path = \"{{ expected_worktree_path_of_branch(branch) }}\"\n");+ let output = repo+ .wt_command()+ .args([+ "step",+ "eval",+ "{{ expected_worktree_path_of_branch('feature') }}",+ ])+ .output()+ .unwrap();+ assert_eq!(output.status.code(), Some(1));+ assert!(+ String::from_utf8_lossy(&output.stderr).contains(+ "expected_worktree_path_of_branch cannot be used in the worktree-path template"+ ),+ "stderr: {}",+ String::from_utf8_lossy(&output.stderr)+ );+}