Skip to content

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

fix: support slash-named remotes in branch inventory (#4271)

DDL94338ed2102e
diff --git a/src/commands/config/state.rs b/src/commands/config/state.rs
index 7881ecdd8..604cef89b 100644
--- a/src/commands/config/state.rs
+++ b/src/commands/config/state.rs
@@ -817,7 +817,12 @@ pub fn handle_state_get(
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, Some(sha)) => {
+ let (remote, branch) = repo
+ .split_remote_branch_name(&branch_name)
+ .context("remote branch has no remote prefix")?;
+ BranchRef::remote_branch(remote, branch, sha)
+ }
(None, None) => {
return Err(worktrunk::git::GitError::BranchNotFound {
// Offering `--create` for a name git rejects sends the
diff --git a/src/commands/list/ci_status/mod.rs b/src/commands/list/ci_status/mod.rs
index 49d4c1a12..8fa6c45ff 100644
--- a/src/commands/list/ci_status/mod.rs
+++ b/src/commands/list/ci_status/mod.rs
@@ -41,22 +41,19 @@ pub struct CiBranchName {
impl CiBranchName {
/// Create from a [`BranchRef`], using its short name and remote/local kind.
///
- /// For remote branches (e.g., "origin/feature"), splits at the first `/`
- /// to extract the remote name and bare branch name.
+ /// For remote branches, uses the remote and branch components retained by
+ /// [`BranchRef`] when the repository inventory parsed the ref.
/// For local branches, the name is already bare.
///
/// Returns `None` for detached HEAD (no short name).
pub fn from_branch_ref(branch_ref: &BranchRef) -> Option<Self> {
let short = branch_ref.short_name()?;
- if branch_ref.is_remote() {
- // Remote branch — split "origin/feature" into remote + bare name.
- if let Some((remote, name)) = short.split_once('/') {
- return Some(Self {
- full_name: short.to_string(),
- remote: Some(remote.to_string()),
- name: name.to_string(),
- });
- }
+ if let Some((remote, name)) = branch_ref.remote_parts() {
+ return Some(Self {
+ full_name: short.to_string(),
+ remote: Some(remote.to_string()),
+ name: name.to_string(),
+ });
}
// Local branch — name is already bare
Some(Self {
@@ -875,7 +872,7 @@ mod tests {
#[test]
fn test_ci_branch_name_from_remote_branch_ref() {
- let branch_ref = BranchRef::remote_branch("origin/feature", "abc123");
+ let branch_ref = BranchRef::remote_branch("origin", "feature", "abc123");
let ci = CiBranchName::from_branch_ref(&branch_ref).expect("remote has short_name");
assert_eq!(ci.full_name, "origin/feature");
assert_eq!(ci.name, "feature");
@@ -883,6 +880,16 @@ mod tests {
assert!(ci.is_remote());
}
+ #[test]
+ fn test_ci_branch_name_from_slash_named_remote_branch_ref() {
+ let branch_ref = BranchRef::remote_branch("team/fork", "feature", "abc123");
+ let ci = CiBranchName::from_branch_ref(&branch_ref).expect("remote has short_name");
+ assert_eq!(ci.full_name, "team/fork/feature");
+ assert_eq!(ci.name, "feature");
+ assert_eq!(ci.remote.as_deref(), Some("team/fork"));
+ assert!(ci.is_remote());
+ }
+
#[test]
fn test_ci_branch_name_from_detached_head() {
let detached =
diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rs
index 3de60c112..3fda303a3 100644
--- a/src/commands/list/collect/mod.rs
+++ b/src/commands/list/collect/mod.rs
@@ -431,7 +431,9 @@ use color_print::cformat;
use crossbeam_channel as chan;
use once_cell::sync::OnceCell;
use rayon::prelude::*;
-use worktrunk::git::{ErrorExt, LocalBranch, Repository, WorktreeId, WorktreeInfo, WorktreeRef};
+use worktrunk::git::{
+ ErrorExt, LocalBranch, RemoteBranch, Repository, WorktreeId, WorktreeInfo, WorktreeRef,
+};
use worktrunk::styling::{
INFO_SYMBOL, eprintln, format_with_gutter, hint_message, info_message, terminal_width,
truncate_visible, warning_message,
@@ -1127,7 +1129,7 @@ pub fn collect(
};
// Remote branches that aren't tracked by any local branch. Filtering
// happens over the cached inventories — no extra subprocess.
- let remote_branches: Vec<(String, String)> = if show_remotes {
+ let remote_branches: Vec<RemoteBranch> = if show_remotes {
let tracked: HashSet<&str> = repo
.local_branches()?
.iter()
@@ -1136,7 +1138,7 @@ pub fn collect(
repo.remote_branches()?
.iter()
.filter(|r| !tracked.contains(r.short_name.as_str()))
- .map(|r| (r.short_name.clone(), r.commit_sha.clone()))
+ .cloned()
.collect()
} else {
Vec::new()
@@ -1198,7 +1200,11 @@ pub fn collect(
.iter()
.map(|(_, sha)| sha.as_str()),
)
- .chain(remote_branches.iter().map(|(_, sha)| sha.as_str()))
+ .chain(
+ remote_branches
+ .iter()
+ .map(|branch| branch.commit_sha.as_str()),
+ )
.filter(|sha| *sha != worktrunk::git::NULL_OID)
.collect();
let commit_details_map = repo.commit_details_many(&all_shas).unwrap_or_else(|err| {
@@ -1226,8 +1232,8 @@ pub fn collect(
|(_, sha)| sha.as_str(),
);
let remote_branches =
- sort_by_timestamp_desc_with_cache(remote_branches, &commit_details_map, |(_, sha)| {
- sha.as_str()
+ sort_by_timestamp_desc_with_cache(remote_branches, &commit_details_map, |branch| {
+ branch.commit_sha.as_str()
});
// Branches living in more than one worktree. Every row on such a branch
@@ -1274,11 +1280,13 @@ pub fn collect(
);
let remote_start_idx = all_items.len();
- all_items.extend(
- remote_branches
- .iter()
- .map(|(name, sha)| ListItem::new_remote_branch(sha.clone(), name.clone())),
- );
+ all_items.extend(remote_branches.iter().map(|branch| {
+ ListItem::new_remote_branch(
+ branch.commit_sha.clone(),
+ branch.remote_name.clone(),
+ branch.local_name.clone(),
+ )
+ }));
// Abbreviated SHAs land here, before layout and the skeleton, rather than
// with the rest of the commit bundle below. The Commit cell and a detached
diff --git a/src/commands/list/collect/tasks.rs b/src/commands/list/collect/tasks.rs
index 970452505..51a34c097 100644
--- a/src/commands/list/collect/tasks.rs
+++ b/src/commands/list/collect/tasks.rs
@@ -669,7 +669,7 @@ fn compute_upstream(ctx: &TaskContext) -> anyhow::Result<TaskResult> {
});
};
- let remote = upstream_branch.split_once('/').map(|(r, _)| r.to_string());
+ let remote = repo.branch(branch).upstream_remote()?;
// Resolve upstream ref to a SHA via the snapshot, then compute
// ahead/behind by SHA. Branch SHA is taken from `branch_ref.commit_sha`
// — for the upstream comparison we want the branch's actual tip,
diff --git a/src/commands/list/json_v2.rs b/src/commands/list/json_v2.rs
index bd1f2165e..2af5a6154 100644
--- a/src/commands/list/json_v2.rs
+++ b/src/commands/list/json_v2.rs
@@ -39,7 +39,7 @@ use worktrunk::git::{
use super::ci_status::{CiSource, CiStatus, PrStatus, ReviewState};
use super::custom_columns::ResolvedCustomColumn;
use super::json_output::JsonDiff;
-use super::model::{BranchScope, Collected, ItemKind, ListItem, MainState, WorktreeData};
+use super::model::{Collected, ItemKind, ListItem, MainState, WorktreeData};
/// Tri-state field encoding the absence rule (see module docs).
#[derive(Debug, Clone, PartialEq)]
@@ -595,19 +595,14 @@ impl JsonItemV2 {
ci_provider_override: Option<&str>,
custom_columns: &[ResolvedCustomColumn],
) -> Self {
- let (worktree_data, remote_scope) = match item.kind() {
- ItemKind::Worktree(data) => (Some(data.as_ref()), false),
- ItemKind::Branch(scope) => (None, *scope == BranchScope::Remote),
+ let worktree_data = match item.kind() {
+ ItemKind::Worktree(data) => Some(data.as_ref()),
+ ItemKind::Branch(_) => None,
};
- // Remote rows store the remote-qualified short name ("origin/feature");
- // split it into the remote and the bare branch name.
- let (branch, remote) = match (item.branch(), remote_scope) {
- (Some(name), true) => match name.split_once('/') {
- Some((remote, branch)) => (Some(branch.to_string()), Some(remote.to_string())),
- None => (Some(name.to_string()), None),
- },
- (name, _) => (name.map(str::to_string), None),
+ let (branch, remote) = match item.branch_ref().remote_parts() {
+ Some((remote, branch)) => (Some(branch.to_string()), Some(remote.to_string())),
+ None => (item.branch().map(str::to_string), None),
};
// HEAD — null for unborn branches (no sentinel strings).
@@ -1099,13 +1094,21 @@ mod tests {
#[test]
fn test_remote_row_splits_branch_and_remote() {
- let mut item = item_with("origin/feature");
- item.reclassify_as_branch(BranchScope::Remote, "origin/feature".into());
+ let item = ListItem::new_remote_branch("a".repeat(40), "origin".into(), "feature".into());
let json = to_value(&convert(&item, Collected::default()));
assert_eq!(json["branch"], "feature");
assert_eq!(json["remote"], "origin");
}
+ #[test]
+ fn test_remote_row_preserves_slash_named_remote() {
+ let item =
+ ListItem::new_remote_branch("a".repeat(40), "team/fork".into(), "feature".into());
+ let json = to_value(&convert(&item, Collected::default()));
+ assert_eq!(json["branch"], "feature");
+ assert_eq!(json["remote"], "team/fork");
+ }
+
#[test]
fn test_unborn_branch_head_is_null() {
let item = ListItem::new_branch(worktrunk::git::NULL_OID.to_string(), "new".into());
@@ -1126,8 +1129,7 @@ mod tests {
// default branch — the name check must compare the remote-stripped
// "main", not the raw "origin/main", so it gets no self-referential
// relation object.
- let mut item = item_with("origin/main");
- item.reclassify_as_branch(BranchScope::Remote, "origin/main".into());
+ let item = ListItem::new_remote_branch("a".repeat(40), "origin".into(), "main".into());
let json = to_value(&convert(&item, Collected::default()));
assert_eq!(json["branch"], "main");
assert!(json.get("default_branch").is_none());
@@ -1337,15 +1339,6 @@ mod tests {
}
}
- #[test]
- fn test_remote_row_without_slash_keeps_name() {
- let mut item = item_with("weird");
- item.reclassify_as_branch(BranchScope::Remote, "weird".into());
- let json = to_value(&convert(&item, Collected::default()));
- assert_eq!(json["branch"], "weird");
- assert!(json.get("remote").is_none());
- }
-
#[test]
fn test_loaded_item_serializes_gated_families() {
// One item with every gated family loaded: PR + checks through the
diff --git a/src/commands/list/mod.rs b/src/commands/list/mod.rs
index 18c42097f..09526a8a4 100644
--- a/src/commands/list/mod.rs
+++ b/src/commands/list/mod.rs
@@ -413,7 +413,11 @@ mod tests {
let items = vec![
ListItem::new_branch("aaaaaaa".to_string(), "feature/login".to_string()),
ListItem::new_branch("bbbbbbb".to_string(), "main".to_string()),
- ListItem::new_remote_branch("ccccccc".to_string(), "origin/feature".to_string()),
+ ListItem::new_remote_branch(
+ "ccccccc".to_string(),
+ "origin".to_string(),
+ "feature".to_string(),
+ ),
];
let metrics = SummaryMetrics::from_items(&items);
assert_eq!(
diff --git a/src/commands/list/model/item.rs b/src/commands/list/model/item.rs
index 13b0cc647..019da8137 100644
--- a/src/commands/list/model/item.rs
+++ b/src/commands/list/model/item.rs
@@ -386,20 +386,14 @@ pub struct Collected {
impl ListItem {
/// Create a ListItem for a local branch without a worktree.
pub(crate) fn new_branch(head: String, branch: String) -> Self {
- Self::new_branch_with_scope(head, branch, BranchScope::Local)
+ let branch_ref = BranchRef::local_branch(&branch, &head);
+ Self::new(branch_ref, ItemKind::Branch(BranchScope::Local))
}
/// Create a ListItem for a remote-tracking branch (no local worktree).
- pub(crate) fn new_remote_branch(head: String, branch: String) -> Self {
- Self::new_branch_with_scope(head, branch, BranchScope::Remote)
- }
-
- fn new_branch_with_scope(head: String, branch: String, scope: BranchScope) -> Self {
- let branch_ref = match scope {
- BranchScope::Local => BranchRef::local_branch(&branch, &head),
- BranchScope::Remote => BranchRef::remote_branch(&branch, &head),
- };
- Self::new(branch_ref, ItemKind::Branch(scope))
+ pub(crate) fn new_remote_branch(head: String, remote_name: String, branch: String) -> Self {
+ let branch_ref = BranchRef::remote_branch(&remote_name, &branch, &head);
+ Self::new(branch_ref, ItemKind::Branch(BranchScope::Remote))
}
/// Create a row for a registered worktree.
@@ -466,13 +460,10 @@ impl ListItem {
/// invariant. The picker's removal morph reclassifies a throwaway clone
/// (`build_morph_branch_row`), so the live row's `PickerRowId` is
/// unaffected: a morphed row's previews stay under its worktree key.
- pub(crate) fn reclassify_as_branch(&mut self, scope: BranchScope, branch: String) {
+ pub(crate) fn reclassify_as_branch(&mut self, branch: String) {
let head = self.head().to_string();
- self.branch_ref = match scope {
- BranchScope::Local => BranchRef::local_branch(&branch, &head),
- BranchScope::Remote => BranchRef::remote_branch(&branch, &head),
- };
- self.kind = ItemKind::Branch(scope);
+ self.branch_ref = BranchRef::local_branch(&branch, &head);
+ self.kind = ItemKind::Branch(BranchScope::Local);
}
pub fn branch(&self) -> Option<&str> {
@@ -1185,11 +1176,8 @@ mod tests {
let mut item = ListItem::new_worktree(worktree_ref, WorktreeData::default());
assert_eq!(item.id(), &worktree_id);
- item.reclassify_as_branch(BranchScope::Remote, "feature".into());
- assert_eq!(
- item.id(),
- BranchRef::remote_branch("feature", "abc123").id()
- );
+ item.reclassify_as_branch("feature".into());
+ assert_eq!(item.id(), BranchRef::local_branch("feature", "abc123").id());
}
#[test]
diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rs
index fced20b8f..eb4457ae9 100644
--- a/src/commands/picker/mod.rs
+++ b/src/commands/picker/mod.rs
@@ -131,7 +131,7 @@ use crate::output::print_json;
use super::hook_plan::{ApprovedHookPlan, HookPlanBuilder};
use super::hooks::HookAnnouncer;
use super::list::collect;
-use super::list::model::{BranchScope, ListItem};
+use super::list::model::ListItem;
use super::list::progressive::RenderTarget;
use super::list::render::PLACEHOLDER;
use super::repository_ext::{RemoveTarget, RepositoryCliExt};
@@ -840,7 +840,7 @@ fn build_morph_branch_row(
default_branch: Option<&str>,
) -> (String, LocalContent) {
let mut branch_item = worktree_item.clone();
- branch_item.reclassify_as_branch(BranchScope::Local, branch.to_string());
+ branch_item.reclassify_as_branch(branch.to_string());
branch_item.status_symbols = Default::default();
branch_item.refresh_status_symbols(default_branch);
let line = layout
@@ -2566,7 +2566,7 @@ pub mod tests {
resolve_shortcut_branch, resolve_shortcut_url, summary_command_and_hint,
switch_pipeline_repo,
};
- use crate::commands::list::model::{BranchScope, ListItem, WorktreeData};
+ use crate::commands::list::model::{ListItem, WorktreeData};
use crate::commands::worktree::RemovalPlan;
use insta::assert_yaml_snapshot;
use skim::prelude::SkimItem;
@@ -4346,7 +4346,7 @@ pub mod tests {
local,
LocalContent::from_item(&{
let mut b = ListItem::new_branch("abc123".to_string(), "feature".to_string());
- b.reclassify_as_branch(BranchScope::Local, "feature".into());
+ b.reclassify_as_branch("feature".into());
b
}),
"the morphed row's diff signals are the branch's (working_tree empty)"
diff --git a/src/commands/picker/progressive_handler.rs b/src/commands/picker/progressive_handler.rs
index 4d96c4654..baa9b6355 100644
--- a/src/commands/picker/progressive_handler.rs
+++ b/src/commands/picker/progressive_handler.rs
@@ -58,7 +58,7 @@ use super::preview::PreviewMode;
use super::preview_notify::PrStatusDelta;
use super::preview_orchestrator::{PreviewOrchestrator, SpawnGeneration};
use crate::commands::list::collect::PickerProgressHandler;
-use crate::commands::list::model::{BranchScope, ItemKind, ListItem};
+use crate::commands::list::model::ListItem;
/// Handler owned by the background collect thread. Implements the
/// `PickerProgressHandler` trait that `collect` drives.
@@ -249,9 +249,9 @@ impl PickerHandler {
/// Branch names the skeleton shows, for the `--prs` thread's dedup: a PR whose
/// head branch is in this set is already on screen, so its row is dropped. A
-/// remote row ("origin/foo") also contributes its bare "foo" — remote names
-/// carry no '/', so the first segment is the remote — so a PR for "foo" dedups
-/// against a shown "origin/foo". Detached rows (no branch) contribute nothing.
+/// remote row ("origin/foo") also contributes its bare "foo", so a PR for
+/// "foo" dedups against a shown "origin/foo". Detached rows (no branch)
+/// contribute nothing.
fn collect_shown_branches(items: &[ListItem]) -> HashSet<String> {
let mut shown = HashSet::new();
for item in items {
@@ -259,9 +259,7 @@ fn collect_shown_branches(items: &[ListItem]) -> HashSet<String> {
continue;
};
shown.insert(name.to_string());
- if matches!(item.kind(), ItemKind::Branch(BranchScope::Remote))
- && let Some((_, bare)) = name.split_once('/')
- {
+ if let Some((_, bare)) = item.branch_ref().remote_parts() {
shown.insert(bare.to_string());
}
}
@@ -1290,7 +1288,7 @@ mod tests {
let (handler, _test, rx) = make_handler();
let items = vec![
ListItem::new_branch("abc".into(), "localbr".into()),
- ListItem::new_remote_branch("abc".into(), "origin/remotebr".into()),
+ ListItem::new_remote_branch("abc".into(), "origin".into(), "remotebr".into()),
];
handler.on_skeleton(
items,
@@ -1408,7 +1406,8 @@ mod tests {
fn collect_shown_branches_adds_remote_bare_names() {
let items = vec![
ListItem::new_branch("a".into(), "local-feat".into()),
- ListItem::new_remote_branch("b".into(), "origin/remote-feat".into()),
+ ListItem::new_remote_branch("b".into(), "origin".into(), "remote-feat".into()),
+ ListItem::new_remote_branch("c".into(), "team/fork".into(), "slash-feat".into()),
];
let shown = collect_shown_branches(&items);
assert!(shown.contains("local-feat"), "local branch name");
@@ -1417,6 +1416,11 @@ mod tests {
shown.contains("remote-feat"),
"bare name so a PR head dedups against the remote row"
);
+ assert!(shown.contains("team/fork/slash-feat"), "slash remote ref");
+ assert!(
+ shown.contains("slash-feat"),
+ "bare name from a slash-named remote"
+ );
}
/// `on_skeleton` strips the shared main-worktree parent from each row's
diff --git a/src/git/mod.rs b/src/git/mod.rs
index f3afc7aa0..9e731812f 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -424,6 +424,9 @@ pub struct LocalBranch {
/// `None` when no upstream is set, or when the configured upstream is gone
/// (git reports `[gone]` via `%(upstream:track)`).
pub upstream_short: Option<String>,
+ /// Configured upstream remote, from `%(upstream:remotename)`.
+ /// `None` for local tracking (`.`) or when no remote is configured.
+ pub upstream_remote: Option<String>,
/// Where this branch pushes, from `%(push:remotename)`: a remote name, or a
/// URL when `branch.<name>.pushRemote` is one (`gh pr checkout` sets that
/// for a fork's PR). `None` when no push remote is configured.
@@ -600,7 +603,7 @@ impl HookType {
/// - From a worktree: `worktree_info.worktree_ref()` and then
/// [`WorktreeRef::into_branch_ref()`]
/// - For a local branch: `BranchRef::local_branch("feature", "abc123")`
-/// - For a remote branch: `BranchRef::remote_branch("origin/feature", "abc123")`
+/// - For a remote branch: `BranchRef::remote_branch("origin", "feature", "abc123")`
///
/// # Working Tree Access
///
@@ -625,6 +628,8 @@ pub struct BranchRef {
/// Path to worktree, if this branch has one.
/// None for branch-only items (remote branches, local branches without worktrees).
worktree_path: Option<PathBuf>,
+ /// Byte offset of the remote/branch separator in the short name.
+ remote_name_len: Option<usize>,
}
/// Canonical snapshot of a registered worktree.
@@ -729,21 +734,25 @@ impl BranchRef {
full_ref: Some(full_ref),
commit_sha: commit_sha.to_string(),
worktree_path: None,
+ remote_name_len: None,
}
}
/// Create a BranchRef for a remote-tracking branch.
///
- /// `branch` is the short remote-qualified name (e.g., `"origin/feature"`),
- /// as produced by `%(refname:lstrip=2)` in `list_remote_branches`. It is
- /// stored as `refs/remotes/<branch>`.
- pub fn remote_branch(branch: &str, commit_sha: &str) -> Self {
- let full_ref = remote_ref(branch);
+ /// `remote_name` and `branch` come from the remote-branch inventory, which
+ /// resolves their boundary against configured remote names. Keeping them
+ /// separate here avoids reparsing ambiguous names such as
+ /// `"team/fork/feature"`.
+ pub fn remote_branch(remote_name: &str, branch: &str, commit_sha: &str) -> Self {
+ let short_name = format!("{remote_name}/{branch}");
+ let full_ref = remote_ref(&short_name);
Self {
- id: GitItemId::remote_branch(branch),
+ id: GitItemId::remote_branch(&short_name),
full_ref: Some(full_ref),
commit_sha: commit_sha.to_string(),
worktree_path: None,
+ remote_name_len: Some(remote_name.len()),
}
}
@@ -800,9 +809,14 @@ impl BranchRef {
/// True if this is a remote-tracking ref (under `refs/remotes/`).
pub fn is_remote(&self) -> bool {
- self.full_ref
- .as_deref()
- .is_some_and(|r| r.starts_with("refs/remotes/"))
+ self.remote_name_len.is_some()
+ }
+
+ /// Remote and branch components of a remote-tracking ref.
+ pub fn remote_parts(&self) -> Option<(&str, &str)> {
+ let short = self.short_name()?;
+ let boundary = self.remote_name_len?;
+ Some((&short[..boundary], &short[boundary + 1..]))
}
}
@@ -816,6 +830,7 @@ impl WorktreeRef {
full_ref: branch.map(local_ref),
commit_sha: commit_sha.to_string(),
worktree_path: Some(path),
+ remote_name_len: None,
})
}
@@ -1188,10 +1203,11 @@ mod tests {
#[test]
fn test_branch_ref_remote_branch() {
- let branch_ref = BranchRef::remote_branch("origin/feature", "abc123");
+ let branch_ref = BranchRef::remote_branch("origin", "feature", "abc123");
assert_eq!(branch_ref.full_ref(), Some("refs/remotes/origin/feature"));
assert_eq!(branch_ref.short_name(), Some("origin/feature"));
+ assert_eq!(branch_ref.remote_parts(), Some(("origin", "feature")));
assert_eq!(branch_ref.commit_sha, "abc123");
assert_eq!(branch_ref.worktree_path, None);
assert!(branch_ref.worktree_path().is_none());
@@ -1207,7 +1223,7 @@ mod tests {
// `git rev-parse` picking the wrong ref lives at
// `test_list_remote_row_not_shadowed_by_same_named_local_branch` in
// `tests/integration_tests/list.rs`.
- let remote = BranchRef::remote_branch("origin/foo", "abc");
+ let remote = BranchRef::remote_branch("origin", "foo", "abc");
let local = BranchRef::local_branch("origin/foo", "def");
assert_eq!(remote.full_ref(), Some("refs/remotes/origin/foo"));
@@ -1244,7 +1260,7 @@ mod tests {
// A short name is presentation; the full ref is identity.
assert_ne!(
BranchRef::local_branch("origin/foo", "abc").id(),
- BranchRef::remote_branch("origin/foo", "abc").id()
+ BranchRef::remote_branch("origin", "foo", "abc").id()
);
}
diff --git a/src/git/repository/branch.rs b/src/git/repository/branch.rs
index 975054f5c..2b1da6a6f 100644
--- a/src/git/repository/branch.rs
+++ b/src/git/repository/branch.rs
@@ -140,6 +140,15 @@ impl<'a> Branch<'a> {
.and_then(|b| b.upstream_short.clone()))
}
+ /// Configured upstream remote, as reported by git's local-branch inventory.
+ /// Local tracking (`.`) has no remote.
+ pub fn upstream_remote(&self) -> anyhow::Result<Option<String>> {
+ Ok(self
+ .repo
+ .local_branch(&self.name)?
+ .and_then(|b| b.upstream_remote.clone()))
+ }
+
/// Where this branch pushes: a remote name, or a URL when
/// `branch.<name>.pushRemote` is one (`gh pr checkout` sets that for a
/// fork's PR). Resolves `pushRemote` → `remote.pushDefault` → the tracking
diff --git a/src/git/repository/branches.rs b/src/git/repository/branches.rs
index f46fb7f3e..0ab304224 100644
--- a/src/git/repository/branches.rs
+++ b/src/git/repository/branches.rs
@@ -75,8 +75,8 @@ const FIELD_SEP: char = '\0';
/// Fields, in order: short name, object SHA, committer Unix timestamp,
/// upstream short name (empty if none), upstream track (`[gone]` if the
/// configured upstream no longer exists on the remote), push remote (a remote
-/// name or URL; empty if none).
-const LOCAL_BRANCH_FORMAT: &str = "--format=%(refname:lstrip=2)%00%(objectname)%00%(committerdate:unix)%00%(upstream:short)%00%(upstream:track)%00%(push:remotename)";
+/// name or URL; empty if none), upstream remote (empty if none).
+const LOCAL_BRANCH_FORMAT: &str = "--format=%(refname:lstrip=2)%00%(objectname)%00%(committerdate:unix)%00%(upstream:short)%00%(upstream:track)%00%(push:remotename)%00%(upstream:remotename)";
/// Format string for the remote-branch scan.
///
@@ -207,12 +207,13 @@ impl Repository {
/// One `for-each-ref refs/remotes/` scan, parsed (excluding
/// `<remote>/HEAD` symrefs) and sorted by committer timestamp. The
/// shared scan primitive behind both [`remote_branches`](Self::remote_branches)
- /// and the snapshot path. No cache side-effect.
+ /// and the snapshot path. Does not populate the remote-branch cache.
pub(super) fn scan_remote_branch_records(&self) -> anyhow::Result<Vec<RemoteBranch>> {
let output = self.run_command(&["for-each-ref", REMOTE_BRANCH_FORMAT, "refs/remotes/"])?;
+ let remotes = self.all_remote_urls();
let mut branches: Vec<RemoteBranch> = output
.lines()
- .filter_map(parse_remote_branch_line)
+ .filter_map(|line| parse_remote_branch_line(line, &remotes))
.collect();
branches.sort_by_key(|b| std::cmp::Reverse(b.committer_ts));
Ok(branches)
@@ -393,27 +394,29 @@ fn parse_local_branch_line(line: &str) -> Option<LocalBranch> {
let push_remote = Some(parts.next()?)
.filter(|s| !s.is_empty())
.map(str::to_string);
+ let upstream_remote = Some(parts.next()?)
+ .filter(|s| !s.is_empty() && *s != ".")
+ .map(str::to_string);
Some(LocalBranch {
name,
commit_sha,
committer_ts,
upstream_short,
+ upstream_remote,
push_remote,
})
}
/// Parse one record from the remote-branch scan.
///
-/// Skips `<remote>/HEAD` symrefs — they duplicate another ref and would
+/// Skips `<remote>/HEAD` symrefs, which duplicate another ref and would
/// confuse callers that key by local name.
-fn parse_remote_branch_line(line: &str) -> Option<RemoteBranch> {
+fn parse_remote_branch_line(line: &str, remotes: &[(String, String)]) -> Option<RemoteBranch> {
let mut parts = line.split(FIELD_SEP);
let short_name = parts.next()?;
let commit_sha = parts.next()?.to_string();
let committer_ts: i64 = parts.next()?.parse().ok()?;
-
- // `<remote>/HEAD` is a symref to the remote's default branch; skip it.
- let (remote_name, local_name) = short_name.split_once('/')?;
+ let (remote_name, local_name) = super::remotes::split_remote_branch_name(short_name, remotes)?;
if local_name == "HEAD" {
return None;
}
diff --git a/src/git/repository/remotes.rs b/src/git/repository/remotes.rs
index 6ea8c283d..e66461efd 100644
--- a/src/git/repository/remotes.rs
+++ b/src/git/repository/remotes.rs
@@ -452,6 +452,11 @@ impl Repository {
.and_then(|config| config.list.url)
}
+ /// Split a remote-tracking branch at the longest configured remote prefix.
+ pub fn split_remote_branch_name<'a>(&self, ref_name: &'a str) -> Option<(&'a str, &'a str)> {
+ split_remote_branch_name(ref_name, &self.all_remote_urls())
+ }
+
/// Strip the remote prefix from a remote-tracking branch name.
///
/// Given a name like `origin/username/feature-1`, returns `Some("username/feature-1")`
@@ -504,6 +509,24 @@ fn refspec_side_matches(pattern: &str, refname: &str) -> bool {
}
}
+/// Remote refs use the longest matching configured prefix; orphaned refs retain
+/// the conventional first-segment split.
+pub(super) fn split_remote_branch_name<'a>(
+ name: &'a str,
+ remotes: &[(String, String)],
+) -> Option<(&'a str, &'a str)> {
+ let boundary = remotes
+ .iter()
+ .filter(|(remote, _)| {
+ name.strip_prefix(remote)
+ .is_some_and(|rest| rest.starts_with('/'))
+ })
+ .map(|(remote, _)| remote.len())
+ .max()
+ .or_else(|| name.find('/'))?;
+ Some((&name[..boundary], &name[boundary + 1..]))
+}
+
#[cfg(test)]
mod tests {
use crate::testing::TestRepo;
diff --git a/tests/integration_tests/config_state.rs b/tests/integration_tests/config_state.rs
index 8fc569736..9c71f1283 100644
--- a/tests/integration_tests/config_state.rs
+++ b/tests/integration_tests/config_state.rs
@@ -774,7 +774,12 @@ 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) {
+#[case("team/fork/foo")]
+#[case("team/fork/HEAD")]
+fn test_state_get_ci_status_remote_only_branch(
+ #[from(repo_with_remote)] repo: TestRepo,
+ #[case] branch: &str,
+) {
repo.create_branch("foo");
repo.run_git(&["checkout", "foo"]);
std::fs::write(repo.root_path().join("f.txt"), "f").unwrap();
@@ -784,7 +789,14 @@ fn test_state_get_ci_status_remote_only_branch(#[from(repo_with_remote)] repo: T
repo.run_git(&["checkout", "main"]);
repo.run_git(&["branch", "-D", "foo"]);
- let output = wt_state_cmd(&repo, "ci-status", "get", &["--branch", "origin/foo"])
+ repo.run_git(&["remote", "rename", "origin", "team/fork"]);
+ repo.run_git(&[
+ "symbolic-ref",
+ "refs/remotes/team/fork/HEAD",
+ "refs/remotes/team/fork/foo",
+ ]);
+
+ let output = wt_state_cmd(&repo, "ci-status", "get", &["--branch", branch])
.output()
.unwrap();
assert!(
diff --git a/tests/integration_tests/list.rs b/tests/integration_tests/list.rs
index 8ce9d2707..6456bf00d 100644
--- a/tests/integration_tests/list.rs
+++ b/tests/integration_tests/list.rs
@@ -781,6 +781,44 @@ fn test_list_with_remotes_and_full(#[from(repo_with_remote)] repo: TestRepo) {
});
}
+#[rstest]
+fn test_list_json_preserves_slash_named_remote(#[from(repo_with_remote)] repo: TestRepo) {
+ repo.create_branch("remote-only");
+ repo.push_branch("remote-only");
+ repo.run_git(&["branch", "-D", "remote-only"]);
+ repo.run_git(&["remote", "rename", "origin", "team/fork"]);
+
+ // Both prefixes are configured; use the complete remote name.
+ repo.run_git(&["config", "remote.team.url", "https://example.com/team.git"]);
+ repo.run_git(&[
+ "symbolic-ref",
+ "refs/remotes/team/fork/HEAD",
+ "refs/remotes/team/fork/main",
+ ]);
+
+ let output = repo
+ .wt_command()
+ .args(["list", "--remotes", "--format=json"])
+ .output()
+ .unwrap();
+ assert!(output.status.success(), "wt list should succeed");
+
+ let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
+ let items = json["items"].as_array().expect("schema 2 items");
+ let remote = items
+ .iter()
+ .find(|item| item.get("remote").is_some())
+ .expect("remote-only row");
+ assert_eq!(remote["branch"], "remote-only");
+ assert_eq!(remote["remote"], "team/fork");
+
+ let main = items
+ .iter()
+ .find(|item| item["branch"] == "main")
+ .expect("main row");
+ assert_eq!(main["upstream"]["remote"], "team/fork");
+}
+
#[rstest]
fn test_list_with_orphaned_remote_ref(#[from(repo_with_remote)] repo: TestRepo) {
// Create a remote-tracking ref for a non-existent remote.
@@ -920,6 +958,47 @@ fn test_list_ordering_rules(mut repo: TestRepo) {
assert_cmd_snapshot!(list_snapshots::command(&repo, &current_path));
}
+#[rstest]
+#[case("origin")]
+#[case(".")]
+fn test_list_upstream_remote_comes_from_tracking_config(
+ #[from(repo_with_remote)] repo: TestRepo,
+ #[case] remote: &str,
+) {
+ // The same short ref can mean remote origin + branch fork/main or
+ // remote origin/fork + branch main. Git's tracking config decides.
+ repo.run_git(&["config", "remote.origin/fork.url", "unused"]);
+ repo.run_git(&["config", "branch.main.remote", remote]);
+ repo.run_git(&["config", "branch.main.merge", "refs/heads/fork/main"]);
+ repo.run_git(&["update-ref", "refs/remotes/origin/fork/main", "HEAD"]);
+ repo.create_branch("fork/main");
+
+ let output = repo
+ .wt_command()
+ .args(["list", "--format=json"])
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
+ let main = json["items"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .find(|item| item["branch"] == "main")
+ .unwrap();
+ if remote == "." {
+ // Local tracking has no remote upstream object.
+ assert!(main.get("upstream").is_none());
+ } else {
+ assert_eq!(main["upstream"]["remote"], "origin");
+ assert_eq!(main["upstream"]["branch"], "fork/main");
+ }
+}
+
#[rstest]
fn test_list_with_upstream_tracking(mut repo: TestRepo) {
repo.commit("Initial commit on main");
diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rs
index 9f8596f1b..c84a23b08 100644
--- a/tests/integration_tests/switch.rs
+++ b/tests/integration_tests/switch.rs
@@ -305,6 +305,43 @@ fn test_switch_dwim_from_remote(#[from(repo_with_remote)] repo: TestRepo) {
snapshot_switch("switch_dwim_from_remote", &repo, &["dwim-feature"]);
}
+#[rstest]
+fn test_switch_dwim_from_remote_with_slash(#[from(repo_with_remote)] repo: TestRepo) {
+ repo.run_git(&["branch", "slash-remote-feature"]);
+ repo.run_git(&["push", "origin", "slash-remote-feature"]);
+ repo.run_git(&["branch", "-D", "slash-remote-feature"]);
+ repo.run_git(&["remote", "rename", "origin", "team/fork"]);
+
+ assert_eq!(repo.git_output(&["remote"]), "team/fork");
+ assert_eq!(
+ repo.git_output(&[
+ "for-each-ref",
+ "--format=%(refname:short)",
+ "refs/remotes/team/fork/slash-remote-feature",
+ ]),
+ "team/fork/slash-remote-feature",
+ );
+
+ let output = repo
+ .wt_command()
+ .args(["switch", "slash-remote-feature"])
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "switch should find the branch on team/fork; stderr: {}",
+ String::from_utf8_lossy(&output.stderr),
+ );
+ assert_eq!(
+ repo.git_output(&[
+ "rev-parse",
+ "--abbrev-ref",
+ "slash-remote-feature@{upstream}",
+ ]),
+ "team/fork/slash-remote-feature",
+ );
+}
+
/// When the branch argument includes the remote prefix (e.g., "origin/feature"),
/// strip the prefix and switch to the local branch via DWIM.
/// This happens when the interactive picker returns a remote branch name.