Skip to content

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

perf(alias): reuse cached HEAD SHA on on-branch dispatch hot path (#2374)

Maximilian Roose8a5ab2ab8d9
diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rs
index 61345ef49..b5b5c3cb7 100644
--- a/src/commands/command_executor.rs
+++ b/src/commands/command_executor.rs
@@ -186,16 +186,21 @@ pub fn build_hook_context(
// Resolve commit from the Active branch, not HEAD at discovery path.
// This ensures {{ commit }} follows the Active branch even when the
// CommandContext points to a different worktree than where we're running.
- // When there is no Active branch (detached HEAD), read the current
- // worktree's HEAD SHA via the cache primed by `WorkingTree::prewarm_info`
- // on the alias hot path.
+ // When `ctx.branch` matches the running worktree's current branch — the
+ // alias / hook hot path — reuse the HEAD SHA already cached by
+ // `WorkingTree::prewarm_info` instead of firing a fresh `rev-parse`.
+ // The same cache read covers detached HEAD (`ctx.branch == None` and the
+ // running worktree is also detached). Cross-worktree contexts, where
+ // `ctx.branch` names a different branch than the running worktree, fall
+ // through to `rev-parse <branch>` in the discovery path.
+ let wt = ctx.repo.current_worktree();
let commit = match ctx.branch {
- Some(branch) => ctx
+ Some(branch) if wt.branch().ok().flatten().as_deref() != Some(branch) => ctx
.repo
.run_command(&["rev-parse", branch])
.ok()
.map(|s| s.trim().to_owned()),
- None => ctx.repo.current_worktree().head_sha().ok().flatten(),
+ _ => wt.head_sha().ok().flatten(),
};
if let Some(commit) = commit {
if commit.len() >= 7 {
diff --git a/tests/integration_tests/eval.rs b/tests/integration_tests/eval.rs
index e7093cfdc..78a1eba79 100644
--- a/tests/integration_tests/eval.rs
+++ b/tests/integration_tests/eval.rs
@@ -105,3 +105,28 @@ fn test_eval_conditional(repo: TestRepo) {
None,
));
}
+
+/// `{{ commit }}` resolves to the running worktree's HEAD SHA on the on-branch
+/// hot path. `build_hook_context` reads the SHA from the cache primed by
+/// `WorkingTree::prewarm_info` instead of firing `git rev-parse <branch>`.
+#[rstest]
+fn test_eval_commit_matches_head_sha(repo: TestRepo) {
+ let expected = repo.git_output(&["rev-parse", "HEAD"]);
+
+ let output = repo
+ .wt_command()
+ .args(["step", "eval", "{{ commit }}"])
+ .output()
+ .expect("run wt step eval");
+
+ assert!(
+ output.status.success(),
+ "wt step eval failed: stderr={}",
+ String::from_utf8_lossy(&output.stderr),
+ );
+ assert_eq!(
+ String::from_utf8_lossy(&output.stdout).trim(),
+ expected,
+ "eval commit should match HEAD SHA"
+ );
+}
diff --git a/tests/integration_tests/for_each.rs b/tests/integration_tests/for_each.rs
index 9b99f9840..e57a2e381 100644
--- a/tests/integration_tests/for_each.rs
+++ b/tests/integration_tests/for_each.rs
@@ -274,6 +274,76 @@ fn test_for_each_json(mut repo: TestRepo) {
);
}
+/// `{{ commit }}` must resolve per-worktree when iterating across worktrees
+/// whose branches differ from the running worktree's branch. This exercises
+/// the `rev-parse <branch>` fallback in `build_hook_context` — the on-branch
+/// cache-reuse path would return the main worktree's SHA for every iteration.
+#[rstest]
+fn test_for_each_commit_matches_per_worktree_head(repo: TestRepo) {
+ // Give each fixture feature worktree a distinct HEAD so a buggy cache
+ // reuse (same SHA everywhere) fails visibly.
+ let mut expected = std::collections::HashMap::new();
+ expected.insert("main".to_string(), repo.git_output(&["rev-parse", "HEAD"]));
+ for branch in ["feature-a", "feature-b", "feature-c"] {
+ let wt_path = repo
+ .root_path()
+ .parent()
+ .unwrap()
+ .join(format!("repo.{branch}"));
+ repo.run_git_in(
+ &wt_path,
+ &["commit", "--allow-empty", "-m", &format!("{branch} tip")],
+ );
+ let sha = repo
+ .git_command()
+ .args(["rev-parse", "HEAD"])
+ .current_dir(&wt_path)
+ .run()
+ .unwrap();
+ expected.insert(
+ branch.to_string(),
+ String::from_utf8_lossy(&sha.stdout).trim().to_owned(),
+ );
+ }
+
+ // echo both fields so we can match each SHA to its branch.
+ let output = repo
+ .wt_command()
+ .args([
+ "step",
+ "for-each",
+ "--",
+ "echo",
+ "{{ branch }} {{ commit }}",
+ ])
+ .output()
+ .expect("run wt step for-each");
+
+ assert!(
+ output.status.success(),
+ "for-each failed: stderr={}",
+ String::from_utf8_lossy(&output.stderr),
+ );
+
+ // for-each pipes foreground output through wt's styling layer, which may
+ // wrap lines in ANSI codes. Substring-match `branch sha` anywhere in the
+ // combined output — each worktree's echo contributes exactly one such
+ // pairing, so a mis-resolved SHA (e.g., main's SHA appearing after
+ // feature-b's branch label) is still caught.
+ let combined = format!(
+ "{}{}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr)
+ );
+ for (branch, sha) in &expected {
+ let needle = format!("{branch} {sha}");
+ assert!(
+ combined.contains(&needle),
+ "expected {branch}'s {{{{ commit }}}} = {sha} in output\noutput={combined}",
+ );
+ }
+}
+
#[rstest]
fn test_for_each_json_with_failure(repo: TestRepo) {
repo.commit("initial");