Skip to content

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

Refactor git functions into Repository struct for clarity

Maximilian Roosade4665ef96a
diff --git a/src/commands/completion.rs b/src/commands/completion.rs
index 23c3d2ac3..c6790611e 100644
--- a/src/commands/completion.rs
+++ b/src/commands/completion.rs
@@ -1,8 +1,7 @@
use clap::Command;
use clap_complete::{Shell as CompletionShell, generate};
use std::io;
-use std::path::Path;
-use worktrunk::git::{GitError, get_all_branches_in, get_available_branches};
+use worktrunk::git::{GitError, Repository};
#[derive(clap::ValueEnum, Clone, Copy)]
pub enum Shell {
@@ -75,7 +74,8 @@ pub fn handle_complete(args: Vec<String>) -> Result<(), GitError> {
match context {
CompletionContext::SwitchBranch => {
// Complete with available branches (excluding those with worktrees)
- let branches = get_branches_for_completion(get_available_branches);
+ let branches =
+ get_branches_for_completion(|| Repository::current().available_branches());
for branch in branches {
println!("{}", branch);
}
@@ -84,7 +84,7 @@ pub fn handle_complete(args: Vec<String>) -> Result<(), GitError> {
| CompletionContext::MergeTarget
| CompletionContext::BaseFlag => {
// Complete with all branches
- let branches = get_branches_for_completion(|| get_all_branches_in(Path::new(".")));
+ let branches = get_branches_for_completion(|| Repository::current().all_branches());
for branch in branches {
println!("{}", branch);
}
diff --git a/src/commands/list/mod.rs b/src/commands/list/mod.rs
index 54ab2dbfd..2a597e412 100644
--- a/src/commands/list/mod.rs
+++ b/src/commands/list/mod.rs
@@ -2,12 +2,7 @@ mod layout;
mod render;
use rayon::prelude::*;
-use std::path::Path;
-use worktrunk::git::{
- GitError, get_ahead_behind_in, get_branch_diff_stats_in, get_commit_message_in,
- get_commit_timestamp_in, get_upstream_branch_in, get_working_tree_diff_stats_in,
- get_worktree_root_in, get_worktree_state_in, list_worktrees,
-};
+use worktrunk::git::{GitError, Repository};
use layout::calculate_responsive_layout;
use render::{format_header_line, format_worktree_line};
@@ -35,7 +30,8 @@ pub struct WorktreeInfo {
}
pub fn handle_list() -> Result<(), GitError> {
- let worktrees = list_worktrees()?;
+ let repo = Repository::current();
+ let worktrees = repo.list_worktrees()?;
if worktrees.is_empty() {
return Ok(());
@@ -46,10 +42,11 @@ pub fn handle_list() -> Result<(), GitError> {
let primary_branch = primary.branch.as_ref();
// Get current worktree to identify active one
- let current_worktree_path = get_worktree_root_in(Path::new(".")).ok();
+ let current_worktree_path = repo.worktree_root().ok();
// Helper function to process a single worktree
let process_worktree = |idx: usize, wt: &worktrunk::git::Worktree| -> WorktreeInfo {
+ let wt_repo = Repository::at(&wt.path);
let is_primary = idx == 0;
let is_current = current_worktree_path
.as_ref()
@@ -57,26 +54,26 @@ pub fn handle_list() -> Result<(), GitError> {
.unwrap_or(false);
// Get commit timestamp
- let timestamp = get_commit_timestamp_in(&wt.path, &wt.head).unwrap_or(0);
+ let timestamp = wt_repo.commit_timestamp(&wt.head).unwrap_or(0);
// Get commit message
- let commit_message = get_commit_message_in(&wt.path, &wt.head).unwrap_or_default();
+ let commit_message = wt_repo.commit_message(&wt.head).unwrap_or_default();
// Calculate ahead/behind relative to primary branch (only if primary has a branch)
let (ahead, behind) = if is_primary {
(0, 0)
} else if let Some(pb) = primary_branch {
- get_ahead_behind_in(&wt.path, pb, &wt.head).unwrap_or((0, 0))
+ wt_repo.ahead_behind(pb, &wt.head).unwrap_or((0, 0))
} else {
(0, 0)
};
- let working_tree_diff = get_working_tree_diff_stats_in(&wt.path).unwrap_or((0, 0));
+ let working_tree_diff = wt_repo.working_tree_diff_stats().unwrap_or((0, 0));
// Get branch diff stats (downstream of primary, only if primary has a branch)
let branch_diff = if is_primary {
(0, 0)
} else if let Some(pb) = primary_branch {
- get_branch_diff_stats_in(&wt.path, pb, &wt.head).unwrap_or((0, 0))
+ wt_repo.branch_diff_stats(pb, &wt.head).unwrap_or((0, 0))
} else {
(0, 0)
};
@@ -84,15 +81,16 @@ pub fn handle_list() -> Result<(), GitError> {
// Get upstream tracking info
let (upstream_remote, upstream_ahead, upstream_behind) = if let Some(ref branch) = wt.branch
{
- if let Ok(Some(upstream_branch)) = get_upstream_branch_in(&wt.path, branch) {
+ if let Ok(Some(upstream_branch)) = wt_repo.upstream_branch(branch) {
// Extract remote name from "origin/main" -> "origin"
let remote = upstream_branch
.split('/')
.next()
.unwrap_or("origin")
.to_string();
- let (ahead, behind) =
- get_ahead_behind_in(&wt.path, &upstream_branch, &wt.head).unwrap_or((0, 0));
+ let (ahead, behind) = wt_repo
+ .ahead_behind(&upstream_branch, &wt.head)
+ .unwrap_or((0, 0));
(Some(remote), ahead, behind)
} else {
(None, 0, 0)
@@ -102,7 +100,7 @@ pub fn handle_list() -> Result<(), GitError> {
};
// Get worktree state (merge/rebase/etc)
- let worktree_state = get_worktree_state_in(&wt.path).unwrap_or(None);
+ let worktree_state = wt_repo.worktree_state().unwrap_or(None);
WorktreeInfo {
path: wt.path.clone(),
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index aea14772c..4316eeecb 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -1,24 +1,22 @@
-use std::path::Path;
use worktrunk::config::load_config;
use worktrunk::error_format::format_error;
-use worktrunk::git::{
- GitError, count_commits_in, get_commit_subjects_in, get_current_branch_in,
- get_default_branch_in, get_merge_base_in, get_repo_root_in, has_staged_changes_in, is_dirty_in,
- run_git_command,
-};
+use worktrunk::git::{GitError, Repository, run_git_command};
use super::worktree::handle_push;
use super::worktree::handle_remove;
pub fn handle_merge(target: Option<&str>, squash: bool, keep: bool) -> Result<(), GitError> {
+ let repo = Repository::current();
+
// Get current branch
- let current_branch = get_current_branch_in(Path::new("."))?
+ let current_branch = repo
+ .current_branch()?
.ok_or_else(|| GitError::CommandFailed(format_error("Not on a branch (detached HEAD)")))?;
// Get target branch (default to default branch if not provided)
let target_branch = match target {
Some(b) => b.to_string(),
- None => get_default_branch_in(Path::new("."))?,
+ None => repo.default_branch()?,
};
// Check if already on target branch
@@ -28,7 +26,7 @@ pub fn handle_merge(target: Option<&str>, squash: bool, keep: bool) -> Result<()
}
// Check for uncommitted changes
- if is_dirty_in(Path::new("."))? {
+ if repo.is_dirty()? {
return Err(GitError::CommandFailed(format_error(
"Working tree has uncommitted changes. Commit or stash them first.",
)));
@@ -42,7 +40,7 @@ pub fn handle_merge(target: Option<&str>, squash: bool, keep: bool) -> Result<()
// Rebase onto target
println!("Rebasing onto '{}'...", target_branch);
- run_git_command(&["rebase", &target_branch], Some(Path::new("."))).map_err(|e| {
+ run_git_command(&["rebase", &target_branch], Some(repo.path())).map_err(|e| {
GitError::CommandFailed(format!("Failed to rebase onto '{}': {}", target_branch, e))
})?;
@@ -55,12 +53,12 @@ pub fn handle_merge(target: Option<&str>, squash: bool, keep: bool) -> Result<()
println!("Cleaning up worktree...");
// Get primary worktree path before finishing (while we can still run git commands)
- let primary_worktree_dir = get_repo_root_in(Path::new("."))?;
+ let primary_worktree_dir = repo.repo_root()?;
handle_remove(false)?;
// Check if we need to switch to target branch
- let new_branch = get_current_branch_in(&primary_worktree_dir)?;
+ let new_branch = Repository::at(&primary_worktree_dir).current_branch()?;
if new_branch.as_deref() != Some(&target_branch) {
println!("Switching to '{}'...", target_branch);
run_git_command(&["switch", &target_branch], Some(&primary_worktree_dir)).map_err(
@@ -83,14 +81,16 @@ pub fn handle_merge(target: Option<&str>, squash: bool, keep: bool) -> Result<()
}
fn handle_squash(target_branch: &str) -> Result<(), GitError> {
+ let repo = Repository::current();
+
// Get merge base with target branch
- let merge_base = get_merge_base_in(Path::new("."), "HEAD", target_branch)?;
+ let merge_base = repo.merge_base("HEAD", target_branch)?;
// Count commits since merge base
- let commit_count = count_commits_in(Path::new("."), &merge_base, "HEAD")?;
+ let commit_count = repo.count_commits(&merge_base, "HEAD")?;
// Check if there are staged changes
- let has_staged = has_staged_changes_in(Path::new("."))?;
+ let has_staged = repo.has_staged_changes()?;
// Handle different scenarios
if commit_count == 0 && !has_staged {
@@ -120,7 +120,7 @@ fn handle_squash(target_branch: &str) -> Result<(), GitError> {
// Get commit subjects for the squash message
let range = format!("{}..HEAD", merge_base);
- let subjects = get_commit_subjects_in(Path::new("."), &range)?;
+ let subjects = repo.commit_subjects(&range)?;
// Load config and generate commit message
let config = load_config()
@@ -128,11 +128,11 @@ fn handle_squash(target_branch: &str) -> Result<(), GitError> {
let commit_message = crate::llm::generate_squash_message(target_branch, &subjects, &config.llm);
// Reset to merge base (soft reset stages all changes)
- run_git_command(&["reset", "--soft", &merge_base], Some(Path::new(".")))
+ run_git_command(&["reset", "--soft", &merge_base], Some(repo.path()))
.map_err(|e| GitError::CommandFailed(format!("Failed to reset to merge base: {}", e)))?;
// Commit with the generated message
- run_git_command(&["commit", "-m", &commit_message], Some(Path::new(".")))
+ run_git_command(&["commit", "-m", &commit_message], Some(repo.path()))
.map_err(|e| GitError::CommandFailed(format!("Failed to create squash commit: {}", e)))?;
println!("Successfully squashed {} commits into one", commit_count);
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rs
index f7ae8a60d..81f86d492 100644
--- a/src/commands/worktree.rs
+++ b/src/commands/worktree.rs
@@ -2,12 +2,7 @@ use std::path::Path;
use std::process;
use worktrunk::config::format_worktree_path;
use worktrunk::error_format::{format_error, format_error_with_bold, format_hint};
-use worktrunk::git::{
- GitError, branch_exists_in, count_commits_in, get_changed_files_in, get_current_branch_in,
- get_default_branch_in, get_git_common_dir_in, get_repo_root_in, get_worktree_root_in,
- has_merge_commits_in, is_ancestor_in, is_dirty_in, is_in_worktree_in, run_git_command,
- worktree_for_branch,
-};
+use worktrunk::git::{GitError, Repository, run_git_command};
pub fn handle_switch(
branch: &str,
@@ -16,8 +11,10 @@ pub fn handle_switch(
internal: bool,
worktree_path_template: &str,
) -> Result<(), GitError> {
+ let repo = Repository::current();
+
// Check for conflicting conditions
- if create && branch_exists_in(Path::new("."), branch)? {
+ if create && repo.branch_exists(branch)? {
return Err(GitError::CommandFailed(format_error_with_bold(
"Branch '",
branch,
@@ -34,7 +31,7 @@ pub fn handle_switch(
}
// Check if worktree already exists for this branch
- if let Some(existing_path) = worktree_for_branch(branch)? {
+ if let Some(existing_path) = repo.worktree_for_branch(branch)? {
if existing_path.exists() {
if internal {
println!("__WORKTRUNK_CD__{}", existing_path.display());
@@ -50,7 +47,7 @@ pub fn handle_switch(
}
// No existing worktree, create one
- let repo_root = get_repo_root_in(Path::new("."))?;
+ let repo_root = repo.repo_root()?;
let repo_name = repo_root
.file_name()
@@ -97,17 +94,19 @@ pub fn handle_switch(
}
pub fn handle_remove(internal: bool) -> Result<(), GitError> {
+ let repo = Repository::current();
+
// Check for uncommitted changes
- if is_dirty_in(Path::new("."))? {
+ if repo.is_dirty()? {
return Err(GitError::CommandFailed(format_error(
"Working tree has uncommitted changes. Commit or stash them first.",
)));
}
// Get current state
- let current_branch = get_current_branch_in(Path::new("."))?;
- let default_branch = get_default_branch_in(Path::new("."))?;
- let in_worktree = is_in_worktree_in(Path::new("."))?;
+ let current_branch = repo.current_branch()?;
+ let default_branch = repo.default_branch()?;
+ let in_worktree = repo.is_in_worktree()?;
// If we're on default branch and not in a worktree, nothing to do
if !in_worktree && current_branch.as_deref() == Some(&default_branch) {
@@ -119,8 +118,8 @@ pub fn handle_remove(internal: bool) -> Result<(), GitError> {
if in_worktree {
// In worktree: navigate to primary worktree and remove this one
- let worktree_root = get_worktree_root_in(Path::new("."))?;
- let primary_worktree_dir = get_repo_root_in(Path::new("."))?;
+ let worktree_root = repo.worktree_root()?;
+ let primary_worktree_dir = repo.repo_root()?;
if internal {
println!("__WORKTRUNK_CD__{}", primary_worktree_dir.display());
@@ -162,14 +161,16 @@ pub fn handle_remove(internal: bool) -> Result<(), GitError> {
}
pub fn handle_push(target: Option<&str>, allow_merge_commits: bool) -> Result<(), GitError> {
+ let repo = Repository::current();
+
// Get target branch (default to default branch if not provided)
let target_branch = match target {
Some(b) => b.to_string(),
- None => get_default_branch_in(Path::new("."))?,
+ None => repo.default_branch()?,
};
// Check if it's a fast-forward
- if !is_ancestor_in(Path::new("."), &target_branch, "HEAD")? {
+ if !repo.is_ancestor(&target_branch, "HEAD")? {
let error_msg =
format_error_with_bold("Not a fast-forward from '", &target_branch, "' to HEAD");
let hint_msg = format_hint(
@@ -182,7 +183,7 @@ pub fn handle_push(target: Option<&str>, allow_merge_commits: bool) -> Result<()
}
// Check for merge commits unless allowed
- if !allow_merge_commits && has_merge_commits_in(Path::new("."), &target_branch, "HEAD")? {
+ if !allow_merge_commits && repo.has_merge_commits(&target_branch, "HEAD")? {
return Err(GitError::CommandFailed(format_error(
"Found merge commits in push range. Use --allow-merge-commits to push non-linear history.",
)));
@@ -205,13 +206,13 @@ pub fn handle_push(target: Option<&str>, allow_merge_commits: bool) -> Result<()
}
// Find worktree for target branch
- let target_worktree = worktree_for_branch(&target_branch)?;
+ let target_worktree = repo.worktree_for_branch(&target_branch)?;
if let Some(ref wt_path) = target_worktree {
// Check if target worktree is dirty
- if is_dirty_in(wt_path)? {
+ if Repository::at(wt_path).is_dirty()? {
// Get files changed in the push
- let push_files = get_changed_files_in(Path::new("."), &target_branch, "HEAD")?;
+ let push_files = repo.changed_files(&target_branch, "HEAD")?;
// Get files changed in the worktree
let wt_status_output = run_git_command(&["status", "--porcelain"], Some(wt_path))?;
@@ -249,7 +250,7 @@ pub fn handle_push(target: Option<&str>, allow_merge_commits: bool) -> Result<()
}
// Count commits and show info
- let commit_count = count_commits_in(Path::new("."), &target_branch, "HEAD")?;
+ let commit_count = repo.count_commits(&target_branch, "HEAD")?;
if commit_count > 0 {
let commit_text = if commit_count == 1 {
"commit"
@@ -263,7 +264,7 @@ pub fn handle_push(target: Option<&str>, allow_merge_commits: bool) -> Result<()
}
// Get git common dir for the push
- let git_common_dir = get_git_common_dir_in(Path::new("."))?;
+ let git_common_dir = repo.git_common_dir()?;
// Perform the push
let push_target = format!("HEAD:{}", target_branch);
diff --git a/src/git.rs b/src/git.rs
index bf6571963..43db89fff 100644
--- a/src/git.rs
+++ b/src/git.rs
@@ -34,6 +34,382 @@ impl std::fmt::Display for GitError {
impl std::error::Error for GitError {}
+/// Repository context for git operations.
+///
+/// Provides a more ergonomic API than the `*_in(path, ...)` functions by
+/// encapsulating the repository path.
+///
+/// # Examples
+///
+/// ```no_run
+/// use worktrunk::git::Repository;
+///
+/// let repo = Repository::current();
+/// let branch = repo.current_branch()?;
+/// let is_dirty = repo.is_dirty()?;
+/// # Ok::<(), worktrunk::git::GitError>(())
+/// ```
+#[derive(Debug, Clone)]
+pub struct Repository {
+ path: PathBuf,
+}
+
+impl Repository {
+ /// Create a repository context at the specified path.
+ pub fn at(path: impl Into<PathBuf>) -> Self {
+ Self { path: path.into() }
+ }
+
+ /// Create a repository context for the current directory.
+ ///
+ /// This is the most common usage pattern.
+ pub fn current() -> Self {
+ Self::at(".")
+ }
+
+ /// Get the path this repository context operates on.
+ pub fn path(&self) -> &std::path::Path {
+ &self.path
+ }
+
+ /// Check if a git branch exists (local or remote).
+ pub fn branch_exists(&self, branch: &str) -> Result<bool, GitError> {
+ // Try local branch first
+ let result = run_git_command(
+ &["rev-parse", "--verify", &format!("refs/heads/{}", branch)],
+ Some(&self.path),
+ );
+ if result.is_ok() {
+ return Ok(true);
+ }
+
+ // Try remote branch
+ let result = run_git_command(
+ &[
+ "rev-parse",
+ "--verify",
+ &format!("refs/remotes/origin/{}", branch),
+ ],
+ Some(&self.path),
+ );
+ Ok(result.is_ok())
+ }
+
+ /// Get the current branch name, or None if in detached HEAD state.
+ pub fn current_branch(&self) -> Result<Option<String>, GitError> {
+ let stdout = run_git_command(&["branch", "--show-current"], Some(&self.path))?;
+ let branch = stdout.trim();
+
+ if branch.is_empty() {
+ Ok(None) // Detached HEAD
+ } else {
+ Ok(Some(branch.to_string()))
+ }
+ }
+
+ /// Get the default branch name for the repository.
+ ///
+ /// Uses a hybrid approach:
+ /// 1. Try local cache (origin/HEAD) first for speed
+ /// 2. If not cached, query the remote and cache the result
+ pub fn default_branch(&self) -> Result<String, GitError> {
+ // Try local cache first (fast path)
+ if let Ok(branch) = self.get_local_default_branch() {
+ return Ok(branch);
+ }
+
+ // Query remote and cache it
+ let branch = self.query_remote_default_branch()?;
+ self.cache_default_branch(&branch)?;
+ Ok(branch)
+ }
+
+ /// Get the git common directory (the actual .git directory for the repository).
+ pub fn git_common_dir(&self) -> Result<PathBuf, GitError> {
+ let stdout = run_git_command(&["rev-parse", "--git-common-dir"], Some(&self.path))?;
+ Ok(PathBuf::from(stdout.trim()))
+ }
+
+ /// Get the git directory (may be different from common-dir in worktrees).
+ pub fn git_dir(&self) -> Result<PathBuf, GitError> {
+ let stdout = run_git_command(&["rev-parse", "--git-dir"], Some(&self.path))?;
+ Ok(PathBuf::from(stdout.trim()))
+ }
+
+ /// Get the canonicalized repository root directory (parent of .git).
+ ///
+ /// The canonicalization resolves symlinks and relative paths, which is important
+ /// for worktree operations to ensure consistent path handling.
+ pub fn repo_root(&self) -> Result<PathBuf, GitError> {
+ let git_common_dir = self
+ .git_common_dir()?
+ .canonicalize()
+ .map_err(|e| GitError::CommandFailed(format!("Failed to canonicalize path: {}", e)))?;
+
+ git_common_dir
+ .parent()
+ .ok_or_else(|| GitError::CommandFailed("Invalid git directory".to_string()))
+ .map(|p| p.to_path_buf())
+ }
+
+ /// Check if the working tree has uncommitted changes.
+ pub fn is_dirty(&self) -> Result<bool, GitError> {
+ let stdout = run_git_command(&["status", "--porcelain"], Some(&self.path))?;
+ Ok(!stdout.trim().is_empty())
+ }
+
+ /// Get the worktree root directory (top-level of the working tree).
+ pub fn worktree_root(&self) -> Result<PathBuf, GitError> {
+ let stdout = run_git_command(&["rev-parse", "--show-toplevel"], Some(&self.path))?;
+ Ok(PathBuf::from(stdout.trim()))
+ }
+
+ /// Check if the path is in a worktree (vs the main repository).
+ pub fn is_in_worktree(&self) -> Result<bool, GitError> {
+ let git_dir = self.git_dir()?;
+ let common_dir = self.git_common_dir()?;
+ Ok(git_dir != common_dir)
+ }
+
+ /// Check if base is an ancestor of head (i.e., would be a fast-forward).
+ pub fn is_ancestor(&self, base: &str, head: &str) -> Result<bool, GitError> {
+ let output = std::process::Command::new("git")
+ .args(["merge-base", "--is-ancestor", base, head])
+ .current_dir(&self.path)
+ .output()
+ .map_err(|e| GitError::CommandFailed(e.to_string()))?;
+
+ Ok(output.status.success())
+ }
+
+ /// Count commits between base and head.
+ pub fn count_commits(&self, base: &str, head: &str) -> Result<usize, GitError> {
+ let range = format!("{}..{}", base, head);
+ let stdout = run_git_command(&["rev-list", "--count", &range], Some(&self.path))?;
+ stdout
+ .trim()
+ .parse()
+ .map_err(|e| GitError::ParseError(format!("Failed to parse commit count: {}", e)))
+ }
+
+ /// Check if there are merge commits in the range base..head.
+ pub fn has_merge_commits(&self, base: &str, head: &str) -> Result<bool, GitError> {
+ let range = format!("{}..{}", base, head);
+ let stdout = run_git_command(&["rev-list", "--merges", &range], Some(&self.path))?;
+ Ok(!stdout.trim().is_empty())
+ }
+
+ /// Get files changed between base and head.
+ pub fn changed_files(&self, base: &str, head: &str) -> Result<Vec<String>, GitError> {
+ let range = format!("{}..{}", base, head);
+ let stdout = run_git_command(&["diff", "--name-only", &range], Some(&self.path))?;
+ Ok(stdout.lines().map(|s| s.to_string()).collect())
+ }
+
+ /// Get commit timestamp in seconds since epoch.
+ pub fn commit_timestamp(&self, commit: &str) -> Result<i64, GitError> {
+ let stdout = run_git_command(&["show", "-s", "--format=%ct", commit], Some(&self.path))?;
+ stdout
+ .trim()
+ .parse()
+ .map_err(|e| GitError::ParseError(format!("Failed to parse timestamp: {}", e)))
+ }
+
+ /// Get commit message (subject line) for a commit.
+ pub fn commit_message(&self, commit: &str) -> Result<String, GitError> {
+ let stdout = run_git_command(&["show", "-s", "--format=%s", commit], Some(&self.path))?;
+ Ok(stdout.trim().to_string())
+ }
+
+ /// Get the upstream tracking branch for the given branch.
+ pub fn upstream_branch(&self, branch: &str) -> Result<Option<String>, GitError> {
+ let result = run_git_command(
+ &["rev-parse", "--abbrev-ref", &format!("{}@{{u}}", branch)],
+ Some(&self.path),
+ );
+
+ match result {
+ Ok(upstream) => {
+ let trimmed = upstream.trim();
+ if trimmed.is_empty() {
+ Ok(None)
+ } else {
+ Ok(Some(trimmed.to_string()))
+ }
+ }
+ Err(_) => Ok(None), // No upstream configured
+ }
+ }
+
+ /// Get merge/rebase status for the worktree.
+ pub fn worktree_state(&self) -> Result<Option<String>, GitError> {
+ let git_dir = self.git_dir()?;
+
+ // Check for merge
+ if git_dir.join("MERGE_HEAD").exists() {
+ return Ok(Some("MERGING".to_string()));
+ }
+
+ // Check for rebase
+ if git_dir.join("rebase-merge").exists() || git_dir.join("rebase-apply").exists() {
+ let rebase_dir = if git_dir.join("rebase-merge").exists() {
+ git_dir.join("rebase-merge")
+ } else {
+ git_dir.join("rebase-apply")
+ };
+
+ if let (Ok(msgnum), Ok(end)) = (
+ std::fs::read_to_string(rebase_dir.join("msgnum")),
+ std::fs::read_to_string(rebase_dir.join("end")),
+ ) {
+ let current = msgnum.trim();
+ let total = end.trim();
+ return Ok(Some(format!("REBASING {}/{}", current, total)));
+ }
+
+ return Ok(Some("REBASING".to_string()));
+ }
+
+ // Check for cherry-pick
+ if git_dir.join("CHERRY_PICK_HEAD").exists() {
+ return Ok(Some("CHERRY-PICKING".to_string()));
+ }
+
+ // Check for revert
+ if git_dir.join("REVERT_HEAD").exists() {
+ return Ok(Some("REVERTING".to_string()));
+ }
+
+ // Check for bisect
+ if git_dir.join("BISECT_LOG").exists() {
+ return Ok(Some("BISECTING".to_string()));
+ }
+
+ Ok(None)
+ }
+
+ /// Calculate commits ahead and behind between two refs.
+ ///
+ /// Returns (ahead, behind) where ahead is commits in head not in base,
+ /// and behind is commits in base not in head.
+ pub fn ahead_behind(&self, base: &str, head: &str) -> Result<(usize, usize), GitError> {
+ let ahead = self.count_commits(base, head)?;
+ let behind = self.count_commits(head, base)?;
+ Ok((ahead, behind))
+ }
+
+ /// Get line diff statistics for working tree changes (unstaged + staged).
+ ///
+ /// Returns (added_lines, deleted_lines).
+ pub fn working_tree_diff_stats(&self) -> Result<(usize, usize), GitError> {
+ let stdout = run_git_command(&["diff", "--numstat", "HEAD"], Some(&self.path))?;
+ parse_numstat(&stdout)
+ }
+
+ /// Get line diff statistics between two refs (using three-dot diff for merge base).
+ ///
+ /// Returns (added_lines, deleted_lines).
+ pub fn branch_diff_stats(&self, base: &str, head: &str) -> Result<(usize, usize), GitError> {
+ let range = format!("{}...{}", base, head);
+ let stdout = run_git_command(&["diff", "--numstat", &range], Some(&self.path))?;
+ parse_numstat(&stdout)
+ }
+
+ /// Get all branch names (local branches only).
+ pub fn all_branches(&self) -> Result<Vec<String>, GitError> {
+ let stdout = run_git_command(&["branch", "--format=%(refname:short)"], Some(&self.path))?;
+ Ok(stdout
+ .lines()
+ .map(|s| s.trim().to_string())
+ .filter(|s| !s.is_empty())
+ .collect())
+ }
+
+ /// Get the merge base between two commits.
+ pub fn merge_base(&self, commit1: &str, commit2: &str) -> Result<String, GitError> {
+ let output = run_git_command(&["merge-base", commit1, commit2], Some(&self.path))?;
+ Ok(output.trim().to_string())
+ }
+
+ /// Get commit subjects (first line of commit message) from a range.
+ pub fn commit_subjects(&self, range: &str) -> Result<Vec<String>, GitError> {
+ let output = run_git_command(&["log", "--format=%s", range], Some(&self.path))?;
+ Ok(output.lines().map(|s| s.to_string()).collect())
+ }
+
+ /// Check if there are staged changes.
+ pub fn has_staged_changes(&self) -> Result<bool, GitError> {
+ let output = std::process::Command::new("git")
+ .args(["diff", "--cached", "--quiet", "--exit-code"])
+ .current_dir(&self.path)
+ .output()
+ .map_err(|e| GitError::CommandFailed(e.to_string()))?;
+
+ // exit code 0 = no changes, 1 = has changes
+ Ok(!output.status.success())
+ }
+
+ /// List all worktrees for this repository.
+ pub fn list_worktrees(&self) -> Result<Vec<Worktree>, GitError> {
+ let stdout = run_git_command(&["worktree", "list", "--porcelain"], Some(&self.path))?;
+ parse_worktree_list(&stdout)
+ }
+
+ /// Find the worktree path for a given branch, if one exists.
+ pub fn worktree_for_branch(&self, branch: &str) -> Result<Option<PathBuf>, GitError> {
+ let worktrees = self.list_worktrees()?;
+
+ for wt in worktrees {
+ if let Some(ref wt_branch) = wt.branch
+ && wt_branch == branch
+ {
+ return Ok(Some(wt.path));
+ }
+ }
+
+ Ok(None)
+ }
+
+ /// Get branches that don't have worktrees (available for switch).
+ pub fn available_branches(&self) -> Result<Vec<String>, GitError> {
+ let all_branches = self.all_branches()?;
+ let worktrees = self.list_worktrees()?;
+
+ // Collect branches that have worktrees
+ let branches_with_worktrees: std::collections::HashSet<String> =
+ worktrees.into_iter().filter_map(|wt| wt.branch).collect();
+
+ // Filter out branches with worktrees
+ Ok(all_branches
+ .into_iter()
+ .filter(|branch| !branches_with_worktrees.contains(branch))
+ .collect())
+ }
+
+ // Private helper methods for default_branch()
+
+ fn get_local_default_branch(&self) -> Result<String, GitError> {
+ let stdout = run_git_command(
+ &["rev-parse", "--abbrev-ref", "origin/HEAD"],
+ Some(&self.path),
+ )?;
+ parse_local_default_branch(&stdout)
+ }
+
+ fn query_remote_default_branch(&self) -> Result<String, GitError> {
+ let stdout = run_git_command(
+ &["ls-remote", "--symref", "origin", "HEAD"],
+ Some(&self.path),
+ )?;
+ parse_remote_default_branch(&stdout)
+ }
+
+ fn cache_default_branch(&self, branch: &str) -> Result<(), GitError> {
+ run_git_command(&["remote", "set-head", "origin", branch], Some(&self.path))?;
+ Ok(())
+ }
+}
+
/// Helper function to run a git command and return its stdout.
///
/// For commands that don't need the output (e.g., git switch, git worktree add),
@@ -58,11 +434,6 @@ pub fn run_git_command(args: &[&str], path: Option<&std::path::Path>) -> Result<
Ok(String::from_utf8_lossy(&output.stdout).to_string())
}
-pub fn list_worktrees() -> Result<Vec<Worktree>, GitError> {
- let stdout = run_git_command(&["worktree", "list", "--porcelain"], None)?;
- parse_worktree_list(&stdout)
-}
-
fn parse_worktree_list(output: &str) -> Result<Vec<Worktree>, GitError> {
let mut worktrees = Vec::new();
let mut current = None;
@@ -146,29 +517,6 @@ fn parse_worktree_list(output: &str) -> Result<Vec<Worktree>, GitError> {
Ok(worktrees)
}
-/// Get the default branch name for a repository at the given path using a hybrid approach:
-/// 1. Try local cache (origin/HEAD) first for speed
-/// 2. If not cached, query the remote and cache the result
-pub fn get_default_branch_in(path: &std::path::Path) -> Result<String, GitError> {
- // Try local cache first (fast path)
- if let Ok(branch) = get_local_default_branch(path) {
- return Ok(branch);
- }
-
- // Query remote and cache it
- let branch = query_remote_default_branch(path)?;
- cache_default_branch(path, &branch)?;
- Ok(branch)
-}
-
-/// Try to get the default branch from the local cache (origin/HEAD)
-fn get_local_default_branch(path: &std::path::Path) -> Result<String, GitError> {
- let stdout = run_git_command(&["rev-parse", "--abbrev-ref", "origin/HEAD"], Some(path))?;
- parse_local_default_branch(&stdout)
-}
-
-/// Parse the output of `git rev-parse --abbrev-ref origin/HEAD`
-/// Expected format: "origin/main\n"
fn parse_local_default_branch(output: &str) -> Result<String, GitError> {
let trimmed = output.trim();
@@ -184,18 +532,6 @@ fn parse_local_default_branch(output: &str) -> Result<String, GitError> {
Ok(branch.to_string())
}
-/// Query the remote to determine the default branch
-fn query_remote_default_branch(path: &std::path::Path) -> Result<String, GitError> {
- let stdout = run_git_command(&["ls-remote", "--symref", "origin", "HEAD"], Some(path))?;
- parse_remote_default_branch(&stdout)
-}
-
-/// Parse the output of `git ls-remote --symref origin HEAD`
-/// Expected format:
-/// ```text
-/// ref: refs/heads/main HEAD
-/// 85a1ce7c7182540f9c02453441cb3e8bf0ced214 HEAD
-/// ```
fn parse_remote_default_branch(output: &str) -> Result<String, GitError> {
for line in output.lines() {
if let Some(symref) = line.strip_prefix("ref: ") {
@@ -215,276 +551,6 @@ fn parse_remote_default_branch(output: &str) -> Result<String, GitError> {
))
}
-/// Cache the default branch locally by setting origin/HEAD
-fn cache_default_branch(path: &std::path::Path, branch: &str) -> Result<(), GitError> {
- run_git_command(&["remote", "set-head", "origin", branch], Some(path))?;
- Ok(())
-}
-
-/// Check if a git branch exists in the repository at the given path (local or remote)
-pub fn branch_exists_in(path: &std::path::Path, branch: &str) -> Result<bool, GitError> {
- // Try local branch first
- let result = run_git_command(
- &["rev-parse", "--verify", &format!("refs/heads/{}", branch)],
- Some(path),
- );
- if result.is_ok() {
- return Ok(true);
- }
-
- // Try remote branch
- let result = run_git_command(
- &[
- "rev-parse",
- "--verify",
- &format!("refs/remotes/origin/{}", branch),
- ],
- Some(path),
- );
- Ok(result.is_ok())
-}
-
-/// Get the current branch name for a repository at the given path, or None if in detached HEAD state
-pub fn get_current_branch_in(path: &std::path::Path) -> Result<Option<String>, GitError> {
- let stdout = run_git_command(&["branch", "--show-current"], Some(path))?;
- let branch = stdout.trim();
-
- if branch.is_empty() {
- Ok(None) // Detached HEAD
- } else {
- Ok(Some(branch.to_string()))
- }
-}
-
-/// Get the git common directory for a repository at the given path (the actual .git directory for the repository)
-pub fn get_git_common_dir_in(path: &std::path::Path) -> Result<PathBuf, GitError> {
- let stdout = run_git_command(&["rev-parse", "--git-common-dir"], Some(path))?;
- Ok(PathBuf::from(stdout.trim()))
-}
-
-/// Get the git directory for a repository at the given path (may be different from common-dir in worktrees)
-pub fn get_git_dir_in(path: &std::path::Path) -> Result<PathBuf, GitError> {
- let stdout = run_git_command(&["rev-parse", "--git-dir"], Some(path))?;
- Ok(PathBuf::from(stdout.trim()))
-}
-
-/// Get the canonicalized repository root directory (parent of .git) for a repository at the given path.
-///
-/// This function:
-/// - Retrieves the git common directory
-/// - Canonicalizes the path (resolves symlinks and relative paths)
-/// - Returns the parent directory (the repository root)
-///
-/// The canonicalization is important for worktree operations as it ensures
-/// consistent path handling across symlinks and relative references.
-pub fn get_repo_root_in(path: &std::path::Path) -> Result<PathBuf, GitError> {
- let git_common_dir = get_git_common_dir_in(path)?
- .canonicalize()
- .map_err(|e| GitError::CommandFailed(format!("Failed to canonicalize path: {}", e)))?;
-
- git_common_dir
- .parent()
- .ok_or_else(|| GitError::CommandFailed("Invalid git directory".to_string()))
- .map(|p| p.to_path_buf())
-}
-
-/// Find the worktree path for a given branch, if one exists
-pub fn worktree_for_branch(branch: &str) -> Result<Option<PathBuf>, GitError> {
- let worktrees = list_worktrees()?;
-
- for wt in worktrees {
- if let Some(ref wt_branch) = wt.branch
- && wt_branch == branch
- {
- return Ok(Some(wt.path));
- }
- }
-
- Ok(None)
-}
-
-/// Check if the working tree is dirty in the repository at the given path (has uncommitted changes)
-pub fn is_dirty_in(path: &std::path::Path) -> Result<bool, GitError> {
- let stdout = run_git_command(&["status", "--porcelain"], Some(path))?;
- Ok(!stdout.trim().is_empty())
-}
-
-/// Get the worktree root directory for a repository at the given path (top-level of the working tree)
-pub fn get_worktree_root_in(path: &std::path::Path) -> Result<PathBuf, GitError> {
- let stdout = run_git_command(&["rev-parse", "--show-toplevel"], Some(path))?;
- Ok(PathBuf::from(stdout.trim()))
-}
-
-/// Check if a path is in a worktree (vs the main repository)
-pub fn is_in_worktree_in(path: &std::path::Path) -> Result<bool, GitError> {
- let git_dir = get_git_dir_in(path)?;
- let common_dir = get_git_common_dir_in(path)?;
- Ok(git_dir != common_dir)
-}
-
-/// Check if base is an ancestor of head in the repository at the given path (i.e., would be a fast-forward)
-pub fn is_ancestor_in(path: &std::path::Path, base: &str, head: &str) -> Result<bool, GitError> {
- let output = std::process::Command::new("git")
- .args(["merge-base", "--is-ancestor", base, head])
- .current_dir(path)
- .output()
- .map_err(|e| GitError::CommandFailed(e.to_string()))?;
-
- Ok(output.status.success())
-}
-
-/// Count commits between base and head in the repository at the given path
-pub fn count_commits_in(path: &std::path::Path, base: &str, head: &str) -> Result<usize, GitError> {
- let range = format!("{}..{}", base, head);
- let stdout = run_git_command(&["rev-list", "--count", &range], Some(path))?;
- stdout
- .trim()
- .parse()
- .map_err(|e| GitError::ParseError(format!("Failed to parse commit count: {}", e)))
-}
-
-/// Check if there are merge commits in the range base..head at the given path
-pub fn has_merge_commits_in(
- path: &std::path::Path,
- base: &str,
- head: &str,
-) -> Result<bool, GitError> {
- let range = format!("{}..{}", base, head);
- let stdout = run_git_command(&["rev-list", "--merges", &range], Some(path))?;
- Ok(!stdout.trim().is_empty())
-}
-
-/// Get files changed between base and head at the given path
-pub fn get_changed_files_in(
- path: &std::path::Path,
- base: &str,
- head: &str,
-) -> Result<Vec<String>, GitError> {
- let range = format!("{}..{}", base, head);
- let stdout = run_git_command(&["diff", "--name-only", &range], Some(path))?;
- Ok(stdout.lines().map(|s| s.to_string()).collect())
-}
-
-/// Get commit timestamp in seconds since epoch for a repository at the given path
-pub fn get_commit_timestamp_in(path: &std::path::Path, commit: &str) -> Result<i64, GitError> {
- let stdout = run_git_command(&["show", "-s", "--format=%ct", commit], Some(path))?;
- stdout
- .trim()
- .parse()
- .map_err(|e| GitError::ParseError(format!("Failed to parse timestamp: {}", e)))
-}
-
-/// Get commit message (subject line) for a commit
-pub fn get_commit_message_in(path: &std::path::Path, commit: &str) -> Result<String, GitError> {
- let stdout = run_git_command(&["show", "-s", "--format=%s", commit], Some(path))?;
- Ok(stdout.trim().to_string())
-}
-
-/// Get the upstream tracking branch for the current branch
-pub fn get_upstream_branch_in(
- path: &std::path::Path,
- branch: &str,
-) -> Result<Option<String>, GitError> {
- let result = run_git_command(
- &["rev-parse", "--abbrev-ref", &format!("{}@{{u}}", branch)],
- Some(path),
- );
-
- match result {
- Ok(upstream) => {
- let trimmed = upstream.trim();
- if trimmed.is_empty() {
- Ok(None)
- } else {
- Ok(Some(trimmed.to_string()))
- }
- }
- Err(_) => Ok(None), // No upstream configured
- }
-}
-
-/// Get merge/rebase status for a worktree
-pub fn get_worktree_state_in(path: &std::path::Path) -> Result<Option<String>, GitError> {
- let git_dir = get_git_dir_in(path)?;
-
- // Check for merge
- if git_dir.join("MERGE_HEAD").exists() {
- return Ok(Some("MERGING".to_string()));
- }
-
- // Check for rebase
- if git_dir.join("rebase-merge").exists() || git_dir.join("rebase-apply").exists() {
- // Try to get rebase progress
- let rebase_dir = if git_dir.join("rebase-merge").exists() {
- git_dir.join("rebase-merge")
- } else {
- git_dir.join("rebase-apply")
- };
-
- if let (Ok(msgnum), Ok(end)) = (
- std::fs::read_to_string(rebase_dir.join("msgnum")),
- std::fs::read_to_string(rebase_dir.join("end")),
- ) {
- let current = msgnum.trim();
- let total = end.trim();
- return Ok(Some(format!("REBASING {}/{}", current, total)));
- }
-
- return Ok(Some("REBASING".to_string()));
- }
-
- // Check for cherry-pick
- if git_dir.join("CHERRY_PICK_HEAD").exists() {
- return Ok(Some("CHERRY-PICKING".to_string()));
- }
-
- // Check for revert
- if git_dir.join("REVERT_HEAD").exists() {
- return Ok(Some("REVERTING".to_string()));
- }
-
- // Check for bisect
- if git_dir.join("BISECT_LOG").exists() {
- return Ok(Some("BISECTING".to_string()));
- }
-
- Ok(None)
-}
-
-/// Calculate commits ahead and behind between two refs
-/// Returns (ahead, behind) where ahead is commits in head not in base,
-/// and behind is commits in base not in head
-pub fn get_ahead_behind_in(
- path: &std::path::Path,
- base: &str,
- head: &str,
-) -> Result<(usize, usize), GitError> {
- let ahead = count_commits_in(path, base, head)?;
- let behind = count_commits_in(path, head, base)?;
- Ok((ahead, behind))
-}
-
-/// Get line diff statistics for working tree changes at the given path (unstaged + staged)
-/// Returns (added_lines, deleted_lines)
-pub fn get_working_tree_diff_stats_in(path: &std::path::Path) -> Result<(usize, usize), GitError> {
- let stdout = run_git_command(&["diff", "--numstat", "HEAD"], Some(path))?;
- parse_numstat(&stdout)
-}
-
-/// Get line diff statistics between two refs at the given path (using three-dot diff for merge base)
-/// Returns (added_lines, deleted_lines)
-pub fn get_branch_diff_stats_in(
- path: &std::path::Path,
- base: &str,
- head: &str,
-) -> Result<(usize, usize), GitError> {
- let range = format!("{}...{}", base, head);
- let stdout = run_git_command(&["diff", "--numstat", &range], Some(path))?;
- parse_numstat(&stdout)
-}
-
-/// Parse git diff --numstat output
-/// Format: "added\tdeleted\tfilename" per line
fn parse_numstat(output: &str) -> Result<(usize, usize), GitError> {
let mut total_added = 0;
let mut total_deleted = 0;
@@ -518,71 +584,6 @@ fn parse_numstat(output: &str) -> Result<(usize, usize), GitError> {
Ok((total_added, total_deleted))
}
-/// Get all branch names in a specific directory (local branches only)
-/// Note: This excludes remote-tracking branches (e.g., origin/main)
-pub fn get_all_branches_in(path: &std::path::Path) -> Result<Vec<String>, GitError> {
- let stdout = run_git_command(
- &["branch", "--format=%(refname:short)"], // Removed --all to exclude remotes
- Some(path),
- )?;
- Ok(stdout
- .lines()
- .map(|s| s.trim().to_string())
- .filter(|s| !s.is_empty())
- .collect())
-}
-
-/// Get branches that don't have worktrees (available for switch)
-/// Note: This function operates on the current directory (assumes you're in a git repo)
-pub fn get_available_branches() -> Result<Vec<String>, GitError> {
- // Get all branches from current directory
- let all_branches = get_all_branches_in(std::path::Path::new("."))?;
-
- // Get worktrees (always operates on current git repository)
- let worktrees = list_worktrees()?;
-
- // Collect branches that have worktrees
- let branches_with_worktrees: std::collections::HashSet<String> =
- worktrees.into_iter().filter_map(|wt| wt.branch).collect();
-
- // Filter out branches with worktrees
- Ok(all_branches
- .into_iter()
- .filter(|branch| !branches_with_worktrees.contains(branch))
- .collect())
-}
-
-/// Get the merge base between two commits at the given path
-pub fn get_merge_base_in(
- path: &std::path::Path,
- commit1: &str,
- commit2: &str,
-) -> Result<String, GitError> {
- let output = run_git_command(&["merge-base", commit1, commit2], Some(path))?;
- Ok(output.trim().to_string())
-}
-
-/// Get commit subjects (first line of commit message) from a range at the given path
-pub fn get_commit_subjects_in(
- path: &std::path::Path,
- range: &str,
-) -> Result<Vec<String>, GitError> {
- let output = run_git_command(&["log", "--format=%s", range], Some(path))?;
- Ok(output.lines().map(|s| s.to_string()).collect())
-}
-
-/// Check if there are staged changes at the given path
-pub fn has_staged_changes_in(path: &std::path::Path) -> Result<bool, GitError> {
- let output = Command::new("git")
- .args(["diff", "--cached", "--quiet", "--exit-code"])
- .current_dir(path)
- .output()
- .map_err(|e| GitError::CommandFailed(e.to_string()))?;
-
- // exit code 0 = no changes, 1 = has changes
- Ok(!output.status.success())
-}
-
#[cfg(test)]
mod tests {
use super::*;
diff --git a/tests/integration_tests/default_branch.rs b/tests/integration_tests/default_branch.rs
index c02dbe8e7..9644df4e6 100644
--- a/tests/integration_tests/default_branch.rs
+++ b/tests/integration_tests/default_branch.rs
@@ -1,4 +1,5 @@
use crate::common::TestRepo;
+use worktrunk::git::Repository;
#[test]
fn test_get_default_branch_with_origin_head() {
@@ -10,7 +11,8 @@ fn test_get_default_branch_with_origin_head() {
assert!(repo.has_origin_head());
// Test that we can get the default branch
- let branch = worktrunk::git::get_default_branch_in(repo.root_path())
+ let branch = Repository::at(repo.root_path())
+ .default_branch()
.expect("Failed to get default branch");
assert_eq!(branch, "main");
}
@@ -26,7 +28,8 @@ fn test_get_default_branch_without_origin_head() {
assert!(!repo.has_origin_head());
// Should still work by querying remote
- let branch = worktrunk::git::get_default_branch_in(repo.root_path())
+ let branch = Repository::at(repo.root_path())
+ .default_branch()
.expect("Failed to get default branch");
assert_eq!(branch, "main");
@@ -45,11 +48,14 @@ fn test_get_default_branch_caches_result() {
assert!(!repo.has_origin_head());
// First call queries remote and caches
- worktrunk::git::get_default_branch_in(repo.root_path()).expect("Failed to get default branch");
+ Repository::at(repo.root_path())
+ .default_branch()
+ .expect("Failed to get default branch");
assert!(repo.has_origin_head());
// Second call uses cache (fast path)
- let branch = worktrunk::git::get_default_branch_in(repo.root_path())
+ let branch = Repository::at(repo.root_path())
+ .default_branch()
.expect("Failed to get default branch on second call");
assert_eq!(branch, "main");
}
@@ -60,6 +66,6 @@ fn test_get_default_branch_no_remote() {
repo.commit("Initial commit");
// No remote configured, should fail
- let result = worktrunk::git::get_default_branch_in(repo.root_path());
+ let result = Repository::at(repo.root_path()).default_branch();
assert!(result.is_err());
}