Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor: add Branch struct for branch-specific operations (#711)
Maximilian Roos1d0db6402b26
diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rsindex ac22cd824..fd56c2073 100644--- a/src/commands/command_executor.rs+++ b/src/commands/command_executor.rs@@ -115,7 +115,7 @@ pub fn build_hook_context(map.insert("remote_url".into(), url);}if let Some(branch) = ctx.branch- && let Ok(Some(upstream)) = ctx.repo.upstream_branch(branch)+ && let Ok(Some(upstream)) = ctx.repo.branch(branch).upstream(){map.insert("upstream".into(), upstream);}diff --git a/src/commands/config/state.rs b/src/commands/config/state.rsindex 8eb08a0c6..8829343d0 100644--- a/src/commands/config/state.rs+++ b/src/commands/config/state.rs@@ -211,7 +211,12 @@ pub fn handle_state_get(key: &str, branch: Option<String>) -> anyhow::Result<()>.into());}- let has_upstream = repo.upstream_branch(&branch_name).ok().flatten().is_some();+ let has_upstream = repo+ .branch(&branch_name)+ .upstream()+ .ok()+ .flatten()+ .is_some();let ci_status = PrStatus::detect(&repo, &branch_name, &head, has_upstream).map_or(super::super::list::ci_status::CiStatus::NoCI, |s| {s.ci_status@@ -246,7 +251,7 @@ pub fn handle_state_set(key: &str, value: String, branch: Option<String>) -> anymatch key {"default-branch" => {// Warn if the branch doesn't exist locally- if !repo.local_branch_exists(&value)? {+ if !repo.branch(&value).exists_locally()? {output::print(warning_message(cformat!("Branch <bold>{value}</> does not exist locally")))?;diff --git a/src/commands/list/collect/tasks.rs b/src/commands/list/collect/tasks.rsindex 815573db9..71b88089b 100644--- a/src/commands/list/collect/tasks.rs+++ b/src/commands/list/collect/tasks.rs@@ -555,7 +555,8 @@ impl Task for UpstreamTask {// Get upstream branch (None is valid - just means no upstream configured)let upstream_branch = repo- .upstream_branch(branch)+ .branch(branch)+ .upstream().map_err(|e| ctx.error(Self::KIND, &e))?;let Some(upstream_branch) = upstream_branch else {return Ok(TaskResult::Upstream {@@ -593,7 +594,7 @@ impl Task for CiStatusTask {fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {let repo = &ctx.repo;let pr_status = ctx.branch_ref.branch.as_deref().and_then(|branch| {- let has_upstream = repo.upstream_branch(branch).ok().flatten().is_some();+ let has_upstream = repo.branch(branch).upstream().ok().flatten().is_some();PrStatus::detect(repo, branch, &ctx.branch_ref.commit_sha, has_upstream)});diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rsindex ec2e8b183..807798cae 100644--- a/src/commands/repository_ext.rs+++ b/src/commands/repository_ext.rs@@ -109,14 +109,15 @@ impl RepositoryCliExt for Repository {}None => {// No worktree found - check if the branch exists locally- if self.local_branch_exists(branch)? {+ let branch_handle = self.branch(branch);+ if branch_handle.exists_locally()? {return Ok(RemoveResult::BranchOnly {branch_name: branch.to_string(),deletion_mode,});}// Check if branch exists on a remote- let remotes = self.remotes_with_branch(branch)?;+ let remotes = branch_handle.remotes()?;if !remotes.is_empty() {return Err(GitError::RemoteOnlyBranch {branch: branch.into(),diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rsindex 508155edb..6b9158876 100644--- a/src/commands/worktree/switch.rs+++ b/src/commands/worktree/switch.rs@@ -139,7 +139,8 @@ fn resolve_switch_target(// Validate --create constraintsif create {- if repo.local_branch_exists(&resolved_branch)? {+ let branch_handle = repo.branch(&resolved_branch);+ if branch_handle.exists_locally()? {return Err(GitError::BranchAlreadyExists {branch: resolved_branch,}@@ -147,7 +148,7 @@ fn resolve_switch_target(}// Warn if --create would shadow a remote branch- let remotes = repo.remotes_with_branch(&resolved_branch)?;+ let remotes = branch_handle.remotes()?;if !remotes.is_empty() {let remote_ref = format!("{}/{}", remotes[0], resolved_branch);crate::output::print(warning_message(cformat!(@@ -175,7 +176,7 @@ fn resolve_switch_target(}repo.resolve_target_branch(None).ok()- .filter(|b| repo.local_branch_exists(b).unwrap_or(false))+ .filter(|b| repo.branch(b).exists_locally().unwrap_or(false))})} else {None@@ -237,7 +238,7 @@ fn validate_worktree_creation(create_branch: false,..} = method- && !repo.branch_exists(branch)?+ && !repo.branch(branch).exists()?{return Err(GitError::InvalidReference {reference: branch.to_string(),@@ -448,8 +449,9 @@ pub fn execute_switch(base_branch,} => {// Check if local branch exists BEFORE git worktree add (for DWIM detection)+ let branch_handle = repo.branch(&branch);let local_branch_existed =- !create_branch && repo.local_branch_exists(&branch).unwrap_or(false);+ !create_branch && branch_handle.exists_locally().unwrap_or(false);// Build git worktree add commandlet worktree_path_str = worktree_path.to_string_lossy();@@ -476,7 +478,7 @@ pub fn execute_switch(// Report tracking info only if git's DWIM created the branch from a remotelet from_remote = if !create_branch && !local_branch_existed {- repo.upstream_branch(&branch)?+ branch_handle.upstream()?} else {None};diff --git a/src/git/mod.rs b/src/git/mod.rsindex a1298327d..0f8e53b7c 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -43,7 +43,7 @@ pub use error::{exit_code,};pub use parse::{parse_porcelain_z, parse_untracked_files};-pub use repository::{Repository, ResolvedWorktree, WorkingTree, set_base_path};+pub use repository::{Branch, Repository, ResolvedWorktree, WorkingTree, set_base_path};pub(crate) use url::GitRemoteUrl;pub use url::{parse_owner_repo, parse_remote_owner};/// Why branch content is considered integrated into the target branch.diff --git a/src/git/repository/branch.rs b/src/git/repository/branch.rsnew file mode 100644index 000000000..01e1370e4--- /dev/null+++ b/src/git/repository/branch.rs@@ -0,0 +1,142 @@+//! Branch - a handle for branch-specific git operations.++use super::Repository;++/// A handle for running git commands on a specific branch.+///+/// This type holds a reference to [`Repository`] and a branch name.+/// All branch-specific operations (like `exists`, `upstream`) are on this type.+///+/// # Examples+///+/// ```no_run+/// use worktrunk::git::Repository;+///+/// let repo = Repository::current()?;+/// let branch = repo.branch("feature");+///+/// // Branch-specific operations+/// let _ = branch.exists_locally();+/// let _ = branch.upstream();+/// let _ = branch.remotes();+///+/// # Ok::<(), anyhow::Error>(())+/// ```+#[derive(Debug)]+#[must_use]+pub struct Branch<'a> {+ pub(super) repo: &'a Repository,+ pub(super) name: String,+}++impl<'a> Branch<'a> {+ /// Get the branch name.+ pub fn name(&self) -> &str {+ &self.name+ }++ /// Check if this branch exists locally.+ pub fn exists_locally(&self) -> anyhow::Result<bool> {+ Ok(self+ .repo+ .run_command(&[+ "rev-parse",+ "--verify",+ &format!("refs/heads/{}", self.name),+ ])+ .is_ok())+ }++ /// Check if this branch exists (local or remote).+ pub fn exists(&self) -> anyhow::Result<bool> {+ // Try local branch first+ if 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())+ }++ /// Find which remotes have this branch.+ ///+ /// Returns a list of remote names that have this branch (e.g., `["origin"]`).+ /// Returns an empty list if no remotes have this branch.+ pub fn remotes(&self) -> anyhow::Result<Vec<String>> {+ // Get all remote tracking branches matching this name+ // Format: refs/remotes/<remote>/<branch>+ let output = self.repo.run_command(&[+ "for-each-ref",+ "--format=%(refname:strip=2)",+ &format!("refs/remotes/*/{}", self.name),+ ])?;++ // Parse output: each line is "<remote>/<branch>"+ // Extract the remote name (everything before the last /<branch>)+ let suffix = format!("/{}", self.name);+ let remotes: Vec<String> = output+ .lines()+ .filter_map(|line| {+ let line = line.trim();+ // Strip the branch suffix to get the remote name+ line.strip_suffix(&suffix).map(String::from)+ })+ .collect();++ Ok(remotes)+ }++ /// Get the upstream tracking branch for this branch.+ ///+ /// Uses [`@{upstream}` syntax][1] to resolve the tracking branch.+ ///+ /// [1]: https://git-scm.com/docs/gitrevisions#Documentation/gitrevisions.txt-emltaboranchgtemuaboranchgtupaboranchgtupstream+ pub fn upstream(&self) -> anyhow::Result<Option<String>> {+ let result =+ self.repo+ .run_command(&["rev-parse", "--abbrev-ref", &format!("{}@{{u}}", self.name)]);++ match result {+ Ok(upstream) => {+ let trimmed = upstream.trim();+ Ok((!trimmed.is_empty()).then(|| trimmed.to_string()))+ }+ Err(_) => Ok(None), // No upstream configured+ }+ }++ /// Get the remote where this branch would be pushed.+ ///+ /// Uses [`@{push}` syntax][1] which resolves through:+ /// 1. `branch.<name>.pushRemote` (branch-specific push remote)+ /// 2. `remote.pushDefault` (default push remote for all branches)+ /// 3. `branch.<name>.remote` (tracking remote)+ ///+ /// Returns `None` if no push destination is configured.+ ///+ /// [1]: https://git-scm.com/docs/gitrevisions#Documentation/gitrevisions.txt-emltbraboranchgtpaboranchgtpush+ pub fn push_remote(&self) -> Option<String> {+ let push_ref = self+ .repo+ .run_command(&[+ "rev-parse",+ "--abbrev-ref",+ &format!("{}@{{push}}", self.name),+ ])+ .ok()?;++ // Returns "origin/branch", extract remote name+ let remote = push_ref.trim().split('/').next()?;+ (!remote.is_empty()).then(|| remote.to_string())+ }+}diff --git a/src/git/repository/branches.rs b/src/git/repository/branches.rsindex 377d3dee0..be6628374 100644--- a/src/git/repository/branches.rs+++ b/src/git/repository/branches.rs@@ -1,37 +1,13 @@//! Branch-related operations for Repository.+//!+//! For single-branch operations, see [`super::Branch`].+//! This module contains multi-branch operations (listing, filtering, etc.).use std::collections::HashSet;use super::{BranchCategory, CompletionBranch, Repository};impl Repository {- /// Check if a local git branch exists.- pub fn local_branch_exists(&self, branch: &str) -> anyhow::Result<bool> {- Ok(self- .run_command(&["rev-parse", "--verify", &format!("refs/heads/{}", branch)])- .is_ok())- }-- /// Check if a git branch exists (local or remote).- pub fn branch_exists(&self, branch: &str) -> anyhow::Result<bool> {- // Try local branch first- if self.local_branch_exists(branch)? {- return Ok(true);- }-- // Try remote branch (if remotes exist)- let Ok(remote) = self.primary_remote() else {- return Ok(false);- };- Ok(self- .run_command(&[- "rev-parse",- "--verify",- &format!("refs/remotes/{}/{}", remote, branch),- ])- .is_ok())- }-/// Check if a git reference exists (branch, tag, commit SHA, HEAD, etc.).////// Accepts any valid commit-ish: branch names, tags, HEAD, commit SHAs,@@ -48,33 +24,6 @@ impl Repository {.is_ok())}- /// Find which remotes have a branch with the given name.- ///- /// Returns a list of remote names that have this branch (e.g., `["origin"]`).- /// Returns an empty list if no remotes have this branch.- pub fn remotes_with_branch(&self, branch: &str) -> anyhow::Result<Vec<String>> {- // Get all remote tracking branches matching this name- // Format: refs/remotes/<remote>/<branch>- let output = self.run_command(&[- "for-each-ref",- "--format=%(refname:strip=2)",- &format!("refs/remotes/*/{}", branch),- ])?;-- // Parse output: each line is "<remote>/<branch>"- // Extract the remote name (everything before the last /<branch>)- let remotes: Vec<String> = output- .lines()- .filter_map(|line| {- let line = line.trim();- // Strip the branch suffix to get the remote name- line.strip_suffix(&format!("/{}", branch)).map(String::from)- })- .collect();-- Ok(remotes)- }-/// Get all branch names (local branches only).pub fn all_branches(&self) -> anyhow::Result<Vec<String>> {let stdout = self.run_command(&[@@ -178,23 +127,6 @@ impl Repository {Ok(remote_branches)}- /// Get the upstream tracking branch for the given branch.- ///- /// Uses [`@{upstream}` syntax][1] to resolve the tracking branch.- ///- /// [1]: https://git-scm.com/docs/gitrevisions#Documentation/gitrevisions.txt-emltaboranchgtemuaboranchgtupaboranchgtupstream- pub fn upstream_branch(&self, branch: &str) -> anyhow::Result<Option<String>> {- let result = self.run_command(&["rev-parse", "--abbrev-ref", &format!("{}@{{u}}", branch)]);-- match result {- Ok(upstream) => {- let trimmed = upstream.trim();- Ok((!trimmed.is_empty()).then(|| trimmed.to_string()))- }- Err(_) => Ok(None), // No upstream configured- }- }-/// Get branches that don't have worktrees (available for switch).pub fn available_branches(&self) -> anyhow::Result<Vec<String>> {let all_branches = self.all_branches()?;diff --git a/src/git/repository/config.rs b/src/git/repository/config.rsindex df4f7af89..f8675cd2f 100644--- a/src/git/repository/config.rs+++ b/src/git/repository/config.rs@@ -152,7 +152,7 @@ impl Repository {// If configured, validate it exists locallyif let Some(ref branch) = configured {- if self.local_branch_exists(branch).unwrap_or(false) {+ if self.branch(branch).exists_locally().unwrap_or(false) {let _ = self.cache.invalid_default_branch.set(None);return Some(branch.clone());}@@ -245,7 +245,7 @@ impl Repository {/// Validates before approval prompts to avoid wasting user time.pub fn require_target_branch(&self, target: Option<&str>) -> anyhow::Result<String> {let branch = self.resolve_target_branch(target)?;- if !self.branch_exists(&branch)? {+ if !self.branch(&branch).exists()? {return Err(GitError::InvalidReference { reference: branch }.into());}Ok(branch)diff --git a/src/git/repository/integration.rs b/src/git/repository/integration.rsindex 4f4f19d12..4669b1a56 100644--- a/src/git/repository/integration.rs+++ b/src/git/repository/integration.rs@@ -176,7 +176,7 @@ impl Repository {/// Current behavior: uses only local in diverged state, may miss remote-merged branches.pub fn effective_integration_target(&self, local_target: &str) -> String {// Get the upstream ref for the local target (e.g., origin/main for main)- let upstream = match self.upstream_branch(local_target) {+ let upstream = match self.branch(local_target).upstream() {Ok(Some(upstream)) => upstream,_ => return local_target.to_string(),};diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 25c6ed264..92730aeb3 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -1,13 +1,15 @@//! Repository - git repository operations.//!//! This module provides the [`Repository`] type for interacting with git repositories,-//! and [`WorkingTree`] for worktree-specific operations.+//! [`WorkingTree`] for worktree-specific operations, and [`Branch`] for branch-specific+//! operations.//!//! # Module organization//!//! - `mod.rs` - Core types and construction//! - `working_tree.rs` - WorkingTree struct and worktree-specific operations-//! - `branches.rs` - Branch listing, existence checks, completions+//! - `branch.rs` - Branch struct and single-branch operations (exists, upstream, remotes)+//! - `branches.rs` - Multi-branch operations (listing, filtering, completions)//! - `worktrees.rs` - Worktree management (list, resolve, remove)//! - `remotes.rs` - Remote and URL operations//! - `diff.rs` - Diff, history, and commit operations@@ -34,6 +36,7 @@ use super::{DefaultBranchName, GitError, LineDiff, WorktreeInfo};pub(super) use super::{BranchCategory, CompletionBranch, DiffStats, GitRemoteUrl};// Submodules with impl blocks+mod branch;mod branches;mod config;mod diff;@@ -42,7 +45,8 @@ mod remotes;mod working_tree;mod worktrees;-// Re-export WorkingTree+// Re-export WorkingTree and Branch+pub use branch::Branch;pub use working_tree::WorkingTree;pub(super) use working_tree::path_to_logging_context;@@ -261,6 +265,16 @@ impl Repository {}}+ /// Get a branch handle for branch-specific operations.+ ///+ /// Use this when you need to query properties of a specific branch.+ pub fn branch(&self, name: &str) -> Branch<'_> {+ Branch {+ repo: self,+ name: name.to_string(),+ }+ }+/// Get the current branch name, or error if in detached HEAD state.////// `action` describes what requires being on a branch (e.g., "merge").diff --git a/tests/integration_tests/default_branch.rs b/tests/integration_tests/default_branch.rsindex ab60b52ff..6b621b5b9 100644--- a/tests/integration_tests/default_branch.rs+++ b/tests/integration_tests/default_branch.rs@@ -120,10 +120,10 @@ fn test_branch_exists_with_custom_remote(mut repo: TestRepo) {let git_repo = Repository::at(repo.root_path()).unwrap();// Should find the branch on the custom remote- assert!(git_repo.branch_exists("main").unwrap());+ assert!(git_repo.branch("main").exists().unwrap());// Should not find non-existent branch- assert!(!git_repo.branch_exists("nonexistent").unwrap());+ assert!(!git_repo.branch("nonexistent").exists().unwrap());}#[rstest]