Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Feat: Support custom remote names for git operations
Maximilian Roos762a8027c306
diff --git a/src/git.rs b/src/git.rsindex 39dde7b2a..eeb215dfe 100644--- a/src/git.rs+++ b/src/git.rs@@ -72,6 +72,29 @@ impl Repository {&self.path}+ /// Get the primary remote name for this repository.+ ///+ /// Uses the following strategy:+ /// 1. If the current branch has an upstream, use its remote+ /// (Note: Detached HEAD falls through to step 2)+ /// 2. Otherwise, get the first remote from `git remote`+ /// 3. Fall back to "origin" if no remotes exist+ pub fn primary_remote(&self) -> Result<String, GitError> {+ // Try to get the remote from the current branch's upstream+ if let Ok(Some(branch)) = self.current_branch()+ && let Ok(Some(upstream)) = self.upstream_branch(&branch)+ && let Some((remote, _)) = upstream.split_once('/')+ {+ return Ok(remote.to_string());+ }++ // Fall back to first remote in the list+ let output = self.run_command(&["remote"])?;+ let first_remote = output.lines().next();++ Ok(first_remote.unwrap_or("origin").to_string())+ }+/// Check if a git branch exists (local or remote).pub fn branch_exists(&self, branch: &str) -> Result<bool, GitError> {// Try local branch first@@ -83,11 +106,12 @@ impl Repository {}// Try remote branch+ let remote = self.primary_remote()?;Ok(self.run_command(&["rev-parse","--verify",- &format!("refs/remotes/origin/{}", branch),+ &format!("refs/remotes/{}/{}", remote, branch),]).is_ok())}@@ -107,14 +131,15 @@ impl Repository {/// Get the default branch name for the repository.////// Uses a hybrid approach:- /// 1. Try local cache (origin/HEAD) first for speed+ /// 1. Try local cache (remote/HEAD) first for speed/// 2. If not cached, query the remote and cache the resultpub fn default_branch(&self) -> Result<String, GitError> {+ let remote = self.primary_remote()?;// Try local cache first (fast path)- self.get_local_default_branch().or_else(|_| {+ self.get_local_default_branch(&remote).or_else(|_| {// Query remote and cache it- let branch = self.query_remote_default_branch()?;- self.cache_default_branch(&branch)?;+ let branch = self.query_remote_default_branch(&remote)?;+ self.cache_default_branch(&remote, &branch)?;Ok(branch)})}@@ -372,18 +397,19 @@ impl Repository {// Private helper methods for default_branch()- fn get_local_default_branch(&self) -> Result<String, GitError> {- let stdout = self.run_command(&["rev-parse", "--abbrev-ref", "origin/HEAD"])?;- parse_local_default_branch(&stdout)+ fn get_local_default_branch(&self, remote: &str) -> Result<String, GitError> {+ let stdout =+ self.run_command(&["rev-parse", "--abbrev-ref", &format!("{}/HEAD", remote)])?;+ parse_local_default_branch(&stdout, remote)}- fn query_remote_default_branch(&self) -> Result<String, GitError> {- let stdout = self.run_command(&["ls-remote", "--symref", "origin", "HEAD"])?;+ fn query_remote_default_branch(&self, remote: &str) -> Result<String, GitError> {+ let stdout = self.run_command(&["ls-remote", "--symref", remote, "HEAD"])?;parse_remote_default_branch(&stdout)}- fn cache_default_branch(&self, branch: &str) -> Result<(), GitError> {- self.run_command(&["remote", "set-head", "origin", branch])?;+ fn cache_default_branch(&self, remote: &str, branch: &str) -> Result<(), GitError> {+ self.run_command(&["remote", "set-head", remote, branch])?;Ok(())}@@ -504,16 +530,18 @@ fn parse_worktree_list(output: &str) -> Result<Vec<Worktree>, GitError> {Ok(worktrees)}-fn parse_local_default_branch(output: &str) -> Result<String, GitError> {+fn parse_local_default_branch(output: &str, remote: &str) -> Result<String, GitError> {let trimmed = output.trim();- // Strip "origin/" prefix if present- let branch = trimmed.strip_prefix("origin/").unwrap_or(trimmed);+ // Strip "remote/" prefix if present+ let prefix = format!("{}/", remote);+ let branch = trimmed.strip_prefix(&prefix).unwrap_or(trimmed);if branch.is_empty() {- return Err(GitError::ParseError(- "Empty branch name from origin/HEAD".to_string(),- ));+ return Err(GitError::ParseError(format!(+ "Empty branch name from {}/HEAD",+ remote+ )));}Ok(branch.to_string())@@ -644,35 +672,42 @@ bare#[test]fn test_parse_local_default_branch_with_prefix() {let output = "origin/main\n";- let branch = parse_local_default_branch(output).unwrap();+ let branch = parse_local_default_branch(output, "origin").unwrap();assert_eq!(branch, "main");}#[test]fn test_parse_local_default_branch_without_prefix() {let output = "main\n";- let branch = parse_local_default_branch(output).unwrap();+ let branch = parse_local_default_branch(output, "origin").unwrap();assert_eq!(branch, "main");}#[test]fn test_parse_local_default_branch_master() {let output = "origin/master\n";- let branch = parse_local_default_branch(output).unwrap();+ let branch = parse_local_default_branch(output, "origin").unwrap();assert_eq!(branch, "master");}#[test]fn test_parse_local_default_branch_custom_name() {let output = "origin/develop\n";- let branch = parse_local_default_branch(output).unwrap();+ let branch = parse_local_default_branch(output, "origin").unwrap();assert_eq!(branch, "develop");}+ #[test]+ fn test_parse_local_default_branch_custom_remote() {+ let output = "upstream/main\n";+ let branch = parse_local_default_branch(output, "upstream").unwrap();+ assert_eq!(branch, "main");+ }+#[test]fn test_parse_local_default_branch_empty() {let output = "";- let result = parse_local_default_branch(output);+ let result = parse_local_default_branch(output, "origin");assert!(result.is_err());assert!(matches!(result.unwrap_err(), GitError::ParseError(_)));}@@ -680,7 +715,7 @@ bare#[test]fn test_parse_local_default_branch_whitespace_only() {let output = " \n ";- let result = parse_local_default_branch(output);+ let result = parse_local_default_branch(output, "origin");assert!(result.is_err());}diff --git a/tests/common/mod.rs b/tests/common/mod.rsindex 8feb16292..adb8ec62e 100644--- a/tests/common/mod.rs+++ b/tests/common/mod.rs@@ -268,8 +268,17 @@ impl TestRepo {/// it as the 'origin' remote. The remote will have the same default branch/// as the local repository (main).pub fn setup_remote(&mut self, default_branch: &str) {+ self.setup_custom_remote("origin", default_branch);+ }++ /// Create a bare remote repository with a custom name+ ///+ /// This creates a bare git repository in the temp directory and configures+ /// it with the specified remote name. The remote will have the same default+ /// branch as the local repository.+ pub fn setup_custom_remote(&mut self, remote_name: &str, default_branch: &str) {// Create bare remote repository- let remote_path = self.temp_dir.path().join("remote.git");+ let remote_path = self.temp_dir.path().join(format!("{}.git", remote_name));std::fs::create_dir(&remote_path).expect("Failed to create remote directory");let mut cmd = Command::new("git");@@ -287,7 +296,7 @@ impl TestRepo {// Add as remotelet mut cmd = Command::new("git");self.configure_git_cmd(&mut cmd);- cmd.args(["remote", "add", "origin", remote_path.to_str().unwrap()])+ cmd.args(["remote", "add", remote_name, remote_path.to_str().unwrap()]).current_dir(&self.root).output().expect("Failed to add remote");@@ -295,18 +304,18 @@ impl TestRepo {// Push current branch to remotelet mut cmd = Command::new("git");self.configure_git_cmd(&mut cmd);- cmd.args(["push", "-u", "origin", default_branch])+ cmd.args(["push", "-u", remote_name, default_branch]).current_dir(&self.root).output().expect("Failed to push to remote");- // Set origin/HEAD to point to the default branch+ // Set remote/HEAD to point to the default branchlet mut cmd = Command::new("git");self.configure_git_cmd(&mut cmd);- cmd.args(["remote", "set-head", "origin", default_branch])+ cmd.args(["remote", "set-head", remote_name, default_branch]).current_dir(&self.root).output()- .expect("Failed to set origin/HEAD");+ .unwrap_or_else(|_| panic!("Failed to set {}/HEAD", remote_name));self.remote = Some(remote_path);}diff --git a/tests/integration_tests/default_branch.rs b/tests/integration_tests/default_branch.rsindex 9644df4e6..f7923e074 100644--- a/tests/integration_tests/default_branch.rs+++ b/tests/integration_tests/default_branch.rs@@ -69,3 +69,52 @@ fn test_get_default_branch_no_remote() {let result = Repository::at(repo.root_path()).default_branch();assert!(result.is_err());}++#[test]+fn test_get_default_branch_with_custom_remote() {+ let mut repo = TestRepo::new();+ repo.commit("Initial commit");+ repo.setup_custom_remote("upstream", "main");++ // Test that we can get the default branch from a custom remote+ let branch = Repository::at(repo.root_path())+ .default_branch()+ .expect("Failed to get default branch");+ assert_eq!(branch, "main");+}++#[test]+fn test_primary_remote_detects_custom_remote() {+ let mut repo = TestRepo::new();+ repo.commit("Initial commit");+ repo.setup_custom_remote("upstream", "develop");++ // Test that primary_remote detects the custom remote name+ let remote = Repository::at(repo.root_path())+ .primary_remote()+ .expect("Failed to get primary remote");+ assert_eq!(remote, "upstream");+}++#[test]+fn test_branch_exists_with_custom_remote() {+ let mut repo = TestRepo::new();+ repo.commit("Initial commit");+ repo.setup_custom_remote("upstream", "main");++ let git_repo = Repository::at(repo.root_path());++ // Should find the branch on the custom remote+ assert!(+ git_repo+ .branch_exists("main")+ .expect("Failed to check branch")+ );++ // Should not find non-existent branch+ assert!(+ !git_repo+ .branch_exists("nonexistent")+ .expect("Failed to check branch")+ );+}