Skip to content

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

fix(list): qualify remote refs so same-named local branch can't shadow them (#2365)

Maximilian Roos3c224cba7b6a
diff --git a/src/commands/list/collect/tasks.rs b/src/commands/list/collect/tasks.rs
index b28d2d7a9..c09b88f82 100644
--- a/src/commands/list/collect/tasks.rs
+++ b/src/commands/list/collect/tasks.rs
@@ -181,11 +181,10 @@ impl Task for AheadBehindTask {
// keeps both paths consistent.
let head = ctx
.branch_ref
- .branch
- .as_deref()
- .unwrap_or(&ctx.branch_ref.commit_sha);
+ .integration_ref()
+ .unwrap_or_else(|| ctx.branch_ref.commit_sha.clone());
let (ahead, behind) = repo
- .ahead_behind(&base, head)
+ .ahead_behind(&base, &head)
.map_err(|e| ctx.error(Self::KIND, &e))?;
Ok(TaskResult::AheadBehind {
@@ -219,11 +218,10 @@ impl Task for CommittedTreesMatchTask {
// equivalent; for detached HEAD, commit_sha is the only option.
let ref_to_check = ctx
.branch_ref
- .branch
- .as_deref()
- .unwrap_or(&ctx.branch_ref.commit_sha);
+ .integration_ref()
+ .unwrap_or_else(|| ctx.branch_ref.commit_sha.clone());
let committed_trees_match = repo
- .trees_match(ref_to_check, &base)
+ .trees_match(&ref_to_check, &base)
.map_err(|e| ctx.error(Self::KIND, &e))?;
Ok(TaskResult::CommittedTreesMatch {
item_idx: ctx.item_idx,
@@ -250,7 +248,7 @@ impl Task for HasFileChangesTask {
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
// No branch name (detached HEAD) - return conservative default (assume has changes)
- let Some(branch) = ctx.branch_ref.branch.as_deref() else {
+ let Some(branch) = ctx.branch_ref.integration_ref() else {
return Ok(TaskResult::HasFileChanges {
item_idx: ctx.item_idx,
has_file_changes: true,
@@ -265,7 +263,7 @@ impl Task for HasFileChangesTask {
};
let repo = &ctx.repo;
let has_file_changes = repo
- .has_added_changes(branch, &target)
+ .has_added_changes(&branch, &target)
.map_err(|e| ctx.error(Self::KIND, &e))?;
Ok(TaskResult::HasFileChanges {
@@ -297,7 +295,7 @@ impl Task for WouldMergeAddTask {
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
// No branch name (detached HEAD) - return conservative default (assume would add)
- let Some(branch) = ctx.branch_ref.branch.as_deref() else {
+ let Some(branch) = ctx.branch_ref.integration_ref() else {
return Ok(TaskResult::WouldMergeAdd {
item_idx: ctx.item_idx,
would_merge_add: true,
@@ -314,7 +312,7 @@ impl Task for WouldMergeAddTask {
};
let probe = ctx
.repo
- .merge_integration_probe(branch, &base)
+ .merge_integration_probe(&branch, &base)
.map_err(|e| ctx.error(Self::KIND, &e))?;
Ok(TaskResult::WouldMergeAdd {
item_idx: ctx.item_idx,
@@ -350,11 +348,10 @@ impl Task for IsAncestorTask {
// for rationale (rebase-in-progress transient HEAD).
let ref_to_check = ctx
.branch_ref
- .branch
- .as_deref()
- .unwrap_or(&ctx.branch_ref.commit_sha);
+ .integration_ref()
+ .unwrap_or_else(|| ctx.branch_ref.commit_sha.clone());
let is_ancestor = repo
- .is_ancestor(ref_to_check, &base)
+ .is_ancestor(&ref_to_check, &base)
.map_err(|e| ctx.error(Self::KIND, &e))?;
Ok(TaskResult::IsAncestor {
@@ -383,11 +380,10 @@ impl Task for BranchDiffTask {
// for rationale (rebase-in-progress transient HEAD).
let ref_to_check = ctx
.branch_ref
- .branch
- .as_deref()
- .unwrap_or(&ctx.branch_ref.commit_sha);
+ .integration_ref()
+ .unwrap_or_else(|| ctx.branch_ref.commit_sha.clone());
let diff = repo
- .branch_diff_stats(&base, ref_to_check)
+ .branch_diff_stats(&base, &ref_to_check)
.map_err(|e| ctx.error(Self::KIND, &e))?;
Ok(TaskResult::BranchDiff {
@@ -460,11 +456,10 @@ impl Task for MergeTreeConflictsTask {
// for rationale (rebase-in-progress transient HEAD).
let ref_to_check = ctx
.branch_ref
- .branch
- .as_deref()
- .unwrap_or(&ctx.branch_ref.commit_sha);
+ .integration_ref()
+ .unwrap_or_else(|| ctx.branch_ref.commit_sha.clone());
let has_merge_tree_conflicts = repo
- .has_merge_conflicts(&base, ref_to_check)
+ .has_merge_conflicts(&base, &ref_to_check)
.map_err(|e| ctx.error(Self::KIND, &e))?;
Ok(TaskResult::MergeTreeConflicts {
item_idx: ctx.item_idx,
diff --git a/src/git/mod.rs b/src/git/mod.rs
index cf74881ea..ce9feb887 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -468,6 +468,29 @@ impl BranchRef {
pub fn has_worktree(&self) -> bool {
self.worktree_path.is_some()
}
+
+ /// Git ref string suitable for passing to integration helpers.
+ ///
+ /// Remote branches are stored as short names like `origin/foo` (from
+ /// `%(refname:lstrip=2)` in `list_remote_branches`). Git allows local
+ /// branches literally named `origin/foo`, so passing the short form to
+ /// `git rev-parse` resolves to `refs/heads/origin/foo` — the local — and
+ /// the remote row silently computes stats against the wrong ref.
+ ///
+ /// Qualifying the remote case to `refs/remotes/<name>` makes the ref
+ /// unambiguous; local branches keep the short form so
+ /// `resolve_preferring_branch` can still promote them over same-named
+ /// tags.
+ ///
+ /// Returns `None` for detached HEAD (no branch name).
+ pub fn integration_ref(&self) -> Option<String> {
+ let name = self.branch.as_deref()?;
+ Some(if self.is_remote {
+ format!("refs/remotes/{name}")
+ } else {
+ name.to_string()
+ })
+ }
}
impl From<&WorktreeInfo> for BranchRef {
@@ -803,6 +826,31 @@ mod tests {
assert!(branch_ref.is_remote);
}
+ #[test]
+ fn test_branch_ref_integration_ref() {
+ // Remote branches qualify to refs/remotes/ so they don't get shadowed
+ // by a same-named local branch (git allows local branches literally
+ // named `origin/foo`).
+ assert_eq!(
+ BranchRef::remote_branch("origin/foo", "abc").integration_ref(),
+ Some("refs/remotes/origin/foo".to_string())
+ );
+ // Local branches keep the short form so `resolve_preferring_branch`
+ // can still promote them over same-named tags.
+ assert_eq!(
+ BranchRef::local_branch("feature", "abc").integration_ref(),
+ Some("feature".to_string())
+ );
+ // Detached HEAD has no branch name — caller falls back to commit_sha.
+ let detached = BranchRef {
+ branch: None,
+ commit_sha: "abc".into(),
+ worktree_path: None,
+ is_remote: false,
+ };
+ assert_eq!(detached.integration_ref(), None);
+ }
+
#[test]
fn test_branch_tracks_ref_matching() {
let test = crate::testing::TestRepo::with_initial_commit();
diff --git a/tests/integration_tests/list.rs b/tests/integration_tests/list.rs
index e04d060a9..3096b8f04 100644
--- a/tests/integration_tests/list.rs
+++ b/tests/integration_tests/list.rs
@@ -469,6 +469,58 @@ fn test_list_with_orphaned_remote_ref(#[from(repo_with_remote)] repo: TestRepo)
);
}
+/// A remote-row must resolve to `refs/remotes/<name>` even when a local branch
+/// with the literal same short name exists. Git allows local branches like
+/// `origin/foo`; without qualifying the ref, `git rev-parse origin/foo` picks
+/// `refs/heads/origin/foo` and the remote row silently reports stats against
+/// the local branch.
+#[rstest]
+fn test_list_remote_row_not_shadowed_by_same_named_local_branch(
+ #[from(repo_with_remote)] repo: TestRepo,
+) {
+ // Remote `foo` = one commit ahead of main.
+ repo.create_branch("foo");
+ repo.run_git(&["checkout", "foo"]);
+ std::fs::write(repo.root_path().join("remote.txt"), "remote").unwrap();
+ repo.run_git(&["add", "."]);
+ repo.run_git(&["commit", "-m", "Remote foo commit"]);
+ repo.push_branch("foo");
+
+ // Drop local `foo` so only `refs/remotes/origin/foo` remains.
+ repo.run_git(&["checkout", "main"]);
+ repo.run_git(&["branch", "-D", "foo"]);
+
+ // Local branch literally named `origin/foo`, two commits ahead of main on a
+ // different history from the remote.
+ repo.run_git(&["checkout", "-b", "origin/foo"]);
+ std::fs::write(repo.root_path().join("local1.txt"), "local1").unwrap();
+ repo.run_git(&["add", "."]);
+ repo.run_git(&["commit", "-m", "Local origin/foo 1"]);
+ std::fs::write(repo.root_path().join("local2.txt"), "local2").unwrap();
+ repo.run_git(&["add", "."]);
+ repo.run_git(&["commit", "-m", "Local origin/foo 2"]);
+ repo.run_git(&["checkout", "main"]);
+
+ let output = repo
+ .wt_command()
+ .args(["list", "--remotes", "--format=json"])
+ .output()
+ .unwrap();
+ assert!(output.status.success(), "wt list should succeed");
+
+ let json: Vec<serde_json::Value> = serde_json::from_slice(&output.stdout).unwrap();
+ let remote_row = json
+ .iter()
+ .find(|w| w["branch"] == "origin/foo" && w["kind"] == "branch")
+ .expect("remote row origin/foo should be present in --remotes output");
+
+ assert_eq!(
+ remote_row["main"]["ahead"].as_u64(),
+ Some(1),
+ "remote row must report remote-branch ahead count (1), not local (2): {remote_row:#?}"
+ );
+}
+
#[rstest]
fn test_list_json_with_display_fields(mut repo: TestRepo) {
repo.commit("Initial commit on main");