Skip to content

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

fix(config): resolve ci-status branch via single ref query so is_remote matches HEAD SHA (#2388)

Maximilian Roosb729a39db69b
diff --git a/src/commands/config/state.rs b/src/commands/config/state.rs
index df0da110a..aa8e026ad 100644
--- a/src/commands/config/state.rs
+++ b/src/commands/config/state.rs
@@ -43,7 +43,7 @@ use anyhow::Context;
use color_print::cformat;
use path_slash::PathExt as _;
use worktrunk::config::config_path;
-use worktrunk::git::Repository;
+use worktrunk::git::{BranchRef, Repository};
use worktrunk::path::format_path_for_display;
use worktrunk::styling::{
eprintln, format_heading, format_with_gutter, info_message, println, success_message,
@@ -660,34 +660,50 @@ pub fn handle_state_get(
None => repo.require_current_branch("get ci-status for current branch")?,
};
- // Determine if this is a remote ref by checking git refs directly.
- // This is authoritative - we check actual refs, not guessing from name.
- let is_remote = repo
+ // Ask git for both qualified forms in one call so the remote/local
+ // determination and the HEAD SHA come from the same ref. A local
+ // branch literally named `origin/foo` can shadow a remote-tracking
+ // ref of the same name — preferring refs/heads/ matches git's
+ // default disambiguation (see `BranchRef::full_ref`).
+ let local_ref = format!("refs/heads/{branch_name}");
+ let remote_ref = format!("refs/remotes/{branch_name}");
+ let output = repo
.run_command(&[
- "show-ref",
- "--verify",
- "--quiet",
- &format!("refs/remotes/{}", branch_name),
+ "for-each-ref",
+ "--format=%(refname)%00%(objectname)",
+ &local_ref,
+ &remote_ref,
])
- .is_ok();
-
- // Get the HEAD commit for this branch
- let head = repo
- .run_command(&["rev-parse", &branch_name])
- .map(|s| s.trim().to_string())
- .unwrap_or_default();
-
- if head.is_empty() {
- return Err(worktrunk::git::GitError::BranchNotFound {
- branch: branch_name,
- show_create_hint: true,
- last_fetch_ago: None,
+ .context("list refs for ci-status")?;
+
+ let mut local_sha: Option<&str> = None;
+ let mut remote_sha: Option<&str> = None;
+ for (ref_name, sha) in output.lines().filter_map(|l| l.split_once('\0')) {
+ if ref_name == local_ref {
+ local_sha = Some(sha);
+ } else if ref_name == remote_ref {
+ remote_sha = Some(sha);
}
- .into());
}
- let ci_branch = CiBranchName::from_branch_ref(&branch_name, is_remote);
- let pr_status = PrStatus::detect(&repo, &ci_branch, &head);
+ let branch_ref = match (local_sha, remote_sha) {
+ (Some(sha), _) => BranchRef::local_branch(&branch_name, sha),
+ (None, Some(sha)) => BranchRef::remote_branch(&branch_name, sha),
+ (None, None) => {
+ return Err(worktrunk::git::GitError::BranchNotFound {
+ branch: branch_name,
+ show_create_hint: true,
+ last_fetch_ago: None,
+ }
+ .into());
+ }
+ };
+
+ let short_name = branch_ref
+ .short_name()
+ .expect("local/remote BranchRef always has short_name");
+ let ci_branch = CiBranchName::from_branch_ref(short_name, branch_ref.is_remote());
+ let pr_status = PrStatus::detect(&repo, &ci_branch, &branch_ref.commit_sha);
if format == SwitchFormat::Json {
let output = pr_status
diff --git a/tests/integration_tests/config_state.rs b/tests/integration_tests/config_state.rs
index 3a9429ea1..37fcd9af2 100644
--- a/tests/integration_tests/config_state.rs
+++ b/tests/integration_tests/config_state.rs
@@ -1,4 +1,4 @@
-use crate::common::{TEST_EPOCH, TestRepo, repo, wt_command};
+use crate::common::{TEST_EPOCH, TestRepo, repo, repo_with_remote, wt_command};
use insta::assert_snapshot;
use rstest::rstest;
use std::path::{Path, PathBuf};
@@ -343,6 +343,95 @@ fn test_state_get_ci_status_nonexistent_branch(repo: TestRepo) {
");
}
+/// Resolve a branch that exists only as a remote-tracking ref (no local
+/// counterpart). Exercises the `remote_branch` arm of the BranchRef match.
+#[rstest]
+fn test_state_get_ci_status_remote_only_branch(#[from(repo_with_remote)] repo: TestRepo) {
+ repo.create_branch("foo");
+ repo.run_git(&["checkout", "foo"]);
+ std::fs::write(repo.root_path().join("f.txt"), "f").unwrap();
+ repo.run_git(&["add", "."]);
+ repo.run_git(&["commit", "-m", "foo commit"]);
+ repo.push_branch("foo");
+ repo.run_git(&["checkout", "main"]);
+ repo.run_git(&["branch", "-D", "foo"]);
+
+ let output = wt_state_cmd(&repo, "ci-status", "get", &["--branch", "origin/foo"])
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "command should succeed: stderr={}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "no-ci");
+}
+
+/// A fresh cached CI status returns from `get` without re-fetching. Exercises
+/// the cache-hit path where `PrStatus::detect` returns `Some` and the match
+/// arm unwraps `ci_status`.
+#[rstest]
+fn test_state_get_ci_status_returns_cached_status(repo: TestRepo) {
+ let head = repo.head_sha();
+ write_ci_cache(
+ &repo,
+ "main",
+ &format!(
+ r#"{{"status":{{"ci_status":"passed","source":"pr","is_stale":false}},"checked_at":{TEST_EPOCH},"head":"{head}","branch":"main"}}"#
+ ),
+ );
+
+ let output = wt_state_cmd(&repo, "ci-status", "get", &["--branch", "main"])
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "command should succeed: stderr={}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "passed");
+}
+
+/// `wt config state ci-status --branch origin/foo` must resolve cleanly when a
+/// local branch literally named `origin/foo` shadows a remote-tracking ref of
+/// the same name. Smoke test: exercises the shadowing code path. The
+/// visible-to-user consequences of the underlying bug (is_remote flag out of
+/// sync with the HEAD SHA, affecting how `gh`/`glab` get invoked) aren't
+/// observable without mocking those tools, but this guards against
+/// regressions that would make the command error on ambiguity (e.g., naive
+/// use of `rev-parse --symbolic-full-name`, which fails on shadowed refs).
+#[rstest]
+fn test_state_get_ci_status_shadow_origin_prefixed(#[from(repo_with_remote)] repo: TestRepo) {
+ // Remote `foo` pushed to origin.
+ 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` with different history.
+ repo.run_git(&["checkout", "-b", "origin/foo"]);
+ std::fs::write(repo.root_path().join("local.txt"), "local").unwrap();
+ repo.run_git(&["add", "."]);
+ repo.run_git(&["commit", "-m", "Local origin/foo"]);
+ repo.run_git(&["checkout", "main"]);
+
+ let output = wt_state_cmd(&repo, "ci-status", "get", &["--branch", "origin/foo"])
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "command should succeed: stderr={}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "no-ci");
+}
+
#[rstest]
fn test_state_clear_ci_status_all_empty(repo: TestRepo) {
let output = wt_state_cmd(&repo, "ci-status", "clear", &["--all"])