Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat: search all remotes for branch existence, matching git's behavior (#744)
Maximilian Roos3193efab4293
diff --git a/src/completion.rs b/src/completion.rsindex f67999dbf..4b22907e9 100644--- a/src/completion.rs+++ b/src/completion.rs@@ -344,7 +344,7 @@ fn complete_branches(let help = match branch.category {BranchCategory::Worktree => format!("+ {}", time_str),BranchCategory::Local => format!("/ {}", time_str),- BranchCategory::Remote(remote) => format!("⇣ {} {}", time_str, remote),+ BranchCategory::Remote(remotes) => format!("⇣ {} {}", time_str, remotes.join(", ")),};CompletionCandidate::new(branch.name).help(Some(help.into()))})diff --git a/src/git/mod.rs b/src/git/mod.rsindex effad94e2..225fb0813 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -232,8 +232,8 @@ pub enum BranchCategory {Worktree,/// Local branch without worktreeLocal,- /// Remote-only branch (includes remote name)- Remote(String),+ /// Remote-only branch (includes remote names — multiple if same branch on multiple remotes)+ Remote(Vec<String>),}/// Branch information for shell completionsdiff --git a/src/git/repository/branch.rs b/src/git/repository/branch.rsindex 50b629477..91edfc026 100644--- a/src/git/repository/branch.rs+++ b/src/git/repository/branch.rs@@ -48,24 +48,16 @@ impl<'a> Branch<'a> {}/// Check if this branch exists (local or remote).+ ///+ /// Checks all remotes, matching git's default behavior for `git checkout`.pub fn exists(&self) -> anyhow::Result<bool> {// Try local branch firstif self.exists_locally()? {return Ok(true);}- // Try remote branch (if remotes exist)- let Ok(remote) = self.repo.primary_remote() else {- return Ok(false);- };- Ok(self- .repo- .run_command(&[- "rev-parse",- "--verify",- &format!("refs/remotes/{}/{}", remote, self.name),- ])- .is_ok())+ // Check if any remote has this branch+ Ok(!self.remotes()?.is_empty())}/// Find which remotes have this branch.diff --git a/src/git/repository/branches.rs b/src/git/repository/branches.rsindex be6628374..fac758e7e 100644--- a/src/git/repository/branches.rs+++ b/src/git/repository/branches.rs@@ -150,6 +150,10 @@ impl Repository {/// Returns branches in completion order: worktrees first, then local branches,/// then remote-only branches. Each category is sorted by recency.///+ /// Searches all remotes (matching git's checkout behavior). If the same branch+ /// exists on multiple remotes, all remote names are included in the result so+ /// completions can show that the branch is ambiguous.+ ////// For remote branches, returns the local name (e.g., "fix" not "origin/fix")/// since `git worktree add path fix` auto-creates a tracking branch.pub fn branches_for_completion(&self) -> anyhow::Result<Vec<CompletionBranch>> {@@ -171,59 +175,70 @@ impl Repository {let local_branches: Vec<(String, i64)> = local_output.lines().filter_map(|line| {- let parts: Vec<&str> = line.split('\t').collect();- if parts.len() == 2 {- let timestamp = parts[1].parse().unwrap_or(0);- Some((parts[0].to_string(), timestamp))- } else {- None- }+ let (name, timestamp_str) = line.split_once('\t')?;+ let timestamp = timestamp_str.parse().unwrap_or(0);+ Some((name.to_string(), timestamp))}).collect();let local_branch_names: HashSet<String> =local_branches.iter().map(|(n, _)| n.clone()).collect();- // Get remote branches with timestamps (if remotes exist)- let remote_branches: Vec<(String, String, i64)> = if let Ok(remote) = self.primary_remote()- {- let remote_ref_path = format!("refs/remotes/{}/", remote);- let remote_prefix = format!("{}/", remote);-- let remote_output = self.run_command(&[- "for-each-ref",- "--sort=-committerdate",- "--format=%(refname:lstrip=2)\t%(committerdate:unix)",- &remote_ref_path,- ])?;-- let remote_head = format!("{}/HEAD", remote);- remote_output- .lines()- .filter_map(|line| {- let parts: Vec<&str> = line.split('\t').collect();- if parts.len() == 2 {- let full_name = parts[0];- // Skip <remote>/HEAD- if full_name == remote_head {- return None;- }- // Strip remote prefix to get local name- let local_name = full_name.strip_prefix(&remote_prefix)?;- // Skip if local branch exists (user should use local)- if local_branch_names.contains(local_name) {- return None;- }- let timestamp = parts[1].parse().unwrap_or(0);- Some((local_name.to_string(), remote.to_string(), timestamp))- } else {- None- }+ // Get remote branches with timestamps from all remotes+ // Matches git's behavior: searches all remotes for branch names+ let remote_output = self.run_command(&[+ "for-each-ref",+ "--sort=-committerdate",+ "--format=%(refname:lstrip=2)\t%(committerdate:unix)",+ "refs/remotes/",+ ])?;++ // Group by branch name, collecting all remotes that have each branch.+ // Uses HashMap for grouping, then sorts by timestamp to preserve recency order.+ use std::collections::HashMap;+ let mut branch_remotes: HashMap<String, (Vec<String>, i64)> = HashMap::new();++ for line in remote_output.lines() {+ // Format: "<remote>/<branch>\t<timestamp>"+ let Some((full_name, timestamp_str)) = line.split_once('\t') else {+ continue;+ };++ // Parse <remote>/<branch> - find first slash to split+ let Some((remote_name, local_name)) = full_name.split_once('/') else {+ continue;+ };++ // Skip <remote>/HEAD+ if local_name == "HEAD" {+ continue;+ }+ // Skip if local branch exists (user should use local)+ if local_branch_names.contains(local_name) {+ continue;+ }++ let timestamp = timestamp_str.parse().unwrap_or(0);++ // Add remote to this branch's list, keeping the most recent timestamp+ branch_remotes+ .entry(local_name.to_string())+ .and_modify(|(remotes, existing_ts)| {+ remotes.push(remote_name.to_string());+ *existing_ts = (*existing_ts).max(timestamp);})- .collect()- } else {- Vec::new()- };+ .or_insert_with(|| (vec![remote_name.to_string()], timestamp));+ }++ // Convert to vec and sort by timestamp (descending = most recent first)+ let mut remote_branches: Vec<(String, Vec<String>, i64)> = branch_remotes+ .into_iter()+ .map(|(name, (mut remotes, timestamp))| {+ remotes.sort(); // Deterministic remote ordering within each branch+ (name, remotes, timestamp)+ })+ .collect();+ remote_branches.sort_by(|a, b| b.2.cmp(&a.2));// Build result: worktrees first, then local, then remotelet mut result = Vec::new();@@ -251,11 +266,11 @@ impl Repository {}// Remote-only branches- for (local_name, remote_name, timestamp) in remote_branches {+ for (local_name, remotes, timestamp) in remote_branches {result.push(CompletionBranch {name: local_name,timestamp,- category: BranchCategory::Remote(remote_name),+ category: BranchCategory::Remote(remotes),});}diff --git a/tests/integration_tests/completion.rs b/tests/integration_tests/completion.rsindex 339c2ef16..2a8c7b782 100644--- a/tests/integration_tests/completion.rs+++ b/tests/integration_tests/completion.rs@@ -1277,3 +1277,42 @@ fn test_static_completions_for_all_shells() {}}}++#[rstest]+fn test_complete_switch_shows_all_remotes_for_ambiguous_branch(mut repo: TestRepo) {+ repo.commit("initial");++ // Set up two remotes: origin and upstream+ repo.setup_remote("main");+ repo.setup_custom_remote("upstream", "main");++ // Create a branch locally and push to both remotes+ repo.run_git(&["checkout", "-b", "shared-feature"]);+ repo.commit_with_message("Add shared feature");+ repo.run_git(&["push", "origin", "shared-feature"]);+ repo.run_git(&["push", "upstream", "shared-feature"]);++ // Delete local branch so it only exists on remotes+ repo.run_git(&["checkout", "main"]);+ repo.run_git(&["branch", "-D", "shared-feature"]);++ // Test completion with fish shell to see help text (bash doesn't show descriptions)+ let output = repo+ .completion_cmd_for_shell(&["wt", "switch", ""], "fish")+ .output()+ .unwrap();+ assert!(output.status.success());+ let stdout = String::from_utf8_lossy(&output.stdout);++ // The branch should appear with both remotes listed+ // Format: "shared-feature\t⇣ <time> origin, upstream" (sorted alphabetically)+ assert!(+ stdout.contains("shared-feature"),+ "Should show shared-feature branch: {stdout}"+ );+ // Check that both remotes are shown (order is alphabetical: origin, upstream)+ assert!(+ stdout.contains("origin") && stdout.contains("upstream"),+ "Should show both remotes for ambiguous branch: {stdout}"+ );+}