Skip to content

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

perf(alias): O(1) upstream lookup in template context (#2337)

Maximilian Roos4f9bd575ae3b
diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rs
index e7f6cbe99..36d20e3c8 100644
--- a/src/commands/command_executor.rs
+++ b/src/commands/command_executor.rs
@@ -202,7 +202,7 @@ pub fn build_hook_context(
map.insert("remote_url".into(), url);
}
if let Some(branch) = ctx.branch
- && let Ok(Some(upstream)) = ctx.repo.branch(branch).upstream()
+ && let Ok(Some(upstream)) = ctx.repo.branch(branch).upstream_single()
{
map.insert("upstream".into(), upstream);
}
diff --git a/src/git/repository/branch.rs b/src/git/repository/branch.rs
index 98e5be75a..273ca67bf 100644
--- a/src/git/repository/branch.rs
+++ b/src/git/repository/branch.rs
@@ -92,9 +92,15 @@ impl<'a> Branch<'a> {
/// Get the upstream tracking branch for this branch.
///
- /// Uses [`@{upstream}` syntax][1] to resolve the tracking branch.
+ /// First call in a process triggers `fetch_all_upstreams` — one
+ /// `git for-each-ref` over every local branch, cached for subsequent
+ /// calls. Amortizes well when callers query many branches
+ /// (`wt list`, integration target resolution). Prefer
+ /// [`upstream_single`] on hot paths that look up exactly one branch
+ /// (e.g. alias/hook template expansion), where the bulk scan becomes
+ /// O(branches) overhead the single call can't amortize.
///
- /// [1]: https://git-scm.com/docs/gitrevisions#Documentation/gitrevisions.txt-emltaboranchgtemuaboranchgtupaboranchgtupstream
+ /// [`upstream_single`]: Self::upstream_single
pub fn upstream(&self) -> anyhow::Result<Option<String>> {
let upstreams = self
.repo
@@ -104,6 +110,33 @@ impl<'a> Branch<'a> {
Ok(upstreams.get(&self.name).cloned().unwrap_or(None))
}
+ /// Get this branch's upstream without the bulk scan used by
+ /// [`upstream`]. Runs one `git for-each-ref` scoped to this branch's
+ /// ref — O(1) in local branch count.
+ ///
+ /// Handles the `[gone]` track state the same way as the bulk path:
+ /// a configured-but-missing upstream reads as `None`.
+ ///
+ /// [`upstream`]: Self::upstream
+ pub fn upstream_single(&self) -> anyhow::Result<Option<String>> {
+ let output = self.repo.run_command(&[
+ "for-each-ref",
+ "--format=%(upstream:short)\t%(upstream:track)",
+ &format!("refs/heads/{}", self.name),
+ ])?;
+ let Some(line) = output.lines().next() else {
+ return Ok(None);
+ };
+ let (upstream, track) = line
+ .split_once('\t')
+ .expect("for-each-ref emits a tab between the two format fields");
+ if upstream.is_empty() || track == "[gone]" {
+ Ok(None)
+ } else {
+ Ok(Some(upstream.to_string()))
+ }
+ }
+
/// Unset the upstream tracking branch for this branch.
///
/// This removes the tracking relationship, preventing accidental pushes